dsh-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 (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
@@ -1,78 +1,21 @@
1
- /**
2
- * Automatic interventions on the Host's native tool and agent lifecycle hooks.
3
- *
4
- * The plugin's eight MCP tools are pull-based: they act only when the *model*
5
- * decides to call one. This module is the push half — the same System 1
6
- * judgments, spent automatically at the four points where the Host already asks
7
- * its listeners a question:
8
- *
9
- * | Hook | Capability | What it may do |
10
- * | --- | --- | --- |
11
- * | `tools/pre-execute` | `stagnation` | deny a call the run is repeating |
12
- * | `tools/post-execute` | `prune` | replace an oversized result with its reduction |
13
- * | `tools/post-execute` | `gate` | turn a repeated failure into corrective feedback |
14
- * | `agent/pre-step` | `stagnation` | attach the correction to the next step |
15
- * | `agent/turn-stopping` | `closing` | object to a turn closing on contradicted evidence |
16
- *
17
- * ## The three-state discipline
18
- *
19
- * Every capability runs in one of three modes. The distinction is *not* "on/off
20
- * with logging": `observe` runs the same detection, the same judgment, and the
21
- * same plan as `active`, and withholds only the application. That is what makes
22
- * the mode worth having — what observe measures is exactly what active would
23
- * have done, on the same payloads, at the same cost.
24
- *
25
- * | Mode | Detection | Judgment | Application | Model-visible change |
26
- * | --- | --- | --- | --- | --- |
27
- * | `off` | none | none | none | none |
28
- * | `observe` | full | full | none | **none at all** |
29
- * | `active` | full | full | full | the planned text |
30
- *
31
- * `observe` is therefore *not* the reference plugin's shadow mode: that one
32
- * injects a model-visible notice saying it changed nothing. Here an observation
33
- * has no model-visible surface whatsoever — no message, no rewritten content, no
34
- * denial, no steering. The one thing it produces is an audit record in the
35
- * session log, which the model cannot read.
36
- *
37
- * ## Cost discipline
38
- *
39
- * A deterministic, local pre-trigger decides whether a *judgment* may be spent
40
- * at all, and judgments are budgeted per turn and per session: at most
41
- * {@link ResolvedInterventionsConfig.maxJudgmentsPerTurn} per turn and
42
- * {@link ResolvedInterventionsConfig.maxJudgmentsPerSession} per agent, with one
43
- * verdict reused by every hook of the same turn. A turn presenting twenty
44
- * similar results therefore costs one judgment, not twenty. Applied
45
- * interventions carry their own ceiling, so an intervention can never become the
46
- * loop it was meant to break.
47
- *
48
- * ## Fail-open and isolation
49
- *
50
- * Every hook delegates first (`await next()`), and every planning step is
51
- * wrapped: an exception, an aborted signal, or an unusable verdict leaves the
52
- * call, the result, the messages, and the turn exactly as the rest of the
53
- * waterfall left them. Detection state is keyed by agent id, so two agents in one
54
- * process can never see each other's history, verdicts, or budgets. Nothing here
55
- * grants a permission the Host would not have granted, and nothing here overrides
56
- * one either: a call the rest of the waterfall denied, cancelled, or routed to an
57
- * approval flow is returned untouched, so the only decision this module can add
58
- * is a strictly narrower one on top of a plain `allow`.
59
- *
60
- * ## Retained originals
61
- *
62
- * A reduction is installed only after the bytes it replaces have been retained
63
- * in the agent's own Session log, in the plugin-record channel the audit trail
64
- * already uses. The replacement publishes a locator derived from the payload's
65
- * digest, a reader resolves it back to the verbatim original, and a payload that
66
- * cannot be retained — too large, no session, a log that did not commit — is
67
- * never replaced: `saved` is reported only for a replacement that really
68
- * happened and can really be checked.
69
- *
70
- * @module dsh-reflex/interventions
71
- */
72
- import { createHash } from 'node:crypto';
73
1
  import { MessageId, boundContextSummary } from '@deepseek-ai/dsh-llm';
74
2
  import { INTERVENTION_CAPABILITIES } from './config.js';
75
3
  import { appendInterventionRecord, pruneLocator } from './session-audit.js';
4
+ import { evidenceOf, failureOf } from './vendor/harness-reflex/core/evidence.js';
5
+ import { applyCharge, emptyBucket, suspicionOf } from './vendor/harness-reflex/core/judge.js';
6
+ import { modeOf, serves as policyServes } from './vendor/harness-reflex/core/policy.js';
7
+ import { orchestratePrune } from './vendor/harness-reflex/core/orchestrate.js';
8
+ import { CLOSING_LATCH, orchestrateClosing } from './vendor/harness-reflex/core/orchestrate-closing.js';
9
+ import { orchestrateStagnationPre, orchestrateStagnationStep, progressSteps as sharedProgressSteps } from './vendor/harness-reflex/core/orchestrate-stagnation.js';
10
+ import { describeCorrection, orchestrateCorrection } from './vendor/harness-reflex/core/orchestrate-correction.js';
11
+ import { clip, digestOf, estimateTokens, hasTextBlock, textOfContent } from './vendor/harness-reflex/core/text.js';
12
+ // The decision primitives keep their historic import path: a caller that already
13
+ // imports the intervention surface does not need a second one for them.
14
+ export { claimCandidates } from './vendor/harness-reflex/core/closing.js';
15
+ export { assembleEvidence, evidenceOf, FAILURE_MARKER, failureOf } from './vendor/harness-reflex/core/evidence.js';
16
+ export { countTrailingFailures, countTrailingRepeats, detectOscillation, suspicionOf } from './vendor/harness-reflex/core/judge.js';
17
+ export { applyPruneFloor, pruneFloorPlan, pruneMarker } from './vendor/harness-reflex/core/prune-plan.js';
18
+ export { digestOf, estimateTokens, textOfContent } from './vendor/harness-reflex/core/text.js';
76
19
  /**
77
20
  * Producer-owned source kind of every message this plugin appends.
78
21
  *
@@ -81,10 +24,6 @@ import { appendInterventionRecord, pruneLocator } from './session-audit.js';
81
24
  * uses for its audit records.
82
25
  */
83
26
  export const INTERVENTION_SOURCE_KIND = 'plugin:dsh-reflex';
84
- /** Default share of a floored reduction's context budget taken from the head. */
85
- const FLOOR_HEAD_CHARS = 400;
86
- /** Default share of a floored reduction's context budget taken from the tail. */
87
- const FLOOR_TAIL_CHARS = 400;
88
27
  /** Characters of one observed step's input or output retained for judging. */
89
28
  const STEP_CHARS = 600;
90
29
  /** Steps one agent's detection window may retain. */
@@ -99,16 +38,6 @@ const CLAIM_CHARS = 4000;
99
38
  * character budget (not this count) decides what the judgment reads.
100
39
  */
101
40
  const MAX_EVIDENCE = 16;
102
- /** Characters of one evidence line. */
103
- const EVIDENCE_CHARS = 400;
104
- /** Characters of one result's tail summary. */
105
- const EVIDENCE_TAIL_CHARS = 240;
106
- /** Characters of the "other" (non-diagnostic, non-tail) fallback per result. */
107
- const EVIDENCE_OTHER_CHARS = 120;
108
- /** Completion claim candidates submitted to one closing judgment. */
109
- const MAX_CLAIMS = 3;
110
- /** Minimum sentence length worth classifying as a claim candidate. */
111
- const MIN_CLAIM_CHARS = 8;
112
41
  /** Agent states retained before the least recently used is dropped. */
113
42
  const MAX_AGENTS = 64;
114
43
  /** Reductions memoized per activation, bounded by least recent use. */
@@ -139,21 +68,6 @@ const PRUNE_MIN_LINES = 4;
139
68
  * never kept. A hundred kilobyte log line stays readable and bounded.
140
69
  */
141
70
  const MAX_RETAINED_CHARS = 100_000;
142
- /**
143
- * Matches the failure markers that make a result a *candidate* for the closing
144
- * evidence. A hit is a safety floor: the line is kept whatever the budget says.
145
- * A miss is never a "failure-free" conclusion — the tail summary goes to System
146
- * One, which decides what the result means.
147
- */
148
- export const FAILURE_MARKER = /(\berror\b|\berrors\b|\bfailed\b|\bfailure\b|\bfailures\b|\bfail\b|exit code [1-9]|\bnot ok\b|\bFAIL\b|\bexception\b|\btraceback\b)/i;
149
- /**
150
- * Prefilter for a failure *suspicion* — the deterministic trigger that makes a
151
- * closing judgment worth buying. It is broader than {@link FAILURE_MARKER}
152
- * because `{ok:false}`, a timeout, and a Chinese error must reach System One
153
- * too; none of these decides anything by itself.
154
- */
155
- const FAILURE_CUE = new RegExp(`${FAILURE_MARKER.source}|\\bok\\b\\s*[:=]\\s*false|"ok"\\s*:\\s*false|\\btimed?\\s*out\\b|\\btimeout\\b|`
156
- + '失败|错误|异常|超时|无法|未通过|仍有失败|还有失败|报错', 'i');
157
71
  /**
158
72
  * The identity of one tool call, stable across its pre- and post-execute hooks.
159
73
  * @param exec - the execution.
@@ -318,24 +232,7 @@ export function annotateWaitHistory(steps, signature) {
318
232
  * @returns the steps that count as progress.
319
233
  */
320
234
  function progressSteps(steps) {
321
- return steps.some((step) => step.wait === true) ? steps.filter((step) => step.wait !== true) : steps;
322
- }
323
- /** A fresh, zeroed cost bucket. */
324
- function emptyBucket() {
325
- return {
326
- plans: 0,
327
- applied: 0,
328
- judgments: 0,
329
- memoHits: 0,
330
- localLatencyMs: 0,
331
- remoteLatencyMs: 0,
332
- judgeTokens: 0,
333
- originalTokens: 0,
334
- candidateTokens: 0,
335
- potentialSavedTokens: 0,
336
- actualSavedTokens: 0,
337
- injectedTokens: 0
338
- };
235
+ return sharedProgressSteps(steps);
339
236
  }
340
237
  /**
341
238
  * The payload half of a prune decision's audit fields.
@@ -372,703 +269,6 @@ function pruneDiagnosticsOf(response) {
372
269
  ...(response.fallbackReason === undefined ? {} : { fallbackReason: response.fallbackReason })
373
270
  };
374
271
  }
375
- /**
376
- * Tokens one text costs, at the ledger's shared four-characters-per-token rate.
377
- * @param text - any text.
378
- * @returns the estimated token count.
379
- */
380
- export function estimateTokens(text) {
381
- return text.length === 0 ? 0 : Math.ceil(text.length / 4);
382
- }
383
- /**
384
- * Stable short digest of one value, used as a tool-call identity.
385
- * @param value - the text to digest.
386
- * @returns sixteen hexadecimal characters.
387
- */
388
- export function digestOf(value) {
389
- return createHash('sha256').update(value).digest('hex').slice(0, 16);
390
- }
391
- /**
392
- * Concatenate the text blocks of one content list.
393
- * @param content - message or result content.
394
- * @returns the text, in block order.
395
- */
396
- export function textOfContent(content) {
397
- if (!content)
398
- return '';
399
- const parts = [];
400
- for (const block of content) {
401
- if (block && typeof block === 'object' && block.type === 'text') {
402
- parts.push(block.text ?? '');
403
- }
404
- }
405
- return parts.join('\n');
406
- }
407
- /**
408
- * Whether one content list carries at least one text block.
409
- * @param content - message or result content.
410
- * @returns whether there is text to rewrite.
411
- */
412
- export function hasTextBlock(content) {
413
- if (!content)
414
- return false;
415
- for (const block of content) {
416
- if (block && typeof block === 'object' && block.type === 'text')
417
- return true;
418
- }
419
- return false;
420
- }
421
- /**
422
- * Bound one text to a character budget, marking the cut.
423
- * @param text - any text.
424
- * @param max - maximum characters to keep.
425
- * @returns the bounded text.
426
- */
427
- function clip(text, max) {
428
- return text.length <= max ? text : `${text.slice(0, max)}…`;
429
- }
430
- // ── what counts as a failed result ──────────────────────────────────────────
431
- /**
432
- * The exit status one tool result carries in its own canonical value.
433
- *
434
- * A shell result is *reported*, not errored: a command that exits 1 returns a
435
- * successful `ToolExecutionResult` whose `value.exitCode` is the whole truth. The
436
- * distinction matters twice over — a correction that never fires because the
437
- * failure looked like a success, and a closing check that reads a green claim
438
- * over a red build — so the status is taken from the tool's own structured field
439
- * whenever the payload exposes one.
440
- *
441
- * @param value - the result's canonical value, when it has one.
442
- * @returns the exit status, or `undefined` when the value is not a shell result.
443
- */
444
- export function structuredExitStatus(value) {
445
- if (typeof value !== 'object' || value === null)
446
- return undefined;
447
- const candidate = value;
448
- if (typeof candidate.exitCode !== 'number' || !Number.isFinite(candidate.exitCode))
449
- return undefined;
450
- const status = { exitCode: candidate.exitCode };
451
- if (typeof candidate.signal === 'string')
452
- status.signal = candidate.signal;
453
- return status;
454
- }
455
- /**
456
- * Whether the text ends in the Host's own exit marker for a failed command.
457
- *
458
- * The marker is the last line of the model-facing content, so anchoring it to the
459
- * end of the text keeps an *ordinary* result that merely mentions "exit code 1"
460
- * in its body from being misread as a failure. This is the fallback for a result
461
- * that carries no structured value — a Virtual tool, a replay from an older
462
- * record — not a replacement for {@link structuredExitStatus}.
463
- * @param text - the model-facing text.
464
- * @returns whether the last marker line reports a non-zero exit or a signal.
465
- */
466
- export function exitMarkerFailure(text) {
467
- const match = /(?:^|\n)\[exit code: ([0-9]+)\]\s*$/.exec(text);
468
- if (match)
469
- return Number(match[1]) !== 0;
470
- return /(?:^|\n)\[killed by signal: [^\]\n]+\]\s*$/.test(text);
471
- }
472
- /**
473
- * Whether one result is a failure the interventions may act on.
474
- *
475
- * Three sources, in order of authority: the Host's own `isError` flag, the exit
476
- * status inside the tool's structured value, and the exit marker the Host appends
477
- * to the text. A text heuristic over words like "failed" is deliberately absent:
478
- * a test log that prints the word is not a failing command, and treating it as
479
- * one would both spend a judgment on it and block a legitimate retry.
480
- *
481
- * @param result - the execution-local result.
482
- * @param text - the effective model-facing text of that result.
483
- * @returns whether the result proves a failure.
484
- */
485
- export function failureOf(result, text) {
486
- if (!result)
487
- return false;
488
- if (result.isError === true)
489
- return true;
490
- const status = structuredExitStatus(result.value);
491
- if (status)
492
- return status.exitCode !== 0 || status.signal !== undefined;
493
- return exitMarkerFailure(text);
494
- }
495
- /** The primitive structured facts one result exposes, for the tail summary. */
496
- function structuredFacts(result) {
497
- const facts = {};
498
- if (!result)
499
- return facts;
500
- if (result.isError !== undefined)
501
- facts.isError = result.isError === true;
502
- const status = structuredExitStatus(result.value);
503
- if (status) {
504
- facts.exitCode = status.exitCode;
505
- if (status.signal !== undefined)
506
- facts.signal = status.signal;
507
- }
508
- let value = result.value;
509
- if (typeof value === 'string' && /^\s*[{[]/.test(value)) {
510
- try {
511
- value = JSON.parse(value);
512
- }
513
- catch {
514
- value = undefined;
515
- }
516
- }
517
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
518
- const record = value;
519
- for (const key of ['ok', 'status', 'timedOut', 'timeout', 'isError', 'exitCode', 'signal']) {
520
- const field = record[key];
521
- if (typeof field === 'string' || typeof field === 'number' || typeof field === 'boolean')
522
- facts[key] = field;
523
- }
524
- }
525
- return facts;
526
- }
527
- /** Whether structured facts alone prove (or at least suspect) a failure. */
528
- function factsSuspectFailure(facts) {
529
- if (facts.isError === true)
530
- return true;
531
- if (typeof facts.exitCode === 'number' && facts.exitCode !== 0)
532
- return true;
533
- if (typeof facts.signal === 'string' && facts.signal.length > 0)
534
- return true;
535
- if (facts.ok === false || facts.timedOut === true || facts.timeout === true)
536
- return true;
537
- if (typeof facts.status === 'string' && /fail|error|timeout|timed_?out/i.test(facts.status))
538
- return true;
539
- return false;
540
- }
541
- /**
542
- * Turn one observed result into closing-evidence candidates.
543
- *
544
- * The regex is a prefilter and a floor, never a conclusion: matching lines are
545
- * kept whatever else happens, and a non-matching result still contributes its
546
- * tail summary (with the structured facts) to System One. A result is a failure
547
- * *suspicion* when a structured fact, a marker line, or a broader cue says so;
548
- * what the result really means is decided by `gate.verify`.
549
- *
550
- * @param tool - tool name that produced the result.
551
- * @param result - the execution-local result.
552
- * @param text - the effective model-facing text.
553
- * @returns bounded candidates, diagnostics first.
554
- */
555
- export function evidenceOf(tool, result, text) {
556
- const entries = [];
557
- const lines = text.split(/\r?\n/);
558
- const diagnostics = lines.filter((line) => FAILURE_MARKER.test(line));
559
- for (const line of diagnostics) {
560
- const clipped = clip(line.trim(), EVIDENCE_CHARS);
561
- if (clipped.length > 0)
562
- entries.push({ tool, text: clipped, priority: 'diagnostic', suspect: true });
563
- }
564
- const facts = structuredFacts(result);
565
- const factText = Object.keys(facts).length > 0 ? `{${JSON.stringify(facts)}} ` : '';
566
- const collapsed = text.replace(/\s+/g, ' ').trim();
567
- const tail = clip(`${factText}${collapsed}`, EVIDENCE_TAIL_CHARS);
568
- if (tail.length > 0) {
569
- entries.push({
570
- tool,
571
- text: `${tool} tail: ${tail}`,
572
- priority: 'tail',
573
- suspect: failureOf(result, text)
574
- || diagnostics.length > 0
575
- || factsSuspectFailure(facts)
576
- || FAILURE_CUE.test(text)
577
- });
578
- }
579
- if (diagnostics.length === 0) {
580
- const head = clip(collapsed, EVIDENCE_OTHER_CHARS);
581
- if (head.length > 0) {
582
- entries.push({ tool, text: `${tool}: ${head}`, priority: 'other', suspect: FAILURE_CUE.test(text) });
583
- }
584
- }
585
- return entries;
586
- }
587
- /**
588
- * Assemble the turn's evidence candidates into one budgeted string.
589
- *
590
- * Priority order is diagnostic → tail → other. A diagnostic line is the safety
591
- * floor and is never dropped; everything else competes for the budget and the
592
- * dropped characters are reported so the truncation is auditable.
593
- *
594
- * @param entries - candidates, oldest first.
595
- * @param budget - character budget of the assembled text.
596
- * @returns assembled text plus the kept/dropped character counts.
597
- */
598
- export function assembleEvidence(entries, budget) {
599
- const lines = [];
600
- let retained = 0;
601
- let truncated = 0;
602
- for (const priority of ['diagnostic', 'tail', 'other']) {
603
- for (const entry of entries) {
604
- if (entry.priority !== priority)
605
- continue;
606
- const size = entry.text.length + (lines.length > 0 ? 1 : 0);
607
- const fits = priority === 'diagnostic' || retained + size <= budget;
608
- if (!fits) {
609
- truncated += size;
610
- continue;
611
- }
612
- lines.push(entry.text);
613
- retained += size;
614
- }
615
- }
616
- return { text: lines.join('\n'), retainedChars: retained, truncatedChars: truncated };
617
- }
618
- /**
619
- * Decide the deterministic floor of one reduction from lengths alone.
620
- *
621
- * Lengths are enough because the floor form is fixed: context, marker, candidate,
622
- * marker, context. Deciding it this way is what lets `observe` account for the
623
- * *same* candidate `active` would install without building it.
624
- *
625
- * The floor is a *share*, not a suggestion. `pruneFloorRatio` says how much of
626
- * the original must survive, so the context budget is derived from it rather than
627
- * capped by the head/tail hints: a candidate that keeps 8% of a long payload is
628
- * not "floored" to 8% plus two small slices, it is widened until the installed
629
- * form really carries the promised share. The head/tail hints only decide how
630
- * that budget is split. A plan that cannot reach the share — because the marker
631
- * alone would eat the whole allowance — is refused, so a reduction never grows
632
- * the context.
633
- *
634
- * @param originalChars - length of the raw payload.
635
- * @param candidateChars - length of the judged candidate.
636
- * @param options - floor ratio, split hints, and marker length.
637
- * @returns the floor decision.
638
- */
639
- export function pruneFloorPlan(originalChars, candidateChars, options) {
640
- if (candidateChars === 0 || candidateChars >= originalChars) {
641
- return idleFloorPlan(originalChars);
642
- }
643
- const marker = Math.max(0, options.markerChars ?? 0);
644
- const head = Math.max(0, options.headChars ?? FLOOR_HEAD_CHARS);
645
- const tail = Math.max(0, options.tailChars ?? FLOOR_TAIL_CHARS);
646
- const share = Math.min(1, Math.max(0, options.floorRatio));
647
- const target = Math.ceil(originalChars * share);
648
- // The judged candidate is already the installed text when the floor does not
649
- // apply, and it carries no marker; only a deeper cut pays for the marker.
650
- if (candidateChars >= target) {
651
- return {
652
- floored: false,
653
- floorMissed: false,
654
- resultChars: candidateChars,
655
- omittedChars: originalChars - candidateChars,
656
- headChars: 0,
657
- tailChars: 0,
658
- markerChars: 0,
659
- markerOmitted: false
660
- };
661
- }
662
- // One marker side is mandatory: it carries the locator of the original. The
663
- // second is bought only when the share's budget leaves room for it. A candidate
664
- // that cannot even pay for the mandatory marker is still a real reduction, so
665
- // it is installed *without* the marker and the omission is recorded: dropping
666
- // it would trade a smaller answer for the whole payload over a missing line.
667
- if (candidateChars + marker >= originalChars) {
668
- return {
669
- floored: false,
670
- floorMissed: true,
671
- resultChars: candidateChars,
672
- omittedChars: originalChars - candidateChars,
673
- headChars: 0,
674
- tailChars: 0,
675
- markerChars: 0,
676
- markerOmitted: true
677
- };
678
- }
679
- let budget = Math.max(candidateChars + marker, Math.min(originalChars, target));
680
- let markerChars = marker;
681
- let context = budget - candidateChars - markerChars;
682
- if (context >= marker) {
683
- markerChars += marker;
684
- context -= marker;
685
- }
686
- const split = splitContext(context, head, tail);
687
- const resultChars = candidateChars + markerChars + context;
688
- if (resultChars >= originalChars)
689
- return idleFloorPlan(originalChars);
690
- return {
691
- floored: true,
692
- floorMissed: false,
693
- resultChars,
694
- omittedChars: originalChars - resultChars,
695
- headChars: split.head,
696
- tailChars: split.tail,
697
- markerChars,
698
- markerOmitted: false
699
- };
700
- }
701
- /**
702
- * Split one context budget between the head and the tail.
703
- *
704
- * The hints describe the *shape* of the context, not its ceiling, so a large
705
- * budget keeps their proportion instead of stopping at their sum. A zero-shaped
706
- * split degrades to an even one rather than dropping the context.
707
- * @param context - characters available for context.
708
- * @param head - head hint.
709
- * @param tail - tail hint.
710
- * @returns the two slice lengths, summing to the context.
711
- */
712
- function splitContext(context, head, tail) {
713
- const total = head + tail;
714
- const headChars = total <= 0 ? Math.ceil(context / 2) : Math.ceil((context * head) / total);
715
- return { head: Math.min(context, headChars), tail: context - Math.min(context, headChars) };
716
- }
717
- /** The plan of a reduction that is not happening. */
718
- function idleFloorPlan(originalChars) {
719
- return {
720
- floored: false,
721
- floorMissed: false,
722
- resultChars: originalChars,
723
- omittedChars: 0,
724
- headChars: 0,
725
- tailChars: 0,
726
- markerChars: 0,
727
- markerOmitted: false
728
- };
729
- }
730
- /** The marker one floored reduction carries on each side of its candidate. */
731
- export function pruneMarker(locator) {
732
- return `\n… [reflex prune: full original retrievable as ${locator}] …\n`;
733
- }
734
- /**
735
- * The marker a floor-missed install appends after its candidate.
736
- *
737
- * The floored form opens with the marker because the head has just ended with a
738
- * newline. A candidate that already ends with one needs no blank line before the
739
- * marker, so only the leading newline is dropped in that case; the trailing
740
- * newline is the same one the floored form carries.
741
- * @param candidate - the judged candidate about to be installed.
742
- * @param marker - the locator marker.
743
- * @returns the suffix to append.
744
- */
745
- function pruneMarkerSuffix(candidate, marker) {
746
- return candidate.endsWith('\n') ? marker.slice(1) : marker;
747
- }
748
- /** Split one payload into whole lines, the terminator kept with its line. */
749
- function floorLines(text) {
750
- return text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
751
- }
752
- /** The identity of one line for the duplicate test: its text without its terminator. */
753
- function floorLineIdentity(line) {
754
- return line.replace(/\r?\n$/, '').replace(/\r$/, '');
755
- }
756
- /**
757
- * How many whole lines of the head a budget can pay for.
758
- *
759
- * The head never crosses its budget and never stops inside a line: a cut that
760
- * cannot pay for the next line stops before it, so the kept prefix is always a
761
- * run of complete lines.
762
- * @param lines - the payload, split into whole lines.
763
- * @param budget - characters the head may spend.
764
- * @returns the number of lines to keep from the top.
765
- */
766
- function alignedHeadLines(lines, budget) {
767
- let used = 0;
768
- let count = 0;
769
- for (const line of lines) {
770
- if (used + line.length > budget)
771
- break;
772
- used += line.length;
773
- count += 1;
774
- }
775
- return count;
776
- }
777
- /**
778
- * How many whole lines of the tail a budget needs.
779
- *
780
- * The tail is the *shortest* run of complete lines from the end that still
781
- * carries the budget. A payload whose lines are longer than the budget cannot
782
- * honour it with a line-aligned suffix; the caller refuses instead of cutting
783
- * one, because half a line is not a shorter answer but a broken one.
784
- * @param lines - the payload, split into whole lines.
785
- * @param budget - characters the tail must carry.
786
- * @returns the number of lines to keep from the bottom.
787
- */
788
- function alignedTailLines(lines, budget) {
789
- if (budget <= 0)
790
- return 0;
791
- let used = 0;
792
- let count = 0;
793
- for (let index = lines.length - 1; index >= 0; index -= 1) {
794
- used += lines[index].length;
795
- count += 1;
796
- if (used >= budget)
797
- break;
798
- }
799
- return count;
800
- }
801
- /**
802
- * Drop the candidate lines the kept context already shows verbatim.
803
- *
804
- * The judgment reads the whole payload, so its extract repeats the lines a
805
- * reader can already see around it — `BEGIN`, `RESULT`, `END` in the trace that
806
- * prompted this. Repeating them is pure cost: the same line twice in one
807
- * message. Removal is per line and verbatim, so a diagnostic the context does
808
- * *not* carry always survives.
809
- * @param candidate - the judged extract.
810
- * @param head - the kept head.
811
- * @param tail - the kept tail.
812
- * @returns the candidate without the lines the context already shows.
813
- */
814
- function dedupeCandidateLines(candidate, head, tail) {
815
- const seen = new Set([...floorLines(head), ...floorLines(tail)].map(floorLineIdentity));
816
- const lines = floorLines(candidate);
817
- if (seen.size === 0 || lines.length === 0)
818
- return candidate;
819
- return lines.filter((line) => !seen.has(floorLineIdentity(line))).join('');
820
- }
821
- /**
822
- * Compose one floored form out of whole lines of the original.
823
- * @param lines - the original, split into whole lines.
824
- * @param headCount - lines kept from the top.
825
- * @param tailCount - lines kept from the bottom.
826
- * @param candidate - the judged extract.
827
- * @param marker - the locator marker.
828
- * @param secondMarker - the closing marker, or `''` when the share cannot pay for it.
829
- * @returns the installed text and the sizes it really carries.
830
- */
831
- function composeFloorLines(lines, headCount, tailCount, candidate, marker, secondMarker) {
832
- const head = lines.slice(0, headCount).join('');
833
- const tail = tailCount === 0 ? '' : lines.slice(lines.length - tailCount).join('');
834
- const middle = dedupeCandidateLines(candidate, head, tail);
835
- // The marker opens with a newline so it sits on its own line after the head.
836
- // With no head there is nothing to separate it from, and a leading blank line
837
- // would be the first thing a reader sees.
838
- const lead = head.length === 0 ? marker.replace(/^\n/, '') : marker;
839
- const closing = middle.length === 0 ? '' : secondMarker;
840
- return {
841
- text: `${head}${lead}${middle}${closing}${tail}`,
842
- headChars: head.length,
843
- tailChars: tail.length,
844
- markerChars: lead.length + closing.length
845
- };
846
- }
847
- /**
848
- * The plan of a floor the composition refused.
849
- *
850
- * A refusal is *not* a reason to throw the candidate away. The candidate is the
851
- * reduction the judgment already produced, and a floor that cannot widen it
852
- * without either breaking the share or growing past the original has simply
853
- * missed the floor, not invalidated the reduction: installing the candidate is
854
- * strictly better than carrying the whole payload. So the candidate is installed
855
- * with `floored: false` (no head/tail form was built) and `floorMissed: true`
856
- * (the promised share is not carried), and the sizes are booked against the text
857
- * that is really installed.
858
- *
859
- * The locator marker is appended when the candidate can still pay for it, so the
860
- * reader sees that a prune happened and where the full payload lives. When the
861
- * marker would push the install to the original's size or past it, the reduction
862
- * wins and the marker is omitted — recorded as `markerOmitted: true`, never
863
- * silently dropped.
864
- *
865
- * Only a candidate that is not actually smaller leaves the original untouched —
866
- * that is a real "no reduction", and the caller's own degradation path owns it.
867
- *
868
- * @param original - the raw payload.
869
- * @param candidate - the judged reduction the composition could not widen.
870
- * @param marker - the locator marker a floor-missed install wants to carry.
871
- * @returns the text to install and the floor decision that says why.
872
- */
873
- function refusedFloor(original, candidate, marker) {
874
- if (candidate.length >= original.length) {
875
- return { ...idleFloorPlan(original.length), text: original };
876
- }
877
- const suffix = pruneMarkerSuffix(candidate, marker);
878
- if (candidate.length + suffix.length < original.length) {
879
- return {
880
- floored: false,
881
- floorMissed: true,
882
- resultChars: candidate.length + suffix.length,
883
- omittedChars: original.length - candidate.length - suffix.length,
884
- headChars: 0,
885
- tailChars: 0,
886
- markerChars: suffix.length,
887
- markerOmitted: false,
888
- text: `${candidate}${suffix}`
889
- };
890
- }
891
- return {
892
- floored: false,
893
- floorMissed: true,
894
- resultChars: candidate.length,
895
- omittedChars: original.length - candidate.length,
896
- headChars: 0,
897
- tailChars: 0,
898
- markerChars: 0,
899
- markerOmitted: true,
900
- text: candidate
901
- };
902
- }
903
- /**
904
- * Enforce the deterministic floor of a judged reduction.
905
- *
906
- * The judgment proposes; this floor disposes. A candidate that cut deeper than
907
- * {@link ResolvedInterventionsConfig.pruneFloorRatio} of the original is replaced
908
- * by a form that keeps the head and the tail — the two places a compiler error, a
909
- * stack-trace summary, and a final result usually are — around the judgment's own
910
- * extract, with explicit markers that name where the full original was retained.
911
- * A candidate that is not actually smaller is refused outright, so a "reduction"
912
- * can never grow the context.
913
- *
914
- * The context is composed out of *whole lines* of the original, never out of
915
- * character slices: a cut that lands mid-line leaves the reader a fragment like
916
- * `=] progress 092`, which is not a shorter answer but a broken one. The head is
917
- * the longest run of complete lines its budget can pay for, the tail the shortest
918
- * run of complete lines that still carries its own, and any candidate line the
919
- * kept context already shows verbatim is dropped as a duplicate. Alignment and
920
- * removal move the real size, so the decision's modelled size is replaced here by
921
- * the size the text really has: a form that would fall short of the promised
922
- * share, or that would not be smaller than the original at all, is refused. A
923
- * refusal installs the judgment's own candidate with `floorMissed: true` rather
924
- * than the original — the candidate is a real reduction, and dropping it would
925
- * trade a smaller answer for the whole payload just because the floor form could
926
- * not be built.
927
- *
928
- * @param original - the raw payload.
929
- * @param candidate - the judged reduction.
930
- * @param options - floor options plus the locator the replacement publishes.
931
- * @returns the text to install, the floor decision, and the sizes involved.
932
- */
933
- export function applyPruneFloor(original, candidate, options) {
934
- const marker = pruneMarker(options.locator);
935
- const plan = pruneFloorPlan(original.length, candidate.length, { ...options, markerChars: marker.length });
936
- if (!plan.floored) {
937
- return { ...plan, text: plan.resultChars === candidate.length ? candidate : original };
938
- }
939
- const lines = floorLines(original);
940
- const share = Math.min(1, Math.max(0, options.floorRatio));
941
- const target = Math.ceil(original.length * share);
942
- const secondMarker = plan.markerChars > marker.length ? marker : '';
943
- let headCount = alignedHeadLines(lines, plan.headChars);
944
- if (headCount === 0 && plan.headChars > 0 && lines.length > 0) {
945
- // A first line longer than the head budget: taking it whole keeps a real line
946
- // where a cut could only produce a fragment. Whether the enlarged form is
947
- // installable at all is decided by the size checks below.
948
- headCount = 1;
949
- }
950
- let tailCount = alignedTailLines(lines, plan.tailChars);
951
- if (headCount + tailCount > lines.length)
952
- return refusedFloor(original, candidate, marker);
953
- let composed = composeFloorLines(lines, headCount, tailCount, candidate, marker, secondMarker);
954
- // The share is a promise, and rounding to a boundary or dropping duplicates can
955
- // fall short of it: widen by whole lines until the form really carries the
956
- // share. A payload with no room left is refused by the checks below, never
957
- // installed short.
958
- while (composed.text.length < target) {
959
- // Grow the smaller side first, so the two keep their configured proportion.
960
- const order = composed.headChars <= composed.tailChars ? [0, 1] : [1, 0];
961
- let grew = false;
962
- for (const side of order) {
963
- const nextHead = side === 0 ? headCount + 1 : headCount;
964
- const nextTail = side === 1 ? tailCount + 1 : tailCount;
965
- if (nextHead + nextTail > lines.length)
966
- continue;
967
- const next = composeFloorLines(lines, nextHead, nextTail, candidate, marker, secondMarker);
968
- if (next.text.length <= composed.text.length)
969
- continue;
970
- headCount = nextHead;
971
- tailCount = nextTail;
972
- composed = next;
973
- grew = true;
974
- break;
975
- }
976
- if (!grew)
977
- break;
978
- }
979
- if (composed.text.length >= original.length || composed.text.length < target) {
980
- return refusedFloor(original, candidate, marker);
981
- }
982
- return {
983
- ...plan,
984
- resultChars: composed.text.length,
985
- omittedChars: original.length - composed.text.length,
986
- headChars: composed.headChars,
987
- tailChars: composed.tailChars,
988
- markerChars: composed.markerChars,
989
- text: composed.text
990
- };
991
- }
992
- /**
993
- * Count the identical trailing repeats of one signature.
994
- * @param steps - observed steps, oldest first.
995
- * @param signature - the identity to count.
996
- * @returns the length of the trailing run of that signature.
997
- */
998
- export function countTrailingRepeats(steps, signature) {
999
- let count = 0;
1000
- for (let index = steps.length - 1; index >= 0; index -= 1) {
1001
- if (steps[index].signature !== signature)
1002
- break;
1003
- count += 1;
1004
- }
1005
- return count;
1006
- }
1007
- /**
1008
- * Count the trailing consecutive failures.
1009
- * @param steps - observed steps, oldest first.
1010
- * @returns the length of the trailing run of failing steps.
1011
- */
1012
- export function countTrailingFailures(steps) {
1013
- let count = 0;
1014
- for (let index = steps.length - 1; index >= 0; index -= 1) {
1015
- if (!steps[index].failed)
1016
- break;
1017
- count += 1;
1018
- }
1019
- return count;
1020
- }
1021
- /**
1022
- * Whether the window's tail alternates between exactly two call identities.
1023
- *
1024
- * `A B A B` is the cheapest loop to miss and among the most wasteful to run:
1025
- * neither call repeats consecutively, so a consecutive-repeat trigger never
1026
- * fires.
1027
- * @param steps - observed steps, oldest first.
1028
- * @param window - how many trailing steps to inspect.
1029
- * @returns whether the tail oscillates.
1030
- */
1031
- export function detectOscillation(steps, window) {
1032
- const tail = steps.slice(Math.max(0, steps.length - window));
1033
- if (tail.length < 4)
1034
- return false;
1035
- const signatures = new Set(tail.map((step) => step.signature));
1036
- if (signatures.size !== 2)
1037
- return false;
1038
- for (let index = 2; index < tail.length; index += 1) {
1039
- if (tail[index].signature !== tail[index - 2].signature)
1040
- return false;
1041
- }
1042
- return true;
1043
- }
1044
- /**
1045
- * Decide, locally and deterministically, whether a judgment is worth spending.
1046
- *
1047
- * This is the cost gate of the whole module: the expensive path is a System 1
1048
- * call, and it only opens when the *cheap* path already sees a pattern. A single
1049
- * distinctive call is never judged, however large its output.
1050
- *
1051
- * @param steps - observed steps, oldest first.
1052
- * @param options - thresholds, window, and the current call identity.
1053
- * @returns the suspicion, with `suspicious: false` when nothing justifies a call.
1054
- */
1055
- export function suspicionOf(steps, options) {
1056
- const window = steps.slice(Math.max(0, steps.length - options.window));
1057
- const repeats = countTrailingRepeats(window, options.signature);
1058
- if (repeats >= options.repeatThreshold) {
1059
- return { suspicious: true, pattern: 'repetition', note: `identical call repeated ${repeats}x`, repeats };
1060
- }
1061
- const failures = countTrailingFailures(window);
1062
- if (failures >= options.failureThreshold) {
1063
- return { suspicious: true, pattern: 'failing_retry', note: `${failures} consecutive failing steps`, repeats: failures };
1064
- }
1065
- if (detectOscillation(window, options.window)) {
1066
- return { suspicious: true, pattern: 'oscillation', note: `two calls alternating over ${window.length} steps`, repeats: window.length };
1067
- }
1068
- return { suspicious: false, note: 'no local pattern', repeats: 0 };
1069
- }
1070
- /** The verdict that stands in when no judgment could be spent. */
1071
- const EMPTY_VERDICT = { isStuck: false, confidence: 0, latencyMs: 0 };
1072
272
  /**
1073
273
  * The automatic-intervention engine of one plugin activation.
1074
274
  *
@@ -1091,6 +291,27 @@ export class InterventionEngine {
1091
291
  #stagnation;
1092
292
  #prune;
1093
293
  #gate;
294
+ #attribute;
295
+ /**
296
+ * Spend one decision inside the runtime's per-call attribution, when wired.
297
+ *
298
+ * Kept as one helper so every outbound judgment this engine makes — the three
299
+ * stagnation purchases, the two closing-gate calls and the prune judge — goes
300
+ * through the same seam. A construction without the seam runs the call
301
+ * unchanged, which is what keeps a bare `InterventionEngine` (tests, embedding
302
+ * Hosts) working.
303
+ * @param run - the decision to make.
304
+ * @param answered - whether the value counts as an answer.
305
+ * @param localFallback - whether the value is a local answer produced after a
306
+ * remote failure (prune's own judge path).
307
+ * @returns whatever the decision returned.
308
+ */
309
+ async #decide(run, answered, localFallback) {
310
+ if (this.#attribute === undefined)
311
+ return run();
312
+ const { result } = await this.#attribute(run, localFallback === undefined ? { answered } : { answered, localFallback });
313
+ return result;
314
+ }
1094
315
  #now;
1095
316
  #retain;
1096
317
  #audit;
@@ -1115,6 +336,7 @@ export class InterventionEngine {
1115
336
  this.#stagnation = options.stagnation;
1116
337
  this.#prune = options.prune;
1117
338
  this.#gate = options.gate;
339
+ this.#attribute = options.attribute;
1118
340
  this.#now = options.now ?? (() => Date.now());
1119
341
  this.#retain = options.retain;
1120
342
  this.#audit = options.audit;
@@ -1168,7 +390,7 @@ export class InterventionEngine {
1168
390
  * @returns its resolved three-state mode.
1169
391
  */
1170
392
  modeOf(capability) {
1171
- return this.config.capabilities[capability];
393
+ return modeOf(this.#config, capability);
1172
394
  }
1173
395
  /**
1174
396
  * Whether a hook serving one capability must be registered at all.
@@ -1176,9 +398,7 @@ export class InterventionEngine {
1176
398
  * @returns whether at least one of them is not `off`.
1177
399
  */
1178
400
  serves(...capabilities) {
1179
- if (!this.config.enabled)
1180
- return false;
1181
- return capabilities.some((capability) => this.modeOf(capability) !== 'off');
401
+ return policyServes(this.#config, ...capabilities);
1182
402
  }
1183
403
  /** The whole activation's accounting. */
1184
404
  report() {
@@ -1270,122 +490,124 @@ export class InterventionEngine {
1270
490
  * @param next - the rest of the waterfall.
1271
491
  * @returns the decision the Host dispatches on.
1272
492
  */
493
+ /**
494
+ * How many recorded steps already carry one identity.
495
+ *
496
+ * The call about to run is counted separately by the shared layer, so this is
497
+ * the count of the ones that really ran — which is what "repeated N times"
498
+ * means to a reader.
499
+ * @param state - the agent's bookkeeping.
500
+ * @param signature - the identity to count.
501
+ * @returns the number of recorded occurrences.
502
+ */
503
+ #priorSame(state, signature) {
504
+ return state.steps.filter((step) => step.signature === signature).length;
505
+ }
1273
506
  async toolCall(exec, next) {
1274
507
  const downstream = await next();
1275
- const capability = this.modeOf('stagnation');
1276
- if (capability === 'off' || !this.config.enabled)
508
+ if (!this.config.enabled)
1277
509
  return downstream;
1278
510
  if (this.#ownTools.has(exec.name))
1279
511
  return downstream;
512
+ // Checked here, outside the fail-open guard below, exactly as before: a call
513
+ // whose signal is already aborted is not a planning failure and must not be
514
+ // reported as one.
1280
515
  if (exec.signal?.aborted)
1281
516
  return downstream;
517
+ const agentId = agentKeyOf(exec.agent);
518
+ const state = this.#state(agentId, exec.agent);
519
+ const signature = callSignature(exec);
520
+ const waitShape = isWaitQuery(exec) ? 'wait-query' : pollShapeOf(exec);
1282
521
  let waitSuspected = false;
1283
- const started = this.#now();
1284
- try {
1285
- const agentId = agentKeyOf(exec.agent);
1286
- const state = this.#state(agentId, exec.agent);
1287
- const signature = callSignature(exec);
1288
- // The call about to run is part of its own window: three identical calls
1289
- // are a repetition at the moment the third one is proposed, and the
1290
- // judgment has to see all three. The pending entry is local — it is not
1291
- // committed to the agent's history, which the result records for real.
1292
- const pending = this.#observed(state, exec, signature);
1293
- const allWindow = [...state.steps, pending];
1294
- // Wait queries already in the window are dropped from the *progress*
1295
- // trigger: they are not progress the run could be repeating, and keeping
1296
- // them would both hide a real loop that waits between its attempts and
1297
- // manufacture an oscillation out of two identical polls.
1298
- const window = progressSteps(allWindow);
1299
- const waitShape = isWaitQuery(exec) ? 'wait-query' : pollShapeOf(exec);
1300
- // A wait-suspect call that this turn already classified is answered by
1301
- // that verdict, not re-asked; anything else is only worth a question when
1302
- // it actually repeats (the same threshold as any other repetition).
1303
- if (waitShape !== undefined && state.waited.has(signature)) {
1304
- this.#skip('wait-query', { capability: 'stagnation', state, agent: exec.agent });
1305
- return downstream;
1306
- }
1307
- const priorSame = allWindow.filter((step) => step.signature === signature).length - 1;
1308
- let suspicion = suspicionOf(window, {
522
+ // The decision itself is the shared layer's (see
523
+ // `core/orchestrate-stagnation.ts`); this method only answers the questions
524
+ // this Host alone can answer. Everything that remains here is a DSH fact: the
525
+ // agent's state slot, the call-signature algorithm, the job-tool list that
526
+ // defines a wait, the message and decision types, and the wording the model
527
+ // reads.
528
+ const port = {
529
+ policy: () => this.#config,
530
+ budget: () => state,
531
+ // One purchase: the service's answer, latency included. The purchase around
532
+ // it (memo, budgets, latency split, charge) is the shared layer's.
533
+ buy: async (step) => this.#decide(() => this.#stagnation.check(step.goal, [...step.history]), (value) => value !== undefined),
534
+ clock: () => ({ now: () => this.#now() }),
535
+ serves: () => this.#config.enabled,
536
+ toolName: () => exec.name,
537
+ window: () => state.steps,
538
+ // The call about to run is a retry exactly when this identity failed before.
539
+ pendingStep: () => ({
540
+ signature,
541
+ tool: exec.name,
542
+ input: clip(this.#argumentsOf(exec), STEP_CHARS),
543
+ output: '',
544
+ error: '',
545
+ failed: state.steps.some((step) => step.signature === signature && step.failed),
546
+ turn: state.turn,
547
+ at: this.#now()
548
+ }),
549
+ signature: () => signature,
550
+ progressWindow: () => progressSteps(state.steps),
551
+ suspicion: (steps) => suspicionOf(steps, {
1309
552
  repeatThreshold: this.config.repeatThreshold,
1310
553
  failureThreshold: this.config.failureThreshold,
1311
554
  window: this.config.windowSize,
1312
555
  signature
1313
- });
1314
- if (waitShape !== undefined && priorSame + 1 >= this.config.repeatThreshold) {
1315
- // The tool list only decides that this repetition is worth asking
1316
- // about; it does not pass or refuse anything by itself.
1317
- suspicion = {
1318
- suspicious: true,
1319
- pattern: 'repetition',
1320
- note: `wait-suspect ${waitShape} repeated ${priorSame + 1}x`,
1321
- repeats: priorSame + 1
1322
- };
1323
- waitSuspected = true;
1324
- }
1325
- if (!suspicion.suspicious || state.denied.has(signature))
1326
- return downstream;
1327
- if (state.applied.has(`stagnation:${signature}`)) {
1328
- this.#skip('duplicate-intervention', { capability: 'stagnation', state, agent: exec.agent });
1329
- return downstream;
1330
- }
1331
- if (!this.#actionWithinBudget(state)) {
1332
- this.#skip('intervention-cap', { capability: 'stagnation', state, agent: exec.agent });
1333
- return downstream;
1334
- }
1335
- // A wait question is judged on the polls themselves (each labelled with
1336
- // its place in the series, so the backend can read a wait rather than an
1337
- // exact repeat); every other question keeps the progress-only window.
1338
- const judgeSteps = waitSuspected ? annotateWaitHistory(allWindow, signature) : window;
1339
- const verdict = await this.#judge(state, exec.signal, judgeSteps, waitSuspected ? waitGoalOf(exec, waitShape ?? 'poll-shape', priorSame + 1) : undefined);
1340
- const judgment = this.#judgmentCharge(verdict, started, this.#now());
1341
- // Denial is latched per signature whether or not it was applied: in observe
1342
- // mode the refusal is what would have happened, and `denied` is what keeps
1343
- // the *next* identical attempt from being judged again in the same turn.
1344
- state.denied.add(signature);
1345
- if (!verdict.useful) {
1346
- this.#charge('stagnation', judgment);
1347
- if (waitSuspected)
1348
- state.waited.add(signature);
1349
- // A budget/abort skip keeps its own reason; only a real "not stuck"
1350
- // answer to a wait question is recorded as the wait outcome.
1351
- this.#skip(verdict.skip ?? (waitSuspected ? 'wait-query' : 'unconfirmed'), {
1352
- capability: 'stagnation',
1353
- state,
1354
- agent: exec.agent,
1355
- judgment
1356
- });
1357
- return downstream;
1358
- }
1359
- const plan = {
556
+ }),
557
+ alreadyIntervened: () => state.applied.has(`stagnation:${signature}`),
558
+ alreadyDenied: () => state.denied.has(signature),
559
+ wasClassifiedAsWait: (stepSignature) => state.waited.has(stepSignature),
560
+ latchDenied: () => state.denied.add(signature),
561
+ latchIntervened: () => state.applied.add(`stagnation:${signature}`),
562
+ passThrough: () => downstream,
563
+ deny: (feedback) => ({ kind: 'deny', reason: feedback }),
564
+ // Pre-execute never corrects a step: the correction belongs to the pre-step
565
+ // hook, whose port answers this. Reaching it here would mean the shared
566
+ // layer asked the wrong hook, so it is a programming error, not a branch.
567
+ correct: (feedback) => {
568
+ throw new Error(`toolCall cannot attach a correction (${feedback.length} chars)`);
569
+ },
570
+ denyFeedback: (facts) => this.#denyFeedback(exec.name, facts.suspicion, facts.verdict),
571
+ contextFeedback: (facts) => this.#contextFeedback(facts.suspicion, facts.verdict),
572
+ skip: (reason, charge) => this.#skip(reason, {
1360
573
  capability: 'stagnation',
1361
- action: 'deny-call',
1362
- reason: `System 1 confirmed ${verdict.response.patternType ?? suspicion.pattern} stagnation before ${exec.name}`,
1363
- feedback: this.#denyFeedback(exec.name, suspicion, verdict.response),
1364
- detail: {
1365
- pattern: String(verdict.response.patternType ?? suspicion.pattern ?? 'unknown'),
1366
- confidence: verdict.response.confidence,
1367
- repeats: suspicion.repeats,
1368
- turn: state.turn,
1369
- step: state.step
1370
- }
1371
- };
1372
- const applied = capability === 'active' && downstream.kind === 'allow';
1373
- if (capability === 'active' && !applied) {
1374
- this.#skip('downstream-decided', { capability: 'stagnation', state, agent: exec.agent });
1375
- }
1376
- // The decision is latched in both modes. Observe has to plan exactly what
1377
- // active would do — one refusal per episode, subject to the same turn cap —
1378
- // otherwise its column would over-count the very thing it is measuring.
1379
- state.refused.add(callKeyOf(exec));
1380
- state.applied.add(`stagnation:${signature}`);
1381
- this.#bookAction(state);
1382
- this.#conclude(plan, applied, exec.agent, { potentialSavedTokens: 0 }, judgment);
1383
- return applied ? { kind: 'deny', reason: plan.feedback } : downstream;
574
+ state,
575
+ agent: exec.agent,
576
+ ...(charge === undefined ? {} : { judgment: charge })
577
+ }),
578
+ chargeJudgment: (charge) => this.#charge('stagnation', charge),
579
+ conclude: (plan, applied, charge) => this.#conclude(plan, applied, exec.agent, { potentialSavedTokens: 0 }, charge)
580
+ };
581
+ // Whether this call reached the wait question, which only decides the
582
+ // fail-open reason: a wait whose judge could not answer is reported with its
583
+ // own reason instead of the generic one.
584
+ waitSuspected =
585
+ waitShape !== undefined &&
586
+ this.#priorSame(state, signature) + 1 >= this.config.repeatThreshold;
587
+ try {
588
+ const outcome = await orchestrateStagnationPre({
589
+ downstreamKind: downstream.kind,
590
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
591
+ ...(waitShape === undefined
592
+ ? {}
593
+ : {
594
+ waitShape: () => ({ shape: waitShape, repeats: this.#priorSame(state, signature) + 1 }),
595
+ waitClassified: () => state.waited.has(signature),
596
+ latchWait: () => state.waited.add(signature),
597
+ // A wait question is judged on the polls themselves: the backend
598
+ // reasons about the run, and labelling each poll with its place in
599
+ // the series keeps a sanctioned wait from reading as an exact
600
+ // repeat. How a poll is labelled is this Host's business.
601
+ judgeSteps: () => annotateWaitHistory([...state.steps, port.pendingStep()], signature),
602
+ waitQuestion: () => waitGoalOf(exec, waitShape, this.#priorSame(state, signature) + 1)
603
+ }),
604
+ noteRefused: () => state.refused.add(callKeyOf(exec))
605
+ }, port);
606
+ return outcome.result;
1384
607
  }
1385
608
  catch {
1386
609
  // FAIL-OPEN: a planning failure must never veto a call the rest of the
1387
- // waterfall already allowed. A wait whose judge could not answer is
1388
- // reported with its own reason instead of the generic one.
610
+ // waterfall already allowed.
1389
611
  this.#skip(waitSuspected ? 'wait-query-unavailable' : 'planning-error', {
1390
612
  capability: 'stagnation',
1391
613
  agent: exec.agent
@@ -1490,85 +712,75 @@ export class InterventionEngine {
1490
712
  state.refused.clear();
1491
713
  }
1492
714
  state.step = payload.step;
1493
- const capability = this.modeOf('stagnation');
1494
- if (capability === 'off' || !this.config.enabled)
1495
- return downstream;
1496
- if (payload.signal?.aborted || downstream.kind !== 'enter')
1497
- return downstream;
1498
- const last = state.steps[state.steps.length - 1];
1499
- if (last === undefined)
1500
- return downstream;
1501
- // A poll that already passed the semantic wait judgment has nothing to
1502
- // correct here: the run asked about a background job again, it did not
1503
- // repeat its work. A poll this turn never judged was not a repetition, so
1504
- // it is not a stagnation episode either.
1505
- if (last.wait === true) {
1506
- this.#skip(state.waited.has(last.signature) ? 'wait-query' : 'wait-query-unjudged', {
1507
- capability: 'stagnation',
1508
- state,
1509
- agent: payload.agent
1510
- });
1511
- return downstream;
1512
- }
1513
- const signature = last.signature;
1514
- if (state.applied.has(`stagnation:${signature}`)) {
1515
- this.#skip('duplicate-intervention', { capability: 'stagnation', state, agent: payload.agent });
1516
- return downstream;
1517
- }
1518
- if (!this.#actionWithinBudget(state)) {
1519
- this.#skip('intervention-cap', { capability: 'stagnation', state, agent: payload.agent });
1520
- return downstream;
1521
- }
1522
- // The same window the pre-execute trigger measures: waits are not progress
1523
- // to count, so a real loop either side of them is still one loop.
1524
- const window = progressSteps(state.steps);
1525
- const suspicion = suspicionOf(window, {
1526
- repeatThreshold: this.config.repeatThreshold,
1527
- failureThreshold: this.config.failureThreshold,
1528
- window: this.config.windowSize,
1529
- signature
1530
- });
1531
- if (!suspicion.suspicious)
1532
- return downstream;
1533
- const verdict = await this.#judge(state, payload.signal, window);
1534
- const judgment = this.#judgmentCharge(verdict, started, this.#now());
1535
- if (!verdict.useful) {
1536
- this.#charge('stagnation', judgment);
1537
- this.#skip(verdict.skip ?? 'unconfirmed', {
715
+ // Turn bookkeeping above is this Host's and stays here: it is what the
716
+ // closing check and the prune memo read, and it belongs to whoever owns
717
+ // the turn boundary. What is shared is the *decision* that follows.
718
+ const agentIdForCorrection = agentId;
719
+ const port = {
720
+ policy: () => this.#config,
721
+ budget: () => state,
722
+ buy: async (step) => this.#decide(() => this.#stagnation.check(step.goal, [...step.history]), (value) => value !== undefined),
723
+ clock: () => ({ now: () => this.#now() }),
724
+ serves: () => this.#config.enabled,
725
+ toolName: () => state.steps[state.steps.length - 1]?.tool ?? '',
726
+ window: () => state.steps,
727
+ pendingStep: () => state.steps[state.steps.length - 1],
728
+ signature: () => state.steps[state.steps.length - 1]?.signature ?? '',
729
+ progressWindow: () => progressSteps(state.steps),
730
+ suspicion: (steps) => suspicionOf(steps, {
731
+ repeatThreshold: this.config.repeatThreshold,
732
+ failureThreshold: this.config.failureThreshold,
733
+ window: this.config.windowSize,
734
+ signature: state.steps[state.steps.length - 1]?.signature ?? ''
735
+ }),
736
+ alreadyIntervened: () => state.applied.has(`stagnation:${state.steps[state.steps.length - 1]?.signature ?? ''}`),
737
+ alreadyDenied: () => false,
738
+ wasClassifiedAsWait: (stepSignature) => state.waited.has(stepSignature),
739
+ latchDenied: () => undefined,
740
+ latchIntervened: () => state.applied.add(`stagnation:${state.steps[state.steps.length - 1]?.signature ?? ''}`),
741
+ passThrough: () => downstream,
742
+ deny: () => downstream,
743
+ // The correction is appended to the messages the rest of the waterfall
744
+ // admitted; the array it was given is not mutated in place.
745
+ //
746
+ // `downstream.messages` is read without a fallback on purpose. An `enter`
747
+ // decision always carries the list, so an absent one means the rest of the
748
+ // waterfall handed back something this Host cannot correct — and the
749
+ // fail-open guard below is what should record that, not a silent
750
+ // `messages: [correction]` that drops the very messages the step admitted.
751
+ correct: (feedback) => ({
752
+ ...downstream,
753
+ messages: [
754
+ ...downstream.messages,
755
+ this.#message(agentIdForCorrection, state.turn, payload.step, feedback)
756
+ ]
757
+ }),
758
+ denyFeedback: (facts) => this.#denyFeedback(facts.tool, facts.suspicion, facts.verdict),
759
+ contextFeedback: (facts) => this.#contextFeedback(facts.suspicion, facts.verdict),
760
+ skip: (reason, charge) => this.#skip(reason, {
1538
761
  capability: 'stagnation',
1539
762
  state,
1540
763
  agent: payload.agent,
1541
- judgment
1542
- });
1543
- return downstream;
1544
- }
1545
- const plan = {
1546
- capability: 'stagnation',
1547
- action: 'corrective-context',
1548
- reason: `System 1 confirmed ${verdict.response.patternType ?? suspicion.pattern} stagnation before step ${payload.step}`,
1549
- feedback: this.#contextFeedback(suspicion, verdict.response),
1550
- detail: {
1551
- pattern: String(verdict.response.patternType ?? suspicion.pattern ?? 'unknown'),
1552
- confidence: verdict.response.confidence,
1553
- repeats: suspicion.repeats,
1554
- turn: state.turn,
1555
- step: payload.step
1556
- }
764
+ ...(charge === undefined ? {} : { judgment: charge })
765
+ }),
766
+ chargeJudgment: (charge) => this.#charge('stagnation', charge),
767
+ conclude: (plan, applied, charge) => this.#conclude(plan, applied, payload.agent, { potentialSavedTokens: 0 }, charge)
1557
768
  };
1558
- const applied = capability === 'active';
1559
- // The latch is mode-independent on purpose. Observe has to consume the same
1560
- // episode — one intervention per detected loop, one charge against the turn's
1561
- // cap — or its accounting would describe a run nobody could reproduce;
1562
- // installing the message is the only thing the mode gates.
1563
- state.applied.add(`stagnation:${signature}`);
1564
- this.#bookAction(state);
1565
- this.#conclude(plan, applied, payload.agent, { potentialSavedTokens: 0 }, judgment);
1566
- if (!applied)
769
+ // The abort is checked *before* the shared call and the catch below is
770
+ // left to do what it always did: a pre-step that throws is reported as a
771
+ // planning error, and that report is what a cancelled turn has always left
772
+ // in the log. Passing the signal through instead would make the shared
773
+ // layer answer `aborted` and leave no trace at all — a quieter outcome, but
774
+ // a different one.
775
+ if (payload.signal?.aborted === true)
1567
776
  return downstream;
1568
- return {
1569
- ...downstream,
1570
- messages: [...downstream.messages, this.#message(agentId, state.turn, payload.step, plan.feedback)]
1571
- };
777
+ const outcome = await orchestrateStagnationStep({
778
+ downstreamKind: downstream.kind,
779
+ // `undefined` is not passed on: the shared layer only knows a signal it
780
+ // can act on, and an absent one has to stay absent.
781
+ signal: undefined
782
+ }, port);
783
+ return outcome.result;
1572
784
  }
1573
785
  catch {
1574
786
  // FAIL-OPEN: the step enters with exactly the messages it would have had.
@@ -1588,133 +800,70 @@ export class InterventionEngine {
1588
800
  * @param payload - the agent whose turn reached its stop boundary.
1589
801
  */
1590
802
  async turnStopping(payload) {
1591
- const capability = this.modeOf('closing');
1592
- if (capability === 'off' || !this.config.enabled)
803
+ // The mode check happens in the shared layer, deliberately: "off" is not a
804
+ // weaker decision, it is the absence of one, and a host that read the mode
805
+ // here as well would be the second place the switch is interpreted.
806
+ // The very first question is whether this decision exists at all. A turn that
807
+ // closes while the capability is off (or the master switch is off) must leave
808
+ // no trace — not even an empty per-agent state, which would show up in
809
+ // `stateOf()` as an agent the engine has seen. Asking it before touching any
810
+ // state is what keeps "off" the absence of a decision rather than a decision
811
+ // that did nothing.
812
+ if (this.modeOf('closing') === 'off' || !this.config.enabled)
1593
813
  return;
1594
814
  const started = this.#now();
1595
815
  try {
1596
816
  const agentId = agentKeyOf(payload.agent);
1597
817
  const state = this.#state(agentId, payload.agent);
1598
- const claimsText = state.claims;
1599
- // Two deterministic facts decide whether a closing judgment is worth
1600
- // buying: the turn said something, and at least one result is a failure
1601
- // suspicion. Neither fact concludes *which* sentence claims completion —
1602
- // that is the System One question asked below.
1603
- if (claimsText.length === 0 || !state.evidenceSuspect)
1604
- return;
1605
- const candidates = claimCandidates(claimsText);
1606
- if (candidates.length === 0)
1607
- return;
1608
- if (state.applied.has(`closing:turn:${payload.turn}`)) {
1609
- this.#skip('duplicate-intervention', { capability: 'closing', state, agent: payload.agent });
1610
- return;
1611
- }
1612
- if (!this.#actionWithinBudget(state)) {
1613
- this.#skip('intervention-cap', { capability: 'closing', state, agent: payload.agent });
1614
- return;
1615
- }
1616
- if (payload.signal?.aborted)
1617
- return;
1618
- // Assemble what the judgment will read. Truncation is by priority and
1619
- // never removes a failure-marker line; the amount dropped is reported.
1620
- const assembled = assembleEvidence(state.evidence, this.config.closingEvidenceChars);
1621
- this.#evidenceStats.retainedChars += assembled.retainedChars;
1622
- this.#evidenceStats.truncatedChars += assembled.truncatedChars;
1623
- if (assembled.truncatedChars > 0) {
1624
- this.#skip('evidence-truncated', { capability: 'closing', state, agent: payload.agent });
1625
- }
1626
- // The closing classification is a judgment like any other: one request
1627
- // with at most MAX_CLAIMS scored questions, bought from the same turn and
1628
- // session budget as a stagnation check.
1629
- const classifySkip = this.#spendJudgment(state);
1630
- if (classifySkip) {
1631
- this.#skip(classifySkip, { capability: 'closing', state, agent: payload.agent });
1632
- return;
1633
- }
1634
- const classifyStarted = this.#now();
1635
- let classification;
1636
- try {
1637
- classification = await this.#gate.classifyClaims({
1638
- statements: candidates,
818
+ const turn = payload.turn;
819
+ const port = {
820
+ policy: () => this.#config,
821
+ budget: () => state,
822
+ clock: () => ({ now: () => this.#now() }),
823
+ serves: () => this.#config.enabled,
824
+ mode: () => this.modeOf('closing'),
825
+ claims: () => state.claims,
826
+ evidenceSuspect: () => state.evidenceSuspect,
827
+ evidence: () => state.evidence,
828
+ evidenceBudget: () => this.config.closingEvidenceChars,
829
+ aborted: () => payload.signal?.aborted === true,
830
+ // The latch is *per turn*, not per signature: a closing episode is the
831
+ // turn itself. This is the one latch that does not fit the `Host*Port`
832
+ // shape the other capabilities use.
833
+ alreadyObjected: () => state.applied.has(CLOSING_LATCH.applied(turn)),
834
+ latchObjected: () => state.applied.add(CLOSING_LATCH.applied(turn)),
835
+ agentId: () => agentId,
836
+ classify: async (request) => this.#decide(() => this.#gate.classifyClaims({
837
+ statements: [...request.statements],
1639
838
  intent: this.config.intent,
1640
- context: assembled.text.slice(0, 600)
1641
- });
1642
- }
1643
- catch {
1644
- // FAIL-OPEN: an unavailable classifier must not become a model-visible
1645
- // objection, and it must never fall back to the retired word list.
1646
- this.#skip('closing-claim-unavailable', { capability: 'closing', state, agent: payload.agent });
1647
- return;
1648
- }
1649
- const claims = classification.results
1650
- .filter((item) => item.isClaim && item.confidence >= this.config.claimMinConfidence)
1651
- .map((item) => ({ statement: item.statement }));
1652
- const classifyTokens = candidates.reduce((sum, statement) => sum + estimateTokens(statement), 0);
1653
- const classificationCharge = {
1654
- judgments: 1,
1655
- memoHits: 0,
1656
- localLatencyMs: Math.max(0, this.#now() - classifyStarted - classification.latencyMs),
1657
- remoteLatencyMs: classification.latencyMs,
1658
- judgeTokens: classifyTokens
1659
- };
1660
- if (claims.length === 0) {
1661
- this.#charge('closing', classificationCharge);
1662
- this.#skip('closing-no-claim', {
1663
- capability: 'closing',
1664
- state,
1665
- agent: payload.agent,
1666
- judgment: classificationCharge
1667
- });
1668
- return;
1669
- }
1670
- // Classification and verification are one logical closing judgment: the
1671
- // classification decides *whether* anything is worth verifying, and both
1672
- // requests are charged (tokens and latency) against the one judgment the
1673
- // turn budget allowed.
1674
- const verdict = await this.#gate.verify(claims, assembled.text, {
1675
- latchCacheKey: `reflex-closing:${agentId}:${payload.turn}`
1676
- });
1677
- const judgeTokens = classifyTokens + claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(assembled.text));
1678
- const judgment = {
1679
- judgments: 1,
1680
- memoHits: 0,
1681
- localLatencyMs: Math.max(0, this.#now() - started - verdict.latencyMs - classification.latencyMs),
1682
- remoteLatencyMs: classification.latencyMs + verdict.latencyMs,
1683
- judgeTokens
1684
- };
1685
- // `escalate` is not a contradiction. It means the gate could not decide —
1686
- // an unavailable backend degrades exactly this way — and steering a turn on
1687
- // an undecided verdict would turn a backend failure into a model-visible
1688
- // objection. Only a verdict that really contradicts the claim steers.
1689
- const contradicted = verdict.results
1690
- .filter((item) => item.outcome === 'contradicted')
1691
- .map((item) => clip(item.statement, 160));
1692
- const undecided = verdict.results.filter((item) => item.outcome === 'escalate').length;
1693
- if (contradicted.length === 0) {
1694
- this.#charge('closing', judgment);
1695
- this.#skip(undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed', {
839
+ context: request.context
840
+ }), (value) => value !== undefined),
841
+ verify: async (claims, evidence, options) => this.#decide(() => this.#gate.verify([...claims], evidence, options), (value) => value !== undefined),
842
+ claimMinConfidence: () => this.config.claimMinConfidence,
843
+ describe: (facts) => this.#closingFeedback(facts.contradicted),
844
+ // The action itself stays here. Steering is the only way a listener may
845
+ // extend a turn, and the message it carries is this Host's to word.
846
+ steer: (feedback) => this.#steer(payload.agent, this.#message(agentId, turn, state.step, feedback)),
847
+ // `#evidenceStats` is engine-level, not per-agent: it counts what this
848
+ // activation assembled, across every agent it served.
849
+ noteEvidence: (stats) => {
850
+ this.#evidenceStats.retainedChars += stats.retainedChars;
851
+ this.#evidenceStats.truncatedChars += stats.truncatedChars;
852
+ },
853
+ skip: (reason, charge) => this.#skip(reason, {
1696
854
  capability: 'closing',
1697
855
  state,
1698
856
  agent: payload.agent,
1699
- judgment
1700
- });
1701
- return;
1702
- }
1703
- const plan = {
1704
- capability: 'closing',
1705
- action: 'steer-closing',
1706
- reason: `closing evidence contradicts ${contradicted.length} completion claim(s)`,
1707
- feedback: this.#closingFeedback(contradicted),
1708
- detail: { confidence: verdict.results[0]?.confidence, turn: payload.turn, step: state.step }
857
+ ...(charge === undefined ? {} : { judgment: charge })
858
+ }),
859
+ chargeJudgment: (charge) => this.#charge('closing', charge),
860
+ conclude: (plan, applied, charge) => this.#conclude(plan, applied, payload.agent, { potentialSavedTokens: 0 }, charge)
1709
861
  };
1710
- const applied = capability === 'active';
1711
- // Latched in both modes, for the same reason as the stagnation path: the
1712
- // episode is consumed once, and only the steering is gated on the mode.
1713
- state.applied.add(`closing:turn:${payload.turn}`);
1714
- this.#bookAction(state);
1715
- this.#conclude(plan, applied, payload.agent, { potentialSavedTokens: 0 }, judgment);
1716
- if (applied)
1717
- this.#steer(payload.agent, this.#message(agentId, payload.turn, state.step, plan.feedback));
862
+ void started;
863
+ // The position is an input of the closing decision, never a port accessor:
864
+ // the turn is the boundary being closed (which can be a turn no step has
865
+ // recorded yet), and the step is the one this engine last recorded.
866
+ await orchestrateClosing({ position: { turn, step: state.step } }, port);
1718
867
  }
1719
868
  catch {
1720
869
  // FAIL-OPEN: a failed closing check leaves the turn boundary alone.
@@ -1768,558 +917,180 @@ export class InterventionEngine {
1768
917
  * @returns the decision the Host commits.
1769
918
  */
1770
919
  async #pruneResult(exec, downstream, effective, state, text, started) {
1771
- const capability = this.modeOf('prune');
1772
- if (capability === 'off')
1773
- return downstream;
1774
- if (downstream.kind === 'block')
1775
- return downstream;
1776
- // The payload identity is taken once, before any branch can refuse it: every
1777
- // skip below names the payload it was about, so the log answers "which result
1778
- // was not pruned" as well as "why".
1779
- const payloadDetail = prunePayloadDetail(text);
1780
- if ('value' in downstream && downstream.value !== undefined) {
1781
- // A value-shaped accept replaced the payload wholesale; nothing here knows
1782
- // what its text is, so nothing here may touch it.
1783
- this.#skip('value-shaped-accept', { capability: 'prune', state, agent: exec.agent });
1784
- return downstream;
1785
- }
1786
- if (!hasTextBlock(effective)) {
1787
- // Nothing to replace, and nothing that could be reported as replaced. Asked
1788
- // before the size checks: an image-only payload is not "small", it is out of
1789
- // scope, and the skip reason should say so.
1790
- this.#skip('no-text-block', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });
1791
- return downstream;
1792
- }
1793
- if (text.length < this.#pruneThreshold) {
1794
- this.#skip('below-threshold', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });
1795
- return downstream;
1796
- }
1797
- if ((text.match(/\n/g)?.length ?? 0) < PRUNE_MIN_LINES) {
1798
- // Not line-oriented output: the judge is asked to extract diagnostics, and a
1799
- // payload with no lines does not have any to extract. Rewriting it would
1800
- // destroy semantic data rather than compress a trace.
1801
- this.#skip('unsupported-payload', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });
1802
- return downstream;
1803
- }
1804
- if (text.length > MAX_RETAINED_CHARS) {
1805
- // Retention is a precondition of replacing anything, so an oversized payload
1806
- // is refused *before* it is judged or reported as a saving.
1807
- this.#skip('retention-too-large', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });
1808
- return downstream;
1809
- }
1810
- const retain = this.#retain;
1811
- if (!retain) {
1812
- // Without a retention sink nothing may be replaced: the module will not
1813
- // destroy the only copy of a result it cannot give back.
1814
- this.#skip('retention-unavailable', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });
1815
- return downstream;
1816
- }
1817
- if (!this.#actionWithinBudget(state)) {
1818
- // A reduction is an intervention like a refusal or a correction, so it draws
1819
- // on the same per-turn allowance — and it is asked here, before a judgment is
1820
- // bought, so a full turn costs nothing to refuse. Both modes are checked:
1821
- // observe has to plan no more actions than active could take, including the
1822
- // ones the memo would have answered for free.
1823
- this.#skip('intervention-cap', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });
1824
- return downstream;
1825
- }
1826
- // Whether *this* agent can retain is the sink's answer, not this module's
1827
- // guess: the production sink refuses a session-less agent by returning nothing,
1828
- // which lands on the same fail-open path below.
1829
- const session = sessionOf(exec.agent);
1830
- const digest = digestOf(text);
1831
- // The locator is derived from the payload, and the production sink names the
1832
- // retained copy the same way — which is what makes the plan's size the size of
1833
- // the form active will install, in both modes.
1834
- const locator = pruneLocator(digest);
1835
- const memo = this.#memoGet(state, digest);
1836
- // A memo hit answers the question the judgment already answered; only a mode
1837
- // that needs the reduction's *text* has to ask for it again.
1838
- const needsCandidate = capability === 'active' && (memo?.text === undefined);
1839
- if (!memo || needsCandidate) {
1840
- const skip = this.#spendJudgment(state);
1841
- if (skip) {
1842
- this.#skip(skip, { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });
1843
- return downstream;
1844
- }
1845
- }
1846
- const response = memo && !needsCandidate
1847
- ? {
1848
- processedOutput: memo.text ?? text,
1849
- originalChars: memo.originalChars,
1850
- prunedChars: memo.prunedChars,
1851
- estimatedTokensSaved: memo.tokensSaved,
1852
- reductionPercentage: reductionPercentage(memo.originalChars, memo.prunedChars),
1853
- shadow: memo.text === undefined,
1854
- latencyMs: 0,
1855
- ...(memo.diagnostics ?? {})
1856
- }
1857
- // Both modes take the *real* candidate, and both ask for it measure-only.
1858
- // `shadow` only decides whether the backend hands its text back, while
1859
- // `prunedChars` is that candidate's size either way; the text is what the floor
1860
- // composes from, so a withheld measurement would not be the same input at all.
1861
- // Whether the payload is installed is decided here, by the floor, *after* the
1862
- // service has written its ledger entry — so this path never lets the service
1863
- // declare a saving: it measures (`tokensSaved` 0, the candidate's size in
1864
- // `details.potentialTokensSaved`) and the intervention record carries what was
1865
- // really installed. The explicit `reflex_prune` tool, which does hand the
1866
- // reduced text back to its caller, keeps booking the reduction it returns.
1867
- : await this.#prune.prune(text, {
1868
- intent: this.config.intent,
1869
- measureOnly: true,
1870
- // Per-segment System One judging starts at this size; below it the
1871
- // backend's deterministic candidates run and no judgment is spent.
1872
- pruneJudgeMinChars: this.config.pruneJudgeMinChars
1873
- });
1874
- const originalTokens = estimateTokens(text);
1875
- // One composition, both modes: the floored text the plan describes is the text
1876
- // active installs, byte for byte. Line alignment and duplicate removal move its
1877
- // real size away from the modelled one, so the number both modes account for is
1878
- // the length of the composed text — never a prediction about it.
1879
- const composed = applyPruneFloor(text, response.processedOutput, {
1880
- floorRatio: this.config.pruneFloorRatio,
1881
- headChars: this.config.pruneHeadChars,
1882
- tailChars: this.config.pruneTailChars,
1883
- locator
1884
- });
1885
- const candidateTokens = Math.ceil(composed.text.length / 4);
1886
- // What the judgment reported about its own path, plus the sizes both the plan
1887
- // and a skip record quote. Recorded even when the candidate is not smaller,
1888
- // because that is exactly the branch a real run cannot explain from its log.
1889
- const diagnostics = pruneDiagnosticsOf(response);
1890
- // A memo hit hands back a form that was composed for this payload already. It is
1891
- // its own fixed point — it carries the share, so the plan of the same lengths
1892
- // stays "not floored" and gives that text straight back — but its provenance is
1893
- // not readable from those lengths any more. The memo, which was written by the
1894
- // composition, answers for it: without this the audit would report a floored
1895
- // install as an unfloored one and flip the wording of the feedback with it.
1896
- const reusedFromMemo = !needsCandidate && memo?.text !== undefined ? memo : undefined;
1897
- const floorApplied = reusedFromMemo ? reusedFromMemo.floored : composed.floored;
1898
- const floorMissed = reusedFromMemo ? reusedFromMemo.floorMissed === true : composed.floorMissed;
1899
- const markerOmitted = reusedFromMemo ? reusedFromMemo.markerOmitted === true : composed.markerOmitted;
1900
- const measured = {
1901
- ...payloadDetail,
1902
- ...diagnostics,
1903
- originalTokens,
1904
- candidateTokens,
1905
- floored: floorApplied,
1906
- floorMissed,
1907
- markerOmitted,
1908
- candidateChars: composed.text.length
1909
- };
1910
- const judged = !memo || needsCandidate;
1911
- const judgment = {
1912
- judgments: judged ? 1 : 0,
1913
- memoHits: judged ? 0 : 1,
1914
- localLatencyMs: Math.max(0, this.#now() - started - (judged ? response.latencyMs : 0)),
1915
- remoteLatencyMs: judged ? response.latencyMs : 0,
1916
- // The pre-prune payload is what the pruner reasoned about; a backend call is
1917
- // a judgment even when it returns locally in under a millisecond.
1918
- judgeTokens: judged ? originalTokens : 0
1919
- };
1920
- if (candidateTokens >= originalTokens) {
1921
- this.#charge('prune', { ...judgment, originalTokens });
1922
- // The branch a real "prune: active but nothing happened" run lands in: the
1923
- // judgment ran, and the candidate it produced was not smaller. The record
1924
- // says so with the path that produced it and the sizes both sides had.
1925
- this.#skip('no-reduction', {
1926
- capability: 'prune',
1927
- state,
1928
- agent: exec.agent,
1929
- detail: measured,
1930
- judgment
1931
- });
1932
- return downstream;
1933
- }
1934
- const plan = {
1935
- capability: 'prune',
1936
- action: 'prune-result',
1937
- reason: `${exec.name} returned ${originalTokens} tokens; the judged reduction carries ${candidateTokens}`,
1938
- feedback: this.#pruneFeedback(exec.name, originalTokens, candidateTokens, {
1939
- floored: floorApplied,
1940
- floorMissed,
1941
- markerOmitted,
1942
- locator,
1943
- keptSegments: diagnostics.keptSegments,
1944
- judgedSegments: diagnostics.judgedSegments
1945
- }),
1946
- detail: {
1947
- digest,
1948
- floorApplied,
1949
- floorMissed,
1950
- markerOmitted,
1951
- confidence: response.reductionPercentage,
1952
- turn: state.turn,
1953
- step: state.step,
1954
- ...diagnostics,
1955
- originalChars: text.length,
1956
- candidateChars: composed.text.length
1957
- }
1958
- };
1959
- const planCosts = { originalTokens, candidateTokens, potentialSavedTokens: originalTokens - candidateTokens };
1960
- if (capability !== 'active') {
1961
- // Observe: the plan is real and charged, the surface is untouched, and the
1962
- // memo keeps the composed form — the same form active would install, from the
1963
- // same candidate — so a later hit reports the reduction this mode really saw.
1964
- // A plan this mode records is the action active would have taken, so it books
1965
- // the slot active would have booked.
1966
- this.#bookAction(state);
1967
- this.#conclude(plan, false, exec.agent, planCosts, judgment);
1968
- if (!memo) {
1969
- this.#memoSet(state, digest, {
1970
- text: composed.text,
1971
- originalChars: text.length,
1972
- prunedChars: composed.text.length,
1973
- tokensSaved: originalTokens - candidateTokens,
1974
- floored: floorApplied,
1975
- floorMissed,
1976
- markerOmitted,
1977
- diagnostics
1978
- });
1979
- }
1980
- return downstream;
1981
- }
1982
- // Active. The original is retained *before* anything is replaced, and only a
1983
- // verified retention makes the replacement installable at all. A payload whose
1984
- // copy is already retained keeps that copy instead of writing a second one.
1985
- const alreadyRetained = memo?.locator;
1986
- const retention = alreadyRetained
1987
- ? { locator: alreadyRetained }
1988
- : retain(session, {
1989
- digest,
1990
- callId: exec.callId,
1991
- tool: exec.name,
1992
- turn: state.turn,
1993
- step: state.step,
1994
- text
1995
- });
1996
- if (!retention || typeof retention.locator !== 'string' || retention.locator.length === 0) {
1997
- // No controlled copy, no reduction. The result stays exactly as the rest of
1998
- // the waterfall produced it, and no saving is recorded — but the judgment
1999
- // that got this far was really made, so it is charged rather than hidden.
2000
- this.#charge('prune', judgment);
2001
- this.#skip('retention-failed', {
2002
- capability: 'prune',
2003
- state,
2004
- agent: exec.agent,
2005
- detail: measured,
2006
- judgment
2007
- });
2008
- return downstream;
2009
- }
2010
- // The form both modes accounted for is the form that gets installed: the locator
2011
- // is derived from the payload and the sink names its copy the same way, so the
2012
- // composition already published is reused byte for byte — with the provenance the
2013
- // plan gave it, rather than with what re-reading its own lengths would say. Only a
2014
- // sink that named the copy differently forces a rebuild, and then the real length
2015
- // and provenance of that rebuild are what gets accounted for.
2016
- const installed = retention.locator === locator
2017
- ? { ...composed, floored: floorApplied, floorMissed, markerOmitted }
2018
- : applyPruneFloor(text, response.processedOutput, {
920
+ // The decision itself is the shared layer's (see `core/orchestrate.ts`); this
921
+ // method only answers the questions this Host alone can answer. Everything
922
+ // that stays here is a DSH fact: the agent's state slot, the session log
923
+ // sink, the content-block shape, and the wording the panel shows.
924
+ const outcome = await orchestratePrune({
925
+ callId: exec.callId,
926
+ tool: exec.name,
927
+ text,
928
+ blockedByDownstream: downstream.kind === 'block',
929
+ valueShapedAccept: 'value' in downstream && downstream.value !== undefined,
930
+ started
931
+ }, {
932
+ policy: () => this.#config,
933
+ budget: () => state,
934
+ // The shared base asks "does this capability apply" the same way for every
935
+ // capability; for pruning the answer is the effective mode. `mode()` stays
936
+ // because the pruning decision needs the three-valued answer, not the
937
+ // boolean.
938
+ serves: () => this.modeOf('prune') !== 'off' && this.#config.enabled,
939
+ clock: () => ({ now: () => this.#now() }),
940
+ mode: () => this.modeOf('prune'),
941
+ threshold: () => this.#pruneThreshold,
942
+ floor: () => ({
2019
943
  floorRatio: this.config.pruneFloorRatio,
2020
944
  headChars: this.config.pruneHeadChars,
2021
- tailChars: this.config.pruneTailChars,
2022
- locator: retention.locator
2023
- });
2024
- if (installed.text.length === 0 || installed.text.length >= text.length) {
2025
- // The plan said the form is smaller; the form that was really built must be
2026
- // too, or nothing is installed and nothing is saved.
2027
- this.#skip('no-reduction', {
2028
- capability: 'prune',
2029
- state,
2030
- agent: exec.agent,
2031
- detail: {
2032
- ...measured,
2033
- floored: installed.floored,
2034
- floorMissed: installed.floorMissed,
2035
- markerOmitted: installed.markerOmitted,
2036
- candidateChars: installed.text.length,
2037
- candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))
2038
- },
2039
- judgment
2040
- });
2041
- return downstream;
2042
- }
2043
- const replacement = this.#replaceText(effective, installed.text);
2044
- if (!replacement) {
2045
- this.#skip('no-text-block', {
945
+ tailChars: this.config.pruneTailChars
946
+ }),
947
+ now: () => this.#now(),
948
+ memoKey: () => state.sessionKey,
949
+ memoGet: (key) => this.#memoGetByKey(key),
950
+ memoSet: (key, entry) => this.#memoSetByKey(key, entry),
951
+ judge: async (raw) => {
952
+ // Both modes ask for the *real* candidate, measure-only. The service
953
+ // writes its own ledger entry first; whether the payload is installed is
954
+ // decided afterwards, by the floor.
955
+ const response = await this.#decide(() => this.#prune.prune(raw, {
956
+ intent: this.config.intent,
957
+ measureOnly: true,
958
+ pruneJudgeMinChars: this.config.pruneJudgeMinChars
959
+ }), (value) => value !== undefined,
960
+ // Prune is its own account of which path produced the text, so a
961
+ // request that was tried and failed is reported as such.
962
+ (value) => value.judgePath === 'fallback' || value.judgePath === 'local');
963
+ return {
964
+ processedOutput: response.processedOutput,
965
+ reductionPercentage: response.reductionPercentage,
966
+ shadow: response.shadow,
967
+ latencyMs: response.latencyMs,
968
+ diagnostics: pruneDiagnosticsOf(response)
969
+ };
970
+ },
971
+ // DSH's sink names a copy after the plugin record type, and the engine
972
+ // must predict that name or every install would be rebuilt.
973
+ locatorOf: (digest) => pruneLocator(digest),
974
+ hasRetention: () => this.#retain !== undefined,
975
+ retain: (request, session) => this.#retain?.(session, request),
976
+ session: () => sessionOf(exec.agent),
977
+ hasTextBlock: () => hasTextBlock(effective),
978
+ install: (installedText) => {
979
+ const replacement = this.#replaceText(effective, installedText);
980
+ if (!replacement)
981
+ return undefined;
982
+ return {
983
+ kind: 'accept',
984
+ content: replacement,
985
+ ...(downstream.additionalContexts && downstream.additionalContexts.length > 0
986
+ ? { additionalContexts: [...downstream.additionalContexts] }
987
+ : {})
988
+ };
989
+ },
990
+ describe: (facts) => this.#pruneFeedback(facts),
991
+ skip: (reason, detail, judgment) => this.#skip(reason, {
2046
992
  capability: 'prune',
