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
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { actionWithinBudget, bookAction, spendJudgment } from './policy.js';
|
|
2
|
+
import { applyPruneFloor } from './prune-plan.js';
|
|
3
|
+
import { digestOf, estimateTokens } from './text.js';
|
|
4
|
+
/** Line breaks a payload needs before it is treated as line-oriented output. */
|
|
5
|
+
export const PRUNE_MIN_LINES = 4;
|
|
6
|
+
/**
|
|
7
|
+
* Largest payload the shared layer is willing to see copied into a host log.
|
|
8
|
+
*
|
|
9
|
+
* Retention is what makes a reduction safe, so this is a *precondition* of
|
|
10
|
+
* pruning rather than a fallback: above it the decision reports
|
|
11
|
+
* `retention-too-large` and leaves the result untouched, so an oversized payload
|
|
12
|
+
* can never be reported as saved on the strength of a copy that was never kept.
|
|
13
|
+
*/
|
|
14
|
+
export const MAX_RETAINED_CHARS = 100_000;
|
|
15
|
+
/** Characters of a reduction's explanatory note. */
|
|
16
|
+
export const PRUNE_FEEDBACK_CHARS = 600;
|
|
17
|
+
/**
|
|
18
|
+
* The payload half of a prune decision's audit fields.
|
|
19
|
+
*
|
|
20
|
+
* Taken before the service is asked, so a branch that refuses the payload early
|
|
21
|
+
* still names the payload it refused.
|
|
22
|
+
* @param text - the effective text the decision is about.
|
|
23
|
+
* @returns the digest and size, or nothing for an empty payload.
|
|
24
|
+
*/
|
|
25
|
+
export function prunePayloadDetail(text) {
|
|
26
|
+
return text.length === 0 ? {} : { digest: digestOf(text), originalChars: text.length };
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The judgment half of a prune decision's audit fields.
|
|
30
|
+
*
|
|
31
|
+
* A pure pass-through of what the prune service computed, plus the two sizes
|
|
32
|
+
* every record quotes.
|
|
33
|
+
* @param response - the service's answer.
|
|
34
|
+
* @param originalTokens - tokens of the raw payload.
|
|
35
|
+
* @param candidateTokens - tokens of the composed candidate.
|
|
36
|
+
* @returns the diagnostics plus sizes.
|
|
37
|
+
*/
|
|
38
|
+
export function pruneDiagnosticsOf(response, originalTokens, candidateTokens) {
|
|
39
|
+
return {
|
|
40
|
+
...(response.judgePath === undefined ? {} : { judgePath: response.judgePath }),
|
|
41
|
+
...(response.judgedSegments === undefined ? {} : { judgedSegments: response.judgedSegments }),
|
|
42
|
+
...(response.unjudgedSegments === undefined ? {} : { unjudgedSegments: response.unjudgedSegments }),
|
|
43
|
+
...(response.keptSegments === undefined ? {} : { keptSegments: response.keptSegments }),
|
|
44
|
+
...(response.aggressiveChars === undefined ? {} : { aggressiveChars: response.aggressiveChars }),
|
|
45
|
+
...(response.balancedChars === undefined ? {} : { balancedChars: response.balancedChars }),
|
|
46
|
+
...(response.conservativeChars === undefined ? {} : { conservativeChars: response.conservativeChars }),
|
|
47
|
+
...(response.scoredSegments === undefined ? {} : { scoredSegments: response.scoredSegments }),
|
|
48
|
+
...(response.autoKeptSegments === undefined ? {} : { autoKeptSegments: response.autoKeptSegments }),
|
|
49
|
+
...(response.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: response.unparsedScoreAnswers }),
|
|
50
|
+
...(response.fallbackReason === undefined ? {} : { fallbackReason: response.fallbackReason }),
|
|
51
|
+
originalTokens,
|
|
52
|
+
candidateTokens
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Run the one pruning decision.
|
|
57
|
+
*
|
|
58
|
+
* @param invocation - the call whose result is being considered, and the
|
|
59
|
+
* effective text of that result.
|
|
60
|
+
* @param port - everything that is the host's to answer.
|
|
61
|
+
* @returns the decision the host commits.
|
|
62
|
+
*/
|
|
63
|
+
export async function orchestratePrune(invocation, port) {
|
|
64
|
+
const mode = port.mode();
|
|
65
|
+
if (mode === 'off')
|
|
66
|
+
return { result: port.passThrough(), applied: false };
|
|
67
|
+
// A blocked result is already not shown to the model; rewriting it is moot and
|
|
68
|
+
// re-deriving its text would ignore the block.
|
|
69
|
+
if (invocation.blockedByDownstream)
|
|
70
|
+
return { result: port.passThrough(), applied: false };
|
|
71
|
+
const text = invocation.text;
|
|
72
|
+
const payloadDetail = prunePayloadDetail(text);
|
|
73
|
+
if (invocation.valueShapedAccept) {
|
|
74
|
+
// A value-shaped accept replaced the payload wholesale; nothing here knows
|
|
75
|
+
// what its text is, so nothing here may touch it.
|
|
76
|
+
port.skip('value-shaped-accept', {});
|
|
77
|
+
return { result: port.passThrough(), applied: false, skip: 'value-shaped-accept' };
|
|
78
|
+
}
|
|
79
|
+
if (!port.hasTextBlock()) {
|
|
80
|
+
// Nothing to replace, and nothing that could be reported as replaced. Asked
|
|
81
|
+
// before the size checks: an image-only payload is not "small", it is out of
|
|
82
|
+
// scope, and the skip reason should say so.
|
|
83
|
+
port.skip('no-text-block', payloadDetail);
|
|
84
|
+
return { result: port.passThrough(), applied: false, skip: 'no-text-block' };
|
|
85
|
+
}
|
|
86
|
+
if (text.length < port.threshold()) {
|
|
87
|
+
port.skip('below-threshold', payloadDetail);
|
|
88
|
+
return { result: port.passThrough(), applied: false, skip: 'below-threshold' };
|
|
89
|
+
}
|
|
90
|
+
if ((text.match(/\n/g)?.length ?? 0) < PRUNE_MIN_LINES) {
|
|
91
|
+
// Not line-oriented output: the judge is asked to extract diagnostics, and a
|
|
92
|
+
// payload with no lines does not have any to extract. Rewriting it would
|
|
93
|
+
// destroy semantic data rather than compress a trace.
|
|
94
|
+
port.skip('unsupported-payload', payloadDetail);
|
|
95
|
+
return { result: port.passThrough(), applied: false, skip: 'unsupported-payload' };
|
|
96
|
+
}
|
|
97
|
+
if (text.length > MAX_RETAINED_CHARS) {
|
|
98
|
+
// Retention is a precondition of replacing anything, so an oversized payload
|
|
99
|
+
// is refused *before* it is judged or reported as a saving.
|
|
100
|
+
port.skip('retention-too-large', payloadDetail);
|
|
101
|
+
return { result: port.passThrough(), applied: false, skip: 'retention-too-large' };
|
|
102
|
+
}
|
|
103
|
+
if (!port.hasRetention()) {
|
|
104
|
+
// Without a retention sink nothing may be replaced: the layer will not
|
|
105
|
+
// destroy the only copy of a result it cannot give back.
|
|
106
|
+
port.skip('retention-unavailable', payloadDetail);
|
|
107
|
+
return { result: port.passThrough(), applied: false, skip: 'retention-unavailable' };
|
|
108
|
+
}
|
|
109
|
+
if (!actionWithinBudget(port.budget(), port.policy())) {
|
|
110
|
+
// A reduction is an intervention like a refusal or a correction, so it draws
|
|
111
|
+
// on the same per-turn allowance — and it is asked here, before a judgment is
|
|
112
|
+
// bought, so a full turn costs nothing to refuse. Both modes are checked:
|
|
113
|
+
// observe has to plan no more actions than active could take, including the
|
|
114
|
+
// ones the memo would have answered for free.
|
|
115
|
+
port.skip('intervention-cap', payloadDetail);
|
|
116
|
+
return { result: port.passThrough(), applied: false, skip: 'intervention-cap' };
|
|
117
|
+
}
|
|
118
|
+
const floor = port.floor();
|
|
119
|
+
// Where this decision is being made travels with the counters, not with a port
|
|
120
|
+
// accessor: the retention request, the audit detail and the plan all quote the
|
|
121
|
+
// same two numbers this state already carries.
|
|
122
|
+
const state = port.budget();
|
|
123
|
+
const digest = digestOf(text);
|
|
124
|
+
// The locator is derived from the payload, and a sink that names its copy the
|
|
125
|
+
// same way makes the plan's size the size of the form active will install, in
|
|
126
|
+
// both modes.
|
|
127
|
+
const locator = port.locatorOf(digest);
|
|
128
|
+
const memo = port.memoGet(`${port.memoKey()}:${digest}`);
|
|
129
|
+
// A memo hit answers the question the judgment already answered; only a mode
|
|
130
|
+
// that needs the reduction's *text* has to ask for it again.
|
|
131
|
+
const needsCandidate = mode === 'active' && memo?.text === undefined;
|
|
132
|
+
if (!memo || needsCandidate) {
|
|
133
|
+
const skip = spendJudgment(port.budget(), port.policy());
|
|
134
|
+
if (skip !== undefined) {
|
|
135
|
+
port.skip(skip, payloadDetail);
|
|
136
|
+
return { result: port.passThrough(), applied: false, skip };
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const candidate = memo && !needsCandidate
|
|
140
|
+
? {
|
|
141
|
+
processedOutput: memo.text ?? text,
|
|
142
|
+
reductionPercentage: reductionPercentageOf(memo.originalChars, memo.prunedChars),
|
|
143
|
+
latencyMs: 0,
|
|
144
|
+
shadow: memo.text === undefined,
|
|
145
|
+
...(memo.diagnostics ?? {})
|
|
146
|
+
}
|
|
147
|
+
: // Both modes take the *real* candidate, and both ask for it measure-only.
|
|
148
|
+
// `shadow` only decides whether the backend hands its text back, while
|
|
149
|
+
// the candidate's size is that candidate's size either way; the text is
|
|
150
|
+
// what the floor composes from, so a withheld measurement would not be
|
|
151
|
+
// the same input at all. Whether the payload is installed is decided
|
|
152
|
+
// here, by the floor, *after* the service has written its ledger entry —
|
|
153
|
+
// so this path never lets the service declare a saving.
|
|
154
|
+
await port.judge(text);
|
|
155
|
+
const originalTokens = estimateTokens(text);
|
|
156
|
+
// One composition, both modes: the floored text the plan describes is the text
|
|
157
|
+
// active installs, byte for byte. Line alignment and duplicate removal move its
|
|
158
|
+
// real size away from the modelled one, so the number both modes account for is
|
|
159
|
+
// the length of the composed text — never a prediction about it.
|
|
160
|
+
const composed = applyPruneFloor(text, candidate.processedOutput, {
|
|
161
|
+
floorRatio: floor.floorRatio,
|
|
162
|
+
headChars: floor.headChars,
|
|
163
|
+
tailChars: floor.tailChars,
|
|
164
|
+
locator
|
|
165
|
+
});
|
|
166
|
+
const candidateTokens = Math.ceil(composed.text.length / 4);
|
|
167
|
+
const diagnostics = pruneDiagnosticsOf(
|
|
168
|
+
// A memo hit replays the provenance of the judgment that composed the form,
|
|
169
|
+
// so a reused reduction still says which path produced it.
|
|
170
|
+
memo && !needsCandidate ? (memo.diagnostics ?? {}) : (candidate.diagnostics ?? {}), originalTokens, candidateTokens);
|
|
171
|
+
// A memo hit hands back a form that was composed for this payload already. It is
|
|
172
|
+
// its own fixed point — it carries the share, so the plan of the same lengths
|
|
173
|
+
// stays "not floored" and gives that text straight back — but its provenance is
|
|
174
|
+
// not readable from those lengths any more. The memo, which was written by the
|
|
175
|
+
// composition, answers for it: without this the audit would report a floored
|
|
176
|
+
// install as an unfloored one.
|
|
177
|
+
const reusedFromMemo = !needsCandidate && memo?.text !== undefined ? memo : undefined;
|
|
178
|
+
const floorApplied = reusedFromMemo ? reusedFromMemo.floored : composed.floored;
|
|
179
|
+
const floorMissed = reusedFromMemo ? reusedFromMemo.floorMissed === true : composed.floorMissed;
|
|
180
|
+
const markerOmitted = reusedFromMemo ? reusedFromMemo.markerOmitted === true : composed.markerOmitted;
|
|
181
|
+
const measured = {
|
|
182
|
+
...payloadDetail,
|
|
183
|
+
...diagnostics,
|
|
184
|
+
floored: floorApplied,
|
|
185
|
+
floorMissed,
|
|
186
|
+
markerOmitted,
|
|
187
|
+
candidateChars: composed.text.length
|
|
188
|
+
};
|
|
189
|
+
const judged = !memo || needsCandidate;
|
|
190
|
+
const judgment = {
|
|
191
|
+
judgments: judged ? 1 : 0,
|
|
192
|
+
memoHits: judged ? 0 : 1,
|
|
193
|
+
localLatencyMs: Math.max(0, port.now() - invocation.started - (judged ? candidate.latencyMs : 0)),
|
|
194
|
+
remoteLatencyMs: judged ? candidate.latencyMs : 0,
|
|
195
|
+
// The pre-prune payload is what the pruner reasoned about; a backend call is
|
|
196
|
+
// a judgment even when it returns locally in under a millisecond.
|
|
197
|
+
judgeTokens: judged ? originalTokens : 0
|
|
198
|
+
};
|
|
199
|
+
if (candidateTokens >= originalTokens) {
|
|
200
|
+
// The judgment ran and the candidate it produced was not smaller, so it is
|
|
201
|
+
// charged with the size it was asked about — nothing else about this payload
|
|
202
|
+
// is billed.
|
|
203
|
+
port.chargeJudgment(judgment, originalTokens);
|
|
204
|
+
// The branch a real "prune: active but nothing happened" run lands in: the
|
|
205
|
+
// judgment ran, and the candidate it produced was not smaller. The record
|
|
206
|
+
// says so with the path that produced it and the sizes both sides had.
|
|
207
|
+
port.skip('no-reduction', measured, judgment);
|
|
208
|
+
return { result: port.passThrough(), applied: false, skip: 'no-reduction' };
|
|
209
|
+
}
|
|
210
|
+
const plan = {
|
|
211
|
+
capability: 'prune',
|
|
212
|
+
action: 'prune-result',
|
|
213
|
+
reason: `${invocation.tool} returned ${originalTokens} tokens; the judged reduction carries ${candidateTokens}`,
|
|
214
|
+
feedback: port.describe({
|
|
215
|
+
tool: invocation.tool,
|
|
216
|
+
originalTokens,
|
|
217
|
+
candidateTokens,
|
|
218
|
+
floored: floorApplied,
|
|
219
|
+
floorMissed,
|
|
220
|
+
markerOmitted,
|
|
221
|
+
locator,
|
|
222
|
+
keptSegments: diagnostics.keptSegments,
|
|
223
|
+
judgedSegments: diagnostics.judgedSegments
|
|
224
|
+
}),
|
|
225
|
+
detail: {
|
|
226
|
+
digest,
|
|
227
|
+
floorApplied,
|
|
228
|
+
floorMissed,
|
|
229
|
+
markerOmitted,
|
|
230
|
+
confidence: candidate.reductionPercentage,
|
|
231
|
+
turn: state.turn,
|
|
232
|
+
step: state.step,
|
|
233
|
+
...diagnostics,
|
|
234
|
+
originalChars: text.length,
|
|
235
|
+
candidateChars: composed.text.length
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
const planCosts = {
|
|
239
|
+
originalTokens,
|
|
240
|
+
candidateTokens,
|
|
241
|
+
potentialSavedTokens: originalTokens - candidateTokens
|
|
242
|
+
};
|
|
243
|
+
if (mode !== 'active') {
|
|
244
|
+
// Observe: the plan is real and charged, the surface is untouched, and the
|
|
245
|
+
// memo keeps the composed form — the same form active would install, from the
|
|
246
|
+
// same candidate — so a later hit reports the reduction this mode really saw.
|
|
247
|
+
// A plan this mode records is the action active would have taken, so it books
|
|
248
|
+
// the slot active would have booked.
|
|
249
|
+
bookAction(port.budget());
|
|
250
|
+
port.conclude(plan, false, planCosts, judgment);
|
|
251
|
+
if (!memo) {
|
|
252
|
+
port.memoSet(`${port.memoKey()}:${digest}`, {
|
|
253
|
+
text: composed.text,
|
|
254
|
+
originalChars: text.length,
|
|
255
|
+
prunedChars: composed.text.length,
|
|
256
|
+
tokensSaved: originalTokens - candidateTokens,
|
|
257
|
+
floored: floorApplied,
|
|
258
|
+
floorMissed,
|
|
259
|
+
markerOmitted,
|
|
260
|
+
diagnostics
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
return { result: port.passThrough(), applied: false };
|
|
264
|
+
}
|
|
265
|
+
// Active. The original is retained *before* anything is replaced, and only a
|
|
266
|
+
// verified retention makes the replacement installable at all. A payload whose
|
|
267
|
+
// copy is already retained keeps that copy instead of writing a second one.
|
|
268
|
+
const alreadyRetained = memo?.locator;
|
|
269
|
+
const retention = alreadyRetained
|
|
270
|
+
? { locator: alreadyRetained }
|
|
271
|
+
: port.retain({
|
|
272
|
+
digest,
|
|
273
|
+
callId: invocation.callId,
|
|
274
|
+
tool: invocation.tool,
|
|
275
|
+
turn: state.turn,
|
|
276
|
+
step: state.step,
|
|
277
|
+
text
|
|
278
|
+
}, port.session());
|
|
279
|
+
if (retention === undefined || typeof retention.locator !== 'string' || retention.locator.length === 0) {
|
|
280
|
+
// No controlled copy, no reduction. The result stays exactly as the rest of
|
|
281
|
+
// the waterfall produced it, and no saving is recorded — but the judgment
|
|
282
|
+
// that got this far was really made, so it is charged rather than hidden.
|
|
283
|
+
port.chargeJudgment(judgment);
|
|
284
|
+
port.skip('retention-failed', measured, judgment);
|
|
285
|
+
return { result: port.passThrough(), applied: false, skip: 'retention-failed' };
|
|
286
|
+
}
|
|
287
|
+
// The form both modes accounted for is the form that gets installed: the locator
|
|
288
|
+
// is derived from the payload and a sink that names its copy the same way makes
|
|
289
|
+
// the composition already published reusable byte for byte — with the provenance
|
|
290
|
+
// the plan gave it. Only a sink that named the copy differently forces a rebuild,
|
|
291
|
+
// and then the real length and provenance of that rebuild are what gets
|
|
292
|
+
// accounted for.
|
|
293
|
+
const installed = retention.locator === locator
|
|
294
|
+
? { ...composed, floored: floorApplied, floorMissed, markerOmitted }
|
|
295
|
+
: applyPruneFloor(text, candidate.processedOutput, {
|
|
296
|
+
floorRatio: floor.floorRatio,
|
|
297
|
+
headChars: floor.headChars,
|
|
298
|
+
tailChars: floor.tailChars,
|
|
299
|
+
locator: retention.locator
|
|
300
|
+
});
|
|
301
|
+
if (installed.text.length === 0 || installed.text.length >= text.length) {
|
|
302
|
+
// The plan said the form is smaller; the form that was really built must be
|
|
303
|
+
// too, or nothing is installed and nothing is saved.
|
|
304
|
+
port.skip('no-reduction', {
|
|
305
|
+
...measured,
|
|
306
|
+
floored: installed.floored,
|
|
307
|
+
floorMissed: installed.floorMissed,
|
|
308
|
+
markerOmitted: installed.markerOmitted,
|
|
309
|
+
candidateChars: installed.text.length,
|
|
310
|
+
candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))
|
|
311
|
+
}, judgment);
|
|
312
|
+
return { result: port.passThrough(), applied: false, skip: 'no-reduction' };
|
|
313
|
+
}
|
|
314
|
+
const replacement = port.install(installed.text);
|
|
315
|
+
if (replacement === undefined) {
|
|
316
|
+
port.skip('no-text-block', {
|
|
317
|
+
...measured,
|
|
318
|
+
floored: installed.floored,
|
|
319
|
+
floorMissed: installed.floorMissed,
|
|
320
|
+
markerOmitted: installed.markerOmitted,
|
|
321
|
+
candidateChars: installed.text.length,
|
|
322
|
+
candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))
|
|
323
|
+
}, judgment);
|
|
324
|
+
return { result: port.passThrough(), applied: false, skip: 'no-text-block' };
|
|
325
|
+
}
|
|
326
|
+
// Only now is there a decision that really took effect, so only now is the
|
|
327
|
+
// saving recorded — against the text that is really about to enter the context.
|
|
328
|
+
const installedTokens = Math.max(0, Math.ceil(installed.text.length / 4));
|
|
329
|
+
plan.detail.floorApplied = installed.floored;
|
|
330
|
+
plan.detail.floorMissed = installed.floorMissed;
|
|
331
|
+
plan.detail.markerOmitted = installed.markerOmitted;
|
|
332
|
+
plan.detail.candidateChars = installed.text.length;
|
|
333
|
+
plan.feedback = port.describe({
|
|
334
|
+
tool: invocation.tool,
|
|
335
|
+
originalTokens,
|
|
336
|
+
candidateTokens: installedTokens,
|
|
337
|
+
floored: installed.floored,
|
|
338
|
+
floorMissed: installed.floorMissed,
|
|
339
|
+
markerOmitted: installed.markerOmitted,
|
|
340
|
+
locator: retention.locator,
|
|
341
|
+
keptSegments: diagnostics.keptSegments,
|
|
342
|
+
judgedSegments: diagnostics.judgedSegments
|
|
343
|
+
});
|
|
344
|
+
// Booked only here: a candidate that was not smaller, a replacement that could
|
|
345
|
+
// not be composed, and a retention that failed all returned above, so none of
|
|
346
|
+
// them consumed the turn's allowance for an action that never happened.
|
|
347
|
+
bookAction(port.budget());
|
|
348
|
+
const installedCosts = {
|
|
349
|
+
originalTokens,
|
|
350
|
+
candidateTokens: installedTokens,
|
|
351
|
+
potentialSavedTokens: originalTokens - installedTokens,
|
|
352
|
+
actualSavedTokens: originalTokens - installedTokens
|
|
353
|
+
};
|
|
354
|
+
port.conclude(plan, true, installedCosts, judgment, retention.locator);
|
|
355
|
+
// Retention is counted once per payload: a duplicate install reuses the copy
|
|
356
|
+
// that is already in the log, and the locator naming it never changes.
|
|
357
|
+
port.noteRetained(retention.locator);
|
|
358
|
+
port.memoSet(`${port.memoKey()}:${digest}`, {
|
|
359
|
+
text: installed.text,
|
|
360
|
+
originalChars: text.length,
|
|
361
|
+
prunedChars: installed.text.length,
|
|
362
|
+
tokensSaved: originalTokens - installedTokens,
|
|
363
|
+
floored: installed.floored,
|
|
364
|
+
floorMissed: installed.floorMissed,
|
|
365
|
+
markerOmitted: installed.markerOmitted,
|
|
366
|
+
locator: retention.locator,
|
|
367
|
+
diagnostics
|
|
368
|
+
});
|
|
369
|
+
return { result: replacement, applied: true };
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Percentage of a payload a reduction kept.
|
|
373
|
+
* @param originalChars - size of the raw payload.
|
|
374
|
+
* @param prunedChars - size of the reduction.
|
|
375
|
+
* @returns the kept share, rounded to one decimal.
|
|
376
|
+
*/
|
|
377
|
+
export function reductionPercentageOf(originalChars, prunedChars) {
|
|
378
|
+
if (originalChars === 0)
|
|
379
|
+
return 0;
|
|
380
|
+
return Math.round(((originalChars - prunedChars) / originalChars) * 1000) / 10;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* The note of one reduction, in the default wording.
|
|
384
|
+
*
|
|
385
|
+
* It is meant for an operator, never for the model: a prune is supposed to remove
|
|
386
|
+
* context, so sending an explanation of the removal would work against the thing
|
|
387
|
+
* it accounts for. A host that shows it to a *person* may keep this wording
|
|
388
|
+
* verbatim; that is why it lives here next to the facts it is built from.
|
|
389
|
+
* @param facts - what the reduction did.
|
|
390
|
+
* @returns the note, bounded.
|
|
391
|
+
*/
|
|
392
|
+
export function describeReduction(facts) {
|
|
393
|
+
const kept = facts.originalTokens === 0 ? 100 : Math.round((facts.candidateTokens / facts.originalTokens) * 100);
|
|
394
|
+
const head = `Reduced ${facts.tool}: ${facts.originalTokens} → ${facts.candidateTokens} tokens (${kept}% kept). `;
|
|
395
|
+
const segmentsShort = facts.keptSegments !== undefined && facts.judgedSegments !== undefined && facts.keptSegments < facts.judgedSegments;
|
|
396
|
+
const segmentNote = segmentsShort
|
|
397
|
+
? `Kept ${facts.keptSegments}/${facts.judgedSegments} segments, omitted ${facts.judgedSegments - facts.keptSegments}. `
|
|
398
|
+
: '';
|
|
399
|
+
let body;
|
|
400
|
+
if (facts.floored) {
|
|
401
|
+
body = 'The head, the judged extract and the tail were kept; the full output was retained and is not in context.';
|
|
402
|
+
}
|
|
403
|
+
else if (facts.floorMissed) {
|
|
404
|
+
const install = facts.markerOmitted
|
|
405
|
+
? 'no locator marker was added because it would not have kept the text smaller than the original'
|
|
406
|
+
: 'the judged extract was installed as-is';
|
|
407
|
+
body = `${segmentNote}The candidate fell short of the floor, so ${install}; the full output is retrievable as ${facts.locator}.`;
|
|
408
|
+
}
|
|
409
|
+
else if (segmentsShort) {
|
|
410
|
+
body = `${segmentNote}The judged extract was installed as-is; the full output is retrievable as ${facts.locator}.`;
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
body = 'The judged extract was kept whole; the full output was retained and is not in context.';
|
|
414
|
+
}
|
|
415
|
+
const note = `${head}${body}`;
|
|
416
|
+
return note.length <= PRUNE_FEEDBACK_CHARS ? note : `${note.slice(0, PRUNE_FEEDBACK_CHARS)}…`;
|
|
417
|
+
}
|
|
418
|
+
//# sourceMappingURL=orchestrate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrate.js","sourceRoot":"","sources":["../../../../src/vendor/harness-reflex/core/orchestrate.ts"],"names":[],"mappings":"AAiDA,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,aAAa,EAAuB,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,eAAe,EAAuB,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAsB,MAAM,WAAW,CAAC;AAEzE,gFAAgF;AAChF,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AAEjC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,OAAO,CAAC;AAE1C,oDAAoD;AACpD,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAoBxC;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC7C,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,aAAa,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;AACzF,CAAC;AAiBD;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAChC,QAA0B,EAC1B,cAAsB,EACtB,eAAuB;IAEvB,OAAO;QACL,GAAG,CAAC,QAAQ,CAAC,SAAS,KAAK,SA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,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,cAAc,sBAAsB,KAAK,CAAC,cAAe,GAAG,KAAK,CAAC,YAAa,IAAI;QACzH,CAAC,CAAC,EAAE,CAAC;IACP,IAAI,IAAY,CAAC;IACjB,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QAClB,IAAI,GAAG,0GAA0G,CAAC;IACpH,CAAC;SAAM,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QAC7B,MAAM,OAAO,GAAG,KAAK,CAAC,aAAa;YACjC,CAAC,CAAC,+FAA+F;YACjG,CAAC,CAAC,wCAAwC,CAAC;QAC7C,IAAI,GAAG,GAAG,WAAW,6CAA6C,OAAO,uCAAuC,KAAK,CAAC,OAAO,GAAG,CAAC;IACnI,CAAC;SAAM,IAAI,aAAa,EAAE,CAAC;QACzB,IAAI,GAAG,GAAG,WAAW,6EAA6E,KAAK,CAAC,OAAO,GAAG,CAAC;IACrH,CAAC;SAAM,CAAC;QACN,IAAI,GAAG,wFAAwF,CAAC;IAClG,CAAC;IACD,MAAM,IAAI,GAAG,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;IAC9B,OAAO,IAAI,CAAC,MAAM,IAAI,oBAAoB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,oBAAoB,CAAC,GAAG,CAAC;AAChG,CAAC","sourcesContent":["/**\n * The shared orchestration of one judged reduction.\n *\n * This module owns *when and in what order* a pruning decision is made; it does\n * not own any of the host facts that decision is made of. It was lifted verbatim\n * in behaviour from the DSH engine's private prune branch so that a second host\n * can reuse it, and it is written as a pure function over a port so that the\n * order — which is a safety property, not a style — is stated in exactly one\n * place:\n *\n * ```\n * refuse off / downstream-blocked / value-shaped\n * → refuse payloads that are not line-oriented output\n * → refuse payloads too large to retain\n * → refuse when no retention sink exists\n * → refuse when the turn's action allowance is spent\n * → buy a judgment (memo first), refuse when the judgment budget is spent\n * → compose the floored candidate, refuse when it is not smaller\n * → [observe: record the plan and stop]\n * → retain the original, refuse when no verifiable copy exists\n * → compose against the real locator, refuse when the result is not smaller\n * → ask the host to install it, refuse when there is no text block\n * → only now record the saving\n * ```\n *\n * Every \"refuse\" returns the downstream decision untouched and reports why. A\n * reduction that cannot be verified can therefore never be reported as applied.\n *\n * ## What is shared and what is not\n *\n * Shared here: the order above, every skip reason, the budget rules (which\n * counter moves when), the size arithmetic, the memo semantics, and the shape of\n * the audit detail. *Not* shared here: how a candidate is obtained (the host's\n * judge), how an original is retained (the host's sink, whose locator differs per\n * host), how text is installed into a host content type, and how the operator-\n * facing note is worded (that is a product decision per host).\n *\n * ## Why the port rather than callback arguments\n *\n * The DSH engine and the Claude hook disagree about nearly every *fact* and\n * about none of the *rules*. A port keeps the rules in one file and lets each\n * host answer only the questions it alone can answer. `HostPrunePort` is\n * deliberately total: there is no optional method, so a host that cannot retain\n * an original says so once, up front, instead of the shared layer guessing from\n * an absent callback.\n *\n * @module core/orchestrate\n */\nimport type { HostDecisionPort, JudgmentState } from './orchestrate-host.js';\nimport { actionWithinBudget, bookAction, spendJudgment, type PolicySnapshot } from './policy.js';\nimport { applyPruneFloor, type PruneFloorPlan } from './prune-plan.js';\nimport { digestOf, estimateTokens, type TextBlockLike } from './text.js';\n\n/** Line breaks a payload needs before it is treated as line-oriented output. */\nexport const PRUNE_MIN_LINES = 4;\n\n/**\n * Largest payload the shared layer is willing to see copied into a host log.\n *\n * Retention is what makes a reduction safe, so this is a *precondition* of\n * pruning rather than a fallback: above it the decision reports\n * `retention-too-large` and leaves the result untouched, so an oversized payload\n * can never be reported as saved on the strength of a copy that was never kept.\n */\nexport const MAX_RETAINED_CHARS = 100_000;\n\n/** Characters of a reduction's explanatory note. */\nexport const PRUNE_FEEDBACK_CHARS = 600;\n\n/** The floor options a reduction is composed with. */\nexport interface PruneFloorSettings {\n /** Lowest share of the original a reduction may keep. */\n readonly floorRatio: number;\n /** Default split of the context budget, taken from the head. */\n readonly headChars: number;\n /** Default split of the context budget, taken from the tail. */\n readonly tailChars: number;\n}\n\n/** The payload half of a prune decision's audit fields. */\nexport type PrunePayloadDetail = {\n /** Payload identity, absent for an empty payload. */\n readonly digest?: string;\n /** Size of the payload the decision is about. */\n readonly originalChars?: number;\n};\n\n/**\n * The payload half of a prune decision's audit fields.\n *\n * Taken before the service is asked, so a branch that refuses the payload early\n * still names the payload it refused.\n * @param text - the effective text the decision is about.\n * @returns the digest and size, or nothing for an empty payload.\n */\nexport function prunePayloadDetail(text: string): PrunePayloadDetail {\n return text.length === 0 ? {} : { digest: digestOf(text), originalChars: text.length };\n}\n\n/** What the judged candidate reports about its own path. */\nexport interface PruneDiagnostics {\n readonly judgePath?: 'segmented' | 'local' | 'fallback';\n readonly judgedSegments?: number;\n readonly unjudgedSegments?: number;\n readonly keptSegments?: number;\n readonly aggressiveChars?: number;\n readonly balancedChars?: number;\n readonly conservativeChars?: number;\n readonly scoredSegments?: number;\n readonly autoKeptSegments?: number;\n readonly unparsedScoreAnswers?: number;\n readonly fallbackReason?: string;\n}\n\n/**\n * The judgment half of a prune decision's audit fields.\n *\n * A pure pass-through of what the prune service computed, plus the two sizes\n * every record quotes.\n * @param response - the service's answer.\n * @param originalTokens - tokens of the raw payload.\n * @param candidateTokens - tokens of the composed candidate.\n * @returns the diagnostics plus sizes.\n */\nexport function pruneDiagnosticsOf(\n response: PruneDiagnostics,\n originalTokens: number,\n candidateTokens: number\n): PruneDiagnostics & { readonly originalTokens: number; readonly candidateTokens: number } {\n return {\n ...(response.judgePath === undefined ? {} : { judgePath: response.judgePath }),\n ...(response.judgedSegments === undefined ? {} : { judgedSegments: response.judgedSegments }),\n ...(response.unjudgedSegments === undefined ? {} : { unjudgedSegments: response.unjudgedSegments }),\n ...(response.keptSegments === undefined ? {} : { keptSegments: response.keptSegments }),\n ...(response.aggressiveChars === undefined ? {} : { aggressiveChars: response.aggressiveChars }),\n ...(response.balancedChars === undefined ? {} : { balancedChars: response.balancedChars }),\n ...(response.conservativeChars === undefined ? {} : { conservativeChars: response.conservativeChars }),\n ...(response.scoredSegments === undefined ? {} : { scoredSegments: response.scoredSegments }),\n ...(response.autoKeptSegments === undefined ? {} : { autoKeptSegments: response.autoKeptSegments }),\n ...(response.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: response.unparsedScoreAnswers }),\n ...(response.fallbackReason === undefined ? {} : { fallbackReason: response.fallbackReason }),\n originalTokens,\n candidateTokens\n };\n}\n\n/** One remembered reduction of one payload. */\nexport interface PruneMemoEntry {\n /** The real reduction, absent until a mode computed it. */\n readonly text?: string;\n readonly originalChars: number;\n readonly prunedChars: number;\n readonly tokensSaved: number;\n /** Whether the reduction was floored, so a memo hit reports the same plan. */\n readonly floored: boolean;\n /** Whether the reduction missed the floor's promised share, replayed on a hit. */\n readonly floorMissed?: boolean;\n /** Whether that miss installed without its locator marker, replayed on a hit. */\n readonly markerOmitted?: boolean;\n /** Locator of the retained original, once a retention for this payload succeeded. */\n readonly locator?: string;\n /** Diagnostics of the judgment that composed this form, replayed on a hit. */\n readonly diagnostics?: PruneDiagnostics;\n}\n\n/** What the shared layer asks a host to retain before it replaces a payload. */\nexport interface PruneRetentionRequest {\n /** Payload identity: `digestOf(text)`. */\n readonly digest: string;\n /** Identity of the call whose result is about to shrink. */\n readonly callId: string;\n /** Name of that call. */\n readonly tool: string;\n /** Turn and step of the replacement. */\n readonly turn: number;\n readonly step: number;\n /** The replaced payload, verbatim. */\n readonly text: string;\n}\n\n/** The controlled copy one retention produced. */\nexport interface PruneRetention {\n /** Locator the replacement publishes. */\n readonly locator: string;\n /** Committed log position, when the sink can report one. */\n readonly seq?: number;\n}\n\n/** The counters one reduction spends from, and where it is deciding. */\nexport type PruneState = JudgmentState;\n\n/** A judged candidate, as the shared layer needs it. */\nexport interface PruneCandidate {\n /** The candidate text the floor composes from. */\n readonly processedOutput: string;\n /** Reduction share the service reported, recorded as the plan's confidence. */\n readonly reductionPercentage: number;\n /** Whether the service withheld the text (measured but not returned). */\n readonly shadow?: boolean;\n /** Service latency, used to split local from remote time. */\n readonly latencyMs: number;\n /** Path diagnostics, recorded only. */\n readonly diagnostics?: PruneDiagnostics;\n}\n\n/** The judgment cost of one decision. */\nexport interface PruneJudgmentCharge {\n readonly judgments: number;\n readonly memoHits: number;\n readonly localLatencyMs: number;\n readonly remoteLatencyMs: number;\n readonly judgeTokens: number;\n}\n\n/**\n * Everything the pruning decision cannot know by itself.\n *\n * {@link HostDecisionPort} answers the part every capability asks — policy,\n * counters, billing channels — but this port departs from the base in two ways,\n * and both are deliberate rather than pending:\n *\n * 1. **`skip` and `conclude` are wider here.** A pruning skip carries the\n * payload diagnostics (`digest`, `floored`, the segment counts) that make\n * \"why was nothing pruned\" answerable, and a pruning `conclude` carries the\n * four size columns and the retained locator that make a saving verifiable.\n * Narrowing either to the base signature would drop a field the audit trail\n * is defined by, so this port overrides them with the wider shape.\n * 2. **`now()` replaces `clock()`.** The pruning decision only ever needs one\n * number, taken at hook entry; handing it a port for one reading would be a\n * ceremony. The signature is structurally compatible with `ClockPort`, so a\n * host can satisfy either reading from the same source.\n *\n * The rest — `serves()`, `budget()`, `chargeJudgment()` — keeps the base\n * contract: `serves()` is answered from the effective mode, which this port\n * already exposes as `mode()`.\n */\nexport interface HostPrunePort<Result> extends HostDecisionPort<PruneState> {\n /** The effective mode of the `prune` capability. */\n mode(): 'off' | 'observe' | 'active';\n /** Whether the decision applies at all: the mode is not `off`. */\n serves(): boolean;\n /** Latest clock reading. Structurally the same reading `ClockPort` gives. */\n now(): number;\n /** Character count above which a payload is a pruning candidate. */\n threshold(): number;\n /** Floor settings in force. */\n floor(): PruneFloorSettings;\n /** The memo namespace of this agent's session. */\n memoKey(): string;\n /** One memoized reduction, refreshed on hit; `undefined` when not remembered. */\n memoGet(key: string): PruneMemoEntry | undefined;\n /** Remember one reduction. */\n memoSet(key: string, entry: PruneMemoEntry): void;\n /**\n * The locator this host's sink *will* give a payload.\n *\n * The prediction exists so both modes account for the same form: the floor\n * composes against a locator, and if the sink then names the copy differently\n * the text has to be rebuilt and the plan no longer describes what is\n * installed. Only the host knows its own naming scheme — DSH prefixes the\n * plugin record type, the Claude store hashes into a path — so this is a host\n * fact, not a shared rule.\n */\n locatorOf(digest: string): string;\n /** Ask the pruning service for a candidate. */\n judge(text: string): Promise<PruneCandidate>;\n /**\n * Retain one original and prove the copy landed.\n *\n * Returns the locator of a *verifiable* copy, or `undefined` when nothing\n * verifiable was written. A host without a sink returns a function that always\n * answers `undefined`; the shared layer then reports `retention-unavailable`\n * before it spends anything.\n */\n retain(request: PruneRetentionRequest, session: unknown): PruneRetention | undefined;\n /** Whether this host has a retention sink at all. */\n hasRetention(): boolean;\n /** The session a retention request belongs to, for a session-scoped sink. */\n session(): unknown;\n /**\n * Install `text` into the host's effective content.\n *\n * @returns the replacement the host commits, or `undefined` when there is no\n * text block to replace.\n */\n install(text: string): Result | undefined;\n /** Whether the effective content carries a text block at all. */\n hasTextBlock(): boolean;\n /** Word the operator-facing note of one reduction. */\n describe(facts: PruneFeedbackFacts): string;\n /**\n * Count one abandoned plan by reason, with the diagnostic detail it carried.\n *\n * An abandoned plan that got far enough to have a candidate is charged by the\n * host here (its judgment really ran); one refused before that is not charged\n * at all, because nothing was bought.\n */\n skip(reason: string, detail: Record<string, unknown>, judgment?: PruneJudgmentCharge): void;\n /**\n * Bill a judgment whose plan was abandoned after it was really made.\n *\n * A refusal before the service runs costs nothing and is never billed here. A\n * refusal *after* it did spend the judgment, so hiding it would understate what\n * the turn cost. `originalTokens` is the size the abandoned branch had already\n * measured, or zero when it had measured nothing.\n */\n chargeJudgment(judgment: PruneJudgmentCharge, originalTokens?: number): void;\n /**\n * Record one applied or observed plan, with the sizes it accounts for.\n *\n * This is the one place a plan is billed: `plans` +1, `applied` +1 when it\n * really took effect, and every size column from `costs`.\n */\n conclude(\n record: PrunePlanRecord,\n applied: boolean,\n costs: {\n readonly originalTokens: number;\n readonly candidateTokens: number;\n readonly potentialSavedTokens: number;\n readonly actualSavedTokens?: number;\n },\n judgment: PruneJudgmentCharge | undefined,\n originalLocator?: string\n ): void;\n /** Count one retained copy, once per payload per activation. */\n noteRetained(locator: string): void;\n /** The decision this reduction passes through when it does nothing. */\n passThrough(): Result;\n}\n\n/** What one reduction installed, for the note. */\nexport interface PruneFeedbackFacts {\n readonly tool: string;\n readonly originalTokens: number;\n readonly candidateTokens: number;\n readonly floored: boolean;\n readonly floorMissed: boolean;\n readonly markerOmitted: boolean;\n readonly locator: string;\n readonly keptSegments?: number;\n readonly judgedSegments?: number;\n}\n\n/** One planned reduction, as the host records it. */\nexport interface PrunePlanRecord {\n readonly capability: 'prune';\n readonly action: 'prune-result';\n readonly reason: string;\n feedback: string;\n readonly detail: Record<string, unknown>;\n}\n\n/** The outcome of one orchestrated decision. */\nexport interface PruneOutcome<Result> {\n /** What the host should return to its caller. */\n readonly result: Result;\n /** Whether a reduction was really installed. */\n readonly applied: boolean;\n /** The skip reason, when the decision refused to reduce. */\n readonly skip?: string;\n}\n\n/**\n * Run the one pruning decision.\n *\n * @param invocation - the call whose result is being considered, and the\n * effective text of that result.\n * @param port - everything that is the host's to answer.\n * @returns the decision the host commits.\n */\nexport async function orchestratePrune<Result>(\n invocation: {\n readonly callId: string;\n readonly tool: string;\n /** The effective text of the result (downstream first). */\n readonly text: string;\n /** Whether the rest of the waterfall blocked the result outright. */\n readonly blockedByDownstream: boolean;\n /** Whether a value-shaped accept replaced the payload wholesale. */\n readonly valueShapedAccept: boolean;\n /** Clock reading at hook entry. */\n readonly started: number;\n },\n port: HostPrunePort<Result>\n): Promise<PruneOutcome<Result>> {\n const mode = port.mode();\n if (mode === 'off') return { result: port.passThrough(), applied: false };\n // A blocked result is already not shown to the model; rewriting it is moot and\n // re-deriving its text would ignore the block.\n if (invocation.blockedByDownstream) return { result: port.passThrough(), applied: false };\n\n const text = invocation.text;\n const payloadDetail = prunePayloadDetail(text);\n\n if (invocation.valueShapedAccept) {\n // A value-shaped accept replaced the payload wholesale; nothing here knows\n // what its text is, so nothing here may touch it.\n port.skip('value-shaped-accept', {});\n return { result: port.passThrough(), applied: false, skip: 'value-shaped-accept' };\n }\n if (!port.hasTextBlock()) {\n // Nothing to replace, and nothing that could be reported as replaced. Asked\n // before the size checks: an image-only payload is not \"small\", it is out of\n // scope, and the skip reason should say so.\n port.skip('no-text-block', payloadDetail);\n return { result: port.passThrough(), applied: false, skip: 'no-text-block' };\n }\n if (text.length < port.threshold()) {\n port.skip('below-threshold', payloadDetail);\n return { result: port.passThrough(), applied: false, skip: 'below-threshold' };\n }\n if ((text.match(/\\n/g)?.length ?? 0) < PRUNE_MIN_LINES) {\n // Not line-oriented output: the judge is asked to extract diagnostics, and a\n // payload with no lines does not have any to extract. Rewriting it would\n // destroy semantic data rather than compress a trace.\n port.skip('unsupported-payload', payloadDetail);\n return { result: port.passThrough(), applied: false, skip: 'unsupported-payload' };\n }\n if (text.length > MAX_RETAINED_CHARS) {\n // Retention is a precondition of replacing anything, so an oversized payload\n // is refused *before* it is judged or reported as a saving.\n port.skip('retention-too-large', payloadDetail);\n return { result: port.passThrough(), applied: false, skip: 'retention-too-large' };\n }\n if (!port.hasRetention()) {\n // Without a retention sink nothing may be replaced: the layer will not\n // destroy the only copy of a result it cannot give back.\n port.skip('retention-unavailable', payloadDetail);\n return { result: port.passThrough(), applied: false, skip: 'retention-unavailable' };\n }\n if (!actionWithinBudget(port.budget(), port.policy())) {\n // A reduction is an intervention like a refusal or a correction, so it draws\n // on the same per-turn allowance — and it is asked here, before a judgment is\n // bought, so a full turn costs nothing to refuse. Both modes are checked:\n // observe has to plan no more actions than active could take, including the\n // ones the memo would have answered for free.\n port.skip('intervention-cap', payloadDetail);\n return { result: port.passThrough(), applied: false, skip: 'intervention-cap' };\n }\n\n const floor = port.floor();\n // Where this decision is being made travels with the counters, not with a port\n // accessor: the retention request, the audit detail and the plan all quote the\n // same two numbers this state already carries.\n const state = port.budget();\n const digest = digestOf(text);\n // The locator is derived from the payload, and a sink that names its copy the\n // same way makes the plan's size the size of the form active will install, in\n // both modes.\n const locator = port.locatorOf(digest);\n const memo = port.memoGet(`${port.memoKey()}:${digest}`);\n // A memo hit answers the question the judgment already answered; only a mode\n // that needs the reduction's *text* has to ask for it again.\n const needsCandidate = mode === 'active' && memo?.text === undefined;\n if (!memo || needsCandidate) {\n const skip = spendJudgment(port.budget(), port.policy());\n if (skip !== undefined) {\n port.skip(skip, payloadDetail);\n return { result: port.passThrough(), applied: false, skip };\n }\n }\n\n const candidate: PruneCandidate =\n memo && !needsCandidate\n ? {\n processedOutput: memo.text ?? text,\n reductionPercentage: reductionPercentageOf(memo.originalChars, memo.prunedChars),\n latencyMs: 0,\n shadow: memo.text === undefined,\n ...(memo.diagnostics ?? {})\n }\n : // Both modes take the *real* candidate, and both ask for it measure-only.\n // `shadow` only decides whether the backend hands its text back, while\n // the candidate's size is that candidate's size either way; the text is\n // what the floor composes from, so a withheld measurement would not be\n // the same input at all. Whether the payload is installed is decided\n // here, by the floor, *after* the service has written its ledger entry —\n // so this path never lets the service declare a saving.\n await port.judge(text);\n\n const originalTokens = estimateTokens(text);\n // One composition, both modes: the floored text the plan describes is the text\n // active installs, byte for byte. Line alignment and duplicate removal move its\n // real size away from the modelled one, so the number both modes account for is\n // the length of the composed text — never a prediction about it.\n const composed: PruneFloorPlan & { text: string } = applyPruneFloor(text, candidate.processedOutput, {\n floorRatio: floor.floorRatio,\n headChars: floor.headChars,\n tailChars: floor.tailChars,\n locator\n });\n const candidateTokens = Math.ceil(composed.text.length / 4);\n const diagnostics = pruneDiagnosticsOf(\n // A memo hit replays the provenance of the judgment that composed the form,\n // so a reused reduction still says which path produced it.\n memo && !needsCandidate ? (memo.diagnostics ?? {}) : (candidate.diagnostics ?? {}),\n originalTokens,\n candidateTokens\n );\n // A memo hit hands back a form that was composed for this payload already. It is\n // its own fixed point — it carries the share, so the plan of the same lengths\n // stays \"not floored\" and gives that text straight back — but its provenance is\n // not readable from those lengths any more. The memo, which was written by the\n // composition, answers for it: without this the audit would report a floored\n // install as an unfloored one.\n const reusedFromMemo = !needsCandidate && memo?.text !== undefined ? memo : undefined;\n const floorApplied = reusedFromMemo ? reusedFromMemo.floored : composed.floored;\n const floorMissed = reusedFromMemo ? reusedFromMemo.floorMissed === true : composed.floorMissed;\n const markerOmitted = reusedFromMemo ? reusedFromMemo.markerOmitted === true : composed.markerOmitted;\n const measured = {\n ...payloadDetail,\n ...diagnostics,\n floored: floorApplied,\n floorMissed,\n markerOmitted,\n candidateChars: composed.text.length\n } as Record<string, unknown>;\n const judged = !memo || needsCandidate;\n const judgment: PruneJudgmentCharge = {\n judgments: judged ? 1 : 0,\n memoHits: judged ? 0 : 1,\n localLatencyMs: Math.max(0, port.now() - invocation.started - (judged ? candidate.latencyMs : 0)),\n remoteLatencyMs: judged ? candidate.latencyMs : 0,\n // The pre-prune payload is what the pruner reasoned about; a backend call is\n // a judgment even when it returns locally in under a millisecond.\n judgeTokens: judged ? originalTokens : 0\n };\n if (candidateTokens >= originalTokens) {\n // The judgment ran and the candidate it produced was not smaller, so it is\n // charged with the size it was asked about — nothing else about this payload\n // is billed.\n port.chargeJudgment(judgment, originalTokens);\n // The branch a real \"prune: active but nothing happened\" run lands in: the\n // judgment ran, and the candidate it produced was not smaller. The record\n // says so with the path that produced it and the sizes both sides had.\n port.skip('no-reduction', measured, judgment);\n return { result: port.passThrough(), applied: false, skip: 'no-reduction' };\n }\n\n const plan: PrunePlanRecord = {\n capability: 'prune',\n action: 'prune-result',\n reason: `${invocation.tool} returned ${originalTokens} tokens; the judged reduction carries ${candidateTokens}`,\n feedback: port.describe({\n tool: invocation.tool,\n originalTokens,\n candidateTokens,\n floored: floorApplied,\n floorMissed,\n markerOmitted,\n locator,\n keptSegments: diagnostics.keptSegments,\n judgedSegments: diagnostics.judgedSegments\n }),\n detail: {\n digest,\n floorApplied,\n floorMissed,\n markerOmitted,\n confidence: candidate.reductionPercentage,\n turn: state.turn,\n step: state.step,\n ...diagnostics,\n originalChars: text.length,\n candidateChars: composed.text.length\n }\n };\n const planCosts = {\n originalTokens,\n candidateTokens,\n potentialSavedTokens: originalTokens - candidateTokens\n };\n\n if (mode !== 'active') {\n // Observe: the plan is real and charged, the surface is untouched, and the\n // memo keeps the composed form — the same form active would install, from the\n // same candidate — so a later hit reports the reduction this mode really saw.\n // A plan this mode records is the action active would have taken, so it books\n // the slot active would have booked.\n bookAction(port.budget());\n port.conclude(plan, false, planCosts, judgment);\n if (!memo) {\n port.memoSet(`${port.memoKey()}:${digest}`, {\n text: composed.text,\n originalChars: text.length,\n prunedChars: composed.text.length,\n tokensSaved: originalTokens - candidateTokens,\n floored: floorApplied,\n floorMissed,\n markerOmitted,\n diagnostics\n });\n }\n return { result: port.passThrough(), applied: false };\n }\n\n // Active. The original is retained *before* anything is replaced, and only a\n // verified retention makes the replacement installable at all. A payload whose\n // copy is already retained keeps that copy instead of writing a second one.\n const alreadyRetained = memo?.locator;\n const retention: PruneRetention | undefined = alreadyRetained\n ? { locator: alreadyRetained }\n : port.retain(\n {\n digest,\n callId: invocation.callId,\n tool: invocation.tool,\n turn: state.turn,\n step: state.step,\n text\n },\n port.session()\n );\n if (retention === undefined || typeof retention.locator !== 'string' || retention.locator.length === 0) {\n // No controlled copy, no reduction. The result stays exactly as the rest of\n // the waterfall produced it, and no saving is recorded — but the judgment\n // that got this far was really made, so it is charged rather than hidden.\n port.chargeJudgment(judgment);\n port.skip('retention-failed', measured, judgment);\n return { result: port.passThrough(), applied: false, skip: 'retention-failed' };\n }\n\n // The form both modes accounted for is the form that gets installed: the locator\n // is derived from the payload and a sink that names its copy the same way makes\n // the composition already published reusable byte for byte — with the provenance\n // the plan gave it. Only a sink that named the copy differently forces a rebuild,\n // and then the real length and provenance of that rebuild are what gets\n // accounted for.\n const installed = retention.locator === locator\n ? { ...composed, floored: floorApplied, floorMissed, markerOmitted }\n : applyPruneFloor(text, candidate.processedOutput, {\n floorRatio: floor.floorRatio,\n headChars: floor.headChars,\n tailChars: floor.tailChars,\n locator: retention.locator\n });\n if (installed.text.length === 0 || installed.text.length >= text.length) {\n // The plan said the form is smaller; the form that was really built must be\n // too, or nothing is installed and nothing is saved.\n port.skip(\n 'no-reduction',\n {\n ...measured,\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n candidateChars: installed.text.length,\n candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))\n },\n judgment\n );\n return { result: port.passThrough(), applied: false, skip: 'no-reduction' };\n }\n const replacement = port.install(installed.text);\n if (replacement === undefined) {\n port.skip(\n 'no-text-block',\n {\n ...measured,\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n candidateChars: installed.text.length,\n candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))\n },\n judgment\n );\n return { result: port.passThrough(), applied: false, skip: 'no-text-block' };\n }\n\n // Only now is there a decision that really took effect, so only now is the\n // saving recorded — against the text that is really about to enter the context.\n const installedTokens = Math.max(0, Math.ceil(installed.text.length / 4));\n plan.detail.floorApplied = installed.floored;\n plan.detail.floorMissed = installed.floorMissed;\n plan.detail.markerOmitted = installed.markerOmitted;\n plan.detail.candidateChars = installed.text.length;\n plan.feedback = port.describe({\n tool: invocation.tool,\n originalTokens,\n candidateTokens: installedTokens,\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n locator: retention.locator,\n keptSegments: diagnostics.keptSegments,\n judgedSegments: diagnostics.judgedSegments\n });\n // Booked only here: a candidate that was not smaller, a replacement that could\n // not be composed, and a retention that failed all returned above, so none of\n // them consumed the turn's allowance for an action that never happened.\n bookAction(port.budget());\n const installedCosts = {\n originalTokens,\n candidateTokens: installedTokens,\n potentialSavedTokens: originalTokens - installedTokens,\n actualSavedTokens: originalTokens - installedTokens\n };\n port.conclude(plan, true, installedCosts, judgment, retention.locator);\n // Retention is counted once per payload: a duplicate install reuses the copy\n // that is already in the log, and the locator naming it never changes.\n port.noteRetained(retention.locator);\n port.memoSet(`${port.memoKey()}:${digest}`, {\n text: installed.text,\n originalChars: text.length,\n prunedChars: installed.text.length,\n tokensSaved: originalTokens - installedTokens,\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n locator: retention.locator,\n diagnostics\n });\n return { result: replacement, applied: true };\n}\n\n/**\n * Percentage of a payload a reduction kept.\n * @param originalChars - size of the raw payload.\n * @param prunedChars - size of the reduction.\n * @returns the kept share, rounded to one decimal.\n */\nexport function reductionPercentageOf(originalChars: number, prunedChars: number): number {\n if (originalChars === 0) return 0;\n return Math.round(((originalChars - prunedChars) / originalChars) * 1000) / 10;\n}\n\n/**\n * The note of one reduction, in the default wording.\n *\n * It is meant for an operator, never for the model: a prune is supposed to remove\n * context, so sending an explanation of the removal would work against the thing\n * it accounts for. A host that shows it to a *person* may keep this wording\n * verbatim; that is why it lives here next to the facts it is built from.\n * @param facts - what the reduction did.\n * @returns the note, bounded.\n */\nexport function describeReduction(facts: PruneFeedbackFacts): string {\n const kept = facts.originalTokens === 0 ? 100 : Math.round((facts.candidateTokens / facts.originalTokens) * 100);\n const head = `Reduced ${facts.tool}: ${facts.originalTokens} → ${facts.candidateTokens} tokens (${kept}% kept). `;\n const segmentsShort =\n facts.keptSegments !== undefined && facts.judgedSegments !== undefined && facts.keptSegments < facts.judgedSegments;\n const segmentNote = segmentsShort\n ? `Kept ${facts.keptSegments}/${facts.judgedSegments} segments, omitted ${facts.judgedSegments! - facts.keptSegments!}. `\n : '';\n let body: string;\n if (facts.floored) {\n body = 'The head, the judged extract and the tail were kept; the full output was retained and is not in context.';\n } else if (facts.floorMissed) {\n const install = facts.markerOmitted\n ? 'no locator marker was added because it would not have kept the text smaller than the original'\n : 'the judged extract was installed as-is';\n body = `${segmentNote}The candidate fell short of the floor, so ${install}; the full output is retrievable as ${facts.locator}.`;\n } else if (segmentsShort) {\n body = `${segmentNote}The judged extract was installed as-is; the full output is retrievable as ${facts.locator}.`;\n } else {\n body = 'The judged extract was kept whole; the full output was retained and is not in context.';\n }\n const note = `${head}${body}`;\n return note.length <= PRUNE_FEEDBACK_CHARS ? note : `${note.slice(0, PRUNE_FEEDBACK_CHARS)}…`;\n}\n\n/** Re-exported so a host can name the same content shape the core reads. */\nexport type { TextBlockLike };\n"]}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The three-state policy and the shared action/judgment budgets.
|
|
3
|
+
*
|
|
4
|
+
* This is the harness-agnostic half of the intervention policy: given what the
|
|
5
|
+
* deployment resolved (a mode per capability, a master switch, and the ceilings)
|
|
6
|
+
* and the current turn's counters, it answers *may this capability act*, *may
|
|
7
|
+
* this judgment be spent*, and *may one more action be planned*. It knows
|
|
8
|
+
* nothing about hooks, payload shapes, or which host is calling.
|
|
9
|
+
*
|
|
10
|
+
* @module core/policy
|
|
11
|
+
*/
|
|
12
|
+
/** The three-state vocabulary every automatic capability shares. */
|
|
13
|
+
export declare const DECISION_MODES: readonly ["off", "observe", "active"];
|
|
14
|
+
/** One resolved three-state mode. */
|
|
15
|
+
export type DecisionMode = (typeof DECISION_MODES)[number];
|
|
16
|
+
/** The capability names the decision surface speaks in. */
|
|
17
|
+
export declare const DECISION_CAPABILITIES: readonly ["stagnation", "prune", "gate", "closing"];
|
|
18
|
+
/** One automatic capability name. */
|
|
19
|
+
export type DecisionCapability = (typeof DECISION_CAPABILITIES)[number];
|
|
20
|
+
/**
|
|
21
|
+
* The resolved policy the core reads.
|
|
22
|
+
*
|
|
23
|
+
* Structural on purpose: a host's own resolved config object satisfies it
|
|
24
|
+
* without importing this module's types, and the core never sees the host's
|
|
25
|
+
* configuration schema.
|
|
26
|
+
*/
|
|
27
|
+
export interface PolicySnapshot<Capability extends string = DecisionCapability> {
|
|
28
|
+
/** Master switch: when false, no capability acts whatever its own mode says. */
|
|
29
|
+
readonly enabled: boolean;
|
|
30
|
+
/** The master three-state mode. */
|
|
31
|
+
readonly mode: DecisionMode;
|
|
32
|
+
/** Effective mode of every capability. */
|
|
33
|
+
readonly capabilities: Readonly<Record<Capability, DecisionMode>>;
|
|
34
|
+
/** Ceiling on planned/applied interventions per turn. */
|
|
35
|
+
readonly maxInterventionsPerTurn: number;
|
|
36
|
+
/** Ceiling on System 1 judgments per turn. */
|
|
37
|
+
readonly maxJudgmentsPerTurn: number;
|
|
38
|
+
/** Ceiling on System 1 judgments per session. */
|
|
39
|
+
readonly maxJudgmentsPerSession: number;
|
|
40
|
+
/** Identical consecutive calls required before a judgment is bought. */
|
|
41
|
+
readonly repeatThreshold: number;
|
|
42
|
+
/** Minimum verdict confidence for an action to be justified. */
|
|
43
|
+
readonly minConfidence: number;
|
|
44
|
+
}
|
|
45
|
+
/** The counters one turn and one session spend from. */
|
|
46
|
+
export interface BudgetState {
|
|
47
|
+
/** Interventions planned or applied in the current turn. */
|
|
48
|
+
interventions: number;
|
|
49
|
+
/** Judgments spent in the current turn. */
|
|
50
|
+
judgmentsCount: number;
|
|
51
|
+
/** Judgments spent in the current session. */
|
|
52
|
+
judgmentsSession: number;
|
|
53
|
+
}
|
|
54
|
+
/** The minimal verdict shape the action gate reads. */
|
|
55
|
+
export interface VerdictLike {
|
|
56
|
+
readonly isStuck?: boolean;
|
|
57
|
+
readonly confidence: number;
|
|
58
|
+
readonly patternType?: string;
|
|
59
|
+
readonly latencyMs?: number;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Effective mode of one capability.
|
|
63
|
+
* @param policy - the resolved policy.
|
|
64
|
+
* @param capability - the capability to ask about.
|
|
65
|
+
* @returns its resolved three-state mode.
|
|
66
|
+
*/
|
|
67
|
+
export declare function modeOf<Capability extends string>(policy: PolicySnapshot<Capability>, capability: Capability): DecisionMode;
|
|
68
|
+
/**
|
|
69
|
+
* Whether a capability may run at all: the master switch is on and the capability
|
|
70
|
+
* is not `off`.
|
|
71
|
+
* @param policy - the resolved policy.
|
|
72
|
+
* @param capability - the capability to ask about.
|
|
73
|
+
* @returns whether it is observable or active.
|
|
74
|
+
*/
|
|
75
|
+
export declare function enabledCapability<Capability extends string>(policy: PolicySnapshot<Capability>, capability: Capability): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Whether a hook serving one capability set must be registered at all.
|
|
78
|
+
* @param policy - the resolved policy.
|
|
79
|
+
* @param capabilities - capabilities the hook serves.
|
|
80
|
+
* @returns whether at least one of them is not `off`.
|
|
81
|
+
*/
|
|
82
|
+
export declare function serves<Capability extends string>(policy: PolicySnapshot<Capability>, ...capabilities: Capability[]): boolean;
|
|
83
|
+
/**
|
|
84
|
+
* Whether this turn still has room for one more planned action.
|
|
85
|
+
*
|
|
86
|
+
* This is the *action* ceiling, and it is deliberately not the judgment budget:
|
|
87
|
+
* a judgment is the question System 1 was asked, this is the number of things
|
|
88
|
+
* the run is allowed to do about the answer. Every capability draws on the same
|
|
89
|
+
* allowance, and both observe and active draw on it the same way.
|
|
90
|
+
*
|
|
91
|
+
* @param state - the deciding state's counters.
|
|
92
|
+
* @param policy - the resolved policy.
|
|
93
|
+
* @returns whether one more planned action fits this turn.
|
|
94
|
+
*/
|
|
95
|
+
export declare function actionWithinBudget(state: BudgetState, policy: PolicySnapshot): boolean;
|
|
96
|
+
/**
|
|
97
|
+
* Book one planned action against the turn's shared allowance.
|
|
98
|
+
* @param state - the deciding state's counters.
|
|
99
|
+
*/
|
|
100
|
+
export declare function bookAction(state: BudgetState): void;
|
|
101
|
+
/**
|
|
102
|
+
* Spend one System 1 judgment against the turn's and the session's budget.
|
|
103
|
+
*
|
|
104
|
+
* Both budgets are spent at the one place a judgment is actually made, so a
|
|
105
|
+
* capability cannot buy its way around them by calling a service directly. The
|
|
106
|
+
* caller decides whether a refusal means "plan nothing" or "do not act"; what
|
|
107
|
+
* matters here is that the count is never overrun and that a shadowed
|
|
108
|
+
* application is charged like a real one.
|
|
109
|
+
*
|
|
110
|
+
* @param state - the deciding state's counters.
|
|
111
|
+
* @param policy - the resolved policy.
|
|
112
|
+
* @returns `undefined` when the judgment was spent, else the skip reason.
|
|
113
|
+
*/
|
|
114
|
+
export declare function spendJudgment(state: BudgetState, policy: PolicySnapshot): string | undefined;
|
|
115
|
+
/**
|
|
116
|
+
* Whether a verdict justifies acting: stuck, confident enough, and about a
|
|
117
|
+
* pattern other than `none`.
|
|
118
|
+
* @param response - the verdict.
|
|
119
|
+
* @param policy - the resolved policy (for the confidence floor).
|
|
120
|
+
* @returns whether the plan may be made.
|
|
121
|
+
*/
|
|
122
|
+
export declare function usefulVerdict(response: VerdictLike, policy: PolicySnapshot): boolean;
|