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
@@ -0,0 +1,250 @@
1
+ /**
2
+ * The shared orchestration of the closing check.
3
+ *
4
+ * The fourth and last lift: {@link ./orchestrate} owns when a result is reduced,
5
+ * {@link ./orchestrate-stagnation} owns when a call is refused and when a step is
6
+ * corrected, {@link ./orchestrate-correction} owns what happens to a result that
7
+ * failed — and this one owns what happens when a turn is about to *close* while
8
+ * its own words claim success the evidence does not support.
9
+ *
10
+ * ```
11
+ * agent/turn-stopping
12
+ * → off, or the host is not serving this capability → nothing at all
13
+ * → the turn said nothing, or no evidence is a failure → not suspicious, nothing at all
14
+ * → no candidate sentence → nothing at all
15
+ * → already latched for this turn → duplicate-intervention
16
+ * → the turn's action allowance is spent → intervention-cap
17
+ * → the caller's signal is aborted → nothing at all
18
+ * → assemble the evidence; truncation is NOTED and the decision continues
19
+ * → buy the classification (turn/session budgets inside)
20
+ * → the classifier could not answer → closing-claim-unavailable (fail open, locally)
21
+ * → nothing really claims completion → closing-no-claim (and the charge is kept)
22
+ * → buy the verification (same judgment, second request)
23
+ * → nothing contradicted → closing-undecided / closing-unconfirmed / closing-evidence-consistent
24
+ * → latch the turn, book the action, conclude
25
+ * → [the host steers the objection into the turn, in active mode only]
26
+ * → a failure anywhere after that → planning-error (fail open)
27
+ * ```
28
+ *
29
+ * ## What is shared and what is not
30
+ *
31
+ * Shared here: the order above, every skip reason, the budget rules, the two
32
+ * per-turn latches, the shape of the audit detail, and the decision that active
33
+ * mode asks its host to steer.
34
+ *
35
+ * *Not* shared here: the act of steering (that is `HostClosingPort#steer`), the
36
+ * wording the model reads (`#describe`), the storage of the evidence counters
37
+ * (`#noteEvidence`), and the accumulation of the turn's own words — a host that
38
+ * reads them from a stream and a host that reads them from a transcript both hand
39
+ * over the same string.
40
+ *
41
+ * ## The two judgments are one decision
42
+ *
43
+ * The closing check buys **two** requests from one capability: a classification
44
+ * of the turn's candidate sentences, and a verification of the claims that
45
+ * classification accepted. They are one logical judgment — the classification
46
+ * decides *whether* anything is worth verifying — so both are charged against the
47
+ * single slot the turn budget allowed, and both are billed as one
48
+ * {@link ClosingJudgment}. That fold is why this port states its two *purchases*
49
+ * ({@link HostClosingPort#classify} and {@link HostClosingPort#verify}) and never
50
+ * the transport behind them: a caller holding the service would have to
51
+ * re-implement the purchase, the memo, the latency split and the billing, and the
52
+ * one-charge rule is only stateable where the charge is built. It stays here.
53
+ *
54
+ * ## The skip that does not return
55
+ *
56
+ * Every skip in the other three modules ends the decision. `evidence-truncated`
57
+ * does not: the evidence was assembled with some of it dropped, the amount is
58
+ * reported, and the judgment proceeds on what survived. This module therefore
59
+ * distinguishes a *note* (`#note`, which records) from a *refusal* (`#refuse`,
60
+ * which records and returns). Collapsing the two would either stop the closing
61
+ * check whenever evidence is large, or lose the fact that it was truncated.
62
+ *
63
+ * ## A verdict that could not decide is not a contradiction
64
+ *
65
+ * `escalate` means the backend could not answer — an unavailable service degrades
66
+ * exactly this way. Steering a turn on an undecided verdict would turn a backend
67
+ * failure into a model-visible objection, so only `contradicted` results steer;
68
+ * `escalate` gets its own reason (`closing-undecided`) precisely so a run can tell
69
+ * "the evidence was fine" from "nobody looked".
70
+ *
71
+ * @module core/orchestrate-closing
72
+ */
73
+ import { claimCandidates } from './closing.js';
74
+ import { assembleEvidence } from './evidence.js';
75
+ import { actionWithinBudget, bookAction, spendJudgment } from './policy.js';
76
+ import { clip, estimateTokens } from './text.js';
77
+ /** The capability every decision in this module belongs to. */
78
+ export const CLOSING_CAPABILITY = 'closing';
79
+ /** The audit action an objection is recorded under. */
80
+ export const CLOSING_ACTION = 'steer-closing';
81
+ /**
82
+ * The two latches this decision keeps, both keyed by turn rather than by identity.
83
+ *
84
+ * The other capabilities latch by *signature* — one repeated call is one episode.
85
+ * A closing check has no such identity: the episode is the turn itself, so the
86
+ * key is `closing:turn:<n>` and it is the host's storage that has to keep it.
87
+ */
88
+ export const CLOSING_LATCH = {
89
+ /** The turn was already objected to (or observed) — never twice per turn. */
90
+ applied: (turn) => `closing:turn:${turn}`,
91
+ /** The memo namespace of the verification request, so a replay is free. */
92
+ verdictKey: (agent, turn) => `reflex-closing:${agent}:${turn}`
93
+ };
94
+ /** Opinion of one contradicted statement, clipped for the wording and the record. */
95
+ const STATEMENT_CHARS = 160;
96
+ /** How much of the assembled evidence the classifier is shown as context. */
97
+ const CLASSIFY_CONTEXT_CHARS = 600;
98
+ /**
99
+ * Decide whether the turn that is closing contradicts its own evidence, and tell
100
+ * the host what to do about it.
101
+ *
102
+ * The position is an *input of this decision*, not a port accessor and not a
103
+ * counter. The turn here is the boundary being closed, which can be a turn no
104
+ * step has recorded yet — a turn that said something and admitted no step — so it
105
+ * cannot be read off the running counters. `step` is the step the engine last
106
+ * recorded, which is the same number the audit detail has always quoted.
107
+ *
108
+ * @param invocation - where in the run this check is being made.
109
+ * @param port - everything the shared layer cannot know by itself.
110
+ * @returns what the check decided, and the message to steer when it applied.
111
+ */
112
+ export async function orchestrateClosing(invocation, port) {
113
+ const mode = port.mode();
114
+ const policy = port.policy();
115
+ // The three "nothing at all" exits are deliberately silent: a turn with nothing
116
+ // to say, or nothing to say it about, is not a refused decision and would fill
117
+ // the skip histogram with entries that describe every turn ever run.
118
+ if (mode === 'off' || !port.serves())
119
+ return silent();
120
+ if (!port.evidenceSuspect())
121
+ return silent();
122
+ const claimsText = port.claims();
123
+ if (claimsText.length === 0)
124
+ return silent();
125
+ const candidates = claimCandidates(claimsText);
126
+ if (candidates.length === 0)
127
+ return silent();
128
+ const state = port.budget();
129
+ // One place in the run, quoted by the latch key, the memo namespace, the audit
130
+ // detail and the wording alike.
131
+ const { turn, step } = invocation.position;
132
+ const skips = [];
133
+ const refuse = (reason, charge) => {
134
+ if (charge !== undefined)
135
+ port.chargeJudgment(charge);
136
+ port.skip(reason, charge);
137
+ skips.push(reason);
138
+ return { action: 'pass-through', skip: reason, skips: [...skips], applied: false };
139
+ };
140
+ // A note records a reason without ending the decision: `evidence-truncated` is
141
+ // the one branch that reports something and keeps going.
142
+ const note = (reason) => {
143
+ port.skip(reason);
144
+ skips.push(reason);
145
+ };
146
+ if (port.alreadyObjected())
147
+ return refuse('duplicate-intervention');
148
+ if (!actionWithinBudget(state, policy))
149
+ return refuse('intervention-cap');
150
+ if (port.aborted())
151
+ return silent();
152
+ const assembled = assembleEvidence(port.evidence(), port.evidenceBudget());
153
+ port.noteEvidence({ retainedChars: assembled.retainedChars, truncatedChars: assembled.truncatedChars });
154
+ if (assembled.truncatedChars > 0)
155
+ note('evidence-truncated');
156
+ const classificationSkip = spendJudgment(state, policy);
157
+ if (classificationSkip !== undefined)
158
+ return refuse(classificationSkip);
159
+ const started = port.clock().now();
160
+ let classification;
161
+ try {
162
+ classification = await port.classify({
163
+ statements: candidates,
164
+ context: assembled.text.slice(0, CLASSIFY_CONTEXT_CHARS)
165
+ });
166
+ }
167
+ catch {
168
+ // FAIL-OPEN, locally: an unavailable classifier must not become a model-visible
169
+ // objection, and it must never fall back to a word list. The spent slot is not
170
+ // refunded — the judgment really was bought — but nothing is billed, because
171
+ // no answer was received.
172
+ return refuse('closing-claim-unavailable');
173
+ }
174
+ const floor = port.claimMinConfidence();
175
+ const claims = classification.results
176
+ .filter((item) => item.isClaim && item.confidence >= floor)
177
+ .map((item) => ({ statement: item.statement }));
178
+ const classifyTokens = candidates.reduce((sum, statement) => sum + estimateTokens(statement), 0);
179
+ const classificationCharge = {
180
+ judgments: 1,
181
+ memoHits: 0,
182
+ localLatencyMs: Math.max(0, port.clock().now() - started - classification.latencyMs),
183
+ remoteLatencyMs: classification.latencyMs,
184
+ judgeTokens: classifyTokens
185
+ };
186
+ if (claims.length === 0) {
187
+ // Paying for the classification and then finding nothing to verify is a
188
+ // complete answer, not a failure: the charge is recorded with the skip.
189
+ return refuse('closing-no-claim', classificationCharge);
190
+ }
191
+ const verdict = await port.verify(claims, assembled.text, {
192
+ latchCacheKey: CLOSING_LATCH.verdictKey(port.agentId(), turn)
193
+ });
194
+ const judgeTokens = classifyTokens + claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(assembled.text));
195
+ const judgment = {
196
+ judgments: 1,
197
+ memoHits: 0,
198
+ localLatencyMs: Math.max(0, port.clock().now() - started - verdict.latencyMs - classification.latencyMs),
199
+ remoteLatencyMs: classification.latencyMs + verdict.latencyMs,
200
+ judgeTokens
201
+ };
202
+ const contradicted = verdict.results
203
+ .filter((item) => item.outcome === 'contradicted')
204
+ .map((item) => clip(item.statement, STATEMENT_CHARS));
205
+ const undecided = verdict.results.filter((item) => item.outcome === 'escalate').length;
206
+ if (contradicted.length === 0) {
207
+ return refuse(undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed', judgment);
208
+ }
209
+ const plan = {
210
+ capability: CLOSING_CAPABILITY,
211
+ action: CLOSING_ACTION,
212
+ reason: `closing evidence contradicts ${contradicted.length} completion claim(s)`,
213
+ feedback: port.describe({ contradicted, turn }),
214
+ detail: { confidence: verdict.results[0]?.confidence, turn, step }
215
+ };
216
+ const applies = mode === 'active';
217
+ // Latched in both modes, for the same reason as the other capabilities: the
218
+ // episode is consumed once, and only the *steering* is gated on the mode. An
219
+ // observe run that did not latch would buy the same judgment again at the next
220
+ // boundary and describe a run nobody could reproduce.
221
+ port.latchObjected();
222
+ bookAction(state);
223
+ port.conclude(plan, applies, judgment);
224
+ if (!applies)
225
+ return { action: 'objected', skips: [...skips], plan, applied: false };
226
+ port.steer(plan.feedback);
227
+ return { action: 'objected', skips: [...skips], plan, applied: true, message: plan.feedback };
228
+ }
229
+ /** The outcome of a check that decided nothing and has nothing to report. */
230
+ function silent() {
231
+ return { action: 'pass-through', skips: [], applied: false };
232
+ }
233
+ /**
234
+ * The objection's wording, in the default form.
235
+ *
236
+ * Exported because a host that shows the text to the same audience may keep it
237
+ * verbatim; a host that words it differently supplies its own through the port.
238
+ * The statement clipping is the shared part: a contradicted claim is quoted at
239
+ * 160 characters with its whitespace collapsed, so a multi-line claim can never
240
+ * make the objection unbounded.
241
+ * @param facts - what the objection is built from.
242
+ * @param limit - the total character budget.
243
+ * @returns the text handed to the model.
244
+ */
245
+ export function describeClosing(facts, limit) {
246
+ return clip(`Reflex closing check: this turn is about to close while its own tool results carry failures that contradict what it claims ` +
247
+ `(${facts.contradicted.map((item) => `"${item}"`).join('; ')}). Before concluding, either fix the failing evidence or state the failure ` +
248
+ `plainly instead of the completion claim.`, limit);
249
+ }
250
+ //# sourceMappingURL=orchestrate-closing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestrate-closing.js","sourceRoot":"","sources":["../../../../src/vendor/harness-reflex/core/orchestrate-closing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuEG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAsB,MAAM,eAAe,CAAC;AAErE,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,IAAI,EAAE,cAAc,EA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AAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1B,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC;AAChG,CAAC;AAED,6EAA6E;AAC7E,SAAS,MAAM;IACb,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC/D,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,eAAe,CAAC,KAA2B,EAAE,KAAa;IACxE,OAAO,IAAI,CACT,6HAA6H;QAC3H,IAAI,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,6EAA6E;QACzI,0CAA0C,EAC5C,KAAK,CACN,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The shared orchestration of the closing check.\n *\n * The fourth and last lift: {@link ./orchestrate} owns when a result is reduced,\n * {@link ./orchestrate-stagnation} owns when a call is refused and when a step is\n * corrected, {@link ./orchestrate-correction} owns what happens to a result that\n * failed — and this one owns what happens when a turn is about to *close* while\n * its own words claim success the evidence does not support.\n *\n * ```\n * agent/turn-stopping\n * → off, or the host is not serving this capability → nothing at all\n * → the turn said nothing, or no evidence is a failure → not suspicious, nothing at all\n * → no candidate sentence → nothing at all\n * → already latched for this turn → duplicate-intervention\n * → the turn's action allowance is spent → intervention-cap\n * → the caller's signal is aborted → nothing at all\n * → assemble the evidence; truncation is NOTED and the decision continues\n * → buy the classification (turn/session budgets inside)\n * → the classifier could not answer → closing-claim-unavailable (fail open, locally)\n * → nothing really claims completion → closing-no-claim (and the charge is kept)\n * → buy the verification (same judgment, second request)\n * → nothing contradicted → closing-undecided / closing-unconfirmed / closing-evidence-consistent\n * → latch the turn, book the action, conclude\n * → [the host steers the objection into the turn, in active mode only]\n * → a failure anywhere after that → planning-error (fail open)\n * ```\n *\n * ## What is shared and what is not\n *\n * Shared here: the order above, every skip reason, the budget rules, the two\n * per-turn latches, the shape of the audit detail, and the decision that active\n * mode asks its host to steer.\n *\n * *Not* shared here: the act of steering (that is `HostClosingPort#steer`), the\n * wording the model reads (`#describe`), the storage of the evidence counters\n * (`#noteEvidence`), and the accumulation of the turn's own words — a host that\n * reads them from a stream and a host that reads them from a transcript both hand\n * over the same string.\n *\n * ## The two judgments are one decision\n *\n * The closing check buys **two** requests from one capability: a classification\n * of the turn's candidate sentences, and a verification of the claims that\n * classification accepted. They are one logical judgment — the classification\n * decides *whether* anything is worth verifying — so both are charged against the\n * single slot the turn budget allowed, and both are billed as one\n * {@link ClosingJudgment}. That fold is why this port states its two *purchases*\n * ({@link HostClosingPort#classify} and {@link HostClosingPort#verify}) and never\n * the transport behind them: a caller holding the service would have to\n * re-implement the purchase, the memo, the latency split and the billing, and the\n * one-charge rule is only stateable where the charge is built. It stays here.\n *\n * ## The skip that does not return\n *\n * Every skip in the other three modules ends the decision. `evidence-truncated`\n * does not: the evidence was assembled with some of it dropped, the amount is\n * reported, and the judgment proceeds on what survived. This module therefore\n * distinguishes a *note* (`#note`, which records) from a *refusal* (`#refuse`,\n * which records and returns). Collapsing the two would either stop the closing\n * check whenever evidence is large, or lose the fact that it was truncated.\n *\n * ## A verdict that could not decide is not a contradiction\n *\n * `escalate` means the backend could not answer — an unavailable service degrades\n * exactly this way. Steering a turn on an undecided verdict would turn a backend\n * failure into a model-visible objection, so only `contradicted` results steer;\n * `escalate` gets its own reason (`closing-undecided`) precisely so a run can tell\n * \"the evidence was fine\" from \"nobody looked\".\n *\n * @module core/orchestrate-closing\n */\n\nimport { claimCandidates } from './closing.js';\nimport { assembleEvidence, type EvidenceEntry } from './evidence.js';\nimport type { HostBillingPort, HostDecisionPort, JudgmentCost, JudgmentPosition } from './orchestrate-host.js';\nimport { actionWithinBudget, bookAction, spendJudgment } from './policy.js';\nimport { clip, estimateTokens } from './text.js';\n\n/** The capability every decision in this module belongs to. */\nexport const CLOSING_CAPABILITY = 'closing' as const;\n\n/** The audit action an objection is recorded under. */\nexport const CLOSING_ACTION = 'steer-closing' as const;\n\n/**\n * The two latches this decision keeps, both keyed by turn rather than by identity.\n *\n * The other capabilities latch by *signature* — one repeated call is one episode.\n * A closing check has no such identity: the episode is the turn itself, so the\n * key is `closing:turn:<n>` and it is the host's storage that has to keep it.\n */\nexport const CLOSING_LATCH = {\n /** The turn was already objected to (or observed) — never twice per turn. */\n applied: (turn: number): string => `closing:turn:${turn}`,\n /** The memo namespace of the verification request, so a replay is free. */\n verdictKey: (agent: string, turn: number): string => `reflex-closing:${agent}:${turn}`\n} as const;\n\n/** One planned objection, as the host records it. */\nexport interface ClosingPlanRecord {\n readonly capability: typeof CLOSING_CAPABILITY;\n readonly action: typeof CLOSING_ACTION;\n readonly reason: string;\n feedback: string;\n readonly detail: Record<string, unknown>;\n}\n\n/**\n * The judgment one closing check rode on.\n *\n * Both requests are folded into one charge on purpose: the turn budget bought one\n * slot, and a reader of the account must not see two slots spent for one decision.\n * `localLatencyMs` is the wait the two requests cost in this process; the two\n * remote times are summed because the model was asked two questions.\n */\nexport interface ClosingJudgment extends JudgmentCost {}\n\n/** What one closing check turned out to be. */\nexport type ClosingAction = 'objected' | 'pass-through';\n\n/** What one orchestrated closing check produced. */\nexport interface ClosingOutcome {\n /** What the capability was in force: a decision is only made when this is not `off`. */\n readonly action: ClosingAction;\n /** The reason the check did nothing, when it did nothing. */\n readonly skip?: string;\n /** Every skip reason this one check reported, in order (normally 0 or 1). */\n readonly skips: readonly string[];\n /** The objection, once the decision is to make one. */\n readonly plan?: ClosingPlanRecord;\n /** Whether the objection was really steered (active mode only). */\n readonly applied: boolean;\n /** The message to hand the model, when the host steers in active mode. */\n readonly message?: string;\n}\n\n/** What the classification half answered. */\nexport interface ClaimClassificationLike {\n readonly results: readonly { readonly statement: string; readonly isClaim: boolean; readonly confidence: number }[];\n readonly latencyMs: number;\n}\n\n/** What the verification half answered. */\nexport interface ClosingVerdictLike {\n readonly passed: boolean;\n readonly results: readonly { readonly statement: string; readonly outcome: string; readonly confidence: number }[];\n readonly latencyMs: number;\n}\n\n/** What the objection is built from, for the host's wording. */\nexport interface ClosingFeedbackFacts {\n /** The contradicted statements, already clipped for quoting. */\n readonly contradicted: readonly string[];\n /** The turn that is closing. */\n readonly turn: number;\n}\n\n/** Everything the shared layer cannot know by itself. */\nexport interface HostClosingPort extends HostDecisionPort, HostBillingPort<ClosingJudgment, ClosingPlanRecord> {\n /** The effective mode of the `closing` capability. */\n mode(): 'off' | 'observe' | 'active';\n /**\n * The turn's own words, as the stream carried them.\n *\n * The host accumulates them (`agent/assistant-stream` in DSH); the shared layer\n * only asks for the string. An empty string means the turn said nothing, which\n * is one of the four deterministic reasons nothing is bought.\n */\n claims(): string;\n /**\n * Whether at least one retained evidence entry looks like a failure.\n *\n * A host computes this from its own reading of its results; the shared layer\n * needs only the boolean, because *which* result failed is what the judgment\n * reads, not what the trigger reads.\n */\n evidenceSuspect(): boolean;\n /** The evidence entries retained for this turn. */\n evidence(): readonly EvidenceEntry[];\n /** The evidence-assembly budget in force. */\n evidenceBudget(): number;\n /** Whether the caller's signal is already aborted (a cancelling turn). */\n aborted(): boolean;\n /** Whether this turn was already objected to (or observed) — the per-turn latch. */\n alreadyObjected(): boolean;\n /** Latch this turn as objected to. */\n latchObjected(): void;\n /** The identity the verification memo is namespaced by. */\n agentId(): string;\n /** The classification half of the one judgment. */\n classify(request: { readonly statements: readonly string[]; readonly context: string }): Promise<ClaimClassificationLike>;\n /** The verification half of the same judgment. */\n verify(\n claims: readonly { readonly statement: string }[],\n evidence: string,\n options: { readonly latchCacheKey: string }\n ): Promise<ClosingVerdictLike>;\n /** The confidence floor a classified sentence must clear to be a claim. */\n claimMinConfidence(): number;\n /** Word the objection the model reads. */\n describe(facts: ClosingFeedbackFacts): string;\n /** Hand the objection to the model. Only called in active mode. */\n steer(message: string): void;\n /** Record the evidence counters, which are engine-level rather than per-agent. */\n noteEvidence(stats: { readonly retainedChars: number; readonly truncatedChars: number }): void;\n}\n\n/** Opinion of one contradicted statement, clipped for the wording and the record. */\nconst STATEMENT_CHARS = 160;\n\n/** How much of the assembled evidence the classifier is shown as context. */\nconst CLASSIFY_CONTEXT_CHARS = 600;\n\n/**\n * Decide whether the turn that is closing contradicts its own evidence, and tell\n * the host what to do about it.\n *\n * The position is an *input of this decision*, not a port accessor and not a\n * counter. The turn here is the boundary being closed, which can be a turn no\n * step has recorded yet — a turn that said something and admitted no step — so it\n * cannot be read off the running counters. `step` is the step the engine last\n * recorded, which is the same number the audit detail has always quoted.\n *\n * @param invocation - where in the run this check is being made.\n * @param port - everything the shared layer cannot know by itself.\n * @returns what the check decided, and the message to steer when it applied.\n */\nexport async function orchestrateClosing(\n invocation: { readonly position: JudgmentPosition },\n port: HostClosingPort\n): Promise<ClosingOutcome> {\n const mode = port.mode();\n const policy = port.policy();\n // The three \"nothing at all\" exits are deliberately silent: a turn with nothing\n // to say, or nothing to say it about, is not a refused decision and would fill\n // the skip histogram with entries that describe every turn ever run.\n if (mode === 'off' || !port.serves()) return silent();\n if (!port.evidenceSuspect()) return silent();\n const claimsText = port.claims();\n if (claimsText.length === 0) return silent();\n const candidates = claimCandidates(claimsText);\n if (candidates.length === 0) return silent();\n\n const state = port.budget();\n // One place in the run, quoted by the latch key, the memo namespace, the audit\n // detail and the wording alike.\n const { turn, step } = invocation.position;\n const skips: string[] = [];\n const refuse = (reason: string, charge?: ClosingJudgment): ClosingOutcome => {\n if (charge !== undefined) port.chargeJudgment(charge);\n port.skip(reason, charge);\n skips.push(reason);\n return { action: 'pass-through', skip: reason, skips: [...skips], applied: false };\n };\n // A note records a reason without ending the decision: `evidence-truncated` is\n // the one branch that reports something and keeps going.\n const note = (reason: string): void => {\n port.skip(reason);\n skips.push(reason);\n };\n\n if (port.alreadyObjected()) return refuse('duplicate-intervention');\n if (!actionWithinBudget(state, policy)) return refuse('intervention-cap');\n if (port.aborted()) return silent();\n\n const assembled = assembleEvidence(port.evidence(), port.evidenceBudget());\n port.noteEvidence({ retainedChars: assembled.retainedChars, truncatedChars: assembled.truncatedChars });\n if (assembled.truncatedChars > 0) note('evidence-truncated');\n\n const classificationSkip = spendJudgment(state, policy);\n if (classificationSkip !== undefined) return refuse(classificationSkip);\n\n const started = port.clock().now();\n let classification: ClaimClassificationLike;\n try {\n classification = await port.classify({\n statements: candidates,\n context: assembled.text.slice(0, CLASSIFY_CONTEXT_CHARS)\n });\n } catch {\n // FAIL-OPEN, locally: an unavailable classifier must not become a model-visible\n // objection, and it must never fall back to a word list. The spent slot is not\n // refunded — the judgment really was bought — but nothing is billed, because\n // no answer was received.\n return refuse('closing-claim-unavailable');\n }\n const floor = port.claimMinConfidence();\n const claims = classification.results\n .filter((item) => item.isClaim && item.confidence >= floor)\n .map((item) => ({ statement: item.statement }));\n const classifyTokens = candidates.reduce((sum, statement) => sum + estimateTokens(statement), 0);\n const classificationCharge: ClosingJudgment = {\n judgments: 1,\n memoHits: 0,\n localLatencyMs: Math.max(0, port.clock().now() - started - classification.latencyMs),\n remoteLatencyMs: classification.latencyMs,\n judgeTokens: classifyTokens\n };\n if (claims.length === 0) {\n // Paying for the classification and then finding nothing to verify is a\n // complete answer, not a failure: the charge is recorded with the skip.\n return refuse('closing-no-claim', classificationCharge);\n }\n\n const verdict = await port.verify(claims, assembled.text, {\n latchCacheKey: CLOSING_LATCH.verdictKey(port.agentId(), turn)\n });\n const judgeTokens =\n classifyTokens + claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(assembled.text));\n const judgment: ClosingJudgment = {\n judgments: 1,\n memoHits: 0,\n localLatencyMs: Math.max(0, port.clock().now() - started - verdict.latencyMs - classification.latencyMs),\n remoteLatencyMs: classification.latencyMs + verdict.latencyMs,\n judgeTokens\n };\n const contradicted = verdict.results\n .filter((item) => item.outcome === 'contradicted')\n .map((item) => clip(item.statement, STATEMENT_CHARS));\n const undecided = verdict.results.filter((item) => item.outcome === 'escalate').length;\n if (contradicted.length === 0) {\n return refuse(undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed', judgment);\n }\n\n const plan: ClosingPlanRecord = {\n capability: CLOSING_CAPABILITY,\n action: CLOSING_ACTION,\n reason: `closing evidence contradicts ${contradicted.length} completion claim(s)`,\n feedback: port.describe({ contradicted, turn }),\n detail: { confidence: verdict.results[0]?.confidence, turn, step }\n };\n const applies = mode === 'active';\n // Latched in both modes, for the same reason as the other capabilities: the\n // episode is consumed once, and only the *steering* is gated on the mode. An\n // observe run that did not latch would buy the same judgment again at the next\n // boundary and describe a run nobody could reproduce.\n port.latchObjected();\n bookAction(state);\n port.conclude(plan, applies, judgment);\n if (!applies) return { action: 'objected', skips: [...skips], plan, applied: false };\n port.steer(plan.feedback);\n return { action: 'objected', skips: [...skips], plan, applied: true, message: plan.feedback };\n}\n\n/** The outcome of a check that decided nothing and has nothing to report. */\nfunction silent(): ClosingOutcome {\n return { action: 'pass-through', skips: [], applied: false };\n}\n\n/**\n * The objection's wording, in the default form.\n *\n * Exported because a host that shows the text to the same audience may keep it\n * verbatim; a host that words it differently supplies its own through the port.\n * The statement clipping is the shared part: a contradicted claim is quoted at\n * 160 characters with its whitespace collapsed, so a multi-line claim can never\n * make the objection unbounded.\n * @param facts - what the objection is built from.\n * @param limit - the total character budget.\n * @returns the text handed to the model.\n */\nexport function describeClosing(facts: ClosingFeedbackFacts, limit: number): string {\n return clip(\n `Reflex closing check: this turn is about to close while its own tool results carry failures that contradict what it claims ` +\n `(${facts.contradicted.map((item) => `\"${item}\"`).join('; ')}). Before concluding, either fix the failing evidence or state the failure ` +\n `plainly instead of the completion claim.`,\n limit\n );\n}\n\n"]}
@@ -0,0 +1,209 @@
1
+ /**
2
+ * The shared orchestration of the failure-correction decision.
3
+ *
4
+ * The third of the three lifts: {@link ./orchestrate} owns when a result is
5
+ * reduced, {@link ./orchestrate-stagnation} owns when a call is refused and when
6
+ * a step is corrected, and this one owns what happens to a result that *failed* —
7
+ * the run is retrying an operation that keeps failing, and what the model is
8
+ * about to read is the failure again rather than the reason it keeps failing.
9
+ *
10
+ * ```
11
+ * agent/turn-stopping / tools/pre-execute (not this module)
12
+ *
13
+ * tools/post-execute
14
+ * downstream first, always
15
+ * → off / own tool / the result of a call this layer refused → hand it back
16
+ * → [the host records the step and reports the result failed]
17
+ * → not a failure → this decision does not apply
18
+ * → downstream blocked the result → hand it back
19
+ * → the cheap trigger (the trailing failing run) → not suspicious → hand it back
20
+ * → already corrected this episode → duplicate-intervention
21
+ * → the turn's action allowance is spent → intervention-cap
22
+ * → buy a judgment (memo first, budgets inside)
23
+ * → not useful → charge it, record why, hand it back
24
+ * → latch the episode, book the action, conclude
25
+ * → rewrite the result *only* in active mode
26
+ * ```
27
+ *
28
+ * ## What is shared and what is not
29
+ *
30
+ * Shared here: the order above, every skip reason, the budget rules
31
+ * (`actionWithinBudget`, `bookAction`, the judgment memo), the latch, the shape
32
+ * of the audit detail, and the *decision* that an active mode rewrites the result.
33
+ *
34
+ * *Not* shared here: whether a result counts as a failure (the host's own reading
35
+ * of `isError`, a structured exit status, or an exit marker in the text), the
36
+ * window it is measured on and what a legitimate wait removes from it (the host
37
+ * records steps and hands over the value — {@link progressSteps} is applied by
38
+ * the caller, and the DSH host deliberately does *not* apply it here, because a
39
+ * failing poll is still a failure), the wording the model reads, and the concrete
40
+ * shape of a rewritten result.
41
+ *
42
+ * ## The strength of the action is the host's, the decision is not
43
+ *
44
+ * A correction has no single strength. The DSH engine answers with
45
+ * `kind: 'block'` and a feedback list, which replaces the result outright; a
46
+ * command hook answers with `additionalContext` next to the result it did not
47
+ * touch. The shared layer therefore decides *whether* the correction applies and
48
+ * *what it says*, and leaves *how strongly* to be expressed to {@link
49
+ * CorrectionPort#apply}: an observation of the same decision is exactly the plan
50
+ * that reaches the log in both modes, and installing it is the only thing the
51
+ * mode gates.
52
+ *
53
+ * For the same reason this module states no permission-monotonicity rule. A
54
+ * refusal is a permission and may not be added to anything stricter than an
55
+ * allow — that rule lives in one place, {@link mayAddDecision}. A correction is
56
+ * text shown to the model about a result that already happened; it grants and
57
+ * denies nothing, so there is no decision it could weaken. The one decision it
58
+ * must not overwrite is a result the rest of the waterfall *blocked*, and that is
59
+ * an early return rather than a rule about kinds.
60
+ *
61
+ * ## Why the host supplies the window, not a store
62
+ *
63
+ * The same reason as the other two modules: the DSH engine keeps its window in
64
+ * the agent's own bookkeeping and hands the shared layer a value, while a host
65
+ * that derives it from a persisted log hands over a different value. Neither has
66
+ * to teach the shared layer how it stores anything; the only thing the shared
67
+ * layer mutates is the counters it is given, through {@link BudgetState}.
68
+ *
69
+ * @module core/orchestrate-correction
70
+ */
71
+ import type { StagnationCheckResponse } from '../backend/types.js';
72
+ import { type ObservedStep, type StagnationSuspicion, type VerdictMemoState } from './judge.js';
73
+ import type { HostBillingPort, HostDecisionPort, HostJudgmentPort } from './orchestrate-host.js';
74
+ /** The capability every decision in this module belongs to. */
75
+ export declare const CORRECTION_CAPABILITY: "gate";
76
+ /** The audit action a correction is recorded under. */
77
+ export declare const CORRECTION_ACTION: "corrective-feedback";
78
+ /** What one orchestrated decision turned out to be. */
79
+ export type CorrectionAction = 'corrected' | 'pass-through';
80
+ /** The judgment cost of one decision, as the host bills it. */
81
+ export interface JudgedCharge {
82
+ readonly judgments: number;
83
+ readonly memoHits: number;
84
+ readonly localLatencyMs: number;
85
+ readonly remoteLatencyMs: number;
86
+ readonly judgeTokens: number;
87
+ }
88
+ /** One planned correction, as the host records it. */
89
+ export interface CorrectionPlanRecord {
90
+ readonly capability: typeof CORRECTION_CAPABILITY;
91
+ readonly action: typeof CORRECTION_ACTION;
92
+ readonly reason: string;
93
+ feedback: string;
94
+ readonly detail: Record<string, unknown>;
95
+ }
96
+ /** What one correction was built from. */
97
+ export interface CorrectionFeedbackFacts {
98
+ /** Name of the call that failed. */
99
+ readonly tool: string;
100
+ /** The failure text the host reads off the result, for quoting. */
101
+ readonly error: string;
102
+ /** The cheap-path trigger. */
103
+ readonly suspicion: StagnationSuspicion;
104
+ /** What System 1 answered. */
105
+ readonly verdict: StagnationCheckResponse;
106
+ }
107
+ /**
108
+ * The counters one correction spends from and books against.
109
+ *
110
+ * The verdict cache is part of the budget state because a cached answer is what
111
+ * makes a second question in the same turn free: this path shares that cache with
112
+ * the stagnation capability, so it reads it through here rather than keeping a
113
+ * second copy. The place in the run (`turn`, `step`) and the counters both come
114
+ * from the judge's state, so a correction adds no field of its own to either.
115
+ */
116
+ export type CorrectionState = VerdictMemoState;
117
+ /**
118
+ * Everything the shared layer cannot know by itself.
119
+ *
120
+ * {@link HostDecisionPort} answers the part every capability asks — policy,
121
+ * counters, clock, switch, and the three billing channels — so this interface
122
+ * states only what a *correction* additionally needs.
123
+ */
124
+ export interface HostCorrectionPort<Result> extends HostDecisionPort<CorrectionState>, HostBillingPort<JudgedCharge, CorrectionPlanRecord>, HostJudgmentPort<StagnationCheckResponse> {
125
+ /** Name of the call whose result is being decided. */
126
+ toolName(): string;
127
+ /** The failure text, as the model would read it. */
128
+ error(): string;
129
+ /**
130
+ * The window the trigger is measured on.
131
+ *
132
+ * The host's, deliberately: it is the one value the three capabilities can
133
+ * disagree about, and the disagreement is real — a failing poll is a failure
134
+ * even though a wait is not progress.
135
+ */
136
+ window(): readonly ObservedStep[];
137
+ /** The identity this decision is about. */
138
+ signature(): string;
139
+ /**
140
+ * The cheap trigger over one window.
141
+ *
142
+ * `PolicySnapshot` carries the repetition threshold, the confidence floor and
143
+ * the judgment budgets — the numbers the *budget* rules are stated in — but the
144
+ * failure threshold and the window size are trigger parameters, and the host
145
+ * owns their values.
146
+ */
147
+ suspicion(steps: readonly ObservedStep[]): StagnationSuspicion;
148
+ /** Whether this identity was already corrected on this turn. */
149
+ alreadyCorrected(): boolean;
150
+ /** Latch this identity as corrected. */
151
+ latchCorrected(): void;
152
+ /** The result to hand back when nothing is done. */
153
+ passThrough(): Result;
154
+ /**
155
+ * The result to hand back when the correction applies.
156
+ *
157
+ * How strong this is — a replacement, an added context, or nothing at all
158
+ * because the host is only observing — is the host's to decide, and it is why
159
+ * this is a callback rather than a kind the shared layer picks.
160
+ */
161
+ apply(feedback: string): Result;
162
+ /** Word the correction handed to the model. */
163
+ describe(facts: CorrectionFeedbackFacts): string;
164
+ }
165
+ /** The outcome of one orchestrated decision. */
166
+ export interface CorrectionOutcome<Result> {
167
+ /** What the host should return to its caller. */
168
+ readonly result: Result;
169
+ /** What the decision was. */
170
+ readonly action: CorrectionAction;
171
+ /** The skip reason, when the decision refused to correct. */
172
+ readonly skip?: string;
173
+ }
174
+ /**
175
+ * `tools/post-execute`: rewrite a result the run keeps failing to change.
176
+ *
177
+ * The host calls this **after** its own `next()`, and hands over what that
178
+ * returned: a result the rest of the waterfall blocked is already unreadable, so
179
+ * rewriting it would be inventing a surface nobody asked for.
180
+ *
181
+ * @param invocation - the downstream decision, the signal, and the failure facts.
182
+ * @param port - everything that is the host's to answer.
183
+ * @returns the result the host commits.
184
+ */
185
+ export declare function orchestrateCorrection<Result>(invocation: {
186
+ /** Whether the result is one this layer reads as a failure. */
187
+ readonly failed: boolean;
188
+ /** Whether the rest of the waterfall blocked the result outright. */
189
+ readonly blockedByDownstream: boolean;
190
+ /** The result's abort signal, if it has one. */
191
+ readonly signal?: AbortSignal;
192
+ }, port: HostCorrectionPort<Result>): Promise<CorrectionOutcome<Result>>;
193
+ /**
194
+ * The correction's wording, in the default form.
195
+ *
196
+ * Exported because a host that shows the text to the same audience may keep it
197
+ * verbatim; a host that words it differently supplies its own through the port.
198
+ * The two clippings are the shared part: an error is quoted at 160 characters and
199
+ * the advice at 240, both with whitespace collapsed, so a multi-line stack can
200
+ * never make the correction unbounded.
201
+ * @param facts - what the correction is built from.
202
+ * @param limits - the two budget lengths.
203
+ * @returns the text handed to the model.
204
+ */
205
+ export declare function describeCorrection(facts: CorrectionFeedbackFacts, limits: {
206
+ readonly errorChars: number;
207
+ readonly adviceChars: number;
208
+ readonly totalChars: number;
209
+ }): string;
@@ -0,0 +1,141 @@
1
+ import { judgmentCharge, runJudgment } from './judge.js';
2
+ import { actionWithinBudget, bookAction, modeOf } from './policy.js';
3
+ import { clip } from './text.js';
4
+ /** The capability every decision in this module belongs to. */
5
+ export const CORRECTION_CAPABILITY = 'gate';
6
+ /** The audit action a correction is recorded under. */
7
+ export const CORRECTION_ACTION = 'corrective-feedback';
8
+ /**
9
+ * The charge of one judgment, through the core's own billing rule.
10
+ * @param outcome - the judgment's outcome.
11
+ * @param started - clock reading at hook entry.
12
+ * @param now - clock reading now.
13
+ * @returns the charge the host records.
14
+ */
15
+ function chargeOf(outcome, started, now) {
16
+ return judgmentCharge(outcome, started, now);
17
+ }
18
+ /**
19
+ * The detail every correction record carries.
20
+ *
21
+ * Kept identical to the correction this module replaced, so an audit trail
22
+ * written before and after the lift reads the same: a reader comparing two
23
+ * sessions must not be able to tell which engine produced which.
24
+ * @param suspicion - the cheap-path trigger.
25
+ * @param verdict - what System 1 answered.
26
+ * @param turn - the deciding turn.
27
+ * @param step - the deciding step.
28
+ * @returns the audit fields.
29
+ */
30
+ function detailOf(suspicion, verdict, turn, step) {
31
+ return {
32
+ pattern: String(verdict.patternType ?? suspicion.pattern ?? 'unknown'),
33
+ confidence: verdict.confidence,
34
+ repeats: suspicion.repeats,
35
+ turn,
36
+ step
37
+ };
38
+ }
39
+ /**
40
+ * `tools/post-execute`: rewrite a result the run keeps failing to change.
41
+ *
42
+ * The host calls this **after** its own `next()`, and hands over what that
43
+ * returned: a result the rest of the waterfall blocked is already unreadable, so
44
+ * rewriting it would be inventing a surface nobody asked for.
45
+ *
46
+ * @param invocation - the downstream decision, the signal, and the failure facts.
47
+ * @param port - everything that is the host's to answer.
48
+ * @returns the result the host commits.
49
+ */
50
+ export async function orchestrateCorrection(invocation, port) {
51
+ const passThrough = (skip) => ({
52
+ result: port.passThrough(),
53
+ action: 'pass-through',
54
+ ...(skip === undefined ? {} : { skip })
55
+ });
56
+ const mode = modeOf(port.policy(), CORRECTION_CAPABILITY);
57
+ if (mode === 'off' || !port.serves())
58
+ return passThrough();
59
+ if (!invocation.failed)
60
+ return passThrough();
61
+ // A result the rest of the waterfall blocked never reaches the model, so there
62
+ // is nothing here to correct. Asked first: it is the cheapest refusal and it
63
+ // must not be able to spend a judgment.
64
+ if (invocation.blockedByDownstream)
65
+ return passThrough();
66
+ const signature = port.signature();
67
+ const suspicion = port.suspicion(port.window());
68
+ if (!suspicion.suspicious)
69
+ return passThrough();
70
+ // The latch is asked in the same breath as the trigger, and only reports when
71
+ // the episode was real: a correction that never happened is not a duplicate of
72
+ // anything, and a record claiming it was would misdescribe the turn.
73
+ if (port.alreadyCorrected()) {
74
+ port.skip('duplicate-intervention');
75
+ return passThrough('duplicate-intervention');
76
+ }
77
+ if (!actionWithinBudget(port.budget(), port.policy())) {
78
+ port.skip('intervention-cap');
79
+ return passThrough('intervention-cap');
80
+ }
81
+ const policy = port.policy();
82
+ const started = port.clock().now();
83
+ const outcome = await runJudgment({
84
+ state: port.budget(),
85
+ policy,
86
+ buy: (step) => port.buy(step),
87
+ clock: port.clock(),
88
+ steps: port.window(),
89
+ ...(invocation.signal === undefined ? {} : { signal: invocation.signal })
90
+ });
91
+ const charge = chargeOf(outcome, started, port.clock().now());
92
+ if (!outcome.useful) {
93
+ // A budget/abort skip keeps its own reason. The judgment really ran, so it is
94
+ // charged rather than hidden — an abandoned paid plan is still a cost.
95
+ port.chargeJudgment(charge);
96
+ const skip = outcome.skip ?? 'unconfirmed';
97
+ port.skip(skip, charge);
98
+ return passThrough(skip);
99
+ }
100
+ const facts = {
101
+ tool: port.toolName(),
102
+ error: port.error(),
103
+ suspicion,
104
+ verdict: outcome.response
105
+ };
106
+ const plan = {
107
+ capability: CORRECTION_CAPABILITY,
108
+ action: CORRECTION_ACTION,
109
+ reason: `${port.toolName()} failed ${suspicion.repeats} times; System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern}`,
110
+ feedback: port.describe(facts),
111
+ detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)
112
+ };
113
+ const applies = mode === 'active';
114
+ // The latch is mode-independent on purpose. Observe has to consume the same
115
+ // episode — one correction per failure episode, one charge against the turn's
116
+ // cap — or its accounting would describe a run nobody could reproduce; the
117
+ // model-visible rewrite is the only thing the mode gates.
118
+ port.latchCorrected();
119
+ bookAction(port.budget());
120
+ port.conclude(plan, applies, charge);
121
+ return applies ? { result: port.apply(plan.feedback), action: 'corrected' } : passThrough();
122
+ }
123
+ /**
124
+ * The correction's wording, in the default form.
125
+ *
126
+ * Exported because a host that shows the text to the same audience may keep it
127
+ * verbatim; a host that words it differently supplies its own through the port.
128
+ * The two clippings are the shared part: an error is quoted at 160 characters and
129
+ * the advice at 240, both with whitespace collapsed, so a multi-line stack can
130
+ * never make the correction unbounded.
131
+ * @param facts - what the correction is built from.
132
+ * @param limits - the two budget lengths.
133
+ * @returns the text handed to the model.
134
+ */
135
+ export function describeCorrection(facts, limits) {
136
+ const advice = clip((facts.verdict.recommendedIntervention ?? '').replace(/\s+/g, ' ').trim(), limits.adviceChars);
137
+ return clip(`Reflex intervention: ${facts.tool} failed ${facts.suspicion.repeats} consecutive times with ${clip(facts.error.replace(/\s+/g, ' ').trim(), limits.errorChars)}. ` +
138
+ `System 1 confirms ${facts.verdict.patternType ?? facts.suspicion.pattern} (confidence ${facts.verdict.confidence.toFixed(2)}). ` +
139
+ `This result is treated as a policy failure: change the command or the code before retrying. ${advice}`, limits.totalChars);
140
+ }
141
+ //# sourceMappingURL=orchestrate-correction.js.map