canon-ai 3.18.0 → 3.19.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/CHANGELOG.md +20 -0
- package/README.md +17 -17
- package/dist/cli/index.js +41 -22
- package/dist/orchestrator/run-task.js +1297 -252
- package/package.json +4 -4
- package/templates/.canon/templates/done.md +10 -0
- package/templates/.canon/templates/handoff.md +20 -0
- package/templates/.canon/templates/review.md +1 -0
- package/templates/.canon/templates/spec.md +2 -0
- package/templates/.claude/agents/code-review-anchored.md +4 -1
- package/templates/.claude/skills/canon-init/write-guide.md +5 -1
- package/templates/.claude/skills/canon-spec/SKILL.md +7 -11
- package/templates/.claude/skills/canon-spec-review/SKILL.md +3 -1
- package/templates/.claude/skills/canon-status/SKILL.md +2 -1
- package/templates/docs/patterns.md +5 -19
- package/templates/docs/pipeline-orchestrator.md +23 -14
- package/templates/scripts/docs-refs-check.mjs +5 -1
|
@@ -2425,11 +2425,11 @@ function resolveDocsFreshness(config3, diff) {
|
|
|
2425
2425
|
}
|
|
2426
2426
|
|
|
2427
2427
|
// src/orchestrator/main.ts
|
|
2428
|
-
import { spawnSync as
|
|
2428
|
+
import { spawnSync as spawnSync8 } from "child_process";
|
|
2429
2429
|
import { createHash } from "crypto";
|
|
2430
|
-
import
|
|
2430
|
+
import fs27 from "fs";
|
|
2431
2431
|
import os from "os";
|
|
2432
|
-
import
|
|
2432
|
+
import path25 from "path";
|
|
2433
2433
|
|
|
2434
2434
|
// src/orchestrator/policy.ts
|
|
2435
2435
|
var config2 = {
|
|
@@ -2506,8 +2506,8 @@ function resolveBundleProvider(statuses) {
|
|
|
2506
2506
|
}
|
|
2507
2507
|
|
|
2508
2508
|
// src/orchestrator/phases/code-review.ts
|
|
2509
|
-
import
|
|
2510
|
-
import
|
|
2509
|
+
import fs21 from "fs";
|
|
2510
|
+
import path19 from "path";
|
|
2511
2511
|
|
|
2512
2512
|
// src/orchestrator/agents/claude.ts
|
|
2513
2513
|
import { spawn as spawn2 } from "child_process";
|
|
@@ -2581,6 +2581,9 @@ function phaseCommands(taskIds, phase, status, verdict = "") {
|
|
|
2581
2581
|
return `(cd '${resolveTaskCwd(id)}' && ${cmd})`;
|
|
2582
2582
|
}).join("\n");
|
|
2583
2583
|
}
|
|
2584
|
+
function makePromptArgSafe(prompt) {
|
|
2585
|
+
return prompt.replaceAll("\0", "\\0");
|
|
2586
|
+
}
|
|
2584
2587
|
function toResumePrompt(prompt) {
|
|
2585
2588
|
let trimmed = prompt;
|
|
2586
2589
|
for (const block of [CLAUDE_STARTUP, CODEX_STARTUP, CLAUDE_IMPLEMENTER_STARTUP, QA_STARTUP]) {
|
|
@@ -2787,6 +2790,7 @@ function runInteractiveClaude(args, cwd) {
|
|
|
2787
2790
|
});
|
|
2788
2791
|
}
|
|
2789
2792
|
async function runClaude(prompt, interactive, resumeId, model, effort, budget, metricsContext, cwd = REPO_ROOT, wrapForResume = true) {
|
|
2793
|
+
const safePrompt = makePromptArgSafe(prompt);
|
|
2790
2794
|
info(resumeId ? `Calling Claude Code (resuming ${resumeId.slice(0, 8)}...)...` : "Calling Claude Code...");
|
|
2791
2795
|
info(interactive ? `Model: ${model} | Effort: ${effort} | Budget: uncapped (interactive)` : `Model: ${model} | Effort: ${effort} | Budget: ${budget}`);
|
|
2792
2796
|
const startMs = Date.now();
|
|
@@ -2805,7 +2809,7 @@ async function runClaude(prompt, interactive, resumeId, model, effort, budget, m
|
|
|
2805
2809
|
const args = ["--model", model, "--effort", effort, "--add-dir", REPO_ROOT];
|
|
2806
2810
|
if (cwd !== REPO_ROOT) args.push("--add-dir", cwd);
|
|
2807
2811
|
if (resumeId) args.push("--resume", resumeId);
|
|
2808
|
-
args.push(resumeId && wrapForResume ? toResumePrompt(
|
|
2812
|
+
args.push(resumeId && wrapForResume ? toResumePrompt(safePrompt) : safePrompt);
|
|
2809
2813
|
const exitCode = await runInteractiveClaude(args, cwd);
|
|
2810
2814
|
if (exitCode !== 0) {
|
|
2811
2815
|
status = "failed";
|
|
@@ -2825,7 +2829,7 @@ async function runClaude(prompt, interactive, resumeId, model, effort, budget, m
|
|
|
2825
2829
|
}
|
|
2826
2830
|
const attempt = async (useResumeId) => {
|
|
2827
2831
|
let sessionId = null;
|
|
2828
|
-
const renderedPrompt = useResumeId && wrapForResume ? toResumePrompt(
|
|
2832
|
+
const renderedPrompt = useResumeId && wrapForResume ? toResumePrompt(safePrompt) : safePrompt;
|
|
2829
2833
|
const effectivePrompt = `${CLAUDE_HEADLESS}
|
|
2830
2834
|
|
|
2831
2835
|
${renderedPrompt}`;
|
|
@@ -3036,7 +3040,8 @@ function invalidCodexEffortMessage(effort) {
|
|
|
3036
3040
|
async function runCodex(prompt, interactive, resumeId, model, effort, metricsContext, cwd = REPO_ROOT, wrapForResume = true) {
|
|
3037
3041
|
const invalidEffort = invalidCodexEffortMessage(effort);
|
|
3038
3042
|
if (invalidEffort) die(invalidEffort);
|
|
3039
|
-
const
|
|
3043
|
+
const safePrompt = makePromptArgSafe(prompt);
|
|
3044
|
+
const renderedPrompt = resumeId && wrapForResume ? toResumePrompt(safePrompt) : safePrompt;
|
|
3040
3045
|
const effectivePrompt = interactive ? renderedPrompt : `${CODEX_HEADLESS}
|
|
3041
3046
|
|
|
3042
3047
|
${renderedPrompt}`;
|
|
@@ -3370,8 +3375,8 @@ function normalizeCells(line) {
|
|
|
3370
3375
|
function isSeparatorRow(cells) {
|
|
3371
3376
|
return cells.length > 0 && cells.every((cell) => /^:?-+:?$/.test(cell.trim()));
|
|
3372
3377
|
}
|
|
3373
|
-
function isSectionHeading(line,
|
|
3374
|
-
return line.trimEnd() === `## ${
|
|
3378
|
+
function isSectionHeading(line, sectionHeading2) {
|
|
3379
|
+
return line.trimEnd() === `## ${sectionHeading2}`;
|
|
3375
3380
|
}
|
|
3376
3381
|
function isHeadingBoundary(line) {
|
|
3377
3382
|
return /^#{1,2}\s/.test(line);
|
|
@@ -3416,9 +3421,9 @@ function extractSectionBodies(markdown, pattern) {
|
|
|
3416
3421
|
if (activeStart !== -1) bodies.push(lines.slice(activeStart).join("\n"));
|
|
3417
3422
|
return bodies;
|
|
3418
3423
|
}
|
|
3419
|
-
function parseTableH3(markdown,
|
|
3424
|
+
function parseTableH3(markdown, sectionHeading2) {
|
|
3420
3425
|
const lines = markdown.split("\n");
|
|
3421
|
-
const headingIndex = lines.findIndex((line) => line.trimEnd() === `### ${
|
|
3426
|
+
const headingIndex = lines.findIndex((line) => line.trimEnd() === `### ${sectionHeading2}`);
|
|
3422
3427
|
if (headingIndex === -1) return [];
|
|
3423
3428
|
let tableStart = -1;
|
|
3424
3429
|
let sectionEnd = lines.length;
|
|
@@ -3627,9 +3632,9 @@ function scanAllTables(markdown) {
|
|
|
3627
3632
|
}
|
|
3628
3633
|
return tables;
|
|
3629
3634
|
}
|
|
3630
|
-
function parseTable(markdown,
|
|
3635
|
+
function parseTable(markdown, sectionHeading2) {
|
|
3631
3636
|
const lines = markdown.split("\n");
|
|
3632
|
-
const headingIndex = lines.findIndex((line) => isSectionHeading(line,
|
|
3637
|
+
const headingIndex = lines.findIndex((line) => isSectionHeading(line, sectionHeading2));
|
|
3633
3638
|
if (headingIndex === -1) return [];
|
|
3634
3639
|
let tableStart = -1;
|
|
3635
3640
|
let sectionEnd = lines.length;
|
|
@@ -3708,6 +3713,42 @@ function checkAcCoveragePlaceholders(handoffContent) {
|
|
|
3708
3713
|
}
|
|
3709
3714
|
return [];
|
|
3710
3715
|
}
|
|
3716
|
+
var SELF_CHECK_ROWS = ["Test integrity", "Restatement sweep", "Sibling parity"];
|
|
3717
|
+
var SELF_CHECK_MISSING = "Self-Check section is missing \u2014 add a baseline `## Self-Check` section to handoff.md in place, after Red-First Evidence (a Check / Evidence table with the rows Test integrity, Restatement sweep and Sibling parity). An Iteration `### Self-Check` subsection does not satisfy this check.";
|
|
3718
|
+
function normalizeSelfCheckLabel(cell) {
|
|
3719
|
+
return cell.replace(/[*_`]/g, "").replace(/:\s*$/, "").replace(/\s+/g, " ").trim().toLowerCase();
|
|
3720
|
+
}
|
|
3721
|
+
function checkSelfCheckEvidence(handoffContent) {
|
|
3722
|
+
const { lines, hidden, headings } = scanSpecManifest(handoffContent);
|
|
3723
|
+
const baseline = headings.find((h) => h.level === 2 && /^##\s+self[- ]check\s*$/i.test(h.text));
|
|
3724
|
+
if (!baseline) return [SELF_CHECK_MISSING];
|
|
3725
|
+
const end = headings.find((h) => h.index > baseline.index && h.level <= 2)?.index ?? lines.length;
|
|
3726
|
+
const rows = scanTableBlocks(lines, hidden, baseline.index + 1, end).flatMap((block) => block.rows);
|
|
3727
|
+
const issues = [];
|
|
3728
|
+
for (const label of SELF_CHECK_ROWS) {
|
|
3729
|
+
const matches = rows.filter((row) => normalizeSelfCheckLabel(row.cells[0] ?? "") === label.toLowerCase());
|
|
3730
|
+
if (matches.length === 0) {
|
|
3731
|
+
issues.push(`Self-Check row "${label}" is missing \u2014 add it to the baseline \`## Self-Check\` table in place, with its evidence or \`N/A \u2014 <reason>\`.`);
|
|
3732
|
+
continue;
|
|
3733
|
+
}
|
|
3734
|
+
for (const row of matches) {
|
|
3735
|
+
const evidence = (row.cells[1] ?? "").trim();
|
|
3736
|
+
const bare = evidence.replace(/[*_`]/g, "").trim();
|
|
3737
|
+
if (row.cells.length !== 2) {
|
|
3738
|
+
issues.push(`Self-Check row "${label}" must have exactly two cells \u2014 repair the baseline \`## Self-Check\` table in place and escape literal pipes as \`\\|\`.`);
|
|
3739
|
+
} else if (!/[\p{L}\p{N}]/u.test(evidence)) {
|
|
3740
|
+
issues.push(`Self-Check row "${label}" has an empty Evidence cell \u2014 fill it in the baseline \`## Self-Check\` table, or write \`N/A \u2014 <reason>\`.`);
|
|
3741
|
+
} else if (evidence.includes("<reason>")) {
|
|
3742
|
+
issues.push(`Self-Check row "${label}" still holds the \`<reason>\` placeholder \u2014 give the reason in the baseline \`## Self-Check\` table.`);
|
|
3743
|
+
} else if (bare.startsWith("(") && bare.endsWith(")")) {
|
|
3744
|
+
issues.push(`Self-Check row "${label}" still holds the template placeholder \u2014 replace it in the baseline \`## Self-Check\` table with the evidence, or \`N/A \u2014 <reason>\`.`);
|
|
3745
|
+
} else if (/^n\/a[\s.:—–-]*$/i.test(bare)) {
|
|
3746
|
+
issues.push(`Self-Check row "${label}" is a bare N/A \u2014 give the reason in the baseline \`## Self-Check\` table: \`N/A \u2014 <reason>\`.`);
|
|
3747
|
+
}
|
|
3748
|
+
}
|
|
3749
|
+
}
|
|
3750
|
+
return issues;
|
|
3751
|
+
}
|
|
3711
3752
|
function computeLatestValidationResults(handoffContent) {
|
|
3712
3753
|
const latest = /* @__PURE__ */ new Map();
|
|
3713
3754
|
const baseline = parseTable(handoffContent, "Validation Outcomes");
|
|
@@ -3999,6 +4040,7 @@ function classifyPreflightBlockersFromData(data) {
|
|
|
3999
4040
|
const fromRows = classifyValidationChecks(data.requiredChecks, data.latestResults, data.changedFiles);
|
|
4000
4041
|
return [
|
|
4001
4042
|
...data.acCoverageIssues.map(format),
|
|
4043
|
+
...data.selfCheckIssues.map(format),
|
|
4002
4044
|
...data.changesTableIssues.map(format),
|
|
4003
4045
|
...data.bundleDiffIssues.map(format),
|
|
4004
4046
|
...fromRows
|
|
@@ -4017,6 +4059,7 @@ function classifyPreflightBlockers(taskId, changedFiles, bundleDiffIssues = [])
|
|
|
4017
4059
|
requiredChecks,
|
|
4018
4060
|
changedFiles,
|
|
4019
4061
|
acCoverageIssues: checkAcCoveragePlaceholders(content),
|
|
4062
|
+
selfCheckIssues: checkSelfCheckEvidence(content),
|
|
4020
4063
|
changesTableIssues: malformed.map((entry) => `Changes table row '${entry.cell}': ${entry.reason}`),
|
|
4021
4064
|
bundleDiffIssues: [...bundleDiffIssues],
|
|
4022
4065
|
handoffMissing: false
|
|
@@ -4027,6 +4070,7 @@ function classifyPreflightBlockers(taskId, changedFiles, bundleDiffIssues = [])
|
|
|
4027
4070
|
requiredChecks: null,
|
|
4028
4071
|
changedFiles,
|
|
4029
4072
|
acCoverageIssues: [],
|
|
4073
|
+
selfCheckIssues: [],
|
|
4030
4074
|
changesTableIssues: [],
|
|
4031
4075
|
bundleDiffIssues: [...bundleDiffIssues],
|
|
4032
4076
|
handoffMissing: true
|
|
@@ -4888,8 +4932,13 @@ ${detail}
|
|
|
4888
4932
|
}
|
|
4889
4933
|
|
|
4890
4934
|
// src/orchestrator/prompts/index.ts
|
|
4891
|
-
import
|
|
4892
|
-
import
|
|
4935
|
+
import fs17 from "fs";
|
|
4936
|
+
import path15 from "path";
|
|
4937
|
+
|
|
4938
|
+
// src/orchestrator/blast-radius.ts
|
|
4939
|
+
import { spawnSync as spawnSync5 } from "child_process";
|
|
4940
|
+
import fs13 from "fs";
|
|
4941
|
+
import path11 from "path";
|
|
4893
4942
|
|
|
4894
4943
|
// src/orchestrator/context.ts
|
|
4895
4944
|
import fs12 from "fs";
|
|
@@ -4948,22 +4997,6 @@ ${content}
|
|
|
4948
4997
|
}
|
|
4949
4998
|
return block;
|
|
4950
4999
|
}
|
|
4951
|
-
function buildKnownPitfalls(taskIds) {
|
|
4952
|
-
const patternsPath = process.env.CANON_PATTERNS_MD_PATH ?? path10.join(getActiveCwd(taskIds), "docs/patterns.md");
|
|
4953
|
-
try {
|
|
4954
|
-
const content = fs12.readFileSync(patternsPath, "utf8");
|
|
4955
|
-
const match = content.match(/## Known Pitfalls\n\n([\s\S]*?)(?:\n## |\n---|\n# |$)/);
|
|
4956
|
-
if (!match) return "";
|
|
4957
|
-
return `
|
|
4958
|
-
## Known Codebase Pitfalls (from docs/patterns.md \u2014 read before touching these areas)
|
|
4959
|
-
|
|
4960
|
-
${match[1].trimEnd()}
|
|
4961
|
-
|
|
4962
|
-
`;
|
|
4963
|
-
} catch {
|
|
4964
|
-
return "";
|
|
4965
|
-
}
|
|
4966
|
-
}
|
|
4967
5000
|
function buildKnownRisks(taskIds) {
|
|
4968
5001
|
const riskBlocks = taskIds.map((taskId) => {
|
|
4969
5002
|
const specPath = path10.join(taskDirFor(taskId), "spec.md");
|
|
@@ -5117,13 +5150,940 @@ ${renderedBlocks.join("\n\n")}${truncMarker}
|
|
|
5117
5150
|
${acSection}`;
|
|
5118
5151
|
}
|
|
5119
5152
|
|
|
5120
|
-
// src/orchestrator/
|
|
5153
|
+
// src/orchestrator/blast-radius.ts
|
|
5154
|
+
var BLAST_RADIUS_ROOT_ENV = "CANON_BLAST_RADIUS_ROOT";
|
|
5155
|
+
var BLAST_RADIUS_HEADING = "## Blast Radius (files outside Affected Files to check)";
|
|
5156
|
+
var BLAST_RADIUS_FRAMING = "These files are surfaces to check for restatements and sibling paths. Editing a file outside Affected Files still requires recording a Blocker in handoff.md.";
|
|
5157
|
+
var PER_ENTRY_LIMIT = 10;
|
|
5158
|
+
var TOKEN_CAP = 20;
|
|
5159
|
+
var BYTE_CAP = 6144;
|
|
5160
|
+
var REFERENCE_FILE_CAP = 40;
|
|
5161
|
+
var GENERIC_STEMS = /* @__PURE__ */ new Set(["index", "types"]);
|
|
5162
|
+
var STOPLIST = /* @__PURE__ */ new Set(["True", "False", "None", "Null", "Pass", "Fail", "Done", "Todo", "Note", "Approved", "Blocked"]);
|
|
5163
|
+
var PIPELINE_TELEMETRY_FILE_SET = new Set(PIPELINE_TELEMETRY_FILES);
|
|
5164
|
+
var NON_GENERATED_PATHSPECS = [".", ":(exclude,attr:linguist-generated)", ":(exclude,attr:linguist-generated=true)"];
|
|
5165
|
+
function tokensFromBodies(bodies) {
|
|
5166
|
+
const tokens = [];
|
|
5167
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5168
|
+
for (const body of bodies) {
|
|
5169
|
+
for (const match of body.matchAll(/`([^`\n]+)`/g)) {
|
|
5170
|
+
const token = match[1];
|
|
5171
|
+
let normalized = null;
|
|
5172
|
+
if (/^--[a-z0-9][a-z0-9-]*$/.test(token)) {
|
|
5173
|
+
normalized = token;
|
|
5174
|
+
} else {
|
|
5175
|
+
const hadParens = token.endsWith("()");
|
|
5176
|
+
const name = hadParens ? token.slice(0, -2) : token;
|
|
5177
|
+
const shaped = hadParens || /^[A-Z][a-z0-9]+$/.test(name) || /[a-z0-9][A-Z]/.test(name) || /[A-Z]{2,}[a-z]{2,}/.test(name) || /[A-Za-z0-9]_[A-Za-z0-9]/.test(name);
|
|
5178
|
+
if (name.length >= 3 && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && shaped && !STOPLIST.has(name)) normalized = name;
|
|
5179
|
+
}
|
|
5180
|
+
if (normalized && !seen.has(normalized)) {
|
|
5181
|
+
seen.add(normalized);
|
|
5182
|
+
tokens.push(normalized);
|
|
5183
|
+
}
|
|
5184
|
+
}
|
|
5185
|
+
}
|
|
5186
|
+
return tokens;
|
|
5187
|
+
}
|
|
5188
|
+
function extractSpecTokens(specMarkdown) {
|
|
5189
|
+
const amendment = extractSectionBodies(specMarkdown, /^## Amendment\b/).reverse();
|
|
5190
|
+
const design = extractSectionBodies(specMarkdown, /^## Design\b/);
|
|
5191
|
+
const ac = extractSectionBodies(specMarkdown, /^## Acceptance Criteria\b/);
|
|
5192
|
+
return {
|
|
5193
|
+
amendment: tokensFromBodies(amendment),
|
|
5194
|
+
design: tokensFromBodies(design),
|
|
5195
|
+
ac: tokensFromBodies(ac)
|
|
5196
|
+
};
|
|
5197
|
+
}
|
|
5198
|
+
function toRepoRelative(file) {
|
|
5199
|
+
const normalized = path11.posix.normalize(file.replace(/\\/g, "/"));
|
|
5200
|
+
return file.endsWith("/") && !normalized.endsWith("/") ? `${normalized}/` : normalized;
|
|
5201
|
+
}
|
|
5202
|
+
function excludedPath(file, affectedFiles, directoryEntries) {
|
|
5203
|
+
return affectedFiles.includes(file) || directoryEntries.some((directory) => file.startsWith(directory)) || file.startsWith("tasks/") || PIPELINE_TELEMETRY_FILE_SET.has(file);
|
|
5204
|
+
}
|
|
5205
|
+
var GREP_MAX_BUFFER = 16 * 1024 * 1024;
|
|
5206
|
+
function gitGrep(root, modeFlags, pattern, maxBuffer = GREP_MAX_BUFFER) {
|
|
5207
|
+
const result = spawnSync5("git", ["grep", "-l", "-I", "-z", ...modeFlags, "-e", pattern, "--", ...NON_GENERATED_PATHSPECS], {
|
|
5208
|
+
cwd: root,
|
|
5209
|
+
encoding: "utf8",
|
|
5210
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
5211
|
+
maxBuffer
|
|
5212
|
+
});
|
|
5213
|
+
if (result.error) {
|
|
5214
|
+
if (result.error.code === "ENOBUFS") return [];
|
|
5215
|
+
throw result.error;
|
|
5216
|
+
}
|
|
5217
|
+
if (result.status === 0) return (result.stdout ?? "").split("\0").filter(Boolean);
|
|
5218
|
+
if (result.status === 1) return [];
|
|
5219
|
+
const stderr = (result.stderr ?? "").trim();
|
|
5220
|
+
const detail = stderr ? `: ${stderr}` : "";
|
|
5221
|
+
throw new Error(`git grep failed with exit status ${result.status ?? "unknown"}${detail}`);
|
|
5222
|
+
}
|
|
5223
|
+
function escapeEre(value) {
|
|
5224
|
+
return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
|
|
5225
|
+
}
|
|
5226
|
+
function trackedReferenceFiles(root, affectedFile) {
|
|
5227
|
+
const basename = path11.basename(affectedFile);
|
|
5228
|
+
const matches = new Set(gitGrep(root, ["-F", "-w"], basename));
|
|
5229
|
+
const stem = path11.basename(affectedFile, path11.extname(affectedFile));
|
|
5230
|
+
if (stem && !GENERIC_STEMS.has(stem)) {
|
|
5231
|
+
const quoteClass = "[" + String.fromCharCode(39, 34, 96) + "]";
|
|
5232
|
+
const moduleSpecifier = "/" + escapeEre(stem) + "(\\.[A-Za-z0-9]+)?" + quoteClass;
|
|
5233
|
+
for (const file of gitGrep(root, ["-E"], moduleSpecifier)) matches.add(file);
|
|
5234
|
+
}
|
|
5235
|
+
return [...matches].sort();
|
|
5236
|
+
}
|
|
5237
|
+
function specTokens(taskIds) {
|
|
5238
|
+
const byTier = { amendment: [], design: [], ac: [] };
|
|
5239
|
+
for (const taskId of taskIds) {
|
|
5240
|
+
try {
|
|
5241
|
+
const markdown = fs13.readFileSync(path11.join(taskDirFor(taskId), "spec.md"), "utf8");
|
|
5242
|
+
const extracted = extractSpecTokens(markdown);
|
|
5243
|
+
byTier.amendment.push(...extracted.amendment);
|
|
5244
|
+
byTier.design.push(...extracted.design);
|
|
5245
|
+
byTier.ac.push(...extracted.ac);
|
|
5246
|
+
} catch {
|
|
5247
|
+
}
|
|
5248
|
+
}
|
|
5249
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5250
|
+
const ordered = [];
|
|
5251
|
+
for (const token of [...byTier.amendment, ...byTier.design, ...byTier.ac]) {
|
|
5252
|
+
if (seen.has(token)) continue;
|
|
5253
|
+
seen.add(token);
|
|
5254
|
+
ordered.push(token);
|
|
5255
|
+
if (ordered.length === TOKEN_CAP) break;
|
|
5256
|
+
}
|
|
5257
|
+
return ordered;
|
|
5258
|
+
}
|
|
5259
|
+
function formatEntry(entry) {
|
|
5260
|
+
const shown = entry.files.slice(0, PER_ENTRY_LIMIT).map((file) => `\`${file}\``);
|
|
5261
|
+
const remaining = entry.files.length - shown.length;
|
|
5262
|
+
return `- \`${entry.label}\`: ${shown.join(", ")}${remaining > 0 ? `, +${remaining} more` : ""}`;
|
|
5263
|
+
}
|
|
5264
|
+
function renderEntries(entries, omitted, skipped) {
|
|
5265
|
+
let block = `
|
|
5266
|
+
${BLAST_RADIUS_HEADING}
|
|
5267
|
+
|
|
5268
|
+
${BLAST_RADIUS_FRAMING}
|
|
5269
|
+
|
|
5270
|
+
`;
|
|
5271
|
+
for (const [part, heading] of [
|
|
5272
|
+
["references", "### Files referencing Affected Files"],
|
|
5273
|
+
["identifiers", "### Files containing spec-named identifiers"]
|
|
5274
|
+
]) {
|
|
5275
|
+
const partEntries = entries.filter((entry) => entry.part === part);
|
|
5276
|
+
if (partEntries.length === 0) continue;
|
|
5277
|
+
block += `${heading}
|
|
5278
|
+
${partEntries.map(formatEntry).join("\n")}
|
|
5279
|
+
|
|
5280
|
+
`;
|
|
5281
|
+
}
|
|
5282
|
+
if (skipped > 0) block += `- \u2026 ${skipped} more Affected Files were not scanned for references (scan limit).
|
|
5283
|
+
`;
|
|
5284
|
+
if (omitted > 0) block += `- \u2026 ${omitted} more entries omitted to stay under the size limit.
|
|
5285
|
+
`;
|
|
5286
|
+
return block;
|
|
5287
|
+
}
|
|
5288
|
+
function boundedBlock(entries, skipped = 0) {
|
|
5289
|
+
if (entries.length === 0 && skipped === 0) return "";
|
|
5290
|
+
const full = renderEntries(entries, 0, skipped);
|
|
5291
|
+
if (Buffer.byteLength(full) <= BYTE_CAP) return full;
|
|
5292
|
+
const retained = [...entries];
|
|
5293
|
+
let omitted = 0;
|
|
5294
|
+
while (retained.length > 0) {
|
|
5295
|
+
retained.pop();
|
|
5296
|
+
omitted += 1;
|
|
5297
|
+
const candidate = renderEntries(retained, omitted, skipped);
|
|
5298
|
+
if (Buffer.byteLength(candidate) <= BYTE_CAP) return candidate;
|
|
5299
|
+
}
|
|
5300
|
+
const truncated = renderEntries([], entries.length, skipped);
|
|
5301
|
+
return Buffer.byteLength(truncated) <= BYTE_CAP ? truncated : "";
|
|
5302
|
+
}
|
|
5303
|
+
function buildBlastRadiusBlock(taskIds, root) {
|
|
5304
|
+
try {
|
|
5305
|
+
const repository = gitSafeAt(root, "rev-parse", "--is-inside-work-tree");
|
|
5306
|
+
if (!repository.ok || repository.stdout !== "true") return "";
|
|
5307
|
+
const affectedFiles = [...new Set(taskIds.flatMap((taskId) => extractAffectedFiles(taskId)).map(toRepoRelative))];
|
|
5308
|
+
const directoryEntries = affectedFiles.filter((file) => file.endsWith("/"));
|
|
5309
|
+
const entries = [];
|
|
5310
|
+
const rootPrefix = path11.resolve(root) + path11.sep;
|
|
5311
|
+
const scannable = affectedFiles.filter((file) => {
|
|
5312
|
+
if (file.endsWith("/")) return false;
|
|
5313
|
+
const absolute = path11.resolve(root, file);
|
|
5314
|
+
return absolute.startsWith(rootPrefix) && Boolean(fs13.statSync(absolute, { throwIfNoEntry: false })?.isFile());
|
|
5315
|
+
});
|
|
5316
|
+
const skipped = Math.max(0, scannable.length - REFERENCE_FILE_CAP);
|
|
5317
|
+
for (const file of scannable.slice(0, REFERENCE_FILE_CAP)) {
|
|
5318
|
+
const matches = new Set(trackedReferenceFiles(root, file));
|
|
5319
|
+
const files = [...matches].filter((candidate) => !excludedPath(candidate, affectedFiles, directoryEntries)).sort();
|
|
5320
|
+
if (files.length > 0) entries.push({ part: "references", label: file, files });
|
|
5321
|
+
}
|
|
5322
|
+
for (const token of specTokens(taskIds)) {
|
|
5323
|
+
const files = gitGrep(root, ["-F", "-w"], token).filter((file) => !excludedPath(file, affectedFiles, directoryEntries)).sort();
|
|
5324
|
+
if (files.length > 0) entries.push({ part: "identifiers", label: token, files: [...new Set(files)] });
|
|
5325
|
+
}
|
|
5326
|
+
return boundedBlock(entries, skipped);
|
|
5327
|
+
} catch {
|
|
5328
|
+
return "";
|
|
5329
|
+
}
|
|
5330
|
+
}
|
|
5331
|
+
function resolveBlastRadiusRoot(taskIds) {
|
|
5332
|
+
return process.env[BLAST_RADIUS_ROOT_ENV] || getActiveCwd(taskIds);
|
|
5333
|
+
}
|
|
5334
|
+
|
|
5335
|
+
// src/orchestrator/pitfalls.ts
|
|
5121
5336
|
import fs14 from "fs";
|
|
5122
5337
|
import path12 from "path";
|
|
5338
|
+
var PITFALLS_DOCS_ROOT_ENV = "CANON_PITFALLS_DOCS_ROOT";
|
|
5339
|
+
var PITFALLS_BYTE_CAP = 24 * 1024;
|
|
5340
|
+
var PITFALLS_HEADING = "## Relevant Pitfalls and Lessons (selected by spec Affected Files)";
|
|
5341
|
+
var CHANNEL_PRIORITY = {
|
|
5342
|
+
direct: 0,
|
|
5343
|
+
linked: 1,
|
|
5344
|
+
section: 2,
|
|
5345
|
+
lesson: 3
|
|
5346
|
+
};
|
|
5347
|
+
var DEMOTION_ORDER = ["lesson", "section", "linked", "direct"];
|
|
5348
|
+
var PATTERNS_PATH = "docs/patterns.md";
|
|
5349
|
+
var LESSONS_PATH = "docs/lessons-learned.md";
|
|
5350
|
+
var TARGET_HEADER_HINT = /\b(?:sections?|docs?)\b|read this/i;
|
|
5351
|
+
function scanMarkdown(markdown, docPath) {
|
|
5352
|
+
markdown = markdown.replace(/\r\n?/g, "\n");
|
|
5353
|
+
const lines = markdown.split("\n");
|
|
5354
|
+
const lineStarts = [];
|
|
5355
|
+
const outsideFence = [];
|
|
5356
|
+
let offset = 0;
|
|
5357
|
+
let fenceChar = "";
|
|
5358
|
+
let fenceLength = 0;
|
|
5359
|
+
const headings = [];
|
|
5360
|
+
for (let index = 0; index < lines.length; index++) {
|
|
5361
|
+
const line = lines[index];
|
|
5362
|
+
lineStarts.push(offset);
|
|
5363
|
+
const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
|
|
5364
|
+
const fence = fenceMatch && !(fenceMatch[1][0] === "`" && fenceMatch[2].includes("`")) ? fenceMatch : null;
|
|
5365
|
+
if (fenceChar) {
|
|
5366
|
+
outsideFence.push(false);
|
|
5367
|
+
const closing = fence && fence[1][0] === fenceChar && fence[1].length >= fenceLength && /^\s*$/.test(fence[2]);
|
|
5368
|
+
if (closing) {
|
|
5369
|
+
fenceChar = "";
|
|
5370
|
+
fenceLength = 0;
|
|
5371
|
+
}
|
|
5372
|
+
} else if (fence) {
|
|
5373
|
+
outsideFence.push(false);
|
|
5374
|
+
fenceChar = fence[1][0];
|
|
5375
|
+
fenceLength = fence[1].length;
|
|
5376
|
+
} else {
|
|
5377
|
+
outsideFence.push(true);
|
|
5378
|
+
const match = line.match(/^ {0,3}(#{1,3})[ \t]+(.+?)[ \t]*$/);
|
|
5379
|
+
if (match) {
|
|
5380
|
+
const title = match[2].replace(/[ \t]+#+[ \t]*$/, "").trim();
|
|
5381
|
+
headings.push({
|
|
5382
|
+
level: match[1].length,
|
|
5383
|
+
text: title,
|
|
5384
|
+
start: offset,
|
|
5385
|
+
end: markdown.length,
|
|
5386
|
+
startLine: index,
|
|
5387
|
+
endLine: lines.length
|
|
5388
|
+
});
|
|
5389
|
+
}
|
|
5390
|
+
}
|
|
5391
|
+
offset += line.length + (index < lines.length - 1 ? 1 : 0);
|
|
5392
|
+
}
|
|
5393
|
+
for (let index = 0; index < headings.length; index++) {
|
|
5394
|
+
const heading = headings[index];
|
|
5395
|
+
let endLine = lines.length;
|
|
5396
|
+
let end = markdown.length;
|
|
5397
|
+
for (let next = index + 1; next < headings.length; next++) {
|
|
5398
|
+
if (headings[next].level <= heading.level) {
|
|
5399
|
+
endLine = headings[next].startLine;
|
|
5400
|
+
end = headings[next].start;
|
|
5401
|
+
break;
|
|
5402
|
+
}
|
|
5403
|
+
}
|
|
5404
|
+
heading.endLine = endLine;
|
|
5405
|
+
heading.end = end;
|
|
5406
|
+
}
|
|
5407
|
+
return { path: docPath, text: markdown, lines, lineStarts, outsideFence, headings };
|
|
5408
|
+
}
|
|
5409
|
+
function headingBody(doc, heading) {
|
|
5410
|
+
return doc.text.slice(heading.start, heading.end).trim();
|
|
5411
|
+
}
|
|
5412
|
+
function headingsAt(doc, level) {
|
|
5413
|
+
return doc.headings.filter((heading) => heading.level === level);
|
|
5414
|
+
}
|
|
5415
|
+
function sectionHeading(doc, name) {
|
|
5416
|
+
const target = name.trim().toLocaleLowerCase();
|
|
5417
|
+
if (!target) return null;
|
|
5418
|
+
const choices = doc.headings.filter((heading) => heading.level === 2 || heading.level === 3);
|
|
5419
|
+
const exact = choices.find((heading) => heading.text.toLocaleLowerCase() === target);
|
|
5420
|
+
if (exact) return exact;
|
|
5421
|
+
return choices.filter((heading) => heading.text.toLocaleLowerCase().startsWith(target)).sort((left, right) => left.text.length - right.text.length || left.start - right.start)[0] ?? null;
|
|
5422
|
+
}
|
|
5423
|
+
function knownPitfallEntries(patterns) {
|
|
5424
|
+
const result = [];
|
|
5425
|
+
for (const section of headingsAt(patterns, 2).filter((heading) => heading.text.toLocaleLowerCase().startsWith("known pitfalls"))) {
|
|
5426
|
+
let foundEntry = false;
|
|
5427
|
+
for (const heading of patterns.headings) {
|
|
5428
|
+
if (heading.level !== 3 || heading.start < section.start || heading.start >= section.end) continue;
|
|
5429
|
+
foundEntry = true;
|
|
5430
|
+
result.push({ doc: patterns, heading, title: heading.text, body: headingBody(patterns, heading) });
|
|
5431
|
+
}
|
|
5432
|
+
if (!foundEntry) {
|
|
5433
|
+
const body = proseFallbackBody(patterns, section);
|
|
5434
|
+
if (body) result.push({ doc: patterns, heading: section, title: section.text, body, unconditional: true });
|
|
5435
|
+
}
|
|
5436
|
+
}
|
|
5437
|
+
return result;
|
|
5438
|
+
}
|
|
5439
|
+
function docEntries(doc) {
|
|
5440
|
+
return headingsAt(doc, 3).map((heading) => ({
|
|
5441
|
+
doc,
|
|
5442
|
+
heading,
|
|
5443
|
+
title: heading.text,
|
|
5444
|
+
body: headingBody(doc, heading)
|
|
5445
|
+
}));
|
|
5446
|
+
}
|
|
5447
|
+
function lessonsEntries(lessons) {
|
|
5448
|
+
const excluded = [];
|
|
5449
|
+
for (const heading of headingsAt(lessons, 2)) {
|
|
5450
|
+
const title = heading.text.toLocaleLowerCase();
|
|
5451
|
+
if (title !== "how to use this doc" && title !== "entry format" && !title.startsWith("example")) continue;
|
|
5452
|
+
let end = heading.end;
|
|
5453
|
+
for (let line = heading.startLine + 1; line < heading.endLine; line++) {
|
|
5454
|
+
if (lessons.outsideFence[line] && lessons.lines[line].trim() === "---") {
|
|
5455
|
+
end = lessons.lineStarts[line];
|
|
5456
|
+
break;
|
|
5457
|
+
}
|
|
5458
|
+
}
|
|
5459
|
+
excluded.push({ start: heading.start, end });
|
|
5460
|
+
}
|
|
5461
|
+
return docEntries(lessons).filter((entry) => !excluded.some((scope) => entry.heading.start >= scope.start && entry.heading.start < scope.end));
|
|
5462
|
+
}
|
|
5463
|
+
function isUrl(value) {
|
|
5464
|
+
return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(value);
|
|
5465
|
+
}
|
|
5466
|
+
function stripLineSuffix(value) {
|
|
5467
|
+
return value.replace(/:\d+(?:-\d+)?$/, "");
|
|
5468
|
+
}
|
|
5469
|
+
function normalizeRepoToken(value, fromDoc, markdownLink = false) {
|
|
5470
|
+
let token = value.trim();
|
|
5471
|
+
if (markdownLink) {
|
|
5472
|
+
token = token.replace(/^<|>$/g, "").split("#", 1)[0];
|
|
5473
|
+
if (isUrl(token)) return null;
|
|
5474
|
+
if (path12.posix.isAbsolute(token)) return null;
|
|
5475
|
+
token = path12.posix.join(path12.posix.dirname(fromDoc ?? PATTERNS_PATH), token);
|
|
5476
|
+
}
|
|
5477
|
+
token = stripLineSuffix(token.replaceAll("\\", "/"));
|
|
5478
|
+
if (!token || /\s/.test(token) || isUrl(token) || path12.posix.isAbsolute(token)) return null;
|
|
5479
|
+
const trailingSlash = token.endsWith("/");
|
|
5480
|
+
const normalized = path12.posix.normalize(token.replace(/^\.\//, ""));
|
|
5481
|
+
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
|
|
5482
|
+
const result = trailingSlash && !normalized.endsWith("/") ? `${normalized}/` : normalized;
|
|
5483
|
+
return result.includes("/") || result.includes("*") ? result : null;
|
|
5484
|
+
}
|
|
5485
|
+
function pathTokens(markdown, docPath) {
|
|
5486
|
+
const doc = scanMarkdown(markdown, docPath);
|
|
5487
|
+
const tokens = [];
|
|
5488
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5489
|
+
for (let index = 0; index < doc.lines.length; index++) {
|
|
5490
|
+
if (!doc.outsideFence[index]) continue;
|
|
5491
|
+
const line = doc.lines[index];
|
|
5492
|
+
for (const match of line.matchAll(/`([^`\n]+)`/g)) {
|
|
5493
|
+
const token = normalizeRepoToken(match[1]);
|
|
5494
|
+
if (token && !seen.has(token)) {
|
|
5495
|
+
seen.add(token);
|
|
5496
|
+
tokens.push(token);
|
|
5497
|
+
}
|
|
5498
|
+
}
|
|
5499
|
+
for (const match of line.matchAll(/\]\((<[^>\n]+>|[^)\s]+)(?:\s+"[^"]*")?\)/g)) {
|
|
5500
|
+
const token = normalizeRepoToken(match[1], docPath, true);
|
|
5501
|
+
if (token && !seen.has(token)) {
|
|
5502
|
+
seen.add(token);
|
|
5503
|
+
tokens.push(token);
|
|
5504
|
+
}
|
|
5505
|
+
}
|
|
5506
|
+
}
|
|
5507
|
+
return tokens;
|
|
5508
|
+
}
|
|
5509
|
+
function normalizeAffectedFile(value) {
|
|
5510
|
+
const token = value.replaceAll("\\", "/").trim();
|
|
5511
|
+
if (!token || path12.posix.isAbsolute(token) || /\s/.test(token)) return null;
|
|
5512
|
+
const trailingSlash = token.endsWith("/");
|
|
5513
|
+
const normalized = path12.posix.normalize(token.replace(/^\.\//, ""));
|
|
5514
|
+
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
|
|
5515
|
+
return trailingSlash && !normalized.endsWith("/") ? `${normalized}/` : normalized;
|
|
5516
|
+
}
|
|
5517
|
+
function globCouldMatchInsideDir(glob, dir) {
|
|
5518
|
+
const globSegments = glob.split("/").filter(Boolean);
|
|
5519
|
+
const dirSegments = dir.split("/").filter(Boolean);
|
|
5520
|
+
for (let index = 0; index < dirSegments.length; index++) {
|
|
5521
|
+
if (index >= globSegments.length) return false;
|
|
5522
|
+
if (globSegments[index] === "**") return true;
|
|
5523
|
+
if (!matchesDocsGlob(globSegments[index], dirSegments[index])) return false;
|
|
5524
|
+
}
|
|
5525
|
+
return globSegments.length > dirSegments.length;
|
|
5526
|
+
}
|
|
5527
|
+
function tokenMatches(token, filePath) {
|
|
5528
|
+
if (token === filePath) return true;
|
|
5529
|
+
if (token.endsWith("/") && filePath.startsWith(token)) return true;
|
|
5530
|
+
if (filePath.endsWith("/")) {
|
|
5531
|
+
if (token.startsWith(filePath)) return true;
|
|
5532
|
+
if (token.includes("*") && globCouldMatchInsideDir(token, filePath)) return true;
|
|
5533
|
+
}
|
|
5534
|
+
return token.includes("*") && matchesDocsGlob(token, filePath);
|
|
5535
|
+
}
|
|
5536
|
+
function rowMatches(keys, affectedFiles) {
|
|
5537
|
+
return keys.some((key) => affectedFiles.some((file) => tokenMatches(key, file)));
|
|
5538
|
+
}
|
|
5539
|
+
function splitCells(line) {
|
|
5540
|
+
const source = line.trim();
|
|
5541
|
+
if (!source.startsWith("|") || !source.endsWith("|")) return null;
|
|
5542
|
+
const cells = [];
|
|
5543
|
+
let cell = "";
|
|
5544
|
+
let codeTicks = 0;
|
|
5545
|
+
for (let index = 1; index < source.length - 1; index++) {
|
|
5546
|
+
const char = source[index];
|
|
5547
|
+
if (char === "`") {
|
|
5548
|
+
let runLength = 1;
|
|
5549
|
+
while (source[index + runLength] === "`") runLength++;
|
|
5550
|
+
if (codeTicks === 0) codeTicks = runLength;
|
|
5551
|
+
else if (runLength === codeTicks) codeTicks = 0;
|
|
5552
|
+
cell += "`".repeat(runLength);
|
|
5553
|
+
index += runLength - 1;
|
|
5554
|
+
} else if (char === "\\" && source[index + 1] === "|") {
|
|
5555
|
+
cell += "\\|";
|
|
5556
|
+
index++;
|
|
5557
|
+
} else if (char === "|" && codeTicks === 0) {
|
|
5558
|
+
cells.push(cell.trim());
|
|
5559
|
+
cell = "";
|
|
5560
|
+
} else {
|
|
5561
|
+
cell += char;
|
|
5562
|
+
}
|
|
5563
|
+
}
|
|
5564
|
+
if (codeTicks !== 0) return null;
|
|
5565
|
+
cells.push(cell.trim());
|
|
5566
|
+
return cells.length >= 2 ? cells : null;
|
|
5567
|
+
}
|
|
5568
|
+
function isSeparatorRow2(cells) {
|
|
5569
|
+
return cells.every((cell) => /^:?-+:?$/.test(cell.replaceAll(" ", "")));
|
|
5570
|
+
}
|
|
5571
|
+
function markdownTablesInSection(doc, section) {
|
|
5572
|
+
const result = [];
|
|
5573
|
+
let line = section.startLine + 1;
|
|
5574
|
+
while (line < section.endLine) {
|
|
5575
|
+
if (!doc.outsideFence[line]) {
|
|
5576
|
+
line++;
|
|
5577
|
+
continue;
|
|
5578
|
+
}
|
|
5579
|
+
const header = splitCells(doc.lines[line]);
|
|
5580
|
+
const separator = line + 1 < section.endLine ? splitCells(doc.lines[line + 1]) : null;
|
|
5581
|
+
if (!header || !separator || !isSeparatorRow2(separator) || separator.length !== header.length) {
|
|
5582
|
+
line++;
|
|
5583
|
+
continue;
|
|
5584
|
+
}
|
|
5585
|
+
const startLine = line;
|
|
5586
|
+
line += 2;
|
|
5587
|
+
const tableRows = [];
|
|
5588
|
+
while (line < section.endLine) {
|
|
5589
|
+
if (!doc.outsideFence[line]) break;
|
|
5590
|
+
const cells = splitCells(doc.lines[line]);
|
|
5591
|
+
if (!cells) {
|
|
5592
|
+
const raw = doc.lines[line].trim();
|
|
5593
|
+
if (raw.startsWith("|") && raw.endsWith("|")) {
|
|
5594
|
+
tableRows.push([raw.replace(/^\|/, "").replace(/\|$/, "").trim()]);
|
|
5595
|
+
line++;
|
|
5596
|
+
continue;
|
|
5597
|
+
}
|
|
5598
|
+
break;
|
|
5599
|
+
}
|
|
5600
|
+
if (cells.length !== header.length) {
|
|
5601
|
+
tableRows.push([doc.lines[line].trim().replace(/^\|/, "").replace(/\|$/, "").trim()]);
|
|
5602
|
+
} else if (!isSeparatorRow2(cells)) {
|
|
5603
|
+
tableRows.push(cells);
|
|
5604
|
+
}
|
|
5605
|
+
line++;
|
|
5606
|
+
}
|
|
5607
|
+
result.push({ startLine, endLine: line, header, rows: tableRows });
|
|
5608
|
+
}
|
|
5609
|
+
return result;
|
|
5610
|
+
}
|
|
5611
|
+
function knownPitfallsIndexTables(doc, section) {
|
|
5612
|
+
const firstH3Line = doc.headings.find((heading) => heading.level === 3 && heading.start >= section.start && heading.start < section.end)?.startLine ?? section.endLine;
|
|
5613
|
+
return markdownTablesInSection(doc, section).filter((table) => table.startLine < firstH3Line);
|
|
5614
|
+
}
|
|
5615
|
+
var BLOCK_START = /^ {0,3}(?:#{1,6}(?:\s|$)|[-*+]\s|\d{1,9}[.)]\s|```|~~~|\||<|(?:[-*_][ \t]*){3,}$)/;
|
|
5616
|
+
function proseFallbackBody(patterns, section) {
|
|
5617
|
+
const indexLines = /* @__PURE__ */ new Set();
|
|
5618
|
+
for (const table of knownPitfallsIndexTables(patterns, section)) {
|
|
5619
|
+
for (let line = table.startLine; line < table.endLine; line++) indexLines.add(line);
|
|
5620
|
+
}
|
|
5621
|
+
const keptLines = [];
|
|
5622
|
+
let inBlockquote = false;
|
|
5623
|
+
for (let line = section.startLine + 1; line < section.endLine; line++) {
|
|
5624
|
+
if (indexLines.has(line)) continue;
|
|
5625
|
+
const text = patterns.lines[line];
|
|
5626
|
+
if (!patterns.outsideFence[line]) {
|
|
5627
|
+
keptLines.push(text);
|
|
5628
|
+
continue;
|
|
5629
|
+
}
|
|
5630
|
+
if (/^ {0,3}>/.test(text)) {
|
|
5631
|
+
inBlockquote = true;
|
|
5632
|
+
continue;
|
|
5633
|
+
}
|
|
5634
|
+
if (inBlockquote && text.trim() !== "" && !BLOCK_START.test(text)) continue;
|
|
5635
|
+
if (inBlockquote) inBlockquote = false;
|
|
5636
|
+
keptLines.push(text);
|
|
5637
|
+
}
|
|
5638
|
+
return keptLines.join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
5639
|
+
}
|
|
5640
|
+
function tableRowsInSection(doc, section) {
|
|
5641
|
+
if (section.text.toLocaleLowerCase().startsWith("known pitfalls")) return knownPitfallsIndexTables(doc, section);
|
|
5642
|
+
return markdownTablesInSection(doc, section);
|
|
5643
|
+
}
|
|
5644
|
+
function stripParenthetical(value) {
|
|
5645
|
+
return value.replace(/\[[^\]]+\]\([^)]+\)|\([^)]*\)/g, (match) => match.startsWith("[") ? match : "").trim();
|
|
5646
|
+
}
|
|
5647
|
+
function resolveLinkPath(target) {
|
|
5648
|
+
const link = target.trim().replace(/^<|>$/g, "").split("#", 1)[0];
|
|
5649
|
+
if (!link || isUrl(link) || path12.posix.isAbsolute(link)) return null;
|
|
5650
|
+
const resolved = path12.posix.normalize(path12.posix.join(path12.posix.dirname(PATTERNS_PATH), link));
|
|
5651
|
+
if (resolved === ".." || resolved.startsWith("../")) return null;
|
|
5652
|
+
return resolved;
|
|
5653
|
+
}
|
|
5654
|
+
function parseDocPathItem(item) {
|
|
5655
|
+
const codePath = item.match(/^\s*`([^`]+)`\s*$/);
|
|
5656
|
+
if (codePath) {
|
|
5657
|
+
const normalized = normalizeRepoToken(codePath[1]);
|
|
5658
|
+
if (normalized?.toLocaleLowerCase().endsWith(".md") && !normalized.includes("*")) return { path: normalized };
|
|
5659
|
+
return null;
|
|
5660
|
+
}
|
|
5661
|
+
const link = item.match(/^\s*\[[^\]]+\]\((<[^>]+>|[^)\s]+)(?:\s+"[^"]*")?\)\s*$/);
|
|
5662
|
+
if (link) {
|
|
5663
|
+
const resolved = resolveLinkPath(link[1]);
|
|
5664
|
+
if (resolved?.toLocaleLowerCase().endsWith(".md") && !resolved.includes("*")) return { path: resolved };
|
|
5665
|
+
}
|
|
5666
|
+
return null;
|
|
5667
|
+
}
|
|
5668
|
+
function docSectionMatch(item) {
|
|
5669
|
+
return stripParenthetical(item).match(/^\s*(`[^`]+`|\[[^\]]+\]\([^)]+\))\s*§\s*(.+?)\s*$/);
|
|
5670
|
+
}
|
|
5671
|
+
function isDocSectionItem(item) {
|
|
5672
|
+
return docSectionMatch(item) !== null;
|
|
5673
|
+
}
|
|
5674
|
+
function parseTargetFromItem(item, patterns, readDoc) {
|
|
5675
|
+
const clean = stripParenthetical(item);
|
|
5676
|
+
const docSection = docSectionMatch(item);
|
|
5677
|
+
if (docSection) {
|
|
5678
|
+
const parsed = parseDocPathItem(docSection[1]);
|
|
5679
|
+
if (!parsed) return null;
|
|
5680
|
+
const sectionName2 = docSection[2].replaceAll("`", "").trim();
|
|
5681
|
+
const doc = parsed.path === PATTERNS_PATH ? patterns : (() => {
|
|
5682
|
+
const text = readDoc(parsed.path);
|
|
5683
|
+
return text === null ? null : scanMarkdown(text, parsed.path);
|
|
5684
|
+
})();
|
|
5685
|
+
const heading2 = doc ? sectionHeading(doc, sectionName2) : null;
|
|
5686
|
+
if (!heading2 || !doc) return null;
|
|
5687
|
+
return {
|
|
5688
|
+
target: { kind: "doc-section", path: parsed.path, section: heading2.text },
|
|
5689
|
+
specificity: heading2.text.toLocaleLowerCase() === sectionName2.toLocaleLowerCase() ? 2 : 0
|
|
5690
|
+
};
|
|
5691
|
+
}
|
|
5692
|
+
const docPath = parseDocPathItem(clean);
|
|
5693
|
+
if (docPath) {
|
|
5694
|
+
if (docPath.path === PATTERNS_PATH) return null;
|
|
5695
|
+
return { target: { kind: "linked", path: docPath.path }, specificity: 1 };
|
|
5696
|
+
}
|
|
5697
|
+
const sectionName = clean.replaceAll("`", "").trim();
|
|
5698
|
+
const heading = sectionHeading(patterns, sectionName);
|
|
5699
|
+
if (!heading) return null;
|
|
5700
|
+
return {
|
|
5701
|
+
target: { kind: "section", doc: patterns, heading },
|
|
5702
|
+
specificity: heading.text.toLocaleLowerCase() === sectionName.toLocaleLowerCase() ? 2 : 0
|
|
5703
|
+
};
|
|
5704
|
+
}
|
|
5705
|
+
function splitTargetItems(value) {
|
|
5706
|
+
const items = [];
|
|
5707
|
+
let item = "";
|
|
5708
|
+
let parentheses = 0;
|
|
5709
|
+
let codeTicks = 0;
|
|
5710
|
+
for (let index = 0; index < value.length; index++) {
|
|
5711
|
+
const char = value[index];
|
|
5712
|
+
if (char === "`") {
|
|
5713
|
+
let runLength = 1;
|
|
5714
|
+
while (value[index + runLength] === "`") runLength++;
|
|
5715
|
+
if (codeTicks === 0) codeTicks = runLength;
|
|
5716
|
+
else if (runLength === codeTicks) codeTicks = 0;
|
|
5717
|
+
item += "`".repeat(runLength);
|
|
5718
|
+
index += runLength - 1;
|
|
5719
|
+
} else if (codeTicks === 0 && char === "(") {
|
|
5720
|
+
parentheses++;
|
|
5721
|
+
item += char;
|
|
5722
|
+
} else if (codeTicks === 0 && char === ")" && parentheses > 0) {
|
|
5723
|
+
parentheses--;
|
|
5724
|
+
item += char;
|
|
5725
|
+
} else if (codeTicks === 0 && parentheses === 0 && char === ";") {
|
|
5726
|
+
items.push(item.trim());
|
|
5727
|
+
item = "";
|
|
5728
|
+
} else {
|
|
5729
|
+
item += char;
|
|
5730
|
+
}
|
|
5731
|
+
}
|
|
5732
|
+
items.push(item.trim());
|
|
5733
|
+
return items.filter(Boolean);
|
|
5734
|
+
}
|
|
5735
|
+
function buildIndexRows(patterns, affectedFiles, readDoc) {
|
|
5736
|
+
if (!patterns) return [];
|
|
5737
|
+
const sections = patterns.headings.filter((heading) => heading.level === 2 && (heading.text.toLocaleLowerCase().startsWith("trigger table") || heading.text.toLocaleLowerCase().startsWith("known pitfalls")));
|
|
5738
|
+
const rows = [];
|
|
5739
|
+
for (const section of sections) {
|
|
5740
|
+
for (const table of tableRowsInSection(patterns, section)) {
|
|
5741
|
+
const targetHint = table.header.findIndex((cell) => TARGET_HEADER_HINT.test(cell.replaceAll("`", "").replaceAll("*", "")));
|
|
5742
|
+
for (const cells of table.rows) {
|
|
5743
|
+
if (cells.length === 1) {
|
|
5744
|
+
rows.push({ line: `- ${cells[0]}`, targets: [], keys: [], matched: false });
|
|
5745
|
+
continue;
|
|
5746
|
+
}
|
|
5747
|
+
let targetCell = targetHint >= 0 && targetHint < cells.length ? targetHint : 0;
|
|
5748
|
+
if (targetHint < 0) {
|
|
5749
|
+
const hasDocPathOrSectionReference = (item) => {
|
|
5750
|
+
if (isDocSectionItem(item)) return true;
|
|
5751
|
+
const docPath = parseDocPathItem(stripParenthetical(item));
|
|
5752
|
+
return docPath !== null && docPath.path !== PATTERNS_PATH;
|
|
5753
|
+
};
|
|
5754
|
+
const isExactSection = (item) => {
|
|
5755
|
+
const parsed = parseTargetFromItem(item, patterns, readDoc);
|
|
5756
|
+
return parsed !== null && parsed.specificity === 2 && parsed.target.kind !== "linked";
|
|
5757
|
+
};
|
|
5758
|
+
const isPrefixSection = (item) => {
|
|
5759
|
+
const parsed = parseTargetFromItem(item, patterns, readDoc);
|
|
5760
|
+
return parsed !== null && parsed.specificity === 0 && parsed.target.kind !== "linked";
|
|
5761
|
+
};
|
|
5762
|
+
const tiers = [hasDocPathOrSectionReference, isExactSection, isPrefixSection];
|
|
5763
|
+
for (const matchesTier of tiers) {
|
|
5764
|
+
const index = cells.findIndex((cell) => splitTargetItems(cell).some(matchesTier));
|
|
5765
|
+
if (index >= 0) {
|
|
5766
|
+
targetCell = index;
|
|
5767
|
+
break;
|
|
5768
|
+
}
|
|
5769
|
+
}
|
|
5770
|
+
}
|
|
5771
|
+
const targets = targetHint >= 0 && targetHint >= cells.length ? [] : splitTargetItems(cells[targetCell]).map((item) => parseTargetFromItem(item, patterns, readDoc)).filter((item) => item !== null).map((item) => item.target);
|
|
5772
|
+
const keys = cells.flatMap((cell, index) => index === targetCell ? [] : pathTokens(cell, patterns.path));
|
|
5773
|
+
const matched = rowMatches(keys, affectedFiles);
|
|
5774
|
+
const targetText = cells[targetCell];
|
|
5775
|
+
const otherText = cells.filter((_, index) => index !== targetCell).join(" \u2014 ");
|
|
5776
|
+
const line = `- ${targetText}${otherText ? ` \u2014 ${otherText}` : ""}${matched ? " **(matches this task)**" : ""}`;
|
|
5777
|
+
rows.push({ line, targets, keys, matched });
|
|
5778
|
+
}
|
|
5779
|
+
}
|
|
5780
|
+
}
|
|
5781
|
+
return rows;
|
|
5782
|
+
}
|
|
5783
|
+
function addCandidate(candidates, candidate) {
|
|
5784
|
+
const sameSpanIndex = candidates.findIndex((existing) => existing.doc.path === candidate.doc.path && existing.start === candidate.start && existing.end === candidate.end);
|
|
5785
|
+
if (sameSpanIndex >= 0) {
|
|
5786
|
+
if (CHANNEL_PRIORITY[candidate.channel] < CHANNEL_PRIORITY[candidates[sameSpanIndex].channel]) {
|
|
5787
|
+
candidates[sameSpanIndex] = candidate;
|
|
5788
|
+
}
|
|
5789
|
+
return;
|
|
5790
|
+
}
|
|
5791
|
+
candidates.push(candidate);
|
|
5792
|
+
}
|
|
5793
|
+
function candidateFromEntry(entry, channel, docOrder) {
|
|
5794
|
+
return {
|
|
5795
|
+
doc: entry.doc,
|
|
5796
|
+
start: entry.heading.start,
|
|
5797
|
+
end: entry.heading.end,
|
|
5798
|
+
title: entry.title,
|
|
5799
|
+
body: entry.body,
|
|
5800
|
+
channel,
|
|
5801
|
+
docOrder,
|
|
5802
|
+
position: entry.heading.start,
|
|
5803
|
+
unconditional: entry.unconditional
|
|
5804
|
+
};
|
|
5805
|
+
}
|
|
5806
|
+
function candidateFromSection(doc, heading, docOrder) {
|
|
5807
|
+
return {
|
|
5808
|
+
doc,
|
|
5809
|
+
start: heading.start,
|
|
5810
|
+
end: heading.end,
|
|
5811
|
+
title: heading.text,
|
|
5812
|
+
body: headingBody(doc, heading),
|
|
5813
|
+
channel: "section",
|
|
5814
|
+
docOrder,
|
|
5815
|
+
position: heading.start
|
|
5816
|
+
};
|
|
5817
|
+
}
|
|
5818
|
+
function candidateCovered(candidate, others) {
|
|
5819
|
+
return others.some((other) => other.doc.path === candidate.doc.path && other.start <= candidate.start && other.end >= candidate.end && (other.start < candidate.start || other.end > candidate.end));
|
|
5820
|
+
}
|
|
5821
|
+
function visibleCandidates(active) {
|
|
5822
|
+
return active.filter((candidate) => !candidateCovered(candidate, active)).sort((left, right) => left.docOrder - right.docOrder || left.start - right.start);
|
|
5823
|
+
}
|
|
5824
|
+
function entryIsCovered(entry, active) {
|
|
5825
|
+
return active.some((candidate) => candidate.doc.path === entry.doc.path && candidate.start <= entry.heading.start && candidate.end >= entry.heading.end);
|
|
5826
|
+
}
|
|
5827
|
+
function isPathInsideRoot(root, repoPath) {
|
|
5828
|
+
if (path12.isAbsolute(repoPath) || repoPath.split(/[\\/]/).includes("..")) return false;
|
|
5829
|
+
const resolvedRoot = path12.resolve(root);
|
|
5830
|
+
const resolved = path12.resolve(resolvedRoot, ...repoPath.split("/"));
|
|
5831
|
+
if (!resolved.startsWith(`${resolvedRoot}${path12.sep}`)) return false;
|
|
5832
|
+
try {
|
|
5833
|
+
const realRoot = fs14.realpathSync(resolvedRoot);
|
|
5834
|
+
const realPath = fs14.realpathSync(resolved);
|
|
5835
|
+
return realPath.startsWith(`${realRoot}${path12.sep}`);
|
|
5836
|
+
} catch {
|
|
5837
|
+
return false;
|
|
5838
|
+
}
|
|
5839
|
+
}
|
|
5840
|
+
function titleGroupsFor(entriesByDoc, active, demoted, matchedLinkedDocs) {
|
|
5841
|
+
const byDoc = /* @__PURE__ */ new Map();
|
|
5842
|
+
for (const [doc, entries] of entriesByDoc) {
|
|
5843
|
+
const titles = entries.filter((entry) => !entryIsCovered(entry, active)).map((entry) => entry.title);
|
|
5844
|
+
if (titles.length > 0) byDoc.set(doc, { doc, titles, open: matchedLinkedDocs.has(doc) });
|
|
5845
|
+
}
|
|
5846
|
+
for (const candidate of demoted) {
|
|
5847
|
+
if (candidate.channel !== "direct" && candidate.channel !== "linked") continue;
|
|
5848
|
+
const group = byDoc.get(candidate.doc.path) ?? { doc: candidate.doc.path, titles: [], open: matchedLinkedDocs.has(candidate.doc.path) };
|
|
5849
|
+
if (!group.titles.includes(candidate.title)) group.titles.push(candidate.title);
|
|
5850
|
+
byDoc.set(candidate.doc.path, group);
|
|
5851
|
+
}
|
|
5852
|
+
return [...byDoc.values()];
|
|
5853
|
+
}
|
|
5854
|
+
function bodyByteLength(value) {
|
|
5855
|
+
return Buffer.byteLength(value, "utf8");
|
|
5856
|
+
}
|
|
5857
|
+
function selectPitfallsInternal(input) {
|
|
5858
|
+
const affectedFiles = [...new Set(input.affectedFiles.map(normalizeAffectedFile).filter((value) => value !== null))];
|
|
5859
|
+
const patterns = input.patterns === null ? null : scanMarkdown(input.patterns, PATTERNS_PATH);
|
|
5860
|
+
const lessonsDoc = input.lessons === null ? null : scanMarkdown(input.lessons, LESSONS_PATH);
|
|
5861
|
+
const linkedDocCache = /* @__PURE__ */ new Map();
|
|
5862
|
+
const readLinkedDoc = (repoPath) => {
|
|
5863
|
+
if (linkedDocCache.has(repoPath)) return linkedDocCache.get(repoPath) ?? null;
|
|
5864
|
+
let text = null;
|
|
5865
|
+
try {
|
|
5866
|
+
text = input.readDoc(repoPath);
|
|
5867
|
+
} catch {
|
|
5868
|
+
text = null;
|
|
5869
|
+
}
|
|
5870
|
+
const doc = text === null ? null : scanMarkdown(text, repoPath);
|
|
5871
|
+
linkedDocCache.set(repoPath, doc);
|
|
5872
|
+
return doc;
|
|
5873
|
+
};
|
|
5874
|
+
const indexRows = buildIndexRows(patterns, affectedFiles, (repoPath) => readLinkedDoc(repoPath)?.text ?? null);
|
|
5875
|
+
const linkedPaths = [];
|
|
5876
|
+
const linkedPathSeen = /* @__PURE__ */ new Set();
|
|
5877
|
+
const matchedLinkedDocs = /* @__PURE__ */ new Set();
|
|
5878
|
+
for (const row of indexRows) {
|
|
5879
|
+
for (const target of row.targets) {
|
|
5880
|
+
if (target.kind === "linked") {
|
|
5881
|
+
if (!linkedPathSeen.has(target.path)) {
|
|
5882
|
+
linkedPathSeen.add(target.path);
|
|
5883
|
+
linkedPaths.push(target.path);
|
|
5884
|
+
}
|
|
5885
|
+
if (row.matched) matchedLinkedDocs.add(target.path);
|
|
5886
|
+
}
|
|
5887
|
+
}
|
|
5888
|
+
}
|
|
5889
|
+
const candidates = [];
|
|
5890
|
+
const titleEntries = /* @__PURE__ */ new Map();
|
|
5891
|
+
const patternsEntries = patterns ? knownPitfallEntries(patterns) : [];
|
|
5892
|
+
if (patterns) titleEntries.set(patterns.path, patternsEntries);
|
|
5893
|
+
if (patterns) {
|
|
5894
|
+
for (const entry of patternsEntries) {
|
|
5895
|
+
if (entry.unconditional || pathTokens(entry.body, patterns.path).some((token) => rowMatches([token], affectedFiles))) {
|
|
5896
|
+
addCandidate(candidates, candidateFromEntry(entry, "direct", 0));
|
|
5897
|
+
}
|
|
5898
|
+
}
|
|
5899
|
+
}
|
|
5900
|
+
linkedPaths.forEach((repoPath, index) => {
|
|
5901
|
+
const doc = readLinkedDoc(repoPath);
|
|
5902
|
+
if (!doc) return;
|
|
5903
|
+
const entries = docEntries(doc);
|
|
5904
|
+
titleEntries.set(repoPath, entries);
|
|
5905
|
+
for (const entry of entries) {
|
|
5906
|
+
if (pathTokens(entry.body, doc.path).some((token) => rowMatches([token], affectedFiles))) {
|
|
5907
|
+
addCandidate(candidates, candidateFromEntry(entry, "linked", index + 1));
|
|
5908
|
+
}
|
|
5909
|
+
}
|
|
5910
|
+
});
|
|
5911
|
+
if (patterns) {
|
|
5912
|
+
for (const row of indexRows) {
|
|
5913
|
+
if (!row.matched) continue;
|
|
5914
|
+
for (const target of row.targets) {
|
|
5915
|
+
if (target.kind === "section") addCandidate(candidates, candidateFromSection(target.doc, target.heading, 0));
|
|
5916
|
+
else if (target.kind === "doc-section") {
|
|
5917
|
+
const doc = target.path === PATTERNS_PATH ? patterns : readLinkedDoc(target.path);
|
|
5918
|
+
const heading = doc ? sectionHeading(doc, target.section) : null;
|
|
5919
|
+
if (doc && heading) addCandidate(candidates, candidateFromSection(doc, heading, target.path === PATTERNS_PATH ? 0 : linkedPaths.indexOf(target.path) + 1 || linkedPaths.length + 1));
|
|
5920
|
+
}
|
|
5921
|
+
}
|
|
5922
|
+
}
|
|
5923
|
+
}
|
|
5924
|
+
const lessonEntries = lessonsDoc ? lessonsEntries(lessonsDoc) : [];
|
|
5925
|
+
if (lessonsDoc) {
|
|
5926
|
+
for (const entry of lessonEntries) {
|
|
5927
|
+
if (pathTokens(entry.body, lessonsDoc.path).some((token) => rowMatches([token], affectedFiles))) {
|
|
5928
|
+
addCandidate(candidates, candidateFromEntry(entry, "lesson", Number.MAX_SAFE_INTEGER));
|
|
5929
|
+
}
|
|
5930
|
+
}
|
|
5931
|
+
}
|
|
5932
|
+
let active = [...candidates];
|
|
5933
|
+
const demoted = [];
|
|
5934
|
+
const titleLimitState = { perDoc: Number.POSITIVE_INFINITY };
|
|
5935
|
+
const areaLimitState = { count: indexRows.length };
|
|
5936
|
+
const demotedLimitState = { count: Number.POSITIVE_INFINITY };
|
|
5937
|
+
const requestedCap = input.cap ?? PITFALLS_BYTE_CAP;
|
|
5938
|
+
const cap = Number.isFinite(requestedCap) ? Math.max(0, Math.floor(requestedCap)) : PITFALLS_BYTE_CAP;
|
|
5939
|
+
let capped = false;
|
|
5940
|
+
function render4() {
|
|
5941
|
+
const full = visibleCandidates(active);
|
|
5942
|
+
const pitfallFull = full.filter((candidate) => candidate.channel !== "lesson" && !candidate.unconditional);
|
|
5943
|
+
const proseFull = full.filter((candidate) => candidate.unconditional);
|
|
5944
|
+
const lessonFull = full.filter((candidate) => candidate.channel === "lesson");
|
|
5945
|
+
const groups2 = titleGroupsFor(titleEntries, active, demoted, matchedLinkedDocs);
|
|
5946
|
+
const titleLines = [];
|
|
5947
|
+
let droppedTitles = 0;
|
|
5948
|
+
for (const group of groups2) {
|
|
5949
|
+
const shown = group.titles.slice(0, titleLimitState.perDoc);
|
|
5950
|
+
const omitted = group.titles.length - shown.length;
|
|
5951
|
+
droppedTitles += omitted;
|
|
5952
|
+
if (shown.length === 0 && omitted === 0) continue;
|
|
5953
|
+
titleLines.push(`**${group.doc}**`);
|
|
5954
|
+
if (group.open) titleLines.push(`Open \`${group.doc}\` \u2014 it covers files this task touches.`);
|
|
5955
|
+
for (const title of shown) titleLines.push(`- ${title}`);
|
|
5956
|
+
if (omitted > 0) titleLines.push(`- +${omitted} more in ${group.doc}`);
|
|
5957
|
+
}
|
|
5958
|
+
const areaVisible = indexRows.slice(0, areaLimitState.count).map((row) => row.line);
|
|
5959
|
+
const droppedRows = indexRows.length - areaVisible.length;
|
|
5960
|
+
if (droppedRows > 0) areaVisible.push(`- +${droppedRows} more index rows`);
|
|
5961
|
+
const demotedCandidates = demoted.filter((candidate) => candidate.channel === "section" || candidate.channel === "lesson");
|
|
5962
|
+
const demotedVisible = demotedCandidates.slice(0, demotedLimitState.count);
|
|
5963
|
+
const droppedDemoted = demotedCandidates.length - demotedVisible.length;
|
|
5964
|
+
const demotedLines = demotedVisible.map((candidate) => `- ${candidate.title} (demoted to fit)`);
|
|
5965
|
+
if (droppedDemoted > 0) demotedLines.push(`- +${droppedDemoted} more demoted titles`);
|
|
5966
|
+
const sections = [];
|
|
5967
|
+
if (pitfallFull.length > 0) sections.push(`### Pitfalls and patterns that cite your files
|
|
5968
|
+
|
|
5969
|
+
${pitfallFull.map((candidate) => candidate.body).join("\n\n")}`);
|
|
5970
|
+
if (proseFull.length > 0) sections.push(`### Known Pitfalls (included regardless of your files)
|
|
5971
|
+
|
|
5972
|
+
_This section has no \`###\` entries, so its prose is included in full (index tables and blockquotes omitted) whatever the task's Affected Files._
|
|
5973
|
+
|
|
5974
|
+
${proseFull.map((candidate) => candidate.body).join("\n\n")}`);
|
|
5975
|
+
if (lessonFull.length > 0) sections.push(`### Lessons that cite your files
|
|
5976
|
+
|
|
5977
|
+
${lessonFull.map((candidate) => candidate.body).join("\n\n")}`);
|
|
5978
|
+
if (areaVisible.length > 0) sections.push(`### Area index
|
|
5979
|
+
|
|
5980
|
+
${areaVisible.join("\n")}`);
|
|
5981
|
+
if (titleLines.length > 0) sections.push(`### Other pitfalls (titles only)
|
|
5982
|
+
|
|
5983
|
+
${titleLines.join("\n")}`);
|
|
5984
|
+
if (demotedLines.length > 0) sections.push(`### Demoted to fit the cap
|
|
5985
|
+
|
|
5986
|
+
${demotedLines.join("\n")}`);
|
|
5987
|
+
const totalDemoted = demoted.length;
|
|
5988
|
+
const note = capped ? `
|
|
5989
|
+
|
|
5990
|
+
_Pitfalls block capped at ${cap} bytes: ${totalDemoted} full ${totalDemoted === 1 ? "candidate" : "candidates"} demoted; ${droppedTitles} titles and ${droppedRows} index rows dropped; ${droppedDemoted} demoted titles dropped._` : "";
|
|
5991
|
+
if (sections.length === 0 && !note) return "";
|
|
5992
|
+
const framing = "Selected full entries match paths in the task spec\u2019s Affected Files. Other pitfalls stay visible by title; open a title\u2019s doc when it may apply.";
|
|
5993
|
+
return `
|
|
5994
|
+
${PITFALLS_HEADING}
|
|
5995
|
+
|
|
5996
|
+
${framing}
|
|
5997
|
+
|
|
5998
|
+
${sections.join("\n\n")}${note}
|
|
5999
|
+
|
|
6000
|
+
`;
|
|
6001
|
+
}
|
|
6002
|
+
capped = bodyByteLength(render4()) > cap;
|
|
6003
|
+
while (bodyByteLength(render4()) > cap) {
|
|
6004
|
+
const visible = visibleCandidates(active);
|
|
6005
|
+
if (visible.length === 0) break;
|
|
6006
|
+
let selected;
|
|
6007
|
+
for (const channel of DEMOTION_ORDER) {
|
|
6008
|
+
const group = visible.filter((candidate) => candidate.channel === channel);
|
|
6009
|
+
if (group.length === 0) continue;
|
|
6010
|
+
selected = group.sort((left, right) => bodyByteLength(right.body) - bodyByteLength(left.body) || right.docOrder - left.docOrder || right.position - left.position)[0];
|
|
6011
|
+
break;
|
|
6012
|
+
}
|
|
6013
|
+
if (!selected) break;
|
|
6014
|
+
active = active.filter((candidate) => candidate !== selected);
|
|
6015
|
+
demoted.push(selected);
|
|
6016
|
+
}
|
|
6017
|
+
if (bodyByteLength(render4()) > cap) {
|
|
6018
|
+
const groups2 = titleGroupsFor(titleEntries, active, demoted, matchedLinkedDocs);
|
|
6019
|
+
const largest = Math.max(0, ...groups2.map((group) => group.titles.length));
|
|
6020
|
+
for (let keep = largest - 1; keep >= 0 && bodyByteLength(render4()) > cap; keep--) {
|
|
6021
|
+
titleLimitState.perDoc = keep;
|
|
6022
|
+
}
|
|
6023
|
+
}
|
|
6024
|
+
if (bodyByteLength(render4()) > cap) {
|
|
6025
|
+
for (let keep = indexRows.length - 1; keep >= 0 && bodyByteLength(render4()) > cap; keep--) {
|
|
6026
|
+
areaLimitState.count = keep;
|
|
6027
|
+
}
|
|
6028
|
+
}
|
|
6029
|
+
if (bodyByteLength(render4()) > cap) {
|
|
6030
|
+
const demotedTitleCount = demoted.filter((candidate) => candidate.channel === "section" || candidate.channel === "lesson").length;
|
|
6031
|
+
for (let keep = demotedTitleCount - 1; keep >= 0 && bodyByteLength(render4()) > cap; keep--) {
|
|
6032
|
+
demotedLimitState.count = keep;
|
|
6033
|
+
}
|
|
6034
|
+
}
|
|
6035
|
+
const rendered = render4();
|
|
6036
|
+
if (bodyByteLength(rendered) <= cap) return rendered;
|
|
6037
|
+
const groups = titleGroupsFor(titleEntries, active, demoted, matchedLinkedDocs);
|
|
6038
|
+
const titleCount = groups.reduce((total, group) => total + group.titles.length, 0);
|
|
6039
|
+
const allDemotedTitles = demoted.filter((candidate) => candidate.channel === "section" || candidate.channel === "lesson").length;
|
|
6040
|
+
const droppedDemotedTitles = Math.max(0, allDemotedTitles - demotedLimitState.count);
|
|
6041
|
+
const summary = `
|
|
6042
|
+
${PITFALLS_HEADING}
|
|
6043
|
+
|
|
6044
|
+
_Pitfalls block capped at ${cap} bytes: ${demoted.length} full candidates demoted; ${titleCount} titles and ${indexRows.length} index rows dropped; ${droppedDemotedTitles} demoted titles dropped._
|
|
6045
|
+
|
|
6046
|
+
`;
|
|
6047
|
+
return bodyByteLength(summary) <= cap ? summary : "";
|
|
6048
|
+
}
|
|
6049
|
+
function selectPitfalls(input) {
|
|
6050
|
+
try {
|
|
6051
|
+
return selectPitfallsInternal(input);
|
|
6052
|
+
} catch (error) {
|
|
6053
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
6054
|
+
console.warn(`Unable to select relevant pitfalls and lessons: ${detail}`);
|
|
6055
|
+
return "";
|
|
6056
|
+
}
|
|
6057
|
+
}
|
|
6058
|
+
function readOrNull(filePath) {
|
|
6059
|
+
try {
|
|
6060
|
+
return fs14.readFileSync(filePath, "utf8");
|
|
6061
|
+
} catch {
|
|
6062
|
+
return null;
|
|
6063
|
+
}
|
|
6064
|
+
}
|
|
6065
|
+
function resolvePitfallsDocsRoot(taskIds) {
|
|
6066
|
+
return process.env[PITFALLS_DOCS_ROOT_ENV] || getActiveCwd(taskIds);
|
|
6067
|
+
}
|
|
6068
|
+
function buildRelevantPitfalls(taskIds) {
|
|
6069
|
+
const root = resolvePitfallsDocsRoot(taskIds);
|
|
6070
|
+
const patternsPath = process.env.CANON_PATTERNS_MD_PATH || path12.join(root, PATTERNS_PATH);
|
|
6071
|
+
const affectedFiles = [...new Set(taskIds.flatMap((taskId) => extractAffectedFiles(taskId)).map(normalizeAffectedFile).filter((value) => value !== null))];
|
|
6072
|
+
return selectPitfalls({
|
|
6073
|
+
patterns: readOrNull(patternsPath),
|
|
6074
|
+
lessons: readOrNull(path12.join(root, LESSONS_PATH)),
|
|
6075
|
+
readDoc: (repoPath) => isPathInsideRoot(root, repoPath) ? readOrNull(path12.join(root, repoPath)) : null,
|
|
6076
|
+
affectedFiles
|
|
6077
|
+
});
|
|
6078
|
+
}
|
|
6079
|
+
|
|
6080
|
+
// src/orchestrator/review-archive.ts
|
|
6081
|
+
import fs16 from "fs";
|
|
6082
|
+
import path14 from "path";
|
|
5123
6083
|
|
|
5124
6084
|
// src/task/templates.ts
|
|
5125
|
-
import
|
|
5126
|
-
import
|
|
6085
|
+
import fs15 from "fs";
|
|
6086
|
+
import path13 from "path";
|
|
5127
6087
|
function tasksRoot(projectRoot) {
|
|
5128
6088
|
return tasksDir(projectRoot);
|
|
5129
6089
|
}
|
|
@@ -5131,21 +6091,21 @@ function templatesRoot(projectRoot) {
|
|
|
5131
6091
|
return templatesDir(projectRoot);
|
|
5132
6092
|
}
|
|
5133
6093
|
function taskTemplateOverrideRoot(projectRoot) {
|
|
5134
|
-
return
|
|
6094
|
+
return path13.join(tasksRoot(projectRoot), "_templates");
|
|
5135
6095
|
}
|
|
5136
6096
|
function resolveTaskTemplateSource(basename, projectRoot = resolveProjectRoot()) {
|
|
5137
|
-
const override =
|
|
5138
|
-
if (
|
|
5139
|
-
const managed =
|
|
5140
|
-
return
|
|
6097
|
+
const override = path13.join(taskTemplateOverrideRoot(projectRoot), basename);
|
|
6098
|
+
if (fs15.existsSync(override)) return override;
|
|
6099
|
+
const managed = path13.join(templatesRoot(projectRoot), basename);
|
|
6100
|
+
return fs15.existsSync(managed) ? managed : null;
|
|
5141
6101
|
}
|
|
5142
6102
|
function renderTaskTemplate(source, taskId, title) {
|
|
5143
|
-
return
|
|
6103
|
+
return fs15.readFileSync(source, "utf8").replaceAll("[TASK-ID]", taskId).replaceAll("[Title]", title);
|
|
5144
6104
|
}
|
|
5145
6105
|
function scaffoldTaskArtifact(taskDir, basename, taskId, title) {
|
|
5146
6106
|
const source = resolveTaskTemplateSource(basename);
|
|
5147
6107
|
if (!source) return null;
|
|
5148
|
-
|
|
6108
|
+
fs15.writeFileSync(path13.join(taskDir, basename), renderTaskTemplate(source, taskId, title), "utf8");
|
|
5149
6109
|
return source;
|
|
5150
6110
|
}
|
|
5151
6111
|
function isPristineTaskArtifact(content, basename, taskId, title) {
|
|
@@ -5167,14 +6127,14 @@ var ROUND_RECORD_PREFIX = "review-round-";
|
|
|
5167
6127
|
var ROUND_RECORD_RE = /^review-round-(\d+)\.md$/;
|
|
5168
6128
|
function writeNumberedRecord(taskDir, pattern, prefix, header, body) {
|
|
5169
6129
|
let newest = 0;
|
|
5170
|
-
for (const name2 of
|
|
6130
|
+
for (const name2 of fs16.readdirSync(taskDir)) {
|
|
5171
6131
|
const match = pattern.exec(name2);
|
|
5172
6132
|
if (match) newest = Math.max(newest, Number(match[1]));
|
|
5173
6133
|
}
|
|
5174
6134
|
const name = `${prefix}${newest + 1}.md`;
|
|
5175
6135
|
const reason = header.reason.replaceAll('"', "'");
|
|
5176
|
-
|
|
5177
|
-
|
|
6136
|
+
fs16.writeFileSync(
|
|
6137
|
+
path14.join(taskDir, name),
|
|
5178
6138
|
`<!-- round=${header.round} reviewed_sha=${header.reviewedSha} scope=${header.scope} base=${header.base} reason="${reason}" -->
|
|
5179
6139
|
|
|
5180
6140
|
${body}`,
|
|
@@ -5213,7 +6173,7 @@ function newestRecordForRound(taskDir, names, pattern, round) {
|
|
|
5213
6173
|
for (const { name } of numbered) {
|
|
5214
6174
|
let content;
|
|
5215
6175
|
try {
|
|
5216
|
-
content =
|
|
6176
|
+
content = fs16.readFileSync(path14.join(taskDir, name), "utf8");
|
|
5217
6177
|
} catch {
|
|
5218
6178
|
continue;
|
|
5219
6179
|
}
|
|
@@ -5225,7 +6185,7 @@ function newestRecordForRound(taskDir, names, pattern, round) {
|
|
|
5225
6185
|
function roundRecordsForRound(taskDir, round) {
|
|
5226
6186
|
let names;
|
|
5227
6187
|
try {
|
|
5228
|
-
names =
|
|
6188
|
+
names = fs16.readdirSync(taskDir);
|
|
5229
6189
|
} catch {
|
|
5230
6190
|
return { cold: null, neutral: null };
|
|
5231
6191
|
}
|
|
@@ -5246,14 +6206,14 @@ function hasConflictingRoundRecords(taskDir, round) {
|
|
|
5246
6206
|
function hasMalformedColdCodexArchive(taskDir) {
|
|
5247
6207
|
let names;
|
|
5248
6208
|
try {
|
|
5249
|
-
names =
|
|
6209
|
+
names = fs16.readdirSync(taskDir);
|
|
5250
6210
|
} catch {
|
|
5251
6211
|
return false;
|
|
5252
6212
|
}
|
|
5253
6213
|
return names.some((name) => {
|
|
5254
6214
|
if (!COLD_CODEX_ARCHIVE_RE.test(name) && !ROUND_RECORD_RE.test(name)) return false;
|
|
5255
6215
|
try {
|
|
5256
|
-
return parseColdCodexArchiveHeader(
|
|
6216
|
+
return parseColdCodexArchiveHeader(fs16.readFileSync(path14.join(taskDir, name), "utf8")) === null;
|
|
5257
6217
|
} catch {
|
|
5258
6218
|
return true;
|
|
5259
6219
|
}
|
|
@@ -5262,7 +6222,7 @@ function hasMalformedColdCodexArchive(taskDir) {
|
|
|
5262
6222
|
var REVIEW_ARCHIVE_RE = new RegExp(`^${REVIEW_ARCHIVE_PREFIX}(\\d+)\\.md$`);
|
|
5263
6223
|
function newestReviewArchiveNumber(taskDir) {
|
|
5264
6224
|
let newest = 0;
|
|
5265
|
-
for (const name of
|
|
6225
|
+
for (const name of fs16.readdirSync(taskDir)) {
|
|
5266
6226
|
const match = REVIEW_ARCHIVE_RE.exec(name);
|
|
5267
6227
|
if (match) newest = Math.max(newest, Number(match[1]));
|
|
5268
6228
|
}
|
|
@@ -5273,22 +6233,22 @@ function findNewestReviewArchive(taskDir) {
|
|
|
5273
6233
|
return newest === 0 ? null : `${REVIEW_ARCHIVE_PREFIX}${newest}.md`;
|
|
5274
6234
|
}
|
|
5275
6235
|
function archivePriorReview(taskDir, options = {}) {
|
|
5276
|
-
const reviewPath =
|
|
5277
|
-
if (!
|
|
6236
|
+
const reviewPath = path14.join(taskDir, "review.md");
|
|
6237
|
+
if (!fs16.existsSync(reviewPath)) return null;
|
|
5278
6238
|
if (options.skipUnfilledTemplate) {
|
|
5279
|
-
const content =
|
|
6239
|
+
const content = fs16.readFileSync(reviewPath, "utf8");
|
|
5280
6240
|
if (isTemplateUnfilled(content)) return null;
|
|
5281
6241
|
if (options.scaffold && isPristineTaskArtifact(content, "review.md", options.scaffold.taskId, options.scaffold.title)) {
|
|
5282
6242
|
return null;
|
|
5283
6243
|
}
|
|
5284
6244
|
}
|
|
5285
6245
|
const archiveName = `${REVIEW_ARCHIVE_PREFIX}${newestReviewArchiveNumber(taskDir) + 1}.md`;
|
|
5286
|
-
|
|
6246
|
+
fs16.renameSync(reviewPath, path14.join(taskDir, archiveName));
|
|
5287
6247
|
return archiveName;
|
|
5288
6248
|
}
|
|
5289
6249
|
function rescaffoldReview(taskDir, identity) {
|
|
5290
6250
|
try {
|
|
5291
|
-
if (
|
|
6251
|
+
if (fs16.existsSync(path14.join(taskDir, "review.md"))) return { outcome: "exists" };
|
|
5292
6252
|
const source = scaffoldTaskArtifact(taskDir, "review.md", identity.taskId, identity.title);
|
|
5293
6253
|
return source ? { outcome: "written", source } : { outcome: "no-template" };
|
|
5294
6254
|
} catch (error) {
|
|
@@ -5762,16 +6722,16 @@ function renderTemplate(template, view) {
|
|
|
5762
6722
|
}
|
|
5763
6723
|
|
|
5764
6724
|
// src/orchestrator/prompts/templates/code-review-foreman.md
|
|
5765
|
-
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\n{{#mixedProvider}}Your 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.{{/mixedProvider}}{{^mixedProvider}}Your job is a two-lens synthesis: the anchored Claude lens and the cold-Claude lens. You spawn both as isolated sub-agents, collect their findings, adjudicate both inputs using the spec (which you hold and the cold lens does not), then write one `review.md` and set the verdict.{{/mixedProvider}}\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}}. {{#mixedProvider}}All three lenses run again this round.{{/mixedProvider}}{{^mixedProvider}}Both Claude lenses run again this round.{{/mixedProvider}} 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{{#mixedProvider}}\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{{/mixedProvider}}\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\nThe Affected Files rows you append under items 1 and 2 must follow the scope manifest contract: Affected Files uses exactly one `### Affected Files` heading under `## Design` and at most one per `## Amendment\u2026` section (a behavior-only amendment needs none), with one file per row: comma-join extra paths for the same change in the first column, put notes in the Change column, and never put a second backticked token in a first-column note (directory entries ending in `/` are fine). Canon does not lint a table you append here, so a malformed row leaves its file outside Affected Files.\n\nExample row (path in the first column, reason in the Change column):\n\n| File | Change |\n|---|---|\n| `path/to/changed-file.ts` | Full-send scope expansion: needed to meet AC-2. |\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\n{{#mixedProvider}}The 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.{{/mixedProvider}}{{^mixedProvider}}Do not let a Claude lens see the other lens's output.{{/mixedProvider}}\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\n{{#mixedProvider}}Use the three lens inputs and the spec.{{/mixedProvider}}{{^mixedProvider}}Use both Claude lens inputs and the spec.{{/mixedProvider}} 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. {{#mixedProvider}}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`.{{/mixedProvider}}{{^mixedProvider}}Agreement between both Claude lenses must not be dismissed as spec-intended without explicit spec evidence cited in `review.md`.{{/mixedProvider}}\n2. Keep the two reconciliation checks separate:\n - Does it hold against the code? {{#mixedProvider}}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>`.{{/mixedProvider}}{{^mixedProvider}}For cold-Claude findings, verify each against the diff/code. Severity levels are claims to check, not verdicts. A finding that does not hold gets recorded as `Dismissed (cold-Claude): <finding> - <reason>`.{{/mixedProvider}}\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 {{#mixedProvider}}verified cold-Claude or cold-Codex finding{{/mixedProvider}}{{^mixedProvider}}verified cold-Claude finding{{/mixedProvider}} 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}}}. {{#mixedProvider}}The numbered cold-Codex archive header is the machine-readable record.{{/mixedProvider}}{{^mixedProvider}}The orchestrator writes the numbered round record with the machine-readable scope header.{{/mixedProvider}}\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, {{#mixedProvider}}including `Dismissed (cold-Claude): ...` and `Dismissed (cold-Codex): ...` entries where applicable.{{/mixedProvider}}{{^mixedProvider}}including `Dismissed (cold-Claude): ...` entries where applicable.{{/mixedProvider}}\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";
|
|
6725
|
+
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\n{{#mixedProvider}}Your 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.{{/mixedProvider}}{{^mixedProvider}}Your job is a two-lens synthesis: the anchored Claude lens and the cold-Claude lens. You spawn both as isolated sub-agents, collect their findings, adjudicate both inputs using the spec (which you hold and the cold lens does not), then write one `review.md` and set the verdict.{{/mixedProvider}}\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}}. {{#mixedProvider}}All three lenses run again this round.{{/mixedProvider}}{{^mixedProvider}}Both Claude lenses run again this round.{{/mixedProvider}} 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. Also tell the anchored lens to read Self-Check evidence across the baseline `## Self-Check` section and every Iteration `### Self-Check` subsection, and to judge the effective record: for each check, the latest filled row; superseded rows are history and are not judged.\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{{#mixedProvider}}\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{{/mixedProvider}}\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\nThe Affected Files rows you append under items 1 and 2 must follow the scope manifest contract: Affected Files uses exactly one `### Affected Files` heading under `## Design` and at most one per `## Amendment\u2026` section (a behavior-only amendment needs none), with one file per row: comma-join extra paths for the same change in the first column, put notes in the Change column, and never put a second backticked token in a first-column note (directory entries ending in `/` are fine). Canon does not lint a table you append here, so a malformed row leaves its file outside Affected Files.\n\nExample row (path in the first column, reason in the Change column):\n\n| File | Change |\n|---|---|\n| `path/to/changed-file.ts` | Full-send scope expansion: needed to meet AC-2. |\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\n{{#mixedProvider}}The 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.{{/mixedProvider}}{{^mixedProvider}}Do not let a Claude lens see the other lens's output.{{/mixedProvider}}\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\n{{#mixedProvider}}Use the three lens inputs and the spec.{{/mixedProvider}}{{^mixedProvider}}Use both Claude lens inputs and the spec.{{/mixedProvider}} 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. {{#mixedProvider}}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`.{{/mixedProvider}}{{^mixedProvider}}Agreement between both Claude lenses must not be dismissed as spec-intended without explicit spec evidence cited in `review.md`.{{/mixedProvider}}\n2. Keep the two reconciliation checks separate:\n - Does it hold against the code? {{#mixedProvider}}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>`.{{/mixedProvider}}{{^mixedProvider}}For cold-Claude findings, verify each against the diff/code. Severity levels are claims to check, not verdicts. A finding that does not hold gets recorded as `Dismissed (cold-Claude): <finding> - <reason>`.{{/mixedProvider}}\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 {{#mixedProvider}}verified cold-Claude or cold-Codex finding{{/mixedProvider}}{{^mixedProvider}}verified cold-Claude finding{{/mixedProvider}} 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\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\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}}}. {{#mixedProvider}}The numbered cold-Codex archive header is the machine-readable record.{{/mixedProvider}}{{^mixedProvider}}The orchestrator writes the numbered round record with the machine-readable scope header.{{/mixedProvider}}\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, {{#mixedProvider}}including `Dismissed (cold-Claude): ...` and `Dismissed (cold-Codex): ...` entries where applicable.{{/mixedProvider}}{{^mixedProvider}}including `Dismissed (cold-Claude): ...` entries where applicable.{{/mixedProvider}}\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";
|
|
5766
6726
|
|
|
5767
6727
|
// src/orchestrator/prompts/templates/implement.md
|
|
5768
|
-
var implement_default =
|
|
6728
|
+
var implement_default = "You are implementing {{taskScope}} for {{projectName}}.\n\n{{{stateHeader}}}\n{{{startup}}}\n{{{risksBlock}}}{{{pitfallsBlock}}}{{{contextBlock}}}{{{blastRadiusBlock}}}\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\n{{#selfCheck}}\n**Pre-handoff self-check** \u2014 after you make your changes and before you run validation and write handoff.md, check the change in this order:\n1. **Test integrity.** For each test this pass added or changed to pin new or altered behavior: would it fail if the change were reverted? Does it assert the specific reason \u2014 the message, value, or state the change produces \u2014 rather than only that something failed or passed? Regenerated snapshots and pure fixture updates are exempt. Where a cheap run against the base commit confirms the failure, do it. A red-first regression-test AC still follows the red-first checkpoint; this check does not replace it.\n2. **Restatement sweep.** For every contract the change alters \u2014 an operator-facing string, flag, format, heading, verdict, or config key \u2014 search the repository for other places that state the same contract, and bring them in line.\n3. **Sibling parity.** For every guard, check, or branch the change adds, find the parallel paths that handle the same input \u2014 other commands, modes, entry points, or platform variants \u2014 and confirm each one either gets the same treatment or deliberately does not.\n\nRecord each check's evidence in handoff.md's `## Self-Check` table (`Check` | `Evidence`, one row each for `Test integrity`, `Restatement sweep` and `Sibling parity`): the tests and the assertion that pins each one's failure reason, and how you know it fails without the change; the search pattern(s) you ran for each changed contract, and how each hit outside Affected Files was handled; the parallel paths you examined, and whether each got the same treatment. Write `N/A \u2014 <reason>` for a check that does not apply, and `\\|` for a literal pipe. Write the section even if the handoff template you are using lacks it: code review rejects a handoff without a filled `## Self-Check` section, and the reviewer checks each row against the diff.\n\nIf a check finds an edit needed in a file outside the spec's Affected Files, do not make it: record it under Blockers in handoff.md.\n{{/selfCheck}}\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";
|
|
5769
6729
|
|
|
5770
6730
|
// src/orchestrator/prompts/templates/implement-reroute.md
|
|
5771
|
-
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. That section holds the newest requirements and wins where it conflicts with an earlier section; earlier sections (the original ACs and prior amendment rounds) stay binding wherever their work is not yet implemented.\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 this round\u2019s plan guide. If absent (fast-tier reroute with no conversational reroute plan), read the base plan for orientation.\n3. Establish the current state from the worktree, not from memory: run `git status` and `git diff` against the task's base branch to see what is actually implemented, committed or not. The prior implementation round may be complete or partial \u2014 a reroute can follow a finished round or interrupt one that was stopped, crashed, or blocked mid-way, leaving uncommitted edits behind. Treat tasks/<id>/handoff.md as a record of prior work only if it has been filled in (after an aborted first pass it may still be the unfilled template); even then it predates the amendment.\n4. Determine this round's scope: the amendment, plus any unfinished work from the original ACs and earlier amendment rounds, plus unresolved blocking findings in the archived review named in the task's entry, if any. Note which ACs are new, which changed, and which the worktree already implements.\n5. Implement that scope. Correct existing work stays; change it only where the amendment or an unmet AC 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 earlier work that still applies, any unfinished work from the original ACs and earlier amendment rounds, and this round\u2019s amendment work. The Changes table must list every file this task has changed \u2014 committed on the branch or dirty in the worktree (`git status --porcelain`), including uncommitted edits left by an interrupted earlier round; a modified tracked file the table omits blocks canon's auto-commit (or, if no listed file is uncommitted, is caught only by the QA-end check), while an untracked file is committed only if the table lists it \u2014 otherwise it is left out of the commit, unseen by code review, until the QA-end check rejects it. Delete leftovers from an interrupted round that the amendment makes obsolete rather than listing them. 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, or an original or earlier-round red-first AC is unfinished because the prior round was partial: write and run the test **before** making the fix edits, and confirm it fails *for the reason the spec states*; then apply the fix and confirm it passes. Keep any carried-forward Red-First Evidence row that already satisfies its AC; do not re-run it. Record each new 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 committed HEAD. Write and run the test before changing any non-test code; files that exist only to support tests count as test files. If the worktree already holds aborted-round edits, first copy every tracked and untracked non-test leftover to a temporary directory. Confirm every set-aside copy exists and matches its worktree file before changing any worktree path. Note any tracked file the aborted round deleted or renamed; it has no copy to make. Only after all copies are verified: for tracked leftovers, restore their paths to committed contents; remove untracked non-test leftovers from the worktree \u2014 never a bare `git stash`. Run the red test against that isolated state, then restore every set-aside file (tracked and untracked) and re-apply each noted deletion or rename before applying the fix. Difficulty isolating the edits is not grounds for skipping the red run. If it cannot be made to fail for the stated reason, record a `[wrong-premise]` Blocker instead of implementing on an unconfirmed premise. If the spec 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. If no isolated pre-fix run is possible and the spec names no environment-bound escape, record a `[wrong-premise]`-style Blocker and do not implement the fix on an unconfirmed premise.\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";
|
|
6731
|
+
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}}}{{{blastRadiusBlock}}}\n{{{affectedFilesBlock}}}\nTasks with amended specs:\n{{{taskLines}}}\n\n{{{groundingRule}}}\n\n**Pre-handoff self-check** \u2014 after you make your changes and before you run validation and write handoff.md, check the change in this order:\n1. **Test integrity.** For each test this pass added or changed to pin new or altered behavior: would it fail if the change were reverted? Does it assert the specific reason \u2014 the message, value, or state the change produces \u2014 rather than only that something failed or passed? Regenerated snapshots and pure fixture updates are exempt. Where a cheap run against the base commit confirms the failure, do it. A red-first regression-test AC still follows the red-first checkpoint; this check does not replace it.\n2. **Restatement sweep.** For every contract the change alters \u2014 an operator-facing string, flag, format, heading, verdict, or config key \u2014 search the repository for other places that state the same contract, and bring them in line.\n3. **Sibling parity.** For every guard, check, or branch the change adds, find the parallel paths that handle the same input \u2014 other commands, modes, entry points, or platform variants \u2014 and confirm each one either gets the same treatment or deliberately does not.\n\nRecord each check's evidence in handoff.md's `## Self-Check` table (`Check` | `Evidence`, one row each for `Test integrity`, `Restatement sweep` and `Sibling parity`): the tests and the assertion that pins each one's failure reason, and how you know it fails without the change; the search pattern(s) you ran for each changed contract, and how each hit outside Affected Files was handled; the parallel paths you examined, and whether each got the same treatment. Write `N/A \u2014 <reason>` for a check that does not apply, and `\\|` for a literal pipe. Write the section even if the handoff template you are using lacks it: code review rejects a handoff without a filled `## Self-Check` section, and the reviewer checks each row against the diff.\n\nIf a check finds an edit needed in a file outside the spec's Affected Files, do not make it: record it under Blockers in handoff.md.\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. That section holds the newest requirements and wins where it conflicts with an earlier section; earlier sections (the original ACs and prior amendment rounds) stay binding wherever their work is not yet implemented.\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 this round\u2019s plan guide. If absent (fast-tier reroute with no conversational reroute plan), read the base plan for orientation.\n3. Establish the current state from the worktree, not from memory: run `git status` and `git diff` against the task's base branch to see what is actually implemented, committed or not. The prior implementation round may be complete or partial \u2014 a reroute can follow a finished round or interrupt one that was stopped, crashed, or blocked mid-way, leaving uncommitted edits behind. Treat tasks/<id>/handoff.md as a record of prior work only if it has been filled in (after an aborted first pass it may still be the unfilled template); even then it predates the amendment.\n4. Determine this round's scope: the amendment, plus any unfinished work from the original ACs and earlier amendment rounds, plus unresolved blocking findings in the archived review named in the task's entry, if any. Note which ACs are new, which changed, and which the worktree already implements.\n5. Implement that scope. Correct existing work stays; change it only where the amendment or an unmet AC 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 earlier work that still applies, any unfinished work from the original ACs and earlier amendment rounds, and this round\u2019s amendment work. The Changes table must list every file this task has changed \u2014 committed on the branch or dirty in the worktree (`git status --porcelain`), including uncommitted edits left by an interrupted earlier round; a modified tracked file the table omits blocks canon's auto-commit (or, if no listed file is uncommitted, is caught only by the QA-end check), while an untracked file is committed only if the table lists it \u2014 otherwise it is left out of the commit, unseen by code review, until the QA-end check rejects it. Delete leftovers from an interrupted round that the amendment makes obsolete rather than listing them. Carry existing Red-First Evidence rows forward. The rewritten `## Self-Check` table covers all work on the branch: carry earlier rounds' Self-Check evidence forward (the baseline rows and any Iteration `### Self-Check` rows), updated to the current diff. 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, or an original or earlier-round red-first AC is unfinished because the prior round was partial: write and run the test **before** making the fix edits, and confirm it fails *for the reason the spec states*; then apply the fix and confirm it passes. Keep any carried-forward Red-First Evidence row that already satisfies its AC; do not re-run it. Record each new 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 committed HEAD. Write and run the test before changing any non-test code; files that exist only to support tests count as test files. If the worktree already holds aborted-round edits, first copy every tracked and untracked non-test leftover to a temporary directory. Confirm every set-aside copy exists and matches its worktree file before changing any worktree path. Note any tracked file the aborted round deleted or renamed; it has no copy to make. Only after all copies are verified: for tracked leftovers, restore their paths to committed contents; remove untracked non-test leftovers from the worktree \u2014 never a bare `git stash`. Run the red test against that isolated state, then restore every set-aside file (tracked and untracked) and re-apply each noted deletion or rename before applying the fix. Difficulty isolating the edits is not grounds for skipping the red run. If it cannot be made to fail for the stated reason, record a `[wrong-premise]` Blocker instead of implementing on an unconfirmed premise. If the spec 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. If no isolated pre-fix run is possible and the spec names no environment-bound escape, record a `[wrong-premise]`-style Blocker and do not implement the fix on an unconfirmed premise.\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";
|
|
5772
6732
|
|
|
5773
6733
|
// src/orchestrator/prompts/templates/implement-revisions.md
|
|
5774
|
-
var implement_revisions_default =
|
|
6734
|
+
var implement_revisions_default = "{{{iterBanner}}}\n\n{{{stateHeader}}}\n{{{startup}}}\n\n{{{affectedFilesBlock}}}\n\n**Pre-handoff self-check** \u2014 after you make this round's changes and before you re-run validation and append to handoff.md, check the change in this order:\n1. **Test integrity.** For each test this pass added or changed to pin new or altered behavior: would it fail if the change were reverted? Does it assert the specific reason \u2014 the message, value, or state the change produces \u2014 rather than only that something failed or passed? Regenerated snapshots and pure fixture updates are exempt. Where a cheap run against the base commit confirms the failure, do it. A red-first regression-test AC still follows the red-first checkpoint; this check does not replace it.\n2. **Restatement sweep.** For every contract the change alters \u2014 an operator-facing string, flag, format, heading, verdict, or config key \u2014 search the repository for other places that state the same contract, and bring them in line.\n3. **Sibling parity.** For every guard, check, or branch the change adds, find the parallel paths that handle the same input \u2014 other commands, modes, entry points, or platform variants \u2014 and confirm each one either gets the same treatment or deliberately does not.\n\nIf a check finds an edit needed in a file outside the spec's Affected Files, do not make it: record it under Blockers in handoff.md.\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. One exception: a `### Self-Check` subsection (see the Self-Check rule below) restates whole-branch evidence rather than this round's delta.\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, Self-Check table, Changes table). Fix a Self-Check item by adding or repairing the baseline `## Self-Check` section in place \u2014 an Iteration `### Self-Check` subsection does not satisfy the pre-flight.\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- **Self-Check evidence on revision rounds**: append a `### Self-Check` subsection to this round's Iteration section whenever the round makes an earlier Self-Check row incomplete or untrue \u2014 it adds, renames, or changes behavioral tests, contracts, or guards, or a review finding says an earlier row is contradicted. Include only the rows that change. Each row you write restates that check's evidence for all work on the branch, not only this round, and supersedes the earlier version of that row; leave earlier rows in place as history. Never write a round-scoped row such as `N/A \u2014 no tests changed this round`: it supersedes the branch's real evidence and reads as false.\n\nAppend to `tasks/<id>/notes.md` for new pitfalls found (prefix: `[implement-revision]`).\n\nWhen done, run:\n{{{phaseCommands}}}\n";
|
|
5775
6735
|
|
|
5776
6736
|
// src/orchestrator/prompts/templates/plan-reroute.md
|
|
5777
6737
|
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 implementation began. {{specReviewer}} 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. Establish the current implementation state from the worktree: `git status` and `git diff` against the task's base branch. The prior implementation round may be complete or partial. Read `tasks/<id>/handoff.md` as a record of {{implementer}}'s prior work only if it has been filled in \u2014 after an aborted first pass it may still be the unfilled template.\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 this round's scope: the amendment, plus any unfinished work from the original ACs and earlier amendment rounds, plus unresolved blocking findings in the archived review named in the task's entry, if any (those sections stay binding wherever not yet implemented; the newest amendment wins on conflict). Reference specific files, functions, and existing patterns. Acknowledge prior plan steps that are already implemented 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 guide for this round.\n\nWhen done, run:\n{{{phaseCommands}}}\n\n<!-- per-round append shape:\n## Reroute Plan [Round N]\n### Round Scope\n- Feasibility: ...\n- ...ordered steps for this round's scope (amendment plus unfinished earlier work)...\n-->\n";
|
|
@@ -5783,10 +6743,10 @@ var plan_default = "You are writing implementation plans for {{taskScope}} for {
|
|
|
5783
6743
|
var qa_default = 'You are writing QA summaries for {{taskScope}} for {{projectName}}.\n\n{{{startup}}}\n\nTasks:\n{{{taskLines}}}\n\nFor each task:\n1. **Use the Write tool** to create tasks/<id>/done.md \u2014 plain-English summary for the human. Include: what changed, files changed, how to test, test results, human verification required, judgment calls to confirm, decisions made, open questions.\n \u26A0\uFE0F CRITICAL: Use the `Write` tool \u2014 do NOT simply output the done.md content as text in your response. Content in your chat reply does not get saved to disk. The pipeline validates that done.md contains real content (not the template) before advancing. Write the file.\n - **Judgment Calls to Confirm**: add the section immediately before `## Decisions Made`. List every `Author` row from the spec\'s *Judgment Calls* section (the call, chosen option, and strongest alternative), or write `None.` if there are no such rows or no section.\n2. Read the latest `## Validation Outcomes` table in `tasks/<id>/handoff.md`, including any later iteration `### Re-run validation` tables. If any check\'s latest result is `human_pending`, include a **Human Verification Required** section in done.md that lists each pending check and its Notes. If none remain, write `None.` in that section. Do not hide `human_pending` checks inside the generic Test Results table.\n - If the human chooses to waive or defer a pending check later, the waiver line in done.md must begin with `Acknowledged:`. The `human_review` gate only treats that explicit prefix as a waiver.\n - Preserve `deferred_by_spec` rows in Test Results with the spec citation from Notes; do not translate them to `Pass`.\n3. Include a **Proposed Changelog** section in done.md \u2014 the changelog **entry text only**. Do **NOT** include a version number, a "Proposed version" line, or a bump tier (Patch/Minor/Major): the version is decided at the release step (`/canon-changelog` + human), never by QA.\n - **Canon release rules (non-negotiable)**: (1) Agents do not bump versions or land changelog edits without explicit scope authorization. (2) The QA step proposes a draft changelog entry text only \u2014 not the version number. (3) Changelog + version bump are committed separately from code changes (when a project versions its releases). (4) No major versioning surprises: if a task introduces a breaking change the spec didn\'t flag, raise it before shipping.\n - Read `docs/decisions.md` \xA7"Versioning and release policy" for this project\'s changelog **scope** (which changes warrant an entry). The bump tier / SemVer interpretation is the release step\'s call, not QA\'s \u2014 do not propose one.\n - If CHANGELOG.md exists, read the top of it (the most recent version section) to calibrate on scope and voice.\n - Apply the "would a user notice" test to every candidate bullet (or the project\'s equivalent scope test): if a candidate falls outside the project\'s defined changelog scope, omit it. If a task is entirely out of scope, say so explicitly ("no user-facing change \u2014 omit from changelog") rather than inventing a bullet.\n - Implementation mechanics belong in the "What Changed" section above \u2014 not in the proposed changelog.\n The human finalizes the changelog entry.\n4. **For single tasks only \u2014 use the Write tool** to create `tasks/<id>/pr-body.md` \u2014 the outward-facing PR body draft for `--pr`. Write it as if a human wrote it after doing the work.\n {{#prTemplate}}\n The repo has this PR template. Fill every section with specifics from what shipped. Keep the headings; replace every placeholder:\n\n {{{prTemplate}}}\n {{/prTemplate}}\n\n {{^prTemplate}}\n No PR template found. Use this structure:\n\n ## Summary\n 1\u20133 bullets: what changed and why.\n\n ## Changes\n Key files or areas touched, described for a reviewer.\n\n ## How to Test\n Steps a reviewer can follow to verify the change.\n\n ## Notes for Reviewer\n Any context, caveats, or follow-up items.\n {{/prTemplate}}\n For each `Author` row in the spec\'s *Judgment Calls* section, add a short note phrased in the engineer\'s voice as a call not explicitly confirmed during spec review. With no PR template, put the rows under "Notes for Reviewer". With a PR template, use its closest notes-like section, or append a short `Judgment calls` heading at the end if it has none. If there are no `Author` rows, add nothing to the PR body.\n \u26A0\uFE0F Write as the human engineer who did the work \u2014 not as the AI or tool that produced it ({{toolExamples}}). \u2705 e.g. "Fix the pagination off-by-one that dropped the last row." \u274C e.g. "\u{1F916} Generated with Claude Code."\n Skip this step entirely for bundle tasks \u2014 per-task bodies are not combined for bundle PRs.\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\nAfter writing all done.md files:\n- Read tasks/<id>/notes.md for each task. For each insight, ask: "would this have changed how a *different* task was approached?" If yes, **append** one new entry for *this* task to its own lessons fragment, using the entry format in docs/lessons-learned.md. The fragment holds only `###` entries: create it if it doesn\'t exist, and give it no title or other `#`/`##` heading. Do not edit docs/lessons-learned.md; `--ship` folds the fragments into it. If no, the detail stays in notes.md only. Append-only: never edit, prune, promote, reorganize, or delete existing entries \u2014 not this task\'s earlier entries, and never another task\'s. Promoting entries into permanent docs (patterns.md / decisions.md) and pruning the buffer is a **human-initiated, human-approved** action \u2014 never perform it during QA, and no entry count ever triggers it. (See docs/lessons-learned.md \u2192 "How to use this doc".)\n\n{{{lessonsFragments}}}\n\n- Add a `## Quality Log` section to done.md with the five judgment cells the pipeline cannot derive from status.json. Do **not** edit docs/task-quality-log.md directly \u2014 the qa \u2192 done transition writes or upserts that row automatically into each task\'s quality-log.md fragment from status.json plus this section. `--ship` folds it into the shared log.\n\n ```markdown\n ## Quality Log\n - Spec verdict: <the FIRST spec_review verdict this task ever received \u2014 approved / approved_with_nits / changes_requested; leave blank only if truly unknown>\n - Human reroute?: <Yes/No \u2014 did the human reroute this task at any phase, forcing rework? Do not infer this from any reroute counter; if this is a fresh QA pass with no human reroute yet, answer No>\n - Dropped ACs: <count of ACs the implementation missed, caught in code review>\n - Validation gaps: <count of validation checks that should have run but did not>\n - Notes: <one-line summary of anything notable \u2014 single line, no embedded line breaks>\n ```\n\n On a re-upsert after a reroute, only fill in cells that changed or that you are correcting \u2014 an omitted cell keeps its previously recorded value. In particular, do not overwrite an already-recorded `Spec verdict` with the current status.json verdict; that column means the first spec_review verdict, and status.json only retains the latest.\n\n- Add a `## Root Cause` section to done.md, after `## Quality Log`. It stays in done.md and is not copied to the quality log. For each blocking review finding, reroute, or dropped AC this task had, write one line `- <class>: <one-line cause>`, where class is one of `context-missing` (a doc or spec lacked a fact the agent needed), `context-conflicting` (docs, spec, or code said two different things, or a term was ambiguous), `spec-gap`, `plan-error`, `execution` (the context was adequate and the agent still got it wrong), or `unrequested-change` (the implementer changed or reinterpreted something the spec did not ask for). If the task had none, write `None.`\n\n**Handoff Validation pre-merge checklist** (include in `done.md` Human Verification section if any item cannot be confirmed):\n- [ ] Version correct (per project policy; skip if unversioned)\n- [ ] Changelog updated if needed (per project policy; skip if unversioned)\n- [ ] PR body current\n- [ ] Final CI/CD checks green\n- [ ] Final diff matches spec intent\n\n**Output Format for Human** \u2014 `done.md` must contain:\n1. One-paragraph plain-English summary\n2. Files changed\n3. How to test (product-level steps, not code)\n4. Test results table\n5. Judgment calls to confirm (`## Judgment Calls to Confirm`)\n6. Decisions made during implementation\n7. Open questions needing human input\n8. Root cause of each blocking finding, reroute, or dropped AC (`## Root Cause`)\n\n**Code is Canonical; Docs Reference Symbols**: Code is the source of truth for anything derivable from code: numbers, thresholds, file locations, function signatures, type shapes, observable behavior. Docs that restate these facts inline rot silently \u2014 reference the symbol or path; do not restate the value.\n\n**Commit Ownership** \u2014 three change categories:\n- Code changes \u2192 task branch, committed by the orchestrator after {{implementer}} static validation.\n- Pre-implement scaffold \u2192 base branch, committed by the orchestrator before first implement.\n- Changelog + version bump (if versioned) \u2192 separate commit, human + Claude, after human_review.\n\n- **Docs freshness \u2014 Two-checkpoint**: {{#docsEditable}}scan these docs ({{{docsEditable}}}) for references that {{docsScope}} *contradicts* \u2014 a renamed symbol, a moved file, a behavior this task changed \u2014 and correct those stale references. That is the only edit QA makes to permanent docs.{{/docsEditable}}{{^docsEditable}}no docs are configured for correction in this project, so QA makes no edits to permanent docs under this step.{{/docsEditable}} Do not add new lessons, pitfalls, or decisions here, and do not promote buffer entries \u2014 promotion is the human sweep, not Docs freshness.\n{{#docsFlagged}}\n- **Docs drift (flag only)**: also check {{{docsFlagged}}} for statements {{docsScope}} makes stale. Do **not** edit these docs. Report each stale statement in a `## Docs drift` section of done.md (doc, the stale statement, and what is now true). Omit the section if nothing is stale.\n{{/docsFlagged}}\n- **Buffer signal** (not an action): after appending, if docs/lessons-learned.md plus this task\'s lessons fragment now hold more than ~15 entries, add one line to this task\'s done.md \u2014 `Maintenance: lessons-learned.md plus this task\u2019s fragment have N entries; a human lessons sweep is due (see docs/lessons-learned.md \u2192 "How to use this doc").` Do not perform the sweep yourself.\n\nWhen done, run (use the Bash tool \u2014 do not just output the command as text):\n{{{phaseCommands}}}\n';
|
|
5784
6744
|
|
|
5785
6745
|
// src/orchestrator/prompts/templates/spec.md
|
|
5786
|
-
var spec_default = '{{{header}}}\n\n{{{startup}}}\n\n{{{instructions}}}\n{{{bundleNote}}}\n{{#doneNote}}\nNote: {{{doneNote}}}{{/doneNote}}\n\n{{#docsMapBlock}}\n{{{docsMapBlock}}}\n\n{{/docsMapBlock}}\n**Spec-writing rules of thumb** \u2014 apply when writing each spec:\n\n- **Name effects to DELETE** \u2014 frame supersession as replacement, not add-plus-remove. State: "replace `oldFn` with `newFn`; `oldFn` must not exist after" \u2014 not separate "Add" and "Remove" bullets.\n- **Prefer positive or structural assertions** over prose negations for load-bearing constraints. Back a "must not" with a grep AC or positive reframe; bare prose negation is fragile.\n- **Symbols named in ACs must exist** \u2014 grep for every function or symbol an AC names; verify its return shape matches the spec\'s assumed data contract before marking spec done.\n- **Enumerate every caller and classify its execution context before asserting how a mechanism works** \u2014 "counter X only increments on event Y" or "this writer can only be invoked from surface Z" is a control-flow claim, and control-flow claims need every caller traced. A helper named for one trigger routinely serves several, and whether a call site runs inside an agent\'s own session or in the orchestrator\'s process is invisible from the function body. Grep every caller of the function or counter \u2014 including skills and docs, not just source \u2014 and classify each site as in-agent-session or orchestrator-context before the spec asserts anything about it.\n- **Find sibling implementations, not just callers** \u2014 before settling Affected Files, search for every other place that implements the behavior the spec changes: a second listener or entry path, a parallel component, or a test or doc that asserts the current behavior. A change that reaches one of two implementations ships half-done, and the gap usually surfaces only at code review.\n- **Behavioral contracts, not mechanics** \u2014 ACs describe observable behavior; defer implementation mechanics (signatures, constant names, precise algorithms) to plan/implement. If review rounds start re-litigating literal regexes, exact file layouts, or verbatim command strings, the spec has dropped to code altitude and each round\'s "underspecified" finding just adds more reviewable surface: move the mechanics into a clearly-labeled non-binding *Implementation Notes* subsection owned by plan/implement, rather than wording the same mechanism more precisely.\n- **List every judgment call in *Judgment Calls*** \u2014 A judgment call is a choice between two or more defensible options where the choice changes behavior or scope. A choice a project doc already settles is not a judgment call: follow the doc and cite it. For each call record the chosen option, the strongest alternative, why the choice fits, and Decided by: `Human` only when the human explicitly chose it, otherwise `Author`. Listing them is your own obligation as author: on fast-tier (XS, non-delicate) tasks the `spec_review` checkpoint is skipped, so the author\'s list is the only check.\n- **Bug and flake-fix specs need a confirmed mechanism and red-first test** \u2014 For a bug or flake fix, the spec author must state, in *Problem*, both the confirmed mechanism and how it was confirmed \u2014 not merely a plausible cause. Evidence must match the mechanism class: a deterministic mechanism (fixed inputs hit the same wrong branch every run) may cite a trace with the verified trigger values; a runtime-dependent mechanism (race, timing, environment/config interaction) needs executed confirmation \u2014 a throwaway prototype-fix spike that makes the symptom vanish, or a deterministic forced repro. The author must satisfy that checkpoint before the spec is marked done; on fast-tier (XS, non-delicate) tasks the `spec_review` checkpoint is skipped, so no reviewer will catch an unverified mechanism. The *Acceptance Criteria* must include a red-first regression-test AC: a test that fails on the pre-fix code for the stated reason and passes after the fix. If the mechanism is environment-bound and a faithful repro is impractical, *Problem* must say so and name a deterministic alternative (integration fixture or documented manual repro) instead of skipping verification silently.\n- **At \u22653 spec_review iterations, read the rounds\' content, not the count** \u2014 label each round *edge-fine-tune* (it narrows an already-identified case \u2014 converging, safe to finish once the remaining findings are addressed) or *scope-expansion* (it names a **new** structural case the spec hadn\'t covered \u2014 a real design gap). Round count alone is not the signal; a 6-round run of successive fine-tunes is convergence, not churn. On genuine scope-expansion, don\'t refine again: check whether the last two rejections share one structural root, and whether an existing layer already owns the concern. Dropping the whole mechanism class \u2014 or deleting the mechanism in favor of the layer that already owns it \u2014 is usually cheaper than another round of hardening.\n- **Refactor specs need structural caps** \u2014 provide hard size caps, explicit deletion expectations per symbol, and an allow-list grep AC for any symbol that must disappear.\n- **Refactor specs need a correctness audit** \u2014 For each behavior a refactor declares preserved, record in Problem whether it is correct today, and state one outcome: correct as-is, fixed deliberately (with its own AC), split into a separate task, or kept as a named quirk. A behavior confirmed correct needs only a one-line record. N/A for features and bug fixes.\n- **UI spatial / gesture tasks** \u2014 flag "visual positioning \u2014 expect human iteration" or "runtime debugging required" in *Known Risks*.\n- **Sensitive-surface escalation** \u2014 flag these categories with `canon task set <id> delicate true` and call them out in *Known Risks*: auth, billing / payments, privacy / data handling, destructive operations, schema / data-model migrations, analytics-event changes. The human spec gate is where such tasks stop for review.\n\n{{{selfCheck}}}\n\nWhen done, run (one per task):\n{{{phaseCommands}}}\n';
|
|
6746
|
+
var spec_default = '{{{header}}}\n\n{{{startup}}}\n\n{{{instructions}}}\n{{{bundleNote}}}\n{{#doneNote}}\nNote: {{{doneNote}}}{{/doneNote}}\n\n{{#docsMapBlock}}\n{{{docsMapBlock}}}\n\n{{/docsMapBlock}}\n**Spec-writing rules of thumb** \u2014 apply when writing each spec:\n\n- **Name effects to DELETE** \u2014 frame supersession as replacement, not add-plus-remove. State: "replace `oldFn` with `newFn`; `oldFn` must not exist after" \u2014 not separate "Add" and "Remove" bullets.\n- **Prefer positive or structural assertions** over prose negations for load-bearing constraints. Back a "must not" with a grep AC or positive reframe; bare prose negation is fragile.\n- **Symbols named in ACs must exist** \u2014 grep for every function or symbol an AC names; verify its return shape matches the spec\'s assumed data contract before marking spec done.\n- **Enumerate every caller and classify its execution context before asserting how a mechanism works** \u2014 "counter X only increments on event Y" or "this writer can only be invoked from surface Z" is a control-flow claim, and control-flow claims need every caller traced. A helper named for one trigger routinely serves several, and whether a call site runs inside an agent\'s own session or in the orchestrator\'s process is invisible from the function body. Grep every caller of the function or counter \u2014 including skills and docs, not just source \u2014 and classify each site as in-agent-session or orchestrator-context before the spec asserts anything about it.\n- **Find sibling implementations, not just callers** \u2014 before settling Affected Files, search for every other place that implements the behavior the spec changes: a second listener or entry path, a parallel component, or a test or doc that asserts the current behavior. A change that reaches one of two implementations ships half-done, and the gap usually surfaces only at code review.\n- **Behavioral contracts, not mechanics** \u2014 ACs describe observable behavior; defer implementation mechanics (signatures, constant names, precise algorithms) to plan/implement. If review rounds start re-litigating literal regexes, exact file layouts, or verbatim command strings, the spec has dropped to code altitude and each round\'s "underspecified" finding just adds more reviewable surface: move the mechanics into a clearly-labeled non-binding *Implementation Notes* subsection owned by plan/implement, rather than wording the same mechanism more precisely.\n- **List every judgment call in *Judgment Calls*** \u2014 A judgment call is a choice between two or more defensible options where the choice changes behavior or scope. A choice a project doc already settles is not a judgment call: follow the doc and cite it. For each call record the chosen option, the strongest alternative, why the choice fits, and Decided by: `Human` only when the human explicitly chose it, otherwise `Author`. Listing them is your own obligation as author: on fast-tier (XS, non-delicate) tasks the `spec_review` checkpoint is skipped, so the author\'s list is the only check.\n- **Bug and flake-fix specs need a confirmed mechanism and red-first test** \u2014 For a bug or flake fix, the spec author must state, in *Problem*, both the confirmed mechanism and how it was confirmed \u2014 not merely a plausible cause. Evidence must match the mechanism class: a deterministic mechanism (fixed inputs hit the same wrong branch every run) may cite a trace with the verified trigger values; a runtime-dependent mechanism (race, timing, environment/config interaction) needs executed confirmation \u2014 a throwaway prototype-fix spike that makes the symptom vanish, or a deterministic forced repro. The author must satisfy that checkpoint before the spec is marked done; on fast-tier (XS, non-delicate) tasks the `spec_review` checkpoint is skipped, so no reviewer will catch an unverified mechanism. The *Acceptance Criteria* must include a red-first regression-test AC: a test that fails on the pre-fix code for the stated reason and passes after the fix. If the mechanism is environment-bound and a faithful repro is impractical, *Problem* must say so and name a deterministic alternative (integration fixture or documented manual repro) instead of skipping verification silently.\n- **At \u22653 spec_review iterations, read the rounds\' content, not the count** \u2014 label each round *edge-fine-tune* (it narrows an already-identified case \u2014 converging, safe to finish once the remaining findings are addressed) or *scope-expansion* (it names a **new** structural case the spec hadn\'t covered \u2014 a real design gap). Round count alone is not the signal; a 6-round run of successive fine-tunes is convergence, not churn. On genuine scope-expansion, don\'t refine again: check whether the last two rejections share one structural root, and whether an existing layer already owns the concern. Dropping the whole mechanism class \u2014 or deleting the mechanism in favor of the layer that already owns it \u2014 is usually cheaper than another round of hardening.\n- **Refactor specs need structural caps** \u2014 provide hard size caps, explicit deletion expectations per symbol, and an allow-list grep AC for any symbol that must disappear.\n- **Refactor specs need a correctness audit** \u2014 For each behavior a refactor declares preserved, record in Problem whether it is correct today, and state one outcome: correct as-is, fixed deliberately (with its own AC), split into a separate task, or kept as a named quirk. A behavior confirmed correct needs only a one-line record. N/A for features and bug fixes.\n- **Codebase-wide term renames: gate per string family, not per enumerated hit** \u2014 a hand-enumerated list of grep hits grows every review round, because each round surfaces a new label *family* rather than a missed instance. Before writing ACs, sweep the codebase once to split the old term into its distinct string families, and gate each family with a zero-result grep AC whose word-bounded pattern catches every separator variant and cannot match the new term. Where the old string is a substring of the new one, a zero-result grep cannot work: verify those surfaces with positive targeted ACs and say so in the spec, so reviewers don\'t read it as a gap. Before finalizing a zero-result AC, read each affected prose file for paraphrases of the retired claim, and fold hits the spec already tolerates elsewhere (historical docs, test fixtures) into a permitted-to-remain list inside the same AC.\n- **UI spatial / gesture tasks** \u2014 flag "visual positioning \u2014 expect human iteration" or "runtime debugging required" in *Known Risks*.\n- **Sensitive-surface escalation** \u2014 flag these categories with `canon task set <id> delicate true` and call them out in *Known Risks*: auth, billing / payments, privacy / data handling, destructive operations, schema / data-model migrations, analytics-event changes. The human spec gate is where such tasks stop for review.\n\n{{{selfCheck}}}\n\nWhen done, run (one per task):\n{{{phaseCommands}}}\n';
|
|
5787
6747
|
|
|
5788
6748
|
// src/orchestrator/prompts/templates/spec-revision.md
|
|
5789
|
-
var spec_revision_default = 'You are revising specs for {{taskScope}} for {{projectName}}.\n\n{{{startup}}}\n\nTasks with review feedback:\n{{{reviewLines}}}\n\nAddress every `changes_requested` finding in each spec.md.{{#combined}}\nAlso update plan.md if spec changes affect the implementation approach.{{/combined}}\n\n{{#docsMapBlock}}\n{{{docsMapBlock}}}\n\n{{/docsMapBlock}}\n**Spec-writing rules of thumb** \u2014 apply when revising each spec:\n\n- **Name effects to DELETE** \u2014 frame supersession as replacement, not add-plus-remove. State: "replace `oldFn` with `newFn`; `oldFn` must not exist after" \u2014 not separate "Add" and "Remove" bullets.\n- **Prefer positive or structural assertions** over prose negations for load-bearing constraints. Back a "must not" with a grep AC or positive reframe; bare prose negation is fragile.\n- **Symbols named in ACs must exist** \u2014 grep for every function or symbol an AC names; verify its return shape matches the spec\'s assumed data contract before marking spec done.\n- **Enumerate every caller and classify its execution context before asserting how a mechanism works** \u2014 "counter X only increments on event Y" or "this writer can only be invoked from surface Z" is a control-flow claim, and control-flow claims need every caller traced. A helper named for one trigger routinely serves several, and whether a call site runs inside an agent\'s own session or in the orchestrator\'s process is invisible from the function body. Grep every caller of the function or counter \u2014 including skills and docs, not just source \u2014 and classify each site as in-agent-session or orchestrator-context before the spec asserts anything about it.\n- **Find sibling implementations, not just callers** \u2014 before settling Affected Files, search for every other place that implements the behavior the spec changes: a second listener or entry path, a parallel component, or a test or doc that asserts the current behavior. A change that reaches one of two implementations ships half-done, and the gap usually surfaces only at code review.\n- **Behavioral contracts, not mechanics** \u2014 ACs describe observable behavior; defer implementation mechanics (signatures, constant names, precise algorithms) to plan/implement. If review rounds start re-litigating literal regexes, exact file layouts, or verbatim command strings, the spec has dropped to code altitude and each round\'s "underspecified" finding just adds more reviewable surface: move the mechanics into a clearly-labeled non-binding *Implementation Notes* subsection owned by plan/implement, rather than wording the same mechanism more precisely.\n- **List every judgment call in *Judgment Calls*** \u2014 A judgment call is a choice between two or more defensible options where the choice changes behavior or scope. A choice a project doc already settles is not a judgment call: follow the doc and cite it. For each call record the chosen option, the strongest alternative, why the choice fits, and Decided by: `Human` only when the human explicitly chose it, otherwise `Author`. Listing them is your own obligation as author. Keep a row\'s Decided by value unchanged when its chosen option stays the same; a revision that changes the chosen option resets that row to `Author`.\n- **Bug and flake-fix specs need a confirmed mechanism and red-first test** \u2014 For a bug or flake fix, the spec author must state, in *Problem*, both the confirmed mechanism and how it was confirmed \u2014 not merely a plausible cause. Evidence must match the mechanism class: a deterministic mechanism (fixed inputs hit the same wrong branch every run) may cite a trace with the verified trigger values; a runtime-dependent mechanism (race, timing, environment/config interaction) needs executed confirmation \u2014 a throwaway prototype-fix spike that makes the symptom vanish, or a deterministic forced repro. The author must satisfy that checkpoint before the spec is marked done; on fast-tier (XS, non-delicate) tasks the `spec_review` checkpoint is skipped, so no reviewer will catch an unverified mechanism. The *Acceptance Criteria* must include a red-first regression-test AC: a test that fails on the pre-fix code for the stated reason and passes after the fix. If the mechanism is environment-bound and a faithful repro is impractical, *Problem* must say so and name a deterministic alternative (integration fixture or documented manual repro) instead of skipping verification silently.\n- **At \u22653 spec_review iterations, read the rounds\' content, not the count** \u2014 label each round *edge-fine-tune* (it narrows an already-identified case \u2014 converging, safe to finish once the remaining findings are addressed) or *scope-expansion* (it names a **new** structural case the spec hadn\'t covered \u2014 a real design gap). Round count alone is not the signal; a 6-round run of successive fine-tunes is convergence, not churn. On genuine scope-expansion, don\'t refine again: check whether the last two rejections share one structural root, and whether an existing layer already owns the concern. Dropping the whole mechanism class \u2014 or deleting the mechanism in favor of the layer that already owns it \u2014 is usually cheaper than another round of hardening.\n- **Refactor specs need structural caps** \u2014 provide hard size caps, explicit deletion expectations per symbol, and an allow-list grep AC for any symbol that must disappear.\n- **Refactor specs need a correctness audit** \u2014 For each behavior a refactor declares preserved, record in Problem whether it is correct today, and state one outcome: correct as-is, fixed deliberately (with its own AC), split into a separate task, or kept as a named quirk. A behavior confirmed correct needs only a one-line record. N/A for features and bug fixes.\n- **UI spatial / gesture tasks** \u2014 flag "visual positioning \u2014 expect human iteration" or "runtime debugging required" in *Known Risks*.\n- **Sensitive-surface escalation** \u2014 flag these categories with `canon task set <id> delicate true` and call them out in *Known Risks*: auth, billing / payments, privacy / data handling, destructive operations, schema / data-model migrations, analytics-event changes. The human spec gate is where such tasks stop for review.\n\n- **Scope manifest** \u2014 Affected Files uses exactly one `### Affected Files` heading under `## Design` and at most one per `## Amendment\u2026` section (a behavior-only amendment needs none), with one file per row: comma-join extra paths for the same change in the first column, put notes in the Change column, and never put a second backticked token in a first-column note (directory entries ending in `/` are fine). Marking the spec done enforces this format, and canon re-checks it before planning and implementation.\n\nWhen done, run:\n{{{phaseCommands}}}\n';
|
|
6749
|
+
var spec_revision_default = 'You are revising specs for {{taskScope}} for {{projectName}}.\n\n{{{startup}}}\n\nTasks with review feedback:\n{{{reviewLines}}}\n\nAddress every `changes_requested` finding in each spec.md.{{#combined}}\nAlso update plan.md if spec changes affect the implementation approach.{{/combined}}\n\n{{#docsMapBlock}}\n{{{docsMapBlock}}}\n\n{{/docsMapBlock}}\n**Spec-writing rules of thumb** \u2014 apply when revising each spec:\n\n- **Name effects to DELETE** \u2014 frame supersession as replacement, not add-plus-remove. State: "replace `oldFn` with `newFn`; `oldFn` must not exist after" \u2014 not separate "Add" and "Remove" bullets.\n- **Prefer positive or structural assertions** over prose negations for load-bearing constraints. Back a "must not" with a grep AC or positive reframe; bare prose negation is fragile.\n- **Symbols named in ACs must exist** \u2014 grep for every function or symbol an AC names; verify its return shape matches the spec\'s assumed data contract before marking spec done.\n- **Enumerate every caller and classify its execution context before asserting how a mechanism works** \u2014 "counter X only increments on event Y" or "this writer can only be invoked from surface Z" is a control-flow claim, and control-flow claims need every caller traced. A helper named for one trigger routinely serves several, and whether a call site runs inside an agent\'s own session or in the orchestrator\'s process is invisible from the function body. Grep every caller of the function or counter \u2014 including skills and docs, not just source \u2014 and classify each site as in-agent-session or orchestrator-context before the spec asserts anything about it.\n- **Find sibling implementations, not just callers** \u2014 before settling Affected Files, search for every other place that implements the behavior the spec changes: a second listener or entry path, a parallel component, or a test or doc that asserts the current behavior. A change that reaches one of two implementations ships half-done, and the gap usually surfaces only at code review.\n- **Behavioral contracts, not mechanics** \u2014 ACs describe observable behavior; defer implementation mechanics (signatures, constant names, precise algorithms) to plan/implement. If review rounds start re-litigating literal regexes, exact file layouts, or verbatim command strings, the spec has dropped to code altitude and each round\'s "underspecified" finding just adds more reviewable surface: move the mechanics into a clearly-labeled non-binding *Implementation Notes* subsection owned by plan/implement, rather than wording the same mechanism more precisely.\n- **List every judgment call in *Judgment Calls*** \u2014 A judgment call is a choice between two or more defensible options where the choice changes behavior or scope. A choice a project doc already settles is not a judgment call: follow the doc and cite it. For each call record the chosen option, the strongest alternative, why the choice fits, and Decided by: `Human` only when the human explicitly chose it, otherwise `Author`. Listing them is your own obligation as author. Keep a row\'s Decided by value unchanged when its chosen option stays the same; a revision that changes the chosen option resets that row to `Author`.\n- **Bug and flake-fix specs need a confirmed mechanism and red-first test** \u2014 For a bug or flake fix, the spec author must state, in *Problem*, both the confirmed mechanism and how it was confirmed \u2014 not merely a plausible cause. Evidence must match the mechanism class: a deterministic mechanism (fixed inputs hit the same wrong branch every run) may cite a trace with the verified trigger values; a runtime-dependent mechanism (race, timing, environment/config interaction) needs executed confirmation \u2014 a throwaway prototype-fix spike that makes the symptom vanish, or a deterministic forced repro. The author must satisfy that checkpoint before the spec is marked done; on fast-tier (XS, non-delicate) tasks the `spec_review` checkpoint is skipped, so no reviewer will catch an unverified mechanism. The *Acceptance Criteria* must include a red-first regression-test AC: a test that fails on the pre-fix code for the stated reason and passes after the fix. If the mechanism is environment-bound and a faithful repro is impractical, *Problem* must say so and name a deterministic alternative (integration fixture or documented manual repro) instead of skipping verification silently.\n- **At \u22653 spec_review iterations, read the rounds\' content, not the count** \u2014 label each round *edge-fine-tune* (it narrows an already-identified case \u2014 converging, safe to finish once the remaining findings are addressed) or *scope-expansion* (it names a **new** structural case the spec hadn\'t covered \u2014 a real design gap). Round count alone is not the signal; a 6-round run of successive fine-tunes is convergence, not churn. On genuine scope-expansion, don\'t refine again: check whether the last two rejections share one structural root, and whether an existing layer already owns the concern. Dropping the whole mechanism class \u2014 or deleting the mechanism in favor of the layer that already owns it \u2014 is usually cheaper than another round of hardening.\n- **Refactor specs need structural caps** \u2014 provide hard size caps, explicit deletion expectations per symbol, and an allow-list grep AC for any symbol that must disappear.\n- **Refactor specs need a correctness audit** \u2014 For each behavior a refactor declares preserved, record in Problem whether it is correct today, and state one outcome: correct as-is, fixed deliberately (with its own AC), split into a separate task, or kept as a named quirk. A behavior confirmed correct needs only a one-line record. N/A for features and bug fixes.\n- **Codebase-wide term renames: gate per string family, not per enumerated hit** \u2014 a hand-enumerated list of grep hits grows every review round, because each round surfaces a new label *family* rather than a missed instance. Before writing ACs, sweep the codebase once to split the old term into its distinct string families, and gate each family with a zero-result grep AC whose word-bounded pattern catches every separator variant and cannot match the new term. Where the old string is a substring of the new one, a zero-result grep cannot work: verify those surfaces with positive targeted ACs and say so in the spec, so reviewers don\'t read it as a gap. Before finalizing a zero-result AC, read each affected prose file for paraphrases of the retired claim, and fold hits the spec already tolerates elsewhere (historical docs, test fixtures) into a permitted-to-remain list inside the same AC.\n- **UI spatial / gesture tasks** \u2014 flag "visual positioning \u2014 expect human iteration" or "runtime debugging required" in *Known Risks*.\n- **Sensitive-surface escalation** \u2014 flag these categories with `canon task set <id> delicate true` and call them out in *Known Risks*: auth, billing / payments, privacy / data handling, destructive operations, schema / data-model migrations, analytics-event changes. The human spec gate is where such tasks stop for review.\n\n- **Scope manifest** \u2014 Affected Files uses exactly one `### Affected Files` heading under `## Design` and at most one per `## Amendment\u2026` section (a behavior-only amendment needs none), with one file per row: comma-join extra paths for the same change in the first column, put notes in the Change column, and never put a second backticked token in a first-column note (directory entries ending in `/` are fine). Marking the spec done enforces this format, and canon re-checks it before planning and implementation.\n\nWhen done, run:\n{{{phaseCommands}}}\n';
|
|
5790
6750
|
|
|
5791
6751
|
// src/orchestrator/prompts/templates/spec-review-reroute.md
|
|
5792
6752
|
var spec_review_reroute_default = "You are reviewing {{taskScope}} for {{projectName}}.\n\n{{{startup}}}\n\nA human amended the spec and rerouted this task after implementation began. The original spec was already reviewed and approved. Your job is to review **the amendment and its integration** with the already-approved spec, not to re-litigate settled findings.\n\n{{{roundBanner}}}Tasks with amendments to review:\n{{{taskLines}}}\n\n**Amendment review scope** (for each task \u2014 EXCEPT tasks whose line above marks them EXEMPT: those have no amendment and require no review work this round; do not request changes for a missing Amendment heading on them):\n1. Read `tasks/<id>/spec.md` from your current directory. Locate the exact amendment heading named above: `## Amendment` for round 1, or `## Amendment Round N` for round 2+.\n2. Read `tasks/<id>/spec-review.md` so you know what was already reviewed and do not re-raise settled findings.\n3. Review the amendment itself: is it implementable as written, are ACs verifiable, and are edge cases handled?\n4. Review integration with approved ACs: does the amendment contradict, weaken, duplicate, or leave gaps against previously approved requirements?\n5. Review overall shape: with the amendment included, is the spec still coherent and in scope?\n6. Do **not** read or audit `handoff.md`, `review.md`, or `done.md`. This phase stays in the spec domain.\n\nGrounding rule: if a finding depends on a symbol or file, re-open it before claiming it exists.\n\n{{#mixedProvider}}**Cross-review rule**: No agent reviews its own output. Claude writes specs \u2192 Codex reviews specs. Codex writes code \u2192 Claude reviews code.{{/mixedProvider}}{{^mixedProvider}}**Cross-review rule**: Separate Claude sessions write specs, review specs, implement code and review code. Reviewers use independent sessions; cold code-review lenses remain spec-blind.{{/mixedProvider}}\n\n**Diagnose before you fix \u2014 3-role checkpoint**: For any amendment addressing a bug or flake fix, each role owns a checkpoint: the spec author states the confirmed mechanism and its evidence in *Problem* (a deterministic mechanism \u2014 fixed inputs hit the same wrong branch every run \u2014 may cite a trace with the verified trigger values; a runtime-dependent mechanism \u2014 race, timing, environment/config interaction \u2014 needs executed confirmation: a throwaway prototype-fix spike that makes the symptom vanish, or a deterministic forced repro); the reviewer challenges whether that evidence establishes the root cause; the implementer runs the spec's red-first test against the pre-fix code (or, under the environment-bound-and-impractical escape, its named deterministic alternative) and reports the result in the handoff. A mechanism with no confirmation evidence, or evidence below its class's required rung, is a blocking Shape Check concern \u2014 as is a bug/flake amendment carrying neither a red-first regression-test AC nor the explicit environment-bound-and-impractical escape with a named deterministic alternative.\n\n**Verdict rules** (same as normal spec review):\n- `changes_requested` \u2014 one or more blocking findings. The human must revise the amendment and re-run.\n- `approved_with_nits` \u2014 no blockers; non-blocking observations only. Loop exits immediately.\n- `approved` \u2014 no findings.\n\nFor each task, append a new amendment-review section to `tasks/<id>/spec-review.md`; do not overwrite the prior review. Use this exact heading for the section (the orchestrator's evidence gate requires it before advancing):\n - Round 1: `## Amendment Review`\n - Round N >= 2: `## Amendment Review Round N`\nRecord your verdict **inside that section** as a checked box \u2014 the evidence gate reads the verdict from this section, not from the original review above it. Check exactly one of:\n`- [x] **Approved**` / `- [x] **Approved with nits**` / `- [x] **Changes requested**`.\n\nWhen done, run (one per task with actual verdict):\n{{{phaseCommands}}}\n\n<!-- per-round append shape (round 1 omits the round suffix):\n## Amendment Review (round 1)\n## Amendment Review Round N (round N >= 2)\n- [x] **Approved** (check exactly one verdict box)\n> Findings: ...\n-->\n";
|
|
@@ -5818,8 +6778,9 @@ function render3(name, view) {
|
|
|
5818
6778
|
}
|
|
5819
6779
|
var ARTIFACT_CITATION_RULE = "**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.";
|
|
5820
6780
|
function promptArtifactFixup(input) {
|
|
6781
|
+
const isCodeReview = input.phase === "code_review";
|
|
5821
6782
|
const lines = [
|
|
5822
|
-
`ARTIFACT FIX-UP (${input.attempt}/${input.maxAttempts}): before committing, canon ran docs-refs-check and found broken references in task artifacts you wrote
|
|
6783
|
+
`ARTIFACT FIX-UP (${input.attempt}/${input.maxAttempts}): ${isCodeReview ? "before acting on the review, canon ran docs-refs-check and found broken references in task artifacts you wrote:" : "before committing, canon ran docs-refs-check and found broken references in task artifacts you wrote:"}`,
|
|
5823
6784
|
...input.findings.map((line) => ` ${line}`),
|
|
5824
6785
|
"",
|
|
5825
6786
|
`The ${input.phase} phase is already complete. This turn overrides the session instructions above about finishing with a phase command: do not run \`canon task phase\` or any other \`canon\` command.`,
|
|
@@ -5829,7 +6790,11 @@ function promptArtifactFixup(input) {
|
|
|
5829
6790
|
"",
|
|
5830
6791
|
"Do not change any other file \u2014 including notes.md, status.json, and source or test files. Canon compares the working tree before and after this turn and stops the run if anything else changed."
|
|
5831
6792
|
];
|
|
5832
|
-
|
|
6793
|
+
if (isCodeReview) {
|
|
6794
|
+
lines.push("Canon checks these references before acting on the review. Edit only references; do not change any verdict checkbox or finding.");
|
|
6795
|
+
} else {
|
|
6796
|
+
lines.push("Do not run git add or git commit; the orchestrator commits after this turn.");
|
|
6797
|
+
}
|
|
5833
6798
|
lines.push("", ARTIFACT_CITATION_RULE, "", "Fix each listed reference \u2014 correct the path, switch a missing file to the markdown-link form, or rephrase it as plain prose if it is not a file reference. Reply with tool calls only.");
|
|
5834
6799
|
return lines.join("\n");
|
|
5835
6800
|
}
|
|
@@ -6072,8 +7037,10 @@ function promptImplement(state, mode = "fresh", affectedFiles, baseBranch) {
|
|
|
6072
7037
|
stateHeader: buildImplementStateHeader(state, mode),
|
|
6073
7038
|
startup: implementationStartup(state.provider),
|
|
6074
7039
|
risksBlock: buildKnownRisks(taskIds),
|
|
6075
|
-
pitfallsBlock:
|
|
7040
|
+
pitfallsBlock: buildRelevantPitfalls(taskIds),
|
|
6076
7041
|
contextBlock: buildContextBlock(taskIds),
|
|
7042
|
+
selfCheck: mode === "fresh",
|
|
7043
|
+
blastRadiusBlock: mode === "fresh" ? buildBlastRadiusBlock(taskIds, resolveBlastRadiusRoot(taskIds)) : "",
|
|
6077
7044
|
affectedFilesBlock: buildAffectedFilesBlock(affectedFiles, baseBranch),
|
|
6078
7045
|
taskLines,
|
|
6079
7046
|
isBundle: tasks.length > 1,
|
|
@@ -6100,7 +7067,7 @@ function promptImplementResume(state) {
|
|
|
6100
7067
|
"",
|
|
6101
7068
|
"Your only remaining tasks:",
|
|
6102
7069
|
`1. Run the project's validation commands (see the change-type \u2192 check-category validation matrix included below and each spec's "Validation Required" section) and record results.`,
|
|
6103
|
-
"2. Write handoff.md for each task (intent/rationale, deviations, AC coverage, validation outcomes).",
|
|
7070
|
+
"2. Write handoff.md for each task (intent/rationale, deviations, AC coverage, the `## Self-Check` evidence table \u2014 test integrity, restatement sweep, sibling parity, each with evidence or `N/A \u2014 <reason>` \u2014 and validation outcomes).",
|
|
6104
7071
|
"3. Run canon task to mark implement done for each task.",
|
|
6105
7072
|
"",
|
|
6106
7073
|
promptImplement(state, "resume")
|
|
@@ -6182,8 +7149,9 @@ function promptImplementReroute(state, isResumedSession = false, affectedFiles,
|
|
|
6182
7149
|
preamble,
|
|
6183
7150
|
groundingRule,
|
|
6184
7151
|
risksBlock: buildKnownRisks(taskIds),
|
|
6185
|
-
pitfallsBlock:
|
|
7152
|
+
pitfallsBlock: buildRelevantPitfalls(taskIds),
|
|
6186
7153
|
contextBlock: buildContextBlock(taskIds),
|
|
7154
|
+
blastRadiusBlock: buildBlastRadiusBlock(taskIds, resolveBlastRadiusRoot(taskIds)),
|
|
6187
7155
|
affectedFilesBlock: buildAffectedFilesBlock(affectedFiles, baseBranch),
|
|
6188
7156
|
taskLines,
|
|
6189
7157
|
phaseCommands: phaseCommands(taskIds, "implement", "done")
|
|
@@ -6207,9 +7175,9 @@ function archivedReviewGuidance(taskId) {
|
|
|
6207
7175
|
}
|
|
6208
7176
|
function bundleHasRealPriorReview(taskIds) {
|
|
6209
7177
|
return taskIds.every((taskId) => {
|
|
6210
|
-
const reviewPath =
|
|
7178
|
+
const reviewPath = path15.join(taskDirFor(taskId), "review.md");
|
|
6211
7179
|
try {
|
|
6212
|
-
const content =
|
|
7180
|
+
const content = fs17.readFileSync(reviewPath, "utf8");
|
|
6213
7181
|
const hasH2 = /^## Stage 1\b/m.test(content);
|
|
6214
7182
|
const hasNested = /^## Round \d+\b/m.test(content) && /^### Stage 1\b/m.test(content);
|
|
6215
7183
|
return (hasH2 || hasNested) && !content.includes("[TASK-ID]");
|
|
@@ -6302,34 +7270,34 @@ function promptQa(state, prTemplate, docs = { editable: DEFAULT_PROTECTED_DOCS,
|
|
|
6302
7270
|
}
|
|
6303
7271
|
|
|
6304
7272
|
// src/task/index.ts
|
|
7273
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
7274
|
+
import fs20 from "fs";
|
|
7275
|
+
import path18 from "path";
|
|
7276
|
+
|
|
7277
|
+
// src/orchestrator/canon-snapshot.ts
|
|
6305
7278
|
import { spawnSync as spawnSync6 } from "child_process";
|
|
6306
7279
|
import fs18 from "fs";
|
|
6307
7280
|
import path16 from "path";
|
|
6308
|
-
|
|
6309
|
-
// src/orchestrator/canon-snapshot.ts
|
|
6310
|
-
import { spawnSync as spawnSync5 } from "child_process";
|
|
6311
|
-
import fs16 from "fs";
|
|
6312
|
-
import path14 from "path";
|
|
6313
7281
|
var CANON_UPSTREAM_REPO = "tstraub89/canon-ai";
|
|
6314
7282
|
function isInstalledSourcePath(sourcePath) {
|
|
6315
7283
|
return sourcePath.includes("/node_modules/") || sourcePath.includes("\\node_modules\\") || sourcePath.includes("/_npx/") || sourcePath.includes("\\_npx\\");
|
|
6316
7284
|
}
|
|
6317
7285
|
function resolveCanonVersion(explicit) {
|
|
6318
|
-
return explicit ?? "3.
|
|
7286
|
+
return explicit ?? "3.19.0" ?? "dev";
|
|
6319
7287
|
}
|
|
6320
7288
|
function resolveOrchestratorCommit(repoRoot, upstreamCommit, runGitAt) {
|
|
6321
7289
|
const ownToplevel = captureGitOutput(repoRoot, ["rev-parse", "--show-toplevel"], runGitAt);
|
|
6322
7290
|
if (!ownToplevel) return upstreamCommit;
|
|
6323
|
-
const parentDir =
|
|
7291
|
+
const parentDir = path16.dirname(repoRoot);
|
|
6324
7292
|
const parentToplevel = captureGitOutput(parentDir, ["rev-parse", "--show-toplevel"], runGitAt);
|
|
6325
7293
|
if (!parentToplevel) return upstreamCommit;
|
|
6326
|
-
if (
|
|
7294
|
+
if (path16.resolve(parentToplevel) === path16.resolve(ownToplevel)) {
|
|
6327
7295
|
return upstreamCommit;
|
|
6328
7296
|
}
|
|
6329
|
-
return captureGitOutput(
|
|
7297
|
+
return captureGitOutput(path16.resolve(parentToplevel), ["rev-parse", "HEAD"], runGitAt) || upstreamCommit;
|
|
6330
7298
|
}
|
|
6331
7299
|
function defaultRunCommand(command, args) {
|
|
6332
|
-
const result =
|
|
7300
|
+
const result = spawnSync6(command, args, {
|
|
6333
7301
|
cwd: REPO_ROOT,
|
|
6334
7302
|
encoding: "utf8",
|
|
6335
7303
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -6360,7 +7328,7 @@ function captureCanonSnapshot(repoRoot = REPO_ROOT, options = {}) {
|
|
|
6360
7328
|
const isInstalled = isInstalledSourcePath(canonSourcePath);
|
|
6361
7329
|
const superprojectWorkingTree = captureGitOutput(repoRoot, ["rev-parse", "--show-superproject-working-tree"], runGitAt);
|
|
6362
7330
|
const drivingCommit = captureGitOutput(repoRoot, ["rev-parse", "HEAD"], runGitAt) || "<unavailable>";
|
|
6363
|
-
const hostCommit = superprojectWorkingTree ? captureGitOutput(
|
|
7331
|
+
const hostCommit = superprojectWorkingTree ? captureGitOutput(path16.resolve(superprojectWorkingTree), ["rev-parse", "HEAD"], runGitAt) || "<unavailable>" : null;
|
|
6364
7332
|
let upstreamCommit;
|
|
6365
7333
|
let orchestratorCommit;
|
|
6366
7334
|
if (isInstalled) {
|
|
@@ -6394,14 +7362,14 @@ function applyCanonSnapshot(status, canon) {
|
|
|
6394
7362
|
return next;
|
|
6395
7363
|
}
|
|
6396
7364
|
function refreshCanonSnapshotAtPath(statusFilePath, options = {}) {
|
|
6397
|
-
const status = JSON.parse(
|
|
7365
|
+
const status = JSON.parse(fs18.readFileSync(statusFilePath, "utf8"));
|
|
6398
7366
|
const canon = captureCanonSnapshot(REPO_ROOT, options);
|
|
6399
7367
|
const next = applyCanonSnapshot(status, canon);
|
|
6400
7368
|
const serialized = `${JSON.stringify(next, null, 2)}
|
|
6401
7369
|
`;
|
|
6402
|
-
const current =
|
|
7370
|
+
const current = fs18.readFileSync(statusFilePath, "utf8");
|
|
6403
7371
|
if (current !== serialized) {
|
|
6404
|
-
|
|
7372
|
+
fs18.writeFileSync(statusFilePath, serialized, "utf8");
|
|
6405
7373
|
}
|
|
6406
7374
|
return canon;
|
|
6407
7375
|
}
|
|
@@ -6410,8 +7378,8 @@ function refreshCanonSnapshotsAtPaths(statusFilePaths, options = {}) {
|
|
|
6410
7378
|
}
|
|
6411
7379
|
|
|
6412
7380
|
// src/orchestrator/quality-log.ts
|
|
6413
|
-
import
|
|
6414
|
-
import
|
|
7381
|
+
import fs19 from "fs";
|
|
7382
|
+
import path17 from "path";
|
|
6415
7383
|
var CANON_LOG_HEADERS = [
|
|
6416
7384
|
"Date",
|
|
6417
7385
|
"Task",
|
|
@@ -6491,7 +7459,7 @@ function splitTableRowCells(line) {
|
|
|
6491
7459
|
);
|
|
6492
7460
|
return innerCells.map((value) => value.trim());
|
|
6493
7461
|
}
|
|
6494
|
-
function
|
|
7462
|
+
function isSeparatorRow3(cells) {
|
|
6495
7463
|
return cells.length > 0 && cells.every((cell) => /^:?-+:?$/.test(cell.trim()));
|
|
6496
7464
|
}
|
|
6497
7465
|
function locateLogTable(lines) {
|
|
@@ -6512,7 +7480,7 @@ function locateLogTable(lines) {
|
|
|
6512
7480
|
return null;
|
|
6513
7481
|
}
|
|
6514
7482
|
let dataStart = headerIndex + 1;
|
|
6515
|
-
if (dataStart < lines.length &&
|
|
7483
|
+
if (dataStart < lines.length && isSeparatorRow3(splitTableRowCells(lines[dataStart]))) {
|
|
6516
7484
|
dataStart += 1;
|
|
6517
7485
|
}
|
|
6518
7486
|
let dataEnd = dataStart;
|
|
@@ -6532,7 +7500,7 @@ function parseLogRows(lines, headerCells, dataStart, dataEnd) {
|
|
|
6532
7500
|
const rows = [];
|
|
6533
7501
|
for (let index = dataStart; index < dataEnd; index += 1) {
|
|
6534
7502
|
const cells = splitTableRowCells(lines[index]);
|
|
6535
|
-
if (
|
|
7503
|
+
if (isSeparatorRow3(cells)) continue;
|
|
6536
7504
|
rows.push({
|
|
6537
7505
|
lineIndex: index,
|
|
6538
7506
|
cells: rowFromCells(headerCells, cells)
|
|
@@ -6547,7 +7515,7 @@ function parseStrayRows(lines, headerCells) {
|
|
|
6547
7515
|
for (let index = periodicIndex + 1; index < lines.length; index += 1) {
|
|
6548
7516
|
if (!lines[index].trimStart().startsWith("|")) continue;
|
|
6549
7517
|
const cells = splitTableRowCells(lines[index]);
|
|
6550
|
-
if (
|
|
7518
|
+
if (isSeparatorRow3(cells) || cells.length !== headerCells.length) continue;
|
|
6551
7519
|
rows.push({
|
|
6552
7520
|
lineIndex: index,
|
|
6553
7521
|
cells: rowFromCells(headerCells, cells)
|
|
@@ -6602,11 +7570,11 @@ function renderRowLine(headerCells, row) {
|
|
|
6602
7570
|
function writeFileAtomic(filePath, content) {
|
|
6603
7571
|
const tempPath = `${filePath}.tmp`;
|
|
6604
7572
|
try {
|
|
6605
|
-
|
|
6606
|
-
|
|
7573
|
+
fs19.writeFileSync(tempPath, content, "utf8");
|
|
7574
|
+
fs19.renameSync(tempPath, filePath);
|
|
6607
7575
|
} finally {
|
|
6608
7576
|
try {
|
|
6609
|
-
|
|
7577
|
+
fs19.unlinkSync(tempPath);
|
|
6610
7578
|
} catch {
|
|
6611
7579
|
}
|
|
6612
7580
|
}
|
|
@@ -6635,7 +7603,7 @@ function upsertQualityLogRow(logFilePath, derived, qaSupplied) {
|
|
|
6635
7603
|
try {
|
|
6636
7604
|
let content;
|
|
6637
7605
|
try {
|
|
6638
|
-
content =
|
|
7606
|
+
content = fs19.readFileSync(logFilePath, "utf8");
|
|
6639
7607
|
} catch (error) {
|
|
6640
7608
|
if (error.code === "ENOENT") {
|
|
6641
7609
|
content = STANDARD_QUALITY_LOG_SKELETON;
|
|
@@ -6677,11 +7645,11 @@ function writeQualityLogForTask(taskId, _activeCwd, donePath, status) {
|
|
|
6677
7645
|
try {
|
|
6678
7646
|
let doneContent = "";
|
|
6679
7647
|
try {
|
|
6680
|
-
doneContent =
|
|
7648
|
+
doneContent = fs19.readFileSync(donePath, "utf8");
|
|
6681
7649
|
} catch {
|
|
6682
7650
|
}
|
|
6683
|
-
const target = process.env.CANON_QUALITY_LOG_FILE_OVERRIDE ?
|
|
6684
|
-
if (!process.env.CANON_QUALITY_LOG_FILE_OVERRIDE)
|
|
7651
|
+
const target = process.env.CANON_QUALITY_LOG_FILE_OVERRIDE ? path17.resolve(process.env.CANON_QUALITY_LOG_FILE_OVERRIDE) : path17.join(path17.dirname(donePath), "quality-log.md");
|
|
7652
|
+
if (!process.env.CANON_QUALITY_LOG_FILE_OVERRIDE) fs19.mkdirSync(path17.dirname(target), { recursive: true });
|
|
6685
7653
|
upsertQualityLogRow(
|
|
6686
7654
|
target,
|
|
6687
7655
|
{
|
|
@@ -6776,17 +7744,17 @@ function validateTaskId2(id) {
|
|
|
6776
7744
|
}
|
|
6777
7745
|
function taskDirForCwd(_cwd, taskId) {
|
|
6778
7746
|
const override = tasksDirOverride();
|
|
6779
|
-
return override ?
|
|
7747
|
+
return override ? path18.join(override, taskId) : path18.join(resolveTaskCwd(taskId), "tasks", taskId);
|
|
6780
7748
|
}
|
|
6781
7749
|
function taskStatusFileForCwd(cwd, taskId) {
|
|
6782
|
-
return
|
|
7750
|
+
return path18.join(taskDirForCwd(cwd, taskId), "status.json");
|
|
6783
7751
|
}
|
|
6784
7752
|
function taskRootForGate(cwd) {
|
|
6785
|
-
return tasksDirOverride() ??
|
|
7753
|
+
return tasksDirOverride() ?? path18.join(cwd, "tasks");
|
|
6786
7754
|
}
|
|
6787
7755
|
function readJsonFile(filePath) {
|
|
6788
7756
|
try {
|
|
6789
|
-
return JSON.parse(
|
|
7757
|
+
return JSON.parse(fs20.readFileSync(filePath, "utf8"));
|
|
6790
7758
|
} catch (error) {
|
|
6791
7759
|
const message = error instanceof Error ? error.message : String(error);
|
|
6792
7760
|
throw new Error(`Error: failed to read ${filePath}: ${message}`);
|
|
@@ -6794,9 +7762,9 @@ function readJsonFile(filePath) {
|
|
|
6794
7762
|
}
|
|
6795
7763
|
function writeJsonAtomic(filePath, data) {
|
|
6796
7764
|
const tmpFile = `${filePath}.tmp`;
|
|
6797
|
-
|
|
7765
|
+
fs20.writeFileSync(tmpFile, `${JSON.stringify(data, null, 2)}
|
|
6798
7766
|
`, "utf8");
|
|
6799
|
-
|
|
7767
|
+
fs20.renameSync(tmpFile, filePath);
|
|
6800
7768
|
}
|
|
6801
7769
|
function writeStatusAtomic(filePath, status) {
|
|
6802
7770
|
status.status = deriveTopLevelStatus(status);
|
|
@@ -6869,7 +7837,7 @@ function taskPhase(id, phaseArg, statusArg, verdictArg) {
|
|
|
6869
7837
|
assertValidVerdict(phaseArg, verdictArg);
|
|
6870
7838
|
const taskCwd = resolveTaskCwd(id);
|
|
6871
7839
|
const statusPath = taskStatusFileForCwd(taskCwd, id);
|
|
6872
|
-
if (!
|
|
7840
|
+
if (!fs20.existsSync(statusPath)) {
|
|
6873
7841
|
throw new Error(`Error: No status.json found for task ${id} (looked in ${taskDirForCwd(taskCwd, id)}/)`);
|
|
6874
7842
|
}
|
|
6875
7843
|
const status = readJsonFile(statusPath);
|
|
@@ -6911,7 +7879,7 @@ function taskPhase(id, phaseArg, statusArg, verdictArg) {
|
|
|
6911
7879
|
writeQualityLogForTask(
|
|
6912
7880
|
id,
|
|
6913
7881
|
taskCwd,
|
|
6914
|
-
|
|
7882
|
+
path18.join(taskDirForCwd(taskCwd, id), "done.md"),
|
|
6915
7883
|
status
|
|
6916
7884
|
);
|
|
6917
7885
|
}
|
|
@@ -6931,7 +7899,7 @@ function taskPhasePreflightRejected(id, phaseArg) {
|
|
|
6931
7899
|
}
|
|
6932
7900
|
const taskCwd = resolveTaskCwd(id);
|
|
6933
7901
|
const statusPath = taskStatusFileForCwd(taskCwd, id);
|
|
6934
|
-
if (!
|
|
7902
|
+
if (!fs20.existsSync(statusPath)) {
|
|
6935
7903
|
throw new Error(`Error: No status.json found for task ${id} (looked in ${taskDirForCwd(taskCwd, id)}/)`);
|
|
6936
7904
|
}
|
|
6937
7905
|
const status = readJsonFile(statusPath);
|
|
@@ -7111,10 +8079,10 @@ function writePreflightReviewArtifacts(tasks, preflightFailed, route) {
|
|
|
7111
8079
|
const failuresByTask = new Map(preflightFailed.map((failure) => [failure.taskId, failure]));
|
|
7112
8080
|
const siblingTaskIds = preflightFailed.map((failure) => failure.taskId);
|
|
7113
8081
|
for (const t of tasks) {
|
|
7114
|
-
const reviewPath =
|
|
8082
|
+
const reviewPath = path19.join(taskDirFor(t.taskId), "review.md");
|
|
7115
8083
|
let existing = "";
|
|
7116
8084
|
try {
|
|
7117
|
-
existing =
|
|
8085
|
+
existing = fs21.readFileSync(reviewPath, "utf8");
|
|
7118
8086
|
} catch {
|
|
7119
8087
|
}
|
|
7120
8088
|
const hasH2Stage1 = /^## Stage 1\b/m.test(existing);
|
|
@@ -7130,7 +8098,7 @@ function writePreflightReviewArtifacts(tasks, preflightFailed, route) {
|
|
|
7130
8098
|
${blockedBlock}` : `# Code Review: ${t.taskId}
|
|
7131
8099
|
|
|
7132
8100
|
${blockedBlock}`;
|
|
7133
|
-
|
|
8101
|
+
fs21.writeFileSync(reviewPath, reviewContent2, "utf8");
|
|
7134
8102
|
continue;
|
|
7135
8103
|
}
|
|
7136
8104
|
const currentPreflight = t.status.phases.code_review?.preflight_rejections_current_loop ?? 0;
|
|
@@ -7141,7 +8109,7 @@ ${blockedBlock}`;
|
|
|
7141
8109
|
---
|
|
7142
8110
|
|
|
7143
8111
|
${stub}` : stub;
|
|
7144
|
-
|
|
8112
|
+
fs21.writeFileSync(reviewPath, reviewContent, "utf8");
|
|
7145
8113
|
}
|
|
7146
8114
|
return true;
|
|
7147
8115
|
}
|
|
@@ -7268,8 +8236,8 @@ Add them to the affected task spec's ### Affected Files table in the active chec
|
|
|
7268
8236
|
});
|
|
7269
8237
|
}
|
|
7270
8238
|
for (const t of tasks) {
|
|
7271
|
-
|
|
7272
|
-
|
|
8239
|
+
fs21.writeFileSync(
|
|
8240
|
+
path19.join(taskDirFor(t.taskId), "review-cold-codex.md"),
|
|
7273
8241
|
coldReview.findings,
|
|
7274
8242
|
"utf8"
|
|
7275
8243
|
);
|
|
@@ -7287,7 +8255,7 @@ Add them to the affected task spec's ### Affected Files table in the active chec
|
|
|
7287
8255
|
info(`\u2192 cold-codex review (${taskIds.join(", ")}): ${Math.round(coldReviewDurationMs / 1e3)}s`);
|
|
7288
8256
|
} else {
|
|
7289
8257
|
for (const t of tasks) {
|
|
7290
|
-
|
|
8258
|
+
fs21.rmSync(path19.join(taskDirFor(t.taskId), "review-cold-codex.md"), { force: true });
|
|
7291
8259
|
deps.writeRoundRecord(taskDirFor(t.taskId), {
|
|
7292
8260
|
round: roundN,
|
|
7293
8261
|
reviewedSha: headSha,
|
|
@@ -7307,10 +8275,10 @@ Add them to the affected task spec's ### Affected Files table in the active chec
|
|
|
7307
8275
|
activeCwd
|
|
7308
8276
|
}, cwd: activeCwd });
|
|
7309
8277
|
for (const t of tasks) {
|
|
7310
|
-
const reviewPath =
|
|
8278
|
+
const reviewPath = path19.join(taskDirFor(t.taskId), "review.md");
|
|
7311
8279
|
let reviewContent = null;
|
|
7312
8280
|
try {
|
|
7313
|
-
reviewContent =
|
|
8281
|
+
reviewContent = fs21.readFileSync(reviewPath, "utf8");
|
|
7314
8282
|
} catch {
|
|
7315
8283
|
}
|
|
7316
8284
|
if (isTemplateUnfilled(reviewContent)) {
|
|
@@ -7419,8 +8387,8 @@ async function runImplementPhase(state, interactive, resumeId, force = false) {
|
|
|
7419
8387
|
}
|
|
7420
8388
|
|
|
7421
8389
|
// src/orchestrator/phases/plan.ts
|
|
7422
|
-
import
|
|
7423
|
-
import
|
|
8390
|
+
import fs22 from "fs";
|
|
8391
|
+
import path20 from "path";
|
|
7424
8392
|
async function runPlanPhase(state, interactive, force = false) {
|
|
7425
8393
|
const { tasks } = state;
|
|
7426
8394
|
const taskIds = tasks.map((t) => t.taskId);
|
|
@@ -7444,10 +8412,10 @@ async function runPlanPhase(state, interactive, force = false) {
|
|
|
7444
8412
|
activeCwd
|
|
7445
8413
|
}, cwd: activeCwd });
|
|
7446
8414
|
for (const t of tasks) {
|
|
7447
|
-
const planPath =
|
|
8415
|
+
const planPath = path20.join(taskDirFor(t.taskId), "plan.md");
|
|
7448
8416
|
let planContent = null;
|
|
7449
8417
|
try {
|
|
7450
|
-
planContent =
|
|
8418
|
+
planContent = fs22.readFileSync(planPath, "utf8");
|
|
7451
8419
|
} catch {
|
|
7452
8420
|
}
|
|
7453
8421
|
if (isTemplateUnfilled(planContent)) {
|
|
@@ -7459,8 +8427,8 @@ async function runPlanPhase(state, interactive, force = false) {
|
|
|
7459
8427
|
}
|
|
7460
8428
|
|
|
7461
8429
|
// src/orchestrator/phases/qa.ts
|
|
7462
|
-
import
|
|
7463
|
-
import
|
|
8430
|
+
import fs23 from "fs";
|
|
8431
|
+
import path21 from "path";
|
|
7464
8432
|
function resolveQaDocsFreshness(taskIds, activeCwd, deps = { getBaseBranch, getAffectedFiles }) {
|
|
7465
8433
|
const config3 = requireDocsFreshnessConfig(activeCwd);
|
|
7466
8434
|
const base = deps.getBaseBranch(taskIds);
|
|
@@ -7485,11 +8453,11 @@ async function runQaPhase(state, interactive, resolvedPrTemplate) {
|
|
|
7485
8453
|
}, cwd: activeCwd });
|
|
7486
8454
|
if (!state.isBundle && (result.text || result.capturedStdout)) {
|
|
7487
8455
|
const taskId = taskIds[0];
|
|
7488
|
-
const donePath =
|
|
8456
|
+
const donePath = path21.join(activeCwd, "tasks", taskId, "done.md");
|
|
7489
8457
|
if (isDoneMdTemplate(donePath)) {
|
|
7490
8458
|
const salvaged = extractDoneMdFromStdout(result.text) || extractDoneMdFromStdout(result.capturedStdout);
|
|
7491
8459
|
if (salvaged) {
|
|
7492
|
-
|
|
8460
|
+
fs23.writeFileSync(donePath, salvaged);
|
|
7493
8461
|
warn(`Salvaged tasks/${taskId}/done.md from captured stdout \u2014 QA sub-agent streamed content instead of using the Write tool.`);
|
|
7494
8462
|
const phaseStatus = readStatus(taskId).phases.qa?.status ?? "pending";
|
|
7495
8463
|
if (phaseStatus === "blocked") {
|
|
@@ -7543,16 +8511,16 @@ async function runSpecPhase(state, interactive, resumeId) {
|
|
|
7543
8511
|
}
|
|
7544
8512
|
|
|
7545
8513
|
// src/orchestrator/phases/spec-review.ts
|
|
7546
|
-
import
|
|
7547
|
-
import
|
|
8514
|
+
import fs24 from "fs";
|
|
8515
|
+
import path22 from "path";
|
|
7548
8516
|
function autoBlockSpecReview(taskIds, iterationCount, reason) {
|
|
7549
8517
|
autoBlockPhase(taskIds, "spec_review", iterationCount, reason);
|
|
7550
8518
|
}
|
|
7551
8519
|
function recordFastTierSpecApproval(taskId, reviewer) {
|
|
7552
|
-
const artifactPath =
|
|
8520
|
+
const artifactPath = path22.join(taskDirFor(taskId), "spec-review.md");
|
|
7553
8521
|
let content;
|
|
7554
8522
|
try {
|
|
7555
|
-
content =
|
|
8523
|
+
content = fs24.readFileSync(artifactPath, "utf8");
|
|
7556
8524
|
} catch {
|
|
7557
8525
|
return;
|
|
7558
8526
|
}
|
|
@@ -7561,7 +8529,7 @@ function recordFastTierSpecApproval(taskId, reviewer) {
|
|
|
7561
8529
|
const note = `
|
|
7562
8530
|
> Fast tier: ${reviewer} spec review skipped \u2014 human conversational spec approval recorded by the orchestrator.
|
|
7563
8531
|
`;
|
|
7564
|
-
|
|
8532
|
+
fs24.writeFileSync(
|
|
7565
8533
|
artifactPath,
|
|
7566
8534
|
(checked !== content ? checked : `${content}
|
|
7567
8535
|
## Verdict
|
|
@@ -7631,10 +8599,10 @@ ${promptSpecReview(state)}` : promptSpecReview(state);
|
|
|
7631
8599
|
activeCwd
|
|
7632
8600
|
}, cwd: activeCwd });
|
|
7633
8601
|
for (const t of tasks) {
|
|
7634
|
-
const reviewPath =
|
|
8602
|
+
const reviewPath = path22.join(resolveTaskCwd(t.taskId), "tasks", t.taskId, "spec-review.md");
|
|
7635
8603
|
let reviewContent = null;
|
|
7636
8604
|
try {
|
|
7637
|
-
reviewContent =
|
|
8605
|
+
reviewContent = fs24.readFileSync(reviewPath, "utf8");
|
|
7638
8606
|
} catch {
|
|
7639
8607
|
}
|
|
7640
8608
|
if (isTemplateUnfilled(reviewContent)) {
|
|
@@ -7647,8 +8615,8 @@ ${promptSpecReview(state)}` : promptSpecReview(state);
|
|
|
7647
8615
|
|
|
7648
8616
|
// src/orchestrator/detach.ts
|
|
7649
8617
|
import { spawn as spawn3 } from "child_process";
|
|
7650
|
-
import
|
|
7651
|
-
import
|
|
8618
|
+
import fs25 from "fs";
|
|
8619
|
+
import path23 from "path";
|
|
7652
8620
|
var DETACH_CHILD_FLAG = "CANON_DETACHED";
|
|
7653
8621
|
var DETACH_DISABLE_FLAG = "CANON_NO_DETACH";
|
|
7654
8622
|
var PID_FILENAME = ".canon-pid";
|
|
@@ -7684,16 +8652,16 @@ function detachAndExit(options) {
|
|
|
7684
8652
|
}
|
|
7685
8653
|
const primaryDir = options.resolveTaskDir(options.taskIds[0]);
|
|
7686
8654
|
try {
|
|
7687
|
-
|
|
8655
|
+
fs25.mkdirSync(primaryDir, { recursive: true });
|
|
7688
8656
|
} catch (error) {
|
|
7689
8657
|
stderrWrite(`canon: cannot create task dir for log file: ${error.message}
|
|
7690
8658
|
`);
|
|
7691
8659
|
return exit(1);
|
|
7692
8660
|
}
|
|
7693
|
-
const logPath =
|
|
8661
|
+
const logPath = path23.join(primaryDir, LOG_FILENAME);
|
|
7694
8662
|
let logFd;
|
|
7695
8663
|
try {
|
|
7696
|
-
logFd =
|
|
8664
|
+
logFd = fs25.openSync(logPath, "a");
|
|
7697
8665
|
} catch (error) {
|
|
7698
8666
|
stderrWrite(`canon: cannot open ${logPath}: ${error.message}
|
|
7699
8667
|
`);
|
|
@@ -7706,7 +8674,7 @@ function detachAndExit(options) {
|
|
|
7706
8674
|
env: { ...process.env, [DETACH_CHILD_FLAG]: "1" }
|
|
7707
8675
|
});
|
|
7708
8676
|
try {
|
|
7709
|
-
|
|
8677
|
+
fs25.closeSync(logFd);
|
|
7710
8678
|
} catch {
|
|
7711
8679
|
}
|
|
7712
8680
|
if (child.pid == null) {
|
|
@@ -7717,8 +8685,8 @@ function detachAndExit(options) {
|
|
|
7717
8685
|
for (const taskId of options.taskIds) {
|
|
7718
8686
|
try {
|
|
7719
8687
|
const dir = options.resolveTaskDir(taskId);
|
|
7720
|
-
|
|
7721
|
-
|
|
8688
|
+
fs25.mkdirSync(dir, { recursive: true });
|
|
8689
|
+
fs25.writeFileSync(path23.join(dir, PID_FILENAME), `${child.pid}
|
|
7722
8690
|
`, "utf8");
|
|
7723
8691
|
} catch (error) {
|
|
7724
8692
|
pidWriteFailures.push({
|
|
@@ -7772,9 +8740,9 @@ ${rule}
|
|
|
7772
8740
|
return exit(0);
|
|
7773
8741
|
}
|
|
7774
8742
|
function readCanonPid(taskDir) {
|
|
7775
|
-
const file =
|
|
8743
|
+
const file = path23.join(taskDir, PID_FILENAME);
|
|
7776
8744
|
try {
|
|
7777
|
-
const raw =
|
|
8745
|
+
const raw = fs25.readFileSync(file, "utf8").trim();
|
|
7778
8746
|
const pid = Number.parseInt(raw, 10);
|
|
7779
8747
|
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
7780
8748
|
} catch {
|
|
@@ -7783,14 +8751,14 @@ function readCanonPid(taskDir) {
|
|
|
7783
8751
|
}
|
|
7784
8752
|
function removeCanonPid(taskDir) {
|
|
7785
8753
|
try {
|
|
7786
|
-
|
|
8754
|
+
fs25.unlinkSync(path23.join(taskDir, PID_FILENAME));
|
|
7787
8755
|
} catch {
|
|
7788
8756
|
}
|
|
7789
8757
|
}
|
|
7790
8758
|
|
|
7791
8759
|
// src/orchestrator/telemetry-fold.ts
|
|
7792
|
-
import
|
|
7793
|
-
import
|
|
8760
|
+
import fs26 from "fs";
|
|
8761
|
+
import path24 from "path";
|
|
7794
8762
|
import { randomUUID } from "crypto";
|
|
7795
8763
|
var LESSONS_SKELETON = "# Lessons Learned\n\n> Distilled cross-task insights. Task lessons fragments are folded here by `canon run --ship`.\n";
|
|
7796
8764
|
var METRICS_HEADER = /^\|\s*Timestamp\s*\|/;
|
|
@@ -7825,7 +8793,7 @@ function sharedTelemetryDocsTouched(paths) {
|
|
|
7825
8793
|
}
|
|
7826
8794
|
function readOptional(file) {
|
|
7827
8795
|
try {
|
|
7828
|
-
return
|
|
8796
|
+
return fs26.readFileSync(file, "utf8");
|
|
7829
8797
|
} catch (error) {
|
|
7830
8798
|
if (error.code === "ENOENT") return null;
|
|
7831
8799
|
throw error;
|
|
@@ -7834,15 +8802,15 @@ function readOptional(file) {
|
|
|
7834
8802
|
function planTelemetryFold(repoRoot, taskIds, taskDirFor3) {
|
|
7835
8803
|
const kinds = [
|
|
7836
8804
|
{ name: "metrics.md", target: getSharedMetricsFile(repoRoot), fold: foldMetricsFragment },
|
|
7837
|
-
{ name: "quality-log.md", target:
|
|
7838
|
-
{ name: "lessons.md", target:
|
|
8805
|
+
{ name: "quality-log.md", target: path24.join(repoRoot, "docs/task-quality-log.md"), fold: foldQualityLogFragment },
|
|
8806
|
+
{ name: "lessons.md", target: path24.join(repoRoot, "docs/lessons-learned.md"), fold: foldLessonsFragment }
|
|
7839
8807
|
];
|
|
7840
8808
|
const before = new Map(kinds.map((kind) => [kind.target, readOptional(kind.target)]));
|
|
7841
8809
|
const contents = new Map(before);
|
|
7842
8810
|
const fragments = [];
|
|
7843
8811
|
for (const taskId of taskIds) {
|
|
7844
8812
|
for (const kind of kinds) {
|
|
7845
|
-
const fragmentPath =
|
|
8813
|
+
const fragmentPath = path24.join(taskDirFor3(taskId), kind.name);
|
|
7846
8814
|
const content = readOptional(fragmentPath);
|
|
7847
8815
|
if (content === null) continue;
|
|
7848
8816
|
fragments.push({ path: fragmentPath, content });
|
|
@@ -7865,22 +8833,22 @@ function applyTelemetryFold(plan) {
|
|
|
7865
8833
|
const deleted = [];
|
|
7866
8834
|
try {
|
|
7867
8835
|
for (const write of plan.writes) {
|
|
7868
|
-
|
|
8836
|
+
fs26.mkdirSync(path24.dirname(write.target), { recursive: true });
|
|
7869
8837
|
const temp = `${write.target}.${randomUUID()}.canon-fold.tmp`;
|
|
7870
|
-
const fd =
|
|
8838
|
+
const fd = fs26.openSync(temp, "wx");
|
|
7871
8839
|
temps.push(temp);
|
|
7872
8840
|
try {
|
|
7873
|
-
|
|
8841
|
+
fs26.writeFileSync(fd, write.after, "utf8");
|
|
7874
8842
|
} finally {
|
|
7875
|
-
|
|
8843
|
+
fs26.closeSync(fd);
|
|
7876
8844
|
}
|
|
7877
8845
|
}
|
|
7878
8846
|
for (let index = 0; index < plan.writes.length; index += 1) {
|
|
7879
|
-
|
|
8847
|
+
fs26.renameSync(temps[index], plan.writes[index].target);
|
|
7880
8848
|
written.push(plan.writes[index]);
|
|
7881
8849
|
}
|
|
7882
8850
|
for (const fragment of plan.fragments) {
|
|
7883
|
-
|
|
8851
|
+
fs26.unlinkSync(fragment.path);
|
|
7884
8852
|
deleted.push(fragment);
|
|
7885
8853
|
}
|
|
7886
8854
|
} catch (error) {
|
|
@@ -7894,17 +8862,17 @@ function applyTelemetryFold(plan) {
|
|
|
7894
8862
|
};
|
|
7895
8863
|
for (const write of written.reverse()) {
|
|
7896
8864
|
restore(() => {
|
|
7897
|
-
if (write.before === null)
|
|
7898
|
-
else
|
|
8865
|
+
if (write.before === null) fs26.unlinkSync(write.target);
|
|
8866
|
+
else fs26.writeFileSync(write.target, write.before, "utf8");
|
|
7899
8867
|
});
|
|
7900
8868
|
}
|
|
7901
|
-
for (const fragment of deleted) restore(() =>
|
|
8869
|
+
for (const fragment of deleted) restore(() => fs26.writeFileSync(fragment.path, fragment.content, "utf8"));
|
|
7902
8870
|
if (rollbackErrors.length) throw new Error(`${String(error)}; rollback failed: ${rollbackErrors.join("; ")}`);
|
|
7903
8871
|
throw error;
|
|
7904
8872
|
} finally {
|
|
7905
8873
|
for (const temp of temps) {
|
|
7906
8874
|
try {
|
|
7907
|
-
|
|
8875
|
+
fs26.unlinkSync(temp);
|
|
7908
8876
|
} catch {
|
|
7909
8877
|
}
|
|
7910
8878
|
}
|
|
@@ -7913,7 +8881,7 @@ function applyTelemetryFold(plan) {
|
|
|
7913
8881
|
function foldTelemetryFragments(repoRoot, taskIds, taskDirFor3) {
|
|
7914
8882
|
const plan = planTelemetryFold(repoRoot, taskIds, taskDirFor3);
|
|
7915
8883
|
applyTelemetryFold(plan);
|
|
7916
|
-
return plan.writes.map((write) =>
|
|
8884
|
+
return plan.writes.map((write) => path24.relative(repoRoot, write.target));
|
|
7917
8885
|
}
|
|
7918
8886
|
function formatPostFoldFailureHint(foldedDocs, state, baseBranch) {
|
|
7919
8887
|
const location = state === "uncommitted" ? "as uncommitted (possibly staged) edits in the working tree. Do not reset or check out those docs." : `in the local chore: archive commit on ${baseBranch}, which was not pushed. Do not reset the local ${baseBranch} branch.`;
|
|
@@ -8099,21 +9067,21 @@ function backupIndexFile(cwd) {
|
|
|
8099
9067
|
const source = indexPath.stdout.trim();
|
|
8100
9068
|
const backup = `${source}.canon-autocommit-backup`;
|
|
8101
9069
|
try {
|
|
8102
|
-
|
|
9070
|
+
fs27.copyFileSync(source, backup);
|
|
8103
9071
|
} catch {
|
|
8104
9072
|
return null;
|
|
8105
9073
|
}
|
|
8106
9074
|
return {
|
|
8107
9075
|
restore() {
|
|
8108
9076
|
try {
|
|
8109
|
-
|
|
9077
|
+
fs27.renameSync(backup, source);
|
|
8110
9078
|
return true;
|
|
8111
9079
|
} catch {
|
|
8112
9080
|
return false;
|
|
8113
9081
|
}
|
|
8114
9082
|
},
|
|
8115
9083
|
discard() {
|
|
8116
|
-
|
|
9084
|
+
fs27.rmSync(backup, { force: true });
|
|
8117
9085
|
}
|
|
8118
9086
|
};
|
|
8119
9087
|
}
|
|
@@ -8225,13 +9193,13 @@ function snapshotOutsideArtifacts(cwd, taskIds) {
|
|
|
8225
9193
|
snap.set("[git HEAD]", head.stdout.trim());
|
|
8226
9194
|
try {
|
|
8227
9195
|
for (const [filePath, xy] of statusByPath) {
|
|
8228
|
-
const absolute =
|
|
9196
|
+
const absolute = path25.join(cwd, filePath);
|
|
8229
9197
|
let fingerprint;
|
|
8230
9198
|
try {
|
|
8231
|
-
const stat =
|
|
8232
|
-
if (stat.isSymbolicLink()) fingerprint = `symlink:${
|
|
9199
|
+
const stat = fs27.lstatSync(absolute);
|
|
9200
|
+
if (stat.isSymbolicLink()) fingerprint = `symlink:${fs27.readlinkSync(absolute)}`;
|
|
8233
9201
|
else if (stat.isDirectory()) fingerprint = "dir";
|
|
8234
|
-
else if (stat.isFile()) fingerprint = createHash("sha256").update(
|
|
9202
|
+
else if (stat.isFile()) fingerprint = createHash("sha256").update(fs27.readFileSync(absolute)).digest("hex");
|
|
8235
9203
|
else fingerprint = `other:${stat.mode}`;
|
|
8236
9204
|
} catch (error) {
|
|
8237
9205
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -8262,7 +9230,7 @@ function fixupTaskContexts(taskIds) {
|
|
|
8262
9230
|
}
|
|
8263
9231
|
async function fixUpOwnArtifactRefs(opts) {
|
|
8264
9232
|
const artifacts = opts.taskIds.flatMap((taskId) => opts.artifactNames.map((name) => `tasks/${taskId}/${name}`));
|
|
8265
|
-
const checkerPath =
|
|
9233
|
+
const checkerPath = path25.join(REPO_ROOT2, "scripts", "docs-refs-check.mjs");
|
|
8266
9234
|
const consequence = opts.phase === "implement" ? "Committing as before; the --pr docs-refs gate will stop on these findings, and a pre-commit hook may also reject the commit." : "Fix them before --pr; its docs-refs gate will stop on them.";
|
|
8267
9235
|
const runCheck = () => runDocsRefsCheck(opts.cwd, checkerPath);
|
|
8268
9236
|
const filter = (result) => result.kind === "findings" ? filterArtifactFindings(result.findings, artifacts) : [];
|
|
@@ -8276,7 +9244,8 @@ ${initial.output}`);
|
|
|
8276
9244
|
let own = filter(initial);
|
|
8277
9245
|
if (own.length === 0) return;
|
|
8278
9246
|
if (!opts.sessionId) {
|
|
8279
|
-
const
|
|
9247
|
+
const role = opts.phase === "implement" ? "implementer" : opts.phase === "qa" ? "qa" : "reviewer";
|
|
9248
|
+
const agent = roleBackendId(role, assignmentForTasks(opts.taskIds));
|
|
8280
9249
|
warn2(`docs-refs-check found broken references in the ${opts.phase} artifacts, but no ${agent} session is available to fix them:
|
|
8281
9250
|
${own.map((f) => f.raw).join("\n")}
|
|
8282
9251
|
${consequence}`);
|
|
@@ -8308,13 +9277,17 @@ ${consequence}`);
|
|
|
8308
9277
|
}
|
|
8309
9278
|
const post = snapshotOutsideArtifacts(opts.cwd, opts.taskIds);
|
|
8310
9279
|
if (!post.ok) {
|
|
8311
|
-
|
|
9280
|
+
const cause = `Artifact fix-up stopped the run: could not inspect the working tree after the fix session (${post.error})`;
|
|
9281
|
+
if (opts.onStop) opts.onStop(cause);
|
|
9282
|
+
die2(`${cause}. Nothing was committed; inspect the tree before re-running.`);
|
|
8312
9283
|
return;
|
|
8313
9284
|
}
|
|
8314
9285
|
const changed = diffScopeSnapshots(pre.snap, post.snap, exempt);
|
|
8315
9286
|
if (changed.length > 0) {
|
|
8316
|
-
|
|
8317
|
-
${changed.map((file) => ` ${file}`).join("\n")}
|
|
9287
|
+
const cause = `Artifact fix-up stopped the run: the ${opts.phase} fix session changed files outside its own artifacts:
|
|
9288
|
+
${changed.map((file) => ` ${file}`).join("\n")}`;
|
|
9289
|
+
if (opts.onStop) opts.onStop(cause);
|
|
9290
|
+
die2(`${cause}
|
|
8318
9291
|
Nothing was committed. Review and revert those changes, then re-run canon run ${opts.taskIds.join(" ")}.`);
|
|
8319
9292
|
}
|
|
8320
9293
|
if (!ok) {
|
|
@@ -8340,6 +9313,63 @@ ${checked.output}`);
|
|
|
8340
9313
|
${own.map((f) => f.raw).join("\n")}
|
|
8341
9314
|
${consequence}`);
|
|
8342
9315
|
}
|
|
9316
|
+
function stopReviewFixup(taskIds, cause) {
|
|
9317
|
+
const recovery = codeReviewResetCommands(taskIds);
|
|
9318
|
+
const reason = `${cause}
|
|
9319
|
+
Code review is auto-blocked for the full task set. Recover with: ${recovery}; then canon run ${taskIds.join(" ")}.`;
|
|
9320
|
+
warn2(reason);
|
|
9321
|
+
autoBlockPhase(taskIds, "code_review", phaseIterationCount(taskIds, "code_review"), reason);
|
|
9322
|
+
setExitReason(reason);
|
|
9323
|
+
process.exit(2);
|
|
9324
|
+
}
|
|
9325
|
+
async function fixUpReviewArtifactRefs(taskIds, cwd, sessionId) {
|
|
9326
|
+
if (!taskIds.every((taskId) => getPhaseStatus(readStatus(taskId), "code_review") === "done")) return;
|
|
9327
|
+
const assignment = assignmentForTasks(taskIds);
|
|
9328
|
+
const reviewer = agentBackendFor("reviewer", assignment);
|
|
9329
|
+
const checkVerdicts = () => {
|
|
9330
|
+
for (const taskId of taskIds) {
|
|
9331
|
+
let content = null;
|
|
9332
|
+
try {
|
|
9333
|
+
content = fs27.readFileSync(path25.join(taskDirFor2(taskId), "review.md"), "utf8");
|
|
9334
|
+
} catch {
|
|
9335
|
+
}
|
|
9336
|
+
const checked = content === null ? null : extractCheckedVerdict(content);
|
|
9337
|
+
const recorded = getVerdict(readStatus(taskId), "code_review");
|
|
9338
|
+
if (checked !== recorded) {
|
|
9339
|
+
stopReviewFixup(
|
|
9340
|
+
taskIds,
|
|
9341
|
+
`Artifact fix-up verdict guard failed for task '${taskId}': checked verdict '${checked ?? "none"}' in review.md differs from recorded verdict '${recorded || "none"}'.`
|
|
9342
|
+
);
|
|
9343
|
+
}
|
|
9344
|
+
}
|
|
9345
|
+
};
|
|
9346
|
+
await fixUpOwnArtifactRefs({
|
|
9347
|
+
phase: "code_review",
|
|
9348
|
+
taskIds,
|
|
9349
|
+
cwd,
|
|
9350
|
+
sessionId,
|
|
9351
|
+
artifactNames: ["review.md"],
|
|
9352
|
+
onStop: (cause) => stopReviewFixup(taskIds, cause),
|
|
9353
|
+
runSession: async (prompt) => {
|
|
9354
|
+
try {
|
|
9355
|
+
const result = await reviewer.run({
|
|
9356
|
+
role: "reviewer",
|
|
9357
|
+
phase: "code_review",
|
|
9358
|
+
tasks: fixupTaskContexts(taskIds),
|
|
9359
|
+
prompt,
|
|
9360
|
+
interactive: false,
|
|
9361
|
+
resumeId: sessionId,
|
|
9362
|
+
metricsContext: { taskId: taskIds[0], phase: "code_review_fixup", activeCwd: cwd },
|
|
9363
|
+
cwd,
|
|
9364
|
+
wrapForResume: false
|
|
9365
|
+
});
|
|
9366
|
+
return result.exitCode === 0;
|
|
9367
|
+
} finally {
|
|
9368
|
+
checkVerdicts();
|
|
9369
|
+
}
|
|
9370
|
+
}
|
|
9371
|
+
});
|
|
9372
|
+
}
|
|
8343
9373
|
async function fixUpImplementArtifactRefs(taskIds, cwd) {
|
|
8344
9374
|
if (operatorAcceptedImplement(taskIds, cwd)) return;
|
|
8345
9375
|
const sessionId = usableSessionId(taskIds, "implementer", assignmentForTasks(taskIds));
|
|
@@ -8447,7 +9477,7 @@ function autoCommitCode(taskIds, cwd = REPO_ROOT2) {
|
|
|
8447
9477
|
if (dirtyFiles.has(f)) continue;
|
|
8448
9478
|
if (gitIgnoredHandoffFiles.has(f)) continue;
|
|
8449
9479
|
if (ownedArtifacts.has(f)) continue;
|
|
8450
|
-
const exists =
|
|
9480
|
+
const exists = fs27.existsSync(path25.join(cwd, f));
|
|
8451
9481
|
if (!exists) {
|
|
8452
9482
|
const committed = gitSafeAt(cwd, "log", "--format=%H", "--max-count=1", `${baseRefForLog}..HEAD`, "--", f);
|
|
8453
9483
|
if (committed.ok && committed.stdout.trim()) {
|
|
@@ -8605,30 +9635,30 @@ function exemptNodeModulesPath(entry, cwd, resolvedWorkspaceDirs) {
|
|
|
8605
9635
|
if (entryPath === null) return null;
|
|
8606
9636
|
if (matchesPorcelainPath(entryPath, "node_modules")) {
|
|
8607
9637
|
return probeNodeModulesEntry(
|
|
8608
|
-
|
|
8609
|
-
|
|
9638
|
+
path25.join(cwd, entryPath),
|
|
9639
|
+
path25.join(REPO_ROOT2, entryPath)
|
|
8610
9640
|
).verdict === "verified-symlink" ? "node_modules" : null;
|
|
8611
9641
|
}
|
|
8612
9642
|
if (!isNodeModulesEntryPath(entryPath)) return null;
|
|
8613
9643
|
let cwdReal;
|
|
8614
9644
|
let repoRootReal;
|
|
8615
9645
|
try {
|
|
8616
|
-
cwdReal =
|
|
8617
|
-
repoRootReal =
|
|
9646
|
+
cwdReal = fs27.realpathSync(cwd);
|
|
9647
|
+
repoRootReal = fs27.realpathSync(REPO_ROOT2);
|
|
8618
9648
|
} catch {
|
|
8619
9649
|
return null;
|
|
8620
9650
|
}
|
|
8621
9651
|
if (cwdReal === repoRootReal) return null;
|
|
8622
9652
|
const workspaceDirs = resolvedWorkspaceDirs ?? resolveWorkspaceDirs(REPO_ROOT2);
|
|
8623
9653
|
for (const workspace of workspaceDirs) {
|
|
8624
|
-
const resolvedDestination = resolveContainedPath(
|
|
9654
|
+
const resolvedDestination = resolveContainedPath(path25.join(cwd, workspace), cwd);
|
|
8625
9655
|
if (resolvedDestination === null) continue;
|
|
8626
|
-
const relativeDestination =
|
|
9656
|
+
const relativeDestination = path25.relative(cwdReal, resolvedDestination).split(path25.sep).join("/");
|
|
8627
9657
|
const expectedEntryPath = `${relativeDestination}/node_modules`;
|
|
8628
9658
|
if (!matchesPorcelainPath(entryPath, expectedEntryPath)) continue;
|
|
8629
9659
|
return probeNodeModulesEntry(
|
|
8630
|
-
|
|
8631
|
-
|
|
9660
|
+
path25.join(resolvedDestination, "node_modules"),
|
|
9661
|
+
path25.join(REPO_ROOT2, workspace, "node_modules")
|
|
8632
9662
|
).verdict === "verified-symlink" ? expectedEntryPath : null;
|
|
8633
9663
|
}
|
|
8634
9664
|
return null;
|
|
@@ -8670,15 +9700,15 @@ function buildHumanReviewStagePaths(taskIds, affectedManagedDocs, dirtyEntries,
|
|
|
8670
9700
|
}
|
|
8671
9701
|
function findPullRequestTemplate(repoRoot) {
|
|
8672
9702
|
const candidates = [
|
|
8673
|
-
|
|
8674
|
-
|
|
8675
|
-
|
|
8676
|
-
|
|
8677
|
-
|
|
8678
|
-
|
|
9703
|
+
path25.join(repoRoot, ".github", "pull_request_template.md"),
|
|
9704
|
+
path25.join(repoRoot, ".github", "PULL_REQUEST_TEMPLATE.md"),
|
|
9705
|
+
path25.join(repoRoot, "docs", "pull_request_template.md"),
|
|
9706
|
+
path25.join(repoRoot, "docs", "PULL_REQUEST_TEMPLATE.md"),
|
|
9707
|
+
path25.join(repoRoot, "pull_request_template.md"),
|
|
9708
|
+
path25.join(repoRoot, "PULL_REQUEST_TEMPLATE.md")
|
|
8679
9709
|
];
|
|
8680
9710
|
for (const candidate of candidates) {
|
|
8681
|
-
if (
|
|
9711
|
+
if (fs27.existsSync(candidate)) return candidate;
|
|
8682
9712
|
}
|
|
8683
9713
|
return null;
|
|
8684
9714
|
}
|
|
@@ -8692,13 +9722,13 @@ function resolveQaPrBody(taskIds, activeCwd) {
|
|
|
8692
9722
|
if (taskIds.length !== 1) {
|
|
8693
9723
|
return { kind: "fallback", reason: "bundle: per-task pr-body.md files are not combined in this version" };
|
|
8694
9724
|
}
|
|
8695
|
-
const prBodyPath =
|
|
9725
|
+
const prBodyPath = path25.join(activeCwd, "tasks", taskIds[0], "pr-body.md");
|
|
8696
9726
|
if (!isPrBodyTemplate(prBodyPath)) {
|
|
8697
9727
|
return { kind: "body-file", path: prBodyPath };
|
|
8698
9728
|
}
|
|
8699
9729
|
return {
|
|
8700
9730
|
kind: "fallback",
|
|
8701
|
-
reason:
|
|
9731
|
+
reason: fs27.existsSync(prBodyPath) ? "pr-body.md is still the stub template" : "pr-body.md not found"
|
|
8702
9732
|
};
|
|
8703
9733
|
}
|
|
8704
9734
|
function commitQaArtifacts(taskIds, cwd) {
|
|
@@ -8819,15 +9849,15 @@ function formatExistingPRMessage(prNum, prUrl) {
|
|
|
8819
9849
|
return `Existing draft PR: #${prNum} (${prUrl})`;
|
|
8820
9850
|
}
|
|
8821
9851
|
function sidecarPathFor(taskId, taskDir = taskDirFor2(taskId)) {
|
|
8822
|
-
return
|
|
9852
|
+
return path25.join(taskDir, ".pr-number");
|
|
8823
9853
|
}
|
|
8824
9854
|
function recordPinnedPRNumber(taskIds, prNum) {
|
|
8825
9855
|
const alreadyPinned = taskIds.every((taskId) => readSidecarPRNumber(taskId) === prNum);
|
|
8826
9856
|
if (alreadyPinned) return;
|
|
8827
9857
|
for (const taskId of taskIds) {
|
|
8828
9858
|
const sidecarPath = sidecarPathFor(taskId);
|
|
8829
|
-
|
|
8830
|
-
|
|
9859
|
+
fs27.mkdirSync(path25.dirname(sidecarPath), { recursive: true });
|
|
9860
|
+
fs27.writeFileSync(sidecarPath, String(prNum), "utf8");
|
|
8831
9861
|
}
|
|
8832
9862
|
}
|
|
8833
9863
|
function reportOrCreatePR(taskIds, branchName, cwd) {
|
|
@@ -9075,9 +10105,9 @@ function commitHumanReviewFiles(taskIds, cwd, createPR) {
|
|
|
9075
10105
|
}
|
|
9076
10106
|
const baseBranch = getBaseBranch(taskIds);
|
|
9077
10107
|
pushScaffoldBaseCommits(taskIds, cwd, createPR);
|
|
9078
|
-
const docsRefsScript =
|
|
9079
|
-
if (
|
|
9080
|
-
const docsRefsResult =
|
|
10108
|
+
const docsRefsScript = path25.join(REPO_ROOT2, "scripts", "docs-refs-check.mjs");
|
|
10109
|
+
if (fs27.existsSync(docsRefsScript)) {
|
|
10110
|
+
const docsRefsResult = spawnSync8("node", [docsRefsScript], {
|
|
9081
10111
|
cwd,
|
|
9082
10112
|
stdio: ["ignore", "pipe", "pipe"],
|
|
9083
10113
|
encoding: "utf8"
|
|
@@ -9405,7 +10435,7 @@ function readSidecarPRNumber(taskId, taskDir = taskDirFor2(taskId)) {
|
|
|
9405
10435
|
const sidecarPath = sidecarPathFor(taskId, taskDir);
|
|
9406
10436
|
let raw;
|
|
9407
10437
|
try {
|
|
9408
|
-
raw =
|
|
10438
|
+
raw = fs27.readFileSync(sidecarPath, "utf8").trim();
|
|
9409
10439
|
} catch {
|
|
9410
10440
|
return null;
|
|
9411
10441
|
}
|
|
@@ -9416,7 +10446,7 @@ function readSidecarPRNumber(taskId, taskDir = taskDirFor2(taskId)) {
|
|
|
9416
10446
|
}
|
|
9417
10447
|
function resolveProofPRNumberForPrefetch(taskId, branchName, baseBranch, taskCwd) {
|
|
9418
10448
|
if (!ghAvailable) return null;
|
|
9419
|
-
const pinnedPrNum = readSidecarPRNumber(taskId,
|
|
10449
|
+
const pinnedPrNum = readSidecarPRNumber(taskId, path25.join(taskCwd, "tasks", taskId));
|
|
9420
10450
|
if (pinnedPrNum !== null) return pinnedPrNum;
|
|
9421
10451
|
return findOpenPRNumber(branchName, baseBranch) ?? findMergedPRNumber(branchName, baseBranch);
|
|
9422
10452
|
}
|
|
@@ -9447,7 +10477,7 @@ function establishPRHeadAncestryProof(cwd, prNum, prHead, localTip) {
|
|
|
9447
10477
|
return { proven: true };
|
|
9448
10478
|
}
|
|
9449
10479
|
function establishMergeProof(taskId, branchName, localTip, baseBranch, cwd, prefetchedHeads) {
|
|
9450
|
-
const pinnedPrNum = readSidecarPRNumber(taskId,
|
|
10480
|
+
const pinnedPrNum = readSidecarPRNumber(taskId, path25.join(cwd, "tasks", taskId));
|
|
9451
10481
|
if (ghAvailable && pinnedPrNum !== null) {
|
|
9452
10482
|
if (!isPRMerged(pinnedPrNum)) {
|
|
9453
10483
|
return { proven: false, reason: `Pinned PR #${pinnedPrNum} is not in MERGED state.` };
|
|
@@ -9558,8 +10588,8 @@ function mergeOpenPRsAndPull(taskIds, baseBranch, branchByTaskId, openPRByBranch
|
|
|
9558
10588
|
return { merged: anyMerged };
|
|
9559
10589
|
}
|
|
9560
10590
|
function runPostMergeHook() {
|
|
9561
|
-
const hookPath =
|
|
9562
|
-
if (!
|
|
10591
|
+
const hookPath = path25.join(REPO_ROOT2, ".canon/hooks/post-merge.sh");
|
|
10592
|
+
if (!fs27.existsSync(hookPath)) return;
|
|
9563
10593
|
info2("Running .canon/hooks/post-merge.sh...");
|
|
9564
10594
|
const result = runCommand2("bash", [hookPath]);
|
|
9565
10595
|
if (!result.ok) {
|
|
@@ -9583,12 +10613,12 @@ function commitArchiveChanges(taskIds, baseBranch) {
|
|
|
9583
10613
|
}
|
|
9584
10614
|
function rewriteArchivedTaskRefs(taskIds) {
|
|
9585
10615
|
const targets = [
|
|
9586
|
-
|
|
9587
|
-
|
|
10616
|
+
path25.join(REPO_ROOT2, "docs", "lessons-learned.md"),
|
|
10617
|
+
path25.join(REPO_ROOT2, "docs", "task-quality-log.md")
|
|
9588
10618
|
];
|
|
9589
10619
|
for (const filePath of targets) {
|
|
9590
|
-
if (!
|
|
9591
|
-
let content =
|
|
10620
|
+
if (!fs27.existsSync(filePath)) continue;
|
|
10621
|
+
let content = fs27.readFileSync(filePath, "utf8");
|
|
9592
10622
|
let changed = false;
|
|
9593
10623
|
for (const taskId of taskIds) {
|
|
9594
10624
|
const stale = `tasks/${taskId}/`;
|
|
@@ -9599,8 +10629,8 @@ function rewriteArchivedTaskRefs(taskIds) {
|
|
|
9599
10629
|
}
|
|
9600
10630
|
}
|
|
9601
10631
|
if (changed) {
|
|
9602
|
-
|
|
9603
|
-
info2(`Updated stale task refs in ${
|
|
10632
|
+
fs27.writeFileSync(filePath, content, "utf8");
|
|
10633
|
+
info2(`Updated stale task refs in ${path25.relative(REPO_ROOT2, filePath)}.`);
|
|
9604
10634
|
}
|
|
9605
10635
|
}
|
|
9606
10636
|
}
|
|
@@ -9635,7 +10665,7 @@ function classifyAndPreserveSharedDocDirt() {
|
|
|
9635
10665
|
if (porcelainCode !== " M") {
|
|
9636
10666
|
return { relPath, docClass, porcelainCode, headContent: null, workingContent: null };
|
|
9637
10667
|
}
|
|
9638
|
-
const workingContent =
|
|
10668
|
+
const workingContent = fs27.readFileSync(path25.join(REPO_ROOT2, relPath), "utf8");
|
|
9639
10669
|
const headResult = gitSafeAtRaw(REPO_ROOT2, "show", `HEAD:${relPath}`);
|
|
9640
10670
|
return {
|
|
9641
10671
|
relPath,
|
|
@@ -9652,11 +10682,11 @@ function classifyAndPreserveSharedDocDirt() {
|
|
|
9652
10682
|
}
|
|
9653
10683
|
const preserve = verdict.preserve;
|
|
9654
10684
|
if (preserve.length === 0) return [];
|
|
9655
|
-
const backupDir =
|
|
10685
|
+
const backupDir = fs27.mkdtempSync(path25.join(os.tmpdir(), "canon-ship-shared-doc-backup-"));
|
|
9656
10686
|
const preserved = [];
|
|
9657
10687
|
for (const { relPath, suffix } of preserve) {
|
|
9658
|
-
const backupPath =
|
|
9659
|
-
|
|
10688
|
+
const backupPath = path25.join(backupDir, relPath.replace(/[\\/]/g, "__"));
|
|
10689
|
+
fs27.writeFileSync(backupPath, suffix, "utf8");
|
|
9660
10690
|
info2(`Preserving uncommitted ${relPath} dirt during --ship; backup: ${backupPath}`);
|
|
9661
10691
|
const checkoutResult = gitSafe("checkout", "HEAD", "--", relPath);
|
|
9662
10692
|
if (!checkoutResult.ok) {
|
|
@@ -9670,21 +10700,21 @@ function shipTasks(taskIds, mergeMethod) {
|
|
|
9670
10700
|
const resolveShipCwd = (taskId) => {
|
|
9671
10701
|
const tasksDirOverride2 = process.env.CANON_TASKS_DIR_OVERRIDE;
|
|
9672
10702
|
if (tasksDirOverride2) {
|
|
9673
|
-
return
|
|
10703
|
+
return path25.dirname(tasksDirOverride2);
|
|
9674
10704
|
}
|
|
9675
10705
|
if (isOrphanedWorktreeState(taskId)) return REPO_ROOT2;
|
|
9676
|
-
return
|
|
10706
|
+
return path25.dirname(path25.dirname(taskDirFor2(taskId)));
|
|
9677
10707
|
};
|
|
9678
10708
|
const taskStatuses = /* @__PURE__ */ new Map();
|
|
9679
10709
|
const readShipStatus = (taskId) => {
|
|
9680
10710
|
const taskCwd = resolveShipCwd(taskId);
|
|
9681
10711
|
const candidates = [
|
|
9682
|
-
|
|
9683
|
-
|
|
9684
|
-
|
|
10712
|
+
path25.join(taskCwd, "tasks", taskId, "status.json"),
|
|
10713
|
+
path25.join(taskCwd, taskId, "status.json"),
|
|
10714
|
+
path25.join(taskDirForRepoRoot2(taskId), "status.json")
|
|
9685
10715
|
];
|
|
9686
10716
|
for (const candidate of candidates) {
|
|
9687
|
-
if (
|
|
10717
|
+
if (fs27.existsSync(candidate)) return readStatusFromPath(candidate, taskId);
|
|
9688
10718
|
}
|
|
9689
10719
|
const snapshot = taskStatuses.get(taskId);
|
|
9690
10720
|
if (snapshot) return snapshot;
|
|
@@ -9716,7 +10746,7 @@ function shipTasks(taskIds, mergeMethod) {
|
|
|
9716
10746
|
const currentPhase = getCurrentPhase(readShipStatus(taskId));
|
|
9717
10747
|
if (currentPhase !== "human_review") continue;
|
|
9718
10748
|
const taskCwd = resolveShipCwd(taskId);
|
|
9719
|
-
const tasksRootForGate = process.env.CANON_TASKS_DIR_OVERRIDE ??
|
|
10749
|
+
const tasksRootForGate = process.env.CANON_TASKS_DIR_OVERRIDE ?? path25.join(taskCwd, "tasks");
|
|
9720
10750
|
const gateResult = checkPhaseGate(
|
|
9721
10751
|
taskId,
|
|
9722
10752
|
"human_review",
|
|
@@ -9777,8 +10807,8 @@ function shipTasks(taskIds, mergeMethod) {
|
|
|
9777
10807
|
let preservedSharedDocDirt = [];
|
|
9778
10808
|
const restorePreservedSharedDocDirt = () => {
|
|
9779
10809
|
for (const { relPath, suffix, backupPath } of preservedSharedDocDirt) {
|
|
9780
|
-
|
|
9781
|
-
|
|
10810
|
+
fs27.appendFileSync(path25.join(REPO_ROOT2, relPath), suffix, "utf8");
|
|
10811
|
+
fs27.rmSync(backupPath, { force: true });
|
|
9782
10812
|
info2(`Re-applied preserved ${relPath} dirt as uncommitted changes; backup removed.`);
|
|
9783
10813
|
}
|
|
9784
10814
|
preservedSharedDocDirt = [];
|
|
@@ -9786,7 +10816,7 @@ function shipTasks(taskIds, mergeMethod) {
|
|
|
9786
10816
|
if (taskIds.some((id) => taskSnapshot(id).worktree)) {
|
|
9787
10817
|
preservedSharedDocDirt = classifyAndPreserveSharedDocDirt();
|
|
9788
10818
|
}
|
|
9789
|
-
const orphanedStatusPaths = taskIds.filter((taskId) => taskSnapshot(taskId).worktree && resolveShipCwd(taskId) === REPO_ROOT2).map((taskId) =>
|
|
10819
|
+
const orphanedStatusPaths = taskIds.filter((taskId) => taskSnapshot(taskId).worktree && resolveShipCwd(taskId) === REPO_ROOT2).map((taskId) => path25.join("tasks", taskId, "status.json"));
|
|
9790
10820
|
if (orphanedStatusPaths.length > 0) {
|
|
9791
10821
|
gitSafe("checkout", "HEAD", "--", ...orphanedStatusPaths);
|
|
9792
10822
|
}
|
|
@@ -9832,7 +10862,7 @@ function shipTasks(taskIds, mergeMethod) {
|
|
|
9832
10862
|
try {
|
|
9833
10863
|
restorePreservedSharedDocDirt();
|
|
9834
10864
|
} catch (error) {
|
|
9835
|
-
const backups = preservedSharedDocDirt.map(({ backupPath }) => backupPath).filter((backupPath) =>
|
|
10865
|
+
const backups = preservedSharedDocDirt.map(({ backupPath }) => backupPath).filter((backupPath) => fs27.existsSync(backupPath)).join(", ") || "none";
|
|
9836
10866
|
warn2(`Could not restore the telemetry notes set aside for this --ship (${error instanceof Error ? error.message : String(error)}). Backups that may remain: ${backups}`);
|
|
9837
10867
|
}
|
|
9838
10868
|
die(failureMessage);
|
|
@@ -9882,8 +10912,8 @@ Recovery:
|
|
|
9882
10912
|
}
|
|
9883
10913
|
const localBranchesToDelete = [];
|
|
9884
10914
|
try {
|
|
9885
|
-
const archiveDir =
|
|
9886
|
-
if (!
|
|
10915
|
+
const archiveDir = path25.join(TASKS_DIR2, "_archive");
|
|
10916
|
+
if (!fs27.existsSync(archiveDir)) fs27.mkdirSync(archiveDir, { recursive: true });
|
|
9887
10917
|
for (const taskId of taskIds) {
|
|
9888
10918
|
const { worktree: hasWorktree } = taskSnapshot(taskId);
|
|
9889
10919
|
const status = readShipStatus(taskId);
|
|
@@ -9891,23 +10921,23 @@ Recovery:
|
|
|
9891
10921
|
status.updated = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
9892
10922
|
const humanReview = status.phases.human_review;
|
|
9893
10923
|
if (humanReview) humanReview.status = "done";
|
|
9894
|
-
writeStatusToFile(
|
|
10924
|
+
writeStatusToFile(path25.join(REPO_ROOT2, "tasks", taskId, "status.json"), status);
|
|
9895
10925
|
const src = taskDirForRepoRoot2(taskId);
|
|
9896
|
-
const dest =
|
|
9897
|
-
|
|
10926
|
+
const dest = path25.join(archiveDir, taskId);
|
|
10927
|
+
fs27.renameSync(src, dest);
|
|
9898
10928
|
info2(`\u{1F4E6} ${taskId} \u2192 tasks/_archive/${taskId}`);
|
|
9899
10929
|
const branchName = taskSnapshot(taskId).branch;
|
|
9900
10930
|
if (branchExistsLocally(branchName)) localBranchesToDelete.push(branchName);
|
|
9901
10931
|
}
|
|
9902
10932
|
rewriteArchivedTaskRefs(taskIds);
|
|
9903
10933
|
const stagedPaths = taskIds.flatMap((id) => [
|
|
9904
|
-
|
|
10934
|
+
path25.join(TASKS_DIR2, id),
|
|
9905
10935
|
// deleted source (if not cleaned up)
|
|
9906
|
-
|
|
10936
|
+
path25.join(TASKS_DIR2, "_archive", id),
|
|
9907
10937
|
// new archive destination
|
|
9908
|
-
|
|
9909
|
-
|
|
9910
|
-
|
|
10938
|
+
path25.join(REPO_ROOT2, "docs", "lessons-learned.md"),
|
|
10939
|
+
path25.join(REPO_ROOT2, "docs", "task-quality-log.md"),
|
|
10940
|
+
path25.join(REPO_ROOT2, "docs", "pipeline-invocations.md")
|
|
9911
10941
|
]);
|
|
9912
10942
|
stageArchiveChanges(stagedPaths);
|
|
9913
10943
|
restorePreservedSharedDocDirt();
|
|
@@ -9987,7 +11017,7 @@ function unnamedBranchMates(entries) {
|
|
|
9987
11017
|
const root = process.env.CANON_TASKS_DIR_OVERRIDE ?? TASKS_DIR2;
|
|
9988
11018
|
let candidates;
|
|
9989
11019
|
try {
|
|
9990
|
-
candidates =
|
|
11020
|
+
candidates = fs27.readdirSync(root).sort();
|
|
9991
11021
|
} catch {
|
|
9992
11022
|
return [];
|
|
9993
11023
|
}
|
|
@@ -9996,7 +11026,7 @@ function unnamedBranchMates(entries) {
|
|
|
9996
11026
|
if (named.has(taskId) || taskId === "_archive" || taskId === "_templates") continue;
|
|
9997
11027
|
let status;
|
|
9998
11028
|
try {
|
|
9999
|
-
status = isOrphanedWorktreeState(taskId) ? readStatusFromPath(
|
|
11029
|
+
status = isOrphanedWorktreeState(taskId) ? readStatusFromPath(path25.join(taskDirForRepoRoot(taskId), "status.json"), taskId) : readStatus(taskId);
|
|
10000
11030
|
} catch {
|
|
10001
11031
|
continue;
|
|
10002
11032
|
}
|
|
@@ -10048,7 +11078,7 @@ function rerouteFromHumanReview(taskIds) {
|
|
|
10048
11078
|
if (!result.amended) {
|
|
10049
11079
|
amendmentFailures.push({
|
|
10050
11080
|
taskId,
|
|
10051
|
-
specPath:
|
|
11081
|
+
specPath: path25.join(taskDirFor2(taskId), "spec.md"),
|
|
10052
11082
|
requiredRound,
|
|
10053
11083
|
expectedHeading,
|
|
10054
11084
|
reason: result.reason
|
|
@@ -10104,7 +11134,7 @@ function rerouteFromHumanReview(taskIds) {
|
|
|
10104
11134
|
}
|
|
10105
11135
|
const rescaffold = rescaffoldReview(taskDirFor2(taskId), scaffoldIdentity);
|
|
10106
11136
|
if (rescaffold.outcome === "written") {
|
|
10107
|
-
info(`Re-scaffolded tasks/${taskId}/review.md from ${
|
|
11137
|
+
info(`Re-scaffolded tasks/${taskId}/review.md from ${path25.relative(process.cwd(), rescaffold.source)}.`);
|
|
10108
11138
|
} else if (rescaffold.outcome === "no-template") {
|
|
10109
11139
|
warn2(
|
|
10110
11140
|
`tasks/${taskId}/review.md is missing and no template was found to re-scaffold it (looked for a review.md override under tasks/_templates/ and .canon/templates/review.md). The code-review foreman will have to write the file from scratch.`
|
|
@@ -10233,7 +11263,7 @@ async function runPhase(phase, state) {
|
|
|
10233
11263
|
if (phase === "qa") {
|
|
10234
11264
|
const activeCwd = getActiveCwd(taskIds);
|
|
10235
11265
|
const qaTemplatePath = state.isBundle ? null : findPullRequestTemplate(activeCwd) ?? findPullRequestTemplate(REPO_ROOT2);
|
|
10236
|
-
const resolvedPrTemplate = qaTemplatePath ?
|
|
11266
|
+
const resolvedPrTemplate = qaTemplatePath ? fs27.readFileSync(qaTemplatePath, "utf8") : null;
|
|
10237
11267
|
return runQaPhase(state, cliArgs.interactive, resolvedPrTemplate);
|
|
10238
11268
|
}
|
|
10239
11269
|
if (phase === "human_review") {
|
|
@@ -10247,7 +11277,7 @@ async function runPhase(phase, state) {
|
|
|
10247
11277
|
}
|
|
10248
11278
|
const branch = [...branches][0];
|
|
10249
11279
|
const cwd = getActiveCwd(taskIds2);
|
|
10250
|
-
const tasksRootForGate = process.env.CANON_TASKS_DIR_OVERRIDE ??
|
|
11280
|
+
const tasksRootForGate = process.env.CANON_TASKS_DIR_OVERRIDE ?? path25.join(cwd, "tasks");
|
|
10251
11281
|
for (const taskId of taskIds2) {
|
|
10252
11282
|
const gateResult = checkPhaseGate(taskId, "human_review", void 0, tasksRootForGate);
|
|
10253
11283
|
if (!gateResult.ok) {
|
|
@@ -10314,9 +11344,9 @@ async function runPhase(phase, state) {
|
|
|
10314
11344
|
}
|
|
10315
11345
|
var extractCheckedVerdict2 = extractCheckedVerdict;
|
|
10316
11346
|
function readArtifact(taskId, name) {
|
|
10317
|
-
const p =
|
|
11347
|
+
const p = path25.join(taskDirFor2(taskId), name);
|
|
10318
11348
|
try {
|
|
10319
|
-
return
|
|
11349
|
+
return fs27.readFileSync(p, "utf8");
|
|
10320
11350
|
} catch {
|
|
10321
11351
|
return null;
|
|
10322
11352
|
}
|
|
@@ -10332,15 +11362,15 @@ function checkImplementEvidence(taskId) {
|
|
|
10332
11362
|
return { advanced: false, note: `handoff.md Changes table has malformed row(s): ${sample}${tail}` };
|
|
10333
11363
|
}
|
|
10334
11364
|
const issues = validateHandoffAgainstSpec(
|
|
10335
|
-
|
|
10336
|
-
|
|
11365
|
+
path25.join(taskDirFor2(taskId), "spec.md"),
|
|
11366
|
+
path25.join(taskDirFor2(taskId), "handoff.md")
|
|
10337
11367
|
);
|
|
10338
11368
|
if (issues.length > 0) return { advanced: false, note: `handoff.md validation failed: ${issues.join("; ")}` };
|
|
10339
11369
|
const checkRoots = [REPO_ROOT2];
|
|
10340
11370
|
const sForEvidence = readStatus(taskId);
|
|
10341
11371
|
if (sForEvidence.worktree === true) {
|
|
10342
11372
|
const wt = worktreePath(taskId);
|
|
10343
|
-
if (
|
|
11373
|
+
if (fs27.existsSync(wt)) checkRoots.push(wt);
|
|
10344
11374
|
}
|
|
10345
11375
|
const ignoreCwd = checkRoots[checkRoots.length - 1];
|
|
10346
11376
|
const gitIgnored = filterGitIgnoredPaths(files, ignoreCwd);
|
|
@@ -10352,7 +11382,7 @@ function checkImplementEvidence(taskId) {
|
|
|
10352
11382
|
};
|
|
10353
11383
|
}
|
|
10354
11384
|
const existingFiles = verifiableFiles.filter(
|
|
10355
|
-
(f) => checkRoots.some((root) =>
|
|
11385
|
+
(f) => checkRoots.some((root) => fs27.existsSync(path25.join(root, f)))
|
|
10356
11386
|
);
|
|
10357
11387
|
if (existingFiles.length === 0) {
|
|
10358
11388
|
const evidenceCwd = checkRoots[checkRoots.length - 1];
|
|
@@ -10442,7 +11472,7 @@ function tryEvidenceAdvance(taskId, phase) {
|
|
|
10442
11472
|
return { advanced: true, note: "spec.md is populated" };
|
|
10443
11473
|
}
|
|
10444
11474
|
case "qa": {
|
|
10445
|
-
const donePath =
|
|
11475
|
+
const donePath = path25.join(taskDirFor(taskId), "done.md");
|
|
10446
11476
|
if (isDoneMdTemplate(donePath)) return { advanced: false, note: "done.md is still the template" };
|
|
10447
11477
|
taskPhase(taskId, "qa", "done");
|
|
10448
11478
|
return { advanced: true, note: "done.md is populated" };
|
|
@@ -10556,9 +11586,13 @@ async function withAgentSessionPark(phase, taskIds, run) {
|
|
|
10556
11586
|
parkAgentSessionFailure(phase, taskIds, error);
|
|
10557
11587
|
}
|
|
10558
11588
|
}
|
|
11589
|
+
function codeReviewResetCommands(taskIds) {
|
|
11590
|
+
const recovery = taskIds.map((id) => `canon task reset-code-review ${id}`).join("; ");
|
|
11591
|
+
return recovery;
|
|
11592
|
+
}
|
|
10559
11593
|
function stopForReviewerBlock(taskIds, blockedIds, statuses) {
|
|
10560
11594
|
const maxIter = statuses.reduce((max, status) => Math.max(max, getIterations(status)), 0);
|
|
10561
|
-
const recovery = taskIds
|
|
11595
|
+
const recovery = codeReviewResetCommands(taskIds);
|
|
10562
11596
|
const reason = `Code review stopped without a verdict for task(s): ${blockedIds.join(", ")}. The reviewer set code_review blocked; see ${taskIds.map((id) => `tasks/${id}/review.md`).join(", ")}. No evidence recovery or retry was attempted. Recovery for the full blocked bundle [${taskIds.join(" ")}]: ${recovery}; then canon run ${taskIds.join(" ")}.`;
|
|
10563
11597
|
console.log("");
|
|
10564
11598
|
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");
|
|
@@ -10590,6 +11624,7 @@ async function checkAndRoute(phase, taskIds) {
|
|
|
10590
11624
|
process.exit(2);
|
|
10591
11625
|
}
|
|
10592
11626
|
}
|
|
11627
|
+
let recoveredReview = false;
|
|
10593
11628
|
for (let i = 0; i < taskIds.length; i += 1) {
|
|
10594
11629
|
const phaseStatus = getPhaseStatus(statuses[i], phase);
|
|
10595
11630
|
if (phase === "implement" && phaseStatus === "done") {
|
|
@@ -10620,6 +11655,7 @@ async function checkAndRoute(phase, taskIds) {
|
|
|
10620
11655
|
process.exit(2);
|
|
10621
11656
|
}
|
|
10622
11657
|
const recovered = await recoverPhaseForTask(taskIds[i], phase, phaseStatus);
|
|
11658
|
+
if (phase === "code_review" && recovered) recoveredReview = true;
|
|
10623
11659
|
if (!recovered) {
|
|
10624
11660
|
warn2(`Phase '${phase}' did not reach 'done' for '${taskIds[i]}'. Stopping for human review.`);
|
|
10625
11661
|
process.exit(2);
|
|
@@ -10627,6 +11663,11 @@ async function checkAndRoute(phase, taskIds) {
|
|
|
10627
11663
|
}
|
|
10628
11664
|
}
|
|
10629
11665
|
statuses = taskIds.map(readStatus);
|
|
11666
|
+
if (phase === "code_review" && recoveredReview) {
|
|
11667
|
+
const sessionId = cliArgs.interactive ? null : usableSessionId(taskIds, "reviewer", assignmentForTasks(taskIds));
|
|
11668
|
+
await fixUpReviewArtifactRefs(taskIds, getActiveCwd(taskIds), sessionId);
|
|
11669
|
+
statuses = taskIds.map(readStatus);
|
|
11670
|
+
}
|
|
10630
11671
|
let specGapScopeFiles = [];
|
|
10631
11672
|
let specGapScopeError = null;
|
|
10632
11673
|
if (phase === "code_review" && statuses.every((status) => status.full_send === true)) {
|
|
@@ -10837,7 +11878,7 @@ Scope was not checked. Fix the base branch or repository history before choosing
|
|
|
10837
11878
|
function checkDeps(taskIds, skipAgentDeps = false) {
|
|
10838
11879
|
if (!skipAgentDeps) {
|
|
10839
11880
|
for (const dep of requiredAgentBackends(assignmentForTasks(taskIds))) {
|
|
10840
|
-
const result =
|
|
11881
|
+
const result = spawnSync8("which", [dep], { stdio: "ignore" });
|
|
10841
11882
|
if (result.error || result.status !== 0) {
|
|
10842
11883
|
const label = dep === "claude" ? "Claude Code CLI" : dep === "codex" ? "Codex CLI" : dep;
|
|
10843
11884
|
die(`${label} is required`);
|
|
@@ -10850,9 +11891,9 @@ function checkDeps(taskIds, skipAgentDeps = false) {
|
|
|
10850
11891
|
}
|
|
10851
11892
|
for (const taskId of taskIds) {
|
|
10852
11893
|
validateTaskId(taskId);
|
|
10853
|
-
const repoRootStatusFile =
|
|
10854
|
-
const statusFile = cliArgs.ship &&
|
|
10855
|
-
if (!
|
|
11894
|
+
const repoRootStatusFile = path25.join(REPO_ROOT2, "tasks", taskId, "status.json");
|
|
11895
|
+
const statusFile = cliArgs.ship && fs27.existsSync(repoRootStatusFile) ? repoRootStatusFile : statusFileFor(taskId);
|
|
11896
|
+
if (!fs27.existsSync(statusFile)) {
|
|
10856
11897
|
die(`No status.json at tasks/${taskId}/status.json \u2014 run canon task new ${taskId} first`);
|
|
10857
11898
|
}
|
|
10858
11899
|
}
|
|
@@ -10891,9 +11932,9 @@ async function main() {
|
|
|
10891
11932
|
try {
|
|
10892
11933
|
const statuses = cliArgs.taskIds.map((id) => {
|
|
10893
11934
|
validateTaskId(id);
|
|
10894
|
-
const mainFile =
|
|
10895
|
-
const statusFile = cliArgs.ship &&
|
|
10896
|
-
if (!
|
|
11935
|
+
const mainFile = path25.join(REPO_ROOT2, "tasks", id, "status.json");
|
|
11936
|
+
const statusFile = cliArgs.ship && fs27.existsSync(mainFile) ? mainFile : statusFileFor(id);
|
|
11937
|
+
if (!fs27.existsSync(statusFile)) die2(`No status.json at tasks/${id}/status.json \u2014 run canon task new ${id} first`);
|
|
10897
11938
|
return readStatusFromPath(statusFile, id);
|
|
10898
11939
|
});
|
|
10899
11940
|
if (!cliArgs.ship || cliArgs.dryRun) runProvider = resolveBundleProvider(statuses);
|
|
@@ -10909,8 +11950,8 @@ async function main() {
|
|
|
10909
11950
|
const earlyHeartbeatTaskIds = cliArgs.taskIds;
|
|
10910
11951
|
let heartbeatStarted = false;
|
|
10911
11952
|
const earlyHeartbeatResolver = (id) => {
|
|
10912
|
-
const repoRootStatusFile =
|
|
10913
|
-
return
|
|
11953
|
+
const repoRootStatusFile = path25.join(REPO_ROOT2, "tasks", id, "status.json");
|
|
11954
|
+
return path25.dirname(cliArgs.ship && fs27.existsSync(repoRootStatusFile) ? repoRootStatusFile : statusFileFor(id));
|
|
10914
11955
|
};
|
|
10915
11956
|
if (!cliArgs.ship && !cliArgs.dryRun) {
|
|
10916
11957
|
guardConcurrentRun(cliArgs.taskIds, earlyHeartbeatResolver);
|
|
@@ -10946,7 +11987,7 @@ async function main() {
|
|
|
10946
11987
|
}
|
|
10947
11988
|
refreshCanonSnapshotsAtPaths(taskIds.map(statusFileFor));
|
|
10948
11989
|
const initialState = buildPipelineState(taskIds);
|
|
10949
|
-
const heartbeatDirResolver = (id) =>
|
|
11990
|
+
const heartbeatDirResolver = (id) => path25.dirname(statusFileFor(id));
|
|
10950
11991
|
if (!isSynchronousMode(cliArgs) && shouldAutoDetach()) {
|
|
10951
11992
|
detachAndExit({
|
|
10952
11993
|
taskIds,
|
|
@@ -10991,6 +12032,10 @@ async function main() {
|
|
|
10991
12032
|
info(`${label} session stored (${slot}): ${lastSessionId.slice(0, 8)}...`);
|
|
10992
12033
|
}
|
|
10993
12034
|
}
|
|
12035
|
+
if (currentPhase === "code_review") {
|
|
12036
|
+
const sessionId = cliArgs.interactive || !lastSessionId ? null : usableSessionId(taskIds, "reviewer", assignmentForTasks(taskIds));
|
|
12037
|
+
await fixUpReviewArtifactRefs(taskIds, getActiveCwd(taskIds), sessionId);
|
|
12038
|
+
}
|
|
10994
12039
|
await checkAndRoute(currentPhase, taskIds);
|
|
10995
12040
|
}
|
|
10996
12041
|
});
|