architecture-harness 0.25.1 → 0.26.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/package.json +2 -18
- package/src/cli/ask.mjs +42 -0
- package/src/cli/ask.test.mjs +40 -0
- package/src/cli/check-commands.mjs +104 -7
- package/src/cli/check-commands.test.mjs +281 -7
- package/src/cli/check-full.test.mjs +152 -0
- package/src/cli/check.mjs +113 -0
- package/src/cli/check.test.mjs +45 -0
- package/src/cli/child-run.mjs +7 -2
- package/src/cli/child-run.test.mjs +17 -2
- package/src/cli/ci-failures.mjs +47 -9
- package/src/cli/ci-failures.test.mjs +116 -10
- package/src/cli/ci-preview.mjs +62 -0
- package/src/cli/ci-preview.test.mjs +85 -0
- package/src/cli/ci-state.mjs +2 -2
- package/src/cli/ci-state.test.mjs +8 -8
- package/src/cli/ci-template.test.mjs +79 -1
- package/src/cli/codex-implement.mjs +373 -44
- package/src/cli/codex-implement.test.mjs +775 -14
- package/src/cli/codex-limit.test.mjs +1 -1
- package/src/cli/codex-verify.mjs +230 -0
- package/src/cli/codex-verify.test.mjs +402 -0
- package/src/cli/comment-watch.mjs +391 -0
- package/src/cli/comment-watch.test.mjs +392 -0
- package/src/cli/commit-guard.mjs +3 -3
- package/src/cli/commit-guard.test.mjs +9 -3
- package/src/cli/diff-shape.mjs +162 -0
- package/src/cli/diff-shape.test.mjs +200 -0
- package/src/cli/dispatch-guard.test.mjs +7 -7
- package/src/cli/dispatch-reminder.mjs +18 -8
- package/src/cli/dispatch-reminder.test.mjs +46 -10
- package/src/cli/dispatch-slot.mjs +2 -2
- package/src/cli/dispatch-slot.test.mjs +18 -19
- package/src/cli/dispatch.test.mjs +3 -3
- package/src/cli/fleet.mjs +180 -0
- package/src/cli/fleet.test.mjs +213 -0
- package/src/cli/gate-slot.mjs +2 -1
- package/src/cli/gh-merge-command.mjs +5 -3
- package/src/cli/gh-merge-command.test.mjs +4 -0
- package/src/cli/gh-run.mjs +50 -7
- package/src/cli/gh-run.test.mjs +35 -5
- package/src/cli/git-read.mjs +2 -1
- package/src/cli/integrate-tree.mjs +47 -0
- package/src/cli/integrate.mjs +35 -26
- package/src/cli/integration-lane.mjs +3 -5
- package/src/cli/integration-lane.test.mjs +2 -2
- package/src/cli/ledger.test.mjs +12 -3
- package/src/cli/legs.mjs +53 -0
- package/src/cli/legs.test.mjs +70 -0
- package/src/cli/locked-tests.mjs +134 -0
- package/src/cli/locked-tests.test.mjs +188 -0
- package/src/cli/merge-guard.mjs +96 -43
- package/src/cli/merge-guard.test.mjs +272 -111
- package/src/cli/metrics.mjs +53 -0
- package/src/cli/metrics.test.mjs +73 -0
- package/src/cli/milestone.mjs +297 -0
- package/src/cli/milestone.test.mjs +294 -0
- package/src/cli/mutate.mjs +203 -0
- package/src/cli/mutate.test.mjs +134 -0
- package/src/cli/overview.mjs +131 -0
- package/src/cli/overview.test.mjs +137 -0
- package/src/cli/platform-risk.mjs +46 -0
- package/src/cli/platform-risk.test.mjs +38 -0
- package/src/cli/pr-guard.mjs +128 -0
- package/src/cli/pr-guard.test.mjs +154 -0
- package/src/cli/qc.mjs +76 -20
- package/src/cli/qc.test.mjs +35 -1
- package/src/cli/retry-failed.mjs +3 -1
- package/src/cli/run-log.mjs +73 -0
- package/src/cli/run-log.test.mjs +121 -0
- package/src/cli/skill-length.test.mjs +8 -0
- package/src/cli/tools.mjs +49 -0
- package/src/cli/tools.test.mjs +89 -0
- package/src/cli/watch.mjs +21 -8
- package/src/cli/watch.test.mjs +45 -21
- package/src/cli/work-order-guard.mjs +2 -1
- package/src/cli/workflow-hooks.test.mjs +1 -1
- package/src/cli/workflow-settings.mjs +3 -2
- package/src/cli/workflow-settings.test.mjs +11 -1
- package/src/config.mjs +64 -2
- package/src/config.test.mjs +93 -20
- package/src/consumer-package.test.mjs +3 -18
- package/src/descriptions.mjs +1 -0
- package/src/eslint/index.mjs +2 -0
- package/src/eslint/preset.mjs +12 -1
- package/src/eslint/preset.test.mjs +1 -1
- package/src/eslint/rules/timeless-comment.mjs +92 -0
- package/src/eslint/rules.test.mjs +34 -0
- package/src/gates/plain-language.mjs +396 -0
- package/src/gates/plain-language.test.mjs +210 -0
- package/src/global-skills.test.mjs +0 -1
- package/templates/docs/enforcement.md +12 -2
- package/templates/github/workflows/ci.yml +51 -4
- package/src/cli/screens-discovery.mjs +0 -60
- package/src/cli/screens.mjs +0 -85
- package/src/cli/stack.mjs +0 -14
- package/src/cli/throwaway-db.mjs +0 -133
- package/src/cli/throwaway-db.test.mjs +0 -137
- package/src/screens/auth-context.test.mjs +0 -41
- package/src/screens/auth-run.test.mjs +0 -147
- package/src/screens/auth.mjs +0 -223
- package/src/screens/auth.test.mjs +0 -76
- package/src/screens/capture-idle.test.mjs +0 -27
- package/src/screens/capture.browser-test.mjs +0 -73
- package/src/screens/capture.mjs +0 -176
- package/src/screens/capture.test.mjs +0 -28
- package/src/screens/catalog.browser-test.mjs +0 -32
- package/src/screens/catalog.mjs +0 -72
- package/src/screens/catalog.test.mjs +0 -36
- package/src/screens/chrome.mjs +0 -21
- package/src/screens/compare.mjs +0 -41
- package/src/screens/compare.test.mjs +0 -30
- package/src/screens/discovery.browser-test.mjs +0 -29
- package/src/screens/discovery.mjs +0 -158
- package/src/screens/discovery.test.mjs +0 -27
- package/src/screens/inventory.mjs +0 -69
- package/src/screens/inventory.test.mjs +0 -10
- package/src/screens/map.mjs +0 -63
- package/src/screens/map.test.mjs +0 -35
- package/src/screens/open.browser-test.mjs +0 -50
- package/src/screens/regions.mjs +0 -138
- package/src/screens/regions.test.mjs +0 -38
- package/src/screens/session-files.mjs +0 -39
- package/src/screens/session-files.test.mjs +0 -39
- package/src/screens/setup.browser-test.mjs +0 -49
- package/src/screens/setup.mjs +0 -79
- package/src/screens/stack-auth.browser-test.mjs +0 -30
- package/src/screens/stack-auth.mjs +0 -107
- package/src/screens/stack-auth.test.mjs +0 -65
- package/src/screens/write-guard.mjs +0 -26
- package/src/stack/stack.mjs +0 -131
- package/src/stack/stack.test.mjs +0 -60
- package/src/stack/supervisor.mjs +0 -30
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
// `qc codex-implement`: run one brief through `codex exec` as an implementer, and start a fresh session
|
|
2
2
|
// after each stop until the progress file says it is done. It never calls Claude; exit 2 hands the brief back.
|
|
3
3
|
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { appendRecord, ledgerFileOf } from "./ledger.mjs";
|
|
6
|
+
import { appendRun, runLogFileOf } from "./run-log.mjs";
|
|
4
7
|
import { spawnCommand as spawn } from "./spawn-command.mjs";
|
|
5
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
8
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeSync } from "node:fs";
|
|
6
9
|
import os from "node:os";
|
|
7
10
|
import path from "node:path";
|
|
8
11
|
import { setTimeout as pause } from "node:timers/promises";
|
|
9
12
|
import { load } from "../config.mjs";
|
|
13
|
+
import { checkDiffShape } from "./diff-shape.mjs";
|
|
14
|
+
import { testsCovering } from "./check-commands.mjs";
|
|
10
15
|
import { limitFileOf, resetTimeOf, writeLimit } from "./codex-limit.mjs";
|
|
11
16
|
import { parseMaxHours, parsePollMinutes, waitForCodexReset } from "./codex-reset.mjs";
|
|
12
17
|
import { budgetsOf } from "./context-budgets.mjs";
|
|
13
18
|
import { checkRunCommits, findingName, guardRefs, protectedAllow } from "./commit-guard.mjs";
|
|
14
19
|
import { pauseRefusal, holdRefusal } from "./pause.mjs";
|
|
15
20
|
import { ciBriefRefusal, currentBranch, lessonRules } from "./ci-failures.mjs";
|
|
21
|
+
import { addedTestCases, checkLockedTests, lockTests, readLockedTests, runTestCommand, verifyBaseTests } from "./locked-tests.mjs";
|
|
22
|
+
import { runMutation } from "./mutate.mjs";
|
|
23
|
+
import { reviewContext, validatePaths, verificationPolicy, verifyBrief } from "./codex-verify.mjs";
|
|
16
24
|
|
|
17
25
|
export const DONE_MARKER = "ALL TASKS DONE";
|
|
18
|
-
export const REVIEW_MODEL = "gpt-6.1-sol";
|
|
19
|
-
export const REVIEW_EFFORT = "high";
|
|
20
26
|
const DEFAULT_MAX_RUNS = 1;
|
|
21
27
|
const TAIL_CHARS = 4000;
|
|
22
28
|
const LIMIT = /usage limit|spend cap|rate limit|hit your limit/i;
|
|
@@ -48,10 +54,10 @@ export function codexEnvironment(env, envAllow = [], platform = process.platform
|
|
|
48
54
|
}
|
|
49
55
|
|
|
50
56
|
const USAGE =
|
|
51
|
-
"usage: qc codex-implement --brief <file> --worktree <path> --progress <file> [--log <file>] [--max-runs <n>] [--
|
|
52
|
-
"exit 0 every task done, 1 bad input or no codex, 2 a Codex usage or spend limit, 3 out of runs, 4 guard refused, 5 paused";
|
|
57
|
+
"usage: qc codex-implement --brief <file> --worktree <path> --progress <file> [--log <file>] [--max-runs <n>] [--role <scout|tests|implement|review>] [--review] [--report <file>] [--resume <id>] [--effort <low|medium|high>] [--wait-reset] [--max-hours <n>] [--poll-minutes <n>]\n" +
|
|
58
|
+
"exit 0 every task done, 1 bad input or no codex, 2 a Codex usage or spend limit, 3 out of runs or report failure, 4 guard or diff shape refused, 5 paused, 7 verify failed";
|
|
53
59
|
|
|
54
|
-
const FLAGS = { "--brief": "brief", "--worktree": "worktree", "--progress": "progress", "--log": "log", "--max-runs": "maxRuns", "--max-hours": "maxHours", "--effort": "effort", "--poll-minutes": "pollMinutes" };
|
|
60
|
+
const FLAGS = { "--role": "role", "--resume": "resume", "--report": "report", "--brief": "brief", "--worktree": "worktree", "--progress": "progress", "--log": "log", "--max-runs": "maxRuns", "--max-hours": "maxHours", "--effort": "effort", "--poll-minutes": "pollMinutes" };
|
|
55
61
|
|
|
56
62
|
/** @returns the settings with resolved paths; throws an Error naming the bad or missing flag. */
|
|
57
63
|
export function parseArgs(argv) {
|
|
@@ -69,7 +75,12 @@ export function parseArgs(argv) {
|
|
|
69
75
|
const maxRuns = found.maxRuns === undefined ? DEFAULT_MAX_RUNS : Number(found.maxRuns);
|
|
70
76
|
if (!Number.isInteger(maxRuns) || maxRuns < 1) throw new Error(`--max-runs must be a positive integer, got ${found.maxRuns}`);
|
|
71
77
|
if (found.effort !== undefined && !["low", "medium", "high"].includes(found.effort)) throw new Error("--effort must be low, medium, or high");
|
|
72
|
-
if (found.review && found.
|
|
78
|
+
if (found.review && found.role !== undefined && found.role !== "review") throw new Error("--review conflicts with --role");
|
|
79
|
+
const role = found.role ?? (found.review ? "review" : "implement");
|
|
80
|
+
if (!["scout", "tests", "implement", "review"].includes(role)) throw new Error("--role must be scout, tests, implement, or review");
|
|
81
|
+
if (found.resume !== undefined && (!found.resume.trim() || found.resume.startsWith("-") || /[\r\n]/.test(found.resume))) throw new Error("--resume needs a session id");
|
|
82
|
+
if (role === "review" && found.effort !== undefined) throw new Error("--review cannot be combined with --effort");
|
|
83
|
+
if (found.report !== undefined && !["scout", "review"].includes(role)) throw new Error("--report requires --review or --role scout");
|
|
73
84
|
const progress = path.resolve(found.progress);
|
|
74
85
|
return {
|
|
75
86
|
brief: path.resolve(found.brief),
|
|
@@ -78,7 +89,10 @@ export function parseArgs(argv) {
|
|
|
78
89
|
log: path.resolve(found.log ?? `${progress}.log`),
|
|
79
90
|
maxRuns,
|
|
80
91
|
effort: found.effort,
|
|
81
|
-
|
|
92
|
+
role,
|
|
93
|
+
resume: found.resume,
|
|
94
|
+
review: role === "review",
|
|
95
|
+
report: found.report === undefined ? undefined : path.resolve(path.dirname(path.resolve(found.brief)), found.report),
|
|
82
96
|
waitReset: found.waitReset ?? false,
|
|
83
97
|
maxHours: parseMaxHours(found.maxHours),
|
|
84
98
|
pollMinutes: parsePollMinutes(found.pollMinutes),
|
|
@@ -88,7 +102,7 @@ export function parseArgs(argv) {
|
|
|
88
102
|
const isDone = (progress) => existsSync(progress) && readFileSync(progress, "utf8").trimEnd().split(/\r?\n/).at(-1).trim() === DONE_MARKER;
|
|
89
103
|
|
|
90
104
|
const FIXED_PREAMBLE = "The brief carries every rule. Load no skill. Write no `Grammar:` line.";
|
|
91
|
-
const FIXED_HEADINGS = new Set(["Product decisions", "Run shape", "Commit", "Exit criteria", "CI failures", "Diagnosis"]);
|
|
105
|
+
const FIXED_HEADINGS = new Set(["Product decisions", "Run shape", "Commit", "Exit criteria", "CI failures", "Diagnosis", "Design"]);
|
|
92
106
|
|
|
93
107
|
const LEAN_RULES = [
|
|
94
108
|
"Lean rules for every session. They cut repeated reading and helper agents. Never drop a security, tenant, data, or correctness check that this brief asks for.",
|
|
@@ -158,10 +172,11 @@ function pluginOverrides(env, disablePlugins) {
|
|
|
158
172
|
function codexSettingsOf(worktree) {
|
|
159
173
|
const codex = load(worktree).codex;
|
|
160
174
|
if (!codex || typeof codex !== "object" || Array.isArray(codex)) throw new Error("codex in qc.config.json must be an object");
|
|
161
|
-
for (const key of ["compactTokens", "briefMaxLines", "briefMaxSteps", "maxRuns"]) {
|
|
175
|
+
for (const key of ["compactTokens", "briefMaxLines", "briefMaxSteps", "maxRuns", "maxDiffLines"]) {
|
|
162
176
|
const value = codex[key];
|
|
163
177
|
if (!Number.isInteger(value) || value < 1) throw new Error(`codex.${key} in qc.config.json must be a positive whole number, got ${JSON.stringify(value)}`);
|
|
164
178
|
}
|
|
179
|
+
if (typeof codex.requireApproval !== "boolean") throw new Error("codex.requireApproval in qc.config.json must be a boolean");
|
|
165
180
|
if (typeof codex.preamble !== "string") throw new Error("codex.preamble in qc.config.json must be a string");
|
|
166
181
|
if (!Array.isArray(codex.disablePlugins) || !codex.disablePlugins.every((name) => typeof name === "string" && name.trim())) {
|
|
167
182
|
throw new Error("codex.disablePlugins in qc.config.json must be an array of non-empty strings");
|
|
@@ -170,12 +185,21 @@ function codexSettingsOf(worktree) {
|
|
|
170
185
|
}
|
|
171
186
|
|
|
172
187
|
/** Branch: refuses briefs that exceed the session limits. */
|
|
173
|
-
function validateBrief(brief, codex) {
|
|
188
|
+
function validateBrief(brief, codex, settings) {
|
|
174
189
|
const lines = brief.split(/\r?\n/);
|
|
175
190
|
const nonBlank = lines.filter((line) => line.trim()).length;
|
|
176
|
-
if (nonBlank > codex.briefMaxLines) throw
|
|
177
|
-
if (!lines.some((line) => /^## Product decisions\s*$/.test(line))) throw
|
|
178
|
-
if (!lines.some((line) => /^Paths:[ \t]*\S/.test(line))) throw
|
|
191
|
+
if (nonBlank > codex.briefMaxLines) throw refusalError("brief:max-lines", `codex.briefMaxLines limit is ${codex.briefMaxLines} non-blank lines; got ${nonBlank}`);
|
|
192
|
+
if (!lines.some((line) => /^## Product decisions\s*$/.test(line))) throw refusalError("brief:product-decisions", "## Product decisions is required: at least 1 heading");
|
|
193
|
+
if (!lines.some((line) => /^Paths:[ \t]*\S/.test(line))) throw refusalError("brief:paths", "Paths: is required: at least 1 line naming owned files or folders");
|
|
194
|
+
validatePaths(brief);
|
|
195
|
+
if (codex.requireApproval && settings.role === "implement") {
|
|
196
|
+
if (!/^## Design[ \t]*\r?$/m.test(brief)) throw refusalError("brief:design", "## Design is required for implement when codex.requireApproval is true");
|
|
197
|
+
const approved = briefPath(brief, "Approved", settings.brief);
|
|
198
|
+
if (!approved) throw refusalError("brief:approval", "Approved: is required for implement when codex.requireApproval is true");
|
|
199
|
+
try {
|
|
200
|
+
if (!readFileSync(approved, "utf8").trim()) throw new Error("empty approval report");
|
|
201
|
+
} catch { throw refusalError("brief:approval", `Approved: must name a readable, non-empty approval report: ${approved}`); }
|
|
202
|
+
}
|
|
179
203
|
let tasks = 0;
|
|
180
204
|
let steps = 0;
|
|
181
205
|
let inTask = false;
|
|
@@ -188,8 +212,8 @@ function validateBrief(brief, codex) {
|
|
|
188
212
|
steps += 1;
|
|
189
213
|
}
|
|
190
214
|
}
|
|
191
|
-
if (tasks > 1) throw
|
|
192
|
-
if (steps > codex.briefMaxSteps) throw
|
|
215
|
+
if (tasks > 1) throw refusalError("brief:task-headings", `task heading limit is 1 besides the fixed template headings; got ${tasks}`);
|
|
216
|
+
if (steps > codex.briefMaxSteps) throw refusalError("brief:max-steps", `codex.briefMaxSteps limit is ${codex.briefMaxSteps} numbered steps under the task; got ${steps}`);
|
|
193
217
|
}
|
|
194
218
|
|
|
195
219
|
/** Fragment: reads the role limits that `budgets.codex` sets; null turns the launch overrides off. */
|
|
@@ -203,42 +227,77 @@ function codexLimitsOf(worktree) {
|
|
|
203
227
|
/** The brief is read again for each run, so an edit reaches the next session. */
|
|
204
228
|
const promptFor = (settings, codex) => {
|
|
205
229
|
const brief = readFileSync(settings.brief, "utf8");
|
|
206
|
-
validateBrief(brief, codex);
|
|
230
|
+
validateBrief(brief, codex, settings);
|
|
207
231
|
const branch = currentBranch(settings.worktree);
|
|
208
232
|
const refusal = ciBriefRefusal(settings.worktree, branch, brief);
|
|
209
|
-
if (refusal) throw
|
|
233
|
+
if (refusal) throw refusalError("brief:ci", refusal);
|
|
234
|
+
let review;
|
|
235
|
+
try { review = reviewContext(brief, settings, branch); } catch (error) { error.refusal = "reviewed"; throw error; }
|
|
236
|
+
const promptBrief = settings.review ? brief.replace(/^Reviewed:[^\r\n]*(?:\r?\n|$)/gm, "") : brief;
|
|
210
237
|
const preamble = [FIXED_PREAMBLE, codex.preamble].filter(Boolean).join("\n");
|
|
211
238
|
const rules = lessonRules(settings.worktree, load(settings.worktree).lessons);
|
|
212
239
|
const lessons = rules.length ? `\n\nCI lesson rules (newest first):\n${rules.join("\n")}` : "";
|
|
213
|
-
|
|
240
|
+
const implementationReport = settings.role === "review" ? briefPath(brief, "Report", settings.brief) : null;
|
|
241
|
+
const roleRule = settings.role === "scout"
|
|
242
|
+
? `\n\nRole: scout. Do not edit, stage, or commit worktree files. Write a fresh report to ${settings.report} with Gap:, Plan:, Check:, Risks:, Questions:, and Breaking: yes|no. Keep report, progress and logs outside the worktree.`
|
|
243
|
+
: settings.role === "review"
|
|
244
|
+
? `\n\nRole: review. Assess the implementation report's ## Survivors section${implementationReport && implementationReport !== settings.report ? ` at ${implementationReport}` : " named in the brief"}.`
|
|
245
|
+
: `\n\nRole: ${settings.role}.`;
|
|
246
|
+
const checklist = settings.role === "review" ? `
|
|
247
|
+
|
|
248
|
+
Review checklist:
|
|
249
|
+
1. Does the diff fit \`docs/architecture.md\` and the \`## Design\` part?
|
|
250
|
+
2. Which input gives a wrong result? Give \`file:line\` and the input.
|
|
251
|
+
3. Do the tests prove the issue? Name any test that adds nothing.
|
|
252
|
+
4. Is there a simpler way with less code?
|
|
253
|
+
5. Put debt outside the scope under \`## Debt\`, not under findings.` : "";
|
|
254
|
+
return `${preamble}\n\n${promptBrief}${review}${roleRule}${checklist}${lessons}${continuationNote(settings.progress)}`;
|
|
214
255
|
};
|
|
215
256
|
|
|
216
257
|
/** Sends the prompt on stdin, appends output to the log, and returns the status and output tail. */
|
|
217
|
-
function spawnRun({
|
|
258
|
+
function spawnRun({ args, input, env, log, cwd }, codexCommand) {
|
|
218
259
|
const [bin, ...prefix] = codexCommand;
|
|
219
260
|
mkdirSync(path.dirname(log), { recursive: true });
|
|
220
|
-
const start = existsSync(log) ? statSync(log).size : 0;
|
|
221
261
|
const fd = openSync(log, "a");
|
|
222
262
|
return new Promise((resolve, reject) => {
|
|
223
263
|
let child;
|
|
264
|
+
let tail = Buffer.alloc(0);
|
|
265
|
+
let pending = "";
|
|
266
|
+
let session;
|
|
267
|
+
let inputTokens = 0;
|
|
268
|
+
let outputTokens = 0;
|
|
269
|
+
const capture = (chunk, json) => {
|
|
270
|
+
writeSync(fd, chunk);
|
|
271
|
+
tail = Buffer.concat([tail, chunk]).subarray(-TAIL_CHARS);
|
|
272
|
+
if (!json) return;
|
|
273
|
+
pending += chunk.toString("utf8");
|
|
274
|
+
const lines = pending.split("\n");
|
|
275
|
+
pending = lines.pop().slice(-65536);
|
|
276
|
+
for (const line of lines) {
|
|
277
|
+
try {
|
|
278
|
+
const event = JSON.parse(line);
|
|
279
|
+
if (event.type === "turn.completed") {
|
|
280
|
+
inputTokens += tokenCount(event.usage?.input_tokens);
|
|
281
|
+
outputTokens += tokenCount(event.usage?.output_tokens);
|
|
282
|
+
}
|
|
283
|
+
if (event.type === "thread.started" && typeof event.thread_id === "string" && /^[a-zA-Z0-9_-]+$/.test(event.thread_id)) session = event.thread_id;
|
|
284
|
+
} catch { /* Non-JSON output remains in the log, without inventing a session. */ }
|
|
285
|
+
}
|
|
286
|
+
};
|
|
224
287
|
try {
|
|
225
|
-
child = spawn(bin, [...prefix, ...args], { env, stdio: ["pipe",
|
|
226
|
-
} catch (error) {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
}
|
|
231
|
-
child.on("error", (error) => {
|
|
232
|
-
reject(error);
|
|
233
|
-
});
|
|
288
|
+
child = spawn(bin, [...prefix, ...args], { env, cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
|
|
289
|
+
} catch (error) { closeSync(fd); reject(error); return; }
|
|
290
|
+
child.stdout.on("data", (chunk) => capture(chunk, true));
|
|
291
|
+
child.stderr.on("data", (chunk) => capture(chunk, false));
|
|
292
|
+
child.on("error", reject);
|
|
234
293
|
child.stdin.on("error", (error) => {
|
|
235
294
|
if (error.code !== "EPIPE" && error.code !== "EOF") reject(error);
|
|
236
295
|
});
|
|
237
296
|
child.stdin.end(input);
|
|
238
297
|
child.on("close", (status) => {
|
|
298
|
+
if (pending) capture(Buffer.from("\n"), true);
|
|
239
299
|
closeSync(fd);
|
|
240
|
-
|
|
241
|
-
resolve({ status, tail: Buffer.from(text).subarray(Math.max(start, Buffer.byteLength(text) - TAIL_CHARS)).toString("utf8") });
|
|
300
|
+
resolve({ status, tail: tail.toString("utf8"), session, inputTokens, outputTokens });
|
|
242
301
|
});
|
|
243
302
|
});
|
|
244
303
|
}
|
|
@@ -247,6 +306,11 @@ function spawnRun({ command, args, input, env, log }, codexCommand) {
|
|
|
247
306
|
const writeLine = (line) => new Promise((resolve) => process.stdout.write(`${line}
|
|
248
307
|
`, resolve));
|
|
249
308
|
|
|
309
|
+
const tokenCount = (value) => Number.isFinite(value) && value >= 0 ? value : 0;
|
|
310
|
+
|
|
311
|
+
/** Tag a refusal at its source without changing its printed diagnostic. */
|
|
312
|
+
const refusalError = (id, message) => Object.assign(new Error(message), { refusal: id });
|
|
313
|
+
|
|
250
314
|
/**
|
|
251
315
|
* The last stdout line is `exit <code>` on every path, so a redirect of the runner into a wrapper log carries
|
|
252
316
|
* the end of the job for `qc watch --codex`, in any shell.
|
|
@@ -254,92 +318,357 @@ const writeLine = (line) => new Promise((resolve) => process.stdout.write(`${lin
|
|
|
254
318
|
* @param out `(line) => Promise|void` writes the `exit` line; the default writes to stdout.
|
|
255
319
|
* @returns the exit code: 0 done, 1 bad input or no codex, 2 a limit, 3 out of runs, 4 guard refused, 5 paused.
|
|
256
320
|
*/
|
|
257
|
-
export async function runCodexImplement(argv, { out = writeLine, ...options } = {}) {
|
|
321
|
+
export async function runCodexImplement(argv, { out = writeLine, warn = console.error, ...options } = {}) {
|
|
322
|
+
const clock = options.now ?? Date.now;
|
|
323
|
+
const started = clock();
|
|
324
|
+
const metrics = { inputTokens: 0, outputTokens: 0, verify: null, live: null, refusal: null };
|
|
325
|
+
const say = options.say ?? ((line) => console.error(line));
|
|
326
|
+
const report = say;
|
|
258
327
|
let code;
|
|
259
328
|
try {
|
|
260
|
-
code = await runJob(argv, options);
|
|
329
|
+
code = await runJob(argv, { ...options, say: report, metrics });
|
|
261
330
|
} catch (error) {
|
|
262
|
-
|
|
331
|
+
metrics.refusal ??= error.refusal ?? null;
|
|
332
|
+
code = finish(report, error.message, 1);
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
const settings = metrics.settings;
|
|
336
|
+
const worktreeIndex = argv.indexOf("--worktree");
|
|
337
|
+
const root = settings?.worktree ?? (worktreeIndex >= 0 ? argv[worktreeIndex + 1] : undefined);
|
|
338
|
+
let verdict = null;
|
|
339
|
+
let findings = null;
|
|
340
|
+
try {
|
|
341
|
+
if (metrics.report) {
|
|
342
|
+
const text = readFileSync(metrics.report, "utf8");
|
|
343
|
+
verdict = /^(?:VERDICT:[ \t]*)?(APPROVED|CHANGES_REQUIRED)[ \t]*$/.exec(text.split(/\r?\n/)[0])?.[1] ?? null;
|
|
344
|
+
findings = text.split(/\r?\n/).filter((line) => line.startsWith("- [P")).length;
|
|
345
|
+
}
|
|
346
|
+
} catch { /* An absent report has no verdict or finding count. */ }
|
|
347
|
+
if (root) appendRun(runLogFileOf(root), {
|
|
348
|
+
kind: "codex", time: new Date(clock()).toISOString(), branch: currentBranch(root),
|
|
349
|
+
issue: metrics.issue ?? null, role: metrics.role ?? settings?.role ?? "implement", effort: metrics.effort ?? null,
|
|
350
|
+
exit: code, refusal: metrics.refusal,
|
|
351
|
+
inputTokens: metrics.inputTokens, outputTokens: metrics.outputTokens,
|
|
352
|
+
minutes: Math.round(Math.max(0, clock() - started) / 6000) / 10,
|
|
353
|
+
verify: metrics.verify, live: metrics.live, verdict, findings,
|
|
354
|
+
});
|
|
355
|
+
} catch {
|
|
356
|
+
warn("qc codex-implement: cannot write run log");
|
|
263
357
|
}
|
|
264
358
|
await out(`exit ${code}`);
|
|
265
359
|
return code;
|
|
266
360
|
}
|
|
267
361
|
|
|
362
|
+
/** Report metadata distinguishes an unchanged old report even if its timestamp is in the future. */
|
|
363
|
+
function reportStamp(file) {
|
|
364
|
+
try {
|
|
365
|
+
const stat = statSync(file, { bigint: true });
|
|
366
|
+
return `${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
367
|
+
} catch (error) {
|
|
368
|
+
if (error.code === "ENOENT") return null;
|
|
369
|
+
throw error;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Fragment: resolves report/approval paths beside the brief, accepting template backticks. */
|
|
374
|
+
function briefPath(brief, label, file) {
|
|
375
|
+
const raw = new RegExp(`^${label}:[ \t]*(.+)$`, "m").exec(brief)?.[1].trim().replace(/^`(.*)`$/, "$1");
|
|
376
|
+
return raw ? path.resolve(path.dirname(file), raw) : undefined;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Fragment: freezes the initial ownership and dependency design across retries. */
|
|
380
|
+
function diffContract(brief) {
|
|
381
|
+
const paths = [...brief.matchAll(/^Paths:[ \t]*(.+)$/gm)].flatMap((match) => {
|
|
382
|
+
const quoted = [...match[1].matchAll(/`([^`]+)`/g)];
|
|
383
|
+
return quoted.length ? quoted.map((entry) => entry[1]) : match[1].split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
384
|
+
});
|
|
385
|
+
const design = /^## Design[ \t]*\r?\n([\s\S]*?)(?=^## |$(?![\s\S]))/m.exec(brief)?.[1] ?? "";
|
|
386
|
+
return { paths, design };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Fragment: this worktree's HEAD history also detects commits later reset away. */
|
|
390
|
+
function scoutReflog(worktree) {
|
|
391
|
+
const options = { cwd: worktree, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
|
|
392
|
+
if (!execFileSync("git", ["rev-parse", "--revs-only", "HEAD"], options).trim()) return "";
|
|
393
|
+
return execFileSync("git", ["reflog", "show", "--format=%H", "HEAD"], options);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function scoutDirt(worktree) {
|
|
397
|
+
return execFileSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { cwd: worktree, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Branch: a scout is complete only with a fresh report and all six labels. */
|
|
401
|
+
function completeScout(settings, started, originalStamp, message, say) {
|
|
402
|
+
try {
|
|
403
|
+
const stamp = reportStamp(settings.report);
|
|
404
|
+
if (stamp === null) throw new Error(`missing scout report: ${settings.report}`);
|
|
405
|
+
if (stamp === originalStamp || statSync(settings.report).mtimeMs < started) throw new Error(`stale scout report: ${settings.report}`);
|
|
406
|
+
const text = readFileSync(settings.report, "utf8");
|
|
407
|
+
for (const label of ["Gap", "Plan", "Check", "Risks", "Questions"]) {
|
|
408
|
+
if (!new RegExp(`^${label}:[ \t]*\\S`, "m").test(text)) throw new Error(`scout report requires ${label}:`);
|
|
409
|
+
}
|
|
410
|
+
if (!/^Breaking:[ \t]*(yes|no)[ \t]*\r?$/m.test(text)) throw new Error("scout report requires Breaking: yes|no");
|
|
411
|
+
return finish(say, message, 0);
|
|
412
|
+
} catch (error) { return finish(say, `cannot accept scout report: ${error.message}`, 3); }
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Records a completed review once; every report, git or ledger error remains a failed job. */
|
|
416
|
+
function completeReview(settings, started, originalStamp, message, say) {
|
|
417
|
+
if (settings.role === "scout") return completeScout(settings, started, originalStamp, message, say);
|
|
418
|
+
if (!settings.report) return finish(say, message, 0);
|
|
419
|
+
try {
|
|
420
|
+
const stamp = reportStamp(settings.report);
|
|
421
|
+
if (stamp === null) throw new Error(`missing review report: ${settings.report}`);
|
|
422
|
+
if (stamp === originalStamp || statSync(settings.report).mtimeMs < started) throw new Error(`stale review report: ${settings.report}`);
|
|
423
|
+
const text = readFileSync(settings.report, "utf8");
|
|
424
|
+
const verdict = /^[ \t]*VERDICT:[ \t]*(APPROVED|CHANGES_REQUIRED)[ \t]*\r?$/m.exec(text)?.[1];
|
|
425
|
+
if (!verdict) throw new Error(`review report has no VERDICT: line: ${settings.report}`);
|
|
426
|
+
const git = (...args) => execFileSync("git", args, { cwd: settings.worktree, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
427
|
+
const sha = git("rev-parse", "--verify", "HEAD^{commit}");
|
|
428
|
+
const branch = git("symbolic-ref", "--quiet", "--short", "HEAD");
|
|
429
|
+
const ledger = ledgerFileOf(settings.worktree);
|
|
430
|
+
if (!ledger) throw new Error("cannot find the worktree ledger");
|
|
431
|
+
appendRecord(ledger, { type: "verdict", kind: "codex", verdict, sha, branch });
|
|
432
|
+
return finish(say, `${message}; recorded ${verdict} on ${sha}`, 0);
|
|
433
|
+
} catch (error) {
|
|
434
|
+
return finish(say, `cannot record review verdict: ${error.message}`, 3);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
268
438
|
async function runJob(argv, {
|
|
269
439
|
run, codexCommand = ["codex"], env = process.env, say = (line) => console.error(line),
|
|
270
|
-
fetch, now = Date.now, sleep,
|
|
440
|
+
fetch, now = Date.now, sleep, runCheck = runTestCommand, runMutation: mutate = runMutation, metrics,
|
|
271
441
|
} = {}) {
|
|
272
442
|
let settings;
|
|
273
443
|
try {
|
|
274
444
|
settings = parseArgs(argv);
|
|
445
|
+
metrics.settings = settings;
|
|
446
|
+
metrics.role = settings.role;
|
|
447
|
+
metrics.effort = settings.effort ?? null;
|
|
448
|
+
try {
|
|
449
|
+
const brief = readFileSync(settings.brief, "utf8");
|
|
450
|
+
const issueMatch = /^Issue:[ \t]*(?:#(\d+)|(\d+)|`#?(\d+)`)[ \t]*\r?$/m.exec(brief);
|
|
451
|
+
const issue = issueMatch?.slice(1).find(Boolean);
|
|
452
|
+
metrics.issue = issue && Number.isSafeInteger(Number(issue)) ? Number(issue) : null;
|
|
453
|
+
if (/^#[ \t]+.*\bfix\b/i.test(brief)) metrics.role = "fix";
|
|
454
|
+
metrics.report = settings.report ?? briefPath(brief, "Report", settings.brief) ?? `${settings.progress}.report.md`;
|
|
455
|
+
} catch { /* Preflight still reports an unreadable brief through its normal exit. */ }
|
|
275
456
|
} catch (error) {
|
|
276
457
|
say(`qc codex-implement: ${error.message}\n${USAGE}`);
|
|
277
458
|
return 1;
|
|
278
459
|
}
|
|
460
|
+
const refuse = (id, message, code = 4) => {
|
|
461
|
+
metrics.refusal = id;
|
|
462
|
+
return finish(say, message, code);
|
|
463
|
+
};
|
|
464
|
+
const started = Date.now();
|
|
465
|
+
let originalStamp;
|
|
466
|
+
try {
|
|
467
|
+
if (settings.role === "scout") {
|
|
468
|
+
settings.report ??= briefPath(readFileSync(settings.brief, "utf8"), "Report", settings.brief);
|
|
469
|
+
if (!settings.report) return finish(say, "scout requires --report or Report:", 1);
|
|
470
|
+
for (const file of [settings.report, settings.progress, settings.log]) {
|
|
471
|
+
const relative = path.relative(settings.worktree, file);
|
|
472
|
+
if (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative)) return finish(say, "scout report, progress and log must be outside the worktree", 1);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if (settings.report) originalStamp = reportStamp(settings.report);
|
|
476
|
+
} catch (error) {
|
|
477
|
+
return finish(say, `cannot stat review report: ${error.message}`, 3);
|
|
478
|
+
}
|
|
279
479
|
let codex;
|
|
280
480
|
let codexLimits;
|
|
281
481
|
let protectedPaths;
|
|
282
482
|
let guardBase;
|
|
483
|
+
let tests;
|
|
484
|
+
let testHead;
|
|
485
|
+
let testBase;
|
|
486
|
+
let locked;
|
|
283
487
|
try {
|
|
284
488
|
codex = codexSettingsOf(settings.worktree);
|
|
489
|
+
if (settings.review) metrics.effort = codex.reviewEffort;
|
|
285
490
|
codexLimits = codexLimitsOf(settings.worktree);
|
|
286
491
|
const guardConfig = load(settings.worktree);
|
|
287
492
|
protectedPaths = guardConfig.guard.protectedPaths;
|
|
288
493
|
guardBase = guardConfig.worktree.base;
|
|
494
|
+
tests = structuredClone(guardConfig.tests);
|
|
495
|
+
if (["tests", "implement"].includes(settings.role)) {
|
|
496
|
+
locked = currentBranch(settings.worktree) ? readLockedTests(settings.worktree) : null;
|
|
497
|
+
if (settings.role === "tests" || locked !== null) {
|
|
498
|
+
const git = (...args) => execFileSync("git", args, { cwd: settings.worktree, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
499
|
+
testHead = git("rev-parse", "--revs-only", "HEAD");
|
|
500
|
+
if (testHead) testBase = git("merge-base", "HEAD", guardConfig.check.base);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
289
503
|
if (settings.maxRuns > codex.maxRuns) throw new Error(`--max-runs exceeds codex.maxRuns limit of ${codex.maxRuns}; got ${settings.maxRuns}`);
|
|
290
504
|
} catch (error) {
|
|
291
505
|
return finish(say, error.message, 1);
|
|
292
506
|
}
|
|
293
507
|
const execute = run ?? ((call) => spawnRun(call, codexCommand));
|
|
508
|
+
/** Applies frozen policy before accepting either a new or a prewritten marker. */
|
|
509
|
+
const verifyTests = async ({ policyOnly = false } = {}) => {
|
|
510
|
+
if (settings.role !== "tests" && (settings.role !== "implement" || locked === null)) return null;
|
|
511
|
+
try {
|
|
512
|
+
if (settings.role === "implement") {
|
|
513
|
+
const { problems } = checkLockedTests(settings.worktree, locked);
|
|
514
|
+
if (problems.length) return refuse("other", `guard refused: ${problems.join("; ")}`, 4);
|
|
515
|
+
const current = readLockedTests(settings.worktree);
|
|
516
|
+
if (JSON.stringify(current) !== JSON.stringify(locked)) return refuse("other", `guard refused: locked test map changed: ${Object.keys(locked).join(", ")}`, 4);
|
|
517
|
+
}
|
|
518
|
+
const cases = addedTestCases(settings.worktree, settings.role === "tests" ? testBase : testHead);
|
|
519
|
+
const cap = settings.role === "tests" ? "maxNewCases" : "maxExtraCases";
|
|
520
|
+
if (cases.length > tests[cap]) return refuse("other", `guard refused: tests.${cap} limit ${tests[cap]}; got ${cases.length}`, 4);
|
|
521
|
+
if (policyOnly) return null;
|
|
522
|
+
if (settings.role === "tests") {
|
|
523
|
+
const { problems } = await verifyBaseTests(settings.worktree, testBase, cases, tests.command);
|
|
524
|
+
if (problems.length) return refuse("other", `guard refused: ${problems.join("; ")}`, 4);
|
|
525
|
+
if (isDone(settings.progress)) lockTests(settings.worktree, [...Object.keys(locked ?? {}), ...cases.map((entry) => entry.path)]);
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
} catch (error) { return refuse("other", `guard refused: cannot verify locked tests: ${error.message}`, 4); }
|
|
529
|
+
try {
|
|
530
|
+
const files = Object.keys(locked).map((file) => path.resolve(settings.worktree, file.replace(/\\/g, "/")));
|
|
531
|
+
if (files.length && await runTestCommand([...tests.command, ...files], settings.worktree) !== 0) return finish(say, "locked tests failed", 3);
|
|
532
|
+
if (await runCheck(["npx", "qc", "check"], settings.worktree) !== 0) return finish(say, "qc check failed", 3);
|
|
533
|
+
} catch (error) { return finish(say, `test run failed: ${error.message}`, 3); }
|
|
534
|
+
return null;
|
|
535
|
+
};
|
|
536
|
+
const mutationReport = async () => {
|
|
537
|
+
if (settings.role !== "implement" || locked === null) return;
|
|
538
|
+
const diagnostics = [];
|
|
539
|
+
try {
|
|
540
|
+
const result = await mutate({ worktree: settings.worktree, base: testBase, command: tests.command, files: Object.keys(locked), say: (line) => { diagnostics.push(line); say(line); } });
|
|
541
|
+
const report = briefPath(readFileSync(settings.brief, "utf8"), "Report", settings.brief);
|
|
542
|
+
if (!report) { say("mutation: no Report: path in brief; cannot append survivors"); return; }
|
|
543
|
+
const rows = result.survived.map(({ file, line, mutant }) => `- ${file}:${line}: ${JSON.stringify(mutant)}`);
|
|
544
|
+
mkdirSync(path.dirname(report), { recursive: true });
|
|
545
|
+
appendFileSync(report, `\n## Survivors\n\n${diagnostics.length ? diagnostics.join("\n") : rows.length ? rows.join("\n") : "No survivors."}\n${result.skippedLines} lines skipped by syntax errors, the budget or ten-line cap.\n`);
|
|
546
|
+
} catch (error) { say(`mutation: ${error.message.replace(/[\r\n]+/g, " ")}; no mutation coverage`); }
|
|
547
|
+
};
|
|
548
|
+
const verifiedCompletion = async (message) => {
|
|
549
|
+
try {
|
|
550
|
+
const passed = await verifyBrief(settings, { env, policy, outcome: metrics });
|
|
551
|
+
if (!passed) return finish(say, "verify failed", 7);
|
|
552
|
+
} catch (error) { return finish(say, `verify failed: ${error.message}`, 7); }
|
|
553
|
+
if (!isDone(settings.progress)) return finish(say, "progress marker missing after verification", 3);
|
|
554
|
+
return completeReview(settings, started, originalStamp, message, say);
|
|
555
|
+
};
|
|
294
556
|
let resetDeadline;
|
|
557
|
+
let boundary;
|
|
558
|
+
let contract;
|
|
559
|
+
let policy;
|
|
560
|
+
try {
|
|
561
|
+
policy = verificationPolicy(readFileSync(settings.brief, "utf8"), settings);
|
|
562
|
+
} catch (error) {
|
|
563
|
+
metrics.refusal = error.refusal ?? "other";
|
|
564
|
+
return finish(say, `cannot prepare the brief: ${error.message}`, 1);
|
|
565
|
+
}
|
|
295
566
|
for (let count = 1; count <= settings.maxRuns; count += 1) {
|
|
296
|
-
if (isDone(settings.progress))
|
|
567
|
+
if (isDone(settings.progress)) {
|
|
568
|
+
const refused = await verifyTests();
|
|
569
|
+
if (refused !== null) return refused;
|
|
570
|
+
await mutationReport();
|
|
571
|
+
return verifiedCompletion(`done after ${count - 1} run(s)`);
|
|
572
|
+
}
|
|
297
573
|
try {
|
|
298
574
|
const branch = currentBranch(settings.worktree);
|
|
299
575
|
const refusal = pauseRefusal(settings.worktree) ?? (branch ? holdRefusal(settings.worktree, branch) : null);
|
|
300
|
-
if (refusal) return
|
|
576
|
+
if (refusal) return refuse("other", refusal, 5);
|
|
301
577
|
} catch (error) {
|
|
302
578
|
return finish(say, `cannot read the operator pause (${error.message}). Wait for the operator to run \`qc resume\`.`, 5);
|
|
303
579
|
}
|
|
304
580
|
let prompt;
|
|
305
581
|
try {
|
|
306
582
|
prompt = promptFor(settings, codex);
|
|
583
|
+
if (!contract) {
|
|
584
|
+
contract = diffContract(readFileSync(settings.brief, "utf8"));
|
|
585
|
+
const coverage = await testsCovering(settings.worktree, contract.paths).catch(() => new Map());
|
|
586
|
+
const named = contract.paths.map((file) => path.posix.normalize(file.replace(/\\/g, "/")).replace(/\/$/, ""));
|
|
587
|
+
const missing = new Set();
|
|
588
|
+
for (const [file, tests] of coverage) for (const test of tests) {
|
|
589
|
+
if (named.some((entry) => entry === "." || test === entry || test.startsWith(`${entry}/`)) || missing.has(test)) continue;
|
|
590
|
+
if (missing.size < 10) say(`qc codex-implement: warning: ${test} covers ${file}; Paths: does not name it`);
|
|
591
|
+
missing.add(test);
|
|
592
|
+
}
|
|
593
|
+
if (missing.size > 10) say(`qc codex-implement: warning: ${missing.size - 10} more covering tests; Paths: does not name them`);
|
|
594
|
+
if (codex.pathsTests === "add") contract.paths.push(...missing);
|
|
595
|
+
}
|
|
596
|
+
if (codex.pathsTests === "add") prompt += `\n\nPaths: ${contract.paths.map((file) => `\`${file}\``).join(", ")}\n`;
|
|
307
597
|
} catch (error) {
|
|
598
|
+
metrics.refusal = error.refusal ?? "other";
|
|
308
599
|
return finish(say, `cannot prepare the brief: ${error.message}`, 1);
|
|
309
600
|
}
|
|
310
601
|
const helperOff = HELPER_AGENT_FEATURES.flatMap((feature) => ["-c", feature]);
|
|
311
602
|
const limits = codexLimits === null ? [] : ["-c", `model_auto_compact_token_limit=${codexLimits.compactAt}`, "-c", `tool_output_token_limit=${codexLimits.toolOutputTokens}`];
|
|
312
|
-
const
|
|
313
|
-
const
|
|
603
|
+
const model = settings.review ? codex.reviewModel : codex.model;
|
|
604
|
+
const modelArgs = model === null ? [] : ["-c", `model=${JSON.stringify(model)}`];
|
|
605
|
+
const effort = settings.review ? ["-c", `model_reasoning_effort=${JSON.stringify(codex.reviewEffort)}`] : settings.effort === undefined ? [] : ["-c", `model_reasoning_effort=${settings.effort}`];
|
|
606
|
+
const globalArgs = ["-s", "danger-full-access", "-C", settings.worktree];
|
|
607
|
+
const overrides = [...helperOff, ...pluginOverrides(env, codex.disablePlugins), ...limits, ...modelArgs, ...effort];
|
|
608
|
+
const args = settings.resume
|
|
609
|
+
? [...globalArgs, ...overrides, "exec", "resume", settings.resume, "--json", "-"]
|
|
610
|
+
: ["exec", ...globalArgs, ...overrides, "--json", "-"];
|
|
314
611
|
const allow = protectedAllow(readFileSync(settings.brief, "utf8"));
|
|
315
612
|
const childEnv = Object.fromEntries(Object.entries(codexEnvironment(env, codex.envAllow)).filter(([name]) => name.toUpperCase() !== "QC_PROTECTED_ALLOW"));
|
|
316
613
|
let before;
|
|
317
614
|
try {
|
|
318
615
|
before = guardRefs(settings.worktree);
|
|
616
|
+
if (!boundary) {
|
|
617
|
+
boundary = before;
|
|
618
|
+
if (settings.role === "scout") boundary.reflog = scoutReflog(settings.worktree);
|
|
619
|
+
}
|
|
620
|
+
if (settings.role === "scout" && scoutDirt(settings.worktree)) return refuse("other", "guard refused: scout requires a clean worktree (tracked, staged and untracked)", 4);
|
|
319
621
|
} catch (error) {
|
|
320
|
-
return
|
|
622
|
+
return refuse("other", `guard refused: cannot capture the commit boundary: ${error.message}`, settings.report ? 3 : 4);
|
|
321
623
|
}
|
|
322
624
|
let result;
|
|
323
625
|
let runError;
|
|
324
626
|
try {
|
|
325
|
-
result = await execute({ command: codexCommand[0], args, input: prompt, env: { ...childEnv, QC_ROLE: "implementer", QC_PROTECTED_ALLOW: allow.join(",") }, log: settings.log });
|
|
627
|
+
result = await execute({ command: codexCommand[0], args, input: prompt, env: { ...childEnv, QC_ROLE: settings.role === "implement" ? "implementer" : settings.role, QC_PROTECTED_ALLOW: allow.join(",") }, log: settings.log, cwd: settings.worktree });
|
|
326
628
|
} catch (error) {
|
|
327
629
|
runError = error;
|
|
328
630
|
}
|
|
631
|
+
metrics.inputTokens += tokenCount(result?.inputTokens);
|
|
632
|
+
metrics.outputTokens += tokenCount(result?.outputTokens);
|
|
633
|
+
if (result?.session) say(`qc codex-implement: session ${result.session}`);
|
|
329
634
|
try {
|
|
635
|
+
if (settings.role === "scout") {
|
|
636
|
+
const after = guardRefs(settings.worktree);
|
|
637
|
+
if (after.head !== boundary.head || after.branch !== boundary.branch || scoutReflog(settings.worktree) !== boundary.reflog || scoutDirt(settings.worktree)) {
|
|
638
|
+
return refuse("other", "guard refused: scout changed commits or tracked, staged, or untracked worktree files", 4);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
330
641
|
const findings = checkRunCommits(settings.worktree, before, { protectedPaths, role: "implementer", allow, base: guardBase, branch: before.branch });
|
|
331
642
|
if (findings.length) {
|
|
643
|
+
metrics.refusal = /^[a-z0-9-]{1,40}$/.test(findings[0].rule) ? `guard:${findings[0].rule}` : "other";
|
|
332
644
|
for (const finding of findings) say(`qc codex-implement: guard refused: ${findingName(finding)}`);
|
|
333
645
|
return 4;
|
|
334
646
|
}
|
|
647
|
+
if (["implement", "tests"].includes(settings.role)) {
|
|
648
|
+
const { problems } = checkDiffShape({ worktree: settings.worktree, base: boundary.head, baseRef: guardBase, ...contract, maxDiffLines: codex.maxDiffLines });
|
|
649
|
+
if (problems.length) {
|
|
650
|
+
metrics.refusal = "diff-shape";
|
|
651
|
+
for (const problem of problems) say(`qc codex-implement: diff shape refused: ${problem}`);
|
|
652
|
+
return 4;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
const refused = await verifyTests({ policyOnly: true });
|
|
656
|
+
if (refused !== null) return refused;
|
|
335
657
|
} catch (error) {
|
|
336
|
-
return
|
|
658
|
+
return refuse("other", `guard refused: cannot check run commits: ${error.message}`, settings.report ? 3 : 4);
|
|
337
659
|
}
|
|
338
660
|
if (runError) return finish(say, `codex did not run: ${runError.message}`, 1);
|
|
339
661
|
say(`qc codex-implement: run ${count} ended with status ${result.status}`);
|
|
340
662
|
const line = limitLineOf(result.tail ?? "", prompt);
|
|
341
663
|
if (!line) clearLimit(limitFileOf(env), say);
|
|
342
|
-
if (isDone(settings.progress))
|
|
664
|
+
if (!line || isDone(settings.progress)) {
|
|
665
|
+
const refused = await verifyTests();
|
|
666
|
+
if (refused !== null) return refused;
|
|
667
|
+
}
|
|
668
|
+
if (isDone(settings.progress)) {
|
|
669
|
+
await mutationReport();
|
|
670
|
+
return verifiedCompletion(`done after ${count} run(s)`);
|
|
671
|
+
}
|
|
343
672
|
if (line) {
|
|
344
673
|
const recordedAt = now();
|
|
345
674
|
const reset = resetTimeOf(line, recordedAt);
|