@event4u/agent-config 9.30.0 → 9.32.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 (94) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +60 -292
  3. package/dist/agent-src/contexts/execution/host-capability-manifest.md +32 -1
  4. package/dist/agent-src/rules/delegation-policy.md +11 -1
  5. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  6. package/dist/agent-src/templates/scripts/work_engine/delivery_state.ts +6 -0
  7. package/dist/agent-src/templates/scripts/work_engine/directives/backend/_self_fix.ts +332 -0
  8. package/dist/agent-src/templates/scripts/work_engine/directives/backend/refine.ts +106 -1
  9. package/dist/agent-src/templates/scripts/work_engine/directives/backend/test.ts +50 -15
  10. package/dist/agent-src/templates/scripts/work_engine/directives/backend/verify.ts +49 -15
  11. package/dist/agent-src/templates/scripts/work_engine/state.ts +74 -0
  12. package/dist/agent-src/templates/scripts/work_engine/state_io.ts +6 -0
  13. package/dist/cli-delegate/chunk-2WELHO3P.js +582 -0
  14. package/dist/cli-delegate/{chunk-IYTGIG2Y.js → chunk-542DZR4P.js} +118 -148
  15. package/dist/cli-delegate/{chunk-66OVWGB5.js → chunk-AG47LAGQ.js} +1 -1
  16. package/dist/cli-delegate/{chunk-MP3JT3IU.js → chunk-DS6BLDMG.js} +1 -1
  17. package/dist/cli-delegate/{chunk-O3CO5BFB.js → chunk-EJITJBJX.js} +12 -1
  18. package/dist/cli-delegate/{chunk-EQY4FLJB.js → chunk-ITIQSGOQ.js} +3 -3
  19. package/dist/cli-delegate/{chunk-LCFJIQ4J.js → chunk-JEJABGKB.js} +110 -6
  20. package/dist/cli-delegate/chunk-PZWRPRWP.js +38 -0
  21. package/dist/cli-delegate/{chunk-BTJNRUX3.js → chunk-QEEB4LHO.js} +1 -1
  22. package/dist/cli-delegate/{chunk-DDUNNFYX.js → chunk-UVKNIJH2.js} +2 -2
  23. package/dist/cli-delegate/cmd_analyze_session.js +1 -1
  24. package/dist/cli-delegate/cmd_brand_status.js +1 -1
  25. package/dist/cli-delegate/cmd_conformance.js +154 -41
  26. package/dist/cli-delegate/cmd_doctor.js +4 -3
  27. package/dist/cli-delegate/cmd_explain.js +2 -2
  28. package/dist/cli-delegate/cmd_export.js +4 -4
  29. package/dist/cli-delegate/cmd_handoff.js +168 -59
  30. package/dist/cli-delegate/cmd_mcp_available.js +1 -1
  31. package/dist/cli-delegate/cmd_migrate.js +2 -2
  32. package/dist/cli-delegate/cmd_packs_active.js +2 -2
  33. package/dist/cli-delegate/cmd_prune.js +4 -4
  34. package/dist/cli-delegate/cmd_route_audit.js +2 -2
  35. package/dist/cli-delegate/cmd_route_explain.js +1 -1
  36. package/dist/cli-delegate/cmd_session_recycle.js +19 -4
  37. package/dist/cli-delegate/cmd_settings_get.js +2 -55
  38. package/dist/cli-delegate/cmd_settings_migrate.js +4 -4
  39. package/dist/cli-delegate/cmd_settings_set.js +1 -1
  40. package/dist/cli-delegate/cmd_sync.js +4 -4
  41. package/dist/cli-delegate/cmd_uninstall.js +4 -4
  42. package/dist/cli-delegate/cmd_update.js +1 -1
  43. package/dist/cli-delegate/cmd_upgrade.js +1 -1
  44. package/dist/cli-delegate/cmd_validate.js +4 -4
  45. package/dist/cli-delegate/cmd_versions.js +1 -1
  46. package/dist/discovery/deprecation-report.md +1 -1
  47. package/dist/discovery/discovery-manifest.json +3 -3
  48. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  49. package/dist/discovery/discovery-manifest.summary.md +1 -1
  50. package/dist/discovery/orphan-report.md +1 -1
  51. package/dist/discovery/packs.json +2 -2
  52. package/dist/discovery/trust-report.md +1 -1
  53. package/dist/discovery/workspaces.json +2 -2
  54. package/dist/hooks/dispatch.js +1411 -810
  55. package/dist/install/install.mjs +121 -16
  56. package/dist/mcp/registry-manifest.json +1 -1
  57. package/dist/mcp/server.json +2 -2
  58. package/dist/mcp/server.mjs +365 -143
  59. package/dist/scripts/_lib/agent_settings.js +111 -2
  60. package/dist/scripts/_lib/agent_settings.js.map +1 -1
  61. package/dist/server/schemas/settings.js +2 -2
  62. package/dist/server/schemas/settings.js.map +1 -1
  63. package/package.json +1 -1
  64. package/src/agent-src/templates/scripts/work_engine/delivery_state.ts +6 -0
  65. package/src/agent-src/templates/scripts/work_engine/directives/backend/_self_fix.ts +332 -0
  66. package/src/agent-src/templates/scripts/work_engine/directives/backend/refine.ts +106 -1
  67. package/src/agent-src/templates/scripts/work_engine/directives/backend/test.ts +50 -15
  68. package/src/agent-src/templates/scripts/work_engine/directives/backend/verify.ts +49 -15
  69. package/src/agent-src/templates/scripts/work_engine/state.ts +74 -0
  70. package/src/agent-src/templates/scripts/work_engine/state_io.ts +6 -0
  71. package/src/config/pack-size-budget.json +3 -2
  72. package/src/scripts/_cli/cmd_session_recycle.ts +25 -0
  73. package/src/scripts/_cli/explain_last/inputs.ts +13 -0
  74. package/src/scripts/_cli/handoff_generate.ts +36 -1
  75. package/src/scripts/_cli/handoff_sessions.ts +140 -9
  76. package/src/scripts/_lib/agent_settings.ts +119 -2
  77. package/src/scripts/_lib/carrier_divergence.ts +120 -2
  78. package/src/scripts/_lib/envelope_grounding.ts +206 -0
  79. package/src/scripts/_lib/host_capability.ts +79 -0
  80. package/src/scripts/_lib/session_eol.ts +85 -0
  81. package/src/scripts/_lib/subagent_capsule.ts +256 -1
  82. package/src/scripts/check_secret_leak.test.ts +43 -0
  83. package/src/scripts/check_secret_leak.ts +12 -0
  84. package/src/scripts/handoff_context_hook.ts +66 -18
  85. package/src/scripts/hooks/session_eol_hook.ts +12 -12
  86. package/src/scripts/hooks/turn_end_gate_hook.ts +296 -88
  87. package/src/scripts/language_mirror_hook.ts +69 -16
  88. package/src/scripts/measure_turn_end_gate.ts +129 -51
  89. package/src/scripts/report_carrier_divergence.ts +143 -30
  90. package/src/scripts/report_conformance_funnel.ts +18 -4
  91. package/src/scripts/routing_doctor.ts +25 -2
  92. package/src/scripts/schemas/dod.schema.json +45 -0
  93. package/src/server/schemas/settings.ts +2 -2
  94. package/dist/cli-delegate/chunk-RVGBH4XK.js +0 -142