2047
993
  state,
2048
994
  agent: exec.agent,
2049
- detail: {
2050
- ...measured,
2051
- floored: installed.floored,
2052
- floorMissed: installed.floorMissed,
2053
- markerOmitted: installed.markerOmitted,
2054
- candidateChars: installed.text.length,
2055
- candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))
2056
- },
2057
- judgment
2058
- });
2059
- return downstream;
2060
- }
2061
- // Only now is there a decision that really took effect, so only now is the
2062
- // saving recorded — against the text that is really about to enter the context.
2063
- const installedTokens = Math.max(0, Math.ceil(installed.text.length / 4));
2064
- plan.detail.floorApplied = installed.floored;
2065
- plan.detail.floorMissed = installed.floorMissed;
2066
- plan.detail.markerOmitted = installed.markerOmitted;
2067
- plan.detail.candidateChars = installed.text.length;
2068
- plan.feedback = this.#pruneFeedback(exec.name, originalTokens, installedTokens, {
2069
- floored: installed.floored,
2070
- floorMissed: installed.floorMissed,
2071
- markerOmitted: installed.markerOmitted,
2072
- locator: retention.locator,
2073
- keptSegments: diagnostics.keptSegments,
2074
- judgedSegments: diagnostics.judgedSegments
2075
- });
2076
- // Booked only here: a candidate that was not smaller, a replacement that could
2077
- // not be composed, and a retention that failed all returned above, so none of
2078
- // them consumed the turn's allowance for an action that never happened.
2079
- this.#bookAction(state);
2080
- this.#conclude(plan, true, exec.agent, {
2081
- originalTokens,
2082
- candidateTokens: installedTokens,
2083
- potentialSavedTokens: originalTokens - installedTokens,
2084
- actualSavedTokens: originalTokens - installedTokens
2085
- }, judgment, retention.locator);
2086
- // Retention is counted once per payload: a duplicate install reuses the copy
2087
- // that is already in the log, and the locator naming it never changes.
2088
- if (!this.#retained.includes(retention.locator)) {
2089
- this.#retained.push(retention.locator);
2090
- if (this.#retained.length > MAX_RECENT)
2091
- this.#retained.shift();
2092
- }
2093
- this.#retainedCopies += 1;
2094
- this.#memoSet(state, digest, {
2095
- text: installed.text,
2096
- originalChars: text.length,
2097
- prunedChars: installed.text.length,
2098
- tokensSaved: originalTokens - installedTokens,
2099
- floored: installed.floored,
2100
- floorMissed: installed.floorMissed,
2101
- markerOmitted: installed.markerOmitted,
2102
- locator: retention.locator,
2103
- diagnostics
2104
- });
2105
- return {
2106
- kind: 'accept',
2107
- content: replacement,
2108
- ...(downstream.additionalContexts && downstream.additionalContexts.length > 0
2109
- ? { additionalContexts: [...downstream.additionalContexts] }
2110
- : {})
2111
- };
2112
- }
2113
- /** Plan, and in active mode apply, the correction of one repeated failure. */
2114
- async #correctFailure(exec, result, downstream, state, signature, started) {
2115
- const capability = this.modeOf('gate');
2116
- if (capability === 'off')
2117
- return downstream;
2118
- if (downstream.kind === 'block')
2119
- return downstream;
2120
- const suspicion = suspicionOf(state.steps, {
2121
- repeatThreshold: this.config.repeatThreshold,
2122
- failureThreshold: this.config.failureThreshold,
2123
- window: this.config.windowSize,
2124
- signature
995
+ ...(Object.keys(detail).length === 0 ? {} : { detail: detail }),
996
+ ...(judgment === undefined ? {} : { judgment })
997
+ }),
998
+ chargeJudgment: (judgment, originalTokens) => this.#charge('prune', {
999
+ ...judgment,
1000
+ originalTokens: originalTokens ?? 0,
1001
+ candidateTokens: 0,
1002
+ potentialSavedTokens: 0,
1003
+ actualSavedTokens: 0,
1004
+ injectedTokens: 0
1005
+ }),
1006
+ conclude: (plan, applied, costs, judgment, locator) => this.#conclude(plan, applied, exec.agent, costs, judgment, locator),
1007
+ noteRetained: (locator) => this.#noteRetained(locator),
1008
+ passThrough: () => downstream
2125
1009
  });
