canon-ai 3.16.0 → 3.18.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.
package/dist/cli/index.js CHANGED
@@ -1,8 +1,46 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/orchestrator/docs-freshness.ts
4
- import fs8 from "fs";
5
- import path7 from "path";
3
+ // src/lib/pipeline-policy.ts
4
+ var SIZE_ORDER = ["XS", "S", "M", "L", "XL"];
5
+ function isPlanCombined(task) {
6
+ return task.task_size === "XS" && !(task.delicate ?? false);
7
+ }
8
+ var AGENT_ROLES = ["author", "spec_reviewer", "implementer", "reviewer", "cold_reviewer", "qa"];
9
+ var MIXED_ROLE_ASSIGNMENT = {
10
+ author: "claude",
11
+ spec_reviewer: "codex",
12
+ implementer: "codex",
13
+ reviewer: "claude",
14
+ cold_reviewer: "codex",
15
+ qa: "claude"
16
+ };
17
+ function roleBackendId(role, assignment) {
18
+ return assignment[role];
19
+ }
20
+ function requiredAgentBackends(assignment) {
21
+ return [...new Set(AGENT_ROLES.map((role) => roleBackendId(role, assignment)))];
22
+ }
23
+ var PROVIDERS = ["mixed", "claude"];
24
+ var CLAUDE_ROLE_ASSIGNMENT = {
25
+ author: "claude",
26
+ spec_reviewer: "claude",
27
+ implementer: "claude",
28
+ reviewer: "claude",
29
+ cold_reviewer: "claude",
30
+ qa: "claude"
31
+ };
32
+ function parseProvider(value) {
33
+ if (value === "mixed" || value === "claude") return value;
34
+ throw new Error(`Invalid provider '${String(value)}'. Accepted values: mixed, claude.${value === "codex" ? " Codex-only mode is not supported yet." : ""}`);
35
+ }
36
+ function roleAssignmentFor(provider) {
37
+ return provider === "claude" ? CLAUDE_ROLE_ASSIGNMENT : MIXED_ROLE_ASSIGNMENT;
38
+ }
39
+
40
+ // src/orchestrator/env.ts
41
+ import fs3 from "fs";
42
+ import path2 from "path";
43
+ import { fileURLToPath } from "url";
6
44
 
7
45
  // src/orchestrator/cli.ts
8
46
  import fs from "fs";