@@ -0,0 +1,332 @@
1
+ /**
2
+ * Bounded self-fix loop — the shared primitive behind the red-check lanes.
3
+ *
4
+ * The gap this closes, verified in code before it was built: `test` and
5
+ * `verify` both halt to `Outcome.BLOCKED` the instant their recorded verdict
6
+ * is not `success`, and neither carries an attempt counter. The halt surface
7
+ * they emit is a *user* question block with no `@agent-directive:` line, so a
8
+ * red check the agent could have fixed unaided still costs a user round-trip.
9
+ *
10
+ * What this module adds is a counter and two floors — nothing else. It
11
+ * deliberately adds **no critic**: the verdict is already a deterministic
12
+ * value the engine holds in hand, so there is no judgement for a second model
13
+ * to make. That distinction is why the TERMINAL honest null on
14
+ * `recursive-verification` (ADR-106: capability 87% vs 87%, McNemar p=1.0)
15
+ * does not bind here — the measured arm added a critic to decide whether an
16
+ * attempt was good enough, and its killer finding was that cost scaled with
17
+ * *all* tasks while benefit sat in the ~28% tail. A red-check retry fires only
18
+ * on a red: zero cost on the passing majority.
19
+ *
20
+ * The null does bind one thing, and it is honoured: the falsification shape.
21
+ * "The loop is redundant" must remain discoverable, so the loop never converts
22
+ * a red into a green. Every exit it owns is `PARTIAL` with the red verdict
23
+ * still on the surface.
24
+ *
25
+ * Two floors, neither invented here:
26
+ *
27
+ * - **Ceiling** — {@link SELF_FIX_CEILING} attempts per lane, which is the
28
+ * N=3 validation-loop budget from the `autonomous-execution` rule, applied
29
+ * per validation target (that rule resets its counter on a different
30
+ * target, so the counters below are per-lane rather than per-run).
31
+ * - **No-progress** — two consecutive attempts producing an identical verdict
32
+ * signature stop the loop immediately, budget remaining or not. This is the
33
+ * floor the `recursive-verification` skill already stated in prose ("two
34
+ * consecutive attempts score identical on the deterministic scorer; further
35
+ * depth cannot help, so stop"), adopted as code rather than left as advice,
36
+ * and it matches `context-hygiene`'s "same failure signature twice → stop
37
+ * and pivot now".
38
+ *
39
+ * No-progress is checked BEFORE the ceiling on purpose: an unchanged signature
40
+ * means the remaining budget cannot help, so spending it would be the exact
41
+ * wasted-attempt pattern both rules name.
42
+ */
43
+
44
+ import type { DeliveryState } from '../../delivery_state.js';
45
+ import { type Any, Outcome, StepResult, agent_directive } from '../../delivery_state.js';
46
+
47
+ /**
48
+ * Attempts allowed per lane before the loop exits PARTIAL.
49
+ *
50
+ * Deliberately the `autonomous-execution` N=3 budget rather than a fresh
51
+ * number: a second, differently-sized retry ceiling in the same package would
52
+ * be a rule the tree contradicts.
53
+ */
54
+ export const SELF_FIX_CEILING = 3;
55
+
56
+ /** Lanes that own a bounded loop. One counter each — they are distinct targets. */
57
+ export const SELF_FIX_LANES = ['test', 'verify'] as const;
58
+
59
+ export type SelfFixLane = (typeof SELF_FIX_LANES)[number];
60
+
61
+ /**
62
+ * Keys excluded from the verdict signature at every depth.
63
+ *
64
+ * Without this the no-progress floor could never fire: a test verdict carries
65
+ * `duration_ms`, which changes on every run, so two byte-identical failures
66
+ * would sign differently and the loop would burn its whole budget on a target
67
+ * it was making no progress against.
68
+ */
69
+ export const VOLATILE_KEYS: ReadonlyArray<string> = [
70
+ 'duration_ms',
71
+ 'elapsed_ms',
72
+ 'timestamp',
73
+ 'started_at',
74
+ 'finished_at',
75
+ 'ran_at',
76
+ ];
77
+
78
+ /** Why the loop stopped, or that it has budget left. */
79
+ export type SelfFixKind = 'retry' | 'exhausted' | 'no_progress';
80
+
81
+ /** Verdict of {@link decide} — pure, so the caller owns every mutation. */
82
+ export interface SelfFixDecision {
83
+ kind: SelfFixKind;
84
+ /** Attempts already spent on this lane before this decision. */
85
+ attempts: number;
86
+ /** 1-based number of the attempt a `retry` authorises. */
87
+ next_attempt: number;
88
+ ceiling: number;
89
+ signature: string;
90
+ }
91
+
92
+ /**
93
+ * Canonical, volatile-free signature of a recorded verdict.
94
+ *
95
+ * Two failures are "the same failure" when this string matches. Object keys
96
+ * are sorted so key order in the recorded state cannot masquerade as progress.
97
+ */
98
+ export function verdict_signature(lane: string, verdict_payload: Any): string {
99
+ return `${lane}:${_canonical(verdict_payload)}`;
100
+ }
101
+
102
+ /** Read the per-lane counter without mutating anything. */
103
+ export function decide(state: DeliveryState, lane: string, signature: string): SelfFixDecision {
104
+ const lane_state = _lane_state(state, lane);
105
+ const attempts = _nonNegativeInt(lane_state['attempts']);
106
+ const signatures = Array.isArray(lane_state['signatures'])
107
+ ? (lane_state['signatures'] as Any[]).filter((s): s is string => typeof s === 'string')
108
+ : [];
109
+ const previous = signatures.length > 0 ? signatures[signatures.length - 1] : null;
110
+
111
+ const base = {
112
+ attempts,
113
+ next_attempt: attempts + 1,
114
+ ceiling: SELF_FIX_CEILING,
115
+ signature,
116
+ };
117
+
118
+ // No-progress before the ceiling: an unchanged signature means the
119
+ // remaining budget cannot move this target, so spending it is waste.
120
+ if (previous !== null && previous === signature) {
121
+ return { kind: 'no_progress', ...base };
122
+ }
123
+ if (attempts >= SELF_FIX_CEILING) {
124
+ return { kind: 'exhausted', ...base };
125
+ }
126
+ return { kind: 'retry', ...base };
127
+ }
128
+
129
+ /**
130
+ * Spend one attempt on `lane` and remember its signature.
131
+ *
132
+ * Mutates `state.self_fix` in place, which is how the counter survives the
133
+ * halt: the dispatcher persists the state it was handed, so the next
134
+ * invocation reads the incremented value. Callers must invoke this exactly
135
+ * once per `retry` decision — recording on an exit would inflate the count.
136
+ */
137
+ export function record_attempt(state: DeliveryState, lane: string, signature: string): void {
138
+ const container = _pyTruthy(state.self_fix) ? (state.self_fix as Record<string, Any>) : {};
139
+ const lane_state = _lane_state(state, lane);
140
+ const signatures = Array.isArray(lane_state['signatures'])
141
+ ? (lane_state['signatures'] as Any[]).filter((s): s is string => typeof s === 'string')
142
+ : [];
143
+ container[lane] = {
144
+ attempts: _nonNegativeInt(lane_state['attempts']) + 1,
145
+ signatures: [...signatures, signature],
146
+ };
147
+ state.self_fix = container;
148
+ }
149
+
150
+ /** DoD entries the agent has not recorded as proven. Never inferred. */
151
+ export function unmet_dod(state: DeliveryState): Array<Record<string, Any>> {
152
+ const dod = (state.ticket ?? {})['dod'];
153
+ if (!Array.isArray(dod)) {
154
+ return [];
155
+ }
156
+ return (dod as Any[]).filter(
157
+ (item): item is Record<string, Any> => _isPlainObject(item) && item['proven'] !== true,
158
+ );
159
+ }
160
+
161
+ /**
162
+ * BLOCKED halt that delegates the fix instead of asking the user.
163
+ *
164
+ * The `@agent-directive:` first line is what makes this an agent round-trip
165
+ * rather than a user one — the same delegation shape `run-tests` and
166
+ * `review-changes` already use. The numbered options stay, because an
167
+ * orchestrator that does not honour directives must still leave the human
168
+ * something to act on.
169
+ */
170
+ export function retry_halt(args: {
171
+ lane: string;
172
+ ticket_id: string;
173
+ verdict: Any;
174
+ decision: SelfFixDecision;
175
+ fix_hint: string;
176
+ rerun_directive: string;
177
+ }): StepResult {
178
+ const { lane, ticket_id, verdict, decision, fix_hint, rerun_directive } = args;
179
+ return new StepResult({
180
+ outcome: Outcome.BLOCKED,
181
+ questions: [
182
+ agent_directive('fix-failing-checks', {
183
+ ticket: ticket_id,
184
+ lane,
185
+ attempt: decision.next_attempt,
186
+ ceiling: decision.ceiling,
187
+ }),
188
+ `> Ticket ${ticket_id} — \`${lane}\` reported \`${String(verdict)}\`. ` +
189
+ `Self-fix attempt ${decision.next_attempt} of ${decision.ceiling}.`,
190
+ `> The verdict is deterministic, so the fix is delegated rather than asked: ${fix_hint}`,
191
+ `> 1. Continue — fix the failures and re-run \`${rerun_directive}\``,
192
+ '> 2. Abort — stop this cycle and hand the failures back',
193
+ ],
194
+ message:
195
+ `Ticket ${ticket_id} ${lane} verdict was \`${String(verdict)}\`; ` +
196
+ `self-fix attempt ${decision.next_attempt}/${decision.ceiling} delegated.`,
197
+ });
198
+ }
199
+
200
+ /**
201
+ * PARTIAL exit — the loop stopped and the check is STILL RED.
202
+ *
203
+ * `PARTIAL` rather than `BLOCKED` because attempts were spent and changes may
204
+ * have landed, and emphatically not `SUCCESS`: the risk this loop carries is
205
+ * that it converts a visible red into an invisible one, which is worse than
206
+ * the round-trip it removes. The dispatcher halts on PARTIAL exactly as it
207
+ * halts on BLOCKED, and the red verdict is the second line of the surface.
208
+ */
209
+ export function partial_exit(args: {
210
+ lane: string;
211
+ ticket_id: string;
212
+ verdict: Any;
213
+ decision: SelfFixDecision;
214
+ unmet: Array<Record<string, Any>>;
215
+ rerun_directive: string;
216
+ }): StepResult {
217
+ const { lane, ticket_id, verdict, decision, unmet, rerun_directive } = args;
218
+ const reason =
219
+ decision.kind === 'no_progress'
220
+ ? `two consecutive attempts produced an identical \`${lane}\` verdict, ` +
221
+ 'so further attempts cannot help'
222
+ : `the ${decision.ceiling}-attempt budget for \`${lane}\` is spent`;
223
+ const dod_lines =
224
+ unmet.length > 0
225
+ ? [
226
+ '> Definition-of-done items still unproven:',
227
+ ...unmet.map((item) => {
228
+ const id = typeof item['id'] === 'string' ? item['id'] : '(no id)';
229
+ const check = typeof item['check'] === 'string' ? item['check'] : '(no check)';
230
+ return `> - \`${id}\` — \`${check}\``;
231
+ }),
232
+ ]
233
+ : [];
234
+ return new StepResult({
235
+ outcome: Outcome.PARTIAL,
236
+ questions: [
237
+ `> Ticket ${ticket_id} — self-fix stopped after ` +
238
+ `${decision.attempts} attempt(s): ${reason}.`,
239
+ `> \`${lane}\` is STILL \`${String(verdict)}\`. Nothing here claims completion.`,
240
+ ...dod_lines,
241
+ `> 1. I'll take it from here — hand me the failures and re-run \`${rerun_directive}\``,
242
+ '> 2. Continue anyway — override on a red verdict (NOT recommended)',
243
+ '> 3. Abort',
244
+ ],
245
+ message:
246
+ `Ticket ${ticket_id} ${lane} verdict is \`${String(verdict)}\` after ` +
247
+ `${decision.attempts} self-fix attempt(s) (${decision.kind}); exiting PARTIAL.`,
248
+ });
249
+ }
250
+
251
+ /** Per-lane record, defaulted without writing anything back. */
252
+ function _lane_state(state: DeliveryState, lane: string): Record<string, Any> {
253
+ const container = _pyTruthy(state.self_fix) ? (state.self_fix as Record<string, Any>) : {};
254
+ const lane_state = container[lane];
255
+ return _isPlainObject(lane_state) ? lane_state : {};
256
+ }
257
+
258
+ /** Ints only; a bool, float, negative, or non-number resets to 0. */
259
+ function _nonNegativeInt(value: Any): number {
260
+ if (typeof value !== 'number' || typeof value === 'boolean') {
261
+ return 0;
262
+ }
263
+ if (!Number.isInteger(value) || value < 0) {
264
+ return 0;
265
+ }
266
+ return value;
267
+ }
268
+
269
+ /**
270
+ * Deterministic JSON rendering with sorted keys and volatile keys removed.
271
+ *
272
+ * Hand-rolled rather than `JSON.stringify`: the replacer form cannot sort
273
+ * object keys, and key order is exactly what must not leak into the signature.
274
+ */
275
+ function _canonical(value: Any): string {
276
+ if (value === null || value === undefined) {
277
+ return 'null';
278
+ }
279
+ if (typeof value === 'boolean' || typeof value === 'number') {
280
+ return String(value);
281
+ }
282
+ if (typeof value === 'string') {
283
+ return JSON.stringify(value);
284
+ }
285
+ if (Array.isArray(value)) {
286
+ return '[' + value.map((v) => _canonical(v)).join(',') + ']';
287
+ }
288
+ if (_isPlainObject(value)) {
289
+ const keys = Object.keys(value)
290
+ .filter((k) => !VOLATILE_KEYS.includes(k))
291
+ .sort();
292
+ return '{' + keys.map((k) => `${JSON.stringify(k)}:${_canonical(value[k])}`).join(',') + '}';
293
+ }
294
+ return JSON.stringify(String(value));
295
+ }
296
+
297
+ /** Python truthiness for the container kinds this module reads. */
298
+ function _pyTruthy(value: Any): boolean {
299
+ if (value === null || value === undefined || value === false) {
300
+ return false;
301
+ }
302
+ if (value === true) {
303
+ return true;
304
+ }
305
+ if (typeof value === 'number') {
306
+ return value !== 0;
307
+ }
308
+ if (typeof value === 'string') {
309
+ return value.length !== 0;
310
+ }
311
+ if (Array.isArray(value)) {
312
+ return value.length !== 0;
313
+ }
314
+ if (value instanceof Set || value instanceof Map) {
315
+ return value.size !== 0;
316
+ }
317
+ if (typeof value === 'object') {
318
+ return Object.keys(value as Record<string, Any>).length !== 0;
319
+ }
320
+ return true;
321
+ }
322
+
323
+ /** True for a dict-like value (mirrors Python `isinstance(x, dict)`). */
324
+ function _isPlainObject(value: Any): value is Record<string, Any> {
325
+ return (
326
+ typeof value === 'object' &&
327
+ value !== null &&
328
+ !Array.isArray(value) &&
329
+ !(value instanceof Set) &&
330
+ !(value instanceof Map)
331
+ );
332
+ }
@@ -7,7 +7,9 @@
7
7
  * part of the contract).