2126
- if (!suspicion.suspicious || state.applied.has(`gate:${signature}`)) {
2127
- if (suspicion.suspicious) {
2128
- this.#skip('duplicate-intervention', { capability: 'gate', state, agent: exec.agent });
2129
- }
2130
- return downstream;
2131
- }
2132
- if (!this.#actionWithinBudget(state)) {
2133
- this.#skip('intervention-cap', { capability: 'gate', state, agent: exec.agent });
2134
- return downstream;
2135
- }
2136
- const agentId = agentKeyOf(exec.agent);
2137
- const verdict = await this.#judge(state, exec.signal);
2138
- const judgment = this.#judgmentCharge(verdict, started, this.#now());
2139
- if (!verdict.useful) {
2140
- this.#charge('gate', judgment);
2141
- this.#skip(verdict.skip ?? 'unconfirmed', {
2142
- capability: 'gate',
2143
- state,
2144
- agent: exec.agent,
2145
- judgment
2146
- });
2147
- return downstream;
2148
- }
2149
- const plan = {
2150
- capability: 'gate',
2151
- action: 'corrective-feedback',
2152
- reason: `${exec.name} failed ${suspicion.repeats} times; System 1 confirmed ${verdict.response.patternType ?? suspicion.pattern}`,
2153
- feedback: this.#failureFeedback(exec.name, this.#errorOf(result), suspicion, verdict.response),
2154
- detail: {
2155
- pattern: String(verdict.response.patternType ?? suspicion.pattern ?? 'unknown'),
2156
- confidence: verdict.response.confidence,
2157
- repeats: suspicion.repeats,
2158
- turn: state.turn,
2159
- step: state.step
2160
- }
2161
- };
2162
- const applied = capability === 'active';
2163
- state.applied.add(`gate:${signature}`);
2164
- this.#bookAction(state);
2165
- this.#conclude(plan, applied, exec.agent, { potentialSavedTokens: 0 }, judgment);
2166
- if (!applied)
2167
- return downstream;
2168
- return {
2169
- kind: 'block',
2170
- feedback: [{ type: 'text', text: plan.feedback }],
2171
- ...(downstream.additionalContexts && downstream.additionalContexts.length > 0
2172
- ? { additionalContexts: [...downstream.additionalContexts] }
2173
- : {})
2174
- };
2175
- }
2176
- // ── judgment, budgets, and memo ─────────────────────────────────────────────
2177
- /**
2178
- * Whether this turn still has room for one more planned action.
2179
- *
2180
- * This is the *action* ceiling, and it is deliberately not the judgment budget:
2181
- * a judgment is the question System 1 was asked, this is the number of things
2182
- * the run is allowed to do about the answer. Every capability draws on the same
2183
- * allowance, and both modes draw on it the same way — the plan observe measures
2184
- * is the action active would install, so an observe run that planned more than
2185
- * the ceiling would be measuring a turn that cannot exist.
2186
- *
2187
- * Asked before a judgment is bought, so a turn that is already full is refused
2188
- * for free.
2189
- * @param state - the deciding agent's state.
2190
- * @returns whether one more planned action fits this turn.
2191
- */
2192
- #actionWithinBudget(state) {
2193
- return state.interventions < this.config.maxInterventionsPerTurn;
1010
+ // No cast: the port's `Result` is this host's decision type, so the generic
1011
+ // carries it from `passThrough`/`install` all the way out.
1012
+ return outcome.result;
2194
1013
  }
