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.
- package/README.md +20 -6
- package/client.js +3511 -185
- package/dist/attribution.d.ts +266 -0
- package/dist/attribution.js +238 -0
- package/dist/attribution.js.map +1 -0
- package/dist/bridge.d.ts +311 -13
- package/dist/bridge.js +714 -42
- package/dist/bridge.js.map +1 -1
- package/dist/client-bundle.js +4 -1
- package/dist/client-bundle.js.map +1 -1
- package/dist/command.js +10 -0
- package/dist/command.js.map +1 -1
- package/dist/config.d.ts +530 -22
- package/dist/config.js +808 -27
- package/dist/config.js.map +1 -1
- package/dist/delegation-dispatch.d.ts +132 -0
- package/dist/delegation-dispatch.js +186 -0
- package/dist/delegation-dispatch.js.map +1 -0
- package/dist/delegation-health.d.ts +131 -0
- package/dist/delegation-health.js +97 -0
- package/dist/delegation-health.js.map +1 -0
- package/dist/delegation.d.ts +148 -0
- package/dist/delegation.js +186 -0
- package/dist/delegation.js.map +1 -0
- package/dist/effort-delegation.d.ts +144 -0
- package/dist/effort-delegation.js +280 -0
- package/dist/effort-delegation.js.map +1 -0
- package/dist/effort.d.ts +141 -0
- package/dist/effort.js +251 -9
- package/dist/effort.js.map +1 -1
- package/dist/host-patch.d.ts +156 -0
- package/dist/host-patch.js +534 -0
- package/dist/host-patch.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.js +99 -7
- package/dist/index.js.map +1 -1
- package/dist/interventions.d.ts +98 -373
- package/dist/interventions.js +442 -1702
- package/dist/interventions.js.map +1 -1
- package/dist/panel-api.d.ts +328 -4
- package/dist/panel-api.js +322 -15
- package/dist/panel-api.js.map +1 -1
- package/dist/panel-mount.d.ts +81 -22
- package/dist/panel-mount.js +228 -7
- package/dist/panel-mount.js.map +1 -1
- package/dist/routing.d.ts +23 -18
- package/dist/routing.js +471 -153
- package/dist/routing.js.map +1 -1
- package/dist/session-audit.d.ts +70 -0
- package/dist/session-audit.js +73 -0
- package/dist/session-audit.js.map +1 -1
- package/dist/systemone-probe.d.ts +114 -0
- package/dist/systemone-probe.js +383 -0
- package/dist/systemone-probe.js.map +1 -0
- package/dist/testing.d.ts +212 -7
- package/dist/testing.js +333 -27
- package/dist/testing.js.map +1 -1
- package/dist/tools.d.ts +109 -3
- package/dist/tools.js +103 -4
- package/dist/tools.js.map +1 -1
- package/dist/unconfigured-backend.d.ts +72 -0
- package/dist/unconfigured-backend.js +94 -0
- package/dist/unconfigured-backend.js.map +1 -0
- package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
- package/dist/vendor/harness-reflex/backend/factory.js +18 -3
- package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
- package/dist/vendor/harness-reflex/backend/jev.js +11 -4
- package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
- package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
- package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
- package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
- package/dist/vendor/harness-reflex/core/closing.js +111 -0
- package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
- package/dist/vendor/harness-reflex/core/evidence.js +209 -0
- package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
- package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
- package/dist/vendor/harness-reflex/core/judge.js +251 -0
- package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
- package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
- package/dist/vendor/harness-reflex/core/policy.js +102 -0
- package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
- package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
- package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
- package/dist/vendor/harness-reflex/core/text.js +66 -0
- package/dist/vendor/harness-reflex/core/text.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
- package/dist/vendor/harness-reflex/ports/audit.js +11 -0
- package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/clock.js +11 -0
- package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
- package/dist/vendor/harness-reflex/ports/decision.js +2 -0
- package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/index.js +2 -0
- package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
- package/dist/vendor/harness-reflex/ports/log.js +12 -0
- package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
- package/dist/vendor/harness-reflex/ports/state.js +13 -0
- package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
- package/package.json +25 -13
package/dist/interventions.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
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
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
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
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
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.
|
|
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
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
this.#
|
|
1537
|
-
this.#
|
|
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
|
-
|
|
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
|
-
|
|
1559
|
-
//
|
|
1560
|
-
//
|
|
1561
|
-
//
|
|
1562
|
-
//
|
|
1563
|
-
|
|
1564
|
-
|
|
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
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
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
|
-
|
|
1592
|
-
|
|
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
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
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:
|
|
1641
|
-
})
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
//
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1711
|
-
//
|
|
1712
|
-
//
|
|
1713
|
-
|
|
1714
|
-
|
|
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
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
//
|
|
1788
|
-
//
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
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
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
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
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
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
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
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
|
-
*
|
|
1015
|
+
* `tools/post-execute`: rewrite a result the run keeps failing to change.
|
|
2197
1016
|
*
|
|
2198
|
-
*
|
|
2199
|
-
*
|
|
2200
|
-
*
|
|
2201
|
-
*
|
|
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
|
-
*
|
|
2212
|
-
*
|
|
2213
|
-
*
|
|
2214
|
-
*
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
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
|
-
*
|
|
2274
|
-
*
|
|
2275
|
-
*
|
|
2276
|
-
*
|
|
2277
|
-
*
|
|
2278
|
-
*
|
|
2279
|
-
* @
|
|
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
|
-
#
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
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
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
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
|
|
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(
|
|
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
|
-
/**
|
|
2692
|
-
|
|
2693
|
-
|
|
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
|
-
#
|
|
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 };
|