@@ -75,7 +113,7 @@ var RUN_USAGE = [
75
113
  " Bundle: canon run fix-hover-state dark-tokens empty-cta",
76
114
  "",
77
115
  " Bundle mode runs all tasks together per phase (one agent session each).",
78
- " Fast tier (XS, non-delicate only) skips Codex spec review. Full tier (any S/M/L/XL",
116
+ " Fast tier (XS, non-delicate only) skips the spec-review phase. Full tier (any S/M/L/XL",
79
117
  " or delicate task) runs the complete pipeline \u2014 any such task pulls the entire",
80
118
  " bundle to full tier.",
81
119
  "",
@@ -100,7 +138,8 @@ var RUN_USAGE = [
100
138
  " --force Acknowledge high-commitment combinations and bypass",
101
139
  " explicit safety gates where documented (currently:",
102
140
  " --full-send on delicate tasks, reroute amendment gate,",
103
- " base-drift gate, and dirty REPO_ROOT worktree-start gate).",
141
+ " base-drift gate, dirty REPO_ROOT worktree-start gate,",
142
+ " and spec manifest pre-flight before plan/implement).",
104
143
  " --allow-divergent-base",
105
144
  " At --push, --pr, and --ship: bypass only the commit-divergence",
106
145
  " block when local <base> has commits not yet on origin/<base>.",
@@ -108,7 +147,8 @@ var RUN_USAGE = [
108
147
  " At --pr/--push, does not apply when origin has no <base> branch.",
109
148
  " Does NOT bypass the base-drift gate; use --force for that.",
110
149
  " Independent of --force \u2014 both may be needed to pass both gates.",
111
- " --ship Merge the open PR (gh pr merge --squash), delete its remote branch, tear",
150
+ " --ship Merge the open PR with the configured method (squash by default; set",
151
+ " ship.merge_method in .canon/config.json), delete its remote branch, tear",
112
152
  " down the worktree, archive the task dir, and pull the base branch. Run",
113
153
  " after the PR is approved \u2014 do NOT merge the PR manually first. If you",
114
154
  " already merged externally, --ship detects the merged state and resumes",
@@ -123,7 +163,7 @@ var RUN_USAGE = [
123
163
  " Full-tier tasks (S/M/L/XL or delicate) re-enter at spec_review; fast-tier",
124
164
  " tasks (XS) re-enter at implement.",
125
165
  " Feedback channel: append a new section to tasks/<id>/spec.md describing",
126
- " what to address. Codex re-reads spec.md only \u2014 additions to review.md",
166
+ " what to address. The implementer re-reads spec.md only \u2014 additions to review.md",
127
167
  " or PR comments are NOT consulted on reroute.",
128
168
  " Pre-flight requires `## Amendment` on round 1 or `## Amendment Round N`",
129
169
  " on round 2+. Bypass with --force. See docs/pipeline-orchestrator.md",
@@ -150,15 +190,6 @@ function warn(message) {
150
190
  console.error(`\u26A0\uFE0F ${message}`);
151
191
  }
152
192
 
153
- // src/orchestrator/worktree.ts
154
- import fs7 from "fs";
155
- import path6 from "path";
156
-
157
- // src/orchestrator/env.ts
158
- import fs3 from "fs";
159
- import path2 from "path";
160
- import { fileURLToPath } from "url";
161
-
162
193
  // src/lib/project-root.ts
163
194
  import { spawnSync } from "child_process";
164
195
  import fs2 from "fs";
@@ -218,6 +249,20 @@ function isTaskEntry(tasksDirPath, name) {
218
249
  // src/orchestrator/env.ts
219
250
  var __filename = fileURLToPath(import.meta.url);
220
251
  var __dirname = path2.dirname(__filename);
252
+ function parseMaxReviewLoops(raw) {
253
+ if (!raw) return null;
254
+ const trimmed = raw.trim();
255
+ if (!/^-?\d+$/.test(trimmed)) {
256
+ warn(`Invalid MAX_REVIEW_LOOPS value "${raw}"; using the size-aware default.`);
257
+ return null;
258
+ }
259
+ const parsed = Number(trimmed);
260
+ if (!Number.isInteger(parsed) || parsed < 0) {
261
+ warn(`Invalid MAX_REVIEW_LOOPS value "${raw}"; using the size-aware default.`);
262
+ return null;
263
+ }
264
+ return parsed;
265
+ }
221
266
  var REPO_ROOT = resolveProjectRoot();
222
267
  var TASKS_DIR = path2.join(REPO_ROOT, "tasks");
223
268
  var WORKTREES_ROOT = process.env.CANON_WORKTREES_ROOT ? path2.resolve(REPO_ROOT, process.env.CANON_WORKTREES_ROOT) : path2.resolve(REPO_ROOT, ".canon/worktrees");
@@ -239,6 +284,37 @@ var config = {
239
284
  maxContextBytes: Number.parseInt(process.env.MAX_CONTEXT_BYTES ?? String(64 * 1024), 10)
240
285
  };
241
286
 
287
+ // src/orchestrator/policy.ts
288
+ var config2 = {
289
+ claudeModelSpecReview: process.env.CLAUDE_MODEL_SPEC_REVIEW ?? null,
290
+ claudeModelImplement: process.env.CLAUDE_MODEL_IMPLEMENT ?? null,
291
+ claudeModelSpec: process.env.CLAUDE_MODEL_SPEC ?? null,
292
+ claudeModelPlan: process.env.CLAUDE_MODEL_PLAN ?? null,
293
+ claudeModelReview: process.env.CLAUDE_MODEL_REVIEW ?? null,
294
+ claudeModelReviewLarge: process.env.CLAUDE_MODEL_REVIEW_LARGE ?? null,
295
+ claudeModelQa: process.env.CLAUDE_MODEL_QA ?? null,
296
+ claudeModelLight: process.env.CLAUDE_MODEL_LIGHT || null,
297
+ claudeModelStrong: process.env.CLAUDE_MODEL_STRONG || null,
298
+ claudeModelLegacy: process.env.CLAUDE_MODEL ?? null,
299
+ codexModelMini: process.env.CODEX_MODEL_MINI ?? process.env.CODEX_MODEL_DEFAULT ?? "gpt-6-luna",
300
+ codexModelFull: process.env.CODEX_MODEL_FULL ?? process.env.CODEX_MODEL_DELICATE ?? "gpt-6.1-sol",
301
+ maxReviewLoops: parseMaxReviewLoops(process.env.MAX_REVIEW_LOOPS),
302
+ claudeBudget: process.env.CLAUDE_BUDGET ?? null
303
+ };
304
+ var PROVIDER_SETTING_NAME = "CANON_PROVIDER";
305
+ function resolveProviderSetting() {
306
+ const value = process.env[PROVIDER_SETTING_NAME];
307
+ return value === void 0 || value === "" ? "mixed" : parseProvider(value);
308
+ }
309
+
310
+ // src/orchestrator/docs-freshness.ts
311
+ import fs8 from "fs";
312
+ import path7 from "path";
313
+
314
+ // src/orchestrator/worktree.ts
315
+ import fs7 from "fs";
316
+ import path6 from "path";
317
+
242
318
  // src/orchestrator/git.ts
243
319
  import { spawnSync as spawnSync3 } from "child_process";
244
320
  import fs6 from "fs";
@@ -515,21 +591,24 @@ function statusFileFor(taskId) {
515
591
  function validateBranchField(value, taskId, fieldName) {
516
592
  if (value === void 0) return;
517
593
  if (typeof value !== "string") {
518
- throw new Error(`Invalid ${fieldName} in task '${taskId}': expected string, got ${typeof value}. Edit status.json.`);
594
+ throw new Error(`Invalid ${fieldName} in task '${taskId}': expected string, got ${typeof value}. ${statusFieldFix(taskId, fieldName)}`);
519
595
  }
520
596
  const trimmed = value.trim();
521
597
  if (trimmed === "") return;
522
598
  if (trimmed.startsWith("-")) {
523
- throw new Error(`Invalid ${fieldName} in task '${taskId}': '${value}' looks like a flag, not a branch name. Edit status.json.`);
599
+ throw new Error(`Invalid ${fieldName} in task '${taskId}': '${value}' looks like a flag, not a branch name. ${statusFieldFix(taskId, fieldName)}`);
524
600
  }
525
601
  if (/[\x00-\x1F\x7F\s:]/.test(trimmed)) {
526
- throw new Error(`Invalid ${fieldName} in task '${taskId}': '${value}' contains control chars, whitespace, or refspec separator. Edit status.json.`);
602
+ throw new Error(`Invalid ${fieldName} in task '${taskId}': '${value}' contains control chars, whitespace, or refspec separator. ${statusFieldFix(taskId, fieldName)}`);
527
603
  }
528
604
  }
605
+ function statusFieldFix(taskId, fieldName) {
606
+ return fieldName === "base_branch" ? `Fix it with \`canon task set ${taskId} base_branch <branch>\` (only before the task branches), or ask the human to correct it in status.json.` : `Ask the human to correct ${fieldName} in status.json.`;
607
+ }
529
608
  function validateNonNegativeInt(value, taskId, fieldPath) {
530
609
  if (value === void 0) return;
531
610
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
532
- throw new Error(`Invalid ${fieldPath} in task '${taskId}': expected non-negative integer, got ${JSON.stringify(value)}. Edit status.json.`);
611
+ throw new Error(`Invalid ${fieldPath} in task '${taskId}': expected non-negative integer, got ${JSON.stringify(value)}. ${statusFieldFix(taskId, fieldPath)}`);
533
612
  }
534
613
  }
535
614
  function validateStatus(taskId, parsed) {
@@ -569,6 +648,31 @@ function isRerouteAdmitted(status) {
569
648
  const codeReview = status.phases.code_review;
570
649
  return implementStatus === "in_progress" || implementStatus === "blocked" || codeReview?.status === "blocked" || currentLoopReviewRounds(codeReview) > 0 || currentLoopCount(codeReview?.preflight_rejections_current_loop) > 0;
571
650
  }
651
+ var LEGACY_SESSION_SLOTS = {
652
+ author: "claude_spec",
653
+ spec_reviewer: "codex_spec_review",
654
+ implementer: "codex",
655
+ reviewer: "claude_review"
656
+ };
657
+ function clearSessionPair(status, slot) {
658
+ delete status.session_backends?.[slot];
659
+ if (!status.sessions) return;
660
+ delete status.sessions[slot];
661
+ delete status.sessions[LEGACY_SESSION_SLOTS[slot]];
662
+ }
663
+ function storedSessionBackend(status, slot) {
664
+ return status.session_backends?.[slot] ?? MIXED_ROLE_ASSIGNMENT[slot];
665
+ }
666
+ function clearMismatchedSessions(status, assignment) {
667
+ const cleared = [];
668
+ for (const slot of Object.keys(LEGACY_SESSION_SLOTS)) {
669
+ if ((status.sessions?.[slot] || status.sessions?.[LEGACY_SESSION_SLOTS[slot]]) && storedSessionBackend(status, slot) !== assignment[slot]) {
670
+ clearSessionPair(status, slot);
671
+ cleared.push(slot);
672
+ }
673
+ }
674
+ return cleared;
675
+ }
572
676
 
573
677
  // src/orchestrator/git.ts
574
678
  function gitSafeAt(cwd, ...args2) {
@@ -605,6 +709,7 @@ var PIPELINE_TELEMETRY_FILES = [
605
709
 
606
710
  // src/orchestrator/docs-freshness.ts
607
711
  var DOCS_FRESHNESS_CONFIG_PATH = ".canon/config.json";
712
+ var SHIP_MERGE_METHODS = ["squash", "rebase", "merge"];
608
713
  var DEFAULT_PROTECTED_DOCS = [
609
714
  "docs/architecture.md",
610
715
  "docs/codebase-map.md",
@@ -646,12 +751,27 @@ function parseDocsFreshnessConfig(raw) {
646
751
  return invalid(`not valid JSON (${error instanceof Error ? error.message : String(error)}).`);
647
752
  }
648
753
  if (!isObject(value)) return invalid("the top level must be a JSON object.");
649
- const unknownKeys = Object.keys(value).filter((key) => key !== "docs_freshness");
650
- if (!Object.hasOwn(value, "docs_freshness")) return { ok: true, source: "file", config: null, unknownKeys };
754
+ const unknownKeys = Object.keys(value).filter((key) => !["docs_freshness", "ship"].includes(key));
755
+ let shipMergeMethod = "squash";
756
+ if (Object.hasOwn(value, "ship")) {
757
+ const ship = value.ship;
758
+ if (!isObject(ship)) {
759
+ return invalid('"ship.merge_method" must be "squash", "rebase" or "merge" ("ship" must be an object).');
760
+ }
761
+ unknownKeys.push(...Object.keys(ship).filter((key) => key !== "merge_method").map((key) => `ship.${key}`));
762
+ if (Object.hasOwn(ship, "merge_method")) {
763
+ const method = ship.merge_method;
764
+ if (typeof method !== "string" || !SHIP_MERGE_METHODS.includes(method)) {
765
+ return invalid('"ship.merge_method" must be "squash", "rebase" or "merge".');
766
+ }
767
+ shipMergeMethod = method;
768
+ }
769
+ }
770
+ if (!Object.hasOwn(value, "docs_freshness")) return { ok: true, source: "file", config: null, shipMergeMethod, unknownKeys };
651
771
  const docs = value.docs_freshness;
652
772
  if (!isObject(docs)) return invalid('"docs_freshness" must be an object.');
653
773
  unknownKeys.push(...Object.keys(docs).filter((key) => !["protected", "paths", "flag_only"].includes(key)).map((key) => `docs_freshness.${key}`));
654
- const config2 = {};
774
+ const config3 = {};
655
775
  for (const key of ["protected", "flag_only"]) {
656
776
  if (!Object.hasOwn(docs, key)) continue;
657
777
  const list = docs[key];
@@ -660,7 +780,7 @@ function parseDocsFreshnessConfig(raw) {
660
780
  const problem = docProblem(doc, `docs_freshness.${key}`);
661
781
  if (problem) return invalid(problem);
662
782
  }
663
- config2[key === "protected" ? "protected" : "flagOnly"] = list.map((doc) => path7.posix.normalize(doc.replaceAll("\\", "/")));
783
+ config3[key === "protected" ? "protected" : "flagOnly"] = list.map((doc) => path7.posix.normalize(doc.replaceAll("\\", "/")));
664
784
  }
665
785
  if (Object.hasOwn(docs, "paths")) {
666
786
  if (!isObject(docs.paths)) return invalid('"docs_freshness.paths" must be an object mapping globs to arrays of doc paths.');
@@ -676,15 +796,15 @@ function parseDocsFreshnessConfig(raw) {
676
796
  }
677
797
  mappings[glob] = list.map((doc) => path7.posix.normalize(doc.replaceAll("\\", "/")));
678
798
  }
679
- config2.paths = mappings;
799
+ config3.paths = mappings;
680
800
  }
681
- return { ok: true, source: "file", config: config2, unknownKeys };
801
+ return { ok: true, source: "file", config: config3, shipMergeMethod, unknownKeys };
682
802
  }
683
803
  function loadDocsFreshnessConfig(root) {
684
804
  try {
685
805
  return parseDocsFreshnessConfig(fs8.readFileSync(path7.join(root, DOCS_FRESHNESS_CONFIG_PATH), "utf8"));
686
806
  } catch (error) {
687
- if (isObject(error) && error.code === "ENOENT") return { ok: true, source: "defaults", config: null, unknownKeys: [] };
807
+ if (isObject(error) && error.code === "ENOENT") return { ok: true, source: "defaults", config: null, shipMergeMethod: "squash", unknownKeys: [] };
688
808
  return invalid(`could not be read (${error instanceof Error ? error.message : String(error)}).`);
689
809
  }
690
810
  }
@@ -755,11 +875,11 @@ function matchesDocsGlob(pattern, filePath) {
755
875
  };
756
876
  return match(0, 0);
757
877
  }
758
- function resolveDocsFreshness(config2, diff) {
759
- const protectedDocs = [...new Set(config2?.protected ?? DEFAULT_PROTECTED_DOCS)];
760
- const mappings = Object.entries(config2?.paths ?? {});
878
+ function resolveDocsFreshness(config3, diff) {
879
+ const protectedDocs = [...new Set(config3?.protected ?? DEFAULT_PROTECTED_DOCS)];
880
+ const mappings = Object.entries(config3?.paths ?? {});
761
881
  const mapped = [...new Set(mappings.flatMap(([, docs]) => [...docs]))];
762
- const flagOnly = [...new Set(config2?.flagOnly ?? [])];
882
+ const flagOnly = [...new Set(config3?.flagOnly ?? [])];
763
883
  const prompt = new Set(protectedDocs);
764
884
  const paths = diff?.filter((file) => !isPipelinePath(file)) ?? [];
765
885
  for (const [glob, docs] of mappings) {
@@ -911,6 +1031,117 @@ function parseTableH3(markdown, sectionHeading) {
911
1031
  }
912
1032
  return rows;
913
1033
  }
1034
+ function listContentColumn(lines, index, indent) {
1035
+ if (indent === 0) return 0;
1036
+ for (let i = index - 1; i >= 0; i -= 1) {
1037
+ const line = lines[i];
1038
+ if (line.trim() === "") continue;
1039
+ const marker = /^( *)([-*+]|\d{1,9}[.)])( +)\S/.exec(line);
1040
+ if (marker) {
1041
+ const column = marker[1].length + marker[2].length + marker[3].length;
1042
+ if (column <= indent) return column;
1043
+ }
1044
+ if (line.length - line.trimStart().length < indent) return 0;
1045
+ }
1046
+ return 0;
1047
+ }
1048
+ function visibleMarkdownLines(markdown) {
1049
+ const hidden = [];
1050
+ let unclosed = null;
1051
+ let comment = false;
1052
+ let fence = null;
1053
+ const source = markdown.split("\n");
1054
+ const lines = source.map((line, index) => {
1055
+ if (fence) {
1056
+ hidden.push(true);
1057
+ const close = /^([ \t]*)(`{3,}|~{3,})\s*$/.exec(line);
1058
+ if (close && close[1].length <= fence.container + 3 && close[2][0] === fence.char && close[2].length >= fence.length) {
1059
+ fence = null;
1060
+ unclosed = null;
1061
+ }
1062
+ return line;
1063
+ }
1064
+ const opener = !comment && /^([ \t]{0,3})(`{3,}|~{3,})/.exec(line);
1065
+ if (opener && (opener[2][0] !== "`" || !line.slice(opener[0].length).includes("`"))) {
1066
+ fence = { char: opener[2][0], length: opener[2].length, container: listContentColumn(source, index, opener[1].length) };
1067
+ unclosed = { kind: "fence", line: index + 1 };
1068
+ hidden.push(true);
1069
+ return line;
1070
+ }
1071
+ let visible = "";
1072
+ let i = 0;
1073
+ while (i < line.length) {
1074
+ if (comment) {
1075
+ const close = line.indexOf("-->", i);
1076
+ if (close === -1) break;
1077
+ comment = false;
1078
+ unclosed = null;
1079
+ i = close + 3;
1080
+ } else if (line.startsWith("<!-->", i) || line.startsWith("<!--->", i)) {
1081
+ i += line[i + 4] === ">" ? 5 : 6;
1082
+ } else if (line.startsWith("<!--", i) && (/^ {0,3}$/.test(line.slice(0, i)) || line.indexOf("-->", i + 4) !== -1)) {
1083
+ comment = true;
1084
+ unclosed = { kind: "comment", line: index + 1 };
1085
+ i += 4;
1086
+ } else if (line[i] === "`") {
1087
+ const run = /^`+/.exec(line.slice(i))[0];
1088
+ const rest = line.slice(i + run.length);
1089
+ const close = [...rest.matchAll(/`+/g)].find((match) => match[0].length === run.length);
1090
+ const end = close ? i + run.length + close.index + run.length : i + run.length;
1091
+ visible += line.slice(i, end);
1092
+ i = end;
1093
+ } else {
1094
+ visible += line[i];
1095
+ i += 1;
1096
+ }
1097
+ }
1098
+ hidden.push(visible.trim() === "");
1099
+ return visible;
1100
+ });
1101
+ return { lines, hidden, unclosed };
1102
+ }
1103
+ function scanTableBlocks(lines, hidden, start, end) {
1104
+ const blocks = [];
1105
+ let i = start;
1106
+ while (i < end) {
1107
+ if (hidden[i] || !lines[i].trimStart().startsWith("|")) {
1108
+ i += 1;
1109
+ continue;
1110
+ }
1111
+ const header = { line: i + 1, cells: normalizeCells(lines[i]) };
1112
+ i += 1;
1113
+ if (header.cells.length === 0) continue;
1114
+ const hasSeparator = i < end && !hidden[i] && isSeparatorRow(normalizeCells(lines[i]));
1115
+ if (hasSeparator) i += 1;
1116
+ const rows = [];
1117
+ while (i < end && !hidden[i] && lines[i].trimStart().startsWith("|")) {
1118
+ const cells = normalizeCells(lines[i]);
1119
+ if (!isSeparatorRow(cells)) rows.push({ line: i + 1, cells });
1120
+ i += 1;
1121
+ }
1122
+ blocks.push({ header, hasSeparator, rows });
1123
+ }
1124
+ return blocks;
1125
+ }
1126
+ function scanSpecManifest(markdown) {
1127
+ const { lines, hidden, unclosed } = visibleMarkdownLines(markdown);
1128
+ const headings = [];
1129
+ lines.forEach((line, index) => {
1130
+ const match = !hidden[index] && /^(#{1,6})\s/.exec(line);
1131
+ if (match) headings.push({ index, line: index + 1, level: match[1].length, text: line.trimEnd(), sectionEnd: lines.length });
1132
+ });
1133
+ headings.forEach((heading, i) => {
1134
+ heading.sectionEnd = headings.slice(i + 1).find((next) => next.level <= Math.max(3, heading.level))?.index ?? lines.length;
1135
+ });
1136
+ const sections = [];
1137
+ headings.forEach((h2, i) => {
1138
+ if (h2.level !== 2 || !/^## (?:Design|Amendment)\b/.test(h2.text)) return;
1139
+ const end = headings.slice(i + 1).find((next) => next.level <= 2)?.index ?? lines.length;
1140
+ const affectedFiles = headings.filter((h) => h.index > h2.index && h.index < end && h.text === "### Affected Files").map((heading) => ({ heading, blocks: scanTableBlocks(lines, hidden, heading.index + 1, Math.min(end, heading.sectionEnd)) }));
1141
+ sections.push({ h2, kind: /^## Design\b/.test(h2.text) ? "design" : "amendment", affectedFiles });
1142
+ });
1143
+ return { lines, hidden, headings, sections, unclosed };
1144
+ }
914
1145
  function parseTable(markdown, sectionHeading) {
915
1146
  const lines = markdown.split("\n");
916
1147
  const headingIndex = lines.findIndex((line) => isSectionHeading(line, sectionHeading));
@@ -1461,11 +1692,12 @@ function upsertCanonBlock(content, block) {
1461
1692
 
1462
1693
  // src/cli/deps.ts
1463
1694
  import { spawnSync as spawnSync4 } from "child_process";
1464
- var HARD_DEPS = [
1465
- { cmd: "git", installHint: "https://git-scm.com/downloads" },
1466
- { cmd: "claude", installHint: "npm install -g @anthropic-ai/claude-code" },
1467
- { cmd: "codex", installHint: "npm install -g @openai/codex" }
1468
- ];
1695
+ function hardDeps(provider) {
1696
+ return [
1697
+ { cmd: "git", installHint: "https://git-scm.com/downloads" },
1698
+ ...requiredAgentBackends(roleAssignmentFor(provider)).map((cmd) => ({ cmd, installHint: cmd === "claude" ? "npm install -g @anthropic-ai/claude-code" : "npm install -g @openai/codex" }))
1699
+ ];
1700
+ }
1469
1701
  var SOFT_DEPS = [
1470
1702
  { cmd: "gh", installHint: "brew install gh && gh auth login (required for --pr / --push)" }
1471
1703
  ];
@@ -1473,8 +1705,15 @@ function isAvailable(cmd) {
1473
1705
  const result = spawnSync4("which", [cmd], { stdio: "ignore" });
1474
1706
  return result.status === 0;
1475
1707
  }
1476
- function checkDeps() {
1477
- const missing = HARD_DEPS.filter((d) => !isAvailable(d.cmd));
1708
+ function checkDeps(available = isAvailable, provider) {
1709
+ let resolved;
1710
+ try {
1711
+ resolved = provider ?? resolveProviderSetting();
1712
+ } catch (error) {
1713
+ console.error(error instanceof Error ? error.message : String(error));
1714
+ process.exit(1);
1715
+ }
1716
+ const missing = hardDeps(resolved).filter((d) => !available(d.cmd));
1478
1717
  if (missing.length > 0) {
1479
1718
  console.error("canon init requires the following tools to be installed:\n");
1480
1719
  for (const dep of missing) {
@@ -1484,7 +1723,7 @@ function checkDeps() {
1484
1723
  console.error("");
1485
1724
  process.exit(1);
1486
1725
  }
1487
- const softMissing = SOFT_DEPS.filter((d) => !isAvailable(d.cmd));
1726
+ const softMissing = SOFT_DEPS.filter((d) => !available(d.cmd));
1488
1727
  for (const dep of softMissing) {
1489
1728
  console.warn(` \u26A0 ${dep.cmd} not found \u2014 needed later: ${dep.installHint}`);
1490
1729
  }
@@ -1568,6 +1807,98 @@ var RECOMMENDED_ALLOW = [
1568
1807
  "Skill(canon-sweep)",
1569
1808
  "Skill(canon-sweep:*)"
1570
1809
  ];
1810
+ var GUARD_HOOK_PATH = ".claude/hooks/canon-guard.mjs";
1811
+ var GUARD_HOOK_TOOLS = ["Bash", "Edit", "Write", "MultiEdit"];
1812
+ var RECOMMENDED_GUARD_HOOKS = {
1813
+ hooks: {
1814
+ PreToolUse: [{
1815
+ matcher: "Bash|Edit|Write|MultiEdit",
1816
+ hooks: [{
1817
+ type: "command",
1818
+ command: 'test -f "$CLAUDE_PROJECT_DIR/.claude/hooks/canon-guard.mjs" && node "$CLAUDE_PROJECT_DIR/.claude/hooks/canon-guard.mjs" || true',
1819
+ timeout: 10
1820
+ }]
1821
+ }]
1822
+ }
1823
+ };
1824
+ function isRecord(value) {
1825
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1826
+ }
1827
+ function readGuardHookTools(settingsPath) {
1828
+ if (!existsSync(settingsPath)) return /* @__PURE__ */ new Set();
1829
+ let parsed;
1830
+ try {
1831
+ parsed = JSON.parse(readFileSync(settingsPath, "utf8"));
1832
+ } catch {
1833
+ return /* @__PURE__ */ new Set();
1834
+ }
1835
+ if (!isRecord(parsed) || !isRecord(parsed.hooks)) return /* @__PURE__ */ new Set();
1836
+ const preToolUse = parsed.hooks.PreToolUse;
1837
+ const entries = Array.isArray(preToolUse) ? preToolUse : preToolUse === void 0 ? [] : [preToolUse];
1838
+ const tools = /* @__PURE__ */ new Set();
1839
+ for (const rawEntry of entries) {
1840
+ if (!isRecord(rawEntry)) continue;
1841
+ const innerHooks = Array.isArray(rawEntry.hooks) ? rawEntry.hooks : [];
1842
+ const runsGuard = innerHooks.some(
1843
+ (hook) => isRecord(hook) && typeof hook.command === "string" && hook.command.includes("canon-guard.mjs")
1844
+ );
1845
+ if (!runsGuard) continue;
1846
+ const matcher = rawEntry.matcher;
1847
+ if (typeof matcher !== "string" || matcher.trim() === "" || matcher.trim() === "*") {
1848
+ GUARD_HOOK_TOOLS.forEach((tool) => tools.add(tool));
1849
+ continue;
1850
+ }
1851
+ const names = matcher.replace(/[\^$()]/g, "").split("|").map((name) => name.trim());
1852
+ for (const tool of GUARD_HOOK_TOOLS) {
1853
+ if (names.includes(tool)) tools.add(tool);
1854
+ }
1855
+ }
1856
+ return tools;
1857
+ }
1858
+ function guardHookRegistration(cwd) {
1859
+ const tools = /* @__PURE__ */ new Set();
1860
+ for (const settingsPath of [
1861
+ join(cwd, ".claude", "settings.json"),
1862
+ join(cwd, ".claude", "settings.local.json")
1863
+ ]) {
1864
+ readGuardHookTools(settingsPath).forEach((tool) => tools.add(tool));
1865
+ }
1866
+ if (GUARD_HOOK_TOOLS.every((tool) => tools.has(tool))) return "full";
1867
+ return tools.size > 0 ? "partial" : "none";
1868
+ }
1869
+ function checkGuardHook(cwd) {
1870
+ const scriptPath = join(cwd, GUARD_HOOK_PATH);
1871
+ let scriptPresent = false;
1872
+ try {
1873
+ scriptPresent = statSync(scriptPath).isFile();
1874
+ } catch {
1875
+ }
1876
+ const registration = guardHookRegistration(cwd);
1877
+ if (scriptPresent && registration === "full") {
1878
+ return { label: GUARD_HOOK_PATH, status: "pass", detail: "registered for Bash, Edit, Write and MultiEdit" };
1879
+ }
1880
+ const missingTools = GUARD_HOOK_TOOLS.filter((tool) => !readGuardHookToolsFromProject(cwd).has(tool));
1881
+ const problems = [];
1882
+ if (!scriptPresent) problems.push("script missing \u2014 run `canon upgrade` to restore it");
1883
+ if (registration === "none") problems.push("not registered in `.claude/settings.json` or `.claude/settings.local.json`");
1884
+ if (registration === "partial") problems.push(`registered, but its matcher misses ${missingTools.join(", ")} \u2014 use matcher Bash|Edit|Write|MultiEdit`);
1885
+ return {
1886
+ label: GUARD_HOOK_PATH,
1887
+ status: "warn",
1888
+ detail: `${problems.join("; ")} \u2014 merge this snippet into your Claude Code settings (see the canon-ai README "Guard hooks"):
1889
+ ${JSON.stringify(RECOMMENDED_GUARD_HOOKS, null, 2)}`
1890
+ };
1891
+ }
1892
+ function readGuardHookToolsFromProject(cwd) {
1893
+ const tools = /* @__PURE__ */ new Set();
1894
+ for (const settingsPath of [
1895
+ join(cwd, ".claude", "settings.json"),
1896
+ join(cwd, ".claude", "settings.local.json")
1897
+ ]) {
1898
+ readGuardHookTools(settingsPath).forEach((tool) => tools.add(tool));
1899
+ }
1900
+ return tools;
1901
+ }
1571
1902
  var RECOMMENDED_NUDGE = [
1572
1903
  "This project uses canon, a spec-first multi-agent pipeline.",
1573
1904
  "Route new features / fixes / refactors through the canon skills.",
@@ -1694,7 +2025,7 @@ function checkTemplates(cwd) {
1694
2025
  }
1695
2026
  function checkCanonVersion(cwd) {
1696
2027
  const versionPath = join(cwd, ".canon", "version");
1697
- const installedVersion = "3.16.0";
2028
+ const installedVersion = "3.18.0";
1698
2029
  if (!existsSync(versionPath)) {
1699
2030
  return { label: ".canon/version", status: "warn", detail: "missing \u2014 run `canon upgrade`" };
1700
2031
  }
@@ -2048,16 +2379,30 @@ function checkDocsFreshness(cwd) {
2048
2379
  const detail = `${source}: ${sets.protected.length} protected, ${globs.length} mappings, ${sets.flagOnly.length} flag-only`;
2049
2380
  return { label, status: warnings.length ? "warn" : "pass", detail: [detail, ...warnings].join("; ") };
2050
2381
  }
2382
+ function agentBackendsEveryProviderNeeds() {
2383
+ const perProvider = PROVIDERS.map((p) => new Set(requiredAgentBackends(roleAssignmentFor(p))));
2384
+ return new Set([...perProvider[0]].filter((backend) => perProvider.every((set) => set.has(backend))));
2385
+ }
2051
2386
  function doctorCmd(args2) {
2052
2387
  handlePreScan(DOCTOR_ARGS, args2, { out: console.log, err: console.error, exit: (code) => process.exit(code) });
2053
2388
  const cwd = resolveProjectRoot();
2389
+ let provider = "mixed";
2390
+ let providerError = null;
2391
+ try {
2392
+ provider = resolveProviderSetting();
2393
+ } catch (error) {
2394
+ providerError = error instanceof Error ? error.message : String(error);
2395
+ }
2396
+ const providerCheck = { label: `Provider (${PROVIDER_SETTING_NAME} setting)`, status: providerError ? "fail" : "pass", detail: providerError ?? provider };
2397
+ const requiredAgents = providerError ? agentBackendsEveryProviderNeeds() : new Set(requiredAgentBackends(roleAssignmentFor(provider)));
2054
2398
  const envChecks = [
2399
+ providerCheck,
2055
2400
  checkPlatform(),
2056
2401
  checkNodeVersion(),
2057
2402
  checkBinary("git", true, "https://git-scm.com/downloads"),
2058
- checkBinary("claude", true, "npm install -g @anthropic-ai/claude-code"),
2059
- ...isAvailable("claude") ? [checkClaudeVersion()] : [],
2060
- checkBinary("codex", true, "npm install -g @openai/codex"),
2403
+ ...requiredAgents.has("claude") ? [checkBinary("claude", true, "npm install -g @anthropic-ai/claude-code")] : [],
2404
+ ...requiredAgents.has("claude") && isAvailable("claude") ? [checkClaudeVersion()] : [],
2405
+ ...requiredAgents.has("codex") ? [checkBinary("codex", true, "npm install -g @openai/codex")] : [],
2061
2406
  checkBinary("gh", false, "brew install gh && gh auth login (required for --pr / --push)")
2062
2407
  ];
2063
2408
  const codexDeprecated = checkCodexMdDeprecated(cwd);
@@ -2070,8 +2415,9 @@ function doctorCmd(args2) {
2070
2415
  checkQualityLog(cwd)
2071
2416
  ];
2072
2417
  const configChecks = [
2073
- checkCodexProjectTrust(cwd),
2418
+ ...requiredAgents.has("codex") ? [checkCodexProjectTrust(cwd)] : [],
2074
2419
  checkRecommendedPermissions(cwd),
2420
+ checkGuardHook(cwd),
2075
2421
  checkLocalSettingsGitignored(cwd),
2076
2422
  checkRuntimeFilesGitignored(cwd),
2077
2423
  checkDocsFreshness(cwd)
@@ -2223,7 +2569,7 @@ function initCmd(args2) {
2223
2569
  }
2224
2570
  function writeCanonVersion(cwd) {
2225
2571
  const versionPath = join2(cwd, ".canon", "version");
2226
- const version = "3.16.0";
2572
+ const version = "3.18.0";
2227
2573
  mkdirSync(dirname2(versionPath), { recursive: true });
2228
2574
  writeFileSync(versionPath, version + "\n");
2229
2575
  }
@@ -3303,7 +3649,7 @@ function isInstalledSourcePath(sourcePath) {
3303
3649
  return sourcePath.includes("/node_modules/") || sourcePath.includes("\\node_modules\\") || sourcePath.includes("/_npx/") || sourcePath.includes("\\_npx\\");
3304
3650
  }
3305
3651
  function resolveCanonVersion(explicit) {
3306
- return explicit ?? "3.16.0" ?? "dev";
3652
+ return explicit ?? "3.18.0" ?? "dev";
3307
3653
  }
3308
3654
  function resolveOrchestratorCommit(repoRoot, upstreamCommit, runGitAt) {
3309
3655
  const ownToplevel = captureGitOutput(repoRoot, ["rev-parse", "--show-toplevel"], runGitAt);
@@ -3603,19 +3949,24 @@ function resolveTaskDirForValidation(taskId, taskDirOverride) {
3603
3949
  return taskDirOverride ? path15.join(taskDirOverride, taskId) : taskDirFor(taskId);
3604
3950
  }
3605
3951
  function checkPhaseGate(taskId, phase, verdict, taskDirOverride) {
3606
- const config2 = PHASE_GATE_CONFIG[phase];
3952
+ const config3 = PHASE_GATE_CONFIG[phase];
3607
3953
  const taskDir = resolveTaskDirForValidation(taskId, taskDirOverride);
3608
- if (config2.artifactName) {
3609
- const artifactPath = path15.join(taskDir, config2.artifactName);
3954
+ if (config3.artifactName) {
3955
+ const artifactPath = path15.join(taskDir, config3.artifactName);
3610
3956
  let content;
3611
3957
  try {
3612
3958
  content = fs15.readFileSync(artifactPath, "utf8");
3613
3959
  } catch {
3614
- return { ok: false, reason: `${config2.artifactName} is missing for phase '${phase}'` };
3960
+ return { ok: false, reason: `${config3.artifactName} is missing for phase '${phase}'` };
3615
3961
  }
3616
- const isTemplate = config2.customTemplateCheck ? config2.customTemplateCheck(artifactPath) : isTemplateUnfilled(content);
3962
+ const isTemplate = config3.customTemplateCheck ? config3.customTemplateCheck(artifactPath) : isTemplateUnfilled(content);
3617
3963
  if (isTemplate) {
3618
- return { ok: false, reason: `${config2.artifactName} is still the unfilled template for phase '${phase}'` };
3964
+ return { ok: false, reason: `${config3.artifactName} is still the unfilled template for phase '${phase}'` };
3965
+ }
3966
+ if (phase === "spec") {
3967
+ const issues = lintSpecManifest(content);
3968
+ if (issues.length > 0) return { ok: false, reason: `${formatManifestLintIssues(issues)}
3969
+ Fix the \`### Affected Files\` table in spec.md, then rerun \`canon task phase ${taskId} spec done\`.` };
3619
3970
  }
3620
3971
  let rerouteEv = { reroute: false };
3621
3972
  if (phase === "spec_review" || phase === "plan") {
@@ -3633,15 +3984,15 @@ function checkPhaseGate(taskId, phase, verdict, taskDirOverride) {
3633
3984
  }
3634
3985
  rerouteEv = checkRerouteEvidence(phase, content, st);
3635
3986
  if (rerouteEv.reroute && !rerouteEv.ok) {
3636
- return { ok: false, reason: `${config2.artifactName}: ${rerouteEv.reason}` };
3987
+ return { ok: false, reason: `${config3.artifactName}: ${rerouteEv.reason}` };
3637
3988
  }
3638
3989
  }
3639
- if (config2.verdictMustMatchArtifact) {
3990
+ if (config3.verdictMustMatchArtifact) {
3640
3991
  if (!verdict) {
3641
3992
  return { ok: false, reason: `phase '${phase}' requires a verdict argument; none provided` };
3642
3993
  }
3643
3994
  const extracted = rerouteEv.reroute && rerouteEv.ok ? rerouteEv.verdict : extractCheckedVerdict(content);
3644
- const scopeLabel = rerouteEv.reroute && rerouteEv.ok ? `${config2.artifactName} reroute amendment-review section` : config2.artifactName;
3995
+ const scopeLabel = rerouteEv.reroute && rerouteEv.ok ? `${config3.artifactName} reroute amendment-review section` : config3.artifactName;
3645
3996
  if (!extracted) {
3646
3997
  return { ok: false, reason: `${scopeLabel} has no checked verdict checkbox` };
3647
3998
  }
@@ -3650,7 +4001,7 @@ function checkPhaseGate(taskId, phase, verdict, taskDirOverride) {
3650
4001
  }
3651
4002
  }
3652
4003
  }
3653
- if (config2.requiresVerdict && !config2.verdictMustMatchArtifact) {
4004
+ if (config3.requiresVerdict && !config3.verdictMustMatchArtifact) {
3654
4005
  if (!verdict) {
3655
4006
  return { ok: false, reason: `phase '${phase}' requires a verdict argument; none provided` };
3656
4007
  }
@@ -3985,6 +4336,63 @@ function parseDiffNameStatus(stdout) {
3985
4336
  }
3986
4337
  return { diffFiles, renamePairs };
3987
4338
  }
4339
+ function lintSpecManifest(markdown) {
4340
+ const scan = scanSpecManifest(markdown);
4341
+ const issues = [];
4342
+ const hasToken = (cell) => /`[^`]+`/.test(cell);
4343
+ for (const section of scan.sections) {
4344
+ const label = section.h2.text;
4345
+ for (const duplicate of section.affectedFiles.slice(1)) {
4346
+ issues.push({ section: label, line: duplicate.heading.line, kind: "duplicate-heading", message: "A second ### Affected Files heading is not read; merge its rows into the first table in this section." });
4347
+ }
4348
+ let row = 0;
4349
+ for (const block of section.affectedFiles[0]?.blocks ?? []) {
4350
+ if (!block.hasSeparator) issues.push({ section: label, line: block.header.line, kind: "header-less-block", message: "This line is being read as a header, so its path is not in scope. Keep each table contiguous and start it with a header followed by a |---|---| separator row." });
4351
+ for (const raw of block.rows) {
4352
+ row += 1;
4353
+ const { cells, line } = raw;
4354
+ const at = { section: label, row, line };
4355
+ if (cells.length > block.header.cells.length && cells.slice(block.header.cells.length).some(hasToken)) {
4356
+ issues.push({ ...at, kind: "fused-cells", message: `Row has ${cells.length} cells but its header has ${block.header.cells.length}; extra backticked content is not read. Put one file per row, or comma-join paths in column 1. For a literal pipe in a cell, write \\|.` });
4357
+ }
4358
+ if (!cells[0] && cells.slice(1).some(hasToken)) {
4359
+ issues.push({ ...at, kind: "empty-first-cell", message: "The first column is empty, so a path in another cell is not read. Put the path in column 1." });
4360
+ } else if (cells[0]) {
4361
+ for (const malformed of parseHandoffPathCell(cells[0]).malformed) {
4362
+ issues.push({ ...at, kind: "malformed-path", message: `First-column cell ${cells[0]}: ${malformed.reason}. Start with backticked paths, comma-join multiple paths, and move notes to the Change column.` });
4363
+ }
4364
+ }
4365
+ }
4366
+ }
4367
+ }
4368
+ const exact = scan.sections.flatMap((s) => s.affectedFiles);
4369
+ for (const heading of scan.headings) {
4370
+ if (!/(?<![a-z])affected files(?![a-z])/i.test(heading.text)) continue;
4371
+ if (exact.some((entry) => entry.heading.index === heading.index || heading.level >= 4 && heading.index > entry.heading.index && heading.index < entry.heading.sectionEnd)) continue;
4372
+ if (scanTableBlocks(scan.lines, scan.hidden, heading.index + 1, heading.sectionEnd).length === 0) continue;
4373
+ const section = scan.headings.filter((h) => h.level === 2 && h.index <= heading.index).at(-1)?.text ?? "(before any ## section)";
4374
+ issues.push({ section, line: heading.line, kind: "ignored-heading", message: `Heading ${heading.text} is not read as scope. Use exactly ### Affected Files directly under ## Design or an ## Amendment\u2026 section.` });
4375
+ }
4376
+ if (scan.unclosed) {
4377
+ const { kind, line } = scan.unclosed;
4378
+ const section = scan.headings.filter((h) => h.level === 2 && h.line <= line).at(-1)?.text ?? "(before any ## section)";
4379
+ const construct = kind === "fence" ? "code fence" : "HTML comment";
4380
+ const fix = kind === "fence" ? "Close it with a matching fence line." : "Close it with -->.";
4381
+ issues.push({ section, line, kind: "unclosed-block", message: `An unclosed ${construct} opened at line ${line} hides everything after it, including any Affected Files table. ${fix}` });
4382
+ }
4383
+ const designs = scan.sections.filter((section) => section.kind === "design");
4384
+ const hasPathRow = (section) => section.affectedFiles[0]?.blocks.some((block) => block.rows.some((raw) => Boolean(raw.cells[0]?.trim()))) ?? false;
4385
+ if (!designs.some(hasPathRow)) {
4386
+ issues.push({ section: designs[0]?.h2.text ?? "(no ## Design section)", kind: "missing-manifest", message: "No ### Affected Files table under ## Design has a row with a file in column 1, so nothing is in scope. Add one under ## Design: a header row, a |---|---| separator, then one backticked file path per row in column 1." });
4387
+ }
4388
+ return issues;
4389
+ }
4390
+ function formatManifestLintIssues(issues) {
4391
+ return `spec.md's Affected Files table has ${issues.length} problem(s):
4392
+ ` + issues.map(
4393
+ (issue) => ` - ${issue.section}${issue.row === void 0 ? "" : `, row ${issue.row}`}${issue.line === void 0 ? "" : ` (line ${issue.line})`}: ${issue.message}`
4394
+ ).join("\n");
4395
+ }
3988
4396
 
3989
4397
  // src/orchestrator/review-archive.ts
3990
4398
  var REVIEW_ARCHIVE_PREFIX = "review-prior-";
@@ -4021,18 +4429,12 @@ function rescaffoldReview(taskDir, identity) {
4021
4429
  }
4022
4430
  }
4023
4431
 
4024
- // src/lib/pipeline-policy.ts
4025
- var SIZE_ORDER = ["XS", "S", "M", "L", "XL"];
4026
- function isPlanCombined(task) {
4027
- return task.task_size === "XS" && !(task.delicate ?? false);
4028
- }
4029
-
4030
4432
  // src/task/index.ts
4031
4433
  var VALID_PHASES = new Set(PHASE_ORDER);
4032
4434
  var VALID_STATUSES = /* @__PURE__ */ new Set(["pending", "in_progress", "done", "changes_requested", "blocked"]);
4033
4435
  var VALID_VERDICTS = /* @__PURE__ */ new Set(["approved", "approved_with_nits", "changes_requested", "needs_re_review", "spec_gap", "sanctioned"]);
4034
4436
  var REVIEW_PHASES = /* @__PURE__ */ new Set(["spec_review", "code_review"]);
4035
- var SETTABLE_FIELDS = ["title", "task_size", "delicate", "worktree", "base_branch", "human_spec_gate"];
4437
+ var SETTABLE_FIELDS = ["title", "task_size", "delicate", "worktree", "base_branch", "human_spec_gate", "provider"];
4036
4438
  var SETTABLE_FIELD_SET = new Set(SETTABLE_FIELDS);
4037
4439
  var IMMUTABLE_FIELDS = /* @__PURE__ */ new Set(["id", "created", "updated"]);
4038
4440
  var REDIRECT_MESSAGES = {
@@ -4040,6 +4442,7 @@ var REDIRECT_MESSAGES = {
4040
4442
  status: "derived from phase states. Use `canon task phase <id> <phase> <status>`.",
4041
4443
  branch: "load-bearing git identity; retargeting it desyncs the worktree. Not settable via `canon task set`.",
4042
4444
  phases: "nested orchestrator-owned state. Use `canon task phase`, `canon task reset-spec-review`, `canon task reset-code-review`, or `canon task accept` instead.",
4445
+ session_backends: "nested orchestrator-owned state. Use `canon task set <id> provider <mixed|claude>` to switch providers and clear incompatible sessions.",
4043
4446
  sessions: "nested orchestrator-owned state. Use `canon task phase`, `canon task reset-spec-review`, `canon task reset-code-review`, or `canon task accept` instead.",
4044
4447
  canon: "nested orchestrator-owned state. `status.json.canon` is stamped by canon snapshot; use `CANON_UPSTREAM_REPO` to override the upstream slug, not `canon task set`.",
4045
4448
  escalations: "nested orchestrator-owned state. Use `canon task phase`, `canon task reset-spec-review`, `canon task reset-code-review`, or `canon task accept` instead."
@@ -4047,6 +4450,7 @@ var REDIRECT_MESSAGES = {
4047
4450
  var ACCEPT_PHASES = ["implement", "spec_review", "code_review"];
4048
4451
  var BOOLEAN_VALUES = ["true", "false"];
4049
4452
  var TASK_SET_FIELD_VALUES = {
4453
+ provider: ["mixed", "claude"],
4050
4454
  task_size: SIZE_ORDER,
4051
4455
  delicate: BOOLEAN_VALUES,
4052
4456
  worktree: BOOLEAN_VALUES,
@@ -4067,7 +4471,7 @@ var TASK_USAGE = [
4067
4471
  " set <TASK-ID> <field> <value> Set task metadata",
4068
4472
  " reset-spec-review <TASK-ID> Reset an auto-blocked spec review",
4069
4473
  " reset-code-review <TASK-ID> Reset an auto-blocked code review",
4070
- " post-merge-sync [<branch>] Reconcile local branch after squash merge",
4474
+ " post-merge-sync [<branch>] Reconcile local branch after a PR merge",
4071
4475
  "",
4072
4476
  "Run 'canon task <subcommand> --help' for details."
4073
4477
  ].join("\n");
@@ -4090,7 +4494,7 @@ Verdicts: ${[...VALID_VERDICTS].join(" | ")}
4090
4494
  Settable fields: ${SETTABLE_FIELDS.join(", ")}. Guarded fields redirect to canon task phase/reset/accept; immutable fields are refused.`, ...noTaskFlags, freeTextSlots: [2], completion: { positionals: [{ kind: "taskId" }, { kind: "settableField" }, { kind: "fieldValue" }] } },
4091
4495
  "reset-spec-review": { command: "task reset-spec-review", usage: "Usage: canon task reset-spec-review <TASK-ID>\n\nClear state for a fresh spec-review pass after an auto-block. Zeroes iterations, clears verdict, archives prior spec-review.md.", ...noTaskFlags, completion: { positionals: [{ kind: "taskId" }] } },
4092
4496
  "reset-code-review": { command: "task reset-code-review", usage: "Usage: canon task reset-code-review <TASK-ID>\n\nClear state for a fresh code-review pass after an auto-block. Zeroes loop counters, clears verdict, archives prior review.md.", ...noTaskFlags, completion: { positionals: [{ kind: "taskId" }] } },
4093
- "post-merge-sync": { command: "task post-merge-sync", usage: "Usage: canon task post-merge-sync [<branch>]\n\nAfter a squash-merge PR lands, reconcile the local branch with origin. Hard-reset when only pipeline telemetry diverged; refuse when real unmerged work is present.", ...noTaskFlags }
4497
+ "post-merge-sync": { command: "task post-merge-sync", usage: "Usage: canon task post-merge-sync [<branch>]\n\nAfter a PR merge lands, reconcile the local branch with origin. Hard-reset when only pipeline telemetry diverged; refuse when real unmerged work is present.", ...noTaskFlags }
4094
4498
  };
4095
4499
  function usage() {
4096
4500
  return TASK_USAGE;
@@ -4219,6 +4623,7 @@ function parseTaskNewArgs(args2) {
4219
4623
  return { id, title, baseBranch };
4220
4624
  }
4221
4625
  function taskNew(args2) {
4626
+ const provider = resolveProviderSetting();
4222
4627
  const { id, title, baseBranch: parsedBaseBranch } = parseTaskNewArgs(args2);
4223
4628
  let baseBranch = parsedBaseBranch;
4224
4629
  validateTaskId(id);
@@ -4255,6 +4660,7 @@ function taskNew(args2) {
4255
4660
  status.created = today();
4256
4661
  status.updated = today();
4257
4662
  status.base_branch = baseBranch;
4663
+ status.provider = provider;
4258
4664
  writeStatusAtomic(statusPath, status);
4259
4665
  try {
4260
4666
  refreshCanonSnapshotAtPath(statusPath);
@@ -4324,7 +4730,7 @@ function taskList() {
4324
4730
  console.log(`${row.id.padEnd(25)} ${row.title.padEnd(40)} ${row.phase}`);
4325
4731
  }
4326
4732
  if (invalidCount > 0) {
4327
- throw new Error(`${invalidCount} task(s) had invalid status.json \u2014 see INVALID: rows above. Fix the malformed files or remove the task dir.`);
4733
+ throw new Error(`${invalidCount} task(s) had invalid status.json \u2014 see INVALID: rows above. Ask the human to repair the malformed status.json files or remove the task dir.`);
4328
4734
  }
4329
4735
  }
4330
4736
  function taskStatus(id) {
@@ -4854,14 +5260,13 @@ function taskResetSpecReview(id) {
4854
5260
  specReview.iterations = 0;
4855
5261
  specReview.iterations_current_loop = 0;
4856
5262
  specReview.verdict = "";
4857
- if (status.sessions && Object.hasOwn(status.sessions, "claude_spec")) {
4858
- delete status.sessions.claude_spec;
4859
- }
5263
+ clearSessionPair(status, "author");
5264
+ if (storedSessionBackend(status, "spec_reviewer") === "claude") clearSessionPair(status, "spec_reviewer");
4860
5265
  const rearmGate = status.full_send !== true && status.human_spec_gate !== true;
4861
5266
  if (rearmGate) status.human_spec_gate = true;
4862
5267
  status.updated = today();
4863
5268
  writeStatusAtomic(statusPath, status);
4864
- console.log(`Reset ${id}: spec \u2192 done, spec_review \u2192 pending (iter=0, verdict cleared, claude_spec session dropped)`);
5269
+ console.log(`Reset ${id}: spec \u2192 done, spec_review \u2192 pending (iter=0, verdict cleared, author session dropped)`);
4865
5270
  if (rearmGate) {
4866
5271
  console.log(
4867
5272
  `Re-armed the spec gate: the next \`canon run ${id}\` stops after spec_review approves. To continue past it instead, run \`canon task set ${id} human_spec_gate false\` first.`
@@ -4907,13 +5312,11 @@ function taskResetCodeReview(id) {
4907
5312
  codeReview.iterations = 0;
4908
5313
  codeReview.preflight_rejections_current_loop = 0;
4909
5314
  codeReview.verdict = "";
4910
- if (status.sessions && Object.hasOwn(status.sessions, "claude_review")) {
4911
- delete status.sessions.claude_review;
4912
- }
5315
+ clearSessionPair(status, "reviewer");
4913
5316
  status.updated = today();
4914
5317
  writeStatusAtomic(statusPath, status);
4915
5318
  console.log(
4916
- `Reset ${id}: implement \u2192 done, code_review \u2192 pending (iter_current_loop=0, iterations=0, preflight_rejections_current_loop=0, verdict cleared, claude_review session dropped)`
5319
+ `Reset ${id}: implement \u2192 done, code_review \u2192 pending (iter_current_loop=0, iterations=0, preflight_rejections_current_loop=0, verdict cleared, reviewer session dropped)`
4917
5320
  );
4918
5321
  }
4919
5322
  function ensureGitAvailable() {
@@ -5046,7 +5449,7 @@ function taskPostMergeSync(branchArg) {
5046
5449
  }
5047
5450
  }
5048
5451
  console.log(`\u2192 ${targetBranch} is ${ahead} commit(s) ahead of origin/${targetBranch}, but only via`);
5049
- console.log(" pipeline telemetry / task-state edits that have been absorbed by squash merges.");
5452
+ console.log(" pipeline telemetry / task-state edits that have been absorbed by PR merges.");
5050
5453
  console.log(` Hard-resetting to origin/${targetBranch}...`);
5051
5454
  const reset = runGit(["reset", "--hard", `origin/${targetBranch}`], { stdio: "inherit" });
5052
5455
  if (reset.error || reset.status !== 0) throw new Error(reset.error?.message ?? "git reset failed");
@@ -5060,7 +5463,7 @@ function taskPostMergeSync(branchArg) {
5060
5463
  console.log("");
5061
5464
  console.log("Refusing to hard-reset. Either push these commits to origin");
5062
5465
  console.log(`(\`git push origin ${targetBranch}\`) if they're real work, or rebase manually`);
5063
- console.log("if they conflict with the squash merge.");
5466
+ console.log("if they conflict with the PR merge.");
5064
5467
  throw new Error("");
5065
5468
  }
5066
5469
  function nudgeShippableTasks() {
@@ -5094,6 +5497,12 @@ function nudgeShippableTasks() {
5094
5497
  }
5095
5498
  function taskSetValue(taskId, field, value, status) {
5096
5499
  switch (field) {
5500
+ case "provider": {
5501
+ const provider = parseProvider(value);
5502
+ const cleared = clearMismatchedSessions(status, roleAssignmentFor(provider));
5503
+ status.provider = provider;
5504
+ return cleared.length ? [`Cleared sessions: ${cleared.join(", ")}.`] : [];
5505
+ }
5097
5506
  case "title":
5098
5507
  if (value.includes("\n") || value.includes("\r")) {
5099
5508
  throw new Error("Error: title must be single-line (no embedded newlines).");
@@ -5180,7 +5589,7 @@ function taskSet(args2) {
5180
5589
  const recordedBranch = (status.branch ?? "").trim();
5181
5590
  if (recordedBranch && (field === "worktree" || field === "base_branch")) {
5182
5591
  throw new Error(
5183
- `Error: ${field} is locked once branch '${recordedBranch}' is recorded. Topology changes are only allowed before branching; recreate the task or migrate status.json manually.`
5592
+ `Error: ${field} is locked once branch '${recordedBranch}' is recorded. Topology changes are only allowed before branching; recreate the task or ask the human to migrate status.json.`
5184
5593
  );
5185
5594
  }
5186
5595
  if (SETTABLE_FIELD_SET.has(field)) {
@@ -5207,7 +5616,7 @@ function taskSet(args2) {
5207
5616
  if (field === "branch") {
5208
5617
  throw new Error(`Error: branch is ${taskSetRedirectMessage(field)}`);
5209
5618
  }
5210
- if (field === "phases" || field === "sessions" || field === "canon" || field === "escalations") {
5619
+ if (field === "phases" || field === "sessions" || field === "session_backends" || field === "canon" || field === "escalations") {
5211
5620
  throw new Error(`Error: ${field} is ${taskSetRedirectMessage(field)}`);
5212
5621
  }
5213
5622
  if (IMMUTABLE_FIELDS.has(field) || field.startsWith("_")) {
@@ -5548,7 +5957,7 @@ function currentPinFromManifest(manifest) {
5548
5957
  return "unknown";
5549
5958
  }
5550
5959
  function bakedVersion() {
5551
- return "3.16.0";
5960
+ return "3.18.0";
5552
5961
  }
5553
5962
  function ownPackageName(pkgDir) {
5554
5963
  try {
@@ -5763,6 +6172,7 @@ var CANON_OWNED = [
5763
6172
  ".claude/skills/canon-spec-review/SKILL.md",
5764
6173
  ".claude/skills/canon-inline-review/SKILL.md",
5765
6174
  ".claude/skills/canon-sweep/SKILL.md",
6175
+ ".claude/hooks/canon-guard.mjs",
5766
6176
  ".claude/agents/code-review-anchored.md",
5767
6177
  ".claude/agents/code-review-cold.md",
5768
6178
  ".claude/agents/spec-review-lens.md",
@@ -5792,6 +6202,15 @@ var UPGRADE_USAGE = [
5792
6202
  " --no-stage Skip the post-write git add"
5793
6203
  ].join("\n");
5794
6204
  var UPGRADE_ARGS = { command: "upgrade", usage: UPGRADE_USAGE, booleanFlags: ["--check", "--dry-run", "--force", "--no-stage"], valueFlags: [], rejectPositionals: true };
6205
+ function guardHookNotice(cwd) {
6206
+ if (!existsSync5(join5(cwd, GUARD_HOOK_PATH))) return null;
6207
+ const registration = guardHookRegistration(cwd);
6208
+ if (registration === "full") return null;
6209
+ if (registration === "partial") {
6210
+ return `Heads-up: ${GUARD_HOOK_PATH} is registered as a Claude Code hook, but its matcher does not cover every guarded tool (Bash, Edit, Write, MultiEdit) \u2014 run \`canon doctor\` to see which are missing and the settings snippet.`;
6211
+ }
6212
+ return `Heads-up: ${GUARD_HOOK_PATH} is installed but not registered as a Claude Code hook \u2014 run \`canon doctor\` for the settings snippet.`;
6213
+ }
5795
6214
  var CANON_END = "<!-- canon:end -->";
5796
6215
  var CANON_START_RE = /<!-- canon:start[^>]* -->/;
5797
6216
  var HEADER_ONLY_SYNC = [
@@ -6035,7 +6454,7 @@ function runUpgrade(cwd, pkgDir, options = {}) {
6035
6454
  cutoverWarnings.push(docsRefsCheckRel);
6036
6455
  }
6037
6456
  const versionPath = join5(cwd, ".canon", "version");
6038
- const newVersion = "3.16.0";
6457
+ const newVersion = "3.18.0";
6039
6458
  const currentVersion = existsSync5(versionPath) ? readFileSync4(versionPath, "utf8").trim() : null;
6040
6459
  if (currentVersion !== newVersion) {
6041
6460
  pending.push({ rel: ".canon/version", projectPath: versionPath, content: newVersion + "\n" });
@@ -6236,6 +6655,9 @@ function upgradeCmd(args2) {
6236
6655
  }
6237
6656
  console.log("");
6238
6657
  }
6658
+ const hookNotice = guardHookNotice(process.cwd());
6659
+ if (hookNotice) console.log(`${hookNotice}
6660
+ `);
6239
6661
  if (upgraded.length === 0 && unchanged.length === 0 && skipped.length === 0 && malformed.length === 0) {
6240
6662
  console.log("No canon-managed files found. Run `canon init` to set up canon in this repo.\n");
6241
6663
  } else {
@@ -6651,7 +7073,7 @@ Global:
6651
7073
  Run 'canon <command> --help' for details.`);
6652
7074
  }
6653
7075
  function printVersion() {
6654
- console.log("3.16.0");
7076
+ console.log("3.18.0");
6655
7077
  }
6656
7078
  switch (command) {
6657
7079
  case "doctor":