8
8
  *
9
9
  * The step never calls an LLM. It inspects `state.ticket` (which carries
10
- * `input.data` after the CLI projection) and routes on shape:
10
+ * `input.data` after the CLI projection), shape-checks the optional
11
+ * `dod[]` slot (the executable definition-of-done —
12
+ * `src/scripts/schemas/dod.schema.json`), and routes on shape:
11
13
  *
12
14
  * - **Ticket envelope** (`id`, `title`, `acceptance_criteria`) — the
13
15
  * R1 path. Validates the minimum viable shape and either returns
@@ -84,6 +86,15 @@ export const AMBIGUITIES: ReadonlyArray<Record<string, string>> = [
84
86
  'user answers one clarifying question; the agent ' +
85
87
  're-runs `refine-prompt` against the refreshed prompt',
86
88
  },
89
+ {
90
+ code: 'malformed_dod',
91
+ trigger:
92
+ '`dod` key present but not a list, or an entry missing a ' +
93
+ 'non-empty `id` / `check` string',
94
+ resolution:
95
+ 'fix the `dod[]` entries against `src/scripts/schemas/dod.schema.json`, ' +
96
+ 'or drop the key — the slot is optional',
97
+ },
87
98
  {
88
99
  code: 'prompt_ui_intent',
89
100
  trigger:
@@ -99,6 +110,27 @@ export const AMBIGUITIES: ReadonlyArray<Record<string, string>> = [
99
110
  /** Route on envelope shape: ticket path or prompt path. */
100
111
  export function run(state: DeliveryState): StepResult {
101
112
  const data = state.ticket || {};
113
+
114
+ // The `dod[]` slot is shape-checked on BOTH paths before either routes, so
115
+ // a malformed definition-of-done cannot reach the self-fix loop that
116
+ // reports it. Absent key → no check, no behaviour change.
117
+ const dod_issues = diagnose_dod(data);
118
+ if (dod_issues.length > 0) {
119
+ const dod_ticket_id = _pyTruthy(data.id) ? _pyStr(data.id) : '(no id)';
120
+ return new StepResult({
121
+ outcome: Outcome.BLOCKED,
122
+ questions: [
123
+ `> Ticket ${dod_ticket_id} — the \`dod[]\` slot is malformed: ` + dod_issues.join('; ') + '.',
124
+ '> Every entry needs a non-empty `id` and a non-empty `check` ' +
125
+ '(the command that proves it) — prose there cannot be run.',
126
+ '> 1. Fix the `dod[]` entries and re-invoke',
127
+ '> 2. Drop the `dod` key — the slot is optional',
128
+ '> 3. Abort',
129
+ ],
130
+ message: `Ticket ${dod_ticket_id} has a malformed dod[] slot: ` + dod_issues.join('; '),
131
+ });
132
+ }
133
+
102
134
  if (_is_prompt_envelope(data)) {
103
135
  return _run_prompt(state, data);
104
136
  }
@@ -117,6 +149,53 @@ export function run(state: DeliveryState): StepResult {
117
149
  });
118
150
  }
119
151
 
152
+ /**
153
+ * Report what is wrong with an envelope's `dod[]` slot; `[]` when it is fine.
154
+ *
155
+ * Exported so the shape is testable on its own and so a caller can ask the
156
+ * question without triggering a halt. An absent key is valid — the slot is
157
+ * optional and omitting it means the author never declared a machine-checkable
158
+ * done-condition, which is different from declaring an empty one.
159
+ *
160
+ * `check` is required to be non-empty for the reason the schema states: the
161
+ * dispatcher spawns no subprocesses, so `check` is handed to an agent to run,
162
+ * and an agent cannot run a sentence.
163
+ */
164
+ export function diagnose_dod(data: Record<string, Any>): string[] {
165
+ if (!_isPlainObject(data) || !('dod' in data)) {
166
+ return [];
167
+ }
168
+ const dod = data.dod;
169
+ if (!Array.isArray(dod)) {
170
+ return [`\`dod\` must be a list, got ${_pyTypeName(dod)}`];
171
+ }
172
+ const issues: string[] = [];
173
+ const seen = new Set<string>();
174
+ dod.forEach((entry, idx) => {
175
+ const position = idx + 1;
176
+ if (!_isPlainObject(entry)) {
177
+ issues.push(`entry ${position} must be an object, got ${_pyTypeName(entry)}`);
178
+ return;
179
+ }
180
+ const id = entry.id;
181
+ if (typeof id !== 'string' || !id.trim()) {
182
+ issues.push(`entry ${position} has no \`id\``);
183
+ } else if (seen.has(id)) {
184
+ issues.push(`entry ${position} repeats id \`${id}\``);
185
+ } else {
186
+ seen.add(id);
187
+ }
188
+ const check = entry.check;
189
+ if (typeof check !== 'string' || !check.trim()) {
190
+ issues.push(`entry ${position} has no \`check\` command`);
191
+ }
192
+ if ('proven' in entry && typeof entry.proven !== 'boolean') {
193
+ issues.push(`entry ${position} has a non-boolean \`proven\``);
194
+ }
195
+ });
196
+ return issues;
197
+ }
198
+
120
199
  /**
121
200
  * True when `state.ticket` carries a prompt envelope.
122
201
  *
@@ -442,6 +521,32 @@ function _pyTruthy(value: unknown): boolean {
442
521
  return true;
443
522
  }
444
523
 
524
+ /** Python `type(x).__name__` for the value kinds the dod diagnose path sees. */
525
+ function _pyTypeName(value: unknown): string {
526
+ if (value === null || value === undefined) {
527
+ return 'NoneType';
528
+ }
529
+ if (typeof value === 'boolean') {
530
+ return 'bool';
531
+ }
532
+ if (typeof value === 'number') {
533
+ return Number.isInteger(value) ? 'int' : 'float';
534
+ }
535
+ if (typeof value === 'string') {
536
+ return 'str';
537
+ }
538
+ if (Array.isArray(value)) {
539
+ return 'list';
540
+ }
541
+ if (value instanceof Set) {
542
+ return 'set';
543
+ }
544
+ if (value instanceof Map || _isPlainObject(value)) {
545
+ return 'dict';
546
+ }
547
+ return typeof value;
548
+ }
549
+
445
550
  /** True for a dict-like value (mirrors Python `isinstance(x, dict)`). */
446
551
  function _isPlainObject(value: unknown): value is Record<string, unknown> {
447
552
  return (
@@ -17,10 +17,12 @@
17
17
  * - Must be a dict.
18
18
  * - Must carry a `verdict` key — one of `success`, `failed`,
19
19
  * or `mixed` (targeted vs full-suite split). Anything else blocks.
20
- * - `failed` or `mixed` verdicts halt with the verdict as part of
21
- * the surfaced message so the user decides whether to continue or
22
- * stop. This follows the `verify-before-complete` rule: a bad test
23
- * outcome must never be silently skipped.
20
+ * - `failed` or `mixed` verdicts enter the bounded self-fix loop
21
+ * (`./_self_fix.ts`): the first attempts are delegated by directive, and an
22
+ * exhausted or non-progressing loop exits `PARTIAL` with the verdict still
23
+ * on the surface so the user decides whether to continue or stop. This
24
+ * follows the `verify-before-complete` rule: a bad test outcome must never
25
+ * be silently skipped, and the loop cannot report one as success.
24
26
  * - Optional keys (`targeted`, `full`, `duration_ms`,
25
27
  * `followups`) feed the delivery report.
26
28
  */
@@ -28,6 +30,7 @@
28
30
  import type { DeliveryState} from '../../delivery_state.js';
29
31
  import { type Any, Outcome, StepResult, agent_directive } from '../../delivery_state.js';
30
32
  import { resolve_policy } from '../../persona_policy.js';
33
+ import { decide, partial_exit, record_attempt, retry_halt, unmet_dod, verdict_signature } from './_self_fix.js';
31
34
 
32
35
  const _ALLOWED_VERDICTS = ['success', 'failed', 'mixed'] as const;
33
36
 
@@ -53,7 +56,18 @@ export const AMBIGUITIES: ReadonlyArray<Record<string, string>> = [
53
56
  {
54
57
  code: 'bad_test_verdict',
55
58
  trigger: '`state.tests[\'verdict\']` is `failed` or `mixed`',
56
- resolution: 'fix failures and re-run, or abort',
59
+ resolution:
60
+ 'bounded self-fix loop: agent directive `fix-failing-checks` ' +
61
+ 'while attempts remain and the verdict signature keeps changing',
62
+ },
63
+ {
64
+ code: 'self_fix_exhausted',
65
+ trigger:
66
+ 'the self-fix budget for `test` is spent, or two consecutive ' +
67
+ 'attempts produced an identical verdict signature',
68
+ resolution:
69
+ 'PARTIAL honest exit — the red verdict stays on the surface, ' +
70
+ 'the user decides whether to take over, override, or abort',
57
71
  },
58
72
  ];
59
73
 
@@ -156,18 +170,39 @@ function _blocked_on_shape(state: DeliveryState, issues: string[]): StepResult {
156
170
  });
157
171
  }
158
172
 
173
+ /**
174
+ * Route a red test verdict through the bounded self-fix loop.
175
+ *
176
+ * Before this loop existed the function below returned a directive-free
177
+ * BLOCKED — a user question block — so every red cost a user round-trip even
178
+ * when the failure was one the agent could fix unaided. Now the first attempts
179
+ * are delegated and only an exhausted or non-progressing loop reaches the
180
+ * user, as a PARTIAL that still carries the red verdict.
181
+ */
159
182
  function _blocked_on_bad_verdict(state: DeliveryState, verdict: Any): StepResult {
160
183
  const ticketId = _ticketId(state);
161
- return new StepResult({
162
- outcome: Outcome.BLOCKED,
163
- questions: [
164
- `> Ticket ${ticketId} — tests reported \`${String(verdict)}\`. ` +
165
- 'Verification cannot proceed on a non-success verdict.',
166
- '> 1. Fix the failing tests and re-run `run-tests`',
167
- '> 2. Continue anyway — override (NOT recommended)',
168
- '> 3. Abort',
169
- ],
170
- message: `Ticket ${ticketId} test verdict was \`${String(verdict)}\`, not success.`,
184
+ const signature = verdict_signature('test', state.tests);
185
+ const decision = decide(state, 'test', signature);
186
+
187
+ if (decision.kind === 'retry') {
188
+ record_attempt(state, 'test', signature);
189
+ return retry_halt({
190
+ lane: 'test',
191
+ ticket_id: ticketId,
192
+ verdict,
193
+ decision,
194
+ fix_hint: 'read the failing assertions, fix the cause, re-run the same filter.',
195
+ rerun_directive: 'run-tests',
196
+ });
197
+ }
198
+
199
+ return partial_exit({
200
+ lane: 'test',
201
+ ticket_id: ticketId,
202
+ verdict,
203
+ decision,
204
+ unmet: unmet_dod(state),
205
+ rerun_directive: 'run-tests',
171
206
  });
172
207
  }
173
208
 
@@ -18,9 +18,12 @@
18
18
  * `partial`. Matches the `Outcome` vocabulary used everywhere
19
19
  * else in the flow.
20
20
  * - A `success` verdict advances the flow to `report`.
21
- * - A `blocked` or `partial` verdict halts with numbered options
22
- * so the user decides whether to address the findings, override
23
- * (rarely appropriate), or abort.
21
+ * - A `blocked` or `partial` verdict enters the bounded self-fix loop
22
+ * (`./_self_fix.ts`): while attempts remain and the verdict signature
23
+ * keeps changing, the fix is delegated by directive. An exhausted or
24
+ * non-progressing loop exits `PARTIAL` with numbered options so the user
25
+ * decides whether to take over, override (rarely appropriate), or abort.
26
+ * The loop never turns a non-success verdict into `SUCCESS`.
24
27
  * - Optional keys (`confidence`, `findings`, `followups`) feed
25
28
  * the delivery report.
26
29
  */
@@ -28,6 +31,7 @@
28
31
  import type { DeliveryState} from '../../delivery_state.js';
29
32
  import { type Any, Outcome, StepResult, agent_directive } from '../../delivery_state.js';
30
33
  import { resolve_policy } from '../../persona_policy.js';
34
+ import { decide, partial_exit, record_attempt, retry_halt, unmet_dod, verdict_signature } from './_self_fix.js';
31
35
 
32
36
  const _ALLOWED_VERDICTS = ['success', 'blocked', 'partial'] as const;
33
37
 
@@ -52,7 +56,17 @@ export const AMBIGUITIES: ReadonlyArray<Record<string, string>> = [
52
56
  code: 'bad_verify_verdict',
53
57
  trigger: '`state.verify[\'verdict\']` is `blocked` or `partial`',
54
58
  resolution:
55
- 'address findings and re-run `/review-changes` — never bypass ' + '(see `verify-before-complete`)',
59
+ 'bounded self-fix loop: agent directive `fix-failing-checks` ' +
60
+ 'while attempts remain — never bypass ' + '(see `verify-before-complete`)',
61
+ },
62
+ {
63
+ code: 'self_fix_exhausted',
64
+ trigger:
65
+ 'the self-fix budget for `verify` is spent, or two consecutive ' +
66
+ 'attempts produced an identical verdict signature',
67
+ resolution:
68
+ 'PARTIAL honest exit — the non-success verdict stays on the ' +
69
+ 'surface; the user takes over, overrides, or aborts',
56
70
  },
57
71
  ];
58
72
 
@@ -145,19 +159,39 @@ function _blocked_on_shape(state: DeliveryState, issues: string[]): StepResult {
145
159
  });
146
160
  }