2195
1014
  /**
2196
- * Book one planned action against the turn's shared allowance.
1015
+ * `tools/post-execute`: rewrite a result the run keeps failing to change.
2197
1016
  *
2198
- * Called at the one point where a plan becomes real: observe books the plan it
2199
- * records, active books the replacement its retention made installable. Never
2200
- * called earlier — a plan abandoned by a failed judgment, a failed retention, or
2201
- * a candidate that turned out not to be smaller must not consume the turn's
2202
- * allowance, or a turn would be spent on actions that never happened.
2203
- * @param state - the deciding agent's state.
2204
- */
2205
- #bookAction(state) {
2206
- state.interventions += 1;
2207
- }
2208
- /**
2209
- * Spend at most one System 1 stagnation judgment per agent and turn.
1017
+ * The *order* of this decision — the failure latch, the turn's allowance, the
1018
+ * judgment and its memo, the episode latch, the booking — is
1019
+ * `orchestrateCorrection`'s. What stays here is everything the shared layer
1020
+ * cannot know:
2210
1021
  *
2211
- * Every hook of one turn shares the verdict — the pre-execute refusal, the
2212
- * pre-step correction, and the failure correction all ask the same question
2213
- * about the same window, so asking it three times would be three times the cost
2214
- * for one answer.
2215
- */
2216
- async #judge(state, signal, steps = state.steps, goal) {
2217
- // The question is the trailing window plus the context it is asked in, so
2218
- // the answer is cached against both: the same episode is never judged twice,
2219
- // while a *different* episode or a different wait context in the same turn is
2220
- // a new question — and therefore subject to the turn's budget.
2221
- const key = `${goal ?? ''}\u0000${steps
2222
- .slice(-Math.max(1, this.config.repeatThreshold))
2223
- .map((step) => step.signature)
2224
- .join('|')}`;
2225
- const cached = state.verdictTurn === state.turn && state.verdictKey === key ? state.verdict : undefined;
2226
- if (cached) {
2227
- return {
2228
- useful: this.#useful(cached),
2229
- paid: false,
2230
- reused: true,
2231
- judgeTokens: 0,
2232
- localLatencyMs: 0,
2233
- remoteLatencyMs: 0,
2234
- response: cached
2235
- };
2236
- }
2237
- if (state.judgmentsCount >= this.config.maxJudgmentsPerTurn) {
2238
- return this.#noJudgment('judgment-turn-cap');
2239
- }
2240
- if (state.judgmentsSession >= this.config.maxJudgmentsPerSession) {
2241
- return this.#noJudgment('judgment-session-cap');
2242
- }
2243
- if (signal?.aborted)
2244
- return this.#noJudgment('aborted');
2245
- this.#spendJudgment(state);
2246
- const history = steps.map((step) => ({
2247
- tool: step.tool,
2248
- input: step.input,
2249
- ...(step.output ? { output: step.output } : {}),
2250
- ...(step.error ? { error: step.error } : {}),
2251
- timestamp: step.at
2252
- }));
2253
- const judgeTokens = history.reduce((sum, step) => sum + estimateTokens(`${step.tool}${step.input}${step.output ?? ''}${step.error ?? ''}`), 0);
2254
- const started = this.#now();
2255
- const response = await this.#stagnation.check(goal, history);
2256
- const remoteLatencyMs = Number.isFinite(response.latencyMs) ? response.latencyMs : 0;
2257
- state.verdict = response;
2258
- state.verdictTurn = state.turn;
2259
- state.verdictKey = key;
2260
- return {
2261
- useful: this.#useful(response),
2262
- paid: true,
2263
- reused: false,
2264
- judgeTokens,
2265
- localLatencyMs: Math.max(0, this.#now() - started - remoteLatencyMs),
2266
- remoteLatencyMs,
2267
- response
2268
- };
2269
- }
2270
- /**
2271
- * Charge one judgment against the turn's and the session's budget.
1022
+ * - **the window**: `state.steps`, recorded by this engine. It is handed over
1023
+ * *unfiltered*, unlike the stagnation windows: a failing poll is a failure
1024
+ * even though a wait is not progress, so `progressSteps` would be the wrong
1025
+ * rule on this path;
1026
+ * - **the strength of the action**: `apply` answers with a `block` carrying the
1027
+ * feedback, which replaces the result outright. That is this Host's way of
1028
+ * showing a correction; a command hook would carry the same text as context
1029
+ * next to the untouched result, and the shared layer may not pick for it;
1030
+ * - **the wording**: `describeCorrection` is the product text, and it is this
1031
+ * plugin's, not the core's — the same decision read by a different host
1032
+ * should still read naturally to that host's user.
2272
1033
  *
2273
- * Both budgets are spent at the one place a judgment is actually made, so a
2274
- * capability cannot buy its way around them by calling a service directly. The
2275
- * caller decides whether a refusal means "plan nothing" or "do not act"; what
2276
- * matters here is that the count is never overrun and that a shadowed
2277
- * application is charged like a real one — an observe run has to cost what the
2278
- * active run would cost, or its column would flatter it.
2279
- * @param state - the deciding agent's state.
2280
- * @returns `undefined` when the judgment was spent, else the skip reason.
1034
+ * @param exec - the call whose result failed.
1035
+ * @param result - the canonical outcome, for its error text.
1036
+ * @param downstream - what the rest of the waterfall decided for the result.
1037
+ * @param state - the deciding agent's bookkeeping.
1038
+ * @param signature - the identity of the failure episode.
1039
+ * @param started - clock reading at hook entry, for the latency split.
1040
+ * @returns the result the Host commits.
2281
1041
  */
