canon-ai 3.12.0 → 3.13.0

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.
@@ -625,6 +625,9 @@ current root shown above and, from the main checkout, run
625
625
  function shellQuotePath(p) {
626
626
  return `'${p.replace(/'/g, `'\\''`)}'`;
627
627
  }
628
+ function shellQuoteArg(arg) {
629
+ return /^[A-Za-z0-9._\/@%+=:,-]+$/.test(arg) ? arg : shellQuotePath(arg);
630
+ }
628
631
  function assertTaskWorktreeWithinRoot(taskId) {
629
632
  if (process.env.CANON_TASKS_DIR_OVERRIDE) return;
630
633
  const resolved = resolveTaskCwd(taskId);
@@ -1018,7 +1021,7 @@ function commitTaskArtifactsToBase(taskIds, _artifactFiles) {
1018
1021
  if (status.ok && status.stdout.trim().length > 0) dirtyTelemetry.push(relPath);
1019
1022
  }
1020
1023
  if (dirtyTelemetry.length > 0) {
1021
- for (const relPath of dirtyTelemetry) git("add", "--", relPath);
1024
+ for (const relPath of filterStageablePaths(dirtyTelemetry, REPO_ROOT)) git("add", "--", relPath);
1022
1025
  git(
1023
1026
  "commit",
1024
1027
  "-m",
@@ -1922,12 +1925,12 @@ function resolveDocsFreshness(config3, diff) {
1922
1925
  // src/orchestrator/main.ts
1923
1926
  import { spawnSync as spawnSync7 } from "child_process";
1924
1927
  import { createHash } from "crypto";
1925
- import fs23 from "fs";
1928
+ import fs24 from "fs";
1926
1929
  import os from "os";
1927
1930
  import path22 from "path";
1928
1931
 
1929
1932
  // src/orchestrator/phases/code-review.ts
1930
- import fs17 from "fs";
1933
+ import fs18 from "fs";
1931
1934
  import path16 from "path";
1932
1935
 
1933
1936
  // src/lib/pipeline-policy.ts
@@ -2184,6 +2187,7 @@ function isPlanCombined2(status) {
2184
2187
 
2185
2188
  // src/orchestrator/agents/claude.ts
2186
2189
  import { spawn as spawn2 } from "child_process";
2190
+ import fs9 from "fs";
2187
2191
 
2188
2192
  // src/orchestrator/metrics.ts
2189
2193
  import fs8 from "fs";
@@ -2193,6 +2197,7 @@ var METRICS_SKELETON = [
2193
2197
  "",
2194
2198
  "> Auto-logged by canon's orchestrator. One row per agent invocation.",
2195
2199
  "> Tokens: per-invocation total (input + cache + output). Parsed from the agent's structured output \u2014 `claude -p --output-format stream-json` for Claude, `codex exec --json` for Codex. Interactive-mode invocations are not tracked.",
2200
+ "> Sub-agent rows: a Claude session that spawns sub-agents also logs one row per top-level sub-agent, Agent `claude:<agent type>`. Their Tokens are that sub-agent's own cumulative usage and are separate from (not included in) the session row.",
2196
2201
  "",
2197
2202
  "| Timestamp | Task | Phase | Agent | Model | Iter | Duration | Tokens | Status |",
2198
2203
  "|---|---|---|---|---|---|---|---|---|",
@@ -2221,7 +2226,7 @@ function recordMetric(entry) {
2221
2226
  const tok = entry.tokens != null ? String(entry.tokens) : "-";
2222
2227
  fs8.appendFileSync(
2223
2228
  metricsFile,
2224
- `| ${(/* @__PURE__ */ new Date()).toISOString()} | ${entry.taskId} | ${entry.phase} | ${entry.agent} | ${safeCell(entry.model)} | ${entry.iteration ?? "-"} | ${dur} | ${tok} | ${entry.status} |
2229
+ `| ${(/* @__PURE__ */ new Date()).toISOString()} | ${entry.taskId} | ${entry.phase} | ${safeCell(entry.agent)} | ${safeCell(entry.model)} | ${entry.iteration ?? "-"} | ${dur} | ${tok} | ${entry.status} |
2225
2230
  `
2226
2231
  );
