@oscaner-skills/cdd-engine 1.0.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/LICENSE +21 -0
- package/README.md +52 -0
- package/README.zh-CN.md +54 -0
- package/dist/chunks/branch.mjs +480 -0
- package/dist/chunks/docs.mjs +253 -0
- package/dist/chunks/task.mjs +913 -0
- package/dist/cli.mjs +5457 -0
- package/dist/documents/schema/add-phase-protocol.json +126 -0
- package/dist/documents/schema/overall.json +361 -0
- package/dist/documents/schema/phase-spec.json +145 -0
- package/dist/documents/schema/plan.json +191 -0
- package/dist/documents/schema/skill-anatomy.json +233 -0
- package/dist/resources/harness-registry.json +49 -0
- package/dist/shared/cdd-engine.liioziig.mjs +184 -0
- package/package.json +51 -0
- package/templates/engine-config.json +302 -0
- package/templates/report/issue-body.json +204 -0
- package/templates/schema/cache-profile-schema.json +23 -0
- package/templates/schema/docs-handoff-schema.json +129 -0
- package/templates/schema/task-handoff-schema.json +332 -0
- package/templates/template-contract.json +231 -0
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { h as handoffName, r as readJson, w as writeHandoff, a as writeOwnHandoff, f as finalizeHandoff, G as GitClient, R as ResidueManager, i as invariant, D as DOC_TOKENS, b as DispatchLifecycle, c as runtime, P as ProgressLedger, T as TemplateLoader, C as CommitChecker, F as FailureResolver, H as HandoffSchemaValidator, d as ReturnBlockParser, e as RoundContext, g as briefPath, j as CddExitError, S as SHA40_RE, E as ExitRequested, k as writeBlockedCarrier, l as FAILURE_CATEGORIES, t as taskBaseFromBrief, m as recoverHandoff, p as persistFinalized, n as normalizeHandoffStatus, o as toTaskGroup, q as DispatchBlocked, s as exitWithCode, u as resolveDocArg, v as materializeWorkspace, x as prevHandoffPath$1, y as DocumentsValidator, z as hashFile, A as workspaceSlug } from '../cli.mjs';
|
|
4
|
+
import { R as Registry, E as EngineInvoker, a as REG_PATH, C as CddBlockedError } from '../shared/cdd-engine.liioziig.mjs';
|
|
5
|
+
import 'node:process';
|
|
6
|
+
import 'citty';
|
|
7
|
+
import 'node:url';
|
|
8
|
+
import 'tinyglobby';
|
|
9
|
+
import 'node:child_process';
|
|
10
|
+
import 'ajv';
|
|
11
|
+
import 'execa';
|
|
12
|
+
import 'simple-git';
|
|
13
|
+
import 'node:crypto';
|
|
14
|
+
import 'hookable';
|
|
15
|
+
import 'handlebars';
|
|
16
|
+
|
|
17
|
+
class Handoff {
|
|
18
|
+
workspace;
|
|
19
|
+
phase;
|
|
20
|
+
type;
|
|
21
|
+
round;
|
|
22
|
+
params;
|
|
23
|
+
constructor(init) {
|
|
24
|
+
this.workspace = init.workspace;
|
|
25
|
+
this.phase = init.phase;
|
|
26
|
+
this.type = init.type;
|
|
27
|
+
this.round = init.round;
|
|
28
|
+
this.params = init.params ?? {};
|
|
29
|
+
}
|
|
30
|
+
/** Task-family factory — `tasks` is the dispatch group's key string (the CLI `--tasks` form). */
|
|
31
|
+
static forTask(workspace, phase, options) {
|
|
32
|
+
return new Handoff({
|
|
33
|
+
workspace,
|
|
34
|
+
phase,
|
|
35
|
+
type: "task",
|
|
36
|
+
round: options.round,
|
|
37
|
+
params: { tasks: options.tasks }
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** Docs-family factory (spec/plan review/fix). */
|
|
41
|
+
static forDocs(workspace, phase, type, round) {
|
|
42
|
+
return new Handoff({ workspace, phase, type, round });
|
|
43
|
+
}
|
|
44
|
+
/** The canonical file name for this identity (handoff-naming single truth). */
|
|
45
|
+
get name() {
|
|
46
|
+
return handoffName(this.phase, this.type, {
|
|
47
|
+
...this.params,
|
|
48
|
+
...this.round != null ? { round: this.round } : {}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** The canonical on-disk path (workspace + name). */
|
|
52
|
+
get path() {
|
|
53
|
+
return `${this.workspace}/${this.name}`.replace(/\/{2,}/g, "/");
|
|
54
|
+
}
|
|
55
|
+
/** Read the carrier; missing / corrupt → null (readJson fail-open). */
|
|
56
|
+
read() {
|
|
57
|
+
return readJson(this.path);
|
|
58
|
+
}
|
|
59
|
+
/** Persist a payload: default full-replace (the engine is the carrier's sole author, T7);
|
|
60
|
+
* replace:false → shallow-merge (the H6 chain-update semantics — writeHandoff). */
|
|
61
|
+
persist(data, opts = {}) {
|
|
62
|
+
return opts.replace === false ? writeHandoff(this.path, data) : writeOwnHandoff(this.path, data);
|
|
63
|
+
}
|
|
64
|
+
/** Run the canonical finalization (finalizeHandoff — the single finalization entry). */
|
|
65
|
+
async finalize(opts = {}) {
|
|
66
|
+
return finalizeHandoff({
|
|
67
|
+
mode: opts.mode,
|
|
68
|
+
returnBlock: opts.returnBlock ?? [],
|
|
69
|
+
agentHandoff: opts.agentHandoff ?? null,
|
|
70
|
+
brief: opts.brief,
|
|
71
|
+
repoRoot: opts.repoRoot,
|
|
72
|
+
workspace: opts.workspace ?? this.workspace,
|
|
73
|
+
tasks: opts.tasks,
|
|
74
|
+
resumeScopeBase: opts.resumeScopeBase ?? null
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
class BriefRenderer {
|
|
80
|
+
#git;
|
|
81
|
+
#residue;
|
|
82
|
+
constructor(deps = {}) {
|
|
83
|
+
this.#git = deps.git ?? new GitClient();
|
|
84
|
+
this.#residue = deps.residue ?? new ResidueManager();
|
|
85
|
+
}
|
|
86
|
+
/** render(planFile, tasks, outPath, repoRoot, residue) — the brief single renderer. `tasks` is a
|
|
87
|
+
* scalar task number or the dispatch group list (the group briefs as one unit: every requested
|
|
88
|
+
* task's `### Task N:` section lands in the one file, then one TASK_BASE line). Any requested task
|
|
89
|
+
* with no matching heading BLOCKs the whole group — the invariant lists every missing task
|
|
90
|
+
* (per-item listing), preserving the `/task N not found/` contract for the single-missing case;
|
|
91
|
+
* nothing is written on the BLOCK path. */
|
|
92
|
+
async render(planFile, tasks, outPath, repoRoot, residue = null) {
|
|
93
|
+
invariant(existsSync(planFile), `plan file not found: ${planFile}`);
|
|
94
|
+
const lines = readFileSync(planFile, "utf8").split("\n");
|
|
95
|
+
const numList = Array.isArray(tasks) ? tasks : [tasks];
|
|
96
|
+
const ranges = [];
|
|
97
|
+
let headStart = -1;
|
|
98
|
+
for (let i = 0; i < lines.length; i++) {
|
|
99
|
+
if (DOC_TOKENS.taskHeadingRe.test(lines[i])) {
|
|
100
|
+
if (headStart >= 0) ranges.push({ start: headStart, end: i });
|
|
101
|
+
headStart = i;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (headStart >= 0) ranges.push({ start: headStart, end: lines.length });
|
|
105
|
+
const missing = [];
|
|
106
|
+
const sections = [];
|
|
107
|
+
for (const n of numList) {
|
|
108
|
+
const header = DOC_TOKENS.taskHeadingFor(n);
|
|
109
|
+
const range = ranges.find((r) => lines[r.start].startsWith(header));
|
|
110
|
+
if (!range) {
|
|
111
|
+
missing.push(n);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
sections.push(lines.slice(range.start, range.end).join("\n").replace(/\n+$/, ""));
|
|
115
|
+
}
|
|
116
|
+
invariant(
|
|
117
|
+
missing.length === 0,
|
|
118
|
+
`task${missing.length > 1 ? "s" : ""} ${missing.join(", ")} not found (CDD-level index; plan must contain '${DOC_TOKENS.taskHeadingFormat}' heading) in plan: ${planFile}`
|
|
119
|
+
);
|
|
120
|
+
const sha = await this.#git.revParseHead(repoRoot);
|
|
121
|
+
invariant(sha, "cannot resolve HEAD: not in a git repo");
|
|
122
|
+
let content = `${sections.join("\n\n")}
|
|
123
|
+
TASK_BASE: ${sha}
|
|
124
|
+
`;
|
|
125
|
+
if (residue) {
|
|
126
|
+
content += `
|
|
127
|
+
${this.#residue.renderResidueAppendix(residue)}
|
|
128
|
+
`;
|
|
129
|
+
}
|
|
130
|
+
writeFileSync(outPath, content, "utf8");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const VALID_MODES = ["implement", "review", "fix"];
|
|
135
|
+
const INVOKE_PARAMS = {
|
|
136
|
+
review: { op: "review", type: "task" },
|
|
137
|
+
fix: { op: "fix", type: "task" },
|
|
138
|
+
implement: { op: "implement" }
|
|
139
|
+
};
|
|
140
|
+
function resolvePlanWorkspace({ planFile, root }) {
|
|
141
|
+
const plan = planFile ? resolveDocArg(planFile, root, "plan") : "";
|
|
142
|
+
if (!plan)
|
|
143
|
+
throw new CddExitError("cannot resolve repo root: provide --plan", {
|
|
144
|
+
exitCode: 1,
|
|
145
|
+
kind: "run-blocked"
|
|
146
|
+
});
|
|
147
|
+
return { plan, workspace: materializeWorkspace({ plan, repoRoot: root }) };
|
|
148
|
+
}
|
|
149
|
+
function readJsonField(filePath, keys) {
|
|
150
|
+
if (!filePath || !existsSync(filePath)) return "";
|
|
151
|
+
try {
|
|
152
|
+
let v = JSON.parse(readFileSync(filePath, "utf8"));
|
|
153
|
+
for (const k of keys) v = v?.[k];
|
|
154
|
+
return typeof v === "string" ? v : "";
|
|
155
|
+
} catch {
|
|
156
|
+
return "";
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function prevHandoffPath(workspace, groupKey, mode, round) {
|
|
160
|
+
if (mode !== "review" && mode !== "fix") return null;
|
|
161
|
+
return prevHandoffPath$1(workspace, mode, "task", round, { tasks: groupKey });
|
|
162
|
+
}
|
|
163
|
+
function validateModeMsg(mode) {
|
|
164
|
+
if (!VALID_MODES.includes(mode)) return `mode must be implement|review|fix (got: ${mode})`;
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
function requireCtx(ctx, mode) {
|
|
168
|
+
const missing = [];
|
|
169
|
+
const required = [
|
|
170
|
+
"workspace",
|
|
171
|
+
"briefPath",
|
|
172
|
+
"ledgerPath",
|
|
173
|
+
"mode",
|
|
174
|
+
"handoffPath",
|
|
175
|
+
"constraintsPath"
|
|
176
|
+
];
|
|
177
|
+
for (const k of required) {
|
|
178
|
+
if (!ctx?.[k]) missing.push(k);
|
|
179
|
+
}
|
|
180
|
+
if (mode === "fix" && !ctx?.findingsPath) missing.push("findingsPath");
|
|
181
|
+
return missing.length > 0 ? `Missing required ctx fields: ${missing.join(" ")}` : null;
|
|
182
|
+
}
|
|
183
|
+
function buildPromptParams(ctx, group) {
|
|
184
|
+
return {
|
|
185
|
+
WORKSPACE: ctx.workspace,
|
|
186
|
+
// Canonical slug slot (Task 20 ⑦): workspaceSlug strips a single -design/-plan layer so a plan and
|
|
187
|
+
// its paired spec converge to the same slug, e.g. osuperpowers-overhaul-p6.
|
|
188
|
+
WORKSPACE_SLUG: workspaceSlug(ctx.plan),
|
|
189
|
+
BRIEF: ctx.briefPath,
|
|
190
|
+
HANDOFF_TARGET: ctx.handoffPath,
|
|
191
|
+
FINDINGS: ctx.findingsPath ?? "",
|
|
192
|
+
CONSTRAINTS: ctx.constraintsPath,
|
|
193
|
+
FIXED_POINT: ctx.fixedPoint ?? "",
|
|
194
|
+
// empty string if the cross-phase read returned nothing
|
|
195
|
+
DISPATCH_UNIT: group.key(),
|
|
196
|
+
REVIEW_PLAN_LINE: ctx.plan ? `**Plan:** ${ctx.plan}` : ""
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
class TaskLifecycle extends DispatchLifecycle {
|
|
200
|
+
#harness;
|
|
201
|
+
#group;
|
|
202
|
+
#firstTask;
|
|
203
|
+
#groupKey;
|
|
204
|
+
#opts;
|
|
205
|
+
#root;
|
|
206
|
+
/** The injected CddRuntime stand-in (P4.4 Task 4 ②) — the singleton by default. All
|
|
207
|
+
* mutable-state reads (dryRun) and lifecycle ops route through this instance. */
|
|
208
|
+
#runtime;
|
|
209
|
+
// Service seams (constructible, stateless or injected): the ctx round anchor + carrier, the
|
|
210
|
+
// rule/service classes the lifecycle delegates to (Task 6/7 seams).
|
|
211
|
+
#registry;
|
|
212
|
+
#invoker;
|
|
213
|
+
#ledger;
|
|
214
|
+
#residue;
|
|
215
|
+
#templates;
|
|
216
|
+
#briefRenderer;
|
|
217
|
+
#commit;
|
|
218
|
+
#failure;
|
|
219
|
+
#schema;
|
|
220
|
+
#returnBlockParser;
|
|
221
|
+
#entry = null;
|
|
222
|
+
#tcx = null;
|
|
223
|
+
#handoff = null;
|
|
224
|
+
#agentOut = "";
|
|
225
|
+
#agentRc = 0;
|
|
226
|
+
#timeoutMs;
|
|
227
|
+
#returnBlock = [];
|
|
228
|
+
#exitCode = -1;
|
|
229
|
+
#diagnostic = null;
|
|
230
|
+
#finished = false;
|
|
231
|
+
/** The dead-round carrier's recovery.scope_base captured at the resume pre-flight (T27,
|
|
232
|
+
* spec T7.6), handed to implement materialization (finalizeImplement pulls the scope ledger
|
|
233
|
+
* strictly earlier along it). null = no earlier anchor was riding the carrier. */
|
|
234
|
+
#resumeScopeBase = null;
|
|
235
|
+
constructor(options) {
|
|
236
|
+
super({ ctx: options.ctx });
|
|
237
|
+
this.#harness = options.harness;
|
|
238
|
+
this.#group = options.group;
|
|
239
|
+
this.#firstTask = options.group.numbers[0];
|
|
240
|
+
this.#groupKey = options.group.key();
|
|
241
|
+
this.#opts = options.opts;
|
|
242
|
+
this.#root = options.ctx.repoRoot ?? "";
|
|
243
|
+
this.#runtime = options.opts.runtime ?? runtime;
|
|
244
|
+
this.#registry = new Registry();
|
|
245
|
+
this.#invoker = new EngineInvoker();
|
|
246
|
+
this.#ledger = new ProgressLedger();
|
|
247
|
+
this.#residue = new ResidueManager();
|
|
248
|
+
this.#templates = new TemplateLoader();
|
|
249
|
+
this.#briefRenderer = new BriefRenderer();
|
|
250
|
+
this.#commit = new CommitChecker();
|
|
251
|
+
this.#failure = new FailureResolver();
|
|
252
|
+
this.#schema = new HandoffSchemaValidator();
|
|
253
|
+
this.#returnBlockParser = new ReturnBlockParser();
|
|
254
|
+
}
|
|
255
|
+
/** The dispatch group's task list (readonly view — the scalar list the agent-facing
|
|
256
|
+
* carriers/progress rows are keyed by; the group key stays TaskGroup-derived, no second form). */
|
|
257
|
+
get #tasks() {
|
|
258
|
+
return [...this.#group.numbers];
|
|
259
|
+
}
|
|
260
|
+
/** dry-run — the injected runtime's isDryRun() feeds the dispatch (P4.4 Task 4 ②): the CLI
|
|
261
|
+
* threads DRY_RUN() via opts.dryRun (same singleton state), and an injected stand-in substitutes
|
|
262
|
+
* its own flag; the OR keeps both seams honest without double state. */
|
|
263
|
+
get #dryRun() {
|
|
264
|
+
return this.#opts.dryRun === true || this.#runtime.isDryRun();
|
|
265
|
+
}
|
|
266
|
+
#mode() {
|
|
267
|
+
return this.#opts.mode ?? "";
|
|
268
|
+
}
|
|
269
|
+
/** runTask-compat result surface — { exitCode, returnBlock } read after run(). */
|
|
270
|
+
get result() {
|
|
271
|
+
return { exitCode: this.#exitCode, returnBlock: [...this.#returnBlock] };
|
|
272
|
+
}
|
|
273
|
+
/** stderr diagnostic ({ prefix, msg }) for the wrapper to emit before the return block lines; null for
|
|
274
|
+
* silent exits (OK / agent-failed-with-handoff). */
|
|
275
|
+
get diagnostic() {
|
|
276
|
+
return this.#diagnostic;
|
|
277
|
+
}
|
|
278
|
+
#done(exitCode, returnBlock, msg = "", prefix = "CDD_BLOCKED") {
|
|
279
|
+
this.#exitCode = exitCode;
|
|
280
|
+
this.#returnBlock = returnBlock;
|
|
281
|
+
this.#diagnostic = msg ? { prefix, msg } : null;
|
|
282
|
+
this.#finished = true;
|
|
283
|
+
}
|
|
284
|
+
/** buildContext(root, group, opts) — the engine-internal state (ctx) UNIQUE construction point
|
|
285
|
+
* (Task 6 ①: the bare function buildCtx moved into TaskLifecycle's public face — ctx assembly is owned via injection with the class construction). ctx
|
|
286
|
+
* always passes by return value, never through env: workspace / handoff / brief / ledger /
|
|
287
|
+
* constraints / findings all derive here in one pass. root is injected by the caller (TaskLifecycle.run
|
|
288
|
+
* passes `opts.root ?? getRoot()`, tests pass a real fixture root); the round anchor derives via
|
|
289
|
+
* RoundContext (the review/fix round's unique context — round anchor) and the handoff path via the
|
|
290
|
+
* Handoff typed carrier (Task 6 ②④). P4.3/P4.4: `group` is the dispatch GROUP value object
|
|
291
|
+
* (TaskGroup — the CLI `--tasks` string IS its key, no second form) — every task artifact is
|
|
292
|
+
* group-keyed (`tasks-{key}-*` with key `"1"` / `"1,2"`), per the canonical derived-grid channels. */
|
|
293
|
+
static buildContext(root, group, opts = {}) {
|
|
294
|
+
const {
|
|
295
|
+
mode,
|
|
296
|
+
harness,
|
|
297
|
+
round = 1,
|
|
298
|
+
findingsPath
|
|
299
|
+
} = opts;
|
|
300
|
+
const planWorkspace = opts.planWorkspace ?? resolvePlanWorkspace({ planFile: opts.planFile, root });
|
|
301
|
+
const { plan, workspace } = planWorkspace;
|
|
302
|
+
const groupKey = group.key();
|
|
303
|
+
let handoffFile;
|
|
304
|
+
if (mode === "implement") {
|
|
305
|
+
handoffFile = new Handoff({
|
|
306
|
+
workspace,
|
|
307
|
+
phase: "implement",
|
|
308
|
+
type: "task",
|
|
309
|
+
params: { tasks: groupKey }
|
|
310
|
+
}).name;
|
|
311
|
+
} else if (mode === "review" || mode === "fix") {
|
|
312
|
+
handoffFile = new RoundContext({
|
|
313
|
+
workspace,
|
|
314
|
+
op: mode,
|
|
315
|
+
type: "task",
|
|
316
|
+
round,
|
|
317
|
+
params: { tasks: groupKey }
|
|
318
|
+
}).name;
|
|
319
|
+
} else {
|
|
320
|
+
handoffFile = `tasks-${groupKey}-${mode}-${round}.json`;
|
|
321
|
+
}
|
|
322
|
+
return {
|
|
323
|
+
plan,
|
|
324
|
+
round,
|
|
325
|
+
workspace,
|
|
326
|
+
handoffPath: path.join(workspace, handoffFile),
|
|
327
|
+
// unconditional derivation
|
|
328
|
+
briefPath: briefPath({ workspace, tasks: groupKey }),
|
|
329
|
+
ledgerPath: path.join(workspace, "progress.json"),
|
|
330
|
+
constraintsPath: path.join(workspace, "plan-constraints.md"),
|
|
331
|
+
// fix: cdd fix --findings opt wins when provided; otherwise the runner-derived review-R.json
|
|
332
|
+
// path for this fix round. implement/review: the open-findings path.
|
|
333
|
+
findingsPath: mode === "fix" ? findingsPath ?? prevHandoffPath(workspace, groupKey, mode, round) : path.join(workspace, `tasks-${groupKey}-open-findings.json`),
|
|
334
|
+
mode,
|
|
335
|
+
harness,
|
|
336
|
+
fixedPoint: ""
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
// ---- pre-flight ----
|
|
340
|
+
/** Steps 1/2/2.5/4/5: registry ship gate → plan → workspace → ctx (brief self-provision, F11),
|
|
341
|
+
* template existence, progressDir, review/fix fixed-point derivation. */
|
|
342
|
+
async resolveContext(_hookCtx) {
|
|
343
|
+
if (this.#finished) return;
|
|
344
|
+
const mode = this.#mode();
|
|
345
|
+
const { registryPath = REG_PATH, pluginRoot: pluginRootFn } = this.#opts;
|
|
346
|
+
let entry;
|
|
347
|
+
try {
|
|
348
|
+
entry = this.#registry.checkHarness(this.#registry.load(registryPath), this.#harness, {
|
|
349
|
+
dryRun: this.#dryRun
|
|
350
|
+
});
|
|
351
|
+
} catch (e) {
|
|
352
|
+
if (e instanceof CddBlockedError) {
|
|
353
|
+
this.#done(
|
|
354
|
+
e.exitCode,
|
|
355
|
+
[],
|
|
356
|
+
e.message,
|
|
357
|
+
e.kind === "cli-missing" ? "CDD_CLI_MISSING" : "CDD_BLOCKED"
|
|
358
|
+
);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
throw e;
|
|
362
|
+
}
|
|
363
|
+
this.#entry = entry;
|
|
364
|
+
let ctx;
|
|
365
|
+
try {
|
|
366
|
+
const planWorkspace = resolvePlanWorkspace({
|
|
367
|
+
planFile: this.#opts.planFile,
|
|
368
|
+
root: this.#root
|
|
369
|
+
});
|
|
370
|
+
const progressData = this.#ledger.read(planWorkspace.workspace, planWorkspace.plan);
|
|
371
|
+
const round = mode === "implement" ? 1 : this.#ledger.getRound(progressData, this.#groupKey, mode);
|
|
372
|
+
ctx = TaskLifecycle.buildContext(this.#root, this.#group, {
|
|
373
|
+
mode,
|
|
374
|
+
harness: this.#harness,
|
|
375
|
+
planWorkspace,
|
|
376
|
+
round,
|
|
377
|
+
findingsPath: this.#opts.findingsPath
|
|
378
|
+
});
|
|
379
|
+
if (!this.#dryRun && mode === "implement") {
|
|
380
|
+
try {
|
|
381
|
+
materializePlanConstraints(planWorkspace.plan, ctx.workspace);
|
|
382
|
+
} catch (e) {
|
|
383
|
+
throw new CddExitError(
|
|
384
|
+
e instanceof ConstraintsSourceUndeclared ? e.message : `${PLAN_CONSTRAINTS_MISSING_BLOCKER} (${e.message})`,
|
|
385
|
+
{ exitCode: 1, kind: "run-blocked" }
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
let residueAppendix = null;
|
|
390
|
+
if (!this.#dryRun && mode === "implement") {
|
|
391
|
+
try {
|
|
392
|
+
const carrier = this.#residue.readDeadCarrier(ctx.handoffPath);
|
|
393
|
+
if (carrier) {
|
|
394
|
+
const recoveryScope = carrier.recovery?.scope_base;
|
|
395
|
+
if (typeof recoveryScope === "string" && SHA40_RE.test(recoveryScope)) {
|
|
396
|
+
this.#resumeScopeBase = recoveryScope;
|
|
397
|
+
}
|
|
398
|
+
const found = await this.#residue.findResumeResidue(
|
|
399
|
+
this.#root,
|
|
400
|
+
carrier,
|
|
401
|
+
this.#firstTask
|
|
402
|
+
);
|
|
403
|
+
if (found) {
|
|
404
|
+
if (await this.#residue.resumeFromResidue(this.#root, found.ref)) {
|
|
405
|
+
residueAppendix = this.#residue.appendixFromRecovery(carrier, found);
|
|
406
|
+
} else {
|
|
407
|
+
process.stderr.write(
|
|
408
|
+
`CDD_WARN: residue stash apply failed (${found.ref}) \u2014 dispatch continues from the clean baseline
|
|
409
|
+
`
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
} catch {
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
try {
|
|
418
|
+
mkdirSync(path.dirname(ctx.briefPath), { recursive: true });
|
|
419
|
+
await this.#briefRenderer.render(
|
|
420
|
+
planWorkspace.plan,
|
|
421
|
+
this.#tasks,
|
|
422
|
+
ctx.briefPath,
|
|
423
|
+
this.#root,
|
|
424
|
+
residueAppendix
|
|
425
|
+
);
|
|
426
|
+
} catch (e) {
|
|
427
|
+
throw new CddExitError(`brief generation failed: ${e.message}`, {
|
|
428
|
+
exitCode: 1,
|
|
429
|
+
kind: "run-blocked"
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
} catch (e) {
|
|
433
|
+
if (e instanceof CddExitError && e.kind === "run-blocked") {
|
|
434
|
+
this.#done(1, [], e.message);
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (e instanceof ExitRequested) {
|
|
438
|
+
this.#done(e.code, [], "");
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
throw e;
|
|
442
|
+
}
|
|
443
|
+
this.#tcx = ctx;
|
|
444
|
+
this.#handoff = new Handoff({
|
|
445
|
+
workspace: ctx.workspace,
|
|
446
|
+
phase: mode,
|
|
447
|
+
type: "task",
|
|
448
|
+
round: mode === "implement" ? void 0 : ctx.round,
|
|
449
|
+
params: { tasks: this.#groupKey }
|
|
450
|
+
});
|
|
451
|
+
this.ctx = { ...this.ctx, handoffPath: ctx.handoffPath };
|
|
452
|
+
try {
|
|
453
|
+
const tplDir = (pluginRootFn ?? this.#templates.pluginRoot)();
|
|
454
|
+
if (!existsSync(tplDir)) {
|
|
455
|
+
this.#done(1, [], `templates missing: ${tplDir}`);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
} catch {
|
|
459
|
+
this.#done(1, [], "templates missing: cdd-engine package root not found");
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const progressDir = path.dirname(ctx.ledgerPath);
|
|
463
|
+
if (mode === "review" || mode === "fix") {
|
|
464
|
+
if (!ctx.fixedPoint) {
|
|
465
|
+
const ledgerBase = this.#ledger.taskScopeBase(progressDir, this.#groupKey);
|
|
466
|
+
if (ledgerBase) {
|
|
467
|
+
ctx.fixedPoint = ledgerBase;
|
|
468
|
+
} else {
|
|
469
|
+
const prev = prevHandoffPath(ctx.workspace, this.#groupKey, mode, ctx.round ?? 1);
|
|
470
|
+
if (prev) {
|
|
471
|
+
const prevCommitsBase = readJsonField(prev, ["commits", "base"]);
|
|
472
|
+
if (prevCommitsBase && prevCommitsBase !== "unknown") {
|
|
473
|
+
ctx.fixedPoint = prevCommitsBase;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
if (this.#dryRun && !ctx.fixedPoint) ctx.fixedPoint = "HEAD~1";
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
/** Step 6: mode validation (implement / review / fix legal trio) + required-ctx completeness. */
|
|
482
|
+
async validateMode(_hookCtx) {
|
|
483
|
+
if (this.#finished) return;
|
|
484
|
+
const modeErr = validateModeMsg(this.#mode());
|
|
485
|
+
if (modeErr) {
|
|
486
|
+
this.#done(1, [], modeErr);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const missing = requireCtx(this.#tcx, this.#mode());
|
|
490
|
+
if (missing) {
|
|
491
|
+
this.#done(1, [], missing);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
/** Lane-declared doc-audit target (Task 3 ④): the task channel audits ITS dispatch plan — the
|
|
496
|
+
* base default docContractValidate walks the plan → `**Spec:**` → Parent program → overall chain,
|
|
497
|
+
* runs the necessary subset (plan 契約 + Class A) plus the overall 契約 + four tables when a
|
|
498
|
+
* parent overall resolves. null when the round already terminated pre-flight (a mode/cli/entry
|
|
499
|
+
* block that #done'd before the doc step wins its diagnostic — the audit never overrides a
|
|
500
|
+
* terminal). */
|
|
501
|
+
docAuditTarget() {
|
|
502
|
+
if (this.#finished) return null;
|
|
503
|
+
return this.#tcx?.plan ?? null;
|
|
504
|
+
}
|
|
505
|
+
/** Plan-bearing declaration (P2 T4): the task lane is ALWAYS plan-bearing — the closeout
|
|
506
|
+
* terminal-debt hard gate and the base-default statusValidate key off the dispatch plan. NOT
|
|
507
|
+
* #finished-gated: the pre-flight-terminated case is already handled by docAuditTarget's guard
|
|
508
|
+
* (the gate waives early on a finished round), while statusValidate runs AFTER the round
|
|
509
|
+
* #done'd — the report describes the tree the round just landed. */
|
|
510
|
+
dispatchPlanPath() {
|
|
511
|
+
return this.#tcx?.plan ?? null;
|
|
512
|
+
}
|
|
513
|
+
/** BLOCK face override (Task 3 ④): the task channel's non-throwing #done terminal — exit 1 +
|
|
514
|
+
* the CDD_BLOCKED diagnostic; no carrier is written (the doc-invalid round stays
|
|
515
|
+
* re-dispatchable the moment the docs are repaired — matching the pre-T3 face exactly). */
|
|
516
|
+
docContractBlocked(guidance) {
|
|
517
|
+
this.#done(
|
|
518
|
+
1,
|
|
519
|
+
[],
|
|
520
|
+
`doc contract validation failed \u2014 fix the docs below, then re-dispatch --tasks ${this.#groupKey}:
|
|
521
|
+
${guidance}`
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
// ---- dispatch ----
|
|
525
|
+
/** Steps 7/8/8.5: prompt render → agent CLI spawn (or dry-run simulation) → the timeout path
|
|
526
|
+
* (partial handoff + canonical counters). */
|
|
527
|
+
async dispatch(_hookCtx) {
|
|
528
|
+
if (this.#finished) return;
|
|
529
|
+
const mode = this.#mode();
|
|
530
|
+
const dryRun = this.#dryRun;
|
|
531
|
+
const ctx = this.#tcx;
|
|
532
|
+
const progressDir = path.dirname(ctx.ledgerPath);
|
|
533
|
+
let prompt;
|
|
534
|
+
try {
|
|
535
|
+
prompt = this.#templates.renderModePrompt(mode, buildPromptParams(ctx, this.#group));
|
|
536
|
+
} catch (e) {
|
|
537
|
+
this.#done(1, [], `template render failed: ${e.message}`);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
let agentOut = "";
|
|
541
|
+
let agentRc = 0;
|
|
542
|
+
let timedOut = false;
|
|
543
|
+
let unkillable = false;
|
|
544
|
+
let cause;
|
|
545
|
+
let idleWindowMs;
|
|
546
|
+
if (dryRun) {
|
|
547
|
+
agentOut = this.#returnBlockParser.dryRunBlock({
|
|
548
|
+
commits: "base=dry-run",
|
|
549
|
+
artifacts: `brief=${ctx.briefPath} report=${ctx.workspace}/tasks-${this.#groupKey}-report.md test_evidence=${ctx.workspace}/tasks-${this.#groupKey}-test-evidence.json`
|
|
550
|
+
});
|
|
551
|
+
} else {
|
|
552
|
+
const terminationCfg = this.#invoker.resolveTerminationConfig(
|
|
553
|
+
"task",
|
|
554
|
+
this.#opts.termination,
|
|
555
|
+
ctx.workspace
|
|
556
|
+
);
|
|
557
|
+
this.#timeoutMs = terminationCfg.budgetMs;
|
|
558
|
+
if (!existsSync(ctx.workspace)) {
|
|
559
|
+
process.stderr.write(
|
|
560
|
+
`CDD_WARN: termination progress path missing (${ctx.workspace}) \u2014 tree signal unavailable, stall detection relies on CPU alone
|
|
561
|
+
`
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
const res = await this.#invoker.invokeCliWithRetry(
|
|
565
|
+
this.#entry,
|
|
566
|
+
prompt,
|
|
567
|
+
INVOKE_PARAMS[mode] ?? { op: mode },
|
|
568
|
+
this.#hostEnv(),
|
|
569
|
+
this.#root,
|
|
570
|
+
terminationCfg
|
|
571
|
+
);
|
|
572
|
+
agentOut = res.ok ? res.stdout : "";
|
|
573
|
+
timedOut = res.timedOut === true;
|
|
574
|
+
unkillable = res.unkillable === true;
|
|
575
|
+
cause = res.cause;
|
|
576
|
+
idleWindowMs = terminationCfg.idleWindowMs;
|
|
577
|
+
if (!res.ok && !timedOut) agentRc = res.code;
|
|
578
|
+
}
|
|
579
|
+
this.#agentOut = agentOut;
|
|
580
|
+
this.#agentRc = agentRc;
|
|
581
|
+
if (timedOut) {
|
|
582
|
+
if (unkillable) {
|
|
583
|
+
writeBlockedCarrier(ctx.handoffPath, {
|
|
584
|
+
tasks: this.#tasks,
|
|
585
|
+
phase: mode,
|
|
586
|
+
failure_category: FAILURE_CATEGORIES.ENGINE_SELF_WRITTEN.id,
|
|
587
|
+
blocker: `cli process unkillable after timeout \u2192 manually kill the process (check ps), then re-dispatch --tasks ${this.#groupKey}`
|
|
588
|
+
});
|
|
589
|
+
if (!dryRun) {
|
|
590
|
+
this.#ledger.incrementRound(progressDir, this.#groupKey, mode);
|
|
591
|
+
this.#failure.maybeExhaust(
|
|
592
|
+
progressDir,
|
|
593
|
+
FAILURE_CATEGORIES.ENGINE_SELF_WRITTEN.id,
|
|
594
|
+
ctx.handoffPath
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
this.#done(
|
|
598
|
+
1,
|
|
599
|
+
this.#returnBlockParser.returnFromHandoff(ctx.handoffPath, ctx.workspace),
|
|
600
|
+
"process unkillable"
|
|
601
|
+
);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
const timeoutMs = this.#timeoutMs;
|
|
605
|
+
const recovery = mode === "implement" ? await this.#residue.settleResidue(this.#root, {
|
|
606
|
+
op: mode,
|
|
607
|
+
type: "task",
|
|
608
|
+
task: this.#firstTask,
|
|
609
|
+
round: ctx.round ?? 1,
|
|
610
|
+
cause: cause ?? "over-budget",
|
|
611
|
+
// The salvage captures the task-level scope anchor (ledger priority / fallback the
|
|
612
|
+
// dead-round brief TASK_BASE; T27) so the resume restores the same scope.
|
|
613
|
+
scopeBase: this.#ledger.taskScopeBase(progressDir, this.#groupKey) ?? taskBaseFromBrief(ctx.briefPath)
|
|
614
|
+
}) : { cause: FAILURE_CATEGORIES.TIMEOUT.id };
|
|
615
|
+
writeBlockedCarrier(ctx.handoffPath, {
|
|
616
|
+
tasks: this.#tasks,
|
|
617
|
+
phase: mode,
|
|
618
|
+
status: "TIMEOUT",
|
|
619
|
+
failure_category: FAILURE_CATEGORIES.TIMEOUT.id,
|
|
620
|
+
recovery: recovery ?? void 0,
|
|
621
|
+
// no salvage / review-fix lane → the termination sub-cause rides `notes` (the only archival
|
|
622
|
+
// channel when recovery.cause is the category id) so a dead round stays replayable by cause
|
|
623
|
+
notes: mode === "implement" ? void 0 : `termination cause: ${cause ?? "unknown"}`,
|
|
624
|
+
blocker: this.#failure.timeoutBlocker({
|
|
625
|
+
cause,
|
|
626
|
+
tasks: this.#groupKey,
|
|
627
|
+
timeoutMs,
|
|
628
|
+
idleWindowMs,
|
|
629
|
+
op: mode,
|
|
630
|
+
residue: recovery?.residue_ref ?? null
|
|
631
|
+
})
|
|
632
|
+
});
|
|
633
|
+
if (!dryRun) this.#ledger.incrementRound(progressDir, this.#groupKey, mode);
|
|
634
|
+
this.#failure.maybeExhaust(progressDir, FAILURE_CATEGORIES.TIMEOUT.id, ctx.handoffPath);
|
|
635
|
+
this.#done(
|
|
636
|
+
1,
|
|
637
|
+
this.#returnBlockParser.returnFromHandoff(ctx.handoffPath, ctx.workspace),
|
|
638
|
+
`cli terminated (cause: ${cause ?? "unknown"})`
|
|
639
|
+
);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
#hostEnv() {
|
|
644
|
+
return this.#opts.env ?? process.env;
|
|
645
|
+
}
|
|
646
|
+
// ---- post-flight ----
|
|
647
|
+
/** Steps 8.8/10/10.5: handoff schema recovery (CONTRACT_VIOLATION keeps findings) +
|
|
648
|
+
* failure-without-handoff BLOCKED writes. */
|
|
649
|
+
async schemaValidate(_hookCtx) {
|
|
650
|
+
if (this.#finished) return;
|
|
651
|
+
const mode = this.#mode();
|
|
652
|
+
const dryRun = this.#dryRun;
|
|
653
|
+
const ctx = this.#tcx;
|
|
654
|
+
const progressDir = path.dirname(ctx.ledgerPath);
|
|
655
|
+
if (mode !== "implement") {
|
|
656
|
+
const existingHandoff = readJson(ctx.handoffPath);
|
|
657
|
+
if (existingHandoff) {
|
|
658
|
+
const sv = this.#schema.validateHandoffSchema(existingHandoff);
|
|
659
|
+
if (!sv.valid) {
|
|
660
|
+
const rec = recoverHandoff(existingHandoff, "task");
|
|
661
|
+
if (rec.valid) {
|
|
662
|
+
writeOwnHandoff(ctx.handoffPath, rec.handoff);
|
|
663
|
+
} else {
|
|
664
|
+
writeBlockedCarrier(ctx.handoffPath, {
|
|
665
|
+
tasks: this.#tasks,
|
|
666
|
+
phase: mode,
|
|
667
|
+
failure_category: FAILURE_CATEGORIES.CONTRACT_VIOLATION.id,
|
|
668
|
+
findings: rec.preservedFindings,
|
|
669
|
+
blocker: `handoff schema invalid${rec.reason} \u2192 fix the handoff JSON at ${ctx.handoffPath} and re-dispatch --tasks ${this.#groupKey}`,
|
|
670
|
+
fullReplace: true
|
|
671
|
+
});
|
|
672
|
+
if (!dryRun) {
|
|
673
|
+
this.#ledger.incrementRound(progressDir, this.#groupKey, mode);
|
|
674
|
+
this.#failure.maybeExhaust(
|
|
675
|
+
progressDir,
|
|
676
|
+
FAILURE_CATEGORIES.CONTRACT_VIOLATION.id,
|
|
677
|
+
ctx.handoffPath
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
this.#done(
|
|
681
|
+
1,
|
|
682
|
+
this.#returnBlockParser.returnFromHandoff(ctx.handoffPath, ctx.workspace),
|
|
683
|
+
`schema validation failed${rec.reason}`
|
|
684
|
+
);
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
if (this.#agentRc !== 0 && !existsSync(ctx.handoffPath)) {
|
|
691
|
+
const recovery = mode === "implement" ? await this.#residue.settleResidue(this.#root, {
|
|
692
|
+
op: mode,
|
|
693
|
+
type: "task",
|
|
694
|
+
task: this.#firstTask,
|
|
695
|
+
round: ctx.round ?? 1,
|
|
696
|
+
cause: "exec-failure",
|
|
697
|
+
// Same scope-anchor capture as the TIMEOUT salvage lane (T27).
|
|
698
|
+
scopeBase: this.#ledger.taskScopeBase(progressDir, this.#groupKey) ?? taskBaseFromBrief(ctx.briefPath)
|
|
699
|
+
}) : (
|
|
700
|
+
// Review/fix EXECUTION_FAILURE death diagnosis rides the carrier (T25): cause = the category
|
|
701
|
+
// id — the preserve eligibility key + exit code distinguishing exit 1 vs 143. The base
|
|
702
|
+
// settleResidue step stashes the dirty-tree WIP afterwards, filling residue_ref/wip_stat/
|
|
703
|
+
// preserved.
|
|
704
|
+
{ cause: FAILURE_CATEGORIES.EXECUTION_FAILURE.id, exit_code: this.#agentRc }
|
|
705
|
+
);
|
|
706
|
+
writeBlockedCarrier(ctx.handoffPath, {
|
|
707
|
+
tasks: this.#tasks,
|
|
708
|
+
phase: mode,
|
|
709
|
+
failure_category: FAILURE_CATEGORIES.EXECUTION_FAILURE.id,
|
|
710
|
+
commits: { base: "unknown" },
|
|
711
|
+
// no real head at failure time — the "unknown" sentinel is the EXECUTION_FAILURE ground (T23)
|
|
712
|
+
recovery: recovery ?? void 0,
|
|
713
|
+
blocker: `cli exited ${this.#agentRc}${this.#agentRc === 143 ? " (SIGTERM \u2014 externally killed)" : ""} without writing handoff \u2192 check stderr above for errors; ` + (`residue_ref` in (recovery ?? {}) ? `WIP salvaged (recovery.residue_ref=${recovery.residue_ref}) \u2014 ` : "") + (mode === "implement" ? `resume or discard: cdd implement --tasks ${this.#groupKey} re-dispatch auto-resumes (recovery.residue_ref), or git stash drop to abandon` : `worktree residue (if any) is preserved as a stash \u2014 \`git stash list\` to find the snapshot, \`git stash apply <ref>\` + review to salvage (then commit) or \`git stash drop\` to discard, then re-dispatch cdd ${mode} --tasks ${this.#groupKey}`)
|
|
714
|
+
});
|
|
715
|
+
if (!dryRun) {
|
|
716
|
+
this.#ledger.incrementRound(progressDir, this.#groupKey, mode);
|
|
717
|
+
this.#ledger.incrementRecovery(progressDir);
|
|
718
|
+
}
|
|
719
|
+
this.#done(
|
|
720
|
+
1,
|
|
721
|
+
this.#returnBlockParser.returnFromHandoff(ctx.handoffPath, ctx.workspace),
|
|
722
|
+
`cli exited ${this.#agentRc} and handoff missing`
|
|
723
|
+
);
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (this.#agentRc === 0 && !dryRun && mode !== "implement" && !existsSync(ctx.handoffPath)) {
|
|
727
|
+
writeBlockedCarrier(ctx.handoffPath, {
|
|
728
|
+
tasks: this.#tasks,
|
|
729
|
+
phase: mode,
|
|
730
|
+
failure_category: FAILURE_CATEGORIES.ENGINE_SELF_WRITTEN.id,
|
|
731
|
+
blocker: `${path.basename(ctx.handoffPath)} not written after exit 0 \u2192 re-run ${mode} and ensure handoff is written to ${ctx.handoffPath} before exit`
|
|
732
|
+
});
|
|
733
|
+
this.#ledger.incrementRound(progressDir, this.#groupKey, mode);
|
|
734
|
+
this.#failure.maybeExhaust(
|
|
735
|
+
progressDir,
|
|
736
|
+
FAILURE_CATEGORIES.ENGINE_SELF_WRITTEN.id,
|
|
737
|
+
ctx.handoffPath
|
|
738
|
+
);
|
|
739
|
+
this.#done(
|
|
740
|
+
1,
|
|
741
|
+
this.#returnBlockParser.returnFromHandoff(ctx.handoffPath, ctx.workspace),
|
|
742
|
+
`${mode} agent did not write handoff`
|
|
743
|
+
);
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/** Steps 11/12/13: return block four-line parse → agent-failure exit → implement materialization
|
|
748
|
+
* (dry-run writes no handoff — aligned with bash). */
|
|
749
|
+
async normalizeResult(_hookCtx) {
|
|
750
|
+
if (this.#finished) return;
|
|
751
|
+
const mode = this.#mode();
|
|
752
|
+
const dryRun = this.#dryRun;
|
|
753
|
+
const ctx = this.#tcx;
|
|
754
|
+
const progressDir = path.dirname(ctx.ledgerPath);
|
|
755
|
+
let returnBlock = this.#returnBlockParser.returnFourLines(this.#agentOut, ctx.workspace);
|
|
756
|
+
if (this.#agentRc !== 0) {
|
|
757
|
+
this.#done(this.#agentRc, returnBlock, "");
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
if (!dryRun && mode === "implement") {
|
|
761
|
+
const finalized = await this.#handoff.finalize({
|
|
762
|
+
mode,
|
|
763
|
+
returnBlock,
|
|
764
|
+
brief: ctx.briefPath,
|
|
765
|
+
repoRoot: this.#root,
|
|
766
|
+
tasks: this.#tasks,
|
|
767
|
+
resumeScopeBase: this.#resumeScopeBase
|
|
768
|
+
});
|
|
769
|
+
if (finalized.handoff) {
|
|
770
|
+
this.#handoff.persist(finalized.handoff);
|
|
771
|
+
returnBlock = this.#returnBlockParser.returnFromHandoff(ctx.handoffPath, ctx.workspace);
|
|
772
|
+
if (finalized.exitCode !== 0) {
|
|
773
|
+
this.#failure.maybeExhaust(
|
|
774
|
+
progressDir,
|
|
775
|
+
FAILURE_CATEGORIES.ENGINE_SELF_WRITTEN.id,
|
|
776
|
+
ctx.handoffPath
|
|
777
|
+
);
|
|
778
|
+
this.#done(finalized.exitCode, returnBlock, "");
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
this.#returnBlock = returnBlock;
|
|
784
|
+
}
|
|
785
|
+
/** Step 13.5 + post-gate writeback: the exit gate (validateCommitContract) runs for every
|
|
786
|
+
* non-finished non-dry-run round; after it passes, the APPROVED-review ensure-row writeback +
|
|
787
|
+
* non-implement round increment land (a dirty failure round never touches the row; the complete
|
|
788
|
+
* verdict is deriveTaskState's — the row keeps only facts). */
|
|
789
|
+
async commitPostCheck(_hookCtx) {
|
|
790
|
+
if (this.#finished) return;
|
|
791
|
+
const mode = this.#mode();
|
|
792
|
+
const dryRun = this.#dryRun;
|
|
793
|
+
const ctx = this.#tcx;
|
|
794
|
+
const progressDir = path.dirname(ctx.ledgerPath);
|
|
795
|
+
if (!dryRun) {
|
|
796
|
+
const cv = await this.#commit.validateCommitContract(mode, this.#root, {
|
|
797
|
+
handoffPath: ctx.handoffPath
|
|
798
|
+
});
|
|
799
|
+
if (!cv.ok) {
|
|
800
|
+
this.#failure.maybeExhaust(
|
|
801
|
+
progressDir,
|
|
802
|
+
FAILURE_CATEGORIES.ENGINE_SELF_WRITTEN.id,
|
|
803
|
+
ctx.handoffPath
|
|
804
|
+
);
|
|
805
|
+
this.#done(
|
|
806
|
+
1,
|
|
807
|
+
this.#returnBlockParser.returnFromHandoff(ctx.handoffPath, ctx.workspace),
|
|
808
|
+
cv.blocker
|
|
809
|
+
);
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
let finalized = null;
|
|
814
|
+
if (!dryRun && (mode === "review" || mode === "fix")) {
|
|
815
|
+
const handoff = readJson(ctx.handoffPath);
|
|
816
|
+
if (handoff) {
|
|
817
|
+
finalized = await this.#handoff.finalize({ mode, agentHandoff: handoff });
|
|
818
|
+
persistFinalized(ctx.handoffPath, handoff, finalized);
|
|
819
|
+
this.#returnBlock = this.#returnBlockParser.returnFromHandoff(
|
|
820
|
+
ctx.handoffPath,
|
|
821
|
+
ctx.workspace
|
|
822
|
+
);
|
|
823
|
+
if (mode === "review" && normalizeHandoffStatus(handoff.status) === "APPROVED") {
|
|
824
|
+
const progressData2 = this.#ledger.read(progressDir);
|
|
825
|
+
let taskEntry = this.#ledger.rowFor(progressData2, this.#groupKey);
|
|
826
|
+
if (!taskEntry) {
|
|
827
|
+
taskEntry = this.#ledger.entryFor(this.#groupKey);
|
|
828
|
+
progressData2.tasks.push(taskEntry);
|
|
829
|
+
}
|
|
830
|
+
this.#ledger.write(progressDir, progressData2);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
if (!dryRun && mode !== "implement")
|
|
835
|
+
this.#ledger.incrementRound(progressDir, this.#groupKey, mode);
|
|
836
|
+
this.#done(finalized?.exitCode ?? 0, this.#returnBlock, "");
|
|
837
|
+
}
|
|
838
|
+
/** runTask — legacy surface kept ({ exitCode, returnBlock }; noExit=true suppresses the stdout/stderr +
|
|
839
|
+
* exit-throw: the unit-test seam) as the class's STATIC entry (Task 6/7 export-surface reshuffle:
|
|
840
|
+
* `runTask` → `TaskLifecycle.run` — the class public face, no bare forwarding shell). Builds the
|
|
841
|
+
* injected ctx via buildContext, runs the lifecycle, converts an entry-gate DispatchBlocked into a
|
|
842
|
+
* CDD_BLOCKED stderr + exit 1 (or a { exitCode: 1, returnBlock: [] } in noExit mode); on the normal
|
|
843
|
+
* path writes the diagnostic + return block lines + exits via exitWithCode when noExit=false.
|
|
844
|
+
* P4.3/P4.4: `tasks` is the dispatch GROUP (scalar task number / list normalized to a TaskGroup
|
|
845
|
+
* at this boundary) — the group is the dispatch unit, never a per-task iteration. */
|
|
846
|
+
static async run(harness, tasks, opts = {}) {
|
|
847
|
+
const rt = opts.runtime ?? runtime;
|
|
848
|
+
return rt.withLifecycle(async () => {
|
|
849
|
+
const root = opts.root ?? rt.getRoot();
|
|
850
|
+
const group = toTaskGroup(tasks);
|
|
851
|
+
const lc = new TaskLifecycle({
|
|
852
|
+
harness,
|
|
853
|
+
group,
|
|
854
|
+
opts,
|
|
855
|
+
ctx: {
|
|
856
|
+
mode: opts.mode ?? "",
|
|
857
|
+
repoRoot: root,
|
|
858
|
+
handoffPath: "",
|
|
859
|
+
dryRun: opts.dryRun === true || rt.isDryRun()
|
|
860
|
+
}
|
|
861
|
+
});
|
|
862
|
+
try {
|
|
863
|
+
await lc.run();
|
|
864
|
+
} catch (e) {
|
|
865
|
+
if (e instanceof DispatchBlocked && e.gate === "entry") {
|
|
866
|
+
if (opts.noExit) return { exitCode: 1, returnBlock: [] };
|
|
867
|
+
process.stderr.write(`CDD_BLOCKED: ${e.message}
|
|
868
|
+
`);
|
|
869
|
+
exitWithCode(1);
|
|
870
|
+
}
|
|
871
|
+
throw e;
|
|
872
|
+
}
|
|
873
|
+
const { exitCode, returnBlock } = lc.result;
|
|
874
|
+
const diag = lc.diagnostic;
|
|
875
|
+
if (!opts.noExit) {
|
|
876
|
+
if (diag) process.stderr.write(`${diag.prefix}: ${diag.msg}
|
|
877
|
+
`);
|
|
878
|
+
for (const line of returnBlock) process.stdout.write(`${line}
|
|
879
|
+
`);
|
|
880
|
+
exitWithCode(exitCode);
|
|
881
|
+
}
|
|
882
|
+
return { exitCode, returnBlock };
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
const PLAN_CONSTRAINTS_FILE = "plan-constraints.md";
|
|
887
|
+
const PLAN_CONSTRAINTS_MISSING_BLOCKER = "plan-constraints.md missing \u2014 run materializer or declare a plan Constraints source";
|
|
888
|
+
const PROSE_ANCHORS = DOC_TOKENS.proseAnchors;
|
|
889
|
+
class ConstraintsSourceUndeclared extends CddExitError {
|
|
890
|
+
constructor(message) {
|
|
891
|
+
super(message, { exitCode: 1, kind: "run-blocked" });
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
function constraintsHeader(planPath, hash) {
|
|
895
|
+
return [
|
|
896
|
+
`<!-- ${PLAN_CONSTRAINTS_FILE} \u2014 CDD workspace artifact derived from the plan's declared Constraints source. Do not edit. -->`,
|
|
897
|
+
`<!-- source plan: ${path.basename(planPath)} \xB7 plan hash: ${hash} -->`,
|
|
898
|
+
""
|
|
899
|
+
].join("\n");
|
|
900
|
+
}
|
|
901
|
+
function materializePlanConstraints(plan, workspace) {
|
|
902
|
+
const outPath = path.join(workspace, PLAN_CONSTRAINTS_FILE);
|
|
903
|
+
const content = new DocumentsValidator().extractPlanConstraints(readFileSync(plan, "utf8"));
|
|
904
|
+
if (content === null) {
|
|
905
|
+
throw new ConstraintsSourceUndeclared(
|
|
906
|
+
`plan Constraints source undeclared \u2014 declare a literal \u201C${DOC_TOKENS.constraintsHeading}\u201D section (canonical) or the prose pointer headings (${PROSE_ANCHORS.join(" / ")}) so cdd implement can materialize ${PLAN_CONSTRAINTS_FILE}`
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
writeFileSync(outPath, constraintsHeader(plan, hashFile(plan)) + content, "utf8");
|
|
910
|
+
return outPath;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
export { ConstraintsSourceUndeclared, TaskLifecycle, buildPromptParams, materializePlanConstraints, resolvePlanWorkspace };
|