2282
- #spendJudgment(state) {
2283
- if (state.judgmentsCount >= this.config.maxJudgmentsPerTurn)
2284
- return 'judgment-turn-cap';
2285
- if (state.judgmentsSession >= this.config.maxJudgmentsPerSession)
2286
- return 'judgment-session-cap';
2287
- state.judgmentsCount += 1;
2288
- state.judgmentsSession += 1;
2289
- return undefined;
2290
- }
2291
- /** The zero-cost verdict of a judgment that could not be spent. */
2292
- #noJudgment(skip) {
2293
- // Not a memo hit: nothing was reused, the budget simply refused to spend.
2294
- return {
2295
- useful: false,
2296
- paid: false,
2297
- reused: false,
2298
- judgeTokens: 0,
2299
- localLatencyMs: 0,
2300
- remoteLatencyMs: 0,
2301
- skip,
2302
- response: EMPTY_VERDICT
2303
- };
2304
- }
2305
- /** The charge of one judgment, so every judgment is billed exactly once. */
2306
- #judgmentCharge(verdict, started, finished) {
2307
- if (!verdict.paid) {
2308
- return { judgments: 0, memoHits: verdict.reused ? 1 : 0, localLatencyMs: 0, remoteLatencyMs: 0, judgeTokens: 0 };
2309
- }
2310
- return {
2311
- judgments: 1,
2312
- memoHits: 0,
2313
- localLatencyMs: Math.max(verdict.localLatencyMs, Math.max(0, finished - started - verdict.remoteLatencyMs)),
2314
- remoteLatencyMs: verdict.remoteLatencyMs,
2315
- judgeTokens: verdict.judgeTokens
1042
+ async #correctFailure(exec, result, downstream, state, signature, started) {
1043
+ const agentId = agentKeyOf(exec.agent);
1044
+ const error = this.#errorOf(result);
1045
+ const port = {
1046
+ policy: () => this.#config,
1047
+ budget: () => state,
1048
+ buy: async (step) => this.#decide(() => this.#stagnation.check(step.goal, [...step.history]), (value) => value !== undefined),
1049
+ clock: () => ({ now: () => this.#now() }),
1050
+ serves: () => this.#config.enabled,
1051
+ toolName: () => exec.name,
1052
+ error: () => error,
1053
+ // Deliberately the raw window, not the progress-only one: see the doc above.
1054
+ window: () => state.steps,
1055
+ signature: () => signature,
1056
+ suspicion: (steps) => suspicionOf(steps, {
1057
+ repeatThreshold: this.config.repeatThreshold,
1058
+ failureThreshold: this.config.failureThreshold,
1059
+ window: this.config.windowSize,
1060
+ signature
1061
+ }),
1062
+ alreadyCorrected: () => state.applied.has(`gate:${signature}`),
1063
+ latchCorrected: () => state.applied.add(`gate:${signature}`),
1064
+ passThrough: () => downstream,
1065
+ // This Host's strength for a correction: the result is replaced by the
1066
+ // feedback. `additionalContexts` the rest of the waterfall attached are
1067
+ // carried over, so somebody else's context is not lost to ours.
1068
+ apply: (feedback) => ({
1069
+ kind: 'block',
1070
+ feedback: [{ type: 'text', text: feedback }],
1071
+ ...(downstream.additionalContexts && downstream.additionalContexts.length > 0
1072
+ ? { additionalContexts: [...downstream.additionalContexts] }
1073
+ : {})
1074
+ }),
1075
+ describe: (facts) => describeCorrection(facts, { errorChars: 160, adviceChars: 240, totalChars: FEEDBACK_CHARS }),
1076
+ skip: (reason, charge) => this.#skip(reason, {
1077
+ capability: 'gate',
1078
+ state,
1079
+ agent: exec.agent,
1080
+ ...(charge === undefined ? {} : { judgment: charge })
1081
+ }),
1082
+ chargeJudgment: (charge) => this.#charge('gate', charge),
1083
+ conclude: (plan, applied, charge) => this.#conclude(plan, applied, exec.agent, { potentialSavedTokens: 0 }, charge)
2316
1084
  };
2317
- }
2318
- /** Whether a verdict justifies acting: stuck, confident, and about a pattern. */
2319
- #useful(response) {
2320
- return (response.isStuck === true &&
2321
- response.confidence >= this.config.minConfidence &&
2322
- (response.patternType ?? 'none') !== 'none');
1085
+ // `started` is kept in the signature because it is what the *hook* measured,
1086
+ // and the shared layer takes its own reading at the moment the judgment is
1087
+ // bought. Both read the same clock, so the latency this decision reports is
1088
+ // unchanged by the lift; the parameter stays so a later local-latency rule
1089
+ // can still see the hook's own entry time.
1090
+ void started;
1091
+ void agentId;
1092
+ const outcome = await orchestrateCorrection({ failed: true, blockedByDownstream: downstream.kind === 'block' }, port);
1093
+ return outcome.result;
2323
1094
  }
