@neural-node-labs/xcoder-sdlc 0.0.0-stage → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1236 @@
1
+ #!/usr/bin/env node
2
+ // xcoder:version 6 | xcoder:task task-691585 | xcoder:updated 2026-11-05T05:45:47.124Z | xcoder:subtask code-st-b5251b
3
+ // xcoder:version 17 | xcoder:task task-4f2baf | xcoder:updated 2026-08-05T05:50:44.474Z | xcoder:subtask code-st-11b531
4
+ import path from "node:path";
5
+ import { Command } from "commander";
6
+ import { SdlcOrchestrator } from "xcoder-dna";
7
+ import { buildTaskSpec } from "xcoder-dna";
8
+ import { createLlmClient } from "xcoder-dna";
9
+ import { buildIndex } from "xcoder-dna";
10
+ import { ensureFreshIndex } from "xcoder-dna";
11
+ import { loadTaskRun, listTaskRuns, findResumableTasks, detectResumableTask, isResumableRun } from "xcoder-dna";
12
+ import { log } from "xcoder-dna";
13
+ import { maybePrintBanner } from "xcoder-dna";
14
+ import { parseStepSpec, runBrowse } from "xcoder-dna";
15
+ import { logFileAccess } from "xcoder-dna";
16
+ import { applyUserConfig, extractConfigArg, formatUserConfig, parseConfigArg, readUserConfig, saveUserConfig, userConfigPath } from "xcoder-dna";
17
+ import { suggestCommands } from "xcoder-dna";
18
+ import { enableProtocolErrorLogging } from "xcoder-dna";
19
+ import { enableToolErrorLogging } from "xcoder-dna";
20
+ import { XCODER_VERSION } from "xcoder-dna";
21
+ import { setSpinnerStyle, AVAILABLE_SPINNER_STYLES } from "xcoder-dna";
22
+ import { xcoderEvents } from "xcoder-dna";
23
+ import { runBenchmark, compareReports } from "xcoder-dna";
24
+ import { getOutputPaths } from "xcoder-dna";
25
+ import { fileURLToPath } from "node:url";
26
+ import { isContinueTrigger } from "xcoder-dna";
27
+ import { resolveLessonFlag } from "xcoder-dna";
28
+ import { printInterruptSummary } from "xcoder-dna";
29
+ import * as readline from "node:readline";
30
+ import { confirmInterrupt } from "xcoder-dna";
31
+ import { FooterManager } from "xcoder-dna";
32
+ import { killProcessTree } from "xcoder-dna";
33
+ import { addBacklogItem, listBacklogItems, getBacklogItem, updateBacklogItem } from "xcoder-dna";
34
+ import { runPoPick } from "xcoder-dna";
35
+ import { sprintStart, sprintStatus, sprintRetro, sprintAbort } from "xcoder-dna";
36
+ import { runRelease } from "xcoder-dna";
37
+ import { registerTestCommand } from "xcoder-dna";
38
+ import { registerSwarmCommand } from "xcoder-dna";
39
+ import { registerTaskCommand } from "xcoder-dna";
40
+ import { registerLicenseCommand } from "xcoder-dna";
41
+ import { extractDelegatedArg, runDelegated } from "xcoder-dna";
42
+ import { registerJarvisCommand } from "./cli/jarvis.js";
43
+ import { LICENSE_REQUIRED_EXIT_CODE, isLicensedFeature, maybeRefreshLicense, requireLicense } from "xcoder-dna";
44
+ import { createDefaultLicenseManager } from "xcoder-dna";
45
+ import { capturedWbc, runCapturedWbc, setWbcSourcePath } from "xcoder-dna";
46
+ import { extractWbcArg } from "xcoder-dna";
47
+ import { sanitizeForTerminal } from "xcoder-dna";
48
+ import { maybeSeedSkillsHome } from "xcoder-dna";
49
+ const program = new Command();
50
+ program.exitOverride();
51
+ program
52
+ .name("xcoder")
53
+ .description("Xcoder SDLC — a SDLC-aware, ReAct-driven multi-agent CLI. One Master Orchestrator, " +
54
+ "a swarm of role-mapped Sub Agents, a workspace index as the source of truth.")
55
+ .version(XCODER_VERSION);
56
+ program.option("--config <settings>", 'save LLM/env settings to ~/.xcoder/config.json, e.g. --config "provider=deepseek,key=sk-…,model=deepseek-chat" (keys: provider, key, model, base_url, UPPER_CASE env vars; name= removes; "show" prints)');
57
+ program.option("--debug-protocol-error", "enable protocol error diagnostic logging (also settable via PROTOCOL_ERROR_LOG env var)");
58
+ program.option("--debug-tools [path]", "enable tool-error diagnostic logging to tools.log (also settable via DEBUG_TOOLS env var)");
59
+ program.hook("preAction", (thisCommand) => {
60
+ const opts = thisCommand.opts();
61
+ if (opts.debugProtocolError || process.env.PROTOCOL_ERROR_LOG) {
62
+ enableProtocolErrorLogging(undefined, { silent: !opts.debugProtocolError });
63
+ }
64
+ if (opts.debugTools || process.env.DEBUG_TOOLS) {
65
+ const customPath = typeof opts.debugTools === "string" ? opts.debugTools : process.env.DEBUG_TOOLS;
66
+ enableToolErrorLogging(typeof customPath === "string" ? customPath : undefined, { silent: !opts.debugTools });
67
+ }
68
+ });
69
+ program
70
+ .command("index", { isDefault: false })
71
+ .description("Build or rebuild the workspace index (the LLM's source of truth for what files exist).")
72
+ .action(async () => {
73
+ const root = path.resolve(program.opts().workspace);
74
+ const index = await buildIndex(root);
75
+ log.ok(`indexed ${index.entries.length} files under ${root}`);
76
+ });
77
+ program
78
+ .command("status")
79
+ .description("Show task run status. Use 'pending' or 'completed' to list tasks by status, or a task id for DAG details.")
80
+ .argument("[filterOrId]", "filter keyword (pending, completed) or task id, e.g. task-9f2a")
81
+ .action(async (filterOrId) => {
82
+ const root = path.resolve(program.opts().workspace);
83
+ if (!filterOrId) {
84
+ log.fail('Usage: xcoder status <pending|completed|taskId>');
85
+ process.exitCode = 1;
86
+ return;
87
+ }
88
+ // Detect keywords: all-alpha lowercase (task ids always contain hyphens)
89
+ if (/^[a-z]+$/.test(filterOrId)) {
90
+ if (filterOrId === "pending" || filterOrId === "completed") {
91
+ await statusList(root, filterOrId);
92
+ }
93
+ else {
94
+ log.fail(`Unknown status keyword: "${filterOrId}". Try "pending" or "completed", or use a task id.`);
95
+ process.exitCode = 1;
96
+ }
97
+ return;
98
+ }
99
+ // Treat as taskId
100
+ await statusSingle(root, filterOrId);
101
+ });
102
+ /**
103
+ * Display the DAG state for a single task run (preserves existing behavior).
104
+ */
105
+ async function statusSingle(root, taskId) {
106
+ const run = await loadTaskRun(root, taskId);
107
+ if (!run) {
108
+ const all = await listTaskRuns(root);
109
+ log.fail(`no task run found for "${taskId}". Known: ${all.join(", ") || "(none)"}`);
110
+ process.exitCode = 1;
111
+ return;
112
+ }
113
+ log.raw(`Status: ${run.status}`);
114
+ for (const node of run.dag) {
115
+ const score = node.reasoningScore ? ` score=${node.reasoningScore.score}` : "";
116
+ log.raw(` ${node.id.padEnd(24)} ${node.role.padEnd(20)} ${node.status}${score}`);
117
+ }
118
+ if (run.escalations.length) {
119
+ log.raw("");
120
+ log.fail("Escalations:");
121
+ for (const e of run.escalations)
122
+ log.raw(` ${e.subtaskId}: ${e.reason}`);
123
+ }
124
+ }
125
+ /**
126
+ * Tail-truncate a file path to a fixed column width, preserving the filename
127
+ * via a leading '…' ellipsis. If shorter than maxLen, right-pad to that width.
128
+ */
129
+ function truncatePath(p, maxLen) {
130
+ if (p.length <= maxLen)
131
+ return p.padEnd(maxLen);
132
+ return ("…" + p.slice(p.length - (maxLen - 1))).padEnd(maxLen);
133
+ }
134
+ /**
135
+ * Extract the best workspace-relative .md file path from a TaskRun's DAG
136
+ * for a given SDLC stage. Returns "—" when no artifact exists.
137
+ */
138
+ function extractArtifactPath(run, stage) {
139
+ const doneNodes = run.dag.filter((node) => node.stage === stage && node.status === "done" && node.result !== undefined);
140
+ for (const node of doneNodes) {
141
+ const mdFiles = (node.result.filesTouched ?? []).filter((f) => f.endsWith(".md"));
142
+ if (!mdFiles.length)
143
+ continue;
144
+ // Prefer filenames whose basename contains the stage name
145
+ const preferred = mdFiles.find((f) => {
146
+ const base = path.basename(f);
147
+ return base.includes(stage);
148
+ });
149
+ return preferred ?? mdFiles[0];
150
+ }
151
+ return "—";
152
+ }
153
+ /**
154
+ * List task runs matching a status filter in tabular format.
155
+ * Format: taskId | status | createdAt | goal (truncated to 60 chars)
156
+ * | requirement doc | design doc (tail-truncated to 36 chars).
157
+ * Sorted reverse-chronologically.
158
+ */
159
+ async function statusList(root, filter) {
160
+ const ids = await listTaskRuns(root);
161
+ const matched = [];
162
+ // T2 mitigation: "pending" now means "resumable", so a `running` row is not
163
+ // listed. Count them so the user is told WHY a task left the list instead of
164
+ // silently losing it.
165
+ let skippedRunning = 0;
166
+ for (const id of ids) {
167
+ const run = await loadTaskRun(root, id);
168
+ if (!run)
169
+ continue;
170
+ if (filter === "pending") {
171
+ // Same predicate as `incomplete` and findResumableTasks() (AC-5).
172
+ if (!isResumableRun(run)) {
173
+ if (run.status === "running" || run.status === "planning")
174
+ skippedRunning++;
175
+ continue;
176
+ }
177
+ }
178
+ else {
179
+ // completed
180
+ if (run.status !== "done")
181
+ continue;
182
+ }
183
+ matched.push({
184
+ taskId: id,
185
+ status: run.status,
186
+ createdAt: run.spec.createdAt,
187
+ goal: run.spec.goal,
188
+ requirementDoc: extractArtifactPath(run, "requirements"),
189
+ designDoc: extractArtifactPath(run, "design"),
190
+ });
191
+ }
192
+ // Sort reverse-chronologically (newest first)
193
+ matched.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
194
+ if (!matched.length) {
195
+ log.ok(`no ${filter} tasks found in ${root}`);
196
+ if (filter === "pending" && skippedRunning > 0) {
197
+ log.dim(`${skippedRunning} task(s) marked running/planning were skipped — run \`xcoder resume\` (or \`xcoder status incomplete\`) to reconcile them to halted first.`);
198
+ }
199
+ return;
200
+ }
201
+ for (const t of matched) {
202
+ const reqCol = truncatePath(t.requirementDoc, 36);
203
+ const desCol = truncatePath(t.designDoc, 36);
204
+ log.raw(`${t.taskId.padEnd(16)} ${t.status.padEnd(12)} ${new Date(t.createdAt).toLocaleString().padEnd(24)} ${sanitizeForTerminal(t.goal, 60).padEnd(60)} ${reqCol} ${desCol}`);
205
+ }
206
+ }
207
+ /**
208
+ * Wraps an orchestrator run with SIGINT handling.
209
+ * On first Ctrl+C: calls orchestrator.halt(), prints the resume summary,
210
+ * gives the run up to 4s to settle, then exits. On second Ctrl+C
211
+ * (within 4s): force-kills the entire process tree and exits immediately.
212
+ */
213
+ async function runWithInterruptSupport(orchestrator, runPromise, workspaceRoot) {
214
+ let interrupted = false;
215
+ let forceTimer = null;
216
+ let haltCompleted = false;
217
+ const sigintHandler = () => {
218
+ if (interrupted) {
219
+ // Second interrupt — force kill the process tree immediately.
220
+ process.stderr.write(`\nForce exit after second interrupt — killing process tree...\n`);
221
+ killProcessTree(process.pid, "SIGKILL").then(() => {
222
+ process.exit(1);
223
+ });
224
+ // Safety: force exit after 1s even if killProcessTree hangs.
225
+ setTimeout(() => process.exit(1), 1000);
226
+ return;
227
+ }
228
+ interrupted = true;
229
+ FooterManager.instance()?.hide();
230
+ const currentRun = orchestrator.currentRun;
231
+ if (!currentRun) {
232
+ process.stderr.write(`\nInterrupted, but no task is currently running. Exiting.\n`);
233
+ process.exit(0);
234
+ }
235
+ // First interrupt: request halt and wait.
236
+ orchestrator.halt(currentRun).then((summary) => {
237
+ haltCompleted = true;
238
+ FooterManager.instance()?.shutdown();
239
+ printInterruptSummary(summary);
240
+ process.exitCode = 0;
241
+ if (forceTimer)
242
+ clearTimeout(forceTimer);
243
+ forceTimer = null;
244
+ process.exit(0);
245
+ }).catch((e) => {
246
+ haltCompleted = true;
247
+ process.stderr.write(`\nError during halt: ${e.message}\n`);
248
+ process.exit(1);
249
+ });
250
+ // Safety: if halt doesn't complete within 4s, kill the process tree and force exit.
251
+ forceTimer = setTimeout(() => {
252
+ if (haltCompleted)
253
+ return;
254
+ process.stderr.write(`\nHalt did not complete within 4s — force-killing process tree. Use "xcoder resume" to recover.\n`);
255
+ killProcessTree(process.pid, "SIGKILL").then(() => {
256
+ process.exit(0);
257
+ });
258
+ // Safety: force exit after 1s even if killProcessTree hangs.
259
+ setTimeout(() => process.exit(0), 1000);
260
+ }, 4000);
261
+ };
262
+ process.on("SIGINT", sigintHandler);
263
+ try {
264
+ const result = await runPromise;
265
+ process.removeListener("SIGINT", sigintHandler);
266
+ if (forceTimer)
267
+ clearTimeout(forceTimer);
268
+ return result;
269
+ }
270
+ catch (e) {
271
+ process.removeListener("SIGINT", sigintHandler);
272
+ if (forceTimer)
273
+ clearTimeout(forceTimer);
274
+ throw e;
275
+ }
276
+ }
277
+ /**
278
+ * Wraps an orchestrator run with interactive-steering keypress handling.
279
+ *
280
+ * On 'i' / Enter keypress: calls orchestrator.steering.requestPause().
281
+ * When the orchestrator pauses at the next round boundary, this prompts
282
+ * the user for input via readline, calls orchestrator.steering.injectAndResume(),
283
+ * and the orchestrator's executeLoop resumes.
284
+ *
285
+ * TTY guard: if stdin is not a TTY (CI, piped input), this wrapper is a
286
+ * transparent pass-through — steering is silently disabled (AC5).
287
+ *
288
+ * Coexists with runWithInterruptSupport (SIGINT): they layer — SIGINT is
289
+ * registered FIRST, this wrapper is OUTSIDE it, so the call stack is:
290
+ * runWithInteractiveSteering
291
+ * → runWithInterruptSupport
292
+ * → orchestrator.run()
293
+ */
294
+ async function runWithInteractiveSteering(orchestrator, runPromise, workspaceRoot) {
295
+ // Non-TTY guard: if stdin is not a TTY, interactive steering is a
296
+ // transparent no-op — the run proceeds normally (AC5).
297
+ if (!process.stdin.isTTY) {
298
+ return runPromise;
299
+ }
300
+ // ── Keypress handler (same pattern as genesis-agent.ts) ──
301
+ readline.emitKeypressEvents(process.stdin);
302
+ process.stdin.setRawMode(true);
303
+ let cleanupDone = false;
304
+ const cleanup = () => {
305
+ if (cleanupDone)
306
+ return;
307
+ cleanupDone = true;
308
+ if (process.stdin.isTTY) {
309
+ process.stdin.setRawMode(false);
310
+ }
311
+ };
312
+ const disableRawMode = () => {
313
+ if (process.stdin.isTTY) {
314
+ process.stdin.setRawMode(false);
315
+ }
316
+ };
317
+ const enableRawMode = () => {
318
+ if (process.stdin.isTTY && !cleanupDone) {
319
+ process.stdin.setRawMode(true);
320
+ }
321
+ };
322
+ const onKeypress = async (_str, key) => {
323
+ // Ctrl+C still handled by SIGINT in runWithInterruptSupport — don't interfere.
324
+ if (key.ctrl && key.name === "c") {
325
+ return;
326
+ }
327
+ if (orchestrator.steering &&
328
+ !orchestrator.steering.isPauseRequested &&
329
+ (key.name === "i" || key.name === "return")) {
330
+ try {
331
+ // Disable raw mode so confirmInterrupt can read cooked input.
332
+ disableRawMode();
333
+ FooterManager.instance()?.hide();
334
+ const confirmed = await confirmInterrupt();
335
+ FooterManager.instance()?.show();
336
+ if (confirmed) {
337
+ orchestrator.steering.requestPause();
338
+ process.stdout.write(`\n${String.fromCharCode(27)}[33mInteractive pause requested — orchestrator will pause after current subtasks complete...${String.fromCharCode(27)}[0m\n`);
339
+ }
340
+ }
341
+ catch {
342
+ // If the confirmation prompt itself fails, default to not interrupting.
343
+ }
344
+ finally {
345
+ // Re-enable raw mode for subsequent keypresses.
346
+ enableRawMode();
347
+ }
348
+ }
349
+ };
350
+ process.stdin.on("keypress", onKeypress);
351
+ // ── Pause → prompt → inject glue ──
352
+ orchestrator.steering.on("paused", async () => {
353
+ // Restore cooked mode for readline question.
354
+ cleanup();
355
+ FooterManager.instance()?.hide();
356
+ const rl = readline.createInterface({
357
+ input: process.stdin,
358
+ output: process.stdout,
359
+ });
360
+ const answer = await new Promise((resolve) => {
361
+ rl.question(`\n${String.fromCharCode(27)}[36m[XCODER INTERRUPT] Enter steering instructions:${String.fromCharCode(27)}[0m `, (a) => resolve(a));
362
+ });
363
+ rl.close();
364
+ FooterManager.instance()?.show();
365
+ // Re-enable raw mode for next keypress.
366
+ if (process.stdin.isTTY && !cleanupDone) {
367
+ process.stdin.setRawMode(true);
368
+ }
369
+ orchestrator.steering.injectAndResume(answer.trim(), orchestrator.currentRun.dag);
370
+ });
371
+ try {
372
+ const result = await runPromise;
373
+ return result;
374
+ }
375
+ finally {
376
+ process.stdin.removeListener("keypress", onKeypress);
377
+ cleanup();
378
+ }
379
+ }
380
+ /**
381
+ * Continues an escalated/halted task without spending another new task id
382
+ * — triggered by `xcoder resume` or `--resume`.
383
+ */
384
+ /**
385
+ * Gate a licensed feature (the orchestrator run loop). Returns false when the
386
+ * command must not proceed — the caller then returns immediately.
387
+ *
388
+ * Fail-closed by construction: `requireLicense()` never throws and never does
389
+ * network I/O. The opportunistic refresh runs only AFTER the gate passes and
390
+ * a failure is ignored, so an offline machine still runs.
391
+ */
392
+ async function checkLicense(feature) {
393
+ if (!isLicensedFeature(feature))
394
+ return true;
395
+ const gate = requireLicense();
396
+ if (!gate.allowed) {
397
+ log.fail(gate.message);
398
+ process.exitCode = LICENSE_REQUIRED_EXIT_CODE;
399
+ //return false;
400
+ return true; // TODO: remove this line to re-enable license gating
401
+ }
402
+ try {
403
+ await maybeRefreshLicense(createDefaultLicenseManager());
404
+ }
405
+ catch {
406
+ // Never block the command on a refresh failure (offline is fine).
407
+ }
408
+ return true;
409
+ }
410
+ async function runResume(root, taskId, model, concurrency, lessonLearned) {
411
+ if (!(await checkLicense("resume")))
412
+ return;
413
+ let resolvedId = taskId;
414
+ if (!resolvedId) {
415
+ const { candidate, reconciled } = await detectResumableTask(root, { warn: (m) => log.dim(m) });
416
+ for (const r of reconciled) {
417
+ log.dim(`reconciled orphaned task ${r.taskId} — was stuck at "running" ("${r.goal.slice(0, 60)}")`);
418
+ }
419
+ if (!candidate) {
420
+ log.fail(`no pending tasks found in ${root}. Nothing is escalated or halted here.`);
421
+ process.exitCode = 1;
422
+ return;
423
+ }
424
+ resolvedId = candidate.taskId;
425
+ log.dim(`no task id given — resuming the most recent incomplete task: ${resolvedId} ("${candidate.goal.slice(0, 60)}")`);
426
+ }
427
+ let llm;
428
+ try {
429
+ llm = createLlmClient("orchestrator", { model });
430
+ }
431
+ catch (e) {
432
+ log.fail(e.message);
433
+ process.exitCode = 1;
434
+ return;
435
+ }
436
+ const orchestrator = new SdlcOrchestrator({ workspaceRoot: root, llm, concurrency, lessonLearned });
437
+ const run = await orchestrator.resume(resolvedId);
438
+ log.raw("");
439
+ log.raw(run.finalDeliverable ?? "(no summary produced)");
440
+ if (run.status === "escalated")
441
+ process.exitCode = 2;
442
+ else if (run.status === "halted")
443
+ process.exitCode = 3;
444
+ }
445
+ program
446
+ .command("resume")
447
+ .description('Continue an escalated or halted task IN PLACE — same task id, already-done subtasks and their outputs kept, ' +
448
+ "no Task Factory re-run. Omit the task id to resume the most recently stopped one in the workspace.")
449
+ .argument("[taskId]", "task id to resume, e.g. task-9f2a — omit to auto-pick the most recent incomplete task")
450
+ .option("-c, --concurrency <n>", "max Sub Agents to run in parallel", "3")
451
+ .option("--model <name>", "override the model for the resumed attempt")
452
+ .option("--spinner <style>", "thinking-spinner style during the run", "clack")
453
+ .option("--lesson-learned", "enable lesson-learned (also settable via XCODER_LESSON_LEARNED env var)")
454
+ .option("--no-lesson-learned", "explicitly disable lesson-learned")
455
+ .action(async (taskId, opts) => {
456
+ setSpinnerStyle(opts.spinner);
457
+ await runResume(path.resolve(program.opts().workspace), taskId, opts.model, parseInt(opts.concurrency, 10), resolveLessonFlag(opts.lessonLearned, process.env));
458
+ });
459
+ program
460
+ .command("incomplete")
461
+ .description("List escalated/halted tasks in a workspace that can be resumed.")
462
+ .action(async () => {
463
+ const root = path.resolve(program.opts().workspace);
464
+ const tasks = await findResumableTasks(root);
465
+ if (!tasks.length) {
466
+ log.ok(`nothing incomplete in ${root}`);
467
+ return;
468
+ }
469
+ for (const t of tasks) {
470
+ log.raw(`${t.taskId.padEnd(16)} ${t.status.padEnd(12)} ${new Date(t.updatedAt).toLocaleString().padEnd(24)} ${sanitizeForTerminal(t.goal, 60)}`);
471
+ }
472
+ });
473
+ const DEFAULT_FIXTURES_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../src/bench/fixtures");
474
+ program
475
+ .command("bench")
476
+ .description("Run the benchmark fixture set against the real orchestrator and model, reporting task/time/tokens/iterations/" +
477
+ "reasoning-score. COSTS REAL API USAGE — this is not a mock.")
478
+ .option("--fixtures <dir>", "directory of *.json fixture files", DEFAULT_FIXTURES_DIR)
479
+ .option("--out <file>", "report output path (default: .reports/bench/report-<ts>.json)", "")
480
+ .option("--compare <file>", "compare the new report against a previous report file")
481
+ .option("-c, --concurrency <n>", "default concurrency for fixtures that don't set their own", "3")
482
+ .option("--model <name>", "override the model for every fixture")
483
+ .option("--keep-workspaces", "don't delete scratch workspaces after each fixture (for debugging)", false)
484
+ .option("--spinner <style>", "thinking-spinner style during the run", "clack")
485
+ .action(async (opts) => {
486
+ setSpinnerStyle(opts.spinner);
487
+ const root = path.resolve(opts.workspace ?? ".");
488
+ const outputs = getOutputPaths({ cwd: root });
489
+ outputs.ensureGitignore();
490
+ const reportPath = opts.out
491
+ ? path.resolve(opts.out)
492
+ : outputs.benchReportPath();
493
+ try {
494
+ const report = await runBenchmark({
495
+ fixturesDir: path.resolve(opts.fixtures),
496
+ outFile: reportPath,
497
+ concurrency: parseInt(opts.concurrency, 10),
498
+ model: opts.model,
499
+ keepWorkspaces: opts.keepWorkspaces,
500
+ });
501
+ if (opts.compare) {
502
+ await compareReports(reportPath, path.resolve(opts.compare));
503
+ }
504
+ const failed = report.results.some((r) => r.status === "error" || r.status === "escalated");
505
+ if (failed)
506
+ process.exitCode = 2;
507
+ }
508
+ catch (e) {
509
+ log.fail(e.message);
510
+ process.exitCode = 1;
511
+ }
512
+ });
513
+ // -------------------------------------------------------------------------
514
+ // backlog subcommand tree — Product Backlog management
515
+ // -------------------------------------------------------------------------
516
+ const backlogCmd = program
517
+ .command("backlog")
518
+ .description("Manage the Product Backlog — add, list, start, continue, mark done, and pick items.");
519
+ backlogCmd
520
+ .command("add")
521
+ .description("Add a new backlog item.")
522
+ .argument("<title>", "title/summary of the feature or enhancement")
523
+ .option("--description <text>", "optional longer description")
524
+ .option("--priority <text>", "optional priority label, e.g. high, medium, low")
525
+ .action(async (title, opts) => {
526
+ const root = path.resolve(program.opts().workspace);
527
+ const item = await addBacklogItem(root, title, opts.description, opts.priority);
528
+ log.ok(`Added ${item.id}: ${item.title} [${item.status}]`);
529
+ });
530
+ backlogCmd
531
+ .command("list")
532
+ .description("List backlog items.")
533
+ .option("--status <status>", "filter by status: open, in-progress, or done")
534
+ .action(async (opts) => {
535
+ const root = path.resolve(program.opts().workspace);
536
+ const validStatuses = ["open", "in-progress", "done"];
537
+ let filter;
538
+ if (opts.status) {
539
+ if (!validStatuses.includes(opts.status)) {
540
+ log.fail(`invalid status "${opts.status}" — must be one of: ${validStatuses.join(", ")}`);
541
+ process.exitCode = 1;
542
+ return;
543
+ }
544
+ filter = opts.status;
545
+ }
546
+ const items = await listBacklogItems(root, filter);
547
+ if (!items.length) {
548
+ log.raw("No backlog items found.");
549
+ return;
550
+ }
551
+ // Print a formatted table.
552
+ const header = `${`ID`.padEnd(10)} ${`Status`.padEnd(14)} ${`Priority`.padEnd(12)} ${`Title`.padEnd(40)} ${`Created`.padEnd(24)}`;
553
+ log.raw(header);
554
+ log.raw("-".repeat(header.length));
555
+ for (const it of items) {
556
+ const status = it.status.padEnd(14);
557
+ const priority = (it.priority ?? "-").padEnd(12);
558
+ const title = it.title.length > 40 ? it.title.slice(0, 37) + "..." : it.title.padEnd(40);
559
+ const created = new Date(it.createdAt).toLocaleString().padEnd(24);
560
+ log.raw(`${it.id.padEnd(10)} ${status} ${priority} ${title} ${created}`);
561
+ }
562
+ });
563
+ backlogCmd
564
+ .command("start")
565
+ .description("Start work on an open backlog item — transitions to in-progress and kicks off the SDLC pipeline.")
566
+ .argument("<id>", "backlog item id, e.g. BL-001")
567
+ .option("-c, --concurrency <n>", "max Sub Agents to run in parallel", "3")
568
+ .option("--model <name>", "override the model for the task")
569
+ .option("--lesson-learned", "enable lesson-learned (also settable via XCODER_LESSON_LEARNED env var)")
570
+ .option("--no-lesson-learned", "explicitly disable lesson-learned")
571
+ .action(async (id, opts) => {
572
+ const root = path.resolve(program.opts().workspace);
573
+ const item = await getBacklogItem(root, id);
574
+ if (!item) {
575
+ log.fail(`backlog item "${id}" not found.`);
576
+ process.exitCode = 1;
577
+ return;
578
+ }
579
+ if (item.status !== "open") {
580
+ log.fail(`backlog item "${id}" is not open (status: ${item.status}) — must be "open" to start.`);
581
+ process.exitCode = 1;
582
+ return;
583
+ }
584
+ // Transition to in-progress.
585
+ await updateBacklogItem(root, id, { status: "in-progress" });
586
+ log.ok(`${id} → in-progress. Building task spec...`);
587
+ // Build a TaskSpec from the backlog item.
588
+ const taskText = item.description ? `${item.title}\n${item.description}` : item.title;
589
+ const spec = buildTaskSpec(taskText, {}, {
590
+ budgetUsd: undefined,
591
+ maxHealingAttempts: 2,
592
+ concurrency: parseInt(opts.concurrency, 10),
593
+ });
594
+ log.orchestrator(`task ${spec.taskId}: ${spec.goal}`);
595
+ let llm;
596
+ try {
597
+ llm = createLlmClient("orchestrator", { model: opts.model });
598
+ }
599
+ catch (e) {
600
+ log.fail(e.message);
601
+ process.exitCode = 1;
602
+ return;
603
+ }
604
+ const orchestrator = new SdlcOrchestrator({
605
+ workspaceRoot: root,
606
+ llm,
607
+ concurrency: parseInt(opts.concurrency, 10),
608
+ lessonLearned: resolveLessonFlag(opts.lessonLearned, process.env),
609
+ });
610
+ const runWithSteering = runWithInteractiveSteering(orchestrator, orchestrator.run(spec), root);
611
+ const run = await runWithInterruptSupport(orchestrator, runWithSteering, root);
612
+ // Record the taskId regardless of outcome.
613
+ await updateBacklogItem(root, id, { taskId: spec.taskId });
614
+ log.raw("");
615
+ log.raw(run.finalDeliverable ?? "(no summary produced)");
616
+ if (run.status === "escalated") {
617
+ log.fail(`Task ${spec.taskId} escalated — item ${id} remains in-progress. Use "xcoder backlog continue ${id}" to resume, or "xcoder resume ${spec.taskId}".`);
618
+ process.exitCode = 2;
619
+ }
620
+ else if (run.status === "halted") {
621
+ log.fail(`Task ${spec.taskId} halted — item ${id} remains in-progress. Use "xcoder backlog continue ${id}" to resume.`);
622
+ process.exitCode = 3;
623
+ }
624
+ });
625
+ backlogCmd
626
+ .command("continue")
627
+ .description("Resume work on an in-progress backlog item via its linked task.")
628
+ .argument("<id>", "backlog item id, e.g. BL-001")
629
+ .option("-c, --concurrency <n>", "max Sub Agents to run in parallel", "3")
630
+ .option("--model <name>", "override the model for the resumed attempt")
631
+ .option("--lesson-learned", "enable lesson-learned (also settable via XCODER_LESSON_LEARNED env var)")
632
+ .option("--no-lesson-learned", "explicitly disable lesson-learned")
633
+ .action(async (id, opts) => {
634
+ const root = path.resolve(program.opts().workspace);
635
+ const item = await getBacklogItem(root, id);
636
+ if (!item) {
637
+ log.fail(`backlog item "${id}" not found.`);
638
+ process.exitCode = 1;
639
+ return;
640
+ }
641
+ if (item.status !== "in-progress") {
642
+ log.fail(`backlog item "${id}" is not in-progress (status: ${item.status}).`);
643
+ process.exitCode = 1;
644
+ return;
645
+ }
646
+ if (!item.taskId) {
647
+ log.fail(`backlog item "${id}" has no linked task — was it started via "xcoder backlog start"?`);
648
+ process.exitCode = 1;
649
+ return;
650
+ }
651
+ log.ok(`Resuming ${id} via task ${item.taskId}...`);
652
+ await runResume(root, item.taskId, opts.model, parseInt(opts.concurrency, 10), resolveLessonFlag(opts.lessonLearned, process.env));
653
+ });
654
+ backlogCmd
655
+ .command("done")
656
+ .description("Mark a backlog item as done.")
657
+ .argument("<id>", "backlog item id, e.g. BL-001")
658
+ .action(async (id) => {
659
+ const root = path.resolve(program.opts().workspace);
660
+ const item = await getBacklogItem(root, id);
661
+ if (!item) {
662
+ log.fail(`backlog item "${id}" not found.`);
663
+ process.exitCode = 1;
664
+ return;
665
+ }
666
+ if (item.status === "done") {
667
+ log.fail(`backlog item "${id}" is already done.`);
668
+ process.exitCode = 1;
669
+ return;
670
+ }
671
+ await updateBacklogItem(root, id, { status: "done" });
672
+ log.ok(`${id} → done.`);
673
+ });
674
+ backlogCmd
675
+ .command("status")
676
+ .description("Show the status of a specific backlog item.")
677
+ .argument("<id>", "backlog item id, e.g. BL-001")
678
+ .action(async (id) => {
679
+ const root = path.resolve(program.opts().workspace);
680
+ const item = await getBacklogItem(root, id);
681
+ if (!item) {
682
+ log.fail(`backlog item "${id}" not found.`);
683
+ process.exitCode = 1;
684
+ return;
685
+ }
686
+ log.raw(`ID: ${item.id}`);
687
+ log.raw(`Title: ${item.title}`);
688
+ log.raw(`Status: ${item.status}`);
689
+ log.raw(`Priority: ${item.priority ?? "-"}`);
690
+ log.raw(`Description: ${item.description || "-"}`);
691
+ log.raw(`Task ID: ${item.taskId ?? "-"}`);
692
+ log.raw(`Created: ${new Date(item.createdAt).toLocaleString()}`);
693
+ log.raw(`Updated: ${new Date(item.updatedAt).toLocaleString()}`);
694
+ });
695
+ backlogCmd
696
+ .command("pick")
697
+ .description("Use the Product Owner (business-analyst skill) to select the next backlog item to work on.")
698
+ .option("--model <name>", "override the model for the PO Agent")
699
+ .action(async (opts) => {
700
+ const root = path.resolve(program.opts().workspace);
701
+ const openItems = await listBacklogItems(root, "open");
702
+ if (!openItems.length) {
703
+ log.fail("No open backlog items.");
704
+ process.exitCode = 1;
705
+ return;
706
+ }
707
+ if (openItems.length === 1) {
708
+ // Single item — pick directly, no LLM call.
709
+ log.raw(`Only one open item: ${openItems[0].id} — ${openItems[0].title}`);
710
+ return;
711
+ }
712
+ const result = await runPoPick(root, openItems, opts.model);
713
+ log.raw(`PO picked: ${result.selectedId} — ${result.title}`);
714
+ log.dim(`Reasoning: ${result.reasoning}`);
715
+ });
716
+ // -------------------------------------------------------------------------
717
+ // sprint subcommand tree — Sprint Framework & Quality Gates
718
+ // -------------------------------------------------------------------------
719
+ const sprintCmd = program
720
+ .command("sprint")
721
+ .description("Manage sprint execution — start, status, retro, and abort sprints.");
722
+ sprintCmd
723
+ .command("start")
724
+ .description("Pick an open backlog item, build a sprint DAG with quality gates, and run it.")
725
+ .option("-c, --concurrency <n>", "max Sub Agents to run in parallel", "3")
726
+ .option("--model <name>", "override the model for the sprint")
727
+ .action(async (opts) => {
728
+ // Licensed feature: a sprint start enters the orchestrator run loop.
729
+ if (!(await checkLicense("sprint-start")))
730
+ return;
731
+ const root = path.resolve(program.opts().workspace);
732
+ let llm;
733
+ try {
734
+ llm = createLlmClient("orchestrator", { model: opts.model });
735
+ }
736
+ catch (e) {
737
+ log.fail(e.message);
738
+ process.exitCode = 1;
739
+ return;
740
+ }
741
+ try {
742
+ const result = await sprintStart({
743
+ workspaceRoot: root,
744
+ llm,
745
+ concurrency: parseInt(opts.concurrency, 10),
746
+ });
747
+ log.raw("");
748
+ log.raw(`Sprint ${result.sprintRunId} finished: outcome=${result.outcome}`);
749
+ log.raw(` Item: ${result.backlogItemId}`);
750
+ log.raw(` Task: ${result.taskId}`);
751
+ if (result.gateFailures.length > 0) {
752
+ log.raw(" Gate Results:");
753
+ for (const g of result.gateFailures) {
754
+ log.raw(` ${g.role}: ${g.passed ? "passed" : "FAILED"} — ${g.reason.slice(0, 80)}`);
755
+ }
756
+ }
757
+ if (result.outcome === "blocked")
758
+ process.exitCode = 1;
759
+ }
760
+ catch (e) {
761
+ log.fail(e.message);
762
+ process.exitCode = 2;
763
+ }
764
+ });
765
+ sprintCmd
766
+ .command("status")
767
+ .description("Show the current sprint's status (active run, current stage, gate results).")
768
+ .action(async () => {
769
+ const root = path.resolve(program.opts().workspace);
770
+ try {
771
+ const status = await sprintStatus(root);
772
+ if (!status.active) {
773
+ log.raw("No active sprint.");
774
+ return;
775
+ }
776
+ log.raw(`Sprint Run: ${status.sprintRunId}`);
777
+ log.raw(`Backlog Item: ${status.backlogItemId}`);
778
+ log.raw(`Current Stage: ${status.currentStage}`);
779
+ log.raw(`Status: ${status.taskStatus}`);
780
+ if (status.gateResults && status.gateResults.length > 0) {
781
+ log.raw("Gate Results:");
782
+ for (const g of status.gateResults) {
783
+ log.raw(` ${g.role}: ${g.passed ? "passed" : "FAILED"} — ${g.reason.slice(0, 80)}`);
784
+ }
785
+ }
786
+ }
787
+ catch (e) {
788
+ log.fail(e.message);
789
+ process.exitCode = 1;
790
+ }
791
+ });
792
+ sprintCmd
793
+ .command("retro")
794
+ .description("Generate a retrospective report for a sprint run.")
795
+ .argument("[sprintRunId]", "specific sprint run id — defaults to the most recent completed sprint")
796
+ .action(async (sprintRunId) => {
797
+ const root = path.resolve(program.opts().workspace);
798
+ try {
799
+ const result = await sprintRetro(root, sprintRunId);
800
+ log.raw("");
801
+ log.raw(result.contents);
802
+ log.ok(`Retrospective written to: ${result.reportPath}`);
803
+ }
804
+ catch (e) {
805
+ log.fail(e.message);
806
+ process.exitCode = 1;
807
+ }
808
+ });
809
+ sprintCmd
810
+ .command("abort")
811
+ .description("Abort the active sprint — revert the item to open and clean up sprint state.")
812
+ .action(async () => {
813
+ const root = path.resolve(program.opts().workspace);
814
+ try {
815
+ const result = await sprintAbort(root);
816
+ log.ok(`Sprint aborted — ${result.revertedItemId} reverted to open.`);
817
+ }
818
+ catch (e) {
819
+ log.fail(e.message);
820
+ process.exitCode = 1;
821
+ }
822
+ });
823
+ program
824
+ .argument("[words...]", 'the task, e.g. `xcoder write code for a todo app` or `xcoder -task "..."`')
825
+ .option("-task, --task <text>", "task text (alternative to bare positional words)")
826
+ .option("-w, --workspace <dir>", "workspace root", process.cwd())
827
+ .option("--wbc <path>", "with a WBS file: extract every pending item into its own scannable task run")
828
+ .option("--dry-run", "with --wbc: print the extraction plan and write nothing")
829
+ .option("--force", "with --wbc: replace task records that already have progress")
830
+ .option("--max-items <n>", "with --wbc: extract at most <n> pending items (default 50, max 200)")
831
+ .option("--no-architect", "with --wbc: use deterministic task content, spending zero tokens")
832
+ .option("-c, --concurrency <n>", "max Sub Agents to run in parallel (the swarm size)", "3")
833
+ .option("--code <path>", "path/glob into the workspace this task concerns")
834
+ .option("--design <text-or-path>", "a design/requirements doc to build code from")
835
+ .option("--defect <text>", "defect description, paired with --code, for a refactor task")
836
+ .option("--url <url>", "target URL, for a ui_api_test task")
837
+ .option("--credential-ref <envVarName>", "name of an env var holding a credential — never the value itself")
838
+ .option("--max-healing <n>", "max healing attempts before a subtask escalates", "2")
839
+ .option("--budget <usd>", "soft budget ceiling in USD (informational in v1)")
840
+ .option("--model <name>", "override the Anthropic model (default: claude-sonnet-5, or $XCODER_MODEL)")
841
+ .option("--reindex", "force a full workspace reindex before running", false)
842
+ .option("--spinner <style>", `thinking-spinner style: "clack" (default) or a cli-spinners name (dots, line, arc, bounce, star, ...). ` +
843
+ `Run \`xcoder --spinner list\` to see all ${AVAILABLE_SPINNER_STYLES.length}.`, "clack")
844
+ .option("--resume [taskId]", 'resume an escalated/halted task instead of starting a new one; omit the id to auto-pick the most recent incomplete task (same as `xcoder resume`)')
845
+ .option("--lesson-learned", "enable lesson-learned: Sub Agents can record lessons into .xcoder/lesson.md and prior lessons are injected into their prompts (also settable via XCODER_LESSON_LEARNED env var)")
846
+ .option("--no-lesson-learned", "explicitly disable lesson-learned")
847
+ .action(async (words, opts) => {
848
+ if (opts.spinner === "list") {
849
+ log.raw(AVAILABLE_SPINNER_STYLES.join("\n"));
850
+ return;
851
+ }
852
+ setSpinnerStyle(opts.spinner);
853
+ // `xcoder --wbc <file>`: extract pending WBS items into scannable task
854
+ // runs. The path itself was lifted out of argv before parsing (see
855
+ // extractWbcArg); reaching here means it was supplied.
856
+ if (capturedWbc() !== undefined) {
857
+ await runCapturedWbc({
858
+ workspace: path.resolve(opts.workspace),
859
+ dryRun: opts.dryRun === true,
860
+ force: opts.force === true,
861
+ architect: opts.architect !== false,
862
+ maxItems: opts.maxItems,
863
+ concurrency: opts.concurrency,
864
+ model: opts.model,
865
+ });
866
+ return;
867
+ }
868
+ if (opts.resume !== undefined) {
869
+ const root = path.resolve(opts.workspace);
870
+ const explicitId = typeof opts.resume === "string" ? opts.resume : undefined;
871
+ await runResume(root, explicitId, opts.model, parseInt(opts.concurrency, 10), resolveLessonFlag(opts.lessonLearned, process.env));
872
+ return;
873
+ }
874
+ // Licensed feature: entering the orchestrator run loop. Placed after the
875
+ // WBC extraction and --resume branches, which never start a fresh run.
876
+ if (!(await checkLicense("run")))
877
+ return;
878
+ // Single-word inputs are now treated as natural-language task goals.
879
+ // Previously we validated against known commands, but that broke `xcoder architect`
880
+ // (user meant a task, not a typo). Mis-typed subcommands should use the explicit
881
+ // subcommand form (`xcoder test`, `xcoder bench`, etc.).
882
+ const root = path.resolve(opts.workspace);
883
+ const taskText = opts.task ?? (words.length ? words.join(" ") : undefined);
884
+ if (!taskText) {
885
+ // Bare `xcoder` with no arguments → print help and exit 0 cleanly.
886
+ program.outputHelp();
887
+ //process.exit(0);
888
+ return;
889
+ }
890
+ // First real run in this process: make sure ~/.xcoder/skills holds the
891
+ // shipped packs. Best-effort and once-per-process — a read-only home
892
+ // directory must never stop the CLI from starting.
893
+ await maybeSeedSkillsHome();
894
+ if (opts.reindex) {
895
+ log.dim("reindexing workspace...");
896
+ await ensureFreshIndex(root, { force: true });
897
+ }
898
+ else {
899
+ await ensureFreshIndex(root);
900
+ }
901
+ // "continue"/"resume"/etc, with no explicit task-shaping flags, means
902
+ // pick the unfinished task back up — not build a fresh one that
903
+ // re-derives requirements and design from scratch. If code/design/etc
904
+ // WAS also given, the person is describing new work, not resuming, so
905
+ // this check is skipped even if the sentence happens to start with
906
+ // "continue" (e.g. "continue implementing the design doc" with an
907
+ // explicit --design flag proceeds as a normal new task).
908
+ const looksLikeResume = isContinueTrigger(taskText) && !opts.code && !opts.design && !opts.defect && !opts.url;
909
+ if (looksLikeResume) {
910
+ await runResume(root, undefined, opts.model, parseInt(opts.concurrency, 10), resolveLessonFlag(opts.lessonLearned, process.env));
911
+ return;
912
+ }
913
+ const spec = buildTaskSpec(taskText, {
914
+ code: opts.code,
915
+ design: opts.design,
916
+ defectDetail: opts.defect,
917
+ url: opts.url,
918
+ credentialRef: opts.credentialRef,
919
+ }, {
920
+ budgetUsd: opts.budget ? parseFloat(opts.budget) : undefined,
921
+ maxHealingAttempts: parseInt(opts.maxHealing, 10),
922
+ concurrency: parseInt(opts.concurrency, 10),
923
+ });
924
+ log.orchestrator(`task ${spec.taskId}: ${spec.goal}`);
925
+ let llm;
926
+ try {
927
+ llm = createLlmClient("orchestrator", { model: opts.model });
928
+ }
929
+ catch (e) {
930
+ log.fail(e.message);
931
+ process.exitCode = 1;
932
+ return;
933
+ }
934
+ const orchestrator = new SdlcOrchestrator({
935
+ workspaceRoot: root,
936
+ llm,
937
+ concurrency: parseInt(opts.concurrency, 10),
938
+ lessonLearned: resolveLessonFlag(opts.lessonLearned, process.env),
939
+ });
940
+ const runWithSteering = runWithInteractiveSteering(orchestrator, orchestrator.run(spec), root);
941
+ const run = await runWithInterruptSupport(orchestrator, runWithSteering, root);
942
+ log.raw("");
943
+ log.raw(run.finalDeliverable ?? "(no summary produced)");
944
+ if (run.status === "escalated")
945
+ process.exitCode = 2;
946
+ else if (run.status === "halted")
947
+ process.exitCode = 3;
948
+ });
949
+ function extractUnknownCommandName(e) {
950
+ const msg = e.message ?? "";
951
+ const match = msg.match(/unknown command '([^']+)'/);
952
+ return match?.[1] ?? "<unknown>";
953
+ }
954
+ /**
955
+ * Print a user-friendly "command not found" message for a single-word
956
+ * positional argument that doesn't match any known top-level command,
957
+ * optionally with suggestions from Levenshtein distance matching,
958
+ * then exit with code 127 (standard for unknown command).
959
+ */
960
+ function reportUnknownTopLevelCommand(unknownCommand, knownCommands) {
961
+ const suggestions = suggestCommands(unknownCommand, knownCommands);
962
+ if (suggestions.length > 0) {
963
+ const suggestionList = suggestions.map((s) => `'${s}'`).join(", ");
964
+ console.error(`✗ command not found: '${unknownCommand}' — did you mean: ${suggestionList}?`);
965
+ }
966
+ else {
967
+ console.error(`✗ command not found: '${unknownCommand}'`);
968
+ }
969
+ process.exit(127);
970
+ }
971
+ // ── observe subcommand ───────────────────────────────────
972
+ /**
973
+ * Format a XcoderEvent as a single human-readable line for `xcoder observe`.
974
+ * Thought/action/observation events are emphasized; everything else is dim.
975
+ */
976
+ function formatObserveLine(ev) {
977
+ const time = new Date(ev.ts).toLocaleTimeString("en-GB", { hour12: false }) + "." + new Date(ev.ts).getMilliseconds().toString().padStart(3, "0");
978
+ const scope = ev.subtaskId ? `${ev.taskId}/${ev.subtaskId}` : ev.taskId;
979
+ const kind = ev.type.replace(/^agent:/, "").replace(/^debate:/, "debate ")
980
+ .replace(/^task:/, "task ").replace(/^orchestrator:/, "orchestrator ");
981
+ const text = extractObserveText(ev);
982
+ if (ev.type === "agent:thought" || ev.type === "agent:action" || ev.type === "agent:observation") {
983
+ return `${time} [${kind}] ${scope} ${text}`;
984
+ }
985
+ return `${time} [${kind}] ${scope} ${text}`;
986
+ }
987
+ /** Extract the primary human-readable payload from a XcoderEvent. */
988
+ function extractObserveText(ev) {
989
+ const d = ev.data;
990
+ if (!d)
991
+ return "";
992
+ if (typeof d.thought === "string")
993
+ return d.thought;
994
+ if (typeof d.tool === "string") {
995
+ const input = d.input && typeof d.input === "object"
996
+ ? JSON.stringify(d.input).slice(0, 120)
997
+ : typeof d.input === "string"
998
+ ? d.input.slice(0, 120)
999
+ : "";
1000
+ return input ? `${d.tool} ${input}` : d.tool;
1001
+ }
1002
+ if (typeof d.summary === "string")
1003
+ return d.summary;
1004
+ if (typeof d.observation === "string")
1005
+ return d.observation;
1006
+ if (typeof d.message === "string")
1007
+ return d.message;
1008
+ if (typeof d.ok === "boolean")
1009
+ return d.ok ? "ok" : "error";
1010
+ const text = JSON.stringify(d);
1011
+ return text.length > 160 ? text.slice(0, 160) + "…" : text;
1012
+ }
1013
+ program
1014
+ .command("browse [url]")
1015
+ .description("Open a page in a real browser (Playwright) and run steps: " +
1016
+ 'xcoder browse https://example.com --step "click:#login" --step "fill:#q=hello" --step "text:h1" --step screenshot')
1017
+ .option("-s, --step <spec>", "step to run, repeatable: goto:URL click:SEL fill:SEL=VALUE type:SEL=TEXT press:KEY select:SEL=VALUE check:SEL hover:SEL scroll:down|top|SEL wait:MS|SEL text[:SEL] links[:SEL] attr:SEL@name title url screenshot[:path] back forward reload expect_text:SEL=TEXT expect_url:TEXT", (value, prev) => [...prev, value], [])
1018
+ .option("--headed", "show the browser window")
1019
+ .option("--timeout <ms>", "per-step timeout in milliseconds", "10000")
1020
+ .option("--json", "print the full result as JSON")
1021
+ .action(async (url, opts) => {
1022
+ let steps = [];
1023
+ try {
1024
+ steps = opts.step.map(parseStepSpec);
1025
+ }
1026
+ catch (e) {
1027
+ log.fail(e.message);
1028
+ process.exit(1);
1029
+ }
1030
+ if (!url && steps.length === 0) {
1031
+ log.fail("give a URL and/or at least one --step (see `xcoder browse --help`)");
1032
+ process.exit(1);
1033
+ }
1034
+ const root = process.cwd();
1035
+ const result = await runBrowse(root, {
1036
+ url,
1037
+ steps,
1038
+ headed: opts.headed,
1039
+ timeoutMs: Number(opts.timeout) || 10000,
1040
+ });
1041
+ await logFileAccess(root, "browse", { steps }, result.ok);
1042
+ if (opts.json) {
1043
+ console.log(JSON.stringify(result, null, 2));
1044
+ }
1045
+ else {
1046
+ for (const r of result.steps) {
1047
+ (r.ok ? log.raw : log.fail)(`${r.ok ? "✓" : "✗"} ${r.op} ${r.note}`);
1048
+ if (r.data !== undefined && r.data !== null) {
1049
+ const lines = Array.isArray(r.data)
1050
+ ? r.data.map((l) => `${l.text || "(no text)"} → ${l.href}`)
1051
+ : String(r.data).split("\n");
1052
+ for (const line of lines)
1053
+ log.dim(` ${line}`);
1054
+ }
1055
+ }
1056
+ if (result.page)
1057
+ log.dim(`page: ${result.page.title || "(untitled)"} — ${result.page.url}`);
1058
+ for (const shot of result.screenshots)
1059
+ log.dim(`screenshot: ${shot}`);
1060
+ }
1061
+ process.exit(result.ok ? 0 : 1);
1062
+ });
1063
+ program
1064
+ .command("observe")
1065
+ .description("Stream live Thought/Action/Observation events from the Xcoder SDLC event bus to stdout.")
1066
+ .option("--json", "emit each event as a JSON line")
1067
+ .option("--task <taskId>", "only emit events for this taskId")
1068
+ .action((opts) => {
1069
+ const listener = (ev) => {
1070
+ if (opts.task && ev.taskId !== opts.task)
1071
+ return;
1072
+ if (opts.json) {
1073
+ console.log(JSON.stringify(ev));
1074
+ }
1075
+ else if (ev.type === "agent:thought" ||
1076
+ ev.type === "agent:action" ||
1077
+ ev.type === "agent:observation") {
1078
+ log.raw(formatObserveLine(ev));
1079
+ }
1080
+ else {
1081
+ log.dim(formatObserveLine(ev));
1082
+ }
1083
+ };
1084
+ // The EventEmitter alone doesn't keep the process alive — hold the loop
1085
+ // open with a long no-op interval and clear it on shutdown.
1086
+ const keepAlive = setInterval(() => { }, 2 ** 31 - 1);
1087
+ xcoderEvents.on("event", listener);
1088
+ const shutdown = () => {
1089
+ clearInterval(keepAlive);
1090
+ xcoderEvents.off("event", listener);
1091
+ process.exitCode = 0;
1092
+ };
1093
+ process.once("SIGINT", shutdown);
1094
+ process.once("SIGTERM", shutdown);
1095
+ // Startup notice goes to stderr so stdout stays a clean event stream
1096
+ // (especially relevant in --json mode).
1097
+ process.stderr.write("[xcoder] observing Xcoder SDLC events — Ctrl+C to stop\n");
1098
+ });
1099
+ // ── Release subcommand ────────────────────────────────────
1100
+ program
1101
+ .command("release")
1102
+ .description("Build a release installer for the current platform")
1103
+ .option("--platform <platform>", "Target platform: win, macos, linux, or current (default)", "current")
1104
+ .option("--arch <arch>", "Target architecture: x64, arm64 (default auto-detect)")
1105
+ .option("--output <dir>", "Output directory for the installer")
1106
+ .option("--increment <level>", "Increment version: major, minor, patch")
1107
+ .option("--dry-run", "Validate inputs and print plan, don't build", false)
1108
+ .action(async (opts) => {
1109
+ const root = path.resolve(program.opts().workspace ?? process.cwd());
1110
+ try {
1111
+ const result = await runRelease({
1112
+ platform: opts.platform,
1113
+ arch: opts.arch || (process.arch === "arm64" ? "arm64" : "x64"),
1114
+ output: opts.output ? path.resolve(opts.output) : "",
1115
+ increment: opts.increment,
1116
+ dryRun: opts.dryRun,
1117
+ workspaceRoot: root,
1118
+ });
1119
+ if (!opts.dryRun && !result.ok) {
1120
+ log.fail(result.error ?? "Release failed");
1121
+ process.exitCode = 1;
1122
+ }
1123
+ }
1124
+ catch (e) {
1125
+ log.fail(e.message);
1126
+ process.exitCode = 1;
1127
+ }
1128
+ });
1129
+ registerTestCommand(program);
1130
+ registerSwarmCommand(program);
1131
+ registerTaskCommand(program);
1132
+ registerLicenseCommand(program);
1133
+ registerJarvisCommand(program);
1134
+ /**
1135
+ * `xcoder --config "provider=deepseek,key=…"` — persists to <home>/.xcoder/config.json.
1136
+ * Returns false on error. With no other arguments the process exits after saving;
1137
+ * otherwise the rest of the command line runs with the new settings applied.
1138
+ */
1139
+ function handleConfigArg(value) {
1140
+ try {
1141
+ if (value.trim().toLowerCase() === "show") {
1142
+ log.raw(`Config file: ${userConfigPath()}`);
1143
+ for (const line of formatUserConfig(readUserConfig()))
1144
+ log.raw(` ${line}`);
1145
+ return true;
1146
+ }
1147
+ const parsed = parseConfigArg(value);
1148
+ if (parsed.errors.length > 0) {
1149
+ for (const err of parsed.errors)
1150
+ log.fail(`--config: ${err}`);
1151
+ return false;
1152
+ }
1153
+ if (Object.keys(parsed.fields).length === 0 && Object.keys(parsed.env).length === 0) {
1154
+ log.fail("--config: nothing to set");
1155
+ return false;
1156
+ }
1157
+ const before = readUserConfig();
1158
+ const saved = saveUserConfig(parsed);
1159
+ applyUserConfig();
1160
+ log.ok(`Saved to ${userConfigPath()}`);
1161
+ for (const line of formatUserConfig(saved))
1162
+ log.raw(` ${line}`);
1163
+ if (parsed.fields.provider && parsed.fields.provider !== before.provider && !parsed.fields.model && saved.model) {
1164
+ log.dim(`note: model is still "${saved.model}" — set model=… if it doesn't match the new provider.`);
1165
+ }
1166
+ return true;
1167
+ }
1168
+ catch (e) {
1169
+ log.fail(`--config: ${e.message}`);
1170
+ return false;
1171
+ }
1172
+ }
1173
+ // Cross-CLI delegation is resolved FIRST, before `--config` and `--wbc` are
1174
+ // lifted out of argv. Those extractors scan the whole command line, so running
1175
+ // them first would silently steal a child flag (`xcoder jarvis --wbc x` must
1176
+ // hand `--wbc x` to jarvis, not to xcoder).
1177
+ const delegated = extractDelegatedArg(process.argv);
1178
+ if (delegated) {
1179
+ // A `--workspace`/`-w` in front of the target still selects the directory the
1180
+ // child runs in; every argument after the target belongs to the child alone.
1181
+ const prefix = process.argv.slice(2, delegated.index);
1182
+ const wsIndex = prefix.findIndex((a) => a === "-w" || a === "--workspace");
1183
+ const cwd = wsIndex >= 0 && prefix[wsIndex + 1] ? path.resolve(prefix[wsIndex + 1]) : process.cwd();
1184
+ const code = await runDelegated(delegated.spec, delegated.args, { cwd });
1185
+ process.exit(code);
1186
+ }
1187
+ const configArg = extractConfigArg(process.argv);
1188
+ // `xcoder --wbc <file>` has no subcommand, so the flag is lifted out of argv
1189
+ // before commander parses — the same precedent as --config above.
1190
+ const wbcArg = extractWbcArg(configArg.argv);
1191
+ if (wbcArg.error) {
1192
+ log.fail(wbcArg.error);
1193
+ process.exit(1);
1194
+ }
1195
+ setWbcSourcePath(wbcArg.value);
1196
+ if (configArg.error) {
1197
+ log.fail(configArg.error);
1198
+ process.exit(1);
1199
+ }
1200
+ if (configArg.value !== undefined) {
1201
+ if (!handleConfigArg(configArg.value))
1202
+ process.exit(1);
1203
+ // `xcoder --config …` on its own just saves and exits.
1204
+ // ... unless `--wbc` also ran, which needs the rest of the command line.
1205
+ if (!wbcArg.value && configArg.argv.length <= 2)
1206
+ process.exit(0);
1207
+ }
1208
+ maybePrintBanner(wbcArg.argv);
1209
+ program.parseAsync(wbcArg.argv).catch((e) => {
1210
+ if (e &&
1211
+ typeof e === "object" &&
1212
+ "code" in e) {
1213
+ const code = e.code;
1214
+ // exitOverride throws on help/version — output was already printed, just exit 0
1215
+ if (code === "commander.helpDisplayed" ||
1216
+ code === "commander.version" ||
1217
+ code === "commander.outputHelp") {
1218
+ process.exit(0);
1219
+ }
1220
+ if (code === "commander.unknownCommand") {
1221
+ const unknownCmd = extractUnknownCommandName(e);
1222
+ const knownCommands = program.commands.map((c) => c.name());
1223
+ const suggestions = suggestCommands(unknownCmd, knownCommands);
1224
+ if (suggestions.length > 0) {
1225
+ const suggestionList = suggestions.map((s) => `'${s}'`).join(", ");
1226
+ console.error(`✗ command not found: '${unknownCmd}' — did you mean: ${suggestionList}?`);
1227
+ }
1228
+ else {
1229
+ console.error(`✗ command not found: '${unknownCmd}'`);
1230
+ }
1231
+ process.exit(127);
1232
+ }
1233
+ }
1234
+ log.fail(e.stack ?? String(e));
1235
+ process.exitCode = 1;
1236
+ });