refactor: SSE event handlers, LLM context optimization, @fileoverview docs (#29)

* refactor: extract SSE event handlers into named class methods

Replace ~80 inline addListener closures in connectSSE() with a
declarative _SSE_HANDLER_MAP array that drives registration in a
single loop. Each handler is now a named _on* method on CodemanApp,
making them individually addressable for LLM navigation.

Add SSE_EVENTS constant object in constants.js to eliminate magic
event-type strings scattered across the frontend.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: fix inaccuracies in CLAUDE.md

- Fix types barrel path: src/types.ts → src/types/index.ts
- Update app.js line count: ~12K → ~11.5K
- Correct route handler counts (113 → 111, per-group fixes)
- Add code style, ESM gotcha, env vars, route test, lifecycle log docs
- Add Node 22 CI note, test teardown timeout, port range

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add mobile screenshots and QR auth security writeup to README

Add 3 mobile screenshots (landing, idle, active) and expand the
mobile section with QR auth security design details and a
touch-optimized interface subsection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: bundle xterm-zerolag-input as vendor IIFE and add pre-commit hook

Build and postinstall now bundle the local xterm-zerolag-input package
as an IIFE at vendor/xterm-zerolag-input.js with global LocalEchoOverlay
shim. Add git pre-commit hook that runs prettier --check on staged .ts
files to catch format issues before CI.

Also bump constants.js and app.js cache-bust versions to 0.3.0 and add
tunnel upload URL display row in settings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add cloudflared install support and interactive launch menu

- Add optional cloudflared dependency detection and installation
  across 6 distro families (macOS, Debian, Fedora, Arch, Alpine, SUSE)
- Add tunnel systemd service setup helper
- Replace post-install instructions with interactive launch menu
  (run now / systemd service / skip)
- Uninstall now cleans up both codeman-web and codeman-tunnel services

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: gitignore readme-preview.mjs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: WIP — SSE event constants, @fileoverview docs, CLAUDE.md compression

- Migrate broadcast() string literals → SseEvent.* typed constants
- Add @fileoverview with cross-domain references to all 13 type domain files
- Add @fileoverview to frontend JS modules (constants, mobile, voice, etc.)
- Add section dividers to route files for LLM scanability
- Compress CLAUDE.md: flat file list → domain table, fix counts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: optimize codebase for LLM context window efficiency

CLAUDE.md: 456 → 309 lines (32% reduction)
- Merge Commands into compact table, remove redundant bash block
- Convert Security section to dense table format
- Merge Performance + Resource Limits, Debugging + Troubleshooting
- Compress Tunnel, Memory Leak, Scripts, Screenshots sections
- Remove Key Patterns that duplicate @fileoverview in source files

Backend @fileoverview enhancements (10 priority files):
- session.ts: key methods, events, cross-domain refs
- respawn-controller.ts: state machine, idle detection layers
- ralph-tracker.ts: exports, circuit breaker, events
- ralph-loop.ts: lifecycle, persistence, events
- subagent-watcher.ts: watched patterns, teammate detection
- server.ts: coordination list, port interfaces
- state-store.ts: dual-file persistence, migration
- session-manager.ts: lifecycle methods, mutex guard
- hooks-config.ts: hook events list, categories
- sse-events.ts: category breakdown (~90 events, 17 categories)

Frontend app.js: add 6 section dividers, update @fileoverview line refs

Fix: escape glob `*/` in JSDoc that broke ESLint parser

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR #29 review bugs

- server.ts: replace hardcoded 'session:needsRefresh' with SseEvent constant
- install.sh: fix Alpine cloudflared install for non-root (download to tmpfile first)
- install.sh: replace Arch pacman (AUR-only) with direct binary download
- index.html: bump all 8 remaining cache-bust versions from v0.2.9 to v0.3.0
- mobile-handlers.js: fix @dependency annotation (keyboard-accessory.js, not constants.js)
- types/push.ts: fix layer number (4, not 5)
- subagent-watcher.ts: fix watched pattern path to include {session} segment
- constants.js: fix SSE_EVENTS count in @fileoverview (~73, not ~65)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Ark0N
2026-03-03 22:40:18 +01:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 14462f7bfe
commit 2ee9ad72e8
52 changed files with 3393 additions and 1860 deletions
+34 -22
View File
@@ -18,10 +18,15 @@ import {
PlanTaskAddSchema,
} from '../schemas.js';
import { findSessionOrFail, CASES_DIR } from '../route-helpers.js';
import { SseEvent } from '../sse-events.js';
import type { SessionPort, EventPort, ConfigPort, InfraPort } from '../ports/index.js';
export function registerPlanRoutes(app: FastifyInstance, ctx: SessionPort & EventPort & ConfigPort & InfraPort): void {
// ============ Plan Generation Endpoints ============
// ═══════════════════════════════════════════════════════════════
// Plan Generation (simple AI + detailed orchestration)
// ═══════════════════════════════════════════════════════════════
// ========== Generate Plan (Simple) ==========
app.post('/api/generate-plan', async (req): Promise<ApiResponse> => {
const gpResult = GeneratePlanSchema.safeParse(req.body);
@@ -215,8 +220,8 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
}
});
// Generate detailed implementation plan using subagent orchestration
// This spawns multiple specialist subagents in parallel for thorough analysis
// ========== Generate Plan (Detailed Orchestration) ==========
app.post('/api/generate-plan-detailed', async (req): Promise<ApiResponse> => {
const gpdResult = GeneratePlanDetailedSchema.safeParse(req.body);
if (!gpdResult.success) {
@@ -257,7 +262,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
ctx.activePlanOrchestrators.set(orchestratorId, orchestrator);
// Broadcast the orchestrator ID so frontend can cancel if needed
ctx.broadcast('plan:started', { orchestratorId });
ctx.broadcast(SseEvent.PlanStarted, { orchestratorId });
// Track progress for SSE updates
const progressUpdates: Array<{ phase: string; detail: string; timestamp: number }> = [];
@@ -265,7 +270,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
const update = { phase, detail, timestamp: Date.now() };
progressUpdates.push(update);
// Broadcast progress to connected clients
ctx.broadcast('plan:progress', update);
ctx.broadcast(SseEvent.PlanProgress, update);
};
// Broadcast plan subagent events for UI visibility
@@ -280,7 +285,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
durationMs?: number;
error?: string;
}) => {
ctx.broadcast('plan:subagent', event);
ctx.broadcast(SseEvent.PlanSubagent, event);
};
try {
@@ -292,7 +297,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
// Clean up orchestrator from active map
ctx.activePlanOrchestrators.delete(orchestratorId);
ctx.broadcast('plan:completed', { orchestratorId, success: result.success });
ctx.broadcast(SseEvent.PlanCompleted, { orchestratorId, success: result.success });
if (!result.success) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, result.error || 'Plan generation failed');
@@ -311,7 +316,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
} catch (err) {
// Clean up on error too
ctx.activePlanOrchestrators.delete(orchestratorId);
ctx.broadcast('plan:completed', {
ctx.broadcast(SseEvent.PlanCompleted, {
orchestratorId,
success: false,
error: getErrorMessage(err),
@@ -323,7 +328,8 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
}
});
// Cancel active plan generation
// ========== Cancel Plan Generation ==========
app.post('/api/cancel-plan-generation', async (req): Promise<ApiResponse> => {
const cpResult = CancelPlanSchema.safeParse(req.body);
if (!cpResult.success) {
@@ -340,7 +346,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
console.log(`[API] Cancelling plan generation ${orchestratorId}`);
await orchestrator.cancel();
ctx.activePlanOrchestrators.delete(orchestratorId);
ctx.broadcast('plan:cancelled', { orchestratorId });
ctx.broadcast(SseEvent.PlanCancelled, { orchestratorId });
return { success: true, data: { cancelled: orchestratorId } };
}
@@ -350,17 +356,19 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
console.log(`[API] Cancelling plan generation ${id}`);
await orchestrator.cancel();
cancelled.push(id);
ctx.broadcast('plan:cancelled', { orchestratorId: id });
ctx.broadcast(SseEvent.PlanCancelled, { orchestratorId: id });
}
ctx.activePlanOrchestrators.clear();
return { success: true, data: { cancelled } };
});
// ============ Plan Management Endpoints ============
// These endpoints support runtime plan adaptation with checkpoints, failure tracking, and versioning
// ═══════════════════════════════════════════════════════════════
// Plan Management (task CRUD, checkpoints, version history, rollback)
// ═══════════════════════════════════════════════════════════════
// ========== Update Plan Task ==========
// Update a specific plan task (status, attempts, errors)
app.patch('/api/sessions/:id/plan/task/:taskId', async (req) => {
const { id, taskId } = req.params as { id: string; taskId: string };
const session = findSessionOrFail(ctx, id);
@@ -385,11 +393,12 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
return createErrorResponse(ApiErrorCode.NOT_FOUND, result.error || 'Task not found');
}
ctx.broadcast('session:planTaskUpdate', { sessionId: id, taskId, update: result.task });
ctx.broadcast(SseEvent.SessionPlanTaskUpdate, { sessionId: id, taskId, update: result.task });
return { success: true, data: result.task };
});
// Trigger a checkpoint review (at iterations 5, 10, 20, etc.)
// ========== Create Checkpoint ==========
app.post('/api/sessions/:id/plan/checkpoint', async (req) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id);
@@ -400,11 +409,12 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
}
const checkpoint = tracker.generateCheckpointReview();
ctx.broadcast('session:planCheckpoint', { sessionId: id, checkpoint });
ctx.broadcast(SseEvent.SessionPlanCheckpoint, { sessionId: id, checkpoint });
return { success: true, data: checkpoint };
});
// Get plan version history
// ========== Get Version History ==========
app.get('/api/sessions/:id/plan/history', async (req) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id);
@@ -417,7 +427,8 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
return { success: true, data: tracker.getPlanHistory() };
});
// Rollback to a previous plan version
// ========== Rollback to Version ==========
app.post('/api/sessions/:id/plan/rollback/:version', async (req) => {
const { id, version } = req.params as { id: string; version: string };
const session = findSessionOrFail(ctx, id);
@@ -432,11 +443,12 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
return createErrorResponse(ApiErrorCode.NOT_FOUND, result.error || 'Version not found');
}
ctx.broadcast('session:planRollback', { sessionId: id, version: parseInt(version, 10) });
ctx.broadcast(SseEvent.SessionPlanRollback, { sessionId: id, version: parseInt(version, 10) });
return { success: true, data: result.plan };
});
// Add a new task to the plan (for runtime adaptation)
// ========== Add Plan Task ==========
app.post('/api/sessions/:id/plan/task', async (req) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id);
@@ -453,7 +465,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
const task = ptaResult.data;
const result = tracker.addPlanTask(task);
ctx.broadcast('session:planTaskAdded', { sessionId: id, task: result.task });
ctx.broadcast(SseEvent.SessionPlanTaskAdded, { sessionId: id, task: result.task });
return { success: true, data: result.task };
});
}