2324
1095
  // ── accounting and audit ───────────────────────────────────────────────────
2325
1096
  /**
@@ -2424,18 +1195,7 @@ export class InterventionEngine {
2424
1195
  #charge(capability, charge, plans = 0, applied = 0) {
2425
1196
  const mode = this.modeOf(capability) === 'active' ? 'active' : 'observe';
2426
1197
  for (const bucket of [this.#costs[mode], this.#byCapability[capability]]) {
2427
- bucket.plans += plans;
2428
- bucket.applied += applied;
2429
- bucket.judgments += charge.judgments ?? 0;
2430
- bucket.memoHits += charge.memoHits ?? 0;
2431
- bucket.localLatencyMs += charge.localLatencyMs ?? 0;
2432
- bucket.remoteLatencyMs += charge.remoteLatencyMs ?? 0;
2433
- bucket.judgeTokens += charge.judgeTokens ?? 0;
2434
- bucket.originalTokens += charge.originalTokens ?? 0;
2435
- bucket.candidateTokens += charge.candidateTokens ?? 0;
2436
- bucket.potentialSavedTokens += charge.potentialSavedTokens ?? 0;
2437
- bucket.actualSavedTokens += charge.actualSavedTokens ?? 0;
2438
- bucket.injectedTokens += charge.injectedTokens ?? 0;
1198
+ applyCharge(bucket, plans, applied, charge);
2439
1199
  }
2440
1200
  }
2441
1201
  /**
@@ -2654,7 +1414,8 @@ export class InterventionEngine {
2654
1414
  * @param outcome - the floor's decision and the judgment's segment counts.
2655
1415
  * @returns the note, clipped to the audit's text budget.
2656
1416
  */
