harness-reflex 0.1.0 → 0.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 (121) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +103 -23
  3. package/USER_GUIDE.md +121 -43
  4. package/dist/adapters/agy.js +1 -1
  5. package/dist/adapters/agy.js.map +1 -1
  6. package/dist/adapters/codex.d.ts +133 -4
  7. package/dist/adapters/codex.js +325 -2
  8. package/dist/adapters/codex.js.map +1 -1
  9. package/dist/backend/defaults.d.ts +31 -0
  10. package/dist/backend/defaults.js +32 -0
  11. package/dist/backend/defaults.js.map +1 -0
  12. package/dist/backend/jev.js +6 -5
  13. package/dist/backend/jev.js.map +1 -1
  14. package/dist/backend/mock.d.ts +12 -1
  15. package/dist/backend/mock.js +34 -0
  16. package/dist/backend/mock.js.map +1 -1
  17. package/dist/backend/simple-jev.js +5 -4
  18. package/dist/backend/simple-jev.js.map +1 -1
  19. package/dist/backend/types.d.ts +34 -0
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/cli/index.js +5 -3
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/core/closing.d.ts +90 -0
  24. package/dist/core/closing.js +111 -0
  25. package/dist/core/closing.js.map +1 -0
  26. package/dist/core/evidence.d.ts +119 -0
  27. package/dist/core/evidence.js +209 -0
  28. package/dist/core/evidence.js.map +1 -0
  29. package/dist/core/judge.d.ts +221 -0
  30. package/dist/core/judge.js +251 -0
  31. package/dist/core/judge.js.map +1 -0
  32. package/dist/core/orchestrate-closing.d.ts +237 -0
  33. package/dist/core/orchestrate-closing.js +250 -0
  34. package/dist/core/orchestrate-closing.js.map +1 -0
  35. package/dist/core/orchestrate-correction.d.ts +209 -0
  36. package/dist/core/orchestrate-correction.js +141 -0
  37. package/dist/core/orchestrate-correction.js.map +1 -0
  38. package/dist/core/orchestrate-host.d.ts +225 -0
  39. package/dist/core/orchestrate-host.js +80 -0
  40. package/dist/core/orchestrate-host.js.map +1 -0
  41. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  42. package/dist/core/orchestrate-stagnation.js +270 -0
  43. package/dist/core/orchestrate-stagnation.js.map +1 -0
  44. package/dist/core/orchestrate.d.ts +357 -0
  45. package/dist/core/orchestrate.js +418 -0
  46. package/dist/core/orchestrate.js.map +1 -0
  47. package/dist/core/policy.d.ts +122 -0
  48. package/dist/core/policy.js +102 -0
  49. package/dist/core/policy.js.map +1 -0
  50. package/dist/core/prune-plan.d.ts +141 -0
  51. package/dist/core/prune-plan.js +390 -0
  52. package/dist/core/prune-plan.js.map +1 -0
  53. package/dist/core/score.d.ts +2 -2
  54. package/dist/core/score.js.map +1 -1
  55. package/dist/core/text.d.ts +36 -0
  56. package/dist/core/text.js +66 -0
  57. package/dist/core/text.js.map +1 -0
  58. package/dist/hook/cli.d.ts +9 -0
  59. package/dist/hook/cli.js +52 -0
  60. package/dist/hook/cli.js.map +1 -0
  61. package/dist/hook/contract.d.ts +125 -0
  62. package/dist/hook/contract.js +159 -0
  63. package/dist/hook/contract.js.map +1 -0
  64. package/dist/hook/decision.d.ts +97 -0
  65. package/dist/hook/decision.js +955 -0
  66. package/dist/hook/decision.js.map +1 -0
  67. package/dist/hook/memory-store.d.ts +81 -0
  68. package/dist/hook/memory-store.js +157 -0
  69. package/dist/hook/memory-store.js.map +1 -0
  70. package/dist/hook/payload.d.ts +55 -0
  71. package/dist/hook/payload.js +129 -0
  72. package/dist/hook/payload.js.map +1 -0
  73. package/dist/hook/run.d.ts +48 -0
  74. package/dist/hook/run.js +218 -0
  75. package/dist/hook/run.js.map +1 -0
  76. package/dist/hook/store-port.d.ts +72 -0
  77. package/dist/hook/store-port.js +2 -0
  78. package/dist/hook/store-port.js.map +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +1 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/ports/audit.d.ts +18 -0
  83. package/dist/ports/audit.js +11 -0
  84. package/dist/ports/audit.js.map +1 -0
  85. package/dist/ports/clock.d.ts +14 -0
  86. package/dist/ports/clock.js +11 -0
  87. package/dist/ports/clock.js.map +1 -0
  88. package/dist/ports/decision.d.ts +75 -0
  89. package/dist/ports/decision.js +2 -0
  90. package/dist/ports/decision.js.map +1 -0
  91. package/dist/ports/index.d.ts +14 -0
  92. package/dist/ports/index.js +2 -0
  93. package/dist/ports/index.js.map +1 -0
  94. package/dist/ports/log.d.ts +22 -0
  95. package/dist/ports/log.js +12 -0
  96. package/dist/ports/log.js.map +1 -0
  97. package/dist/ports/state.d.ts +46 -0
  98. package/dist/ports/state.js +13 -0
  99. package/dist/ports/state.js.map +1 -0
  100. package/dist/state/clock.d.ts +40 -0
  101. package/dist/state/clock.js +43 -0
  102. package/dist/state/clock.js.map +1 -0
  103. package/dist/state/file-store.d.ts +340 -0
  104. package/dist/state/file-store.js +849 -0
  105. package/dist/state/file-store.js.map +1 -0
  106. package/dist/state/paths.d.ts +41 -0
  107. package/dist/state/paths.js +73 -0
  108. package/dist/state/paths.js.map +1 -0
  109. package/docs/USER_GUIDE.en.md +79 -36
  110. package/docs/claude-code.md +281 -0
  111. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  112. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  113. package/docs/dsh-plugin.md +54 -54
  114. package/docs/release-checklist-v0.1.0.md +32 -21
  115. package/docs/release-handbook-porting-notes.md +11 -11
  116. package/docs/release-handbook.md +55 -30
  117. package/docs/release-notes-v0.1.0.md +27 -14
  118. package/docs/release-notes-v0.3.0.md +152 -0
  119. package/docs/research/claude-code-harness.md +607 -0
  120. package/docs/research/pi-harness.md +621 -0
  121. package/package.json +16 -7
