@dzhechkov/harness-core 0.5.0 → 0.5.2

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 (96) hide show
  1. package/.dz-manifest.json +339 -75
  2. package/README.md +47 -4
  3. package/dist/codex-hooks-assets.d.ts.map +1 -1
  4. package/dist/codex-hooks-assets.js +39 -2
  5. package/dist/codex-hooks-assets.js.map +1 -1
  6. package/dist/codex-hooks-verify.d.ts +23 -2
  7. package/dist/codex-hooks-verify.d.ts.map +1 -1
  8. package/dist/codex-hooks-verify.js +29 -0
  9. package/dist/codex-hooks-verify.js.map +1 -1
  10. package/dist/codex-hooks.d.ts +90 -7
  11. package/dist/codex-hooks.d.ts.map +1 -1
  12. package/dist/codex-hooks.js +171 -21
  13. package/dist/codex-hooks.js.map +1 -1
  14. package/dist/feature-adr-routing.d.ts +22 -0
  15. package/dist/feature-adr-routing.d.ts.map +1 -1
  16. package/dist/feature-adr-routing.js +45 -0
  17. package/dist/feature-adr-routing.js.map +1 -1
  18. package/dist/index.d.ts +11 -4
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +17 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/loop-blobs.generated.d.ts +1 -1
  23. package/dist/loop-blobs.generated.d.ts.map +1 -1
  24. package/dist/loop-blobs.generated.js +12 -3
  25. package/dist/loop-blobs.generated.js.map +1 -1
  26. package/dist/loop-plan.d.ts +70 -0
  27. package/dist/loop-plan.d.ts.map +1 -1
  28. package/dist/loop-plan.js +103 -0
  29. package/dist/loop-plan.js.map +1 -1
  30. package/dist/loop-render.d.ts.map +1 -1
  31. package/dist/loop-render.js +38 -130
  32. package/dist/loop-render.js.map +1 -1
  33. package/dist/loop-run-semantics.d.ts +130 -0
  34. package/dist/loop-run-semantics.d.ts.map +1 -0
  35. package/dist/loop-run-semantics.js +257 -0
  36. package/dist/loop-run-semantics.js.map +1 -0
  37. package/dist/loop-trace.d.ts +106 -5
  38. package/dist/loop-trace.d.ts.map +1 -1
  39. package/dist/loop-trace.js +151 -18
  40. package/dist/loop-trace.js.map +1 -1
  41. package/dist/managed-hooks.d.ts +10 -0
  42. package/dist/managed-hooks.d.ts.map +1 -1
  43. package/dist/managed-hooks.js +17 -5
  44. package/dist/managed-hooks.js.map +1 -1
  45. package/dist/named-lock.d.ts +57 -0
  46. package/dist/named-lock.d.ts.map +1 -0
  47. package/dist/named-lock.js +247 -0
  48. package/dist/named-lock.js.map +1 -0
  49. package/dist/operations.d.ts +81 -5
  50. package/dist/operations.d.ts.map +1 -1
  51. package/dist/operations.js +356 -38
  52. package/dist/operations.js.map +1 -1
  53. package/dist/parity.d.ts +70 -2
  54. package/dist/parity.d.ts.map +1 -1
  55. package/dist/parity.js +133 -2
  56. package/dist/parity.js.map +1 -1
  57. package/dist/qe-bridge.d.ts +291 -0
  58. package/dist/qe-bridge.d.ts.map +1 -0
  59. package/dist/qe-bridge.js +538 -0
  60. package/dist/qe-bridge.js.map +1 -0
  61. package/dist/score.d.ts.map +1 -1
  62. package/dist/score.js +43 -9
  63. package/dist/score.js.map +1 -1
  64. package/dist/trace-corroborate.d.ts +48 -0
  65. package/dist/trace-corroborate.d.ts.map +1 -0
  66. package/dist/trace-corroborate.js +172 -0
  67. package/dist/trace-corroborate.js.map +1 -0
  68. package/dist/workflow-run-dispatch.d.ts +230 -0
  69. package/dist/workflow-run-dispatch.d.ts.map +1 -0
  70. package/dist/workflow-run-dispatch.js +363 -0
  71. package/dist/workflow-run-dispatch.js.map +1 -0
  72. package/dist/workflow-run.d.ts +513 -0
  73. package/dist/workflow-run.d.ts.map +1 -0
  74. package/dist/workflow-run.js +1377 -0
  75. package/dist/workflow-run.js.map +1 -0
  76. package/package.json +2 -2
  77. package/sbom.json +740 -80
  78. package/src/codex-hooks-assets.ts +39 -2
  79. package/src/codex-hooks-verify.ts +55 -2
  80. package/src/codex-hooks.ts +172 -20
  81. package/src/feature-adr-routing.ts +55 -0
  82. package/src/index.ts +46 -1
  83. package/src/loop-blobs.generated.ts +12 -3
  84. package/src/loop-plan.ts +185 -0
  85. package/src/loop-render.ts +38 -128
  86. package/src/loop-run-semantics.ts +278 -0
  87. package/src/loop-trace.ts +207 -16
  88. package/src/managed-hooks.ts +26 -5
  89. package/src/named-lock.ts +277 -0
  90. package/src/operations.ts +441 -40
  91. package/src/parity.ts +177 -2
  92. package/src/qe-bridge.ts +737 -0
  93. package/src/score.ts +50 -9
  94. package/src/trace-corroborate.ts +205 -0
  95. package/src/workflow-run-dispatch.ts +459 -0
  96. package/src/workflow-run.ts +1773 -0