2657
- #pruneFeedback(tool, originalTokens, candidateTokens, outcome) {
1417
+ #pruneFeedback(facts) {
1418
+ const { tool, originalTokens, candidateTokens, ...outcome } = facts;
2658
1419
  const kept = originalTokens === 0 ? 100 : Math.round((candidateTokens / originalTokens) * 100);
2659
1420
  const head = `Reflex reduced ${tool}: ${originalTokens} → ${candidateTokens} tokens (${kept}% kept). `;
2660
1421
  const keptSegments = outcome.keptSegments;
@@ -2688,9 +1449,23 @@ export class InterventionEngine {
2688
1449
  }
2689
1450
  return clip(`${head}${body}`, FEEDBACK_CHARS);
2690
1451
  }
2691
- /** The memoized reduction of one payload, when it is still remembered. */
2692
- #memoGet(state, digest) {
2693
- const key = `${state.sessionKey}:${digest}`;
1452
+ /**
1453
+ * Count one retained copy for the panel, once per payload.
1454
+ *
1455
+ * A duplicate install reuses the copy that is already in the log, so the
1456
+ * locator naming it never changes and the recent list keeps one entry.
1457
+ * @param locator - the locator the replacement published.
1458
+ */
1459
+ #noteRetained(locator) {
1460
+ if (!this.#retained.includes(locator)) {
1461
+ this.#retained.push(locator);
1462
+ if (this.#retained.length > MAX_RECENT)
1463
+ this.#retained.shift();
1464
+ }
1465
+ this.#retainedCopies += 1;
1466
+ }
1467
+ /** The memoized reduction under one already-namespaced key, when remembered. */
1468
+ #memoGetByKey(key) {
2694
1469
  const hit = this.#memo.get(key);
