@oscaner-skills/cdd-engine 4.1.0 → 4.3.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.
Files changed (59) hide show
  1. package/README.md +39 -9
  2. package/README.zh-CN.md +44 -9
  3. package/dist/contract/completion-criterion.js +351 -0
  4. package/dist/contract/declare.js +181 -43
  5. package/dist/contract/doc.js +84 -271
  6. package/dist/contract/frontmatter.js +2 -1
  7. package/dist/contract/home-extractors.js +49 -316
  8. package/dist/contract/invariants.js +400 -296
  9. package/dist/contract/judge.js +74 -49
  10. package/dist/contract/lint.js +3 -2
  11. package/dist/contract/liveness-signal.js +103 -0
  12. package/dist/contract/markdown-document.js +410 -0
  13. package/dist/contract/markdown-tree-types.js +6 -0
  14. package/dist/contract/markdown-tree.js +137 -0
  15. package/dist/contract/project.js +1 -1
  16. package/dist/contract/rules.js +106 -0
  17. package/dist/contract/selector-engine.js +332 -0
  18. package/dist/contract/selector-spec.js +74 -0
  19. package/dist/contract/skill-anatomy.js +29 -1
  20. package/dist/contract/task-block-grammar.js +285 -0
  21. package/dist/contract/task-blocks.js +65 -0
  22. package/dist/contract/translate.js +21 -0
  23. package/dist/contract/wave-width.js +15 -0
  24. package/dist/face/board-view.js +401 -131
  25. package/dist/face/capsule.js +66 -89
  26. package/dist/face/cli.js +174 -48
  27. package/dist/face/declare.js +59 -23
  28. package/dist/face/gate.js +117 -40
  29. package/dist/face/host.js +9 -35
  30. package/dist/face/init.js +108 -0
  31. package/dist/face/lifecycle.js +540 -123
  32. package/dist/face/plugins.js +73 -0
  33. package/dist/face/preview.js +43 -10
  34. package/dist/face/projection.js +3 -3
  35. package/dist/face/route-render.js +51 -21
  36. package/dist/face/termination.js +135 -261
  37. package/dist/face/words.js +134 -12
  38. package/dist/infra/atomic.js +15 -0
  39. package/dist/infra/git.js +25 -0
  40. package/dist/infra/proc.js +150 -0
  41. package/dist/infra/round-log.js +104 -0
  42. package/dist/infra/runtime.js +16 -4
  43. package/dist/infra/workspace.js +7 -2
  44. package/dist/render/brief.js +15 -17
  45. package/dist/render/skeleton.js +41 -28
  46. package/dist/render/templates.js +128 -84
  47. package/dist/session/faces.js +47 -20
  48. package/dist/session/graph.js +13 -37
  49. package/dist/session/handoff-schema.js +16 -8
  50. package/dist/session/inflight.js +282 -0
  51. package/dist/session/ledger.js +581 -136
  52. package/dist/session/line-identity.js +33 -0
  53. package/dist/session/next.js +138 -80
  54. package/dist/session/preflight.js +276 -68
  55. package/dist/session/round-naming.js +56 -8
  56. package/dist/session/run.js +317 -78
  57. package/dist/session/wave.js +94 -14
  58. package/package.json +13 -3
  59. package/dist/infra/process.js +0 -22
@@ -41,11 +41,12 @@ const FINDING = {
41
41
  fix: { type: "string" },
42
42
  },
43
43
  };
44
- /** The ONE carrier declaration — the four child-writable slots. DECLARATION ORDER IS
44
+ /** The ONE carrier declaration — the five child-writable slots. DECLARATION ORDER IS
45
45
  * PROJECTION ORDER: `#writable(plane)` filters these properties in this order, so the
46
- * judge fence keeps its `findings` · `artifacts` · `notes` byte order. Reserved
47
- * fields (phase · tasks) are NOT declared and are DROPPED by materialize (never a
48
- * BLOCK) — the engine stays the carrier's single author.
46
+ * judge fence keeps its `findings` · `artifacts` · `notes` byte order and the work
47
+ * fence appends `dispositions` after its long-standing three. Reserved fields
48
+ * (phase · tasks) are NOT declared and are DROPPED by materialize (never a BLOCK) —
49
+ * the engine stays the carrier's single author.
49
50
  * `as const` preserves the literal property keys — the `Carrier` type family below
50
51
  * derives its field set FROM these declared keys. */