2227
2232
  } catch (error) {
@@ -2382,6 +2387,35 @@ function formatLiveTick(event) {
2382
2387
  // src/orchestrator/agents/claude.ts
2383
2388
  var CLAUDE_RESUME_NOT_FOUND_RE = /No conversation found with session ID/i;
2384
2389
  var CLAUDE_UNKNOWN_EFFORT_RE = /unknown (?:option|flag)[^\n]*--effort/i;
2390
+ function sumTranscriptTokens(file) {
2391
+ try {
2392
+ const seen = /* @__PURE__ */ new Set();
2393
+ let total = 0;
2394
+ for (const line of fs9.readFileSync(file, "utf8").split(/\r?\n/)) {
2395
+ let entry;
2396
+ try {
2397
+ entry = JSON.parse(line);
2398
+ } catch {
2399
+ continue;
2400
+ }
2401
+ if (entry.type !== "assistant") continue;
2402
+ const message = entry.message;
2403
+ if (!message?.usage) continue;
2404
+ if (typeof message.id === "string") {
2405
+ if (seen.has(message.id)) continue;
2406
+ seen.add(message.id);
2407
+ }
2408
+ const usage = message.usage;
2409
+ for (const key of ["input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"]) {
2410
+ const value = usage[key];
2411
+ if (typeof value === "number" && Number.isFinite(value)) total += value;
2412
+ }
2413
+ }
2414
+ return total > 0 ? total : void 0;
2415
+ } catch {
2416
+ return void 0;
2417
+ }
2418
+ }
2385
2419
  var CLAUDE_TOO_OLD_HINT = "Claude Code is too old for canon \u2014 run `canon doctor` to verify (canon requires Claude Code 2.1.72+).";
2386
2420
  function printClaudeTooOldHint(capturedStderr) {
2387
2421
  if (CLAUDE_UNKNOWN_EFFORT_RE.test(capturedStderr)) {
@@ -2428,6 +2462,8 @@ async function runClaude(prompt, interactive, resumeId, model, effort, budget, m
2428
2462
  let tokens;
2429
2463
  let processedText = "";
2430
2464
  let sessionId = null;
2465
+ const subagentResults = [];
2466
+ const notificationFiles = /* @__PURE__ */ new Map();
2431
2467
  try {
2432
2468
  if (interactive) {
2433
2469
  console.log("");
@@ -2505,6 +2541,26 @@ ${renderedPrompt}`;
2505
2541
  captured.sessionId = event.session_id ?? null;
2506
2542
  captured.usage = event.usage ?? null;
2507
2543
  }
2544
+ if (event.type === "system" && event.subtype === "task_notification" && typeof event.tool_use_id === "string" && typeof event.output_file === "string") {
2545
+ notificationFiles.set(event.tool_use_id, event.output_file);
2546
+ }
2547
+ if (event.type === "user" && event.parent_tool_use_id == null) {
2548
+ const result2 = event.tool_use_result;
2549
+ if (result2 && typeof result2.agentType === "string" && typeof result2.totalDurationMs === "number" && Number.isFinite(result2.totalDurationMs)) {
2550
+ const message = event.message;
2551
+ const toolResult = message?.content?.find((block) => block.type === "tool_result" && typeof block.tool_use_id === "string");
2552
+ const toolUseId = toolResult && typeof toolResult.tool_use_id === "string" ? toolResult.tool_use_id : null;
2553
+ if (!toolUseId || !subagentResults.some((item) => item.toolUseId === toolUseId)) {
2554
+ subagentResults.push({
2555
+ toolUseId,
2556
+ agentType: result2.agentType,
2557
+ resolvedModel: typeof result2.resolvedModel === "string" ? result2.resolvedModel : null,
2558
+ durationMs: result2.totalDurationMs,
2559
+ ok: result2.status === "completed"
2560
+ });
2561
+ }
2562
+ }
2563
+ }
2508
2564
  };
2509
2565
  const result = await streamProcess("claude", args, {
2510
2566
  cwd,
@@ -2582,6 +2638,23 @@ ${renderedPrompt}`;
2582
2638
  throw err;
2583
2639
  } finally {
2584
2640
  if (metricsContext) recordMetric({ ...metricsContext, agent: "claude", model, durationMs: Date.now() - startMs, status, tokens });
2641
+ if (metricsContext) {
2642
+ try {
2643
+ for (const result of subagentResults) {
2644
+ const file = result.toolUseId ? notificationFiles.get(result.toolUseId) : void 0;
2645
+ recordMetric({
2646
+ ...metricsContext,
2647
+ agent: `claude:${result.agentType}`,
2648
+ model: result.resolvedModel ?? model,
2649
+ durationMs: result.durationMs,
2650
+ status: result.ok ? "ok" : "failed",
2651
+ tokens: file ? sumTranscriptTokens(file) : void 0
2652
+ });
2653
+ }
2654
+ } catch (error) {
2655
+ warn(`metrics: could not record Claude sub-agent rows: ${error instanceof Error ? error.message : String(error)}`);
2656
+ }
2657
+ }
2585
2658
  }
2586
2659
  }
2587
2660
 
@@ -2842,7 +2915,7 @@ function evaluateCodeReviewLoop(tasks, cap) {
2842
2915
 
2843
2916
  // src/orchestrator/validation.ts
2844
2917
  import { spawnSync as spawnSync4 } from "child_process";
2845
- import fs9 from "fs";
2918
+ import fs10 from "fs";
2846
2919
  import path8 from "path";
2847
2920
 
2848
2921
  // src/orchestrator/markdown-table.ts
@@ -3126,7 +3199,7 @@ function filterArtifactFindings(findings, artifactPaths) {
3126
3199
  return findings.filter((finding) => artifactSet.has(finding.file));
3127
3200
  }
3128
3201
  function runDocsRefsCheck(cwd, scriptPath) {
3129
- if (!fs9.existsSync(scriptPath)) return { kind: "absent" };
3202
+ if (!fs10.existsSync(scriptPath)) return { kind: "absent" };
3130
3203
  const result = spawnSync4("node", [scriptPath], {
3131
3204
  cwd,
3132
3205
  stdio: ["ignore", "pipe", "pipe"],
@@ -3186,7 +3259,7 @@ function normalizeCheckLabel(value) {
3186
3259
  }
3187
3260
  function parseValidationRequiredChecks(specPath) {
3188
3261
  try {
3189
- const content = fs9.readFileSync(specPath, "utf8");
3262
+ const content = fs10.readFileSync(specPath, "utf8");
3190
3263
  const section = content.match(/## Validation Required\n\n([\s\S]*?)(?:\n## |\n# |$)/);
3191
3264
  if (!section) return null;
3192
3265
  const checks = [];
@@ -3273,12 +3346,13 @@ function checkRerouteEvidence(phase, artifactContent, status) {
3273
3346
  }
3274
3347
  return { reroute: true, ok: true };
3275
3348
  }
3349
+ var FULL_SEND_SCOPE_AMENDMENT_HEADING = "## Amendment (full-send scope)";
3276
3350
  var HUMAN_AMENDMENT_HEADING_RE = /^#{2,6}[ \t]+Amendment\b(?![ \t]*\(full-send scope\))/im;
3277
3351
  function verifyRerouteAmendment(taskId, requiredRound) {
3278
3352
  const specPath = path8.join(taskDirFor(taskId), "spec.md");
3279
3353
  let content;
3280
3354
  try {
3281
- content = fs9.readFileSync(specPath, "utf8");
3355
+ content = fs10.readFileSync(specPath, "utf8");
3282
3356
  } catch {
3283
3357
  return { amended: false, reason: `spec.md missing at ${specPath}` };
3284
3358
  }
@@ -3453,7 +3527,7 @@ function classifyPreflightBlockers(taskId, changedFiles, bundleDiffIssues = [])
3453
3527
  const handoffPath = path8.join(taskDirFor(taskId), "handoff.md");
3454
3528
  const specPath = path8.join(taskDirFor(taskId), "spec.md");
3455
3529
  try {
3456
- const content = fs9.readFileSync(handoffPath, "utf8");
3530
+ const content = fs10.readFileSync(handoffPath, "utf8");
3457
3531
  const latestResults = computeLatestValidationResults(content);
3458
3532
  const requiredChecks = parseValidationRequiredChecks(specPath);
3459
3533
  const { malformed } = parseHandoffChangesRows(taskId);
@@ -3485,7 +3559,7 @@ function validateHandoffAgainstSpec(specPath, handoffPath, latestResults, change
3485
3559
  rowMap = latestResults;
3486
3560
  } else {
3487
3561
  try {
3488
- const content = fs9.readFileSync(handoffPath, "utf8");
3562
+ const content = fs10.readFileSync(handoffPath, "utf8");
3489
3563
  rowMap = computeLatestValidationResults(content);
3490
3564
  } catch {
3491
3565
  rowMap = /* @__PURE__ */ new Map();
@@ -3539,7 +3613,7 @@ function isTemplateUnfilled(content) {
3539
3613
  function isDoneMdTemplate(donePath) {
3540
3614
  let content;
3541
3615
  try {
3542
- content = fs9.readFileSync(donePath, "utf8");
3616
+ content = fs10.readFileSync(donePath, "utf8");
3543
3617
  } catch {
3544
3618
  return true;
3545
3619
  }
@@ -3548,7 +3622,7 @@ function isDoneMdTemplate(donePath) {
3548
3622
  function isPrBodyTemplate(prBodyPath) {
3549
3623
  let content;
3550
3624
  try {
3551
- content = fs9.readFileSync(prBodyPath, "utf8");
3625
+ content = fs10.readFileSync(prBodyPath, "utf8");
3552
3626
  } catch {
3553
3627
  return true;
3554
3628
  }
@@ -3594,7 +3668,7 @@ function checkPhaseGate(taskId, phase, verdict, taskDirOverride) {
3594
3668
  const artifactPath = path8.join(taskDir, config3.artifactName);
3595
3669
  let content;
3596
3670
  try {
3597
- content = fs9.readFileSync(artifactPath, "utf8");
3671
+ content = fs10.readFileSync(artifactPath, "utf8");
3598
3672
  } catch {
3599
3673
  return { ok: false, reason: `${config3.artifactName} is missing for phase '${phase}'` };
3600
3674
  }
@@ -3606,7 +3680,7 @@ function checkPhaseGate(taskId, phase, verdict, taskDirOverride) {
3606
3680
  if (phase === "spec_review" || phase === "plan") {
3607
3681
  let statusRaw;
3608
3682
  try {
3609
- statusRaw = fs9.readFileSync(path8.join(taskDir, "status.json"), "utf8");
3683
+ statusRaw = fs10.readFileSync(path8.join(taskDir, "status.json"), "utf8");
3610
3684
  } catch {
3611
3685
  return { ok: false, reason: `cannot determine reroute state for '${phase}': status.json in ${taskDir} is missing or unreadable` };
3612
3686
  }
@@ -3644,7 +3718,7 @@ function checkPhaseGate(taskId, phase, verdict, taskDirOverride) {
3644
3718
  const handoffPath = path8.join(taskDir, "handoff.md");
3645
3719
  let handoffContent;
3646
3720
  try {
3647
- handoffContent = fs9.readFileSync(handoffPath, "utf8");
3721
+ handoffContent = fs10.readFileSync(handoffPath, "utf8");
3648
3722
  } catch {
3649
3723
  return { ok: false, reason: `closing human_review requires a handoff.md \u2014 none found in ${taskDir}` };
3650
3724
  }
@@ -3653,7 +3727,7 @@ function checkPhaseGate(taskId, phase, verdict, taskDirOverride) {
3653
3727
  const donePath = path8.join(taskDir, "done.md");
3654
3728
  let doneContent = "";
3655
3729
  try {
3656
- doneContent = fs9.readFileSync(donePath, "utf8");
3730
+ doneContent = fs10.readFileSync(donePath, "utf8");
3657
3731
  } catch {
3658
3732
  }
3659
3733
  if (hasHumanPendingWaiver(doneContent)) return { ok: true };
@@ -3674,7 +3748,7 @@ function parseHandoffChangesRows(taskId) {
3674
3748
  const handoffPath = path8.join(taskDirFor(taskId), "handoff.md");
3675
3749
  let content;
3676
3750
  try {
3677
- content = fs9.readFileSync(handoffPath, "utf8");
3751
+ content = fs10.readFileSync(handoffPath, "utf8");
3678
3752
  } catch {
3679
3753
  return { files: [], malformed: [] };
3680
3754
  }
@@ -3701,7 +3775,7 @@ function parseAffectedFilesFromSpec(taskId) {
3701
3775
  const specPath = path8.join(taskDirFor(taskId), "spec.md");
3702
3776
  let content;
3703
3777
  try {
3704
- content = fs9.readFileSync(specPath, "utf8");
3778
+ content = fs10.readFileSync(specPath, "utf8");
3705
3779
  } catch {
3706
3780
  return { files: [], malformed: [] };
3707
3781
  }
@@ -3972,6 +4046,7 @@ function verifyHandoffAgainstDiffFromData(taskIds, inputs) {
3972
4046
  const files = handoffFilesByTask.get(taskId) ?? [];
3973
4047
  for (const filePath of files) {
3974
4048
  if (gitIgnored.has(filePath)) continue;
4049
+ if (isPipelineOwnedTaskArtifact(filePath, [taskId])) continue;
3975
4050
  if (!coveredPaths.has(filePath)) {
3976
4051
  issues.push(`[${taskId}] handoff\u2192diff: ${filePath} listed in handoff but not in diff \u2014 it has no committed change against the task base. If it was untouched or rewritten with identical content, drop the row`);
3977
4052
  }
@@ -4094,7 +4169,7 @@ function verifyHandoffAgainstDiff(taskIds, baseRef) {
4094
4169
  for (const taskId of taskIds) {
4095
4170
  let content;
4096
4171
  try {
4097
- content = fs9.readFileSync(path8.join(taskDirFor(taskId), "handoff.md"), "utf8");
4172
+ content = fs10.readFileSync(path8.join(taskDirFor(taskId), "handoff.md"), "utf8");
4098
4173
  } catch {
4099
4174
  continue;
4100
4175
  }
@@ -4144,20 +4219,20 @@ function verifyBaseDrift(taskIds, baseBranch, cwd) {
4144
4219
  conflict: probeMergeConflicts("HEAD", `origin/${baseBranch}`, cwd)
4145
4220
  };
4146
4221
  }
4147
- function verifyBaseDivergenceFromData(commits) {
4222
+ function verifyBaseDivergenceFromData(commits, baseBranch) {
4148
4223
  if (commits.length === 0) return "";
4149
4224
  const noun = commits.length === 1 ? "commit" : "commits";
4150
4225
  return [
4151
- `Base divergence detected: ${commits.length} colliding ${noun} on <base> not yet on origin/<base>; they will collide when <base> is pulled:`,
4226
+ `Base divergence detected: ${commits.length} colliding ${noun} on ${baseBranch} not yet on origin/${baseBranch}; they will collide when ${baseBranch} is pulled:`,
4152
4227
  ...commits.map((commit) => ` ${commit.sha.slice(0, 7)} ${commit.subject}`),
4153
- "Fix: git push origin <base>",
4228
+ `Fix: git push origin ${shellQuoteArg(baseBranch)}`,
4154
4229
  "Override: rerun with --allow-divergent-base to skip this commit-divergence check only."
4155
4230
  ].join("\n");
4156
4231
  }
4157
4232
  function verifyBaseDivergence(baseBranch, cwd) {
4158
4233
  const fetchResult = gitSafeAt(cwd, "fetch", "origin", baseBranch);
4159
4234
  if (!fetchResult.ok) {
4160
- if (!fs9.existsSync(cwd)) {
4235
+ if (!fs10.existsSync(cwd)) {
4161
4236
  return { commits: [], ok: false, stderr: fetchResult.stderr, fetchFailed: false };
4162
4237
  }
4163
4238
  warn(
@@ -4241,11 +4316,11 @@ function buildSharedDocAbortMessage(abortedFiles) {
4241
4316
  }
4242
4317
 
4243
4318
  // src/orchestrator/prompts/index.ts
4244
- import fs13 from "fs";
4319
+ import fs14 from "fs";
4245
4320
  import path12 from "path";
4246
4321
 
4247
4322
  // src/orchestrator/context.ts
4248
- import fs10 from "fs";
4323
+ import fs11 from "fs";
4249
4324
  import path9 from "path";
4250
4325
  function extractAffectedFiles(taskId) {
4251
4326
  try {
@@ -4259,7 +4334,7 @@ function isSafeRepoPath(file) {
4259
4334
  const resolved = path9.resolve(REPO_ROOT, file);
4260
4335
  if (!resolved.startsWith(REPO_ROOT + path9.sep)) return false;
4261
4336
  try {
4262
- const real = fs10.realpathSync(resolved);
4337
+ const real = fs11.realpathSync(resolved);
4263
4338
  if (!real.startsWith(REPO_ROOT + path9.sep)) return false;
4264
4339
  } catch {
4265
4340
  }
@@ -4273,7 +4348,7 @@ function buildContextBlock(taskIds) {
4273
4348
  if (!isSafeRepoPath(file)) continue;
4274
4349
  const filePath = path9.join(REPO_ROOT, file);
4275
4350
  try {
4276
- allFiles.set(file, fs10.readFileSync(filePath, "utf8"));
4351
+ allFiles.set(file, fs11.readFileSync(filePath, "utf8"));
4277
4352
  } catch {
4278
4353
  }
4279
4354
  }
@@ -4304,7 +4379,7 @@ ${content}
4304
4379
  function buildKnownPitfalls(taskIds) {
4305
4380
  const patternsPath = process.env.CANON_PATTERNS_MD_PATH ?? path9.join(getActiveCwd(taskIds), "docs/patterns.md");
4306
4381
  try {
4307
- const content = fs10.readFileSync(patternsPath, "utf8");
4382
+ const content = fs11.readFileSync(patternsPath, "utf8");
4308
4383
  const match = content.match(/## Known Pitfalls\n\n([\s\S]*?)(?:\n## |\n---|\n# |$)/);
4309
4384
  if (!match) return "";
4310
4385
  return `
@@ -4321,7 +4396,7 @@ function buildKnownRisks(taskIds) {
4321
4396
  const riskBlocks = taskIds.map((taskId) => {
4322
4397
  const specPath = path9.join(taskDirFor(taskId), "spec.md");
4323
4398
  try {
4324
- const content = fs10.readFileSync(specPath, "utf8");
4399
+ const content = fs11.readFileSync(specPath, "utf8");
4325
4400
  const match = content.match(/## Known Risks\n\n([\s\S]*?)(?:\n## |\n# |$)/);
4326
4401
  if (!match) return "";
4327
4402
  const risks = match[1].trim();
@@ -4348,7 +4423,7 @@ function summarizePreloadStatus(taskIds) {
4348
4423
  if (!isSafeRepoPath(file)) continue;
4349
4424
  const filePath = path9.join(REPO_ROOT, file);
4350
4425
  try {
4351
- files.set(file, fs10.statSync(filePath).size);
4426
+ files.set(file, fs11.statSync(filePath).size);
4352
4427
  } catch {
4353
4428
  files.set(file, 0);
4354
4429
  }
@@ -4365,7 +4440,7 @@ function summarizePreloadStatus(taskIds) {
4365
4440
  function extractValidationChecks(taskId) {
4366
4441
  const specPath = path9.join(taskDirFor(taskId), "spec.md");
4367
4442
  try {
4368
- const content = fs10.readFileSync(specPath, "utf8");
4443
+ const content = fs11.readFileSync(specPath, "utf8");
4369
4444
  const section = content.match(/## Validation Required\n\n([\s\S]*?)(?:\n## |\n# |$)/);
4370
4445
  if (!section) return [];
4371
4446
  const checks = [];
@@ -4381,7 +4456,7 @@ function extractValidationChecks(taskId) {
4381
4456
  function extractAcSummary(taskId) {
4382
4457
  const specPath = path9.join(taskDirFor(taskId), "spec.md");
4383
4458
  try {
4384
- const content = fs10.readFileSync(specPath, "utf8");
4459
+ const content = fs11.readFileSync(specPath, "utf8");
4385
4460
  const lines = [];
4386
4461
  for (const line of content.split("\n")) {
4387
4462
  const match = line.match(/^-\s+\[[ x]\]\s+(AC-[\w.-]+):\s+(.+)$/);
@@ -4471,11 +4546,11 @@ ${acSection}`;
4471
4546
  }
4472
4547
 
4473
4548
  // src/orchestrator/review-archive.ts
4474
- import fs12 from "fs";
4549
+ import fs13 from "fs";
4475
4550
  import path11 from "path";
4476
4551
 
4477
4552
  // src/task/templates.ts
4478
- import fs11 from "fs";
4553
+ import fs12 from "fs";
4479
4554
  import path10 from "path";
4480
4555
  function tasksRoot() {
4481
4556
  return process.env.CANON_TASKS_DIR_OVERRIDE ?? "tasks";
@@ -4488,17 +4563,17 @@ function taskTemplateOverrideRoot() {
4488
4563
  }
4489
4564
  function resolveTaskTemplateSource(basename) {
4490
4565
  const override = path10.join(taskTemplateOverrideRoot(), basename);
4491
- if (fs11.existsSync(override)) return override;
4566
+ if (fs12.existsSync(override)) return override;
4492
4567
  const managed = path10.join(templatesRoot(), basename);
4493
- return fs11.existsSync(managed) ? managed : null;
4568
+ return fs12.existsSync(managed) ? managed : null;
4494
4569
  }
4495
4570
  function renderTaskTemplate(source, taskId, title) {
4496
- return fs11.readFileSync(source, "utf8").replaceAll("[TASK-ID]", taskId).replaceAll("[Title]", title);
4571
+ return fs12.readFileSync(source, "utf8").replaceAll("[TASK-ID]", taskId).replaceAll("[Title]", title);
4497
4572
  }
4498
4573
  function scaffoldTaskArtifact(taskDir, basename, taskId, title) {
4499
4574
  const source = resolveTaskTemplateSource(basename);
4500
4575
  if (!source) return null;
4501
- fs11.writeFileSync(path10.join(taskDir, basename), renderTaskTemplate(source, taskId, title), "utf8");
4576
+ fs12.writeFileSync(path10.join(taskDir, basename), renderTaskTemplate(source, taskId, title), "utf8");
4502
4577
  return source;
4503
4578
  }
4504
4579
  function isPristineTaskArtifact(content, basename, taskId, title) {
@@ -4518,13 +4593,13 @@ var COLD_CODEX_ARCHIVE_PREFIX = "review-cold-codex-run-";
4518
4593
  var COLD_CODEX_ARCHIVE_RE = /^review-cold-codex-run-(\d+)\.md$/;
4519
4594
  function writeColdCodexArchive(taskDir, header, findings) {
4520
4595
  let newest = 0;
4521
- for (const name2 of fs12.readdirSync(taskDir)) {
4596
+ for (const name2 of fs13.readdirSync(taskDir)) {
4522
4597
  const match = COLD_CODEX_ARCHIVE_RE.exec(name2);
4523
4598
  if (match) newest = Math.max(newest, Number(match[1]));
4524
4599
  }
4525
4600
  const name = `${COLD_CODEX_ARCHIVE_PREFIX}${newest + 1}.md`;
4526
4601
  const reason = header.reason.replaceAll('"', "'");
4527
- fs12.writeFileSync(
4602
+ fs13.writeFileSync(
4528
4603
  path11.join(taskDir, name),
4529
4604
  `<!-- round=${header.round} reviewed_sha=${header.reviewedSha} scope=${header.scope} base=${header.base} reason="${reason}" -->
4530
4605
 
@@ -4547,7 +4622,7 @@ function parseColdCodexArchiveHeader(content) {
4547
4622
  function findColdCodexArchiveForRound(taskDir, round) {
4548
4623
  let names;
4549
4624
  try {
4550
- names = fs12.readdirSync(taskDir);
4625
+ names = fs13.readdirSync(taskDir);
4551
4626
  } catch {
4552
4627
  return null;
4553
4628
  }
@@ -4558,7 +4633,7 @@ function findColdCodexArchiveForRound(taskDir, round) {
4558
4633
  for (const { name } of numbered) {
4559
4634
  let content;
4560
4635
  try {
4561
- content = fs12.readFileSync(path11.join(taskDir, name), "utf8");
4636
+ content = fs13.readFileSync(path11.join(taskDir, name), "utf8");
4562
4637
  } catch {
4563
4638
  continue;
4564
4639
  }
@@ -4570,14 +4645,14 @@ function findColdCodexArchiveForRound(taskDir, round) {
4570
4645
  function hasMalformedColdCodexArchive(taskDir) {
4571
4646
  let names;
4572
4647
  try {
4573
- names = fs12.readdirSync(taskDir);
4648
+ names = fs13.readdirSync(taskDir);
4574
4649
  } catch {
4575
4650
  return false;
4576
4651
  }
4577
4652
  return names.some((name) => {
4578
4653
  if (!COLD_CODEX_ARCHIVE_RE.test(name)) return false;
4579
4654
  try {
4580
- return parseColdCodexArchiveHeader(fs12.readFileSync(path11.join(taskDir, name), "utf8")) === null;
4655
+ return parseColdCodexArchiveHeader(fs13.readFileSync(path11.join(taskDir, name), "utf8")) === null;
4581
4656
  } catch {
4582
4657
  return true;
4583
4658
  }
@@ -4586,7 +4661,7 @@ function hasMalformedColdCodexArchive(taskDir) {
4586
4661
  var REVIEW_ARCHIVE_RE = new RegExp(`^${REVIEW_ARCHIVE_PREFIX}(\\d+)\\.md$`);
4587
4662
  function newestReviewArchiveNumber(taskDir) {
4588
4663
  let newest = 0;
4589
- for (const name of fs12.readdirSync(taskDir)) {
4664
+ for (const name of fs13.readdirSync(taskDir)) {
4590
4665
  const match = REVIEW_ARCHIVE_RE.exec(name);
4591
4666
  if (match) newest = Math.max(newest, Number(match[1]));
4592
4667
  }
@@ -4598,21 +4673,21 @@ function findNewestReviewArchive(taskDir) {
4598
4673
  }
4599
4674
  function archivePriorReview(taskDir, options = {}) {
4600
4675
  const reviewPath = path11.join(taskDir, "review.md");
4601
- if (!fs12.existsSync(reviewPath)) return null;
4676
+ if (!fs13.existsSync(reviewPath)) return null;
4602
4677
  if (options.skipUnfilledTemplate) {
4603
- const content = fs12.readFileSync(reviewPath, "utf8");
4678
+ const content = fs13.readFileSync(reviewPath, "utf8");
4604
4679
  if (isTemplateUnfilled(content)) return null;
4605
4680
  if (options.scaffold && isPristineTaskArtifact(content, "review.md", options.scaffold.taskId, options.scaffold.title)) {
4606
4681
  return null;
4607
4682
  }
4608
4683
  }
4609
4684
  const archiveName = `${REVIEW_ARCHIVE_PREFIX}${newestReviewArchiveNumber(taskDir) + 1}.md`;
4610
- fs12.renameSync(reviewPath, path11.join(taskDir, archiveName));
4685
+ fs13.renameSync(reviewPath, path11.join(taskDir, archiveName));
4611
4686
  return archiveName;
4612
4687
  }
4613
4688
  function rescaffoldReview(taskDir, identity) {
4614
4689
  try {
4615
- if (fs12.existsSync(path11.join(taskDir, "review.md"))) return { outcome: "exists" };
4690
+ if (fs13.existsSync(path11.join(taskDir, "review.md"))) return { outcome: "exists" };
4616
4691
  const source = scaffoldTaskArtifact(taskDir, "review.md", identity.taskId, identity.title);
4617
4692
  return source ? { outcome: "written", source } : { outcome: "no-template" };
4618
4693
  } catch (error) {
@@ -5086,16 +5161,16 @@ function renderTemplate(template, view) {
5086
5161
  }
5087
5162
 
5088
5163
  // src/orchestrator/prompts/templates/code-review-foreman.md
5089
- var code_review_foreman_default = "You are the synthesis foreman for the code review phase for {{taskScope}} for {{projectName}}.\n\n{{{startup}}}\n\n## Code-Review Rules of Thumb (Foreman)\n\n- **Reviewer diffs against the task baseline, not `main`, on release branches**: on a shared release branch ahead of `main`, always diff against the task's baseline \u2014 diffing against `main` attributes unrelated work to the task.\n- **Use `git -C <absolute-path>` for every worktree git op, not `cd` + git**: when operating across REPO_ROOT and a task worktree, `git -C /absolute/path` avoids silent cwd reversion between tool calls.\n- **Don't infer one git invariant from another**: `git status --porcelain` empty \u2260 origin matches HEAD; `origin/<branch>` exists \u2260 origin matches HEAD; PR exists \u2260 PR is in the expected state. Do the actual check directly.\n- **A cross-cutting invariant belongs in one shared helper, not patched per call site**: when the same rule must hold at multiple enforcement points, implement it once. The tell: findings come back round after round as the same bug class at a new location. At \u22653 sites, extract the shared helper and route all sites through it.\n\nYour job is to synthesize three review inputs: the anchored Claude lens, the cold-Claude lens, and the pre-obtained cold-Codex findings injected below. You spawn the Claude lenses as isolated sub-agents, collect their findings, adjudicate all three inputs using the spec (which you hold and the cold lenses do not), then write one `review.md` and set the verdict. Do not run `codex` yourself.\n\nTasks:\n{{{taskLines}}}\n\n{{#isRound1}}\nThis is Round 1, the initial code review.\n{{/isRound1}}\n{{^isRound1}}\nThis is Round {{roundN}}: re-review after iteration {{priorIteration}}. All three lenses run again this round. Direct the anchored lens to read the Iteration {{priorIteration}} section of `handoff.md` that addresses review round {{priorIteration}}.\n{{#tightenLine}}\n{{{tightenLine}}}\n{{/tightenLine}}\n{{/isRound1}}\n\n**Scope:** {{{scopeWord}}} \u2014 base `{{{scopeBase}}}` \u2014 reason: {{{scopeReason}}}\n\n{{#hasDiff}}\nTask diff against {{{baseBranch}}}:\n\n```diff\n{{{diffContent}}}\n```\n{{#diffTruncated}}\n> Diff truncated at 50 000 bytes. Give the Claude lenses the visible diff first; for the omitted remainder, direct them to inspect only the changed files named in the handoff Changes table. Do not give the cold-Claude lens spec, AC, or canon-doc context.\n{{/diffTruncated}}\n{{/hasDiff}}\n{{^hasDiff}}\nRetrieve the task diff with `git diff {{{baseBranch}}}...HEAD`.\n{{/hasDiff}}\n{{#isDeltaScope}}\n\n{{#hasDeltaDiff}}\nDelta diff (`{{{deltaBase}}}..HEAD`) \u2014 give this delta to the cold-Claude lens:\n\n```diff\n{{{deltaDiffContent}}}\n```\n{{#deltaDiffTruncated}}\n> Delta diff truncated at 50 000 bytes. Give the cold-Claude lens the visible delta first; for the remainder, direct it to `git diff {{{deltaBase}}}..HEAD`.\n{{/deltaDiffTruncated}}\n{{/hasDeltaDiff}}\n{{^hasDeltaDiff}}\nThe delta diff could not be injected. Retrieve it with `git diff {{{deltaBase}}}..HEAD` and give it to the cold-Claude lens before it reviews.\n{{/hasDeltaDiff}}\n{{/isDeltaScope}}\n\n## Injected Cold-Codex Findings\n\n{{#hasColdCodexFindings}}\nThe orchestrator ran `codex review` before spawning you. Its findings are reproduced below. These are unanchored: Codex reviewed adversarially without the spec as a checklist. Treat them as the third lens input. Do not re-run Codex; synthesize these findings alongside the Claude lens outputs.\n{{#isDeltaScope}}\nFor this round, cold-Codex reviewed only `{{{deltaBase}}}..HEAD`.\n{{/isDeltaScope}}\n{{^isDeltaScope}}\nFor this round, cold-Codex reviewed the full task diff against `{{{baseBranch}}}`.\n{{/isDeltaScope}}\n\n{{{coldCodexFindings}}}\n{{/hasColdCodexFindings}}\n{{^hasColdCodexFindings}}\nNo cold-Codex findings were provided to this prompt. In production code_review, the orchestrator must obtain that artifact before foreman synthesis; do not treat a missing cold-Codex lens as approval evidence.\n{{/hasColdCodexFindings}}\n\n{{#hasOutOfScopeFiles}}\n## Full-Send Scope Judgment\n\nThe task changed these files outside the spec's `### Affected Files` table:\n\n{{{outOfScopeFilesList}}}\n\nJudge each file against the owning task's ACs and record its outcome and reason in `review.md`:\n\n1. **Appropriate scope expansion:** If needed to meet the ACs and consistent with the spec's intent, append an `## Amendment (full-send scope)` section to the owning task's `spec.md` (use exactly that heading; a bare `## Amendment` is reserved for human reroute amendments). Include an exact `### Affected Files` heading and table row naming the file, plus a one-line reason that calls it a full-send scope expansion.\n2. **Spec miss:** If the spec should have listed the file, append the same `## Amendment (full-send scope)` section and exact `### Affected Files` table row, with a one-line reason that calls it a spec miss.\n3. **Should not have been changed:** Do not amend the spec. Write a finding requiring the file to be reverted or removed, and set the verdict to `changes_requested`.\n\nFor a bundle, amend the member spec whose ACs the file serves. The orchestrator checks after code review completes: every listed file must be in a member's Affected Files or a `changes_requested` verdict must route it back to implement. The legacy `needs_re_review` verdict routes the same way. A `spec_gap` verdict blocks for human triage and names any files still outside Affected Files; blessing that verdict does not amend the spec. An approved review with unjudged files auto-blocks.\n\n{{/hasOutOfScopeFiles}}\n## Foreman Protocol\n\n### 1. Spawn Claude Lenses In Parallel\n\nSpawn both Claude lenses with the sub-agent tool (`Agent`, called `Task` in older harnesses) in a single message so they run concurrently, and run them **in the foreground** (`run_in_background: false`) so the call returns their findings. Do not spawn them in the background and do not end your turn to wait for them: a turn that ends while a lens is still running ends the code review with no `review.md` and no verdict, and the phase is retried from scratch. Your turn ends only after step 5 below has run.\n\n**Anchored lens** (`subagent_type: code-review-anchored`)\n{{#isDeltaScope}}\n- Retrieve the full task diff with `git diff {{{baseBranch}}}...HEAD` and give it that full diff, not the delta, plus `spec.md`, `handoff.md`, and prior `review.md`.\n{{/isDeltaScope}}\n{{^isDeltaScope}}\n- Give it the full diff, `spec.md`, `handoff.md`, and prior `review.md` if this is a re-review.\n{{/isDeltaScope}}\n- It applies canon's anchored Stage 1 / Stage 2 code-review charter.\n- It returns structured findings to you. It must not write `review.md` or run `canon task phase`.\n\n**Cold-Claude lens** (`subagent_type: code-review-cold`)\n{{#isDeltaScope}}\n- This round is delta-scoped. Give it the delta (`{{{deltaBase}}}..HEAD`) and the delta base ref only.\n{{/isDeltaScope}}\n{{^isDeltaScope}}\n- Give it the full diff and base ref only.\n{{/isDeltaScope}}\n- Do not give it `spec.md`, ACs, handoff rationale, canon docs, known risks, or your anchored-lens prompt.\n- If it needs to inspect files for truncated diff context, constrain it to changed files only and preserve the spec-blind framing.\n- Separately, its sibling-site sweep may search other code files for guards, checks, and invariants that need the same treatment. Keep the search spec-blind.\n- It returns structured findings to you. It must not write `review.md` or run `canon task phase`.\n\nThe injected cold-Codex findings above are the third lens input. Do not spawn a Codex agent or shell out to Codex yourself. Do not let a Claude lens see another lens's output.\n\nSpawn exactly the two Claude lenses above each round, plus at most one re-spawn of a lens whose return is missing. Spawn no other reviewers or review agents, run no review skills, and never substitute your own review for a lens's return.\n\nA lens return is valid when it follows that lens's charter return format. This includes a clean empty form (`STAGE_2_FINDINGS: (none)` or `COLD_FINDINGS: (none)`) and the anchored Stage 1 fail form (`STAGE_1: fail`, no Stage 2 findings, `OVERALL_SIGNAL: changes_requested`). A return is missing if absent or outside the charter format. Re-spawn a missing lens once with the same inputs. If still missing, do not approve or guess at its findings: it is not approval evidence. Write `review.md` recording which lens was missing and what came back, check no verdict box, then run the `code_review blocked` commands in step 5 for every task. Other lenses' findings may be recorded but not adjudicated into a verdict.\n\n### 2. Adjudicate\n\nUse the three lens inputs and the spec. Do not perform a new full diff review for novel bugs; your role is synthesis and adjudication.\n\nThe lenses are instructed to over-report \u2014 to surface low-confidence and low-severity findings rather than self-censor. Filtering is **your** job, not theirs. A clean return in the charter's empty form is a valid result; only a missing return (step 1) is a lens failure. Rank surviving findings by confidence \xD7 severity. A low-confidence, low-severity finding is a nit or gets dismissed; it does not by itself drive `changes_requested`. Do not discard a finding merely because a lens marked it low-confidence \u2014 verify it against the spec/diff first, then rank.\n\n1. Dedup: if 2+ lenses flagged the same behavior, collapse it to one finding and record \"flagged by N lenses.\" A finding flagged by 2+ lenses is higher-confidence regardless of any lens's self-tag. Cross-model agreement \u2014 the same behavior flagged by cold-Claude and cold-Codex \u2014 must not be dismissed as spec-intended without explicit spec evidence cited in `review.md`.\n2. Keep the two reconciliation checks separate:\n - Does it hold against the code? For cold findings (cold-Claude and cold-Codex), verify each against the diff/code. Codex P-levels are claims to check, not verdicts. A finding that does not hold gets recorded as `Dismissed (cold-Claude): <finding> - <reason>` or `Dismissed (cold-Codex): <finding> - <reason>`.\n - Is it in spec scope? Apply this only to anchored-lens findings as part of the Stage 1 / Stage 2 charter.\n - Forbidden: do not dismiss a verified cold-Claude or cold-Codex finding merely for being off-AC or out of spec scope. A real bug caught by a cold lens is still a bug even if no AC named it.\n3. Altitude classification: every surviving finding is either:\n - `code-bug`: the implementation is wrong or test integrity is compromised.\n - `spec-gap`: the implementation may match the written spec, but the spec is missing, wrong, or too ambiguous for the implementer to fix.\n\n### 3. Choose Verdict\n\n- Any `code-bug` finding -> `changes_requested`.\n- Any `spec-gap` finding and no code-bugs -> `spec_gap`.\n- Optional nits or cleanup without blocking findings -> `approved_with_nits`.\n- No surviving findings -> `approved`.\n\nTest-integrity findings are always code-bugs.\n\n### 4. Write `review.md`\n\nWhen you cite a section of a Markdown doc with the quoted form `\xA7\"\u2026\"`, the quoted text must be an exact heading in that file. To point at a bold-lead paragraph or anything that is not a heading, use `file:line` or the unquoted `\xA7Name` form instead.\n\nFor each task, write `tasks/<id>/review.md`.\n\nRound 1 fills the existing template structure directly \u2014 do **not** wrap it in a `## Round 1` section; the `## Stage 1` and `## Stage 2` headings stay at H2. Re-review appends a new `## Round {{roundN}}` section near the bottom (with `### Stage 1` / `### Stage 2` sub-headings), preserving earlier rounds.\n\nEvery round \u2014 the Round 1 body and each `## Round N` section \u2014 includes one scope line near the top: **Scope:** {{{scopeWord}}} \u2014 base `{{{scopeBase}}}` \u2014 reason: {{{scopeReason}}}. The numbered cold-Codex archive header is the machine-readable record.\n\nInclude:\n- Stage 1: anchored lens validation gate result and AC table.\n- Stage 2 / Findings: surviving findings with altitude (`code-bug` or `spec-gap`), source lens, and file:line.\n- Dismissed Cold Findings: every dropped cold finding plus the reason, including `Dismissed (cold-Claude): ...` and `Dismissed (cold-Codex): ...` entries where applicable.\n- Final Verdict: check exactly one verdict checkbox, including `Spec gap` when applicable (except the missing-lens stop in step 1, which checks none).\n\n### 5. Set Phase Verdict\n\nRun one command per task with the actual verdict:\n{{{phaseCommands}}}\n\nIf a lens was still missing after its re-spawn (step 1), write `review.md` first, then run these instead, with no verdict \u2014 this stops the run for the human:\n{{{blockedCommands}}}\n";
5164
+ var code_review_foreman_default = "You are the synthesis foreman for the code review phase for {{taskScope}} for {{projectName}}.\n\n{{{startup}}}\n\n## Code-Review Rules of Thumb (Foreman)\n\n- **Reviewer diffs against the task baseline, not `main`, on release branches**: on a shared release branch ahead of `main`, always diff against the task's baseline \u2014 diffing against `main` attributes unrelated work to the task.\n- **Use `git -C <absolute-path>` for every worktree git op, not `cd` + git**: when operating across REPO_ROOT and a task worktree, `git -C /absolute/path` avoids silent cwd reversion between tool calls.\n- **Don't infer one git invariant from another**: `git status --porcelain` empty \u2260 origin matches HEAD; `origin/<branch>` exists \u2260 origin matches HEAD; PR exists \u2260 PR is in the expected state. Do the actual check directly.\n- **A cross-cutting invariant belongs in one shared helper, not patched per call site**: when the same rule must hold at multiple enforcement points, implement it once. The tell: findings come back round after round as the same bug class at a new location. At \u22653 sites, extract the shared helper and route all sites through it.\n\nYour job is to synthesize three review inputs: the anchored Claude lens, the cold-Claude lens, and the pre-obtained cold-Codex findings injected below. You spawn the Claude lenses as isolated sub-agents, collect their findings, adjudicate all three inputs using the spec (which you hold and the cold lenses do not), then write one `review.md` and set the verdict. Do not run `codex` yourself.\n\nTasks:\n{{{taskLines}}}\n\n{{#isRound1}}\nThis is Round 1, the initial code review.\n{{/isRound1}}\n{{^isRound1}}\nThis is Round {{roundN}}: re-review after iteration {{priorIteration}}. All three lenses run again this round. Direct the anchored lens to read the Iteration {{priorIteration}} section of `handoff.md` that addresses review round {{priorIteration}}. Also tell the anchored lens that red-first evidence is read across the whole handoff (baseline section and every Iteration subsection), not only that Iteration section.\n{{#tightenLine}}\n{{{tightenLine}}}\n{{/tightenLine}}\n{{/isRound1}}\n\n**Scope:** {{{scopeWord}}} \u2014 base `{{{scopeBase}}}` \u2014 reason: {{{scopeReason}}}\n\n{{#hasDiff}}\nTask diff against {{{baseBranch}}}:\n\n```diff\n{{{diffContent}}}\n```\n{{#diffTruncated}}\n> Diff truncated at 50 000 bytes. Give the Claude lenses the visible diff first; for the omitted remainder, direct them to inspect only the changed files named in the handoff Changes table. Do not give the cold-Claude lens spec, AC, or canon-doc context.\n{{/diffTruncated}}\n{{/hasDiff}}\n{{^hasDiff}}\nRetrieve the task diff with `git diff {{{baseBranch}}}...HEAD`.\n{{/hasDiff}}\n{{#isDeltaScope}}\n\n{{#hasDeltaDiff}}\nDelta diff (`{{{deltaBase}}}..HEAD`) \u2014 give this delta to the cold-Claude lens:\n\n```diff\n{{{deltaDiffContent}}}\n```\n{{#deltaDiffTruncated}}\n> Delta diff truncated at 50 000 bytes. Give the cold-Claude lens the visible delta first; for the remainder, direct it to `git diff {{{deltaBase}}}..HEAD`.\n{{/deltaDiffTruncated}}\n{{/hasDeltaDiff}}\n{{^hasDeltaDiff}}\nThe delta diff could not be injected. Retrieve it with `git diff {{{deltaBase}}}..HEAD` and give it to the cold-Claude lens before it reviews.\n{{/hasDeltaDiff}}\n{{/isDeltaScope}}\n\n## Injected Cold-Codex Findings\n\n{{#hasColdCodexFindings}}\nThe orchestrator ran `codex review` before spawning you. Its findings are reproduced below. These are unanchored: Codex reviewed adversarially without the spec as a checklist. Treat them as the third lens input. Do not re-run Codex; synthesize these findings alongside the Claude lens outputs.\n{{#isDeltaScope}}\nFor this round, cold-Codex reviewed only `{{{deltaBase}}}..HEAD`.\n{{/isDeltaScope}}\n{{^isDeltaScope}}\nFor this round, cold-Codex reviewed the full task diff against `{{{baseBranch}}}`.\n{{/isDeltaScope}}\n\n{{{coldCodexFindings}}}\n{{/hasColdCodexFindings}}\n{{^hasColdCodexFindings}}\nNo cold-Codex findings were provided to this prompt. In production code_review, the orchestrator must obtain that artifact before foreman synthesis; do not treat a missing cold-Codex lens as approval evidence.\n{{/hasColdCodexFindings}}\n\n{{#hasOutOfScopeFiles}}\n## Full-Send Scope Judgment\n\nThe task changed these files outside the spec's `### Affected Files` table:\n\n{{{outOfScopeFilesList}}}\n\nJudge each file against the owning task's ACs and record its outcome and reason in `review.md`:\n\n1. **Appropriate scope expansion:** If needed to meet the ACs and consistent with the spec's intent, append an `## Amendment (full-send scope)` section to the owning task's `spec.md` (use exactly that heading; a bare `## Amendment` is reserved for human reroute amendments). Include an exact `### Affected Files` heading and table row naming the file, plus a one-line reason that calls it a full-send scope expansion.\n2. **Spec miss:** If the spec should have listed the file, append the same `## Amendment (full-send scope)` section and exact `### Affected Files` table row, with a one-line reason that calls it a spec miss.\n3. **Should not have been changed:** Do not amend the spec. Write a finding requiring the file to be reverted or removed, and set the verdict to `changes_requested`.\n\nFor a bundle, amend the member spec whose ACs the file serves. The orchestrator checks after code review completes: every listed file must be in a member's Affected Files or a `changes_requested` verdict must route it back to implement. The legacy `needs_re_review` verdict routes the same way. A `spec_gap` verdict blocks for human triage and names any files still outside Affected Files; blessing that verdict does not amend the spec. An approved review with unjudged files auto-blocks.\n\n{{/hasOutOfScopeFiles}}\n## Foreman Protocol\n\n### 1. Spawn Claude Lenses In Parallel\n\nSpawn both Claude lenses with the sub-agent tool (`Agent`, called `Task` in older harnesses) in a single message so they run concurrently, and run them **in the foreground** (`run_in_background: false`) so the call returns their findings. Do not spawn them in the background and do not end your turn to wait for them: a turn that ends while a lens is still running ends the code review with no `review.md` and no verdict, and the phase is retried from scratch. Your turn ends only after step 5 below has run.\n\n**Anchored lens** (`subagent_type: code-review-anchored`)\n{{#isDeltaScope}}\n- Retrieve the full task diff with `git diff {{{baseBranch}}}...HEAD` and give it that full diff, not the delta, plus `spec.md`, `handoff.md`, and prior `review.md`.\n{{/isDeltaScope}}\n{{^isDeltaScope}}\n- Give it the full diff, `spec.md`, `handoff.md`, and prior `review.md` if this is a re-review.\n{{/isDeltaScope}}\n- It applies canon's anchored Stage 1 / Stage 2 code-review charter.\n- It returns structured findings to you. It must not write `review.md` or run `canon task phase`.\n\n**Cold-Claude lens** (`subagent_type: code-review-cold`)\n{{#isDeltaScope}}\n- This round is delta-scoped. Give it the delta (`{{{deltaBase}}}..HEAD`) and the delta base ref only.\n{{/isDeltaScope}}\n{{^isDeltaScope}}\n- Give it the full diff and base ref only.\n{{/isDeltaScope}}\n- Do not give it `spec.md`, ACs, handoff rationale, canon docs, known risks, or your anchored-lens prompt.\n- If it needs to inspect files for truncated diff context, constrain it to changed files only and preserve the spec-blind framing.\n- Separately, its sibling-site sweep may search other code files for guards, checks, and invariants that need the same treatment. Keep the search spec-blind.\n- It returns structured findings to you. It must not write `review.md` or run `canon task phase`.\n\nThe injected cold-Codex findings above are the third lens input. Do not spawn a Codex agent or shell out to Codex yourself. Do not let a Claude lens see another lens's output.\n\nSpawn exactly the two Claude lenses above each round, plus at most one re-spawn of a lens whose return is missing. Spawn no other reviewers or review agents, run no review skills, and never substitute your own review for a lens's return.\n\nA lens return is valid when it follows that lens's charter return format. This includes a clean empty form (`STAGE_2_FINDINGS: (none)` or `COLD_FINDINGS: (none)`) and the anchored Stage 1 fail form (`STAGE_1: fail`, no Stage 2 findings, `OVERALL_SIGNAL: changes_requested`). A return is missing if absent or outside the charter format. Re-spawn a missing lens once with the same inputs. If still missing, do not approve or guess at its findings: it is not approval evidence. Write `review.md` recording which lens was missing and what came back, check no verdict box, then run the `code_review blocked` commands in step 5 for every task. Other lenses' findings may be recorded but not adjudicated into a verdict.\n\n### 2. Adjudicate\n\nUse the three lens inputs and the spec. Do not perform a new full diff review for novel bugs; your role is synthesis and adjudication.\n\nThe lenses are instructed to over-report \u2014 to surface low-confidence and low-severity findings rather than self-censor. Filtering is **your** job, not theirs. A clean return in the charter's empty form is a valid result; only a missing return (step 1) is a lens failure. Rank surviving findings by confidence \xD7 severity. A low-confidence, low-severity finding is a nit or gets dismissed; it does not by itself drive `changes_requested`. Do not discard a finding merely because a lens marked it low-confidence \u2014 verify it against the spec/diff first, then rank.\n\n1. Dedup: if 2+ lenses flagged the same behavior, collapse it to one finding and record \"flagged by N lenses.\" A finding flagged by 2+ lenses is higher-confidence regardless of any lens's self-tag. Cross-model agreement \u2014 the same behavior flagged by cold-Claude and cold-Codex \u2014 must not be dismissed as spec-intended without explicit spec evidence cited in `review.md`.\n2. Keep the two reconciliation checks separate:\n - Does it hold against the code? For cold findings (cold-Claude and cold-Codex), verify each against the diff/code. Codex P-levels are claims to check, not verdicts. A finding that does not hold gets recorded as `Dismissed (cold-Claude): <finding> - <reason>` or `Dismissed (cold-Codex): <finding> - <reason>`.\n - Is it in spec scope? Apply this only to anchored-lens findings as part of the Stage 1 / Stage 2 charter.\n - Forbidden: do not dismiss a verified cold-Claude or cold-Codex finding merely for being off-AC or out of spec scope. A real bug caught by a cold lens is still a bug even if no AC named it.\n3. Altitude classification: every surviving finding is either:\n - `code-bug`: the implementation is wrong or test integrity is compromised.\n - `spec-gap`: the implementation may match the written spec, but the spec is missing, wrong, or too ambiguous for the implementer to fix.\n\n### 3. Choose Verdict\n\n- Any `code-bug` finding -> `changes_requested`.\n- Any `spec-gap` finding and no code-bugs -> `spec_gap`.\n- Optional nits or cleanup without blocking findings -> `approved_with_nits`.\n- No surviving findings -> `approved`.\n\nTest-integrity findings are always code-bugs.\n\n### 4. Write `review.md`\n\nWhen you cite a section of a Markdown doc with the quoted form `\xA7\"\u2026\"`, the quoted text must be an exact heading in that file. To point at a bold-lead paragraph or anything that is not a heading, use `file:line` or the unquoted `\xA7Name` form instead.\n\nFor each task, write `tasks/<id>/review.md`.\n\nRound 1 fills the existing template structure directly \u2014 do **not** wrap it in a `## Round 1` section; the `## Stage 1` and `## Stage 2` headings stay at H2. Re-review appends a new `## Round {{roundN}}` section near the bottom (with `### Stage 1` / `### Stage 2` sub-headings), preserving earlier rounds.\n\nEvery round \u2014 the Round 1 body and each `## Round N` section \u2014 includes one scope line near the top: **Scope:** {{{scopeWord}}} \u2014 base `{{{scopeBase}}}` \u2014 reason: {{{scopeReason}}}. The numbered cold-Codex archive header is the machine-readable record.\n\nInclude:\n- Stage 1: anchored lens validation gate result and AC table.\n- Stage 2 / Findings: surviving findings with altitude (`code-bug` or `spec-gap`), source lens, and file:line.\n- Dismissed Cold Findings: every dropped cold finding plus the reason, including `Dismissed (cold-Claude): ...` and `Dismissed (cold-Codex): ...` entries where applicable.\n- Final Verdict: check exactly one verdict checkbox, including `Spec gap` when applicable (except the missing-lens stop in step 1, which checks none).\n\n### 5. Set Phase Verdict\n\nRun one command per task with the actual verdict:\n{{{phaseCommands}}}\n\nIf a lens was still missing after its re-spawn (step 1), write `review.md` first, then run these instead, with no verdict \u2014 this stops the run for the human:\n{{{blockedCommands}}}\n";
5090
5165
 
5091
5166
  // src/orchestrator/prompts/templates/implement.md
5092
- var implement_default = 'You are implementing {{taskScope}} for {{projectName}}.\n\n{{{stateHeader}}}\n{{{startup}}}\n{{{risksBlock}}}{{{pitfallsBlock}}}{{{contextBlock}}}\n{{{affectedFilesBlock}}}\nTasks to implement:\n{{{taskLines}}}{{#isBundle}}\nThese tasks are related \u2014 implement them together. Consider shared code paths and cross-task interactions.{{/isBundle}}\n\nGrounding rule: before you write handoff.md, re-open the files you changed and verify the current diff against the spec. Do not treat a previous session\'s memory as proof that the work is already in place.\n\n**Spec ACs are binding. Plan approach is guidance.**\n- Every Acceptance Criterion in spec.md MUST be met \u2014 these are non-negotiable.\n- If you find a better implementation approach than what\'s in the plan, use it. Document every deviation in handoff.md under "Deviations" with specific rationale.\n- You may NOT silently drop an AC, skip a required validation check, or omit a spec requirement.\n- If an AC is infeasible as written, document it in Blockers \u2014 do not silently skip.\n- If an AC is ambiguous enough that two reasonable implementations exist, document your interpretation in handoff.md under Blockers with label `[ambiguity]` \u2014 do not silently guess. Claude will evaluate whether the interpretation was correct.\n\n## Implementation Rules\n\n**Safe-First Rules** \u2014 always applicable regardless of stack:\n1. For storage, reload, sync, or data-affecting flows: ship the safer guarded behavior first.\n2. Behavior that reloads the app, replaces local state, or dismisses user work must be gated by explicit user action.\n3. Prefer shared types over duplicating signatures.\n\n**Scope Discipline** \u2014 always applicable; the spec is the contract:\n1. **Affected Files is the scope cap.** If satisfying an AC genuinely requires editing files outside the spec\'s *Affected Files* table, do not make that edit. Record the gap in `handoff.md` under *Blockers* \u2014 the handoff is how it reaches a human \u2014 then finish the remaining in-scope work, the handoff, and the phase command. Do not silently expand scope. New helpers, fixtures, and test files introduced during implementation count against this cap too.\n2. **No unauthorized new abstractions.** Do not introduce new top-level modules, services, packages, or routing layers that the spec did not authorize. Minor refactors within an authorized file are fine; new abstractions are an architecture decision and belong in the spec.\n3. **No incidental dependency changes.** Do not add, remove, upgrade, or downgrade dependencies (or their pinned versions) unless the spec explicitly requests it.\n\n**Lint & Type Safety Policy** \u2014 always applicable:\n1. **Suppressing a lint or type error is a last resort**, not a convenience escape hatch. Never add a suppression without a same-line justification explaining *why the rule is wrong for this specific case*.\n2. **`any` / dynamic typing**: When the shape is truly unknown at the boundary, type as `unknown` and narrow explicitly.\n\n**Bug/Flake-Fix Red-First Checkpoint** \u2014 applicable when a spec\'s ACs include a red-first regression test:\nWrite the test and run it against the pre-fix code first; confirm it fails *for the reason the spec states*, then apply the fix and confirm it passes. Report the red run (command + observed failure) in handoff.md. If the test cannot be made to fail on the pre-fix code for the stated reason, do not implement a fix on a premise you could not reproduce \u2014 record a `[wrong-premise]` Blocker in handoff.md instead, then finish the remaining in-scope work, the handoff, and the phase command. If the spec instead uses the environment-bound-and-impractical escape, run its named deterministic alternative before fixing if it is executable in your sandbox (e.g. an integration fixture) and report the outcome in handoff.md the same way; if it is not executable (e.g. a documented manual repro), state that in handoff.md instead \u2014 never report an outcome for a run that did not happen.\n\n**Parsing Structured Input** \u2014 always applicable when implementing a parser for author-facing structured input:\nParse cell-by-cell with explicit rejection, not a permissive whole-string regex. Anchor each cell to exactly one expected shape and reject malformed cells with a specific reason at the parse boundary.\n\nRun ALL applicable validation checks before writing handoff. See "Validation Required" in each spec.md. The universal change-type \u2192 check-category matrix:\n\n| Change Type | Required Check Categories |\n|---|---|\n| Most changes | Linting, type checking, unit tests |\n| Docs references | Docs references |\n| Routes / config / build | Full build |\n| UI / interaction changes | End-to-end tests |\n| Content / SEO / metadata | Prerender / sitemap / feed regeneration |\n| Schema / migration | Migration runner + manual review |\n| Cross-platform | Subset of the above on each platform |\n\nFor which command runs each category: see `docs/architecture.md` \xA7Validation (project command bindings). Required checks must be recorded as Pass or Fail; do not mark a required check N/A unless the spec explicitly removed it.\n\n**Test flakiness in your sandbox.** Validation suites \u2014 especially E2E or integration tests \u2014 can hit transient failures (timing races, environment quirks, network jitter) that have nothing to do with the code in your spec\'s Affected Files. **If a failure is in a test / file outside your Affected Files table, do NOT fix it.** Note the observed test name, file, line, and a one-line repro hint in handoff.md \u2192 Blockers (or "Validation Outcomes" Notes column with status `Fail \u2013 unrelated`), then continue. `Fail \u2013 unrelated` is only valid for failures in files outside your Affected Files; a failure in a file you changed is yours to fix. Scope discipline > fixing adjacent bugs you spot during validation. The reviewer/operator will decide whether to triage the unrelated failure separately.\n\nFor each task, write tasks/<id>/handoff.md using the template. The Validation Outcomes table must have no Fail results EXCEPT for unrelated-flake rows clearly labeled in the Notes column.\n\n**Citing files in task artifacts:** cite every repository file by its full path from the repository root, including any workspace or package prefix \u2014 never a path relative to a package or to the current directory. For a file that does not exist \u2014 one this task deleted, or one only planned \u2014 use the markdown-link form `[path](path)` instead of backticks, because `docs-refs-check` reports a backticked path to a missing file as a broken reference.\nAppend to tasks/<id>/notes.md for any surprising codebase behavior (prefix: [implement]).\n\nWhen done, run:\n{{{phaseCommands}}}\n';
5167
+ var implement_default = 'You are implementing {{taskScope}} for {{projectName}}.\n\n{{{stateHeader}}}\n{{{startup}}}\n{{{risksBlock}}}{{{pitfallsBlock}}}{{{contextBlock}}}\n{{{affectedFilesBlock}}}\nTasks to implement:\n{{{taskLines}}}{{#isBundle}}\nThese tasks are related \u2014 implement them together. Consider shared code paths and cross-task interactions.{{/isBundle}}\n\nGrounding rule: before you write handoff.md, re-open the files you changed and verify the current diff against the spec. Do not treat a previous session\'s memory as proof that the work is already in place.\n\n**Spec ACs are binding. Plan approach is guidance.**\n- Every Acceptance Criterion in spec.md MUST be met \u2014 these are non-negotiable.\n- If you find a better implementation approach than what\'s in the plan, use it. Document every deviation in handoff.md under "Deviations" with specific rationale.\n- You may NOT silently drop an AC, skip a required validation check, or omit a spec requirement.\n- If an AC is infeasible as written, document it in Blockers \u2014 do not silently skip.\n- If an AC is ambiguous enough that two reasonable implementations exist, document your interpretation in handoff.md under Blockers with label `[ambiguity]` \u2014 do not silently guess. Claude will evaluate whether the interpretation was correct.\n\n## Implementation Rules\n\n**Safe-First Rules** \u2014 always applicable regardless of stack:\n1. For storage, reload, sync, or data-affecting flows: ship the safer guarded behavior first.\n2. Behavior that reloads the app, replaces local state, or dismisses user work must be gated by explicit user action.\n3. Prefer shared types over duplicating signatures.\n\n**Scope Discipline** \u2014 always applicable; the spec is the contract:\n1. **Affected Files is the scope cap.** If satisfying an AC genuinely requires editing files outside the spec\'s *Affected Files* table, do not make that edit. Record the gap in `handoff.md` under *Blockers* \u2014 the handoff is how it reaches a human \u2014 then finish the remaining in-scope work, the handoff, and the phase command. Do not silently expand scope. New helpers, fixtures, and test files introduced during implementation count against this cap too.\n2. **No unauthorized new abstractions.** Do not introduce new top-level modules, services, packages, or routing layers that the spec did not authorize. Minor refactors within an authorized file are fine; new abstractions are an architecture decision and belong in the spec.\n3. **No incidental dependency changes.** Do not add, remove, upgrade, or downgrade dependencies (or their pinned versions) unless the spec explicitly requests it.\n\n**Lint & Type Safety Policy** \u2014 always applicable:\n1. **Suppressing a lint or type error is a last resort**, not a convenience escape hatch. Never add a suppression without a same-line justification explaining *why the rule is wrong for this specific case*.\n2. **`any` / dynamic typing**: When the shape is truly unknown at the boundary, type as `unknown` and narrow explicitly.\n\n**Bug/Flake-Fix Red-First Checkpoint** \u2014 applicable when a spec\'s ACs include a red-first regression test:\nWrite the test and run it against the pre-fix code first; confirm it fails *for the reason the spec states*, then apply the fix and confirm it passes. Record the red run as a row in the handoff\u2019s Red-First Evidence section (AC, command, the commit it ran against, observed failure, post-fix result). The pre-fix state is the task\u2019s base commit: write the test and run it before changing any non-test code; files that exist only to support tests count as test files. If the test cannot be made to fail on the pre-fix code for the stated reason, do not implement a fix on a premise you could not reproduce \u2014 record a `[wrong-premise]` Blocker in handoff.md instead, then finish the remaining in-scope work, the handoff, and the phase command. If the spec instead uses the environment-bound-and-impractical escape, run its named deterministic alternative before fixing if it is executable in your sandbox (e.g. an integration fixture) and record the outcome in the Red-First Evidence section; if it is not executable (e.g. a documented manual repro), state that in handoff.md instead \u2014 never report an outcome for a run that did not happen.\n\n**Parsing Structured Input** \u2014 always applicable when implementing a parser for author-facing structured input:\nParse cell-by-cell with explicit rejection, not a permissive whole-string regex. Anchor each cell to exactly one expected shape and reject malformed cells with a specific reason at the parse boundary.\n\nRun ALL applicable validation checks before writing handoff. See "Validation Required" in each spec.md. The universal change-type \u2192 check-category matrix:\n\n| Change Type | Required Check Categories |\n|---|---|\n| Most changes | Linting, type checking, unit tests |\n| Docs references | Docs references |\n| Routes / config / build | Full build |\n| UI / interaction changes | End-to-end tests |\n| Content / SEO / metadata | Prerender / sitemap / feed regeneration |\n| Schema / migration | Migration runner + manual review |\n| Cross-platform | Subset of the above on each platform |\n\nFor which command runs each category: see `docs/architecture.md` \xA7Validation (project command bindings). Required checks must be recorded as Pass or Fail; do not mark a required check N/A unless the spec explicitly removed it.\n\n**Test flakiness in your sandbox.** Validation suites \u2014 especially E2E or integration tests \u2014 can hit transient failures (timing races, environment quirks, network jitter) that have nothing to do with the code in your spec\'s Affected Files. **If a failure is in a test / file outside your Affected Files table, do NOT fix it.** Note the observed test name, file, line, and a one-line repro hint in handoff.md \u2192 Blockers (or "Validation Outcomes" Notes column with status `Fail \u2013 unrelated`), then continue. `Fail \u2013 unrelated` is only valid for failures in files outside your Affected Files; a failure in a file you changed is yours to fix. Scope discipline > fixing adjacent bugs you spot during validation. The reviewer/operator will decide whether to triage the unrelated failure separately.\n\nFor each task, write tasks/<id>/handoff.md using the template. The Validation Outcomes table must have no Fail results EXCEPT for unrelated-flake rows clearly labeled in the Notes column.\n\n**Citing files in task artifacts:** cite every repository file by its full path from the repository root, including any workspace or package prefix \u2014 never a path relative to a package or to the current directory. For a file that does not exist \u2014 one this task deleted, or one only planned \u2014 use the markdown-link form `[path](path)` instead of backticks, because `docs-refs-check` reports a backticked path to a missing file as a broken reference.\nAppend to tasks/<id>/notes.md for any surprising codebase behavior (prefix: [implement]).\n\nWhen done, run:\n{{{phaseCommands}}}\n';
5093
5168
 
5094
5169
  // src/orchestrator/prompts/templates/implement-reroute.md
5095
- var implement_reroute_default = "A human wrote a spec amendment and rerouted {{taskScope}} for {{projectName}}.\n\n{{{stateHeader}}}\n{{{roundBanner}}}{{{preamble}}}\n\n{{#startup}}{{{startup}}}\n{{/startup}}{{{risksBlock}}}{{{pitfallsBlock}}}{{{contextBlock}}}\n{{{affectedFilesBlock}}}\nTasks with amended specs:\n{{{taskLines}}}\n\n{{{groundingRule}}}\n\n**How to approach this:**\n0. If a task's line above marks it EXEMPT, skip steps 1-2 for that task entirely \u2014 its spec has NO Amendment section and its plan has NO Reroute Plan section, by design. For exempt tasks, follow the task-specific line above: approved siblings only need shared-behavior re-verification, while siblings with prior review findings must still address those findings.\n1. For each task above, read `tasks/<id>/spec.md` from your current working directory (the worktree). REPO_ROOT's copy is the pre-implement scaffold and does NOT contain operator amendments. Locate the exact heading named in its entry \u2014 `## Amendment` for round 1, or `## Amendment Round N` for round 2+. Each task carries its own reroute round (bundles may mix rounds), so use the heading specified in that task's line, not a bundle-wide assumption. Treat that section's content as the new requirements; ignore prior-round sections when implementing this one.\n2. Check `tasks/<id>/plan.md` for `## Reroute Plan` (round 1) or `## Reroute Plan Round N` (N = that task's reroute round). If present, use that section as the delta guide. If absent (fast-tier reroute with no conversational reroute plan), read the base plan for orientation.\n3. Read tasks/<id>/handoff.md to understand what you previously shipped. Do NOT assume the handoff covers the amendment \u2014 it was written before the amendment existed.\n4. Identify the delta: which ACs are new, which changed, which were already addressed by the previous implementation.\n5. Implement the delta. Previously-correct work stays; only change what the amendment requires. If the amendment conflicts with a prior AC, the amendment wins.\n6. Re-run ALL applicable validation checks (lint, type-check, test, build, e2e as applicable per the spec's Validation Required). Required checks must be recorded as Pass or Fail; do not mark a required check N/A.\n7. **Rewrite handoff.md** to reflect the complete current state of the implementation \u2014 including the round-1 work that still applies plus the new amendment work. The reviewer reads handoff.md as the single source of truth, not your prior session's context.\n\n**Citing files in task artifacts:** cite every repository file by its full path from the repository root, including any workspace or package prefix \u2014 never a path relative to a package or to the current directory. For a file that does not exist \u2014 one this task deleted, or one only planned \u2014 use the markdown-link form `[path](path)` instead of backticks, because `docs-refs-check` reports a backticked path to a missing file as a broken reference.\n\n**Spec ACs are binding** \u2014 including both original ACs and amendment ACs. If you think an amendment AC is infeasible as written, document it under Blockers in handoff.md. Do not silently drop any AC.\n\n**Bug/flake-fix red-first checkpoint** \u2014 if the amendment adds or modifies a red-first regression-test AC: write and run the test against the task's current state **before** making this round's fix edits, and confirm it fails *for the reason the spec states*; then apply the fix and confirm it passes. Report the red run in handoff.md. If it cannot be made to fail for that reason, record a `[wrong-premise]` Blocker instead of implementing on an unconfirmed premise. If the amendment instead relies on the environment-bound-and-impractical escape, run its named deterministic alternative if it is executable in your sandbox and report the outcome in handoff.md; if it is not executable (e.g. a documented manual repro), state that instead \u2014 never report an outcome for a run that did not happen.\n\nAppend to tasks/<id>/notes.md for any surprising behavior found while re-reading the codebase (prefix: `[implement-reroute]`).\n\nWhen done, run:\n{{{phaseCommands}}}\n";
5170
+ var implement_reroute_default = "A human wrote a spec amendment and rerouted {{taskScope}} for {{projectName}}.\n\n{{{stateHeader}}}\n{{{roundBanner}}}{{{preamble}}}\n\n{{#startup}}{{{startup}}}\n{{/startup}}{{{risksBlock}}}{{{pitfallsBlock}}}{{{contextBlock}}}\n{{{affectedFilesBlock}}}\nTasks with amended specs:\n{{{taskLines}}}\n\n{{{groundingRule}}}\n\n**How to approach this:**\n0. If a task's line above marks it EXEMPT, skip steps 1-2 for that task entirely \u2014 its spec has NO Amendment section and its plan has NO Reroute Plan section, by design. For exempt tasks, follow the task-specific line above: approved siblings only need shared-behavior re-verification, while siblings with prior review findings must still address those findings.\n1. For each task above, read `tasks/<id>/spec.md` from your current working directory (the worktree). REPO_ROOT's copy is the pre-implement scaffold and does NOT contain operator amendments. Locate the exact heading named in its entry \u2014 `## Amendment` for round 1, or `## Amendment Round N` for round 2+. Each task carries its own reroute round (bundles may mix rounds), so use the heading specified in that task's line, not a bundle-wide assumption. Treat that section's content as the new requirements; ignore prior-round sections when implementing this one.\n2. Check `tasks/<id>/plan.md` for `## Reroute Plan` (round 1) or `## Reroute Plan Round N` (N = that task's reroute round). If present, use that section as the delta guide. If absent (fast-tier reroute with no conversational reroute plan), read the base plan for orientation.\n3. Read tasks/<id>/handoff.md to understand what you previously shipped. Do NOT assume the handoff covers the amendment \u2014 it was written before the amendment existed.\n4. Identify the delta: which ACs are new, which changed, which were already addressed by the previous implementation.\n5. Implement the delta. Previously-correct work stays; only change what the amendment requires. If the amendment conflicts with a prior AC, the amendment wins.\n6. Re-run ALL applicable validation checks (lint, type-check, test, build, e2e as applicable per the spec's Validation Required). Required checks must be recorded as Pass or Fail; do not mark a required check N/A.\n7. **Rewrite handoff.md** to reflect the complete current state of the implementation \u2014 including the round-1 work that still applies plus the new amendment work. Carry existing Red-First Evidence rows forward. The reviewer reads handoff.md as the single source of truth, not your prior session's context.\n\n**Citing files in task artifacts:** cite every repository file by its full path from the repository root, including any workspace or package prefix \u2014 never a path relative to a package or to the current directory. For a file that does not exist \u2014 one this task deleted, or one only planned \u2014 use the markdown-link form `[path](path)` instead of backticks, because `docs-refs-check` reports a backticked path to a missing file as a broken reference.\n\n**Spec ACs are binding** \u2014 including both original ACs and amendment ACs. If you think an amendment AC is infeasible as written, document it under Blockers in handoff.md. Do not silently drop any AC.\n\n**Bug/flake-fix red-first checkpoint** \u2014 if the amendment adds or modifies a red-first regression-test AC: write and run the test against the task's current state **before** making this round's fix edits, and confirm it fails *for the reason the spec states*; then apply the fix and confirm it passes. Record the red run as a row in the rewritten handoff\u2019s `## Red-First Evidence` table, next to the rows carried forward from earlier rounds (AC, command, the commit it ran against, observed failure, post-fix result). The pre-fix state is the task branch\u2019s HEAD before this round\u2019s edits: write the test and run it before changing any non-test code; files that exist only to support tests count as test files. If it cannot be made to fail for that reason, record a `[wrong-premise]` Blocker instead of implementing on an unconfirmed premise. If the amendment instead relies on the environment-bound-and-impractical escape, run its named deterministic alternative if it is executable in your sandbox and record the outcome in the Red-First Evidence section; if it is not executable (e.g. a documented manual repro), state that instead \u2014 never report an outcome for a run that did not happen.\n\nAppend to tasks/<id>/notes.md for any surprising behavior found while re-reading the codebase (prefix: `[implement-reroute]`).\n\nWhen done, run:\n{{{phaseCommands}}}\n";
5096
5171
 
5097
5172
  // src/orchestrator/prompts/templates/implement-revisions.md
5098
- var implement_revisions_default = '{{{iterBanner}}}\n\n{{{stateHeader}}}\n{{{startup}}}\n\n{{{affectedFilesBlock}}}\n\n{{#hasReviewFindings}}\nYour prior iteration shipped; the reviewer (Claude) appended findings to `review.md` as `## Round {{priorRound}}`. If you\'re resuming the prior session, the full task framing (spec, plan, repo conventions) is already in context \u2014 skip the re-read. If your context is cold, re-read `tasks/<id>/spec.md` and `tasks/<id>/plan.md` before addressing findings.\n\nTasks with new review feedback:\n{{{reviewLines}}}\n\nFor each task:\n1. Read the most recent `## Round {{priorRound}}` section of `tasks/<id>/review.md`. That is the entire scope of this iteration.\n2. Address every `correctness bug`, `risk/guardrail`, and `spec gap` finding from that round (blocking). `optional cleanup/nit` is at your discretion{{#tightenLine}}{{{tightenLine}}}{{/tightenLine}}\n3. Re-run only the validation checks affected by your changes (typically lint, type-check, plus whatever the diff touches).\n4. **APPEND** to `tasks/<id>/handoff.md` a new section `{{{handoffAppend}}}` (the template\'s "On revision rounds" comment shows the shape). Do NOT rewrite the file from scratch \u2014 earlier iterations stay as the cumulative record. Include only the delta: findings addressed, AC deltas, re-run validation results.\n{{/hasReviewFindings}}\n{{#hasPreflightFindings}}\nYour prior iteration was rejected by the orchestrator\'s pre-flight gate **before any Claude review ran**. The rejection details are recorded in `review.md` under `## Validation Gate` / `## Pre-Flight Rejection`.\n\nTasks with pre-flight rejection feedback:\n{{{reviewLines}}}\n\nFor each task:\n1. Read the pre-flight block in `tasks/<id>/review.md` and follow **whichever framing it carries**:\n - **"Fix the handoff"** items \u2192 fix `handoff.md` (Validation Outcomes rows, AC Coverage table, Changes table).\n - **"Fix the code"** items \u2192 a required check failed on a file you changed. Fix the regression, re-run the check, and update the handoff.\n - Both framings may be present \u2014 address all items from both before resubmitting.\n2. **APPEND** to `tasks/<id>/handoff.md` a new section `{{{handoffAppend}}}`. Include the delta: which items you addressed and how.\n{{/hasPreflightFindings}}\n\nSpec ACs remain binding. If the review identifies a dropped AC, restore it.\n\n**Iteration rules:**\n\n- **Reverting a file**: For a byte-perfect revert to the task baseline, use `git show origin/<base-branch>:<path>` (read-only git, always allowed) and write the output to the file.\n - *Perfect revert* (file no longer in `git diff base...HEAD`): delete it from all prior iteration Changes tables in `handoff.md`.\n - *Imperfect revert* (trailing newline or other residual remains): add it to the current iteration\'s Changes table with "Reverted to original (describe residual diff)".\n- **Referencing deleted (or not-yet-created) files in artifacts**: **Citing files in task artifacts:** cite every repository file by its full path from the repository root, including any workspace or package prefix \u2014 never a path relative to a package or to the current directory. For a file that does not exist \u2014 one this task deleted, or one only planned \u2014 use the markdown-link form `[path](path)` instead of backticks, because `docs-refs-check` reports a backticked path to a missing file as a broken reference. In the handoff Changes-table first column this is the only accepted form for a deleted path \u2014 backtick form fails both checks.\n- **Rerouted / revised tasks \u2014 the pre-flight diff is cumulative**: the verifier checks the union of all Changes tables against `git diff <base>...HEAD`. Before submitting, run `git diff <base>...HEAD --name-only` and confirm every listed path is covered by at least one Changes-table row across ALL iterations.\n- **Bug/flake-fix red-first checkpoint**: if this round adds or modifies the spec\'s red-first regression test, write and run the test **before** making this round\'s fix edits and confirm it fails *for the reason the spec states*; then apply the fix and confirm it passes. Report the red run in the handoff delta. If it cannot be made to fail for that reason, do not implement around an unconfirmed premise \u2014 record a `[wrong-premise]` Blocker in handoff.md instead, then finish the remaining in-scope work, the handoff, and the phase command. If the spec instead uses the environment-bound-and-impractical escape, run its named deterministic alternative if it is executable in your sandbox and report the outcome in the handoff delta; if it is not executable (e.g. a documented manual repro), state that instead \u2014 never report an outcome for a run that did not happen.\n\nAppend to `tasks/<id>/notes.md` for new pitfalls found (prefix: `[implement-revision]`).\n\nWhen done, run:\n{{{phaseCommands}}}\n';
5173
+ var implement_revisions_default = '{{{iterBanner}}}\n\n{{{stateHeader}}}\n{{{startup}}}\n\n{{{affectedFilesBlock}}}\n\n{{#hasReviewFindings}}\nYour prior iteration shipped; the reviewer (Claude) appended findings to `review.md` as `## Round {{priorRound}}`. If you\'re resuming the prior session, the full task framing (spec, plan, repo conventions) is already in context \u2014 skip the re-read. If your context is cold, re-read `tasks/<id>/spec.md` and `tasks/<id>/plan.md` before addressing findings.\n\nTasks with new review feedback:\n{{{reviewLines}}}\n\nFor each task:\n1. Read the most recent `## Round {{priorRound}}` section of `tasks/<id>/review.md`. That is the entire scope of this iteration.\n2. Address every `correctness bug`, `risk/guardrail`, and `spec gap` finding from that round (blocking). `optional cleanup/nit` is at your discretion{{#tightenLine}}{{{tightenLine}}}{{/tightenLine}}\n3. Re-run only the validation checks affected by your changes (typically lint, type-check, plus whatever the diff touches).\n4. **APPEND** to `tasks/<id>/handoff.md` a new section `{{{handoffAppend}}}` (the template\'s "On revision rounds" comment shows the shape). Do NOT rewrite the file from scratch \u2014 earlier iterations stay as the cumulative record. Include only the delta: findings addressed, AC deltas, re-run validation results.\n{{/hasReviewFindings}}\n{{#hasPreflightFindings}}\nYour prior iteration was rejected by the orchestrator\'s pre-flight gate **before any Claude review ran**. The rejection details are recorded in `review.md` under `## Validation Gate` / `## Pre-Flight Rejection`.\n\nTasks with pre-flight rejection feedback:\n{{{reviewLines}}}\n\nFor each task:\n1. Read the pre-flight block in `tasks/<id>/review.md` and follow **whichever framing it carries**:\n - **"Fix the handoff"** items \u2192 fix `handoff.md` (Validation Outcomes rows, AC Coverage table, Changes table).\n - **"Fix the code"** items \u2192 a required check failed on a file you changed. Fix the regression, re-run the check, and update the handoff.\n - Both framings may be present \u2014 address all items from both before resubmitting.\n2. **APPEND** to `tasks/<id>/handoff.md` a new section `{{{handoffAppend}}}`. Include the delta: which items you addressed and how.\n{{/hasPreflightFindings}}\n\nSpec ACs remain binding. If the review identifies a dropped AC, restore it.\n\n**Iteration rules:**\n\n- **Reverting a file**: For a byte-perfect revert to the task baseline, use `git show origin/<base-branch>:<path>` (read-only git, always allowed) and write the output to the file.\n - *Perfect revert* (file no longer in `git diff base...HEAD`): delete it from all prior iteration Changes tables in `handoff.md`.\n - *Imperfect revert* (trailing newline or other residual remains): add it to the current iteration\'s Changes table with "Reverted to original (describe residual diff)".\n- **Referencing deleted (or not-yet-created) files in artifacts**: **Citing files in task artifacts:** cite every repository file by its full path from the repository root, including any workspace or package prefix \u2014 never a path relative to a package or to the current directory. For a file that does not exist \u2014 one this task deleted, or one only planned \u2014 use the markdown-link form `[path](path)` instead of backticks, because `docs-refs-check` reports a backticked path to a missing file as a broken reference. In the handoff Changes-table first column this is the only accepted form for a deleted path \u2014 backtick form fails both checks.\n- **Rerouted / revised tasks \u2014 the pre-flight diff is cumulative**: the verifier checks the union of all Changes tables against `git diff <base>...HEAD`. Before submitting, run `git diff <base>...HEAD --name-only` and confirm every listed path is covered by at least one Changes-table row across ALL iterations.\n- **Bug/flake-fix red-first checkpoint**: if this round adds or modifies the spec\'s red-first regression test, write and run the test **before** making this round\'s fix edits and confirm it fails *for the reason the spec states*; then apply the fix and confirm it passes. Record the red run as a row in this round\u2019s Iteration subsection, `### Red-First Evidence` (AC, command, the commit it ran against, observed failure, post-fix result). The pre-fix state is the task branch\u2019s HEAD before this round\u2019s edits: write the test and run it before changing any non-test code; files that exist only to support tests count as test files. If a review round flagged missing red-first evidence, run the test against the recorded pre-fix commit (for example in a scratch checkout of that commit with only the test applied) and record the row; you do not need to redo the fix. If it cannot be made to fail for that reason, do not implement around an unconfirmed premise \u2014 record a `[wrong-premise]` Blocker in handoff.md instead, then finish the remaining in-scope work, the handoff, and the phase command. If the spec instead uses the environment-bound-and-impractical escape, run its named deterministic alternative if it is executable in your sandbox and record the outcome in this round\u2019s `### Red-First Evidence` subsection; if it is not executable (e.g. a documented manual repro), state that instead \u2014 never report an outcome for a run that did not happen.\n\nAppend to `tasks/<id>/notes.md` for new pitfalls found (prefix: `[implement-revision]`).\n\nWhen done, run:\n{{{phaseCommands}}}\n';
5099
5174
 
5100
5175
  // src/orchestrator/prompts/templates/plan-reroute.md
5101
5176
  var plan_reroute_default = "You are updating the implementation plan for {{taskScope}} for {{projectName}} after a human reroute.\n\n{{{startup}}}\n\nA human amended the spec and rerouted the task after a completed implementation round. Codex has reviewed the amendment. Your job is to **append** a reroute plan section to `plan.md`; do not rewrite or remove existing plan content.\n\n{{{roundBanner}}}Amendment review verdicts:\n{{{verdictLines}}}\n\nFor each task \u2014 EXCEPT tasks whose line above marks them EXEMPT (those have no amendment; skip every step below for them and append NO Reroute Plan section to their plan.md):\n1. Read `tasks/<id>/spec.md` from your current directory, including the amendment for the round listed above.\n2. Read `tasks/<id>/plan.md` to understand the prior plan.\n3. Read `tasks/<id>/handoff.md` to understand what Codex previously shipped.\n4. Read `tasks/<id>/spec-review.md` for the latest reroute amendment review and any nits to incorporate.\n5. Append a new section to `tasks/<id>/plan.md`:\n - Round 1: `## Reroute Plan`\n - Round N >= 2: `## Reroute Plan Round N`\n6. Plan only the delta from the amendment. Reference specific files, functions, and existing patterns. Acknowledge prior plan steps that still apply without re-planning them.\n7. {{{feasibilityCheck}}}\n\nDo **not** rewrite or remove existing sections from `plan.md`. The appended reroute plan is what implement-reroute reads as its delta guide.\n\nWhen done, run:\n{{{phaseCommands}}}\n\n<!-- per-round append shape:\n## Reroute Plan [Round N]\n### Delta\n- Feasibility: ...\n- ...ordered steps for the amendment delta only...\n-->\n";
@@ -5483,7 +5558,7 @@ function bundleHasRealPriorReview(taskIds) {
5483
5558
  return taskIds.every((taskId) => {
5484
5559
  const reviewPath = path12.join(taskDirFor(taskId), "review.md");
5485
5560
  try {
5486
- const content = fs13.readFileSync(reviewPath, "utf8");
5561
+ const content = fs14.readFileSync(reviewPath, "utf8");
5487
5562
  const hasH2 = /^## Stage 1\b/m.test(content);
5488
5563
  const hasNested = /^## Round \d+\b/m.test(content) && /^### Stage 1\b/m.test(content);
5489
5564
  return (hasH2 || hasNested) && !content.includes("[TASK-ID]");
@@ -5575,19 +5650,19 @@ function promptQa(state, prTemplate, docs = { editable: DEFAULT_PROTECTED_DOCS,
5575
5650
 
5576
5651
  // src/task/index.ts
5577
5652
  import { spawnSync as spawnSync6 } from "child_process";
5578
- import fs16 from "fs";
5653
+ import fs17 from "fs";
5579
5654
  import path15 from "path";
5580
5655
 
5581
5656
  // src/orchestrator/canon-snapshot.ts
5582
5657
  import { spawnSync as spawnSync5 } from "child_process";
5583
- import fs14 from "fs";
5658
+ import fs15 from "fs";
5584
5659
  import path13 from "path";
5585
5660
  var CANON_UPSTREAM_REPO = "tstraub89/canon-ai";
5586
5661
  function isInstalledSourcePath(sourcePath) {
5587
5662
  return sourcePath.includes("/node_modules/") || sourcePath.includes("\\node_modules\\") || sourcePath.includes("/_npx/") || sourcePath.includes("\\_npx\\");
5588
5663
  }
5589
5664
  function resolveCanonVersion(explicit) {
5590
- return explicit ?? "3.12.0" ?? "dev";
5665
+ return explicit ?? "3.13.0" ?? "dev";
5591
5666
  }
5592
5667
  function resolveOrchestratorCommit(repoRoot, upstreamCommit, runGitAt) {
5593
5668
  const ownToplevel = captureGitOutput(repoRoot, ["rev-parse", "--show-toplevel"], runGitAt);
@@ -5666,14 +5741,14 @@ function applyCanonSnapshot(status, canon) {
5666
5741
  return next;
5667
5742
  }
5668
5743
  function refreshCanonSnapshotAtPath(statusFilePath, options = {}) {
5669
- const status = JSON.parse(fs14.readFileSync(statusFilePath, "utf8"));
5744
+ const status = JSON.parse(fs15.readFileSync(statusFilePath, "utf8"));
5670
5745
  const canon = captureCanonSnapshot(REPO_ROOT, options);
5671
5746
  const next = applyCanonSnapshot(status, canon);
5672
5747
  const serialized = `${JSON.stringify(next, null, 2)}
5673
5748
  `;
5674
- const current = fs14.readFileSync(statusFilePath, "utf8");
5749
+ const current = fs15.readFileSync(statusFilePath, "utf8");
5675
5750
  if (current !== serialized) {
5676
- fs14.writeFileSync(statusFilePath, serialized, "utf8");
5751
+ fs15.writeFileSync(statusFilePath, serialized, "utf8");
5677
5752
  }
5678
5753
  return canon;
5679
5754
  }
@@ -5682,7 +5757,7 @@ function refreshCanonSnapshotsAtPaths(statusFilePaths, options = {}) {
5682
5757
  }
5683
5758
 
5684
5759
  // src/orchestrator/quality-log.ts
5685
- import fs15 from "fs";
5760
+ import fs16 from "fs";
5686
5761
  import path14 from "path";
5687
5762
  var CANON_LOG_HEADERS = [
5688
5763
  "Date",
@@ -5874,11 +5949,11 @@ function renderRowLine(headerCells, row) {
5874
5949
  function writeFileAtomic(filePath, content) {
5875
5950
  const tempPath = `${filePath}.tmp`;
5876
5951
  try {
5877
- fs15.writeFileSync(tempPath, content, "utf8");
5878
- fs15.renameSync(tempPath, filePath);
5952
+ fs16.writeFileSync(tempPath, content, "utf8");
5953
+ fs16.renameSync(tempPath, filePath);
5879
5954
  } finally {
5880
5955
  try {
5881
- fs15.unlinkSync(tempPath);
5956
+ fs16.unlinkSync(tempPath);
5882
5957
  } catch {
5883
5958
  }
5884
5959
  }
@@ -5907,7 +5982,7 @@ function upsertQualityLogRow(logFilePath, derived, qaSupplied) {
5907
5982
  try {
5908
5983
  let content;
5909
5984
  try {
5910
- content = fs15.readFileSync(logFilePath, "utf8");
5985
+ content = fs16.readFileSync(logFilePath, "utf8");
5911
5986
  } catch (error) {
5912
5987
  if (error.code === "ENOENT") {
5913
5988
  content = STANDARD_QUALITY_LOG_SKELETON;
@@ -5949,11 +6024,11 @@ function writeQualityLogForTask(taskId, _activeCwd, donePath, status) {
5949
6024
  try {
5950
6025
  let doneContent = "";
5951
6026
  try {
5952
- doneContent = fs15.readFileSync(donePath, "utf8");
6027
+ doneContent = fs16.readFileSync(donePath, "utf8");
5953
6028
  } catch {
5954
6029
  }
5955
6030
  const target = process.env.CANON_QUALITY_LOG_FILE_OVERRIDE ? path14.resolve(process.env.CANON_QUALITY_LOG_FILE_OVERRIDE) : path14.join(path14.dirname(donePath), "quality-log.md");
5956
- if (!process.env.CANON_QUALITY_LOG_FILE_OVERRIDE) fs15.mkdirSync(path14.dirname(target), { recursive: true });
6031
+ if (!process.env.CANON_QUALITY_LOG_FILE_OVERRIDE) fs16.mkdirSync(path14.dirname(target), { recursive: true });
5957
6032
  upsertQualityLogRow(
5958
6033
  target,
5959
6034
  {
@@ -6024,7 +6099,7 @@ function taskRootForGate(cwd) {
6024
6099
  }
6025
6100
  function readJsonFile(filePath) {
6026
6101
  try {
6027
- return JSON.parse(fs16.readFileSync(filePath, "utf8"));
6102
+ return JSON.parse(fs17.readFileSync(filePath, "utf8"));
6028
6103
  } catch (error) {
6029
6104
  const message = error instanceof Error ? error.message : String(error);
6030
6105
  throw new Error(`Error: failed to read ${filePath}: ${message}`);
@@ -6032,9 +6107,9 @@ function readJsonFile(filePath) {
6032
6107
  }
6033
6108
  function writeJsonAtomic(filePath, data) {
6034
6109
  const tmpFile = `${filePath}.tmp`;
6035
- fs16.writeFileSync(tmpFile, `${JSON.stringify(data, null, 2)}
6110
+ fs17.writeFileSync(tmpFile, `${JSON.stringify(data, null, 2)}
6036
6111
  `, "utf8");
6037
- fs16.renameSync(tmpFile, filePath);
6112
+ fs17.renameSync(tmpFile, filePath);
6038
6113
  }
6039
6114
  function writeStatusAtomic(filePath, status) {
6040
6115
  status.status = deriveTopLevelStatus(status);
@@ -6107,7 +6182,7 @@ function taskPhase(id, phaseArg, statusArg, verdictArg) {
6107
6182
  assertValidVerdict(phaseArg, verdictArg);
6108
6183
  const taskCwd = resolveTaskCwd(id);
6109
6184
  const statusPath = taskStatusFileForCwd(taskCwd, id);
6110
- if (!fs16.existsSync(statusPath)) {
6185
+ if (!fs17.existsSync(statusPath)) {
6111
6186
  throw new Error(`Error: No status.json found for task ${id} (looked in ${taskDirForCwd(taskCwd, id)}/)`);
6112
6187
  }
6113
6188
  const status = readJsonFile(statusPath);
@@ -6169,7 +6244,7 @@ function taskPhasePreflightRejected(id, phaseArg) {
6169
6244
  }
6170
6245
  const taskCwd = resolveTaskCwd(id);
6171
6246
  const statusPath = taskStatusFileForCwd(taskCwd, id);
6172
- if (!fs16.existsSync(statusPath)) {
6247
+ if (!fs17.existsSync(statusPath)) {
6173
6248
  throw new Error(`Error: No status.json found for task ${id} (looked in ${taskDirForCwd(taskCwd, id)}/)`);
6174
6249
  }
6175
6250
  const status = readJsonFile(statusPath);
@@ -6353,7 +6428,7 @@ function writePreflightReviewArtifacts(tasks, preflightFailed, route) {
6353
6428
  const reviewPath = path16.join(taskDirFor(t.taskId), "review.md");
6354
6429
  let existing = "";
6355
6430
  try {
6356
- existing = fs17.readFileSync(reviewPath, "utf8");
6431
+ existing = fs18.readFileSync(reviewPath, "utf8");
6357
6432
  } catch {
6358
6433
  }
6359
6434
  const hasH2Stage1 = /^## Stage 1\b/m.test(existing);
@@ -6369,7 +6444,7 @@ function writePreflightReviewArtifacts(tasks, preflightFailed, route) {
6369
6444
  ${blockedBlock}` : `# Code Review: ${t.taskId}
6370
6445
 
6371
6446
  ${blockedBlock}`;
6372
- fs17.writeFileSync(reviewPath, reviewContent2, "utf8");
6447
+ fs18.writeFileSync(reviewPath, reviewContent2, "utf8");
6373
6448
  continue;
6374
6449
  }
6375
6450
  const currentPreflight = t.status.phases.code_review?.preflight_rejections_current_loop ?? 0;
@@ -6380,7 +6455,7 @@ ${blockedBlock}`;
6380
6455
  ---
6381
6456
 
6382
6457
  ${stub}` : stub;
6383
- fs17.writeFileSync(reviewPath, reviewContent, "utf8");
6458
+ fs18.writeFileSync(reviewPath, reviewContent, "utf8");
6384
6459
  }
6385
6460
  return true;
6386
6461
  }
@@ -6503,7 +6578,7 @@ Add them to the affected task spec's ### Affected Files table in the active chec
6503
6578
  });
6504
6579
  }
6505
6580
  for (const t of tasks) {
6506
- fs17.writeFileSync(
6581
+ fs18.writeFileSync(
6507
6582
  path16.join(taskDirFor(t.taskId), "review-cold-codex.md"),
6508
6583
  coldReview.findings,
6509
6584
  "utf8"
@@ -6532,7 +6607,7 @@ Add them to the affected task spec's ### Affected Files table in the active chec
6532
6607
  const reviewPath = path16.join(taskDirFor(t.taskId), "review.md");
6533
6608
  let reviewContent = null;
6534
6609
  try {
6535
- reviewContent = fs17.readFileSync(reviewPath, "utf8");
6610
+ reviewContent = fs18.readFileSync(reviewPath, "utf8");
6536
6611
  } catch {
6537
6612
  }
6538
6613
  if (isTemplateUnfilled(reviewContent)) {
@@ -6645,7 +6720,7 @@ async function runImplementPhase(state, interactive, resumeId, force = false) {
6645
6720
  }
6646
6721
 
6647
6722
  // src/orchestrator/phases/plan.ts
6648
- import fs18 from "fs";
6723
+ import fs19 from "fs";
6649
6724
  import path17 from "path";
6650
6725
  async function runPlanPhase(state, interactive) {
6651
6726
  const { tasks } = state;
@@ -6664,7 +6739,7 @@ async function runPlanPhase(state, interactive) {
6664
6739
  const planPath = path17.join(taskDirFor(t.taskId), "plan.md");
6665
6740
  let planContent = null;
6666
6741
  try {
6667
- planContent = fs18.readFileSync(planPath, "utf8");
6742
+ planContent = fs19.readFileSync(planPath, "utf8");
6668
6743
  } catch {
6669
6744
  }
6670
6745
  if (isTemplateUnfilled(planContent)) {
@@ -6676,7 +6751,7 @@ async function runPlanPhase(state, interactive) {
6676
6751
  }
6677
6752
 
6678
6753
  // src/orchestrator/phases/qa.ts
6679
- import fs19 from "fs";
6754
+ import fs20 from "fs";
6680
6755
  import path18 from "path";
6681
6756
  function resolveQaDocsFreshness(taskIds, activeCwd, deps = { getBaseBranch, getAffectedFiles }) {
6682
6757
  const config3 = requireDocsFreshnessConfig(activeCwd);
@@ -6706,7 +6781,7 @@ async function runQaPhase(state, interactive, resolvedPrTemplate) {
6706
6781
  if (isDoneMdTemplate(donePath)) {
6707
6782
  const salvaged = extractDoneMdFromStdout(result.capturedStdout);
6708
6783
  if (salvaged) {
6709
- fs19.writeFileSync(donePath, salvaged);
6784
+ fs20.writeFileSync(donePath, salvaged);
6710
6785
  warn(`Salvaged tasks/${taskId}/done.md from captured stdout \u2014 QA sub-agent streamed content instead of using the Write tool.`);
6711
6786
  const phaseStatus = readStatus(taskId).phases.qa?.status ?? "pending";
6712
6787
  if (phaseStatus !== "done") {
@@ -6758,7 +6833,7 @@ async function runSpecPhase(state, interactive, resumeId) {
6758
6833
  }
6759
6834
 
6760
6835
  // src/orchestrator/phases/spec-review.ts
6761
- import fs20 from "fs";
6836
+ import fs21 from "fs";
6762
6837
  import path19 from "path";
6763
6838
  function autoBlockSpecReview(taskIds, iterationCount, reason) {
6764
6839
  autoBlockPhase(taskIds, "spec_review", iterationCount, reason);
@@ -6767,14 +6842,14 @@ function recordFastTierSpecApproval(taskId) {
6767
6842
  const artifactPath = path19.join(taskDirFor(taskId), "spec-review.md");
6768
6843
  let content;
6769
6844
  try {
6770
- content = fs20.readFileSync(artifactPath, "utf8");
6845
+ content = fs21.readFileSync(artifactPath, "utf8");
6771
6846
  } catch {
6772
6847
  return;
6773
6848
  }
6774
6849
  if (extractCheckedVerdict(content)) return;
6775
6850
  const checked = content.replace(/^- \[ \] (\*\*Approved\*\*)/m, "- [x] $1");
6776
6851
  const note = "\n> Fast tier: Codex spec review skipped \u2014 human conversational spec approval recorded by the orchestrator.\n";
6777
- fs20.writeFileSync(
6852
+ fs21.writeFileSync(
6778
6853
  artifactPath,
6779
6854
  (checked !== content ? checked : `${content}
6780
6855
  ## Verdict
@@ -6846,7 +6921,7 @@ ${promptSpecReview(state)}` : promptSpecReview(state);
6846
6921
  const reviewPath = path19.join(resolveTaskCwd(t.taskId), "tasks", t.taskId, "spec-review.md");
6847
6922
  let reviewContent = null;
6848
6923
  try {
6849
- reviewContent = fs20.readFileSync(reviewPath, "utf8");
6924
+ reviewContent = fs21.readFileSync(reviewPath, "utf8");
6850
6925
  } catch {
6851
6926
  }
6852
6927
  if (isTemplateUnfilled(reviewContent)) {
@@ -6859,7 +6934,7 @@ ${promptSpecReview(state)}` : promptSpecReview(state);
6859
6934
 
6860
6935
  // src/orchestrator/detach.ts
6861
6936
  import { spawn as spawn3 } from "child_process";
6862
- import fs21 from "fs";
6937
+ import fs22 from "fs";
6863
6938
  import path20 from "path";
6864
6939
  var DETACH_CHILD_FLAG = "CANON_DETACHED";
6865
6940
  var DETACH_DISABLE_FLAG = "CANON_NO_DETACH";
@@ -6896,7 +6971,7 @@ function detachAndExit(options) {
6896
6971
  }
6897
6972
  const primaryDir = options.resolveTaskDir(options.taskIds[0]);
6898
6973
  try {
6899
- fs21.mkdirSync(primaryDir, { recursive: true });
6974
+ fs22.mkdirSync(primaryDir, { recursive: true });
6900
6975
  } catch (error) {
6901
6976
  stderrWrite(`canon: cannot create task dir for log file: ${error.message}
6902
6977
  `);
@@ -6905,7 +6980,7 @@ function detachAndExit(options) {
6905
6980
  const logPath = path20.join(primaryDir, LOG_FILENAME);
6906
6981
  let logFd;
6907
6982
  try {
6908
- logFd = fs21.openSync(logPath, "a");
6983
+ logFd = fs22.openSync(logPath, "a");
6909
6984
  } catch (error) {
6910
6985
  stderrWrite(`canon: cannot open ${logPath}: ${error.message}
6911
6986
  `);
@@ -6918,7 +6993,7 @@ function detachAndExit(options) {
6918
6993
  env: { ...process.env, [DETACH_CHILD_FLAG]: "1" }
6919
6994
  });
6920
6995
  try {
6921
- fs21.closeSync(logFd);
6996
+ fs22.closeSync(logFd);
6922
6997
  } catch {
6923
6998
  }
6924
6999
  if (child.pid == null) {
@@ -6929,8 +7004,8 @@ function detachAndExit(options) {
6929
7004
  for (const taskId of options.taskIds) {
6930
7005
  try {
6931
7006
  const dir = options.resolveTaskDir(taskId);
6932
- fs21.mkdirSync(dir, { recursive: true });
6933
- fs21.writeFileSync(path20.join(dir, PID_FILENAME), `${child.pid}
7007
+ fs22.mkdirSync(dir, { recursive: true });
7008
+ fs22.writeFileSync(path20.join(dir, PID_FILENAME), `${child.pid}
6934
7009
  `, "utf8");
6935
7010
  } catch (error) {
6936
7011
  pidWriteFailures.push({
@@ -6986,7 +7061,7 @@ ${rule}
6986
7061
  function readCanonPid(taskDir) {
6987
7062
  const file = path20.join(taskDir, PID_FILENAME);
6988
7063
  try {
6989
- const raw = fs21.readFileSync(file, "utf8").trim();
7064
+ const raw = fs22.readFileSync(file, "utf8").trim();
6990
7065
  const pid = Number.parseInt(raw, 10);
6991
7066
  return Number.isInteger(pid) && pid > 0 ? pid : null;
6992
7067
  } catch {
@@ -6995,13 +7070,13 @@ function readCanonPid(taskDir) {
6995
7070
  }
6996
7071
  function removeCanonPid(taskDir) {
6997
7072
  try {
6998
- fs21.unlinkSync(path20.join(taskDir, PID_FILENAME));
7073
+ fs22.unlinkSync(path20.join(taskDir, PID_FILENAME));
6999
7074
  } catch {
7000
7075
  }
7001
7076
  }
7002
7077
 
7003
7078
  // src/orchestrator/telemetry-fold.ts
7004
- import fs22 from "fs";
7079
+ import fs23 from "fs";
7005
7080
  import path21 from "path";
7006
7081
  import { randomUUID } from "crypto";
7007
7082
  var LESSONS_SKELETON = "# Lessons Learned\n\n> Distilled cross-task insights. Task lessons fragments are folded here by `canon run --ship`.\n";
@@ -7037,7 +7112,7 @@ function sharedTelemetryDocsTouched(paths) {
7037
7112
  }
7038
7113
  function readOptional(file) {
7039
7114
  try {
7040
- return fs22.readFileSync(file, "utf8");
7115
+ return fs23.readFileSync(file, "utf8");
7041
7116
  } catch (error) {
7042
7117
  if (error.code === "ENOENT") return null;
7043
7118
  throw error;
@@ -7077,22 +7152,22 @@ function applyTelemetryFold(plan) {
7077
7152
  const deleted = [];
7078
7153
  try {
7079
7154
  for (const write of plan.writes) {
7080
- fs22.mkdirSync(path21.dirname(write.target), { recursive: true });
7155
+ fs23.mkdirSync(path21.dirname(write.target), { recursive: true });
7081
7156
  const temp = `${write.target}.${randomUUID()}.canon-fold.tmp`;
7082
- const fd = fs22.openSync(temp, "wx");
7157
+ const fd = fs23.openSync(temp, "wx");
7083
7158
  temps.push(temp);
7084
7159
  try {
7085
- fs22.writeFileSync(fd, write.after, "utf8");
7160
+ fs23.writeFileSync(fd, write.after, "utf8");
7086
7161
  } finally {
7087
- fs22.closeSync(fd);
7162
+ fs23.closeSync(fd);
7088
7163
  }
7089
7164
  }
7090
7165
  for (let index = 0; index < plan.writes.length; index += 1) {
7091
- fs22.renameSync(temps[index], plan.writes[index].target);
7166
+ fs23.renameSync(temps[index], plan.writes[index].target);
7092
7167
  written.push(plan.writes[index]);
7093
7168
  }
7094
7169
  for (const fragment of plan.fragments) {
7095
- fs22.unlinkSync(fragment.path);
7170
+ fs23.unlinkSync(fragment.path);
7096
7171
  deleted.push(fragment);
7097
7172
  }
7098
7173
  } catch (error) {
@@ -7106,17 +7181,17 @@ function applyTelemetryFold(plan) {
7106
7181
  };
7107
7182
  for (const write of written.reverse()) {
7108
7183
  restore(() => {
7109
- if (write.before === null) fs22.unlinkSync(write.target);
7110
- else fs22.writeFileSync(write.target, write.before, "utf8");
7184
+ if (write.before === null) fs23.unlinkSync(write.target);
7185
+ else fs23.writeFileSync(write.target, write.before, "utf8");
7111
7186
  });
7112
7187
  }
7113
- for (const fragment of deleted) restore(() => fs22.writeFileSync(fragment.path, fragment.content, "utf8"));
7188
+ for (const fragment of deleted) restore(() => fs23.writeFileSync(fragment.path, fragment.content, "utf8"));
7114
7189
  if (rollbackErrors.length) throw new Error(`${String(error)}; rollback failed: ${rollbackErrors.join("; ")}`);
7115
7190
  throw error;
7116
7191
  } finally {
7117
7192
  for (const temp of temps) {
7118
7193
  try {
7119
- fs22.unlinkSync(temp);
7194
+ fs23.unlinkSync(temp);
7120
7195
  } catch {
7121
7196
  }
7122
7197
  }
@@ -7260,10 +7335,47 @@ function assertSamePhase(taskIds) {
7260
7335
  }
7261
7336
  return phases[0];
7262
7337
  }
7338
+ function backupIndexFile(cwd) {
7339
+ const indexPath = gitSafeAt(cwd, "rev-parse", "--path-format=absolute", "--git-path", "index");
7340
+ if (!indexPath.ok) return null;
7341
+ const source = indexPath.stdout.trim();
7342
+ const backup = `${source}.canon-autocommit-backup`;
7343
+ try {
7344
+ fs24.copyFileSync(source, backup);
7345
+ } catch {
7346
+ return null;
7347
+ }
7348
+ return {
7349
+ restore() {
7350
+ try {
7351
+ fs24.renameSync(backup, source);
7352
+ return true;
7353
+ } catch {
7354
+ return false;
7355
+ }
7356
+ },
7357
+ discard() {
7358
+ fs24.rmSync(backup, { force: true });
7359
+ }
7360
+ };
7361
+ }
7362
+ function ownedTaskArtifactRows(taskIds) {
7363
+ const owned = /* @__PURE__ */ new Set();
7364
+ const foreign = /* @__PURE__ */ new Set();
7365
+ for (const taskId of taskIds) {
7366
+ for (const file of parseHandoffChangesRows(taskId).files) {
7367
+ if (isPipelineOwnedTaskArtifact(file, [taskId])) owned.add(file);
7368
+ else foreign.add(file);
7369
+ }
7370
+ }
7371
+ for (const file of foreign) owned.delete(file);
7372
+ return owned;
7373
+ }
7263
7374
  function verifyHandoffFilesCommitted(taskIds, cwd, handoffFiles) {
7264
7375
  const baseRef = getBaseBranch2(taskIds);
7265
7376
  const gitIgnoredHandoffFiles = filterGitIgnoredPaths(handoffFiles, cwd);
7266
- const verifiableHandoffFiles = handoffFiles.filter((f) => !gitIgnoredHandoffFiles.has(f));
7377
+ const ownedArtifacts = ownedTaskArtifactRows(taskIds);
7378
+ const verifiableHandoffFiles = handoffFiles.filter((f) => !gitIgnoredHandoffFiles.has(f) && !ownedArtifacts.has(f));
7267
7379
  if (verifiableHandoffFiles.length === 0) {
7268
7380
  return;
7269
7381
  }
@@ -7358,10 +7470,10 @@ function snapshotOutsideArtifacts(cwd, taskIds) {
7358
7470
  const absolute = path22.join(cwd, filePath);
7359
7471
  let fingerprint;
7360
7472
  try {
7361
- const stat = fs23.lstatSync(absolute);
7362
- if (stat.isSymbolicLink()) fingerprint = `symlink:${fs23.readlinkSync(absolute)}`;
7473
+ const stat = fs24.lstatSync(absolute);
7474
+ if (stat.isSymbolicLink()) fingerprint = `symlink:${fs24.readlinkSync(absolute)}`;
7363
7475
  else if (stat.isDirectory()) fingerprint = "dir";
7364
- else if (stat.isFile()) fingerprint = createHash("sha256").update(fs23.readFileSync(absolute)).digest("hex");
7476
+ else if (stat.isFile()) fingerprint = createHash("sha256").update(fs24.readFileSync(absolute)).digest("hex");
7365
7477
  else fingerprint = `other:${stat.mode}`;
7366
7478
  } catch (error) {
7367
7479
  if (error.code !== "ENOENT") throw error;
@@ -7572,10 +7684,12 @@ function autoCommitCode(taskIds, cwd = REPO_ROOT2) {
7572
7684
  const gitIgnoredHandoffFiles = filterGitIgnoredPaths(handoffFiles, cwd);
7573
7685
  const missing = [];
7574
7686
  const baseRefForLog = getBaseBranch(taskIds);
7687
+ const ownedArtifacts = ownedTaskArtifactRows(taskIds);
7575
7688
  for (const f of allHandoffFiles) {
7576
7689
  if (dirtyFiles.has(f)) continue;
7577
7690
  if (gitIgnoredHandoffFiles.has(f)) continue;
7578
- const exists = fs23.existsSync(path22.join(cwd, f));
7691
+ if (ownedArtifacts.has(f)) continue;
7692
+ const exists = fs24.existsSync(path22.join(cwd, f));
7579
7693
  if (!exists) {
7580
7694
  const committed = gitSafeAt(cwd, "log", "--format=%H", "--max-count=1", `${baseRefForLog}..HEAD`, "--", f);
7581
7695
  if (committed.ok && committed.stdout.trim()) {
@@ -7614,10 +7728,19 @@ ${stagedBeforeUnexpected.map((f) => ` ${f}`).join("\n")}
7614
7728
  info("Handoff files are already committed or unchanged \u2014 skipping auto-commit.");
7615
7729
  return;
7616
7730
  }
7617
- const stageable = filterStageablePaths(handoffFiles, cwd);
7731
+ const stageable = filterStageablePaths(
7732
+ handoffFiles.filter((f) => !gitIgnoredHandoffFiles.has(f)),
7733
+ cwd
7734
+ );
7618
7735
  if (stageable.length > 0) {
7736
+ const indexBackup = backupIndexFile(cwd);
7619
7737
  const addResult = gitSafeAt(cwd, "add", "-A", "--", ...stageable);
7620
- if (!addResult.ok) die2(`Failed to stage files: ${addResult.stderr || "unknown error"}`);
7738
+ if (!addResult.ok) {
7739
+ if (/index\.lock/.test(addResult.stderr)) indexBackup?.discard();
7740
+ else if (!indexBackup?.restore()) gitSafeAt(cwd, "reset", "HEAD", "--", ...handoffFiles);
7741
+ die2(`Failed to stage files: ${addResult.stderr || "unknown error"}`);
7742
+ }
7743
+ indexBackup?.discard();
7621
7744
  }
7622
7745
  const preCheck = gitSafeAtRaw(cwd, "status", "--porcelain=v1", "-uall");
7623
7746
  const remaining = preCheck.ok ? findUncoveredTrackedChanges(preCheck.stdout, allHandoffFiles) : [];
@@ -7732,8 +7855,8 @@ function exemptNodeModulesPath(entry, cwd, resolvedWorkspaceDirs) {
7732
7855
  let cwdReal;
7733
7856
  let repoRootReal;
7734
7857
  try {
7735
- cwdReal = fs23.realpathSync(cwd);
7736
- repoRootReal = fs23.realpathSync(REPO_ROOT2);
7858
+ cwdReal = fs24.realpathSync(cwd);
7859
+ repoRootReal = fs24.realpathSync(REPO_ROOT2);
7737
7860
  } catch {
7738
7861
  return null;
7739
7862
  }
@@ -7797,7 +7920,7 @@ function findPullRequestTemplate(repoRoot) {
7797
7920
  path22.join(repoRoot, "PULL_REQUEST_TEMPLATE.md")
7798
7921
  ];
7799
7922
  for (const candidate of candidates) {
7800
- if (fs23.existsSync(candidate)) return candidate;
7923
+ if (fs24.existsSync(candidate)) return candidate;
7801
7924
  }
7802
7925
  return null;
7803
7926
  }
@@ -7817,7 +7940,7 @@ function resolveQaPrBody(taskIds, activeCwd) {
7817
7940
  }
7818
7941
  return {
7819
7942
  kind: "fallback",
7820
- reason: fs23.existsSync(prBodyPath) ? "pr-body.md is still the stub template" : "pr-body.md not found"
7943
+ reason: fs24.existsSync(prBodyPath) ? "pr-body.md is still the stub template" : "pr-body.md not found"
7821
7944
  };
7822
7945
  }
7823
7946
  function commitQaArtifacts(taskIds, cwd) {
@@ -7945,8 +8068,8 @@ function recordPinnedPRNumber(taskIds, prNum) {
7945
8068
  if (alreadyPinned) return;
7946
8069
  for (const taskId of taskIds) {
7947
8070
  const sidecarPath = sidecarPathFor(taskId);
7948
- fs23.mkdirSync(path22.dirname(sidecarPath), { recursive: true });
7949
- fs23.writeFileSync(sidecarPath, String(prNum), "utf8");
8071
+ fs24.mkdirSync(path22.dirname(sidecarPath), { recursive: true });
8072
+ fs24.writeFileSync(sidecarPath, String(prNum), "utf8");
7950
8073
  }
7951
8074
  }
7952
8075
  function reportOrCreatePR(taskIds, branchName, cwd) {
@@ -8179,7 +8302,7 @@ function commitHumanReviewFiles(taskIds, cwd, createPR) {
8179
8302
  die2(`--pr aborted: git error checking base divergence: ${baseDivergenceResult.stderr || "unknown error"}`);
8180
8303
  } else if (!baseDivergenceResult.fetchFailed && baseDivergenceResult.commits.length > 0) {
8181
8304
  if (!cliArgs.allowDivergentBase) {
8182
- die2(verifyBaseDivergenceFromData(baseDivergenceResult.commits));
8305
+ die2(verifyBaseDivergenceFromData(baseDivergenceResult.commits, baseBranch));
8183
8306
  }
8184
8307
  warn2(
8185
8308
  `--allow-divergent-base override: bypassing base-divergence gate. Divergent commits:
@@ -8187,7 +8310,7 @@ function commitHumanReviewFiles(taskIds, cwd, createPR) {
8187
8310
  );
8188
8311
  }
8189
8312
  const docsRefsScript = path22.join(REPO_ROOT2, "scripts", "docs-refs-check.mjs");
8190
- if (fs23.existsSync(docsRefsScript)) {
8313
+ if (fs24.existsSync(docsRefsScript)) {
8191
8314
  const docsRefsResult = spawnSync7("node", [docsRefsScript], {
8192
8315
  cwd,
8193
8316
  stdio: ["ignore", "pipe", "pipe"],
@@ -8487,7 +8610,7 @@ function assertOriginTaskBranchAbsent(branchName, baseBranch) {
8487
8610
  Either the remote branch has commits that were never PR'd, or a prior merge
8488
8611
  failed to delete it. Shipping silently would orphan the remote work.
8489
8612
  Resolve manually:
8490
- - If unmerged work: open + merge a PR (gh pr create --base <base> --head ${branchName} ...).
8613
+ - If unmerged work: open + merge a PR (gh pr create --base ${shellQuoteArg(baseBranch)} --head ${shellQuoteArg(branchName)} ...).
8491
8614
  - If already merged elsewhere: \`git push origin --delete ${branchName}\` and re-run --ship.`
8492
8615
  );
8493
8616
  }
@@ -8519,7 +8642,7 @@ function readSidecarPRNumber(taskId, taskDir = taskDirFor2(taskId)) {
8519
8642
  const sidecarPath = sidecarPathFor(taskId, taskDir);
8520
8643
  let raw;
8521
8644
  try {
8522
- raw = fs23.readFileSync(sidecarPath, "utf8").trim();
8645
+ raw = fs24.readFileSync(sidecarPath, "utf8").trim();
8523
8646
  } catch {
8524
8647
  return null;
8525
8648
  }
@@ -8666,7 +8789,7 @@ function mergeOpenPRsAndPull(taskIds, baseBranch, branchByTaskId) {
8666
8789
  }
8667
8790
  function runPostMergeHook() {
8668
8791
  const hookPath = path22.join(REPO_ROOT2, ".canon/hooks/post-merge.sh");
8669
- if (!fs23.existsSync(hookPath)) return;
8792
+ if (!fs24.existsSync(hookPath)) return;
8670
8793
  info2("Running .canon/hooks/post-merge.sh...");
8671
8794
  const result = runCommand2("bash", [hookPath]);
8672
8795
  if (!result.ok) {
@@ -8694,8 +8817,8 @@ function rewriteArchivedTaskRefs(taskIds) {
8694
8817
  path22.join(REPO_ROOT2, "docs", "task-quality-log.md")
8695
8818
  ];
8696
8819
  for (const filePath of targets) {
8697
- if (!fs23.existsSync(filePath)) continue;
8698
- let content = fs23.readFileSync(filePath, "utf8");
8820
+ if (!fs24.existsSync(filePath)) continue;
8821
+ let content = fs24.readFileSync(filePath, "utf8");
8699
8822
  let changed = false;
8700
8823
  for (const taskId of taskIds) {
8701
8824
  const stale = `tasks/${taskId}/`;
@@ -8706,7 +8829,7 @@ function rewriteArchivedTaskRefs(taskIds) {
8706
8829
  }
8707
8830
  }
8708
8831
  if (changed) {
8709
- fs23.writeFileSync(filePath, content, "utf8");
8832
+ fs24.writeFileSync(filePath, content, "utf8");
8710
8833
  info2(`Updated stale task refs in ${path22.relative(REPO_ROOT2, filePath)}.`);
8711
8834
  }
8712
8835
  }
@@ -8742,7 +8865,7 @@ function classifyAndPreserveSharedDocDirt() {
8742
8865
  if (porcelainCode !== " M") {
8743
8866
  return { relPath, docClass, porcelainCode, headContent: null, workingContent: null };
8744
8867
  }
8745
- const workingContent = fs23.readFileSync(path22.join(REPO_ROOT2, relPath), "utf8");
8868
+ const workingContent = fs24.readFileSync(path22.join(REPO_ROOT2, relPath), "utf8");
8746
8869
  const headResult = gitSafeAtRaw(REPO_ROOT2, "show", `HEAD:${relPath}`);
8747
8870
  return {
8748
8871
  relPath,
@@ -8759,11 +8882,11 @@ function classifyAndPreserveSharedDocDirt() {
8759
8882
  }
8760
8883
  const preserve = verdict.preserve;
8761
8884
  if (preserve.length === 0) return [];
8762
- const backupDir = fs23.mkdtempSync(path22.join(os.tmpdir(), "canon-ship-shared-doc-backup-"));
8885
+ const backupDir = fs24.mkdtempSync(path22.join(os.tmpdir(), "canon-ship-shared-doc-backup-"));
8763
8886
  const preserved = [];
8764
8887
  for (const { relPath, suffix } of preserve) {
8765
8888
  const backupPath = path22.join(backupDir, relPath.replace(/[\\/]/g, "__"));
8766
- fs23.writeFileSync(backupPath, suffix, "utf8");
8889
+ fs24.writeFileSync(backupPath, suffix, "utf8");
8767
8890
  info2(`Preserving uncommitted ${relPath} dirt during --ship; backup: ${backupPath}`);
8768
8891
  const checkoutResult = gitSafe("checkout", "HEAD", "--", relPath);
8769
8892
  if (!checkoutResult.ok) {
@@ -8791,7 +8914,7 @@ function shipTasks(taskIds) {
8791
8914
  path22.join(taskDirForRepoRoot2(taskId), "status.json")
8792
8915
  ];
8793
8916
  for (const candidate of candidates) {
8794
- if (fs23.existsSync(candidate)) return readStatusFromPath(candidate, taskId);
8917
+ if (fs24.existsSync(candidate)) return readStatusFromPath(candidate, taskId);
8795
8918
  }
8796
8919
  const snapshot = taskStatuses.get(taskId);
8797
8920
  if (snapshot) return snapshot;
@@ -8857,8 +8980,8 @@ function shipTasks(taskIds) {
8857
8980
  let preservedSharedDocDirt = [];
8858
8981
  const restorePreservedSharedDocDirt = () => {
8859
8982
  for (const { relPath, suffix, backupPath } of preservedSharedDocDirt) {
8860
- fs23.appendFileSync(path22.join(REPO_ROOT2, relPath), suffix, "utf8");
8861
- fs23.rmSync(backupPath, { force: true });
8983
+ fs24.appendFileSync(path22.join(REPO_ROOT2, relPath), suffix, "utf8");
8984
+ fs24.rmSync(backupPath, { force: true });
8862
8985
  info2(`Re-applied preserved ${relPath} dirt as uncommitted changes; backup removed.`);
8863
8986
  }
8864
8987
  preservedSharedDocDirt = [];
@@ -8885,7 +9008,7 @@ function shipTasks(taskIds) {
8885
9008
  die(`--ship aborted: git error checking base divergence: ${shipBaseDivergenceResult.stderr || "unknown error"}`);
8886
9009
  } else if (!shipBaseDivergenceResult.fetchFailed && shipBaseDivergenceResult.commits.length > 0) {
8887
9010
  if (!cliArgs.allowDivergentBase) {
8888
- die(verifyBaseDivergenceFromData(shipBaseDivergenceResult.commits));
9011
+ die(verifyBaseDivergenceFromData(shipBaseDivergenceResult.commits, baseBranch));
8889
9012
  }
8890
9013
  warn(
8891
9014
  `--allow-divergent-base override: bypassing base-divergence gate at --ship. Divergent commits:
@@ -8952,7 +9075,7 @@ Recovery:
8952
9075
  const localBranchesToDelete = [];
8953
9076
  try {
8954
9077
  const archiveDir = path22.join(TASKS_DIR2, "_archive");
8955
- if (!fs23.existsSync(archiveDir)) fs23.mkdirSync(archiveDir, { recursive: true });
9078
+ if (!fs24.existsSync(archiveDir)) fs24.mkdirSync(archiveDir, { recursive: true });
8956
9079
  for (const taskId of taskIds) {
8957
9080
  const { worktree: hasWorktree } = taskSnapshot(taskId);
8958
9081
  const status = readShipStatus(taskId);
@@ -8963,7 +9086,7 @@ Recovery:
8963
9086
  writeStatusToFile(path22.join(REPO_ROOT2, "tasks", taskId, "status.json"), status);
8964
9087
  const src = taskDirForRepoRoot2(taskId);
8965
9088
  const dest = path22.join(archiveDir, taskId);
8966
- fs23.renameSync(src, dest);
9089
+ fs24.renameSync(src, dest);
8967
9090
  info2(`\u{1F4E6} ${taskId} \u2192 tasks/_archive/${taskId}`);
8968
9091
  const branchName = taskSnapshot(taskId).branch;
8969
9092
  if (branchExistsLocally(branchName)) localBranchesToDelete.push(branchName);
@@ -9017,6 +9140,10 @@ var REROUTE_ADMITTED_PHASES = /* @__PURE__ */ new Set([
9017
9140
  "qa",
9018
9141
  "human_review"
9019
9142
  ]);
9143
+ function rerouteAmendmentHeading(status) {
9144
+ const round = (status.phases.implement?.reroute_count ?? 0) + 1;
9145
+ return { round, heading: round === 1 ? "## Amendment" : `## Amendment Round ${round}` };
9146
+ }
9020
9147
  function describeRerouteEntryPhase(status) {
9021
9148
  const phase = getCurrentPhase(status);
9022
9149
  if (phase === "code_review") {
@@ -9053,14 +9180,14 @@ function rerouteFromHumanReview(taskIds) {
9053
9180
  if (isSpecGapReroute && codeReviewVerdict !== "spec_gap") {
9054
9181
  continue;
9055
9182
  }
9056
- const requiredRound = (status.phases.implement?.reroute_count ?? 0) + 1;
9183
+ const { round: requiredRound, heading: expectedHeading } = rerouteAmendmentHeading(status);
9057
9184
  const result = verifyRerouteAmendment(taskId, requiredRound);
9058
9185
  if (!result.amended) {
9059
9186
  amendmentFailures.push({
9060
9187
  taskId,
9061
9188
  specPath: path22.join(taskDirFor2(taskId), "spec.md"),
9062
9189
  requiredRound,
9063
- expectedHeading: requiredRound === 1 ? "## Amendment" : `## Amendment Round ${requiredRound}`,
9190
+ expectedHeading,
9064
9191
  reason: result.reason
9065
9192
  });
9066
9193
  }
@@ -9248,7 +9375,7 @@ async function runPhase(phase, state) {
9248
9375
  if (phase === "qa") {
9249
9376
  const activeCwd = getActiveCwd(taskIds);
9250
9377
  const qaTemplatePath = state.isBundle ? null : findPullRequestTemplate(activeCwd) ?? findPullRequestTemplate(REPO_ROOT2);
9251
- const resolvedPrTemplate = qaTemplatePath ? fs23.readFileSync(qaTemplatePath, "utf8") : null;
9378
+ const resolvedPrTemplate = qaTemplatePath ? fs24.readFileSync(qaTemplatePath, "utf8") : null;
9252
9379
  return runQaPhase(state, cliArgs.interactive, resolvedPrTemplate);
9253
9380
  }
9254
9381
  if (phase === "human_review") {
@@ -9332,7 +9459,7 @@ var extractCheckedVerdict2 = extractCheckedVerdict;
9332
9459
  function readArtifact(taskId, name) {
9333
9460
  const p = path22.join(taskDirFor2(taskId), name);
9334
9461
  try {
9335
- return fs23.readFileSync(p, "utf8");
9462
+ return fs24.readFileSync(p, "utf8");
9336
9463
  } catch {
9337
9464
  return null;
9338
9465
  }
@@ -9356,7 +9483,7 @@ function checkImplementEvidence(taskId) {
9356
9483
  const sForEvidence = readStatus(taskId);
9357
9484
  if (sForEvidence.worktree === true) {
9358
9485
  const wt = worktreePath(taskId);
9359
- if (fs23.existsSync(wt)) checkRoots.push(wt);
9486
+ if (fs24.existsSync(wt)) checkRoots.push(wt);
9360
9487
  }
9361
9488
  const ignoreCwd = checkRoots[checkRoots.length - 1];
9362
9489
  const gitIgnored = filterGitIgnoredPaths(files, ignoreCwd);
@@ -9368,7 +9495,7 @@ function checkImplementEvidence(taskId) {
9368
9495
  };
9369
9496
  }
9370
9497
  const existingFiles = verifiableFiles.filter(
9371
- (f) => checkRoots.some((root) => fs23.existsSync(path22.join(root, f)))
9498
+ (f) => checkRoots.some((root) => fs24.existsSync(path22.join(root, f)))
9372
9499
  );
9373
9500
  if (existingFiles.length === 0) {
9374
9501
  const evidenceCwd = checkRoots[checkRoots.length - 1];
@@ -9381,6 +9508,7 @@ function checkImplementEvidence(taskId) {
9381
9508
  evidenceCwd,
9382
9509
  "diff",
9383
9510
  "--name-status",
9511
+ "--no-renames",
9384
9512
  `${baseBranch}...HEAD`
9385
9513
  );
9386
9514
  const deletedInCommits = new Set(
@@ -9766,13 +9894,18 @@ async function checkAndRoute(phase, taskIds) {
9766
9894
  case "code_review": {
9767
9895
  const specGapIds = taskIds.filter((_, index) => getVerdict(statuses[index], "code_review") === "spec_gap");
9768
9896
  if (specGapIds.length > 0) {
9897
+ const amendHeadings = specGapIds.map((id) => ({
9898
+ id,
9899
+ heading: rerouteAmendmentHeading(statuses[taskIds.indexOf(id)]).heading
9900
+ }));
9901
+ const fullSendScopeAction = `add them to Affected Files under ${FULL_SEND_SCOPE_AMENDMENT_HEADING} or remove them from the branch`;
9769
9902
  const maxIter = statuses.reduce((max, s) => Math.max(max, getIterations(s)), 0);
9770
- const scopeNote = specGapScopeFiles.length > 0 ? `Full-send files remain outside Affected Files: ${specGapScopeFiles.join(", ")}. A BLESS accepts the verdict but does not amend the spec, so --pr will still reject these files: before blessing, add them to the spec's Affected Files (as an ## Amendment) or remove them from the branch. ` : specGapScopeError !== null ? `Full-send scope could not be verified: the committed diff against the base branch could not be read.
9903
+ const scopeNote = specGapScopeFiles.length > 0 ? `Full-send files remain outside Affected Files: ${specGapScopeFiles.join(", ")}. A BLESS accepts the verdict but does not amend the spec, so --pr will still reject these files: before blessing, ${fullSendScopeAction}. ` : specGapScopeError !== null ? `Full-send scope could not be verified: the committed diff against the base branch could not be read.
9771
9904
  Git error: ${specGapScopeError}
9772
9905
  Scope was not checked. Fix the base branch or repository history before choosing a recovery option below, and verify scope manually before blessing.
9773
9906
  ` : "";
9774
9907
  const reason = `Code review surfaced a spec_gap verdict for task(s): ${specGapIds.join(", ")}. The implementation cannot resolve this \u2014 the root cause is in the spec. ` + scopeNote + `Recovery options (both operate on the full blocked bundle [${taskIds.join(" ")}]):
9775
- FIX: amend spec.md with ## Amendment, then: canon run ${taskIds.join(" ")} --reroute
9908
+ FIX: add ${amendHeadings.map((a) => `${a.heading} to tasks/${a.id}/spec.md`).join("; ")}, then: canon run ${taskIds.join(" ")} --reroute
9776
9909
  BLESS: canon task accept ${taskIds.join(" ")} code_review --reason "<why>"`;
9777
9910
  console.log("");
9778
9911
  console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
@@ -9785,7 +9918,7 @@ Scope was not checked. Fix the base branch or repository history before choosing
9785
9918
  console.log(" Full-send files still outside Affected Files:");
9786
9919
  for (const file of specGapScopeFiles) console.log(` ${file}`);
9787
9920
  console.log(" BLESS does not amend the spec, so --pr will still reject these files.");
9788
- console.log(" Before blessing, add them to Affected Files (## Amendment) or remove them.");
9921
+ console.log(` Before blessing, ${fullSendScopeAction}.`);
9789
9922
  } else if (specGapScopeError !== null) {
9790
9923
  console.log(" Full-send scope could not be verified.");
9791
9924
  console.log(` Git error: ${specGapScopeError}`);
@@ -9795,8 +9928,8 @@ Scope was not checked. Fix the base branch or repository history before choosing
9795
9928
  console.log(" Two recovery options:");
9796
9929
  console.log("");
9797
9930
  console.log(" FIX \u2014 Amend the spec and re-run the full review chain:");
9798
- for (const id of specGapIds) {
9799
- console.log(` # Edit tasks/${id}/spec.md \u2014 add a ## Amendment section`);
9931
+ for (const { id, heading } of amendHeadings) {
9932
+ console.log(` # Edit tasks/${id}/spec.md \u2014 add a ${heading} section`);
9800
9933
  }
9801
9934
  console.log(` canon run ${taskIds.join(" ")} --reroute`);
9802
9935
  console.log("");
@@ -9865,8 +9998,8 @@ function checkDeps(taskIds, skipAgentDeps = false) {
9865
9998
  for (const taskId of taskIds) {
9866
9999
  validateTaskId(taskId);
9867
10000
  const repoRootStatusFile = path22.join(REPO_ROOT2, "tasks", taskId, "status.json");
9868
- const statusFile = cliArgs.ship && fs23.existsSync(repoRootStatusFile) ? repoRootStatusFile : statusFileFor(taskId);
9869
- if (!fs23.existsSync(statusFile)) {
10001
+ const statusFile = cliArgs.ship && fs24.existsSync(repoRootStatusFile) ? repoRootStatusFile : statusFileFor(taskId);
10002
+ if (!fs24.existsSync(statusFile)) {
9870
10003
  die(`No status.json at tasks/${taskId}/status.json \u2014 run canon task new ${taskId} first`);
9871
10004
  }
9872
10005
  }
@@ -9912,7 +10045,7 @@ async function main() {
9912
10045
  let heartbeatStarted = false;
9913
10046
  const earlyHeartbeatResolver = (id) => {
9914
10047
  const repoRootStatusFile = path22.join(REPO_ROOT2, "tasks", id, "status.json");
9915
- return path22.dirname(cliArgs.ship && fs23.existsSync(repoRootStatusFile) ? repoRootStatusFile : statusFileFor(id));
10048
+ return path22.dirname(cliArgs.ship && fs24.existsSync(repoRootStatusFile) ? repoRootStatusFile : statusFileFor(id));
9916
10049
  };
9917
10050
  if (!cliArgs.ship && !cliArgs.dryRun) {
9918
10051
  guardConcurrentRun(cliArgs.taskIds, earlyHeartbeatResolver);