2695
1470
  if (!hit)
2696
1471
  return undefined;
@@ -2707,8 +1482,7 @@ export class InterventionEngine {
2707
1482
  * a later active decision re-plans that payload for real instead of installing a
2708
1483
  * cached fragment it never saw.
2709
1484
  */
2710
- #memoSet(state, digest, memo) {
2711
- const key = `${state.sessionKey}:${digest}`;
1485
+ #memoSetByKey(key, memo) {
2712
1486
  this.#memo.set(key, memo);
2713
1487
  if (this.#memo.size > MAX_MEMO) {
2714
1488
  const oldest = this.#memo.keys().next().value;
@@ -2756,13 +1530,6 @@ export class InterventionEngine {
2756
1530
  `confidence ${verdict.confidence.toFixed(2)}). Stop the loop and change strategy: ` +
2757
1531
  `${advice || 're-read the last failure, then either fix the cause or try a different tool.'}`, FEEDBACK_CHARS);
2758
1532
  }
2759
- /** The corrective feedback carried by a repeated failing result. */
2760
- #failureFeedback(tool, error, suspicion, verdict) {
2761
- const advice = clip((verdict.recommendedIntervention ?? '').replace(/\s+/g, ' ').trim(), 240);
2762
- return clip(`Reflex intervention: ${tool} failed ${suspicion.repeats} consecutive times with ${clip(error.replace(/\s+/g, ' ').trim(), 160)}. ` +
2763
- `System 1 confirms ${verdict.patternType ?? suspicion.pattern} (confidence ${verdict.confidence.toFixed(2)}). ` +
2764
- `This result is treated as a policy failure: change the command or the code before retrying. ${advice}`, FEEDBACK_CHARS);
2765
- }
2766
1533
  /** The objection steered into a turn that is closing on contradicted evidence. */
2767
1534
  #closingFeedback(contradicted) {
2768
1535
  return clip(`Reflex closing check: this turn is about to close while its own tool results carry failures that contradict what it claims ` +
@@ -2970,33 +1737,6 @@ function callSignature(exec) {
2970
1737
  function reductionPercentage(originalChars, prunedChars) {
2971
1738
  return originalChars === 0 ? 0 : Math.round(((originalChars - prunedChars) / originalChars) * 1000) / 10;
2972
1739
  }
2973
- /**
2974
- * The *candidate* sentences of one turn's assistant text.
2975
- *
2976
- * Deterministic and semantic-free on purpose: splitting, de-duplication, the
2977
- * length floor, and the last-{@link MAX_CLAIMS} bound are all the local work
2978
- * this module may do. Whether a candidate really claims completion is System
2979
- * One's answer — an English word list would miss 中文「全部通过」 and read
2980
- * `not complete` as the opposite, so there is none here any more.
2981
- *
2982
- * @param text - the turn's assistant text.
2983
- * @returns bounded, deduplicated candidates in their original order.
2984
- */
2985
- export function claimCandidates(text) {
2986
- const candidates = [];
2987
- const seen = new Set();
2988
- for (const raw of text.split(/(?<=[.!?。!?\n])/)) {
2989
- const sentence = raw.replace(/\s+/g, ' ').trim();
2990
- if (sentence.length < MIN_CLAIM_CHARS)
2991
- continue;
2992
- const statement = clip(sentence, 200);
2993
- if (seen.has(statement))
2994
- continue;
2995
- seen.add(statement);
2996
- candidates.push(statement);
2997
- }
2998
- return candidates.length > MAX_CLAIMS ? candidates.slice(candidates.length - MAX_CLAIMS) : candidates;
2999
- }
3000
1740
  // Re-exported so a Host attaching the session log does not have to import the
3001
1741
  // audit module directly.
3002
1742
  export { appendInterventionRecord };