51
52
  const CARRIER = {
@@ -55,20 +56,27 @@ const CARRIER = {
55
56
  findings: { type: "array", items: FINDING },
56
57
  artifacts: { type: "object" },
57
58
  notes: { type: "array", items: { type: "string" } },
59
+ // The fix round's per-finding dispositions (design spec §3.4) — a WORK carrier
60
+ // slot whose keys are the requesting review carrier's finding summaries verbatim.
61
+ // Declared as a bare object: the key set is data (the summaries), never a fixed
62
+ // property table — the fix criterion judges the value shape, the schema the slot's.
63
+ dispositions: { type: "object" },
58
64
  },
59
65
  };
60
66
  /** The plane → writable slot table — the ONE projection source (`#writable`) the
61
67
  * prompt fence, the read-back validator and the dropped-key walk all read. The
62
- * shared slots (artifacts · notes) are both-plane by design; the exclusive slot IS
63
- * the plane (`status` for work, `findings` for judge). */
68
+ * shared slots (artifacts · notes) are both-plane by design; the exclusive slots ARE
69
+ * the plane (`status` + `dispositions` for work, `findings` for judge). */
64
70
  const PLANE_SLOTS = {
65
- work: ["status", "artifacts", "notes"],
71
+ work: ["status", "artifacts", "notes", "dispositions"],
66
72
  judge: ["findings", "artifacts", "notes"],
67
73
  };