@@ -0,0 +1,278 @@
1
+ /**
2
+ * `loop-run-semantics` — the ONE home of loop-designer's ENACTMENT DECISIONS (feature
3
+ * dz-workflow-run, ADR-001 W4).
4
+ *
5
+ * Before this module these semantics existed ONLY as template strings inside
6
+ * `loop-render.ts:renderRuntime` — readable by the generated Claude-host script and by nobody
7
+ * else. A second enactor (`dz workflow run`) would have had to COPY them, and two copies of a
8
+ * gate-verdict grammar is exactly how a runner comes to synthesize a pass the render would have
9
+ * refused. So the decisions move here once and are consumed twice:
10
+ * • the generated script gets them as a BLOB (`scripts/gen-loop-blobs.mjs`, blob `loop-semantics`,
11
+ * always on — the base runtime references errText/classifyFailure in every script);
12
+ * • the dz runner imports them directly.
13
+ * "Imported, not copied" stops being an intention and becomes a fact a test can check.
14
+ *
15
+ * SCOPE, honestly (ADR-001 names it): what moves is DECISION semantics. `__drainAll`,
16
+ * `runStep` and `__settleStep` do NOT move — they are HOST-STRUCTURAL (they wrap the sandbox's
17
+ * `parallel()`/`agent()` and its settle discipline); the runner has its own structured concurrency
18
+ * and its own settle path.
19
+ *
20
+ * BLOB-SOURCE DISCIPLINE (same rule as `loop-trace.ts`): this module has NO RUNTIME IMPORT — its
21
+ * single `import type` is erased at compile time, so the generator can slice declarations out of it
22
+ * with no import to resolve. The generator's INV-12 output ban (fs / clock / randomness / process)
23
+ * holds here by construction: every function below is pure.
24
+ *
25
+ * One consequence of that discipline is visible in the signatures: the six BLOB-EXPORTED functions
26
+ * may not mention an IMPORTED type by bare name (the slicer would see an unresolvable cross-file
27
+ * reference and fail closed), so `classifyFailure` spells its return type as the inline import type
28
+ * `import('./loop-plan.js').FailureClass`. It is the SAME closed enum — one domain, not a restated
29
+ * copy — written in the one form the slicer can carry.
30
+ */
31
+
32
+ import type { Deliverable, LoopPlan } from './loop-plan.js';
33
+
34
+ /** Blob version stamp read by scripts/gen-loop-blobs.mjs. */
35
+ export const LOOP_RUN_SEMANTICS_BLOB_VERSION = '1.0.0';
36
+
37
+ // ─────────────────────────────────────────────────────────────────────────────
38
+ // BLOB EXPORTS — sliced verbatim into every rendered script AND imported by the runner.
39
+ // Byte-semantics preserved from the template originals (loop-render.ts, pre-extraction):
40
+ // errText ← __errText · causeChain ← __causeChain · errSnap ← __errSnap
41
+ // classifyFailure ← __classifyFailure · gateVerdict ← __gateVerdict · joinRegion ← joinRegion
42
+ // ─────────────────────────────────────────────────────────────────────────────
43
+
44
+ export interface ErrSnapLink {
45
+ code: string | null;
46
+ name: string | null;
47
+ text: string;
48
+ }
49
+
50
+ /**
51
+ * TOTAL error-to-text (the ha-consilium 5b totality lesson): the writer's own settle event must
52
+ * survive a hostile error object. `String(err)` throws on a null-prototype object and a throwing
53
+ * `.message` getter throws on access — both are caught here, so rendering a message can never
54
+ * replace the original failure or lose the settle. `.message` is read ONCE into a local (a one-shot
55
+ * getter answered the `typeof` probe and vanished on the value read — snapshot-once defeats it).
56
+ */
57
+ export function errText(err: unknown): string {
58
+ try {
59
+ if (err !== null && typeof err === 'object') {
60
+ const m = (err as { message?: unknown }).message;
61
+ if (typeof m === 'string') return m;
62
+ }
63
+ return String(err);
64
+ } catch (_e) {
65
+ try {
66
+ return Object.prototype.toString.call(err);
67
+ } catch (_e2) {
68
+ return '[unrenderable error]';
69
+ }
70
+ }
71
+ }
72
+
73
+ /**
74
+ * The `err.cause` chain, bounded (depth 5), cycle-safe and getter-safe. The standard Node fetch
75
+ * shape `TypeError('fetch failed', { cause: { code: 'ECONNRESET' } })` hides its real class one
76
+ * link down, so classification must see the whole chain, not the outermost error.
77
+ */
78
+ export function causeChain(err: unknown): unknown[] {
79
+ const chain: unknown[] = [];
80
+ let cur: unknown = err;
81
+ for (let d = 0; d < 5; d++) {
82
+ if (cur === null || cur === undefined) break;
83
+ if (chain.indexOf(cur) !== -1) break; // cycle-safe
84
+ chain.push(cur);
85
+ try {
86
+ cur = typeof cur === 'object' ? (cur as { cause?: unknown }).cause : undefined;
87
+ } catch (_e) {
88
+ cur = undefined; // getter-safe
89
+ }
90
+ }
91
+ return chain.length > 0 ? chain : [err];
92
+ }
93
+
94
+ /**
95
+ * ONE snapshot PER FAILURE. The earlier shape snapshotted `.message` once per `errText` CALL, not
96
+ * once per failure — so logging read it, classification read it AGAIN, and a one-shot `.message`
97
+ * getter answered the log and defeated the classifier (2 getter reads, 1 attempt, MEASURED). The
98
+ * catch site builds this snapshot once; the log line and the classifier both consume the SNAPSHOT,
99
+ * so `.code` / `.name` / `.message` are each read exactly once per failure, over the whole chain.
100
+ */
101
+ export function errSnap(err: unknown): ErrSnapLink[] {
102
+ const chain = causeChain(err);
103
+ const snap: ErrSnapLink[] = [];
104
+ for (let ci = 0; ci < chain.length; ci++) {
105
+ let code: string | null = null;
106
+ try {
107
+ const c = chain[ci] !== null && typeof chain[ci] === 'object' ? (chain[ci] as { code?: unknown }).code : null;
108
+ code = typeof c === 'string' ? c.toUpperCase() : null;
109
+ } catch (_e) {
110
+ code = null;
111
+ }
112
+ let name: string | null = null;
113
+ try {
114
+ const n = chain[ci] !== null && typeof chain[ci] === 'object' ? (chain[ci] as { name?: unknown }).name : null;
115
+ name = typeof n === 'string' ? n : null;
116
+ } catch (_e) {
117
+ name = null;
118
+ }
119
+ snap.push({ code: code, name: name, text: errText(chain[ci]) });
120
+ }
121
+ return snap;
122
+ }
123
+
124
+ /**
125
+ * The CLOSED failure classification of `loop-plan/1` (timeout | transport | malformed-output |
126
+ * policy-refusal). THREE TIERS over the whole cause chain, strongest first:
127
+ * 1. error CODE — works on non-Error shapes like `{code:'ECONNRESET'}`, never message-dependent
128
+ * (`ETIMEDOUT` is a TRANSPORT code; an earlier message regex captured it as 'timeout' first);
129
+ * 2. error NAME — `SyntaxError` = parsing the model's output failed → malformed-output;
130
+ * 3. message patterns, DISJOINT by precedence transport > policy-refusal > malformed-output >
131
+ * timeout, every alternative WORD-BOUNDED (an unbounded `rate.?limit` matched
132
+ * 'delibeRATE LIMITation' — a substring must never smuggle a class).
133
+ * `outcome: 'null'` (a dead/empty agent) is a delivery failure ⇒ `transport`, retryable ONLY under
134
+ * `retryOn: ['transport']`. An UNCLASSIFIABLE failure returns null and is NEVER retried.
135
+ */
136
+ export function classifyFailure(
137
+ outcome: 'null' | 'error',
138
+ snap: ErrSnapLink[],
139
+ ): import('./loop-plan.js').FailureClass | null {
140
+ if (outcome === 'null') return 'transport';
141
+ const links = Array.isArray(snap) ? snap : [];
142
+ for (let ci = 0; ci < links.length; ci++) {
143
+ const code = (links[ci] as ErrSnapLink).code;
144
+ if (code === 'ETIMEDOUT' || code === 'ECONNRESET' || code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EPIPE' || code === 'ECONNABORTED' || code === 'EAI_AGAIN') return 'transport';
145
+ }
146
+ for (let ci = 0; ci < links.length; ci++) {
147
+ if ((links[ci] as ErrSnapLink).name === 'SyntaxError') return 'malformed-output';
148
+ }
149
+ let msg = '';
150
+ for (let ci = 0; ci < links.length; ci++) msg += (ci > 0 ? '\n' : '') + (links[ci] as ErrSnapLink).text;
151
+ msg = msg.toLowerCase();
152
+ // rate[ -]?limit(ed|ing|s)? is RIGHT-BOUNDED: the open 'rate.?limit' matched
153
+ // 'rate limitation: invalid JSON' as transport — a malformed-output failure smuggled a class.
154
+ if (/\btransport\b|\beconnreset\b|\beconnrefused\b|\benotfound\b|\bepipe\b|\betimedout\b|\bsocket hang up\b|\bnetwork error\b|\brate[ -]?limit(ed|ing|s)?\b|\boverloaded\b|\bhttp 5[0-9][0-9]\b/.test(msg)) return 'transport';
155
+ if (/\bpolicy\b|\brefus(e|ed|es|al|ing)\b|\bdeclin(e|ed|es|ing)\b|\bcontent filter\b|\bsafety block\b/.test(msg)) return 'policy-refusal';
156
+ if (/\bmalformed\b|\bunparseable\b|\bparse error\b|\binvalid json\b|\bunexpected token\b|\bunexpected end of json\b|\bschema mismatch\b/.test(msg)) return 'malformed-output';
157
+ if (/\btimeout\b|\btimed out\b/.test(msg)) return 'timeout';
158
+ return null;
159
+ }
160
+
161
+ export type GateVerdict = 'pass' | 'fail' | 'invalid';
162
+
163
+ /**
164
+ * Gate verdict parsing — parse-NEVER-synthesize, with the EXACTLY-ONE-ENDING-LINE protocol
165
+ * enforced: the verdict must be an ANCHORED line ("GATE: PASS" or "GATE: FAIL" alone on its line),
166
+ * it must be the LAST non-empty line of the reply, and it must be the ONLY anchored verdict line.
167
+ * Embedded mid-reply "GATE: PASS" text never counts, "GATE: PASS" followed by trailing prose is
168
+ * invalid, and "GATE: FAIL … GATE: PASS" is an INVALID verdict (never a success) — routed like a
169
+ * failure (redo / fail route), never a pass.
170
+ */
171
+ export function gateVerdict(reply: unknown): GateVerdict {
172
+ if (typeof reply !== 'string') return 'invalid';
173
+ const vLines = reply.split('\n');
174
+ const vRe = /^\s*GATE:\s*(PASS|FAIL)\s*$/;
175
+ let vCount = 0;
176
+ let vLast = '';
177
+ for (let i = 0; i < vLines.length; i++) {
178
+ if (vRe.test(vLines[i] as string)) vCount++;
179
+ if ((vLines[i] as string).trim() !== '') vLast = vLines[i] as string;
180
+ }
181
+ const vEnd = vRe.exec(vLast);
182
+ if (vCount !== 1 || vEnd === null) return 'invalid';
183
+ return vEnd[1] === 'PASS' ? 'pass' : 'fail';
184
+ }
185
+
186
+ export interface JoinOutcome {
187
+ ok: true;
188
+ values: unknown[];
189
+ failures: number[];
190
+ }
191
+
192
+ /**
193
+ * The join decision — explicit policy from the closed set; a dispatched branch is never skippable.
194
+ * `any` fails only when EVERY branch failed; `quorum:<n>` needs n non-failing branches; every other
195
+ * policy (the `all-*` family) fails on the first failing branch. Throws with a NAMED message, which
196
+ * the caller settles through its own single terminal exit.
197
+ */
198
+ export function joinRegion(results: unknown[], o: { policy: string; onInvalid: string; region: string }): JoinOutcome {
199
+ const policy = o && o.policy ? o.policy : 'all-activated';
200
+ const failures: number[] = [];
201
+ for (let i = 0; i < results.length; i++) {
202
+ if (results[i] === null || results[i] === undefined) failures.push(i);
203
+ }
204
+ if (policy === 'any') {
205
+ if (failures.length === results.length) throw new Error('join ' + o.region + ': every branch failed (policy any)');
206
+ return { ok: true, values: results, failures: failures };
207
+ }
208
+ const quorum = /^quorum:([1-9][0-9]*)$/.exec(policy);
209
+ if (quorum) {
210
+ const okN = results.length - failures.length;
211
+ if (okN < Number(quorum[1])) throw new Error('join ' + o.region + ': quorum ' + quorum[1] + ' not met (' + okN + ' ok)');
212
+ return { ok: true, values: results, failures: failures };
213
+ }
214
+ if (failures.length > 0) throw new Error('join ' + o.region + ': ' + failures.length + ' dispatched branch(es) failed under policy ' + policy + ' — a dispatched branch is never skippable');
215
+ return { ok: true, values: results, failures: [] };
216
+ }
217
+
218
+ // ─────────────────────────────────────────────────────────────────────────────
219
+ // NON-BLOB EXPORTS — shared by loop-render.ts and workflow-run.ts, never injected into a script
220
+ // (the rendered script receives the RESULT of these as literal text / a literal number).
221
+ // ─────────────────────────────────────────────────────────────────────────────
222
+
223
+ export interface ContractInputs {
224
+ reads: string[];
225
+ writes: string[];
226
+ deliverable: Deliverable;
227
+ tools: string[];
228
+ gate: { kind: string } | null;
229
+ }
230
+
231
+ /**
232
+ * THE agent-visible contract TEXT lines (ADR-001 Confirmation-5) — byte-for-byte the strings the
233
+ * render splices after a step's USER prompt, minus the JS quoting. Both enactors assemble a step's
234
+ * prompt from the SAME function, so a dz-hosted step and a Claude-hosted step communicate the plan's
235
+ * declarations identically; a value-pinned wiring test compares the rendered USER-region contract
236
+ * lines against the runner-assembled ones.
237
+ *
238
+ * The tools line's second sentence is not decoration — it is the honesty clause the whole feature
239
+ * rests on: a declaration is not enforcement.
240
+ */
241
+ export function stepContractLines(c: ContractInputs): string[] {
242
+ const lines: string[] = [];
243
+ const reads = c.reads ?? [];
244
+ const writes = c.writes ?? [];
245
+ const tools = c.tools ?? [];
246
+ if (reads.length > 0) lines.push('declared inputs (plan artifacts.reads): ' + reads.join(', '));
247
+ if (writes.length > 0) {
248
+ const fileNote = (c.deliverable ?? 'return-value') === 'file' ? '; your deliverable is the written file(s), not your reply' : '';
249
+ lines.push('declared outputs (plan artifacts.writes): ' + writes.join(', ') + ' — write them' + fileNote + '. The loop verifies they land.');
250
+ }
251
+ if (tools.length > 0) {
252
+ lines.push('declared MCP tool allowlist (plan tools): ' + tools.join(', ') + ' — use NOTHING outside it. In this environment every one of these is a labeled STUB, not a live integration; enforcement lives at the MCP server, not here.');
253
+ }
254
+ if (c.gate !== null && c.gate !== undefined) {
255
+ lines.push('GATE PROTOCOL (kind: ' + (c.gate.kind ?? 'gate') + '): end your reply with exactly one line "GATE: PASS" or "GATE: FAIL" — the loop PARSES this verdict and never synthesizes one.');
256
+ }
257
+ return lines;
258
+ }
259
+
260
+ /**
261
+ * THE budget ceiling formula (ADR-004 Confirmation-2): declared per-step budgets PLUS the declared
262
+ * gate-redo allowance — a plan-declared redo must be AFFORDABLE (an undeclared one still hits the
263
+ * guard loudly). A gate whose failRoute is a `terminal:` route reserves nothing: a terminal route
264
+ * ends the run, it does not re-run anything.
265
+ *
266
+ * This is the number the rendered script carries as `const __budget = { left: N }`; the runner reads
267
+ * it from HERE, so the two enactors cannot drift into two ceilings.
268
+ */
269
+ export function computeBudgetTotal(plan: LoopPlan): number {
270
+ const stepBudget = plan.steps.reduce((n, s) => n + (s.budget?.maxAgents ?? 1), 0);
271
+ const byId = new Map(plan.steps.map((s) => [s.stepId, s]));
272
+ const gateRedoBudget = (plan.gates ?? []).reduce((n, g) => {
273
+ const redos = typeof g.maxRedos === 'number' && Number.isFinite(g.maxRedos) && g.maxRedos > 0 ? Math.floor(g.maxRedos) : 0;
274
+ if (redos === 0 || typeof g.failRoute !== 'string' || g.failRoute.startsWith('terminal:')) return n;
275
+ return n + redos * ((byId.get(g.failRoute)?.budget?.maxAgents ?? 1) + (byId.get(g.stepId)?.budget?.maxAgents ?? 1));
276
+ }, 0);
277
+ return stepBudget + gateRedoBudget;
278
+ }
package/src/loop-trace.ts CHANGED
@@ -60,6 +60,15 @@ export interface TraceSettleEvent {
60
60
  wallTime?: string | null;
61
61
  }
62
62
 
63
+ /**
64
+ * WHICH CODE PATH was meant to write this file. A HINT, never a trust statement — the rendered
65
+ * script's flush is performed BY AN AGENT, which therefore controls these bytes before the file
66
+ * exists and could write any value here. It is deliberately NOT called `attestedBy`, so nothing in
67
+ * the codebase can read it as provenance (ADR-001 round 1 made exactly that mistake). The trust
68
+ * question is answered by `deriveAttestation`, from an artifact the sandboxed script cannot write.
69
+ */
70
+ export type TraceEmitterPath = 'dz-process' | 'rendered-script';
71
+
63
72
  export interface TraceRunOpened {
64
73
  v: 1;
65
74
  runId: string;
@@ -67,6 +76,9 @@ export interface TraceRunOpened {
67
76
  event: 'run.opened';
68
77
  planDigest: string;
69
78
  execFp: string;
79
+ /** Optional ON THE WIRE (NFR-1): an older reader ignores it, a newer reader over an older trace
80
+ * gets `unknown` — which is never `instrument`. */
81
+ emitterPath?: TraceEmitterPath;
70
82
  }
71
83
 
72
84
  export interface TraceRunClosed {
@@ -122,6 +134,10 @@ export function traceValidateEvent(e: unknown): string | null {
122
134
  }
123
135
  if (kind === 'run.opened') {
124
136
  if (typeof ev['planDigest'] !== 'string' || typeof ev['execFp'] !== 'string') return 'run.opened needs planDigest + execFp';
137
+ const ep = ev['emitterPath'];
138
+ // Absent is legal (NFR-1). Present-but-outside-the-union is a REFUSAL, not a downgrade: a value
139
+ // like 'trusted' is someone trying to say something the vocabulary does not permit.
140
+ if (ep !== undefined && ep !== 'dz-process' && ep !== 'rendered-script') return 'emitterPath must be dz-process|rendered-script';
125
141
  return null;
126
142
  }
127
143
  if (kind === 'run.closed') {
@@ -132,11 +148,17 @@ export function traceValidateEvent(e: unknown): string | null {
132
148
  return 'unknown event kind';
133
149
  }
134
150
 
135
- /** Open a trace state and buffer the run.opened frame. Throws on an invalid runId (fail-closed). */
136
- export function traceInit(runId: string, planDigest: string, execFp: string): TraceState {
151
+ /**
152
+ * Open a trace state and buffer the run.opened frame. Throws on an invalid runId (fail-closed).
153
+ *
154
+ * `emitterPath` is REQUIRED and has NO DEFAULT, on purpose: a default would be chosen once, by
155
+ * whoever added the parameter, and every future caller that forgot it would silently inherit that
156
+ * choice. A missing argument must be a compile error instead.
157
+ */
158
+ export function traceInit(runId: string, planDigest: string, execFp: string, emitterPath: TraceEmitterPath): TraceState {
137
159
  if (!TRACE_RUNID_RE.test(runId)) throw new Error('loop-trace: runId fails ' + String(TRACE_RUNID_RE));
138
160
  const state: TraceState = { runId, seq: 0, dispatched: 0, settled: 0, buffer: [] };
139
- const opened: TraceRunOpened = { v: 1, runId, seq: ++state.seq, event: 'run.opened', planDigest, execFp };
161
+ const opened: TraceRunOpened = { v: 1, runId, seq: ++state.seq, event: 'run.opened', planDigest, execFp, emitterPath };
140
162
  traceBuffer(state, opened);
141
163
  return state;
142
164
  }
@@ -211,6 +233,19 @@ export function traceFlushCmd(state: TraceState, traceFileAbs: string): string |
211
233
  return 'mkdir -p ' + dir + ' && ' + printfs;
212
234
  }
213
235
 
236
+ /**
237
+ * Drain the buffered, already-VALIDATED lines — the runner's flush primitive (W17/T0.1). The
238
+ * fs-less Claude host turns the same buffer into a shell command (`traceFlushCmd`); a host that
239
+ * HAS fs (the `dz workflow run` scheduler) appends exactly these lines itself. One buffer, two
240
+ * drains, zero second line-shape: a line this returns has already passed `traceValidateEvent`,
241
+ * because nothing else can enter the buffer. Empty buffer ⇒ `[]` (never a repeat of the last
242
+ * batch).
243
+ */
244
+ export function traceDrain(state: TraceState): string[] {
245
+ if (state.buffer.length === 0) return [];
246
+ return state.buffer.splice(0, state.buffer.length);
247
+ }
248
+
214
249
  /**
215
250
  * Build the feature-ADR live-panel telemetry leg. Totality comes from the caller's grouped splice:
216
251
  * returning the bare command lets that splice preserve the trace flush's exit status while
@@ -301,14 +336,38 @@ export interface TraceRun {
301
336
  /** No run.closed frame ⇒ the tail may be lost; truncated-window invariants report inconclusive. */
302
337
  incomplete: boolean;
303
338
  parseErrors: string[];
339
+ /** The self-declared HINT (see TraceEmitterPath) — null when absent. NEVER read as provenance. */
340
+ emitterPath: TraceEmitterPath | null;
341
+ /** Two `run.opened` frames that DISAGREE. The scan used to keep the last one silently, which
342
+ * would let a spliced frame overwrite the genuine one; a conflict now forbids `instrument`. */
343
+ openConflict: boolean;
304
344
  }
305
345
 
306
- /** Parse a trace.jsonl text. Tolerant of a missing run.closed (incomplete: true); a DUPLICATE
307
- * settle for one invocation is a PARSE ERROR, never a silent merge (INV-15). */
346
+ /**
347
+ * Parse a trace.jsonl text. Tolerant of a missing run.closed (incomplete: true); a DUPLICATE
348
+ * settle for one invocation is a PARSE ERROR, never a silent merge (INV-15).
349
+ *
350
+ * W17 / AM-12 — `run.events` is CANONICALIZED by ascending `seq` after the line scan. The host's
351
+ * batched racing flush agents legitimately append out of seq order (MEASURED on the committed
352
+ * `pkg-audit-1` run: lines 1-2 are settles seq 7 and 6, ahead of `run.opened` seq 1), and the
353
+ * reader used to inherit that file order — so `invocations()` DROPPED every settle that preceded
354
+ * its own dispatch in the file, and a complete, successful run read as three FAIL verdicts. seq is
355
+ * the authoritative order (it is allocated synchronously at the lifecycle transition); file order
356
+ * is a durability artifact the flush design already blesses, and it stays recoverable only from the
357
+ * raw text.
358
+ *
359
+ * Order of the two bookkeeping passes is load-bearing:
360
+ * • LINE-SHAPE errors (unparseable / invalid event) are recorded in FILE order — they describe
361
+ * the bytes, and quoting them in file order is what lets a human find the line.
362
+ * • The duplicate-dispatch and duplicate-settle checks run AFTER canonicalization, so "which
363
+ * settle is the duplicate" is decided by seq, not by which flush batch happened to land first
364
+ * (before this, reversing the flush order changed WHICH event INV-15 refused).
365
+ * The sort is stable, so two events sharing one seq keep their file order relative to each other —
366
+ * the only ordering the file can still testify to. INV-14 fails such a trace on uniqueness anyway.
367
+ */
308
368
  export function parseTrace(text: string): TraceRun {
309
- const run: TraceRun = { runId: null, planDigest: null, execFp: null, events: [], incomplete: true, parseErrors: [] };
310
- const settledSeen = new Set<string>();
311
- const dispatchSeen = new Set<string>();
369
+ const run: TraceRun = { runId: null, planDigest: null, execFp: null, events: [], incomplete: true, parseErrors: [], emitterPath: null, openConflict: false };
370
+ const scanned: TraceEvent[] = [];
312
371
  for (const line of String(text ?? '').split('\n')) {
313
372
  const t = line.trim();
314
373
  if (t === '') continue;
@@ -324,11 +383,30 @@ export function parseTrace(text: string): TraceRun {
324
383
  run.parseErrors.push('invalid event (' + err + '): ' + t.slice(0, 120));
325
384
  continue;
326
385
  }
327
- const ev = e as TraceEvent;
386
+ scanned.push(e as TraceEvent);
387
+ }
388
+ // CANONICALIZATION (the W17 fix): ascending seq, stable.
389
+ scanned.sort((a, b) => a.seq - b.seq);
390
+ const settledSeen = new Set<string>();
391
+ const dispatchSeen = new Set<string>();
392
+ for (const ev of scanned) {
328
393
  if (ev.event === 'run.opened') {
394
+ const prior = run.events.some((p) => p.event === 'run.opened');
395
+ if (prior) {
396
+ const disagrees =
397
+ run.runId !== ev.runId ||
398
+ run.planDigest !== ev.planDigest ||
399
+ run.execFp !== ev.execFp ||
400
+ run.emitterPath !== (ev.emitterPath ?? null);
401
+ if (disagrees) {
402
+ run.openConflict = true;
403
+ run.parseErrors.push('conflicting run.opened frames — refusing to prefer either (ADR-001)');
404
+ }
405
+ }
329
406
  run.runId = ev.runId;
330
407
  run.planDigest = ev.planDigest;
331
408
  run.execFp = ev.execFp;
409
+ run.emitterPath = ev.emitterPath ?? null;
332
410
  }
333
411
  if (ev.event === 'run.closed') run.incomplete = false;
334
412
  if (ev.event === 'dispatched') {
@@ -348,12 +426,84 @@ export function parseTrace(text: string): TraceRun {
348
426
  return run;
349
427
  }
350
428
 
429
+ /**
430
+ * ATTESTATION — the trust question, answered by the READER, never by the file.
431
+ *
432
+ * `instrument` means, EXACTLY (ADR-001 round 3, wording taken from the cross-family reviewer):
433
+ * *the bytes read match the identifiers, the hash and the line count asserted by the co-located
434
+ * `run-state.json`.* It does NOT mean `dz` historically wrote those bytes, nor that this is the
435
+ * directory it wrote them in. A byte-identical replay passes. Copying the matched trace+run-state
436
+ * pair elsewhere passes. Both are accepted and tested, not patched.
437
+ *
438
+ * What it DOES buy: `run-state.json` is written by the dz process, and the rendered script runs in a
439
+ * sandbox with no filesystem — so an agent that mis-writes, truncates, reorders or invents its
440
+ * flush cannot reach `instrument`. What it cannot buy: a defence against an actor with write access
441
+ * to the run directory. On this machine the agent IS such an actor and the signing key is readable
442
+ * by the same account, so no local artifact — signature included — closes that. Named, not hidden.
443
+ *
444
+ * `unknown` is kept DISTINCT from `agent` (a legacy instrument run, a stripped field and explicit
445
+ * agent testimony are different facts) while sharing its conservative tier for every decision.
446
+ */
447
+ export type TraceAttestation = 'instrument' | 'agent' | 'unknown';
448
+
449
+ /** The subset of `run-state.json` the attestation reads. Unknown-shaped input is not an error — it
450
+ * simply fails to bind, which yields `unknown`. */
451
+ export interface TraceRunStateBinding {
452
+ runId?: unknown;
453
+ planDigest?: unknown;
454
+ execFp?: unknown;
455
+ traceSha256?: unknown;
456
+ traceLines?: unknown;
457
+ }
458
+
459
+ /** What the CALLER measured about the trace text it actually read. Passed in rather than computed
460
+ * here so this module keeps its zero dependencies (no node:crypto) and stays trivially testable. */
461
+ export interface TraceObserved {
462
+ sha256: string;
463
+ lines: number;
464
+ }
465
+
466
+ export function deriveAttestation(run: TraceRun, state: TraceRunStateBinding | null | undefined, observed: TraceObserved): TraceAttestation {
467
+ // A conflict between two run.opened frames forbids the favourable reading outright: preferring
468
+ // either one is exactly the silent choice this feature exists to remove.
469
+ if (run.openConflict) return 'unknown';
470
+ // QE round 1 / H1: EVERY bound value must be non-empty. Equality alone let a trace whose
471
+ // planDigest and execFp are both '' bind against a state carrying the same two empty strings —
472
+ // an "identity" that identifies nothing. A binding over absent values is not a binding.
473
+ const nonEmpty = (a: unknown, b: unknown): boolean => typeof a === 'string' && a !== '' && a === b;
474
+ const bound =
475
+ state != null &&
476
+ nonEmpty(state.runId, run.runId) &&
477
+ nonEmpty(state.planDigest, run.planDigest) &&
478
+ nonEmpty(state.execFp, run.execFp) &&
479
+ // CONTENT binding, not just identifiers: a legacy run-state with no traceSha256 can never mint
480
+ // `instrument` (that was the reviewer's stale-directory counterexample).
481
+ nonEmpty(state.traceSha256, observed.sha256) &&
482
+ typeof state.traceLines === 'number' && state.traceLines === observed.lines;
483
+ if (bound) return 'instrument';
484
+ if (run.emitterPath === 'rendered-script') return 'agent';
485
+ return 'unknown';
486
+ }
487
+
351
488
  export type InvariantStatus = 'pass' | 'fail' | 'inconclusive';
352
489
 
353
490
  export interface InvariantVerdict {
354
491
  id: string;
355
492
  status: InvariantStatus;
356
493
  message: string;
494
+ /**
495
+ * FR-3 — the qualifier travels IN the verdict, never beside it. A caller that stores a verdict
496
+ * and reads it back later must not be able to end up holding a bare `pass` whose attestation was
497
+ * dropped in transit. Optional only so a caller that has not derived one is a compile-time
498
+ * possibility; `stampAttestation` is how the reader attaches it.
499
+ */
500
+ attestation?: TraceAttestation;
501
+ }
502
+
503
+ /** Attach one attestation to every verdict in a batch. Kept as a named function rather than a spread
504
+ * at each call site so a NEW verdict producer cannot silently ship unstamped verdicts. */
505
+ export function stampAttestation(verdicts: InvariantVerdict[], attestation: TraceAttestation): InvariantVerdict[] {
506
+ return verdicts.map((v) => ({ ...v, attestation }));
357
507
  }
358
508
 
359
509
  interface Invocation {
@@ -395,13 +545,49 @@ export function runInvariants(projection: TraceProjection, run: TraceRun): Invar
395
545
  const out: InvariantVerdict[] = [];
396
546
  const invs = invocations(run);
397
547
 
398
- // INV-14: seq unique + strictly increasing in event order.
548
+ // INV-14 (RESTATED, W17/AM-12 verdict id UNCHANGED: `seq-monotonic` is the consumer contract,
549
+ // keyed on by the fitness suite and every `dz workflow-trace` reader, so only the SEMANTICS and
550
+ // the message restate). `parseTrace` now canonicalizes by seq, so "strictly increasing in event
551
+ // order" became tautological — it tested the reader's own sort. The property that still has
552
+ // teeth is the SINGLE-ALLOCATOR witness:
553
+ // • seq values are UNIQUE (two writers, or one writer allocating twice, collide) — always;
554
+ // • on a COMPLETE trace they are exactly contiguous 1..maxSeq (a closed run that skips a
555
+ // number lost an event or had a second allocator);
556
+ // • on an INCOMPLETE trace a gap is INCONCLUSIVE, never a pass — the window is truncated, so
557
+ // a missing number is indistinguishable from an unflushed one.
558
+ // Residue accepted and named in AM-12: a writer allocating unique + contiguous seq in a
559
+ // non-monotonic ORDER is no longer detectable. Allocation order was only ever observable through
560
+ // the racy append that this fix (correctly) stopped trusting.
399
561
  {
400
562
  const seqs = run.events.map((e) => e.seq);
401
- const dup = seqs.some((s, i) => seqs.indexOf(s) !== i);
402
- const decreasing = seqs.some((s, i) => i > 0 && s <= (seqs[i - 1] as number));
403
- if (dup || decreasing) out.push({ id: 'seq-monotonic', status: 'fail', message: 'seq is not unique/strictly-increasing — the single serialized writer property is broken' });
404
- else out.push({ id: 'seq-monotonic', status: 'pass', message: 'seq unique and strictly increasing (' + seqs.length + ' events)' });
563
+ const dupes = [...new Set(seqs.filter((s, i) => seqs.indexOf(s) !== i))].sort((a, b) => a - b);
564
+ if (dupes.length > 0) {
565
+ out.push({
566
+ id: 'seq-monotonic',
567
+ status: 'fail',
568
+ message: 'duplicate seq value(s) ' + dupes.join(', ') + ' — the single-ALLOCATOR property is broken (seq must be unique across the whole run)',
569
+ });
570
+ } else {
571
+ const maxSeq = seqs.length === 0 ? 0 : Math.max(...seqs);
572
+ const missing: number[] = [];
573
+ const present = new Set(seqs);
574
+ for (let s = 1; s <= maxSeq && missing.length < 8; s++) if (!present.has(s)) missing.push(s);
575
+ if (missing.length === 0) {
576
+ out.push({ id: 'seq-monotonic', status: 'pass', message: 'seq unique and contiguous 1..' + maxSeq + ' (' + seqs.length + ' events)' });
577
+ } else if (run.incomplete) {
578
+ out.push({
579
+ id: 'seq-monotonic',
580
+ status: 'inconclusive',
581
+ message: 'seq unique but NOT contiguous (missing ' + missing.join(', ') + ' of 1..' + maxSeq + ') on an INCOMPLETE trace — a truncated window is indistinguishable from a lost event',
582
+ });
583
+ } else {
584
+ out.push({
585
+ id: 'seq-monotonic',
586
+ status: 'fail',
587
+ message: 'seq is not contiguous 1..' + maxSeq + ' on a COMPLETE trace — missing ' + missing.join(', ') + ' (a closed run that skips a number lost an event or had a second allocator)',
588
+ });
589
+ }
590
+ }
405
591
  }
406
592
 
407
593
  // INV-15: pairing (a dangling dispatch is only conclusive on a complete trace).
@@ -623,7 +809,12 @@ export interface Timeline {
623
809
  /**
624
810
  * Merge one timeline: trace.jsonl is the AUTHORITATIVE order (rows sorted by seq); checkpoints,
625
811
  * cost-ledger lines and usageEvents are appended as unordered context rows (seq 0); journal.jsonl
626
- * contributes DIAGNOSTIC agentId correlation only, never ordering (the ACL of 04 §8).
812
+ * contributes a DIAGNOSTIC LINE COUNT only, never ordering (the ACL of 04 §8).
813
+ *
814
+ * Honesty fix (2026-08-20): this note used to promise "agentId correlation", which the code never
815
+ * did — it counts lines. A comment claiming an analysis that does not exist is the same defect class
816
+ * this feature was built to remove, one layer up. The real correlation now lives in
817
+ * `trace-corroborate.ts`, behind `dz workflow-trace --corroborate`, where it is scoped and tested.
627
818
  */
628
819
  export function assembleTimeline(input: {
629
820
  trace: string;
@@ -675,7 +866,7 @@ export function assembleTimeline(input: {
675
866
  sources.push('journal (diagnostic only — never ordering)');
676
867
  let n = 0;
677
868
  for (const line of input.journal.split('\n')) if (line.trim() !== '') n++;
678
- rows.push({ seq: 0, kind: 'journal', label: 'journal', detail: `${n} host-journal line(s) — agentId correlation only; the host journal carries no seq/ts and NEVER orders this timeline`, wallTime: null });
869
+ rows.push({ seq: 0, kind: 'journal', label: 'journal', detail: n + ' host-journal line(s) — COUNT only; the host journal carries no seq/ts and NEVER orders this timeline. For an actual comparison run: dz workflow-trace --corroborate <hostRunDir>', wallTime: null });
679
870
  }
680
871
  return { runId: run.runId, incomplete: run.incomplete, rows, sources };
681
872
  }
@@ -65,6 +65,16 @@ export interface MergeManagedHookOptions {
65
65
  readonly looksLikeOurs?: (entry: ManagedHookEntry, event: string) => boolean;
66
66
  /** True ⇒ this OURS entry was in a legacy shape/vintage (Claude path only). */
67
67
  readonly isLegacy?: (entry: ManagedHookEntry, event: string) => boolean;
68
+ /**
69
+ * Per-HANDLER salvage for an entry `isManaged` claimed. Given an OWNED entry, return it rebuilt
70
+ * from only the handlers that are NOT ours, or `null` when every handler was ours.
71
+ *
72
+ * Optional, and absent means the historical whole-entry behaviour — the Claude path passes
73
+ * nothing and is byte-identical to before (AM-3). The Codex path passes it because attribution at
74
+ * matcher-group granularity deleted a foreign handler that merely shared a group with dz's
75
+ * (independent review, finding 6).
76
+ */
77
+ readonly retainForeign?: (entry: ManagedHookEntry, event: string) => ManagedHookEntry | null;
68
78
  /** e.g. `'agentdb'` → `merged agentdb hooks (user hooks preserved)`. */
69
79
  readonly reportLabel?: string;
70
80
  /** Report text when nothing changed. */
@@ -98,7 +108,12 @@ export function mergeManagedHookEntries(
98
108
  for (const [event, entries] of Object.entries(source)) {
99
109
  if (!Array.isArray(entries)) continue;
100
110
  for (const entry of entries) {
101
- if (options.isManaged(entry, event)) continue;
111
+ if (options.isManaged(entry, event)) {
112
+ // A mixed group counts as a preserved foreign entry when something of the user's survives
113
+ // in it — the census must not report zero for a handler the merge actually keeps.
114
+ if (options.retainForeign?.(entry, event) != null) foreignPreserved += 1;
115
+ continue;
116
+ }
102
117
  foreignPreserved += 1;
103
118
  if (options.looksLikeOurs?.(entry, event) === true) unattributable += 1;
104
119
  }
@@ -108,11 +123,17 @@ export function mergeManagedHookEntries(
108
123
  let replacedLegacy = false;
109
124
  for (const event of Object.keys(managed)) {
110
125
  const current = Array.isArray(hooks[event]) ? (hooks[event] as ManagedHookEntry[]) : [];
111
- const kept = current.filter((entry) => {
126
+ const kept: ManagedHookEntry[] = [];
127
+ for (const entry of current) {
112
128
  const ours = options.isManaged(entry, event);
113
- if (ours && options.isLegacy?.(entry, event) === true) replacedLegacy = true;
114
- return !ours;
115
- });
129
+ if (!ours) {
130
+ kept.push(entry);
131
+ continue;
132
+ }
133
+ if (options.isLegacy?.(entry, event) === true) replacedLegacy = true;
134
+ const salvaged = options.retainForeign?.(entry, event) ?? null;
135
+ if (salvaged !== null) kept.push(salvaged);
136
+ }
116
137
  const next = [...kept, ...(managed[event] ?? [])];
117
138
  if (JSON.stringify(next) !== JSON.stringify(current)) changed = true;
118
139
  hooks[event] = next;