@@ -0,0 +1,955 @@
1
+ import { claimCandidates, claimsOf, closingSkipReason, contradictedOf } from '../core/closing.js';
2
+ import { assembleEvidence, evidenceOf } from '../core/evidence.js';
3
+ import { countTrailingFailures, suspicionOf } from '../core/judge.js';
4
+ import { applyPruneFloor } from '../core/prune-plan.js';
5
+ import { clip, digestOf, estimateTokens } from '../core/text.js';
6
+ import { emptyHookOutput, preToolUseDeny, postToolUseFailureContext, postToolUseReplace, sessionStartContext, stopBlock } from './contract.js';
7
+ import { EVENT_BUDGETS } from './contract.js';
8
+ export const MAX_STDIN_BYTES = 8 * 1024 * 1024;
9
+ /** Defaults mirrored from the DSH intervention policy (config.ts). */
10
+ export const DEFAULT_HOOK_CONFIG = {
11
+ maxInterventionsPerTurn: 3,
12
+ maxJudgmentsPerTurn: 3,
13
+ maxJudgmentsPerSession: 20,
14
+ repeatThreshold: 3,
15
+ failureThreshold: 3,
16
+ windowSize: 6,
17
+ minConfidence: 0.6,
18
+ pruneThreshold: 500,
19
+ pruneMinLines: 4,
20
+ maxRetainedChars: 100_000,
21
+ pruneFloorRatio: 0.5,
22
+ pruneHeadChars: 400,
23
+ pruneTailChars: 400,
24
+ claimMinConfidence: 0.6,
25
+ closingEvidenceChars: 2000,
26
+ closingIntent: 'verify a completion claim against this turn\'s tool evidence',
27
+ maxClosingBlocksPerTurn: 2,
28
+ eventBudgets: EVENT_BUDGETS
29
+ };
30
+ /** A stable label for `meta.mode`, the only place a single mode string is stored. */
31
+ export function modeLabel(modes) {
32
+ const values = [modes.stagnation, modes.prune, modes.gate, modes.closing];
33
+ if (values.every((value) => value === 'active'))
34
+ return 'active';
35
+ if (values.every((value) => value === 'off'))
36
+ return 'off';
37
+ if (values.every((value) => value === 'observe'))
38
+ return 'observe';
39
+ return 'mixed';
40
+ }
41
+ /**
42
+ * The S3 default: the three tool-call interventions act, the closing check only
43
+ * observes. A closing block is the most destructive action available (it keeps
44
+ * the user's turn open), so it ships opt-in (design §4.2).
45
+ */
46
+ export const DEFAULT_CAPABILITY_MODES = {
47
+ stagnation: 'active',
48
+ prune: 'active',
49
+ gate: 'active',
50
+ closing: 'observe'
51
+ };
52
+ /** One explicit three-state value, or `undefined` when unset/unknown. */
53
+ function explicitMode(raw) {
54
+ const value = raw?.trim().toLowerCase();
55
+ return value === 'off' || value === 'observe' || value === 'active' ? value : undefined;
56
+ }
57
+ /**
58
+ * Resolve the per-capability modes.
59
+ *
60
+ * Precedence, highest first:
61
+ * 1. `HARNESS_REFLEX_MODE` — one global override, kept for the S2 fixtures and
62
+ * for users who want to silence or shadow the whole layer;
63
+ * 2. a capability's own `HARNESS_REFLEX_<CAP>_MODE`;
64
+ * 3. the plugin's `userConfig` option, exported as `CLAUDE_PLUGIN_OPTION_<KEY>`
65
+ * (only `closing` has one: `closing_mode`, default `observe`);
66
+ * 4. the S3 defaults in {@link DEFAULT_CAPABILITY_MODES}.
67
+ *
68
+ * @param env - environment to read.
69
+ * @returns one mode per capability.
70
+ */
71
+ export function resolveHookModes(env = process.env) {
72
+ const global = explicitMode(env.HARNESS_REFLEX_MODE);
73
+ if (global)
74
+ return { stagnation: global, prune: global, gate: global, closing: global };
75
+ return {
76
+ stagnation: explicitMode(env.HARNESS_REFLEX_STAGNATION_MODE) ?? DEFAULT_CAPABILITY_MODES.stagnation,
77
+ prune: explicitMode(env.HARNESS_REFLEX_PRUNE_MODE) ?? DEFAULT_CAPABILITY_MODES.prune,
78
+ gate: explicitMode(env.HARNESS_REFLEX_GATE_MODE) ?? DEFAULT_CAPABILITY_MODES.gate,
79
+ closing: explicitMode(env.HARNESS_REFLEX_CLOSING_MODE) ??
80
+ explicitMode(env.CLAUDE_PLUGIN_OPTION_CLOSING_MODE) ??
81
+ DEFAULT_CAPABILITY_MODES.closing
82
+ };
83
+ }
84
+ /**
85
+ * Read stdin up to a hard cap.
86
+ *
87
+ * Once the cap is crossed the buffered chunks are dropped and the rest of the
88
+ * stream is drained without retention: the process must not OOM over a payload
89
+ * it will refuse anyway, and it must not leave the writer with EPIPE.
90
+ * @param stream - stdin.
91
+ * @param limit - maximum retained bytes.
92
+ * @returns the retained text, or `overflow: true` when the cap was crossed.
93
+ */
94
+ function canonicalJson(value) {
95
+ if (value === null || value === undefined)
96
+ return 'null';
97
+ if (typeof value === 'number')
98
+ return Number.isFinite(value) ? String(value) : 'null';
99
+ if (typeof value === 'boolean' || typeof value === 'string')
100
+ return JSON.stringify(value);
101
+ if (Array.isArray(value))
102
+ return `[${value.map(canonicalJson).join(',')}]`;
103
+ if (typeof value === 'object') {
104
+ const record = value;
105
+ return `{${Object.keys(record)
106
+ .sort()
107
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
108
+ .join(',')}}`;
109
+ }
110
+ return 'null';
111
+ }
112
+ /** One string field, when it is a non-empty string. */
113
+ export function stringField(value) {
114
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
115
+ }
116
+ /** The text a tool result shows the model, from any of the host's shapes. */
117
+ export function toolResponseText(response) {
118
+ if (typeof response === 'string')
119
+ return response;
120
+ if (response === null || response === undefined)
121
+ return '';
122
+ if (Array.isArray(response)) {
123
+ const parts = [];
124
+ for (const item of response) {
125
+ if (typeof item === 'string')
126
+ parts.push(item);
127
+ else if (item && typeof item === 'object' && item.type === 'text') {
128
+ parts.push(String(item.text ?? ''));
129
+ }
130
+ }
131
+ return parts.join('\n');
132
+ }
133
+ if (typeof response === 'object') {
134
+ const record = response;
135
+ if (typeof record.stdout === 'string' || typeof record.stderr === 'string') {
136
+ return [record.stdout, record.stderr].filter((part) => typeof part === 'string').join('\n');
137
+ }
138
+ if (Array.isArray(record.content))
139
+ return toolResponseText(record.content);
140
+ for (const key of ['output', 'text', 'message', 'error', 'result']) {
141
+ if (typeof record[key] === 'string')
142
+ return record[key];
143
+ }
144
+ try {
145
+ return JSON.stringify(response);
146
+ }
147
+ catch {
148
+ return '';
149
+ }
150
+ }
151
+ return String(response);
152
+ }
153
+ /** Whether a tool result is already known to be a failure. */
154
+ function toolResponseFailed(response) {
155
+ if (response === null || typeof response !== 'object')
156
+ return false;
157
+ const record = response;
158
+ if (record.isError === true || record.interrupted === true)
159
+ return true;
160
+ if (typeof record.exitCode === 'number' && record.exitCode !== 0)
161
+ return true;
162
+ return false;
163
+ }
164
+ /** The dedupe key of design §2.5, extended for the events without a call id. */
165
+ export function dedupeKeyFor(event, payload) {
166
+ const session = stringField(payload.session_id) ?? '';
167
+ const toolUseId = stringField(payload.tool_use_id) ?? '';
168
+ const toolName = stringField(payload.tool_name) ?? '';
169
+ let inputDigest = '';
170
+ switch (event) {
171
+ case 'pretooluse':
172
+ case 'posttooluse':
173
+ case 'postfailure':
174
+ inputDigest = digestOf(canonicalJson(payload.tool_input ?? null));
175
+ break;
176
+ case 'stop':
177
+ case 'substop':
178
+ // `stop_hook_active` is part of the identity: the host's guarded retry
179
+ // must reach the allow path instead of replaying the previous block.
180
+ inputDigest = digestOf([
181
+ stringField(payload.last_assistant_message) ?? '',
182
+ payload.stop_hook_active === true ? 'active' : 'inactive',
183
+ stringField(payload.agent_id) ?? ''
184
+ ].join('\u0000'));
185
+ break;
186
+ case 'sessionstart':
187
+ inputDigest = digestOf(stringField(payload.source) ?? '');
188
+ break;
189
+ case 'sessionend':
190
+ inputDigest = digestOf(stringField(payload.reason) ?? '');
191
+ break;
192
+ }
193
+ return digestOf([session, event, toolUseId, toolName, inputDigest].join('\u0000')) + digestOf(`${event}:${session}`);
194
+ }
195
+ export class HookDecision {
196
+ #store;
197
+ #backend;
198
+ #config;
199
+ #modes;
200
+ #sessionId;
201
+ #clock;
202
+ #stderr;
203
+ #aborted = false;
204
+ #currentEvent = 'pretooluse';
205
+ constructor(args) {
206
+ this.#store = args.store;
207
+ this.#backend = args.backend;
208
+ this.#config = args.config;
209
+ this.#modes = args.modes;
210
+ this.#sessionId = args.sessionId;
211
+ this.#clock = args.clock;
212
+ this.#stderr = args.stderr;
213
+ }
214
+ /** Mark the turn as timed out: later completion must not write anything. */
215
+ abort() {
216
+ this.#aborted = true;
217
+ }
218
+ /** The current turn number, from the discardable cache. */
219
+ turnNo() {
220
+ try {
221
+ return this.#store.readState(this.#sessionId).turnNo;
222
+ }
223
+ catch {
224
+ return 0;
225
+ }
226
+ }
227
+ /** The mode's resolved policy, shared by every capability. */
228
+ #policy() {
229
+ const modes = this.#modes;
230
+ const mode = modes.stagnation !== 'off' || modes.prune !== 'off' || modes.gate !== 'off' || modes.closing !== 'off'
231
+ ? 'active'
232
+ : 'off';
233
+ return {
234
+ enabled: mode !== 'off',
235
+ mode,
236
+ capabilities: { ...modes },
237
+ maxInterventionsPerTurn: this.#config.maxInterventionsPerTurn,
238
+ maxJudgmentsPerTurn: this.#config.maxJudgmentsPerTurn,
239
+ maxJudgmentsPerSession: this.#config.maxJudgmentsPerSession,
240
+ repeatThreshold: this.#config.repeatThreshold,
241
+ minConfidence: this.#config.minConfidence
242
+ };
243
+ }
244
+ /**
245
+ * Reserve a budget slot (and optionally a judgment) under the lock.
246
+ *
247
+ * The checks and the increments happen in one locked read-modify-write, so two
248
+ * processes cannot both believe the last slot is free. A lock that cannot be
249
+ * taken skips this turn's decision, never blocks the tool call.
250
+ */
251
+ #reserve(needs) {
252
+ const result = this.#store.updateState(this.#sessionId, (state) => {
253
+ const policy = this.#policy();
254
+ const budget = {
255
+ interventions: state.budgets.interventions,
256
+ judgmentsCount: state.budgets.judgmentsTurn,
257
+ judgmentsSession: state.budgets.judgmentsSession
258
+ };
259
+ if (needs.action && budget.interventions >= policy.maxInterventionsPerTurn) {
260
+ return { skip: 'intervention-cap' };
261
+ }
262
+ if (needs.judgment) {
263
+ if (budget.judgmentsCount >= policy.maxJudgmentsPerTurn)
264
+ return { skip: 'judgment-turn-cap' };
265
+ if (budget.judgmentsSession >= policy.maxJudgmentsPerSession)
266
+ return { skip: 'judgment-session-cap' };
267
+ budget.judgmentsCount += 1;
268
+ budget.judgmentsSession += 1;
269
+ }
270
+ if (needs.action)
271
+ budget.interventions += 1;
272
+ state.budgets = {
273
+ interventions: budget.interventions,
274
+ judgmentsTurn: budget.judgmentsCount,
275
+ judgmentsSession: budget.judgmentsSession
276
+ };
277
+ return { skip: undefined };
278
+ });
279
+ if (!result.acquired)
280
+ return { ok: false, skipReason: 'skippedLockContention' };
281
+ if (result.value?.skip)
282
+ return { ok: false, skipReason: result.value.skip };
283
+ return { ok: true };
284
+ }
285
+ /** Reserve the closing action and its per-turn repeat ceiling together. */
286
+ #reserveClosing() {
287
+ const result = this.#store.updateState(this.#sessionId, (state) => {
288
+ const policy = this.#policy();
289
+ if (state.budgets.interventions >= policy.maxInterventionsPerTurn)
290
+ return { skip: 'intervention-cap' };
291
+ const used = state.continues.closing ?? 0;
292
+ if (used >= this.#config.maxClosingBlocksPerTurn)
293
+ return { skip: 'closing-turn-cap' };
294
+ state.budgets = { ...state.budgets, interventions: state.budgets.interventions + 1 };
295
+ state.continues = { ...state.continues, closing: used + 1 };
296
+ return { skip: undefined };
297
+ });
298
+ if (!result.acquired)
299
+ return { ok: false, skipReason: 'skippedLockContention' };
300
+ if (result.value?.skip)
301
+ return { ok: false, skipReason: result.value.skip };
302
+ return { ok: true };
303
+ }
304
+ /** Append an error record; never throws and never becomes a decision. */
305
+ auditError(event, reason, message, key) {
306
+ try {
307
+ this.#store.appendLedger(this.#sessionId, {
308
+ id: `hr_${this.#clock.now()}_${Math.random().toString(36).slice(2, 8)}`,
309
+ timestamp: this.#clock.iso(),
310
+ harness: this.#store.harness,
311
+ event,
312
+ dedupeKey: key,
313
+ turnNo: this.turnNo(),
314
+ type: 'error',
315
+ backend: this.#backend.name,
316
+ latencyMs: 0,
317
+ skipReason: reason,
318
+ details: { message: clip(message, 300) }
319
+ });
320
+ }
321
+ catch (error) {
322
+ this.#stderr(`harness-reflex hook: audit write failed: ${error.message}`);
323
+ }
324
+ }
325
+ /**
326
+ * Commit one decision and return the exact stdout object.
327
+ *
328
+ * The order is deliberate: observation, audit line, then the decision cache.
329
+ * A retry that finds the cache always has the ledger line; one that finds only
330
+ * the observation decides once more without appending it twice; one that finds
331
+ * only the ledger line is an explicit no-op. No window can produce a second
332
+ * intervention.
333
+ */
334
+ #finish(key, output, ledger, event, eventAlreadyRecorded) {
335
+ if (this.#aborted) {
336
+ // The caller timed out; the handler may still be running. The claim is
337
+ // left to expire rather than opening a race with this still-live path.
338
+ return emptyHookOutput();
339
+ }
340
+ // Observation, then the authoritative ledger line, then the idempotency
341
+ // commit, then stdout. A crash in any window leaves the retry with one of:
342
+ // nothing (decide), an existing observation (decide, do not append it
343
+ // twice), an existing ledger line (explicit no-op), or an existing decision
344
+ // cache (replay the exact same output) — never a second intervention.
345
+ try {
346
+ if (event && !eventAlreadyRecorded) {
347
+ try {
348
+ this.#store.appendEvent(this.#sessionId, {
349
+ ...event,
350
+ v: 1,
351
+ at: this.#clock.now(),
352
+ atIso: this.#clock.iso(),
353
+ dedupeKey: key
354
+ });
355
+ }
356
+ catch (error) {
357
+ this.#stderr(`harness-reflex hook: event append failed: ${error.message}`);
358
+ }
359
+ }
360
+ try {
361
+ this.#store.appendLedger(this.#sessionId, {
362
+ ...ledger,
363
+ id: `hr_${this.#clock.now()}_${Math.random().toString(36).slice(2, 8)}`,
364
+ timestamp: this.#clock.iso(),
365
+ harness: this.#store.harness,
366
+ event: this.#currentEvent,
367
+ dedupeKey: key,
368
+ turnNo: this.turnNo()
369
+ });
370
+ }
371
+ catch (error) {
372
+ this.#stderr(`harness-reflex hook: ledger append failed: ${error.message}`);
373
+ }
374
+ // The cache is the idempotency marker even when the audit line failed: a
375
+ // duplicate must never repeat an intervention. A ledger gap is visible in
376
+ // stderr and left for the next delivery to fill only if it can decide again.
377
+ if (Object.keys(output).length > 0) {
378
+ this.#store.writeDecision(this.#sessionId, key, output);
379
+ }
380
+ return output;
381
+ }
382
+ finally {
383
+ this.#store.releaseDecisionClaim(this.#sessionId, key);
384
+ }
385
+ }
386
+ /** Look up a previous delivery of this exact event. */
387
+ #lookup(key) {
388
+ let cached;
389
+ try {
390
+ cached = this.#store.readDecision(this.#sessionId, key);
391
+ }
392
+ catch {
393
+ cached = undefined;
394
+ }
395
+ let ledgerSeen = false;
396
+ let eventSeen = false;
397
+ try {
398
+ ledgerSeen = this.#store.ledgerHasKey(this.#sessionId, key);
399
+ eventSeen = this.#store.eventsHaveKey(this.#sessionId, key);
400
+ }
401
+ catch {
402
+ // A read failure means no dedupe evidence; deciding again is safe.
403
+ }
404
+ return { cached, ledgerSeen, eventSeen };
405
+ }
406
+ /** Dispatch one event. Callers have already ensured the session exists. */
407
+ async handle(event, payload, budget) {
408
+ this.#currentEvent = event;
409
+ const key = dedupeKeyFor(event, payload);
410
+ const lookup = this.#lookup(key);
411
+ if (lookup.cached)
412
+ return lookup.cached;
413
+ if (lookup.ledgerSeen)
414
+ return emptyHookOutput();
415
+ const ctx = { key, payload, budget, eventSeen: lookup.eventSeen };
416
+ switch (event) {
417
+ case 'pretooluse':
418
+ return this.#preToolUse(ctx);
419
+ case 'posttooluse':
420
+ return this.#postToolUse(ctx);
421
+ case 'postfailure':
422
+ return this.#postToolUseFailure(ctx);
423
+ case 'stop':
424
+ case 'substop':
425
+ return this.#stop(ctx, event);
426
+ case 'sessionstart':
427
+ return this.#sessionStart();
428
+ case 'sessionend':
429
+ return this.#sessionEnd();
430
+ }
431
+ }
432
+ /** PreToolUse: deny a provably repeated call, otherwise allow silently. */
433
+ async #preToolUse(ctx) {
434
+ if (this.#modes.stagnation === 'off') {
435
+ return this.#finish(ctx.key, emptyHookOutput(), {
436
+ type: 'stagnation',
437
+ backend: this.#backend.name,
438
+ latencyMs: 0,
439
+ applied: false,
440
+ skipReason: 'capability-off'
441
+ }, undefined, ctx.eventSeen);
442
+ }
443
+ const toolName = stringField(ctx.payload.tool_name) ?? 'unknown';
444
+ const inputDigest = digestOf(canonicalJson(ctx.payload.tool_input ?? null));
445
+ const signature = `${toolName}:${inputDigest}`;
446
+ const prior = this.#store
447
+ .readEvents(this.#sessionId, this.#config.windowSize + 4)
448
+ .filter((event) => event.kind === 'pre' || event.kind === 'post' || event.kind === 'failure');
449
+ const steps = prior.map((event) => ({
450
+ signature: event.signature ?? `${event.tool ?? 'unknown'}:${''}`,
451
+ tool: event.tool ?? 'unknown',
452
+ input: '',
453
+ output: event.output ?? '',
454
+ error: event.failed ? (event.output ?? 'failed') : '',
455
+ failed: event.failed === true,
456
+ turn: event.turnNo,
457
+ at: event.at
458
+ }));
459
+ const current = {
460
+ signature,
461
+ tool: toolName,
462
+ input: '',
463
+ output: '',
464
+ error: '',
465
+ failed: false,
466
+ turn: this.turnNo(),
467
+ at: this.#clock.now()
468
+ };
469
+ const suspicion = suspicionOf([...steps, current], {
470
+ repeatThreshold: this.#config.repeatThreshold,
471
+ failureThreshold: this.#config.failureThreshold,
472
+ window: this.#config.windowSize,
473
+ signature
474
+ });
475
+ const event = {
476
+ kind: 'pre',
477
+ turnNo: this.turnNo(),
478
+ tool: toolName,
479
+ toolUseId: stringField(ctx.payload.tool_use_id),
480
+ signature
481
+ };
482
+ if (!suspicion.suspicious) {
483
+ return this.#finish(ctx.key, emptyHookOutput(), {
484
+ type: 'stagnation',
485
+ backend: this.#backend.name,
486
+ latencyMs: 0,
487
+ applied: false,
488
+ isStuck: false,
489
+ skipReason: 'no-local-pattern'
490
+ }, event, ctx.eventSeen);
491
+ }
492
+ const reservation = this.#reserve({ action: true, judgment: true });
493
+ if (!reservation.ok) {
494
+ return this.#finish(ctx.key, emptyHookOutput(), {
495
+ type: 'stagnation',
496
+ backend: this.#backend.name,
497
+ latencyMs: 0,
498
+ applied: false,
499
+ skipReason: reservation.skipReason
500
+ }, event, ctx.eventSeen);
501
+ }
502
+ const started = this.#clock.now();
503
+ const history = [
504
+ ...steps,
505
+ current
506
+ ].map((step) => ({
507
+ tool: step.tool,
508
+ input: step.signature,
509
+ ...(step.output ? { output: step.output } : {}),
510
+ ...(step.error ? { error: step.error } : {}),
511
+ timestamp: step.at
512
+ }));
513
+ let verdict;
514
+ try {
515
+ verdict = await this.#backend.checkStagnation({ history, windowSize: this.#config.windowSize });
516
+ }
517
+ catch (error) {
518
+ return this.#finish(ctx.key, emptyHookOutput(), {
519
+ type: 'error',
520
+ backend: this.#backend.name,
521
+ latencyMs: Math.max(0, this.#clock.now() - started),
522
+ applied: false,
523
+ skipReason: 'backend-error',
524
+ details: { message: clip(error.message, 300) }
525
+ }, event, ctx.eventSeen);
526
+ }
527
+ const latencyMs = Math.max(0, this.#clock.now() - started);
528
+ const useful = verdict.isStuck === true &&
529
+ verdict.confidence >= this.#config.minConfidence &&
530
+ (verdict.patternType ?? 'none') !== 'none';
531
+ if (!useful) {
532
+ return this.#finish(ctx.key, emptyHookOutput(), {
533
+ type: 'stagnation',
534
+ backend: this.#backend.name,
535
+ latencyMs,
536
+ applied: false,
537
+ isStuck: false,
538
+ judged: true,
539
+ skipReason: 'verdict-not-useful',
540
+ details: { patternType: verdict.patternType ?? 'none', confidence: verdict.confidence }
541
+ }, event, ctx.eventSeen);
542
+ }
543
+ const reason = clip(`harness-reflex: this call repeats a pattern this session already ran (${verdict.patternType ?? 'repetition'}). ` +
544
+ `${verdict.diagnosis ?? 'Repeating it will not produce a different result.'} ` +
545
+ `${verdict.recommendedIntervention ?? 'Change the approach or inspect the previous failure.'}`, 600);
546
+ const mode = this.#modes.stagnation;
547
+ const output = mode === 'active' ? preToolUseDeny(reason) : emptyHookOutput();
548
+ return this.#finish(ctx.key, output, {
549
+ type: 'stagnation',
550
+ backend: this.#backend.name,
551
+ latencyMs,
552
+ applied: mode === 'active',
553
+ shadow: mode !== 'active',
554
+ isStuck: true,
555
+ judged: true,
556
+ details: { patternType: verdict.patternType ?? 'repetition', confidence: verdict.confidence }
557
+ }, event, ctx.eventSeen);
558
+ }
559
+ /** PostToolUse: replace an oversized result with its verified reduction. */
560
+ async #postToolUse(ctx) {
561
+ if (this.#modes.prune === 'off') {
562
+ return this.#finish(ctx.key, emptyHookOutput(), {
563
+ type: 'prune',
564
+ backend: this.#backend.name,
565
+ latencyMs: 0,
566
+ applied: false,
567
+ tokensSaved: 0,
568
+ skipReason: 'capability-off'
569
+ }, undefined, ctx.eventSeen);
570
+ }
571
+ const toolName = stringField(ctx.payload.tool_name) ?? 'unknown';
572
+ const text = toolResponseText(ctx.payload.tool_response);
573
+ const failed = toolResponseFailed(ctx.payload.tool_response);
574
+ const inputDigest = digestOf(canonicalJson(ctx.payload.tool_input ?? null));
575
+ const signature = `${toolName}:${inputDigest}`;
576
+ const event = {
577
+ kind: 'post',
578
+ turnNo: this.turnNo(),
579
+ tool: toolName,
580
+ toolUseId: stringField(ctx.payload.tool_use_id),
581
+ signature,
582
+ failed,
583
+ output: clip(text, 400)
584
+ };
585
+ const skip = (reason) => this.#finish(ctx.key, emptyHookOutput(), {
586
+ type: 'prune',
587
+ backend: this.#backend.name,
588
+ latencyMs: 0,
589
+ applied: false,
590
+ tokensSaved: 0,
591
+ skipReason: reason
592
+ }, event, ctx.eventSeen);
593
+ if (text.length < this.#config.pruneThreshold)
594
+ return skip('below-threshold');
595
+ if ((text.match(/\n/g)?.length ?? 0) < this.#config.pruneMinLines)
596
+ return skip('unsupported-payload');
597
+ if (text.length > this.#config.maxRetainedChars)
598
+ return skip('retention-too-large');
599
+ const reservation = this.#reserve({ action: true, judgment: true });
600
+ if (!reservation.ok)
601
+ return skip(reservation.skipReason ?? 'intervention-cap');
602
+ const started = this.#clock.now();
603
+ let response;
604
+ try {
605
+ response = await this.#backend.prune({ rawOutput: text, intent: 'extract errors and key results' });
606
+ }
607
+ catch (error) {
608
+ return this.#finish(ctx.key, emptyHookOutput(), {
609
+ type: 'error',
610
+ backend: this.#backend.name,
611
+ latencyMs: Math.max(0, this.#clock.now() - started),
612
+ applied: false,
613
+ skipReason: 'backend-error',
614
+ details: { message: clip(error.message, 300) }
615
+ }, event, ctx.eventSeen);
616
+ }
617
+ const latencyMs = Math.max(0, this.#clock.now() - started);
618
+ const digest = digestOf(text);
619
+ const locator = `originals/${digest}.txt`;
620
+ const composed = applyPruneFloor(text, response.processedOutput, {
621
+ floorRatio: this.#config.pruneFloorRatio,
622
+ headChars: this.#config.pruneHeadChars,
623
+ tailChars: this.#config.pruneTailChars,
624
+ locator
625
+ });
626
+ const pruneMode = this.#modes.prune;
627
+ const originalTokens = estimateTokens(text);
628
+ let installed = composed.text;
629
+ let retained = false;
630
+ let evicted = [];
631
+ if (pruneMode === 'active') {
632
+ const retention = this.#store.retainOriginal(this.#sessionId, digest, text);
633
+ retained = retention.retained;
634
+ evicted = retention.evicted;
635
+ if (!retained) {
636
+ // Downgraded: shrink without a locator and without claiming a saving.
637
+ installed = response.processedOutput.length > 0 ? response.processedOutput : text;
638
+ }
639
+ }
640
+ const prunedTokens = estimateTokens(installed);
641
+ const smaller = installed.length < text.length;
642
+ if (!smaller) {
643
+ return this.#finish(ctx.key, emptyHookOutput(), {
644
+ type: 'prune',
645
+ backend: this.#backend.name,
646
+ latencyMs,
647
+ applied: false,
648
+ judged: true,
649
+ tokensSaved: 0,
650
+ originalTokens,
651
+ prunedTokens,
652
+ skipReason: 'no-reduction',
653
+ retention: 'none'
654
+ }, event, ctx.eventSeen);
655
+ }
656
+ const shadow = pruneMode !== 'active';
657
+ const saved = pruneMode === 'active' && retained ? Math.max(0, originalTokens - prunedTokens) : 0;
658
+ const output = pruneMode === 'active' ? postToolUseReplace(installed) : emptyHookOutput();
659
+ return this.#finish(ctx.key, output, {
660
+ type: 'prune',
661
+ backend: this.#backend.name,
662
+ latencyMs,
663
+ applied: pruneMode === 'active',
664
+ shadow,
665
+ judged: true,
666
+ tokensSaved: saved,
667
+ originalTokens,
668
+ prunedTokens,
669
+ retention: retained ? 'retained' : evicted.length > 0 || !retained ? 'evicted' : 'none',
670
+ details: {
671
+ digest,
672
+ floored: composed.floored,
673
+ potentialSavedTokens: Math.max(0, originalTokens - prunedTokens),
674
+ ...(evicted.length > 0 ? { evictedOriginals: evicted.slice(0, 8) } : {})
675
+ }
676
+ }, event, ctx.eventSeen);
677
+ }
678
+ /** PostToolUseFailure: attach one correction after a failing run. */
679
+ async #postToolUseFailure(ctx) {
680
+ if (this.#modes.gate === 'off') {
681
+ return this.#finish(ctx.key, emptyHookOutput(), {
682
+ type: 'gate',
683
+ backend: this.#backend.name,
684
+ latencyMs: 0,
685
+ applied: false,
686
+ skipReason: 'capability-off'
687
+ }, undefined, ctx.eventSeen);
688
+ }
689
+ const toolName = stringField(ctx.payload.tool_name) ?? 'unknown';
690
+ const errorText = toolResponseText(ctx.payload.error) || 'tool call failed';
691
+ const inputDigest = digestOf(canonicalJson(ctx.payload.tool_input ?? null));
692
+ const signature = `${toolName}:${inputDigest}`;
693
+ const prior = this.#store
694
+ .readEvents(this.#sessionId, 30)
695
+ .filter((event) => event.kind === 'pre' || event.kind === 'post' || event.kind === 'failure');
696
+ const steps = prior.map((event) => ({
697
+ signature: event.signature ?? `${event.tool ?? 'unknown'}:${''}`,
698
+ tool: event.tool ?? 'unknown',
699
+ input: '',
700
+ output: event.output ?? '',
701
+ error: event.failed ? (event.output ?? 'failed') : '',
702
+ failed: event.failed === true,
703
+ turn: event.turnNo,
704
+ at: event.at
705
+ }));
706
+ steps.push({
707
+ signature,
708
+ tool: toolName,
709
+ input: '',
710
+ output: '',
711
+ error: errorText,
712
+ failed: true,
713
+ turn: this.turnNo(),
714
+ at: this.#clock.now()
715
+ });
716
+ const failures = countTrailingFailures(steps);
717
+ const event = {
718
+ kind: 'failure',
719
+ turnNo: this.turnNo(),
720
+ tool: toolName,
721
+ toolUseId: stringField(ctx.payload.tool_use_id),
722
+ signature,
723
+ failed: true,
724
+ output: clip(errorText, 400)
725
+ };
726
+ if (failures < this.#config.failureThreshold) {
727
+ return this.#finish(ctx.key, emptyHookOutput(), {
728
+ type: 'gate',
729
+ backend: this.#backend.name,
730
+ latencyMs: 0,
731
+ applied: false,
732
+ skipReason: 'below-failure-threshold'
733
+ }, event, ctx.eventSeen);
734
+ }
735
+ const reservation = this.#reserve({ action: true, judgment: false });
736
+ if (!reservation.ok) {
737
+ return this.#finish(ctx.key, emptyHookOutput(), {
738
+ type: 'gate',
739
+ backend: this.#backend.name,
740
+ latencyMs: 0,
741
+ applied: false,
742
+ skipReason: reservation.skipReason
743
+ }, event, ctx.eventSeen);
744
+ }
745
+ const context = clip(`harness-reflex: ${failures} consecutive tool calls failed (latest: ${toolName}). ` +
746
+ 'Stop retrying the same call. Read the error, change the input or the approach, and verify a smaller step before retrying.', 600);
747
+ const gateMode = this.#modes.gate;
748
+ const output = gateMode === 'active' ? postToolUseFailureContext(context) : emptyHookOutput();
749
+ return this.#finish(ctx.key, output, {
750
+ type: 'gate',
751
+ backend: this.#backend.name,
752
+ latencyMs: 0,
753
+ applied: gateMode === 'active',
754
+ shadow: gateMode !== 'active',
755
+ details: { failures, tool: toolName }
756
+ }, event, ctx.eventSeen);
757
+ }
758
+ /** Stop/SubagentStop: the one place a normal decision may block. */
759
+ async #stop(ctx, hookEvent) {
760
+ const increment = this.#store.updateState(this.#sessionId, (state) => {
761
+ state.turnNo += 1;
762
+ state.budgets = { interventions: 0, judgmentsTurn: 0, judgmentsSession: state.budgets.judgmentsSession };
763
+ state.continues = {};
764
+ return { turnNo: state.turnNo };
765
+ });
766
+ const turnNo = increment.acquired ? increment.value?.turnNo ?? this.turnNo() : this.turnNo();
767
+ const stopHookActive = ctx.payload.stop_hook_active === true;
768
+ const message = stringField(ctx.payload.last_assistant_message) ?? '';
769
+ const event = {
770
+ kind: 'stop',
771
+ turnNo,
772
+ source: hookEvent,
773
+ toolUseId: stringField(ctx.payload.agent_id)
774
+ };
775
+ if (!increment.acquired) {
776
+ return this.#finish(ctx.key, emptyHookOutput(), {
777
+ type: 'closing',
778
+ backend: this.#backend.name,
779
+ latencyMs: 0,
780
+ applied: false,
781
+ skipReason: 'skippedLockContention'
782
+ }, event, ctx.eventSeen);
783
+ }
784
+ // The turn counter and per-turn budgets were reset above; only the judgment
785
+ // and the action are skipped when closing is off.
786
+ if (this.#modes.closing === 'off') {
787
+ return this.#finish(ctx.key, emptyHookOutput(), {
788
+ type: 'closing',
789
+ backend: this.#backend.name,
790
+ latencyMs: 0,
791
+ applied: false,
792
+ skipReason: 'capability-off'
793
+ }, event, ctx.eventSeen);
794
+ }
795
+ if (stopHookActive) {
796
+ return this.#finish(ctx.key, emptyHookOutput(), {
797
+ type: 'closing',
798
+ backend: this.#backend.name,
799
+ latencyMs: 0,
800
+ applied: false,
801
+ passed: true,
802
+ skipReason: 'stop-hook-active'
803
+ }, event, ctx.eventSeen);
804
+ }
805
+ const candidates = claimCandidates(message);
806
+ if (candidates.length === 0) {
807
+ return this.#finish(ctx.key, emptyHookOutput(), {
808
+ type: 'closing',
809
+ backend: this.#backend.name,
810
+ latencyMs: 0,
811
+ applied: false,
812
+ skipReason: 'no-claim-candidates'
813
+ }, event, ctx.eventSeen);
814
+ }
815
+ if (typeof this.#backend.classifyClaims !== 'function') {
816
+ return this.#finish(ctx.key, emptyHookOutput(), {
817
+ type: 'closing',
818
+ backend: this.#backend.name,
819
+ latencyMs: 0,
820
+ applied: false,
821
+ skipReason: 'classifier-unavailable'
822
+ }, event, ctx.eventSeen);
823
+ }
824
+ const reservation = this.#reserve({ action: false, judgment: true });
825
+ if (!reservation.ok) {
826
+ return this.#finish(ctx.key, emptyHookOutput(), {
827
+ type: 'closing',
828
+ backend: this.#backend.name,
829
+ latencyMs: 0,
830
+ applied: false,
831
+ skipReason: reservation.skipReason
832
+ }, event, ctx.eventSeen);
833
+ }
834
+ const started = this.#clock.now();
835
+ let classification;
836
+ try {
837
+ classification = await this.#backend.classifyClaims({
838
+ statements: candidates,
839
+ intent: this.#config.closingIntent
840
+ });
841
+ }
842
+ catch (error) {
843
+ return this.#finish(ctx.key, emptyHookOutput(), {
844
+ type: 'error',
845
+ backend: this.#backend.name,
846
+ latencyMs: Math.max(0, this.#clock.now() - started),
847
+ applied: false,
848
+ skipReason: 'backend-error',
849
+ details: { message: clip(error.message, 300) }
850
+ }, event, ctx.eventSeen);
851
+ }
852
+ const claims = claimsOf(classification, this.#config.claimMinConfidence);
853
+ if (claims.length === 0) {
854
+ return this.#finish(ctx.key, emptyHookOutput(), {
855
+ type: 'closing',
856
+ backend: this.#backend.name,
857
+ latencyMs: Math.max(0, this.#clock.now() - started),
858
+ applied: false,
859
+ passed: true,
860
+ skipReason: 'no-completion-claim'
861
+ }, event, ctx.eventSeen);
862
+ }
863
+ const evidence = this.#evidence();
864
+ let verdict;
865
+ try {
866
+ verdict = await this.#backend.gate({ assertions: claims, evidence: evidence.text, strictness: 'normal' });
867
+ }
868
+ catch (error) {
869
+ return this.#finish(ctx.key, emptyHookOutput(), {
870
+ type: 'error',
871
+ backend: this.#backend.name,
872
+ latencyMs: Math.max(0, this.#clock.now() - started),
873
+ applied: false,
874
+ skipReason: 'backend-error',
875
+ details: { message: clip(error.message, 300) }
876
+ }, event, ctx.eventSeen);
877
+ }
878
+ const latencyMs = Math.max(0, this.#clock.now() - started);
879
+ const contradicted = contradictedOf(verdict);
880
+ if (contradicted.length === 0) {
881
+ return this.#finish(ctx.key, emptyHookOutput(), {
882
+ type: 'closing',
883
+ backend: this.#backend.name,
884
+ latencyMs,
885
+ applied: false,
886
+ passed: verdict.passed,
887
+ judged: true,
888
+ skipReason: closingSkipReason(verdict, contradicted)
889
+ }, event, ctx.eventSeen);
890
+ }
891
+ const closingReservation = this.#reserveClosing();
892
+ if (!closingReservation.ok) {
893
+ return this.#finish(ctx.key, emptyHookOutput(), {
894
+ type: 'closing',
895
+ backend: this.#backend.name,
896
+ latencyMs,
897
+ applied: false,
898
+ passed: false,
899
+ judged: true,
900
+ skipReason: closingReservation.skipReason
901
+ }, event, ctx.eventSeen);
902
+ }
903
+ const reason = clip(`harness-reflex: this turn claims completion but its own tool evidence contradicts it: ${contradicted.join('; ')}. ` +
904
+ 'Address the contradiction or restate the claim with the evidence that supports it.', 900);
905
+ const closingMode = this.#modes.closing;
906
+ const output = closingMode === 'active' ? stopBlock(reason) : emptyHookOutput();
907
+ return this.#finish(ctx.key, output, {
908
+ type: 'closing',
909
+ backend: this.#backend.name,
910
+ latencyMs,
911
+ applied: closingMode === 'active',
912
+ shadow: closingMode !== 'active',
913
+ passed: false,
914
+ judged: true,
915
+ details: { contradicted: contradicted.slice(0, 5), evidenceChars: evidence.retainedChars }
916
+ }, event, ctx.eventSeen);
917
+ }
918
+ /** SessionStart: create the session, apply retention, announce the mode. */
919
+ #sessionStart() {
920
+ const modes = this.#modes;
921
+ this.#store.ensureSession(this.#sessionId, modeLabel(modes));
922
+ this.#store.gcSessions(undefined, this.#sessionId);
923
+ this.#store.gcOriginals(this.#sessionId);
924
+ const active = ['stagnation', 'prune', 'gate'].filter((capability) => modes[capability] === 'active');
925
+ if (active.length === 0 && modes.closing !== 'active')
926
+ return emptyHookOutput();
927
+ const closing = modes.closing === 'active' ? 'closing=active' : 'closing=observe';
928
+ return sessionStartContext(`harness-reflex: mode=active (${active.length > 0 ? active.join('/') : 'none'}, ${closing}). ` +
929
+ 'Oversized tool results may be reduced; repeated calls, repeated failures, and contradicted completion claims are flagged.');
930
+ }
931
+ /** SessionEnd: the same cleanup, with no output at all. */
932
+ #sessionEnd() {
933
+ try {
934
+ this.#store.gcOriginals(this.#sessionId);
935
+ this.#store.gcSessions(undefined, this.#sessionId);
936
+ }
937
+ catch {
938
+ // F2: session teardown is silent even when it fails.
939
+ }
940
+ return emptyHookOutput();
941
+ }
942
+ /** Assemble this turn's evidence from the appended observations. */
943
+ #evidence() {
944
+ const events = this.#store
945
+ .readEvents(this.#sessionId, 40)
946
+ .filter((event) => (event.kind === 'post' || event.kind === 'failure') && (event.output ?? '').length > 0);
947
+ const entries = [];
948
+ for (const event of events) {
949
+ entries.push(...evidenceOf(event.tool ?? 'tool', { isError: event.failed === true }, event.output ?? ''));
950
+ }
951
+ return assembleEvidence(entries, this.#config.closingEvidenceChars);
952
+ }
953
+ }
954
+ /** Run one hook invocation. Never throws; failure is always `{}` + exit 0. */
955
+ //# sourceMappingURL=decision.js.map