68
74
  /** The plane → required slot table. The work plane's round conclusion is the child's
69
75
  * own declared status, so status + artifacts are the required core. The judge plane
70
76
  * requires the findings its conclusion rolls up from; artifacts / notes ride as
71
- * declared optional slots (a review writes only what it has). */
77
+ * declared optional slots (a review writes only what it has). `dispositions` stays
78
+ * OPTIONAL on the work plane: its absence is the fix criterion's own hard refusal,
79
+ * so `implement` is never asked to declare it. */
72
80
  const PLANE_REQUIRED = {
73
81
  work: ["status", "artifacts"],
74
82
  judge: ["findings"],
@@ -0,0 +1,282 @@
1
+ // packages/cdd-engine/src-next/session/inflight.ts
2
+ // P21 §2.2 — the ONE in-flight fact of a work tree. A dispatch publishes its intent
3
+ // record BEFORE it spawns the child, overwrites the sampling trail through the same
4
+ // class while it runs, and releases it when the round finishes normally. The record
5
+ // is the only truth of "a dispatch is running" (the lock is only the mutual
6
+ // exclusion; gate/report judgments read the RECORD and the holder's liveness, never
7
+ // whether the lock is held):
8
+ //
9
+ // · the record lives at the workspace-root level (`.kairos/cdd/in-flight.json` under
10
+ // the default configuration) — the tree, not a slug, is the collision domain, so a
11
+ // second dispatch of ANY slug is refused while a live record stands;
12
+ // · the write order is fixed: publish the namespace keep-out marker → (the flag's
13
+ // takeover) → the live-holder guard → take the lock (`proper-lockfile`) → only then
14
+ // write the record. The guard is this class's own fail-closed check on a standing
15
+ // record (the pre-flight gate is the primary one), so a second write point cannot
16
+ // skip the protection. A failed lock leaves the record bytes untouched: a challenger
17
+ // never overwrites a live holder's facts;
18
+ // · no exit path removes the record — a crash / kill / timeout leaves it behind as
19
+ // the postmortem fact. Only `release()` (the normal end) and `steal()` (the
20
+ // explicit takeover) remove it. `proper-lockfile` drops the lock on any graceful
21
+ // exit and leaves it only on SIGKILL, which is why the lock is never the criterion;
22
+ // · the survival judgment is `ProcessFacts.live`: the record's pid + start time
23
+ // against the process table. The recorded instant is the pid's OWN start time (a
24
+ // record written hours into a session still describes the same process), since the
25
+ // tolerance compares two start times, never a start time against a dispatch. An
26
+ // UNREADABLE start time (the tool's `null`) folds to "alive" here — a takeover
27
+ // must never be authorized by a fact that could not be read — but a pid-reuse (a
28
+ // start time far from the recorded one) is "dead".
29
+ //
30
+ // Module-level exports are types / the error class / the class — zero
31
+ // behavior-carrying bare functions.
32
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
33
+ import path from "node:path";
34
+ import lockfile from "proper-lockfile";
35
+ import { AtomicWriter } from "../infra/atomic.js";
36
+ import { ProcessFacts } from "../infra/proc.js";
37
+ /** The acquire refusal — another dispatch holds the record (or the lock) already. The
38
+ * carrier keeps the holder's facts so the CLI renders the held BLOCK from them; a
39
+ * corrupt record yields a null `record`. */
40
+ export class HoldingError extends Error {
41
+ /** The holder's record (null when the record was present but unreadable). */
42
+ record;
43
+ constructor(message, record) {
44
+ super(message);
45
+ this.name = "HoldingError";
46
+ this.record = record;
47
+ }
48
+ }
49
+ /**
50
+ * InFlight — one workspace root's in-flight record, lock and sampling trail. The
51
+ * instance is bound to `<workspaceRoot>` + the dispatching slug; every path derives
52
+ * from the root, so the lock and the record always share one directory.
53
+ */
54
+ export class InFlight {
55
+ /** The record's file name inside the workspace-root namespace — the tree-level
56
+ * `.kairos/cdd/in-flight.json` under the default configuration. */
57
+ static FILE = "in-flight.json";
58
+ /** The lock's stale window (ms) — a FINITE value larger than the longest dispatch
59
+ * budget (implement, 6 h). Finiteness is deliberate: `stale: Infinity` pushes the
60
+ * default `update` to `Infinity`, which Node clamps to 1 ms of lock-touch churn
61
+ * for the whole dispatch. "Never steal automatically" is guaranteed by the record
62
+ * + pid criterion below, never by the lock's duration. */
63
+ static LOCK_STALE_MS = 12 * 60 * 60 * 1000;
64
+ /** The lock's refresh interval (ms). */
65
+ static LOCK_UPDATE_MS = 60 * 1000;
66
+ #root;
67
+ #slug;
68
+ #liveness;
69
+ #atomic = new AtomicWriter();
70
+ /** The held lock's release function — present exactly between acquire and release. */
71
+ #unlock = null;
72
+ constructor(root, slug, liveness = ProcessFacts) {
73
+ this.#root = root;
74
+ this.#slug = slug;
75
+ this.#liveness = liveness;
76
+ }
77
+ /** The record's absolute path (`<workspaceRoot>/in-flight.json`). */
78
+ path() {
79
+ return path.join(this.#root.path, InFlight.FILE);
80
+ }
81
+ /** The lock directory's absolute path (`proper-lockfile`'s default carrier). */
82
+ lockPath() {
83
+ return `${this.path()}.lock`;
84
+ }
85
+ /** Publish the namespace keep-out marker (`<namespace>/.gitignore` = `*`) — the
86
+ * PRECONDITION of the record's first write, so a fresh namespace killed before
87
+ * `WorkspaceRoot.ensure()` never leaves untracked in-flight artifacts behind. The
88
+ * marker itself is the root's single implementation (`WorkspaceRoot.ensure`): this
89
+ * class decides WHEN it must be published, never re-implements its bytes. */
90
+ ensureMarker() {
91
+ this.#root.ensure();
92
+ return this;
93
+ }
94
+ /** Take the record — the ONLY write point of a real dispatch (the gates read
95
+ * `inspect()`, they never call this). The order is fixed: marker → (flag's takeover)
96
+ * → live-holder guard → lock → record. The guard is the class's OWN fail-closed
97
+ * check that a standing record is never displaced while its holder lives: the
98
+ * pre-flight gate is the primary guard, this one keeps the invariant true for any
99
+ * other write point. `stealStale` only acts HERE: a standing record whose holder is
100
+ * dead (or a corrupt record with a leftover lock) is taken over first; a live holder
101
+ * is never displaced. A failed lock throws `HoldingError` carrying the holder's
102
+ * facts and leaves the record bytes untouched. */
103
+ async acquire(record, options = {}) {
104
+ this.ensureMarker();
105
+ if (options.stealStale === true)
106
+ await this.#stealIfDead();
107
+ await this.#refuseLiveHolder();
108
+ try {
109
+ this.#unlock = await lockfile.lock(this.path(), {
110
+ stale: InFlight.LOCK_STALE_MS,
111
+ update: InFlight.LOCK_UPDATE_MS,
112
+ realpath: false,
113
+ retries: 0,
114
+ });
115
+ }
116
+ catch {
117
+ // The lock is held: READ the standing record (zero write) so the refusal names
118
+ // the live holder instead of a mystery lock.
119
+ const state = await this.inspect();
120
+ const holder = state.kind === "held" ? state.record : null;
121
+ throw new HoldingError(this.#holdingMessage(holder), holder);
122
+ }
123
+ this.#writeRecord(record);
124
+ }
125
+ /** The live-holder guard — refuse a standing record whose holder is alive (or whose
126
+ * liveness cannot be read, which folds to alive), BEFORE the lock is taken: zero
127
+ * write, zero lock left behind. A record proven dead is displaced (the lock was
128
+ * free, so this dispatch is the tree's next legitimate holder); a corrupt record
129
+ * carries no live fact to honor and is displaced too — refusing there would wedge
130
+ * the tree for good, since nothing else clears an unlocked corrupt record. */
131
+ async #refuseLiveHolder() {
132
+ const state = await this.inspect();
133
+ if (state.kind !== "held" || !state.alive)
134
+ return;
135
+ throw new HoldingError(this.#holdingMessage(state.record), state.record);
136
+ }
137
+ /** Overwrite the running dispatch's sampling cells — the identity fields stay
138
+ * untouched. Fail-open on both sides: a missing/corrupt record (the record was
139
+ * taken over, or the sampler outlived it) is skipped, never fabricated into a new
140
+ * record, and a failed WRITE is swallowed too — the trail is a diagnostic, so an
141
+ * unwritable namespace neither aborts a dispatch whose child is already spawned nor
142
+ * throws inside the sampler's interval. `acquire()` keeps its write loud: a lock
143
+ * taken without a record standing behind it would break the invariant. */
144
+ heartbeat(sample) {
145
+ const current = this.#readRecord();
146
+ if (current === null)
147
+ return;
148
+ try {
149
+ this.#writeRecord({ ...current, sampledAt: sample.sampledAt, verdict: sample.verdict });
150
+ }
151
+ catch {
152
+ // Fail-open: the next tick retries, and the record's identity fields still
153
+ // describe the holder — a lost sample is never a lost dispatch.
154
+ }
155
+ }
156
+ /** Release the record at the normal end — the reverse of acquire: delete the record,
157
+ * then drop the lock. One of the only two removal paths (the other is `steal`). */
158
+ async release() {
159
+ try {
160
+ rmSync(this.path(), { force: true });
161
+ }
162
+ catch {
163
+ // Fail-open: an unremovable record is still the truthful postmortem fact.
164
+ }
165
+ const unlock = this.#unlock;
166
+ this.#unlock = null;
167
+ if (unlock !== null) {
168
+ try {
169
+ await unlock();
170
+ }
171
+ catch {
172
+ // The library's own exit hook removes it as well; never throw on cleanup.
173
+ }
174
+ }
175
+ }
176
+ /** Judge the tree NOW — the three-state read every gate and report face shares.
177
+ * `held.alive` is `ProcessFacts.live` verbatim, except that its `null` (an
178
+ * unreadable start time) folds to `true`: refusing a takeover on a fact that could
179
+ * not be read is the safe direction (a false "alive" only delays a takeover). */
180
+ async inspect() {
181
+ const record = this.#readRecord();
182
+ if (record !== null) {
183
+ const alive = await this.#liveness.live(record.pid, record.startedAt);
184
+ return { kind: "held", record, alive: alive ?? true };
185
+ }
186
+ if (!existsSync(this.path()))
187
+ return { kind: "absent" };
188
+ return { kind: "corrupt", locked: existsSync(this.lockPath()) };
189
+ }
190
+ /** Take the record over explicitly — the `--steal-stale` path. The precondition is
191
+ * that the holder cannot be alive: a readable record whose pid is live is refused
192
+ * (the flag never crosses "alive → no takeover"); a corrupt record has no live
193
+ * fact to honor and is cleared. Clears the lock, then the record. */
194
+ async steal(reason) {
195
+ const record = this.#readRecord();
196
+ if (record !== null) {
197
+ const alive = await this.#liveness.live(record.pid, record.startedAt);
198
+ if ((alive ?? true) === true) {
199
+ throw new Error(`refusing to steal the in-flight record (${reason}): pid ${record.pid} is alive`);
200
+ }
201
+ }
202
+ try {
203
+ rmSync(this.lockPath(), { recursive: true, force: true });
204
+ }
205
+ catch {
206
+ // Fail-open: the record removal below is the takeover's real effect.
207
+ }
208
+ if (existsSync(this.path()))
209
+ rmSync(this.path(), { force: true });
210
+ return record;
211
+ }
212
+ /** The `stealStale` pre-step of acquire: take over a standing record whose holder is
213
+ * dead, a corrupt record with a leftover lock, or a lock remnant with no record —
214
+ * and do nothing while the holder is alive (the lock then refuses the acquire). */
215
+ async #stealIfDead() {
216
+ const state = await this.inspect();
217
+ if (state.kind === "held" && !state.alive) {
218
+ await this.steal("the holder is dead");
219
+ return;
220
+ }
221
+ if (state.kind === "corrupt" && state.locked) {
222
+ await this.steal("the record is corrupt and the lock is left behind");
223
+ return;
224
+ }
225
+ if (state.kind === "absent" && existsSync(this.lockPath())) {
226
+ await this.steal("a lock without a record");
227
+ }
228
+ }
229
+ /** The refusal message — the holder's identity facts as plain text (the words
230
+ * table owns the CLI's held report; this is the thrown carrier's own summary). */
231
+ #holdingMessage(holder) {
232
+ if (holder === null) {
233
+ return `another dispatch holds the in-flight lock under ${this.#root.path} — the standing record is unreadable (dispatch ${this.#slug} refuses to overwrite it)`;
234
+ }
235
+ return `another dispatch is in flight: pid ${holder.pid} (${holder.command}), slug ${holder.slug}, started ${new Date(holder.startedAt).toISOString()} — it must finish, or its record must be taken over with --steal-stale`;
236
+ }
237
+ /** The record write — the JSON shape through the ONE atomic write seam, with the
238
+ * repo's single trailing newline. */
239
+ #writeRecord(record) {
240
+ mkdirSync(this.#root.path, { recursive: true });
241
+ this.#atomic.write(this.path(), `${JSON.stringify(record, null, 2)}\n`);
242
+ }
243
+ /** Read the record — null on an absent OR unreadable/invalid file (the caller's
244
+ * `existsSync` tells the two apart for the corrupt state). */
245
+ #readRecord() {
246
+ let text;
247
+ try {
248
+ text = readFileSync(this.path(), "utf8");
249
+ }
250
+ catch {
251
+ return null;
252
+ }
253
+ let value;
254
+ try {
255
+ value = JSON.parse(text);
256
+ }
257
+ catch {
258
+ return null;
259
+ }
260
+ if (value === null || typeof value !== "object")
261
+ return null;
262
+ const row = value;
263
+ if (typeof row.pid !== "number" || typeof row.startedAt !== "number")
264
+ return null;
265
+ if (typeof row.command !== "string" || typeof row.slug !== "string")
266
+ return null;
267
+ return {
268
+ pid: row.pid,
269
+ command: row.command,
270
+ slug: row.slug,
271
+ startedAt: row.startedAt,
272
+ wave: typeof row.wave === "string" ? row.wave : null,
273
+ phase: typeof row.phase === "string" ? row.phase : null,
274
+ cycle: typeof row.cycle === "number" ? row.cycle : null,
275
+ attempt: typeof row.attempt === "number" ? row.attempt : null,
276
+ briefHash: typeof row.briefHash === "string" ? row.briefHash : null,
277
+ plan: typeof row.plan === "string" ? row.plan : null,
278
+ sampledAt: typeof row.sampledAt === "number" ? row.sampledAt : null,
279
+ verdict: typeof row.verdict === "string" ? row.verdict : null,
280
+ };
281
+ }
282
+ }