147
161
 
162
+ /**
163
+ * Route a red review verdict through the bounded self-fix loop.
164
+ *
165
+ * Same shape as the `test` lane, separate counter: `autonomous-execution`
166
+ * resets its N=3 budget on a different validation target, and a review finding
167
+ * is not a failing test. `verify-before-complete` is unaffected — the loop
168
+ * cannot report completion, and its exhausted exit is PARTIAL with the
169
+ * non-success verdict still on the surface.
170
+ */
148
171
  function _blocked_on_bad_verdict(state: DeliveryState, verdict: Any): StepResult {
149
172
  const ticketId = _ticketId(state);
150
- return new StepResult({
151
- outcome: Outcome.BLOCKED,
152
- questions: [
153
- `> Ticket ${ticketId} — \`review-changes\` reported ` +
154
- `\`${String(verdict)}\`. The delivery report cannot claim completion on a ` +
155
- 'non-success verdict (see `verify-before-complete`).',
156
- '> 1. Address the findings and re-run `review-changes`',
157
- '> 2. Continue anyway — override (NOT recommended)',
158
- '> 3. Abort',
159
- ],
160
- message: `Ticket ${ticketId} verify verdict was \`${String(verdict)}\`, not success.`,
173
+ const signature = verdict_signature('verify', state.verify);
174
+ const decision = decide(state, 'verify', signature);
175
+
176
+ if (decision.kind === 'retry') {
177
+ record_attempt(state, 'verify', signature);
178
+ return retry_halt({
179
+ lane: 'verify',
180
+ ticket_id: ticketId,
181
+ verdict,
182
+ decision,
183
+ fix_hint: 'address the recorded findings, then re-run the four-judge review.',
184
+ rerun_directive: 'review-changes',
185
+ });
186
+ }
187
+
188
+ return partial_exit({
189
+ lane: 'verify',
190
+ ticket_id: ticketId,
191
+ verdict,
192
+ decision,
193
+ unmet: unmet_dod(state),
194
+ rerun_directive: 'review-changes',
161
195
  });
162
196
  }
163
197