harness-reflex 0.0.0-stage → 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/CHANGELOG.md +20 -0
- package/README.md +266 -2
- package/USER_GUIDE.md +639 -0
- package/dist/adapters/agy.d.ts +8 -0
- package/dist/adapters/agy.js +80 -0
- package/dist/adapters/agy.js.map +1 -0
- package/dist/adapters/claude.d.ts +13 -0
- package/dist/adapters/claude.js +46 -0
- package/dist/adapters/claude.js.map +1 -0
- package/dist/adapters/codex.d.ts +139 -0
- package/dist/adapters/codex.js +368 -0
- package/dist/adapters/codex.js.map +1 -0
- package/dist/backend/defaults.d.ts +31 -0
- package/dist/backend/defaults.js +32 -0
- package/dist/backend/defaults.js.map +1 -0
- package/dist/backend/factory.d.ts +11 -0
- package/dist/backend/factory.js +40 -0
- package/dist/backend/factory.js.map +1 -0
- package/dist/backend/jev.d.ts +524 -0
- package/dist/backend/jev.js +1486 -0
- package/dist/backend/jev.js.map +1 -0
- package/dist/backend/mock.d.ts +26 -0
- package/dist/backend/mock.js +320 -0
- package/dist/backend/mock.js.map +1 -0
- package/dist/backend/route-prompt.d.ts +37 -0
- package/dist/backend/route-prompt.js +42 -0
- package/dist/backend/route-prompt.js.map +1 -0
- package/dist/backend/simple-jev.d.ts +35 -0
- package/dist/backend/simple-jev.js +273 -0
- package/dist/backend/simple-jev.js.map +1 -0
- package/dist/backend/types.d.ts +270 -0
- package/dist/backend/types.js +5 -0
- package/dist/backend/types.js.map +1 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +278 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/core/calibrate.d.ts +56 -0
- package/dist/core/calibrate.js +144 -0
- package/dist/core/calibrate.js.map +1 -0
- package/dist/core/closing.d.ts +90 -0
- package/dist/core/closing.js +111 -0
- package/dist/core/closing.js.map +1 -0
- package/dist/core/evidence.d.ts +119 -0
- package/dist/core/evidence.js +209 -0
- package/dist/core/evidence.js.map +1 -0
- package/dist/core/gate.d.ts +25 -0
- package/dist/core/gate.js +114 -0
- package/dist/core/gate.js.map +1 -0
- package/dist/core/judge.d.ts +221 -0
- package/dist/core/judge.js +251 -0
- package/dist/core/judge.js.map +1 -0
- package/dist/core/ledger.d.ts +67 -0
- package/dist/core/ledger.js +173 -0
- package/dist/core/ledger.js.map +1 -0
- package/dist/core/orchestrate-closing.d.ts +237 -0
- package/dist/core/orchestrate-closing.js +250 -0
- package/dist/core/orchestrate-closing.js.map +1 -0
- package/dist/core/orchestrate-correction.d.ts +209 -0
- package/dist/core/orchestrate-correction.js +141 -0
- package/dist/core/orchestrate-correction.js.map +1 -0
- package/dist/core/orchestrate-host.d.ts +225 -0
- package/dist/core/orchestrate-host.js +80 -0
- package/dist/core/orchestrate-host.js.map +1 -0
- package/dist/core/orchestrate-stagnation.d.ts +259 -0
- package/dist/core/orchestrate-stagnation.js +270 -0
- package/dist/core/orchestrate-stagnation.js.map +1 -0
- package/dist/core/orchestrate.d.ts +357 -0
- package/dist/core/orchestrate.js +418 -0
- package/dist/core/orchestrate.js.map +1 -0
- package/dist/core/policy.d.ts +122 -0
- package/dist/core/policy.js +102 -0
- package/dist/core/policy.js.map +1 -0
- package/dist/core/prune-plan.d.ts +141 -0
- package/dist/core/prune-plan.js +390 -0
- package/dist/core/prune-plan.js.map +1 -0
- package/dist/core/prune.d.ts +30 -0
- package/dist/core/prune.js +73 -0
- package/dist/core/prune.js.map +1 -0
- package/dist/core/route.d.ts +35 -0
- package/dist/core/route.js +39 -0
- package/dist/core/route.js.map +1 -0
- package/dist/core/score.d.ts +40 -0
- package/dist/core/score.js +49 -0
- package/dist/core/score.js.map +1 -0
- package/dist/core/screen.d.ts +22 -0
- package/dist/core/screen.js +117 -0
- package/dist/core/screen.js.map +1 -0
- package/dist/core/stagnation.d.ts +23 -0
- package/dist/core/stagnation.js +93 -0
- package/dist/core/stagnation.js.map +1 -0
- package/dist/core/text.d.ts +36 -0
- package/dist/core/text.js +66 -0
- package/dist/core/text.js.map +1 -0
- package/dist/hook/cli.d.ts +9 -0
- package/dist/hook/cli.js +52 -0
- package/dist/hook/cli.js.map +1 -0
- package/dist/hook/contract.d.ts +125 -0
- package/dist/hook/contract.js +159 -0
- package/dist/hook/contract.js.map +1 -0
- package/dist/hook/decision.d.ts +97 -0
- package/dist/hook/decision.js +955 -0
- package/dist/hook/decision.js.map +1 -0
- package/dist/hook/memory-store.d.ts +81 -0
- package/dist/hook/memory-store.js +157 -0
- package/dist/hook/memory-store.js.map +1 -0
- package/dist/hook/payload.d.ts +55 -0
- package/dist/hook/payload.js +129 -0
- package/dist/hook/payload.js.map +1 -0
- package/dist/hook/run.d.ts +48 -0
- package/dist/hook/run.js +218 -0
- package/dist/hook/run.js.map +1 -0
- package/dist/hook/store-port.d.ts +72 -0
- package/dist/hook/store-port.js +2 -0
- package/dist/hook/store-port.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/server.d.ts +12 -0
- package/dist/mcp/server.js +368 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/ports/audit.d.ts +18 -0
- package/dist/ports/audit.js +11 -0
- package/dist/ports/audit.js.map +1 -0
- package/dist/ports/clock.d.ts +14 -0
- package/dist/ports/clock.js +11 -0
- package/dist/ports/clock.js.map +1 -0
- package/dist/ports/decision.d.ts +75 -0
- package/dist/ports/decision.js +2 -0
- package/dist/ports/decision.js.map +1 -0
- package/dist/ports/index.d.ts +14 -0
- package/dist/ports/index.js +2 -0
- package/dist/ports/index.js.map +1 -0
- package/dist/ports/log.d.ts +22 -0
- package/dist/ports/log.js +12 -0
- package/dist/ports/log.js.map +1 -0
- package/dist/ports/state.d.ts +46 -0
- package/dist/ports/state.js +13 -0
- package/dist/ports/state.js.map +1 -0
- package/dist/state/clock.d.ts +40 -0
- package/dist/state/clock.js +43 -0
- package/dist/state/clock.js.map +1 -0
- package/dist/state/file-store.d.ts +340 -0
- package/dist/state/file-store.js +849 -0
- package/dist/state/file-store.js.map +1 -0
- package/dist/state/paths.d.ts +41 -0
- package/dist/state/paths.js +73 -0
- package/dist/state/paths.js.map +1 -0
- package/docs/USER_GUIDE.en.md +721 -0
- package/docs/claude-code.md +281 -0
- package/docs/design/v0.2.0-harness-plugins.md +381 -0
- package/docs/design/v0.3.0-orchestration-unification.md +580 -0
- package/docs/dsh-plugin.md +578 -0
- package/docs/reflex-ui-regression-2026-10-20.md +34 -0
- package/docs/release-checklist-v0.1.0.md +315 -0
- package/docs/release-handbook-porting-notes.md +106 -0
- package/docs/release-handbook.md +393 -0
- package/docs/release-notes-v0.1.0.md +63 -0
- package/docs/release-notes-v0.3.0.md +152 -0
- package/docs/research/claude-code-harness.md +607 -0
- package/docs/research/pi-harness.md +621 -0
- package/experiments/data/calibration_sample.json +14 -0
- package/experiments/index.ts +29 -0
- package/experiments/runner.ts +156 -0
- package/package.json +82 -4
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { judgmentCharge, runJudgment } from './judge.js';
|
|
2
|
+
import { actionWithinBudget, bookAction, modeOf } from './policy.js';
|
|
3
|
+
/** The capability every decision in this module belongs to. */
|
|
4
|
+
export const STAGNATION_CAPABILITY = 'stagnation';
|
|
5
|
+
/**
|
|
6
|
+
* The window a stagnation trigger and its judgment are measured on.
|
|
7
|
+
*
|
|
8
|
+
* A wait query is not progress the run can be repeating: an identically repeated
|
|
9
|
+
* status/result query of the same background job is the sanctioned way to wait,
|
|
10
|
+
* so those steps are dropped before the repetition, failure and oscillation
|
|
11
|
+
* triggers read the window. Genuine calls on either side of a wait stay adjacent
|
|
12
|
+
* instead of being separated by it, which keeps a real loop visible while a run
|
|
13
|
+
* is waiting.
|
|
14
|
+
* @param steps - observed steps, oldest first.
|
|
15
|
+
* @returns the steps that count as progress.
|
|
16
|
+
*/
|
|
17
|
+
export function progressSteps(steps) {
|
|
18
|
+
return steps.some((step) => step.wait === true) ? steps.filter((step) => step.wait !== true) : steps;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Whether an action may be added on top of the decision the rest of the
|
|
22
|
+
* waterfall already made.
|
|
23
|
+
*
|
|
24
|
+
* This is the permission-monotonicity rule, in one place: a `deny` may be added
|
|
25
|
+
* only to an `allow`. An approval in flight, a denial carrying its own structured
|
|
26
|
+
* error identity, or a cancellation is information the Host attached, and
|
|
27
|
+
* overwriting any of it would drop that information or relax the decision.
|
|
28
|
+
* @param downstreamKind - the kind of the downstream decision.
|
|
29
|
+
* @returns whether the shared layer may add a refusal.
|
|
30
|
+
*/
|
|
31
|
+
export function mayAddDecision(downstreamKind) {
|
|
32
|
+
return downstreamKind === 'allow';
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The trigger for a repetition of a *wait-shaped* call.
|
|
36
|
+
*
|
|
37
|
+
* The host's tool list only decides that this repetition is worth asking about;
|
|
38
|
+
* it does not pass or refuse anything by itself.
|
|
39
|
+
* @param shape - the wait shape the host recognised.
|
|
40
|
+
* @param repeats - how many times the identity already occurred.
|
|
41
|
+
* @returns the promoted trigger.
|
|
42
|
+
*/
|
|
43
|
+
export function waitTrigger(shape, repeats) {
|
|
44
|
+
return {
|
|
45
|
+
suspicious: true,
|
|
46
|
+
pattern: 'repetition',
|
|
47
|
+
note: `wait-suspect ${shape} repeated ${repeats}x`,
|
|
48
|
+
repeats
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The charge of one judgment, through the core's own billing rule.
|
|
53
|
+
* @param outcome - the judgment's outcome.
|
|
54
|
+
* @param started - clock reading at hook entry.
|
|
55
|
+
* @param now - clock reading now.
|
|
56
|
+
* @returns the charge the host records.
|
|
57
|
+
*/
|
|
58
|
+
function chargeOf(outcome, started, now) {
|
|
59
|
+
return judgmentCharge(outcome, started, now);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The detail every stagnation record carries.
|
|
63
|
+
* @param suspicion - the cheap-path trigger.
|
|
64
|
+
* @param verdict - what System 1 answered.
|
|
65
|
+
* @param state - the deciding state, for turn and step.
|
|
66
|
+
* @param step - the step the decision belongs to.
|
|
67
|
+
* @returns the audit fields.
|
|
68
|
+
*/
|
|
69
|
+
function detailOf(suspicion, verdict, turn, step) {
|
|
70
|
+
return {
|
|
71
|
+
pattern: String(verdict.patternType ?? suspicion.pattern ?? 'unknown'),
|
|
72
|
+
confidence: verdict.confidence,
|
|
73
|
+
repeats: suspicion.repeats,
|
|
74
|
+
turn,
|
|
75
|
+
step
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* `tools/pre-execute`: refuse a call the run is repeating.
|
|
80
|
+
*
|
|
81
|
+
* The host calls this **after** its own `next()`, and hands over what that
|
|
82
|
+
* returned: the downstream decision is the first fact the decision is about, and
|
|
83
|
+
* a refusal may only ever be added to an allow.
|
|
84
|
+
*
|
|
85
|
+
* @param invocation - the downstream decision, the signal, and the window facts.
|
|
86
|
+
* @param port - everything that is the host's to answer.
|
|
87
|
+
* @returns the decision the Host dispatches on.
|
|
88
|
+
*/
|
|
89
|
+
export async function orchestrateStagnationPre(invocation, port) {
|
|
90
|
+
const { signal } = invocation;
|
|
91
|
+
const passThrough = () => ({ result: port.passThrough(), action: 'pass-through' });
|
|
92
|
+
const mode = modeOf(port.policy(), STAGNATION_CAPABILITY);
|
|
93
|
+
if (mode === 'off' || !port.serves())
|
|
94
|
+
return passThrough();
|
|
95
|
+
if (signal?.aborted === true)
|
|
96
|
+
return passThrough();
|
|
97
|
+
const policy = port.policy();
|
|
98
|
+
const pending = port.pendingStep();
|
|
99
|
+
// The call about to run is part of its own window: three identical calls are a
|
|
100
|
+
// repetition at the moment the third one is proposed, and the judgment has to
|
|
101
|
+
// see all three.
|
|
102
|
+
const allWindow = [...port.window(), pending];
|
|
103
|
+
const window = progressSteps(allWindow);
|
|
104
|
+
const signalValue = invocation.waitShape?.();
|
|
105
|
+
// A wait-suspect call this turn already classified is answered by that verdict
|
|
106
|
+
// rather than re-asked; anything else is only worth a question when it actually
|
|
107
|
+
// repeats (the same threshold as any other repetition).
|
|
108
|
+
if (signalValue !== undefined && invocation.waitClassified?.() === true) {
|
|
109
|
+
port.skip('wait-query');
|
|
110
|
+
return passThrough();
|
|
111
|
+
}
|
|
112
|
+
let suspicion = port.suspicion(window);
|
|
113
|
+
let waitSuspected = false;
|
|
114
|
+
if (signalValue !== undefined && signalValue.repeats >= policy.repeatThreshold) {
|
|
115
|
+
suspicion = waitTrigger(signalValue.shape, signalValue.repeats);
|
|
116
|
+
waitSuspected = true;
|
|
117
|
+
}
|
|
118
|
+
if (!suspicion.suspicious || port.alreadyDenied())
|
|
119
|
+
return passThrough();
|
|
120
|
+
if (port.alreadyIntervened()) {
|
|
121
|
+
port.skip('duplicate-intervention');
|
|
122
|
+
return passThrough();
|
|
123
|
+
}
|
|
124
|
+
if (!actionWithinBudget(port.budget(), policy)) {
|
|
125
|
+
port.skip('intervention-cap');
|
|
126
|
+
return passThrough();
|
|
127
|
+
}
|
|
128
|
+
// A wait question is judged on the polls themselves (each labelled with its
|
|
129
|
+
// place in the series, so the backend can read a wait rather than an exact
|
|
130
|
+
// repeat); every other question keeps the progress-only window.
|
|
131
|
+
const steps = waitSuspected ? (invocation.judgeSteps?.() ?? window) : window;
|
|
132
|
+
const started = port.clock().now();
|
|
133
|
+
const outcome = await runJudgment({
|
|
134
|
+
state: port.budget(),
|
|
135
|
+
policy,
|
|
136
|
+
buy: (step) => port.buy(step),
|
|
137
|
+
clock: port.clock(),
|
|
138
|
+
steps,
|
|
139
|
+
...(waitSuspected ? { goal: invocation.waitQuestion?.() } : {}),
|
|
140
|
+
...(signal === undefined ? {} : { signal })
|
|
141
|
+
});
|
|
142
|
+
const charge = chargeOf(outcome, started, port.clock().now());
|
|
143
|
+
// Denial is latched per signature whether or not it was applied: in observe
|
|
144
|
+
// mode the refusal is what would have happened, and the latch is what keeps the
|
|
145
|
+
// next identical attempt from being judged again in the same turn.
|
|
146
|
+
port.latchDenied();
|
|
147
|
+
if (!outcome.useful) {
|
|
148
|
+
if (waitSuspected)
|
|
149
|
+
invocation.latchWait?.();
|
|
150
|
+
// A budget/abort skip keeps its own reason; only a real "not stuck" answer to
|
|
151
|
+
// a wait question is recorded as the wait outcome.
|
|
152
|
+
port.chargeJudgment(charge);
|
|
153
|
+
port.skip(outcome.skip ?? (waitSuspected ? 'wait-query' : 'unconfirmed'), charge);
|
|
154
|
+
return passThrough();
|
|
155
|
+
}
|
|
156
|
+
const facts = {
|
|
157
|
+
tool: port.toolName(),
|
|
158
|
+
suspicion,
|
|
159
|
+
verdict: outcome.response
|
|
160
|
+
};
|
|
161
|
+
const plan = {
|
|
162
|
+
capability: STAGNATION_CAPABILITY,
|
|
163
|
+
action: 'deny-call',
|
|
164
|
+
reason: `System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern} stagnation before ${port.toolName()}`,
|
|
165
|
+
feedback: port.denyFeedback(facts),
|
|
166
|
+
detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)
|
|
167
|
+
};
|
|
168
|
+
const applies = mode === 'active' && mayAddDecision(invocation.downstreamKind);
|
|
169
|
+
if (mode === 'active' && !applies)
|
|
170
|
+
port.skip('downstream-decided');
|
|
171
|
+
invocation.noteRefused?.();
|
|
172
|
+
// The episode and the action are latched in both modes: observe has to plan
|
|
173
|
+
// exactly what active would do — one refusal per episode, subject to the same
|
|
174
|
+
// turn cap — or its column would over-count the very thing it is measuring.
|
|
175
|
+
port.latchIntervened();
|
|
176
|
+
bookAction(port.budget());
|
|
177
|
+
port.conclude(plan, applies, charge);
|
|
178
|
+
return applies
|
|
179
|
+
? { result: port.deny(plan.feedback), action: 'deny' }
|
|
180
|
+
: passThrough();
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* `agent/pre-step`: attach the correction to the step after a loop repeated
|
|
184
|
+
* itself.
|
|
185
|
+
*
|
|
186
|
+
* The host calls this **after** its own `next()`. A step the rest of the
|
|
187
|
+
* waterfall rejected, or a step whose turn is being cancelled, is not corrected.
|
|
188
|
+
*
|
|
189
|
+
* @param invocation - the downstream decision and the signal.
|
|
190
|
+
* @param port - everything that is the host's to answer.
|
|
191
|
+
* @returns the decision the loop enters with.
|
|
192
|
+
*/
|
|
193
|
+
export async function orchestrateStagnationStep(invocation, port) {
|
|
194
|
+
const passThrough = () => ({
|
|
195
|
+
result: port.passThrough(),
|
|
196
|
+
action: 'pass-through'
|
|
197
|
+
});
|
|
198
|
+
const mode = modeOf(port.policy(), STAGNATION_CAPABILITY);
|
|
199
|
+
if (mode === 'off' || !port.serves())
|
|
200
|
+
return passThrough();
|
|
201
|
+
if (invocation.signal?.aborted === true || invocation.downstreamKind !== 'enter')
|
|
202
|
+
return passThrough();
|
|
203
|
+
// The last observation is read from the *raw* window, before waits are dropped:
|
|
204
|
+
// a wait is exactly what this branch is about, so a window that had already
|
|
205
|
+
// filtered it out could never recognize one. Everything after this reads the
|
|
206
|
+
// progress-only window.
|
|
207
|
+
const recorded = port.window();
|
|
208
|
+
const last = recorded[recorded.length - 1];
|
|
209
|
+
if (last === undefined)
|
|
210
|
+
return passThrough();
|
|
211
|
+
// A poll that already passed the semantic wait judgment has nothing to correct
|
|
212
|
+
// here: the run asked about a background job again, it did not repeat its work.
|
|
213
|
+
// A poll this turn never judged was not a repetition, so it is not an episode.
|
|
214
|
+
if (last.wait === true) {
|
|
215
|
+
port.skip(port.wasClassifiedAsWait(last.signature) ? 'wait-query' : 'wait-query-unjudged');
|
|
216
|
+
return passThrough();
|
|
217
|
+
}
|
|
218
|
+
const window = port.progressWindow();
|
|
219
|
+
if (port.alreadyIntervened()) {
|
|
220
|
+
port.skip('duplicate-intervention');
|
|
221
|
+
return passThrough();
|
|
222
|
+
}
|
|
223
|
+
const policy = port.policy();
|
|
224
|
+
if (!actionWithinBudget(port.budget(), policy)) {
|
|
225
|
+
port.skip('intervention-cap');
|
|
226
|
+
return passThrough();
|
|
227
|
+
}
|
|
228
|
+
const suspicion = port.suspicion(window);
|
|
229
|
+
if (!suspicion.suspicious)
|
|
230
|
+
return passThrough();
|
|
231
|
+
const started = port.clock().now();
|
|
232
|
+
const outcome = await runJudgment({
|
|
233
|
+
state: port.budget(),
|
|
234
|
+
policy,
|
|
235
|
+
buy: (step) => port.buy(step),
|
|
236
|
+
clock: port.clock(),
|
|
237
|
+
steps: window,
|
|
238
|
+
...(invocation.signal === undefined ? {} : { signal: invocation.signal })
|
|
239
|
+
});
|
|
240
|
+
const charge = chargeOf(outcome, started, port.clock().now());
|
|
241
|
+
if (!outcome.useful) {
|
|
242
|
+
port.chargeJudgment(charge);
|
|
243
|
+
port.skip(outcome.skip ?? 'unconfirmed', charge);
|
|
244
|
+
return passThrough();
|
|
245
|
+
}
|
|
246
|
+
const facts = {
|
|
247
|
+
tool: port.toolName(),
|
|
248
|
+
suspicion,
|
|
249
|
+
verdict: outcome.response
|
|
250
|
+
};
|
|
251
|
+
const plan = {
|
|
252
|
+
capability: STAGNATION_CAPABILITY,
|
|
253
|
+
action: 'corrective-context',
|
|
254
|
+
reason: `System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern} stagnation before step ${port.budget().step}`,
|
|
255
|
+
feedback: port.contextFeedback(facts),
|
|
256
|
+
detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)
|
|
257
|
+
};
|
|
258
|
+
const applies = mode === 'active';
|
|
259
|
+
// The latch is mode-independent on purpose. Observe has to consume the same
|
|
260
|
+
// episode — one intervention per detected loop, one charge against the turn's
|
|
261
|
+
// cap — or its accounting would describe a run nobody could reproduce;
|
|
262
|
+
// installing the message is the only thing the mode gates.
|
|
263
|
+
port.latchIntervened();
|
|
264
|
+
bookAction(port.budget());
|
|
265
|
+
port.conclude(plan, applies, charge);
|
|
266
|
+
return applies
|
|
267
|
+
? { result: port.correct(plan.feedback), action: 'allow' }
|
|
268
|
+
: passThrough();
|
|
269
|
+
}
|
|
270
|
+
//# sourceMappingURL=orchestrate-stagnation.js.map
|
|
@@ -0,0 +1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O,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC;KACtF,CAAC;IACF,MAAM,OAAO,GAAG,IAAI,KAAK,QAAQ,CAAC;IAClC,4EAA4E;IAC5E,8EAA8E;IAC9E,uEAAuE;IACvE,2DAA2D;IAC3D,IAAI,CAAC,eAAe,EAAE,CAAC;IACvB,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1B,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IACrC,OAAO,OAAO;QACZ,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE;QAC1D,CAAC,CAAC,WAAW,EAAE,CAAC;AACpB,CAAC","sourcesContent":["/**\n * The shared orchestration of the stagnation decision.\n *\n * Like {@link ./orchestrate}, this module owns *when and in what order* a\n * decision is made, and none of the host facts the decision is made of. It was\n * lifted in behaviour from the DSH engine's `toolCall` and `preStep` branches so\n * that a second host can reuse them, and each of the two hooks is a function over\n * a port:\n *\n * ```\n * tools/pre-execute\n * downstream first, always\n * → off / own tool / aborted → hand the downstream decision back\n * → [the window: recorded steps + this call, waits removed]\n * → a wait shape already classified this turn → wait-query, nothing asked\n * → the cheap trigger (repetition / failing retry / oscillation)\n * → a handle-shaped repetition promoted to a wait question\n * → not suspicious, or already refused → hand it back\n * → already intervened on this episode → duplicate-intervention\n * → the turn's action allowance is spent → intervention-cap\n * → buy a judgment (memo first, budgets inside)\n * → not useful → charge it, record why, hand it back\n * → latch the refusal, latch the episode, book the action, conclude\n * → deny *only* when the downstream decision was an allow\n *\n * agent/pre-step\n * downstream first, always\n * → off / aborted / not `enter` → hand the downstream decision back\n * → nothing observed → nothing to correct\n * → the last observation was a wait → wait-query / wait-query-unjudged\n * → already intervened / no allowance → duplicate-intervention / cap\n * → the cheap trigger over the progress-only window\n * → buy a judgment → not useful → charge it, record why, hand it back\n * → latch the correction, book the action, conclude\n * → append the correction to the admitted messages (active only)\n * ```\n *\n * ## What is shared and what is not\n *\n * Shared here: both orders, every skip reason, the budget rules\n * (`actionWithinBudget`, `bookAction`, the judgment memo), the latch semantics,\n * the shape of the audit detail, and the rule that decides whether a refusal may\n * be *added* at all.\n *\n * *Not* shared here: the window itself (the host records steps and hands over an\n * array), the call identity a repetition is measured on (the host's signature\n * algorithm), what counts as a legitimate wait (the host's tool list and argument\n * shape), how a correction is attached to a step or a refusal delivered (the\n * host's message and decision types), and the operator-facing wording of either.\n *\n * ## Why the host supplies the window, not a store\n *\n * The DSH engine keeps its window in the agent's own bookkeeping and hands the\n * shared layer a value; a host that derives the window from a persisted log would\n * hand over a different value. Both are legal, and neither has to teach the\n * shared layer how it stores anything. The only thing the shared layer mutates is\n * the counters it is given, through {@link BudgetState}.\n *\n * ## The safety property this module states\n *\n * A refusal may only ever be *added on top of an allow* — {@link mayAddDecision},\n * one place, one rule. A host that returned something stricter is never\n * overwritten, because the harness would otherwise be able to turn a host's\n * conservative decision into a weaker one.\n *\n * @module core/orchestrate-stagnation\n */\nimport type { StagnationCheckResponse } from '../backend/types.js';\nimport type { HostBillingPort, HostDecisionPort, HostJudgmentPort, JudgmentState } from './orchestrate-host.js';\nimport {\n judgmentCharge,\n runJudgment,\n type JudgmentOutcome,\n type ObservedStep,\n type StagnationSuspicion,\n type VerdictMemoState\n} from './judge.js';\nimport { actionWithinBudget, bookAction, modeOf, type PolicySnapshot } from './policy.js';\n\n/** The capability every decision in this module belongs to. */\nexport const STAGNATION_CAPABILITY = 'stagnation' as const;\n\n/** What one orchestrated decision turned out to be. */\nexport type StagnationAction = 'allow' | 'deny' | 'pass-through';\n\n/**\n * The window a stagnation trigger and its judgment are measured on.\n *\n * A wait query is not progress the run can be repeating: an identically repeated\n * status/result query of the same background job is the sanctioned way to wait,\n * so those steps are dropped before the repetition, failure and oscillation\n * triggers read the window. Genuine calls on either side of a wait stay adjacent\n * instead of being separated by it, which keeps a real loop visible while a run\n * is waiting.\n * @param steps - observed steps, oldest first.\n * @returns the steps that count as progress.\n */\nexport function progressSteps(steps: readonly ObservedStep[]): readonly ObservedStep[] {\n return steps.some((step) => step.wait === true) ? steps.filter((step) => step.wait !== true) : steps;\n}\n\n/**\n * Whether an action may be added on top of the decision the rest of the\n * waterfall already made.\n *\n * This is the permission-monotonicity rule, in one place: a `deny` may be added\n * only to an `allow`. An approval in flight, a denial carrying its own structured\n * error identity, or a cancellation is information the Host attached, and\n * overwriting any of it would drop that information or relax the decision.\n * @param downstreamKind - the kind of the downstream decision.\n * @returns whether the shared layer may add a refusal.\n */\nexport function mayAddDecision(downstreamKind: string): boolean {\n return downstreamKind === 'allow';\n}\n\n/**\n * The trigger for a repetition of a *wait-shaped* call.\n *\n * The host's tool list only decides that this repetition is worth asking about;\n * it does not pass or refuse anything by itself.\n * @param shape - the wait shape the host recognised.\n * @param repeats - how many times the identity already occurred.\n * @returns the promoted trigger.\n */\nexport function waitTrigger(shape: string, repeats: number): StagnationSuspicion {\n return {\n suspicious: true,\n pattern: 'repetition',\n note: `wait-suspect ${shape} repeated ${repeats}x`,\n repeats\n };\n}\n\n/** The judgment cost of one decision, as the host bills it. */\nexport interface JudgedCharge {\n readonly judgments: number;\n readonly memoHits: number;\n readonly localLatencyMs: number;\n readonly remoteLatencyMs: number;\n readonly judgeTokens: number;\n}\n\n/** One planned stagnation decision, as the host records it. */\nexport interface StagnationPlanRecord {\n readonly capability: typeof STAGNATION_CAPABILITY;\n readonly action: 'deny-call' | 'corrective-context';\n readonly reason: string;\n feedback: string;\n readonly detail: Record<string, unknown>;\n}\n\n/** What one refusal or correction was built from. */\nexport interface StagnationFeedbackFacts {\n readonly tool: string;\n readonly suspicion: StagnationSuspicion;\n readonly verdict: StagnationCheckResponse;\n}\n\n/**\n * The counters one decision spends from and books against.\n *\n * The verdict cache is part of the budget state because a cached answer is what\n * makes a second question in the same turn free: the shared layer reads it\n * through here rather than keeping a second copy.\n */\nexport interface StagnationState extends VerdictMemoState {\n verdictTurn: number;\n verdictKey: string;\n verdict?: StagnationCheckResponse;\n}\n\n/**\n * Everything the shared layer cannot know by itself.\n *\n * {@link HostDecisionPort} answers the part every capability asks — policy,\n * counters, clock, switch, and the three billing channels — so this interface\n * states only what a *refusal or correction* additionally needs.\n */\nexport interface HostStagnationPort<Decision, Corrected>\n extends HostDecisionPort<StagnationState>,\n HostBillingPort<JudgedCharge, StagnationPlanRecord>,\n HostJudgmentPort<StagnationCheckResponse> {\n /** Name of the call being decided, for the record and the wording. */\n toolName(): string;\n /** The recorded window, oldest first, *without* the call about to run. */\n window(): readonly ObservedStep[];\n /** The step the call about to run would append, without committing it. */\n pendingStep(): ObservedStep;\n /** The identity this decision is about. */\n signature(): string;\n /**\n * The cheap trigger over one window.\n *\n * `PolicySnapshot` carries the repetition threshold and the confidence floor —\n * the two numbers the *budget* rules are stated in — but the failure threshold\n * and the window size are trigger parameters, and the host owns their values.\n * Keeping them here is what keeps one policy type for every capability.\n */\n suspicion(steps: readonly ObservedStep[]): StagnationSuspicion;\n /** The progress-only window a pre-step corrects against. */\n progressWindow(): readonly ObservedStep[];\n /** Whether this identity was already intervened on this turn. */\n alreadyIntervened(): boolean;\n /** Whether this identity was already refused this turn. */\n alreadyDenied(): boolean;\n /**\n * Whether the signature of a step was already classified as a wait.\n *\n * The pre-step hook needs it to tell \"a poll the run already had answered\" from\n * \"a poll this turn never judged\" — two different skip reasons, and the second\n * one is not a stagnation episode at all.\n */\n wasClassifiedAsWait(signature: string): boolean;\n /** Latch this identity as refused. */\n latchDenied(): void;\n /** Latch this identity as an episode already acted on. */\n latchIntervened(): void;\n /** The decision to hand back when nothing is done. */\n passThrough(): Decision;\n /** Build the refusal, once the decision is to apply one. */\n deny(feedback: string): Decision;\n /** Append the correction to the admitted messages, once the decision is to apply one. */\n correct(feedback: string): Corrected;\n /** Word the refusal handed to the model. */\n denyFeedback(facts: StagnationFeedbackFacts): string;\n /** Word the corrective context attached to a step. */\n contextFeedback(facts: StagnationFeedbackFacts): string;\n}\n\n/** The outcome of one orchestrated decision. */\nexport interface StagnationOutcome<Decision> {\n /** What the host should return to its caller. */\n readonly result: Decision;\n /** What the decision was. */\n readonly action: StagnationAction;\n}\n\n/**\n * The charge of one judgment, through the core's own billing rule.\n * @param outcome - the judgment's outcome.\n * @param started - clock reading at hook entry.\n * @param now - clock reading now.\n * @returns the charge the host records.\n */\nfunction chargeOf(outcome: JudgmentOutcome, started: number, now: number): JudgedCharge {\n return judgmentCharge(outcome, started, now);\n}\n\n/**\n * The detail every stagnation record carries.\n * @param suspicion - the cheap-path trigger.\n * @param verdict - what System 1 answered.\n * @param state - the deciding state, for turn and step.\n * @param step - the step the decision belongs to.\n * @returns the audit fields.\n */\nfunction detailOf(\n suspicion: StagnationSuspicion,\n verdict: StagnationCheckResponse,\n turn: number,\n step: number\n): Record<string, unknown> {\n return {\n pattern: String(verdict.patternType ?? suspicion.pattern ?? 'unknown'),\n confidence: verdict.confidence,\n repeats: suspicion.repeats,\n turn,\n step\n };\n}\n\n/**\n * `tools/pre-execute`: refuse a call the run is repeating.\n *\n * The host calls this **after** its own `next()`, and hands over what that\n * returned: the downstream decision is the first fact the decision is about, and\n * a refusal may only ever be added to an allow.\n *\n * @param invocation - the downstream decision, the signal, and the window facts.\n * @param port - everything that is the host's to answer.\n * @returns the decision the Host dispatches on.\n */\nexport async function orchestrateStagnationPre<Decision, Corrected>(\n invocation: {\n /** Kind of the decision the rest of the waterfall made. */\n readonly downstreamKind: string;\n /** The call's abort signal, if it has one. */\n readonly signal?: AbortSignal;\n /**\n * The window the judgment is about, when a wait question needs one.\n *\n * Defaults to the progress-only window. A host that annotates its polls\n * supplies the annotated list here, because *how* a poll is labelled is the\n * host's business and the shared layer only asks the question.\n */\n judgeSteps?: () => readonly ObservedStep[];\n /** The question a promoted wait asks, or nothing for an ordinary repetition. */\n waitQuestion?: () => string | undefined;\n /** Whether this wait shape was already classified this turn. */\n waitClassified?: () => boolean;\n /** Latch the wait shape as classified. */\n latchWait?: () => void;\n /** The wait handle shape, so the trigger can name it. */\n waitShape?: () => { readonly shape: string; readonly repeats: number } | undefined;\n /** Record that this call was refused, so its result is not judged as evidence. */\n noteRefused?: () => void;\n },\n port: HostStagnationPort<Decision, Corrected>\n): Promise<StagnationOutcome<Decision>> {\n const { signal } = invocation;\n const passThrough = (): StagnationOutcome<Decision> => ({ result: port.passThrough(), action: 'pass-through' });\n const mode = modeOf(port.policy(), STAGNATION_CAPABILITY);\n if (mode === 'off' || !port.serves()) return passThrough();\n if (signal?.aborted === true) return passThrough();\n\n const policy = port.policy();\n const pending = port.pendingStep();\n // The call about to run is part of its own window: three identical calls are a\n // repetition at the moment the third one is proposed, and the judgment has to\n // see all three.\n const allWindow = [...port.window(), pending];\n const window = progressSteps(allWindow);\n const signalValue = invocation.waitShape?.();\n\n // A wait-suspect call this turn already classified is answered by that verdict\n // rather than re-asked; anything else is only worth a question when it actually\n // repeats (the same threshold as any other repetition).\n if (signalValue !== undefined && invocation.waitClassified?.() === true) {\n port.skip('wait-query');\n return passThrough();\n }\n\n let suspicion = port.suspicion(window);\n let waitSuspected = false;\n if (signalValue !== undefined && signalValue.repeats >= policy.repeatThreshold) {\n suspicion = waitTrigger(signalValue.shape, signalValue.repeats);\n waitSuspected = true;\n }\n if (!suspicion.suspicious || port.alreadyDenied()) return passThrough();\n if (port.alreadyIntervened()) {\n port.skip('duplicate-intervention');\n return passThrough();\n }\n if (!actionWithinBudget(port.budget(), policy)) {\n port.skip('intervention-cap');\n return passThrough();\n }\n\n // A wait question is judged on the polls themselves (each labelled with its\n // place in the series, so the backend can read a wait rather than an exact\n // repeat); every other question keeps the progress-only window.\n const steps = waitSuspected ? (invocation.judgeSteps?.() ?? window) : window;\n const started = port.clock().now();\n const outcome = await runJudgment({\n state: port.budget(),\n policy,\n buy: (step) => port.buy(step),\n clock: port.clock(),\n steps,\n ...(waitSuspected ? { goal: invocation.waitQuestion?.() } : {}),\n ...(signal === undefined ? {} : { signal })\n });\n const charge = chargeOf(outcome, started, port.clock().now());\n // Denial is latched per signature whether or not it was applied: in observe\n // mode the refusal is what would have happened, and the latch is what keeps the\n // next identical attempt from being judged again in the same turn.\n port.latchDenied();\n\n if (!outcome.useful) {\n if (waitSuspected) invocation.latchWait?.();\n // A budget/abort skip keeps its own reason; only a real \"not stuck\" answer to\n // a wait question is recorded as the wait outcome.\n port.chargeJudgment(charge);\n port.skip(outcome.skip ?? (waitSuspected ? 'wait-query' : 'unconfirmed'), charge);\n return passThrough();\n }\n\n const facts: StagnationFeedbackFacts = {\n tool: port.toolName(),\n suspicion,\n verdict: outcome.response\n };\n const plan: StagnationPlanRecord = {\n capability: STAGNATION_CAPABILITY,\n action: 'deny-call',\n reason: `System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern} stagnation before ${port.toolName()}`,\n feedback: port.denyFeedback(facts),\n detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)\n };\n const applies = mode === 'active' && mayAddDecision(invocation.downstreamKind);\n if (mode === 'active' && !applies) port.skip('downstream-decided');\n invocation.noteRefused?.();\n // The episode and the action are latched in both modes: observe has to plan\n // exactly what active would do — one refusal per episode, subject to the same\n // turn cap — or its column would over-count the very thing it is measuring.\n port.latchIntervened();\n bookAction(port.budget());\n port.conclude(plan, applies, charge);\n return applies\n ? { result: port.deny(plan.feedback), action: 'deny' }\n : passThrough();\n}\n\n/**\n * `agent/pre-step`: attach the correction to the step after a loop repeated\n * itself.\n *\n * The host calls this **after** its own `next()`. A step the rest of the\n * waterfall rejected, or a step whose turn is being cancelled, is not corrected.\n *\n * @param invocation - the downstream decision and the signal.\n * @param port - everything that is the host's to answer.\n * @returns the decision the loop enters with.\n */\nexport async function orchestrateStagnationStep<Decision, Corrected>(\n invocation: {\n /** Kind of the decision the rest of the waterfall made. */\n readonly downstreamKind: string;\n /** The step's abort signal, if it has one. */\n readonly signal?: AbortSignal;\n },\n port: HostStagnationPort<Decision, Corrected>\n): Promise<StagnationOutcome<Decision | Corrected>> {\n const passThrough = (): StagnationOutcome<Decision | Corrected> => ({\n result: port.passThrough() as Decision | Corrected,\n action: 'pass-through'\n });\n const mode = modeOf(port.policy(), STAGNATION_CAPABILITY);\n if (mode === 'off' || !port.serves()) return passThrough();\n if (invocation.signal?.aborted === true || invocation.downstreamKind !== 'enter') return passThrough();\n\n // The last observation is read from the *raw* window, before waits are dropped:\n // a wait is exactly what this branch is about, so a window that had already\n // filtered it out could never recognize one. Everything after this reads the\n // progress-only window.\n const recorded = port.window();\n const last = recorded[recorded.length - 1];\n if (last === undefined) return passThrough();\n // A poll that already passed the semantic wait judgment has nothing to correct\n // here: the run asked about a background job again, it did not repeat its work.\n // A poll this turn never judged was not a repetition, so it is not an episode.\n if (last.wait === true) {\n port.skip(port.wasClassifiedAsWait(last.signature) ? 'wait-query' : 'wait-query-unjudged');\n return passThrough();\n }\n const window = port.progressWindow();\n if (port.alreadyIntervened()) {\n port.skip('duplicate-intervention');\n return passThrough();\n }\n const policy = port.policy();\n if (!actionWithinBudget(port.budget(), policy)) {\n port.skip('intervention-cap');\n return passThrough();\n }\n\n const suspicion = port.suspicion(window);\n if (!suspicion.suspicious) return passThrough();\n\n const started = port.clock().now();\n const outcome = await runJudgment({\n state: port.budget(),\n policy,\n buy: (step) => port.buy(step),\n clock: port.clock(),\n steps: window,\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal })\n });\n const charge = chargeOf(outcome, started, port.clock().now());\n if (!outcome.useful) {\n port.chargeJudgment(charge);\n port.skip(outcome.skip ?? 'unconfirmed', charge);\n return passThrough();\n }\n\n const facts: StagnationFeedbackFacts = {\n tool: port.toolName(),\n suspicion,\n verdict: outcome.response\n };\n const plan: StagnationPlanRecord = {\n capability: STAGNATION_CAPABILITY,\n action: 'corrective-context',\n reason: `System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern} stagnation before step ${port.budget().step}`,\n feedback: port.contextFeedback(facts),\n detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)\n };\n const applies = mode === 'active';\n // The latch is mode-independent on purpose. Observe has to consume the same\n // episode — one intervention per detected loop, one charge against the turn's\n // cap — or its accounting would describe a run nobody could reproduce;\n // installing the message is the only thing the mode gates.\n port.latchIntervened();\n bookAction(port.budget());\n port.conclude(plan, applies, charge);\n return applies\n ? { result: port.correct(plan.feedback), action: 'allow' }\n : passThrough();\n}\n"]}
|