harness-reflex 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +103 -23
  3. package/USER_GUIDE.md +121 -43
  4. package/dist/adapters/agy.js +1 -1
  5. package/dist/adapters/agy.js.map +1 -1
  6. package/dist/adapters/codex.d.ts +133 -4
  7. package/dist/adapters/codex.js +325 -2
  8. package/dist/adapters/codex.js.map +1 -1
  9. package/dist/backend/defaults.d.ts +31 -0
  10. package/dist/backend/defaults.js +32 -0
  11. package/dist/backend/defaults.js.map +1 -0
  12. package/dist/backend/jev.js +6 -5
  13. package/dist/backend/jev.js.map +1 -1
  14. package/dist/backend/mock.d.ts +12 -1
  15. package/dist/backend/mock.js +34 -0
  16. package/dist/backend/mock.js.map +1 -1
  17. package/dist/backend/simple-jev.js +5 -4
  18. package/dist/backend/simple-jev.js.map +1 -1
  19. package/dist/backend/types.d.ts +34 -0
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/cli/index.js +5 -3
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/core/closing.d.ts +90 -0
  24. package/dist/core/closing.js +111 -0
  25. package/dist/core/closing.js.map +1 -0
  26. package/dist/core/evidence.d.ts +119 -0
  27. package/dist/core/evidence.js +209 -0
  28. package/dist/core/evidence.js.map +1 -0
  29. package/dist/core/judge.d.ts +221 -0
  30. package/dist/core/judge.js +251 -0
  31. package/dist/core/judge.js.map +1 -0
  32. package/dist/core/orchestrate-closing.d.ts +237 -0
  33. package/dist/core/orchestrate-closing.js +250 -0
  34. package/dist/core/orchestrate-closing.js.map +1 -0
  35. package/dist/core/orchestrate-correction.d.ts +209 -0
  36. package/dist/core/orchestrate-correction.js +141 -0
  37. package/dist/core/orchestrate-correction.js.map +1 -0
  38. package/dist/core/orchestrate-host.d.ts +225 -0
  39. package/dist/core/orchestrate-host.js +80 -0
  40. package/dist/core/orchestrate-host.js.map +1 -0
  41. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  42. package/dist/core/orchestrate-stagnation.js +270 -0
  43. package/dist/core/orchestrate-stagnation.js.map +1 -0
  44. package/dist/core/orchestrate.d.ts +357 -0
  45. package/dist/core/orchestrate.js +418 -0
  46. package/dist/core/orchestrate.js.map +1 -0
  47. package/dist/core/policy.d.ts +122 -0
  48. package/dist/core/policy.js +102 -0
  49. package/dist/core/policy.js.map +1 -0
  50. package/dist/core/prune-plan.d.ts +141 -0
  51. package/dist/core/prune-plan.js +390 -0
  52. package/dist/core/prune-plan.js.map +1 -0
  53. package/dist/core/score.d.ts +2 -2
  54. package/dist/core/score.js.map +1 -1
  55. package/dist/core/text.d.ts +36 -0
  56. package/dist/core/text.js +66 -0
  57. package/dist/core/text.js.map +1 -0
  58. package/dist/hook/cli.d.ts +9 -0
  59. package/dist/hook/cli.js +52 -0
  60. package/dist/hook/cli.js.map +1 -0
  61. package/dist/hook/contract.d.ts +125 -0
  62. package/dist/hook/contract.js +159 -0
  63. package/dist/hook/contract.js.map +1 -0
  64. package/dist/hook/decision.d.ts +97 -0
  65. package/dist/hook/decision.js +955 -0
  66. package/dist/hook/decision.js.map +1 -0
  67. package/dist/hook/memory-store.d.ts +81 -0
  68. package/dist/hook/memory-store.js +157 -0
  69. package/dist/hook/memory-store.js.map +1 -0
  70. package/dist/hook/payload.d.ts +55 -0
  71. package/dist/hook/payload.js +129 -0
  72. package/dist/hook/payload.js.map +1 -0
  73. package/dist/hook/run.d.ts +48 -0
  74. package/dist/hook/run.js +218 -0
  75. package/dist/hook/run.js.map +1 -0
  76. package/dist/hook/store-port.d.ts +72 -0
  77. package/dist/hook/store-port.js +2 -0
  78. package/dist/hook/store-port.js.map +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +1 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/ports/audit.d.ts +18 -0
  83. package/dist/ports/audit.js +11 -0
  84. package/dist/ports/audit.js.map +1 -0
  85. package/dist/ports/clock.d.ts +14 -0
  86. package/dist/ports/clock.js +11 -0
  87. package/dist/ports/clock.js.map +1 -0
  88. package/dist/ports/decision.d.ts +75 -0
  89. package/dist/ports/decision.js +2 -0
  90. package/dist/ports/decision.js.map +1 -0
  91. package/dist/ports/index.d.ts +14 -0
  92. package/dist/ports/index.js +2 -0
  93. package/dist/ports/index.js.map +1 -0
  94. package/dist/ports/log.d.ts +22 -0
  95. package/dist/ports/log.js +12 -0
  96. package/dist/ports/log.js.map +1 -0
  97. package/dist/ports/state.d.ts +46 -0
  98. package/dist/ports/state.js +13 -0
  99. package/dist/ports/state.js.map +1 -0
  100. package/dist/state/clock.d.ts +40 -0
  101. package/dist/state/clock.js +43 -0
  102. package/dist/state/clock.js.map +1 -0
  103. package/dist/state/file-store.d.ts +340 -0
  104. package/dist/state/file-store.js +849 -0
  105. package/dist/state/file-store.js.map +1 -0
  106. package/dist/state/paths.d.ts +41 -0
  107. package/dist/state/paths.js +73 -0
  108. package/dist/state/paths.js.map +1 -0
  109. package/docs/USER_GUIDE.en.md +79 -36
  110. package/docs/claude-code.md +281 -0
  111. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  112. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  113. package/docs/dsh-plugin.md +54 -54
  114. package/docs/release-checklist-v0.1.0.md +32 -21
  115. package/docs/release-handbook-porting-notes.md +11 -11
  116. package/docs/release-handbook.md +55 -30
  117. package/docs/release-notes-v0.1.0.md +27 -14
  118. package/docs/release-notes-v0.3.0.md +152 -0
  119. package/docs/research/claude-code-harness.md +607 -0
  120. package/docs/research/pi-harness.md +621 -0
  121. package/package.json +16 -7
@@ -0,0 +1,209 @@
1
+ /**
2
+ * The shared orchestration of the failure-correction decision.
3
+ *
4
+ * The third of the three lifts: {@link ./orchestrate} owns when a result is
5
+ * reduced, {@link ./orchestrate-stagnation} owns when a call is refused and when
6
+ * a step is corrected, and this one owns what happens to a result that *failed* —
7
+ * the run is retrying an operation that keeps failing, and what the model is
8
+ * about to read is the failure again rather than the reason it keeps failing.
9
+ *
10
+ * ```
11
+ * agent/turn-stopping / tools/pre-execute (not this module)
12
+ *
13
+ * tools/post-execute
14
+ * downstream first, always
15
+ * → off / own tool / the result of a call this layer refused → hand it back
16
+ * → [the host records the step and reports the result failed]
17
+ * → not a failure → this decision does not apply
18
+ * → downstream blocked the result → hand it back
19
+ * → the cheap trigger (the trailing failing run) → not suspicious → hand it back
20
+ * → already corrected this episode → duplicate-intervention
21
+ * → the turn's action allowance is spent → intervention-cap
22
+ * → buy a judgment (memo first, budgets inside)
23
+ * → not useful → charge it, record why, hand it back
24
+ * → latch the episode, book the action, conclude
25
+ * → rewrite the result *only* in active mode
26
+ * ```
27
+ *
28
+ * ## What is shared and what is not
29
+ *
30
+ * Shared here: the order above, every skip reason, the budget rules
31
+ * (`actionWithinBudget`, `bookAction`, the judgment memo), the latch, the shape
32
+ * of the audit detail, and the *decision* that an active mode rewrites the result.
33
+ *
34
+ * *Not* shared here: whether a result counts as a failure (the host's own reading
35
+ * of `isError`, a structured exit status, or an exit marker in the text), the
36
+ * window it is measured on and what a legitimate wait removes from it (the host
37
+ * records steps and hands over the value — {@link progressSteps} is applied by
38
+ * the caller, and the DSH host deliberately does *not* apply it here, because a
39
+ * failing poll is still a failure), the wording the model reads, and the concrete
40
+ * shape of a rewritten result.
41
+ *
42
+ * ## The strength of the action is the host's, the decision is not
43
+ *
44
+ * A correction has no single strength. The DSH engine answers with
45
+ * `kind: 'block'` and a feedback list, which replaces the result outright; a
46
+ * command hook answers with `additionalContext` next to the result it did not
47
+ * touch. The shared layer therefore decides *whether* the correction applies and
48
+ * *what it says*, and leaves *how strongly* to be expressed to {@link
49
+ * CorrectionPort#apply}: an observation of the same decision is exactly the plan
50
+ * that reaches the log in both modes, and installing it is the only thing the
51
+ * mode gates.
52
+ *
53
+ * For the same reason this module states no permission-monotonicity rule. A
54
+ * refusal is a permission and may not be added to anything stricter than an
55
+ * allow — that rule lives in one place, {@link mayAddDecision}. A correction is
56
+ * text shown to the model about a result that already happened; it grants and
57
+ * denies nothing, so there is no decision it could weaken. The one decision it
58
+ * must not overwrite is a result the rest of the waterfall *blocked*, and that is
59
+ * an early return rather than a rule about kinds.
60
+ *
61
+ * ## Why the host supplies the window, not a store
62
+ *
63
+ * The same reason as the other two modules: the DSH engine keeps its window in
64
+ * the agent's own bookkeeping and hands the shared layer a value, while a host
65
+ * that derives it from a persisted log hands over a different value. Neither has
66
+ * to teach the shared layer how it stores anything; the only thing the shared
67
+ * layer mutates is the counters it is given, through {@link BudgetState}.
68
+ *
69
+ * @module core/orchestrate-correction
70
+ */
71
+ import type { StagnationCheckResponse } from '../backend/types.js';
72
+ import { type ObservedStep, type StagnationSuspicion, type VerdictMemoState } from './judge.js';
73
+ import type { HostBillingPort, HostDecisionPort, HostJudgmentPort } from './orchestrate-host.js';
74
+ /** The capability every decision in this module belongs to. */
75
+ export declare const CORRECTION_CAPABILITY: "gate";
76
+ /** The audit action a correction is recorded under. */
77
+ export declare const CORRECTION_ACTION: "corrective-feedback";
78
+ /** What one orchestrated decision turned out to be. */
79
+ export type CorrectionAction = 'corrected' | 'pass-through';
80
+ /** The judgment cost of one decision, as the host bills it. */
81
+ export interface JudgedCharge {
82
+ readonly judgments: number;
83
+ readonly memoHits: number;
84
+ readonly localLatencyMs: number;
85
+ readonly remoteLatencyMs: number;
86
+ readonly judgeTokens: number;
87
+ }
88
+ /** One planned correction, as the host records it. */
89
+ export interface CorrectionPlanRecord {
90
+ readonly capability: typeof CORRECTION_CAPABILITY;
91
+ readonly action: typeof CORRECTION_ACTION;
92
+ readonly reason: string;
93
+ feedback: string;
94
+ readonly detail: Record<string, unknown>;
95
+ }
96
+ /** What one correction was built from. */
97
+ export interface CorrectionFeedbackFacts {
98
+ /** Name of the call that failed. */
99
+ readonly tool: string;
100
+ /** The failure text the host reads off the result, for quoting. */
101
+ readonly error: string;
102
+ /** The cheap-path trigger. */
103
+ readonly suspicion: StagnationSuspicion;
104
+ /** What System 1 answered. */
105
+ readonly verdict: StagnationCheckResponse;
106
+ }
107
+ /**
108
+ * The counters one correction spends from and books against.
109
+ *
110
+ * The verdict cache is part of the budget state because a cached answer is what
111
+ * makes a second question in the same turn free: this path shares that cache with
112
+ * the stagnation capability, so it reads it through here rather than keeping a
113
+ * second copy. The place in the run (`turn`, `step`) and the counters both come
114
+ * from the judge's state, so a correction adds no field of its own to either.
115
+ */
116
+ export type CorrectionState = VerdictMemoState;
117
+ /**
118
+ * Everything the shared layer cannot know by itself.
119
+ *
120
+ * {@link HostDecisionPort} answers the part every capability asks — policy,
121
+ * counters, clock, switch, and the three billing channels — so this interface
122
+ * states only what a *correction* additionally needs.
123
+ */
124
+ export interface HostCorrectionPort<Result> extends HostDecisionPort<CorrectionState>, HostBillingPort<JudgedCharge, CorrectionPlanRecord>, HostJudgmentPort<StagnationCheckResponse> {
125
+ /** Name of the call whose result is being decided. */
126
+ toolName(): string;
127
+ /** The failure text, as the model would read it. */
128
+ error(): string;
129
+ /**
130
+ * The window the trigger is measured on.
131
+ *
132
+ * The host's, deliberately: it is the one value the three capabilities can
133
+ * disagree about, and the disagreement is real — a failing poll is a failure
134
+ * even though a wait is not progress.
135
+ */
136
+ window(): readonly ObservedStep[];
137
+ /** The identity this decision is about. */
138
+ signature(): string;
139
+ /**
140
+ * The cheap trigger over one window.
141
+ *
142
+ * `PolicySnapshot` carries the repetition threshold, the confidence floor and
143
+ * the judgment budgets — the numbers the *budget* rules are stated in — but the
144
+ * failure threshold and the window size are trigger parameters, and the host
145
+ * owns their values.
146
+ */
147
+ suspicion(steps: readonly ObservedStep[]): StagnationSuspicion;
148
+ /** Whether this identity was already corrected on this turn. */
149
+ alreadyCorrected(): boolean;
150
+ /** Latch this identity as corrected. */
151
+ latchCorrected(): void;
152
+ /** The result to hand back when nothing is done. */
153
+ passThrough(): Result;
154
+ /**
155
+ * The result to hand back when the correction applies.
156
+ *
157
+ * How strong this is — a replacement, an added context, or nothing at all
158
+ * because the host is only observing — is the host's to decide, and it is why
159
+ * this is a callback rather than a kind the shared layer picks.
160
+ */
161
+ apply(feedback: string): Result;
162
+ /** Word the correction handed to the model. */
163
+ describe(facts: CorrectionFeedbackFacts): string;
164
+ }
165
+ /** The outcome of one orchestrated decision. */
166
+ export interface CorrectionOutcome<Result> {
167
+ /** What the host should return to its caller. */
168
+ readonly result: Result;
169
+ /** What the decision was. */
170
+ readonly action: CorrectionAction;
171
+ /** The skip reason, when the decision refused to correct. */
172
+ readonly skip?: string;
173
+ }
174
+ /**
175
+ * `tools/post-execute`: rewrite a result the run keeps failing to change.
176
+ *
177
+ * The host calls this **after** its own `next()`, and hands over what that
178
+ * returned: a result the rest of the waterfall blocked is already unreadable, so
179
+ * rewriting it would be inventing a surface nobody asked for.
180
+ *
181
+ * @param invocation - the downstream decision, the signal, and the failure facts.
182
+ * @param port - everything that is the host's to answer.
183
+ * @returns the result the host commits.
184
+ */
185
+ export declare function orchestrateCorrection<Result>(invocation: {
186
+ /** Whether the result is one this layer reads as a failure. */
187
+ readonly failed: boolean;
188
+ /** Whether the rest of the waterfall blocked the result outright. */
189
+ readonly blockedByDownstream: boolean;
190
+ /** The result's abort signal, if it has one. */
191
+ readonly signal?: AbortSignal;
192
+ }, port: HostCorrectionPort<Result>): Promise<CorrectionOutcome<Result>>;
193
+ /**
194
+ * The correction's wording, in the default form.
195
+ *
196
+ * Exported because a host that shows the text to the same audience may keep it
197
+ * verbatim; a host that words it differently supplies its own through the port.
198
+ * The two clippings are the shared part: an error is quoted at 160 characters and
199
+ * the advice at 240, both with whitespace collapsed, so a multi-line stack can
200
+ * never make the correction unbounded.
201
+ * @param facts - what the correction is built from.
202
+ * @param limits - the two budget lengths.
203
+ * @returns the text handed to the model.
204
+ */
205
+ export declare function describeCorrection(facts: CorrectionFeedbackFacts, limits: {
206
+ readonly errorChars: number;
207
+ readonly adviceChars: number;
208
+ readonly totalChars: number;
209
+ }): string;
@@ -0,0 +1,141 @@
1
+ import { judgmentCharge, runJudgment } from './judge.js';
2
+ import { actionWithinBudget, bookAction, modeOf } from './policy.js';
3
+ import { clip } from './text.js';
4
+ /** The capability every decision in this module belongs to. */
5
+ export const CORRECTION_CAPABILITY = 'gate';
6
+ /** The audit action a correction is recorded under. */
7
+ export const CORRECTION_ACTION = 'corrective-feedback';
8
+ /**
9
+ * The charge of one judgment, through the core's own billing rule.
10
+ * @param outcome - the judgment's outcome.
11
+ * @param started - clock reading at hook entry.
12
+ * @param now - clock reading now.
13
+ * @returns the charge the host records.
14
+ */
15
+ function chargeOf(outcome, started, now) {
16
+ return judgmentCharge(outcome, started, now);
17
+ }
18
+ /**
19
+ * The detail every correction record carries.
20
+ *
21
+ * Kept identical to the correction this module replaced, so an audit trail
22
+ * written before and after the lift reads the same: a reader comparing two
23
+ * sessions must not be able to tell which engine produced which.
24
+ * @param suspicion - the cheap-path trigger.
25
+ * @param verdict - what System 1 answered.
26
+ * @param turn - the deciding turn.
27
+ * @param step - the deciding step.
28
+ * @returns the audit fields.
29
+ */
30
+ function detailOf(suspicion, verdict, turn, step) {
31
+ return {
32
+ pattern: String(verdict.patternType ?? suspicion.pattern ?? 'unknown'),
33
+ confidence: verdict.confidence,
34
+ repeats: suspicion.repeats,
35
+ turn,
36
+ step
37
+ };
38
+ }
39
+ /**
40
+ * `tools/post-execute`: rewrite a result the run keeps failing to change.
41
+ *
42
+ * The host calls this **after** its own `next()`, and hands over what that
43
+ * returned: a result the rest of the waterfall blocked is already unreadable, so
44
+ * rewriting it would be inventing a surface nobody asked for.
45
+ *
46
+ * @param invocation - the downstream decision, the signal, and the failure facts.
47
+ * @param port - everything that is the host's to answer.
48
+ * @returns the result the host commits.
49
+ */
50
+ export async function orchestrateCorrection(invocation, port) {
51
+ const passThrough = (skip) => ({
52
+ result: port.passThrough(),
53
+ action: 'pass-through',
54
+ ...(skip === undefined ? {} : { skip })
55
+ });
56
+ const mode = modeOf(port.policy(), CORRECTION_CAPABILITY);
57
+ if (mode === 'off' || !port.serves())
58
+ return passThrough();
59
+ if (!invocation.failed)
60
+ return passThrough();
61
+ // A result the rest of the waterfall blocked never reaches the model, so there
62
+ // is nothing here to correct. Asked first: it is the cheapest refusal and it
63
+ // must not be able to spend a judgment.
64
+ if (invocation.blockedByDownstream)
65
+ return passThrough();
66
+ const signature = port.signature();
67
+ const suspicion = port.suspicion(port.window());
68
+ if (!suspicion.suspicious)
69
+ return passThrough();
70
+ // The latch is asked in the same breath as the trigger, and only reports when
71
+ // the episode was real: a correction that never happened is not a duplicate of
72
+ // anything, and a record claiming it was would misdescribe the turn.
73
+ if (port.alreadyCorrected()) {
74
+ port.skip('duplicate-intervention');
75
+ return passThrough('duplicate-intervention');
76
+ }
77
+ if (!actionWithinBudget(port.budget(), port.policy())) {
78
+ port.skip('intervention-cap');
79
+ return passThrough('intervention-cap');
80
+ }
81
+ const policy = port.policy();
82
+ const started = port.clock().now();
83
+ const outcome = await runJudgment({
84
+ state: port.budget(),
85
+ policy,
86
+ buy: (step) => port.buy(step),
87
+ clock: port.clock(),
88
+ steps: port.window(),
89
+ ...(invocation.signal === undefined ? {} : { signal: invocation.signal })
90
+ });
91
+ const charge = chargeOf(outcome, started, port.clock().now());
92
+ if (!outcome.useful) {
93
+ // A budget/abort skip keeps its own reason. The judgment really ran, so it is
94
+ // charged rather than hidden — an abandoned paid plan is still a cost.
95
+ port.chargeJudgment(charge);
96
+ const skip = outcome.skip ?? 'unconfirmed';
97
+ port.skip(skip, charge);
98
+ return passThrough(skip);
99
+ }
100
+ const facts = {
101
+ tool: port.toolName(),
102
+ error: port.error(),
103
+ suspicion,
104
+ verdict: outcome.response
105
+ };
106
+ const plan = {
107
+ capability: CORRECTION_CAPABILITY,
108
+ action: CORRECTION_ACTION,
109
+ reason: `${port.toolName()} failed ${suspicion.repeats} times; System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern}`,
110
+ feedback: port.describe(facts),
111
+ detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)
112
+ };
113
+ const applies = mode === 'active';
114
+ // The latch is mode-independent on purpose. Observe has to consume the same
115
+ // episode — one correction per failure episode, one charge against the turn's
116
+ // cap — or its accounting would describe a run nobody could reproduce; the
117
+ // model-visible rewrite is the only thing the mode gates.
118
+ port.latchCorrected();
119
+ bookAction(port.budget());
120
+ port.conclude(plan, applies, charge);
121
+ return applies ? { result: port.apply(plan.feedback), action: 'corrected' } : passThrough();
122
+ }
123
+ /**
124
+ * The correction's wording, in the default form.
125
+ *
126
+ * Exported because a host that shows the text to the same audience may keep it
127
+ * verbatim; a host that words it differently supplies its own through the port.
128
+ * The two clippings are the shared part: an error is quoted at 160 characters and
129
+ * the advice at 240, both with whitespace collapsed, so a multi-line stack can
130
+ * never make the correction unbounded.
131
+ * @param facts - what the correction is built from.
132
+ * @param limits - the two budget lengths.
133
+ * @returns the text handed to the model.
134
+ */
135
+ export function describeCorrection(facts, limits) {
136
+ const advice = clip((facts.verdict.recommendedIntervention ?? '').replace(/\s+/g, ' ').trim(), limits.adviceChars);
137
+ return clip(`Reflex intervention: ${facts.tool} failed ${facts.suspicion.repeats} consecutive times with ${clip(facts.error.replace(/\s+/g, ' ').trim(), limits.errorChars)}. ` +
138
+ `System 1 confirms ${facts.verdict.patternType ?? facts.suspicion.pattern} (confidence ${facts.verdict.confidence.toFixed(2)}). ` +
139
+ `This result is treated as a policy failure: change the command or the code before retrying. ${advice}`, limits.totalChars);
140
+ }
141
+ //# sourceMappingURL=orchestrate-correction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestrate-correction.js","sourceRoot":"","sources":["../../src/core/orchestrate-correction.ts"],"names":[],"mappings":"AAuEA,OAAO,EACL,cAAc,EACd,WAAW,EAKZ,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,EAAuB,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,+DAA+D;AAC/D,MAAM,CAAC,MAAM,qBA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I,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IACrC,OAAO,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9F,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,kBAAkB,CAChC,KAA8B,EAC9B,MAAkG;IAElG,MAAM,MAAM,GAAG,IAAI,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,uBAAuB,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;IACnH,OAAO,IAAI,CACT,wBAAwB,KAAK,CAAC,IAAI,WAAW,KAAK,CAAC,SAAS,CAAC,OAAO,2BAA2B,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,UAAU,CAAC,IAAI;QACjK,qBAAqB,KAAK,CAAC,OAAO,CAAC,WAAW,IAAI,KAAK,CAAC,SAAS,CAAC,OAAO,gBAAgB,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK;QACjI,+FAA+F,MAAM,EAAE,EACzG,MAAM,CAAC,UAAU,CAClB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The shared orchestration of the failure-correction decision.\n *\n * The third of the three lifts: {@link ./orchestrate} owns when a result is\n * reduced, {@link ./orchestrate-stagnation} owns when a call is refused and when\n * a step is corrected, and this one owns what happens to a result that *failed* —\n * the run is retrying an operation that keeps failing, and what the model is\n * about to read is the failure again rather than the reason it keeps failing.\n *\n * ```\n * agent/turn-stopping / tools/pre-execute (not this module)\n *\n * tools/post-execute\n * downstream first, always\n * → off / own tool / the result of a call this layer refused → hand it back\n * → [the host records the step and reports the result failed]\n * → not a failure → this decision does not apply\n * → downstream blocked the result → hand it back\n * → the cheap trigger (the trailing failing run) → not suspicious → hand it back\n * → already corrected 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 episode, book the action, conclude\n * → rewrite the result *only* in active mode\n * ```\n *\n * ## What is shared and what is not\n *\n * Shared here: the order above, every skip reason, the budget rules\n * (`actionWithinBudget`, `bookAction`, the judgment memo), the latch, the shape\n * of the audit detail, and the *decision* that an active mode rewrites the result.\n *\n * *Not* shared here: whether a result counts as a failure (the host's own reading\n * of `isError`, a structured exit status, or an exit marker in the text), the\n * window it is measured on and what a legitimate wait removes from it (the host\n * records steps and hands over the value — {@link progressSteps} is applied by\n * the caller, and the DSH host deliberately does *not* apply it here, because a\n * failing poll is still a failure), the wording the model reads, and the concrete\n * shape of a rewritten result.\n *\n * ## The strength of the action is the host's, the decision is not\n *\n * A correction has no single strength. The DSH engine answers with\n * `kind: 'block'` and a feedback list, which replaces the result outright; a\n * command hook answers with `additionalContext` next to the result it did not\n * touch. The shared layer therefore decides *whether* the correction applies and\n * *what it says*, and leaves *how strongly* to be expressed to {@link\n * CorrectionPort#apply}: an observation of the same decision is exactly the plan\n * that reaches the log in both modes, and installing it is the only thing the\n * mode gates.\n *\n * For the same reason this module states no permission-monotonicity rule. A\n * refusal is a permission and may not be added to anything stricter than an\n * allow — that rule lives in one place, {@link mayAddDecision}. A correction is\n * text shown to the model about a result that already happened; it grants and\n * denies nothing, so there is no decision it could weaken. The one decision it\n * must not overwrite is a result the rest of the waterfall *blocked*, and that is\n * an early return rather than a rule about kinds.\n *\n * ## Why the host supplies the window, not a store\n *\n * The same reason as the other two modules: the DSH engine keeps its window in\n * the agent's own bookkeeping and hands the shared layer a value, while a host\n * that derives it from a persisted log hands over a different value. Neither has\n * to teach the shared layer how it stores anything; the only thing the shared\n * layer mutates is the counters it is given, through {@link BudgetState}.\n *\n * @module core/orchestrate-correction\n */\nimport type { StagnationCheckResponse } from '../backend/types.js';\nimport {\n judgmentCharge,\n runJudgment,\n type JudgmentOutcome,\n type ObservedStep,\n type StagnationSuspicion,\n type VerdictMemoState\n} from './judge.js';\nimport type { HostBillingPort, HostDecisionPort, HostJudgmentPort } from './orchestrate-host.js';\nimport { actionWithinBudget, bookAction, modeOf, type PolicySnapshot } from './policy.js';\nimport { clip } from './text.js';\n\n/** The capability every decision in this module belongs to. */\nexport const CORRECTION_CAPABILITY = 'gate' as const;\n\n/** The audit action a correction is recorded under. */\nexport const CORRECTION_ACTION = 'corrective-feedback' as const;\n\n/** What one orchestrated decision turned out to be. */\nexport type CorrectionAction = 'corrected' | 'pass-through';\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 correction, as the host records it. */\nexport interface CorrectionPlanRecord {\n readonly capability: typeof CORRECTION_CAPABILITY;\n readonly action: typeof CORRECTION_ACTION;\n readonly reason: string;\n feedback: string;\n readonly detail: Record<string, unknown>;\n}\n\n/** What one correction was built from. */\nexport interface CorrectionFeedbackFacts {\n /** Name of the call that failed. */\n readonly tool: string;\n /** The failure text the host reads off the result, for quoting. */\n readonly error: string;\n /** The cheap-path trigger. */\n readonly suspicion: StagnationSuspicion;\n /** What System 1 answered. */\n readonly verdict: StagnationCheckResponse;\n}\n\n/**\n * The counters one correction 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: this path shares that cache with\n * the stagnation capability, so it reads it through here rather than keeping a\n * second copy. The place in the run (`turn`, `step`) and the counters both come\n * from the judge's state, so a correction adds no field of its own to either.\n */\nexport type CorrectionState = VerdictMemoState;\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 *correction* additionally needs.\n */\nexport interface HostCorrectionPort<Result>\n extends HostDecisionPort<CorrectionState>,\n HostBillingPort<JudgedCharge, CorrectionPlanRecord>,\n HostJudgmentPort<StagnationCheckResponse> {\n /** Name of the call whose result is being decided. */\n toolName(): string;\n /** The failure text, as the model would read it. */\n error(): string;\n /**\n * The window the trigger is measured on.\n *\n * The host's, deliberately: it is the one value the three capabilities can\n * disagree about, and the disagreement is real — a failing poll is a failure\n * even though a wait is not progress.\n */\n window(): readonly 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, the confidence floor and\n * the judgment budgets — the numbers the *budget* rules are stated in — but the\n * failure threshold and the window size are trigger parameters, and the host\n * owns their values.\n */\n suspicion(steps: readonly ObservedStep[]): StagnationSuspicion;\n /** Whether this identity was already corrected on this turn. */\n alreadyCorrected(): boolean;\n /** Latch this identity as corrected. */\n latchCorrected(): void;\n /** The result to hand back when nothing is done. */\n passThrough(): Result;\n /**\n * The result to hand back when the correction applies.\n *\n * How strong this is — a replacement, an added context, or nothing at all\n * because the host is only observing — is the host's to decide, and it is why\n * this is a callback rather than a kind the shared layer picks.\n */\n apply(feedback: string): Result;\n /** Word the correction handed to the model. */\n describe(facts: CorrectionFeedbackFacts): string;\n}\n\n/** The outcome of one orchestrated decision. */\nexport interface CorrectionOutcome<Result> {\n /** What the host should return to its caller. */\n readonly result: Result;\n /** What the decision was. */\n readonly action: CorrectionAction;\n /** The skip reason, when the decision refused to correct. */\n readonly skip?: string;\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 correction record carries.\n *\n * Kept identical to the correction this module replaced, so an audit trail\n * written before and after the lift reads the same: a reader comparing two\n * sessions must not be able to tell which engine produced which.\n * @param suspicion - the cheap-path trigger.\n * @param verdict - what System 1 answered.\n * @param turn - the deciding turn.\n * @param step - the deciding step.\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/post-execute`: rewrite a result the run keeps failing to change.\n *\n * The host calls this **after** its own `next()`, and hands over what that\n * returned: a result the rest of the waterfall blocked is already unreadable, so\n * rewriting it would be inventing a surface nobody asked for.\n *\n * @param invocation - the downstream decision, the signal, and the failure facts.\n * @param port - everything that is the host's to answer.\n * @returns the result the host commits.\n */\nexport async function orchestrateCorrection<Result>(\n invocation: {\n /** Whether the result is one this layer reads as a failure. */\n readonly failed: boolean;\n /** Whether the rest of the waterfall blocked the result outright. */\n readonly blockedByDownstream: boolean;\n /** The result's abort signal, if it has one. */\n readonly signal?: AbortSignal;\n },\n port: HostCorrectionPort<Result>\n): Promise<CorrectionOutcome<Result>> {\n const passThrough = (skip?: string): CorrectionOutcome<Result> => ({\n result: port.passThrough(),\n action: 'pass-through',\n ...(skip === undefined ? {} : { skip })\n });\n\n const mode = modeOf(port.policy(), CORRECTION_CAPABILITY);\n if (mode === 'off' || !port.serves()) return passThrough();\n if (!invocation.failed) return passThrough();\n // A result the rest of the waterfall blocked never reaches the model, so there\n // is nothing here to correct. Asked first: it is the cheapest refusal and it\n // must not be able to spend a judgment.\n if (invocation.blockedByDownstream) return passThrough();\n\n const signature = port.signature();\n const suspicion = port.suspicion(port.window());\n if (!suspicion.suspicious) return passThrough();\n // The latch is asked in the same breath as the trigger, and only reports when\n // the episode was real: a correction that never happened is not a duplicate of\n // anything, and a record claiming it was would misdescribe the turn.\n if (port.alreadyCorrected()) {\n port.skip('duplicate-intervention');\n return passThrough('duplicate-intervention');\n }\n if (!actionWithinBudget(port.budget(), port.policy())) {\n port.skip('intervention-cap');\n return passThrough('intervention-cap');\n }\n\n const policy = port.policy();\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: port.window(),\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal })\n });\n const charge = chargeOf(outcome, started, port.clock().now());\n if (!outcome.useful) {\n // A budget/abort skip keeps its own reason. The judgment really ran, so it is\n // charged rather than hidden — an abandoned paid plan is still a cost.\n port.chargeJudgment(charge);\n const skip = outcome.skip ?? 'unconfirmed';\n port.skip(skip, charge);\n return passThrough(skip);\n }\n\n const facts: CorrectionFeedbackFacts = {\n tool: port.toolName(),\n error: port.error(),\n suspicion,\n verdict: outcome.response\n };\n const plan: CorrectionPlanRecord = {\n capability: CORRECTION_CAPABILITY,\n action: CORRECTION_ACTION,\n reason: `${port.toolName()} failed ${suspicion.repeats} times; System 1 confirmed ${\n outcome.response.patternType ?? suspicion.pattern\n }`,\n feedback: port.describe(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 correction per failure episode, one charge against the turn's\n // cap — or its accounting would describe a run nobody could reproduce; the\n // model-visible rewrite is the only thing the mode gates.\n port.latchCorrected();\n bookAction(port.budget());\n port.conclude(plan, applies, charge);\n return applies ? { result: port.apply(plan.feedback), action: 'corrected' } : passThrough();\n}\n\n/**\n * The correction's wording, in the default form.\n *\n * Exported because a host that shows the text to the same audience may keep it\n * verbatim; a host that words it differently supplies its own through the port.\n * The two clippings are the shared part: an error is quoted at 160 characters and\n * the advice at 240, both with whitespace collapsed, so a multi-line stack can\n * never make the correction unbounded.\n * @param facts - what the correction is built from.\n * @param limits - the two budget lengths.\n * @returns the text handed to the model.\n */\nexport function describeCorrection(\n facts: CorrectionFeedbackFacts,\n limits: { readonly errorChars: number; readonly adviceChars: number; readonly totalChars: number }\n): string {\n const advice = clip((facts.verdict.recommendedIntervention ?? '').replace(/\\s+/g, ' ').trim(), limits.adviceChars);\n return clip(\n `Reflex intervention: ${facts.tool} failed ${facts.suspicion.repeats} consecutive times with ${clip(facts.error.replace(/\\s+/g, ' ').trim(), limits.errorChars)}. ` +\n `System 1 confirms ${facts.verdict.patternType ?? facts.suspicion.pattern} (confidence ${facts.verdict.confidence.toFixed(2)}). ` +\n `This result is treated as a policy failure: change the command or the code before retrying. ${advice}`,\n limits.totalChars\n );\n}\n"]}
@@ -0,0 +1,225 @@
1
+ /**
2
+ * The decisions every orchestrated capability asks its host for.
3
+ *
4
+ * ## Why this exists
5
+ *
6
+ * Four capabilities now share one orchestration layer (prune, stagnation,
7
+ * correction, closing), and each of them asks its host the same handful of
8
+ * questions: what policy is in force, which counters may move, how one abandoned
9
+ * plan is recorded, how one plan is billed. Before this module, each `Host*Port`
10
+ * re-declared that surface in its own words. The declarations agreed, but
11
+ * nothing *made* them agree — a fourth capability would have been the fourth copy,
12
+ * and a divergence between two ports meant to be the same would have had nowhere
13
+ * to be caught.
14
+ *
15
+ * The shared surface is stated once, here. It is deliberately split into two
16
+ * interfaces rather than one, because the corpus of four ports showed the two
17
+ * halves have different reach:
18
+ *
19
+ * | Interface | Members | Who extends it |
20
+ * |---|---|---|
21
+ * | {@link HostDecisionPort} | `policy`, `budget`, `clock`/`now`, `serves` | **all four** |
22
+ * | {@link HostBillingPort} | `skip`, `chargeJudgment`, `conclude` | the three that bill the same way |
23
+ *
24
+ * ## Why the billing channels are a second interface
25
+ *
26
+ * The judgment capabilities (stagnation, correction, closing) record an abandoned
27
+ * plan as "reason + the judgment it cost" and bill an applied plan as "record +
28
+ * applied + the judgment it rode on". All three are literally the same two calls,
29
+ * so they share {@link HostBillingPort}.
30
+ *
31
+ * Pruning is **not** one of them, and this is the finding that stopped this batch
32
+ * from collapsing everything into one interface. Its two billing channels are
33
+ * genuinely wider:
34
+ *
35
+ * - `skip(reason, detail, judgment?)` — the `detail` is not a charge. It carries
36
+ * the payload diagnostics (`digest`, `floored`, `floorMissed`, the segment
37
+ * counts) that make *"why was nothing pruned"* answerable. Those fields are the
38
+ * reason the pruning audit trail exists at all.
39
+ * - `conclude(plan, applied, costs, judgment?, locator?)` — `costs` carries the
40
+ * four size columns and the retained locator, i.e. every number that makes a
41
+ * claimed saving *verifiable*. Collapsing it into the judgment-capability shape
42
+ * would silently drop them.
43
+ *
44
+ * Fitting pruning to the common shape would therefore have required either
45
+ * deleting audit fields or making the base `skip(reason, x?: unknown)`, which
46
+ * buys nothing: every caller would cast, and the one place a wrong answer is a
47
+ * model-visible regression would be the place the type stopped helping. Both were
48
+ * rejected. Pruning extends only {@link HostDecisionPort}, states its two wider
49
+ * channels in its own interface, and the divergence is documented there.
50
+ *
51
+ * ## The judgment is bought, not fetched
52
+ *
53
+ * A port never hands over a backend. It answers **one purchase at a time** —
54
+ * {@link HostJudgmentPort#buy} for the stagnation verdict (bought by both the
55
+ * stagnation and the correction capability, which ask the same question of the
56
+ * same service), `classify`/`verify` for closing's two-request judgment, and
57
+ * `judge(payload)` for pruning's reduction.
58
+ *
59
+ * The distinction matters because a port that exposes `backend()` forces every
60
+ * caller to re-implement the purchase: the memo key, the budget check, the
61
+ * local/remote latency split, and the billing. Those four are the shared layer's
62
+ * — {@link ../judge.runJudgment} and each capability's own accounting — and they
63
+ * are stated once. A host answers only "what did the service say, and how long
64
+ * did it wait".
65
+ *
66
+ * ### One buy is one request; one charge may be several buys
67
+ *
68
+ * The unit of `buy` is the *request*, not the bill. The closing check buys twice
69
+ * from one capability — a classification of the turn's sentences, then a
70
+ * verification of the claims that classification accepted — but bills them as a
71
+ * single {@link JudgmentCost} against the single slot the turn budget granted.
72
+ * That fold is the shared layer's (`orchestrateClosing`), which is exactly why
73
+ * the closing port must not be collapsing the two requests into one method: the
74
+ * latency split and the token sum belong where the charge is built. For the
75
+ * stagnation verdict one buy is one request and one charge.
76
+ *
77
+ * @module core/orchestrate-host
78
+ */
79
+ import type { ActionStep } from '../backend/types.js';
80
+ import type { ClockPort } from '../ports/clock.js';
81
+ import type { BudgetState, PolicySnapshot } from './policy.js';
82
+ /**
83
+ * The charge of one judgment, as every capability bills it.
84
+ *
85
+ * Stated here rather than in one capability's module because all of them record
86
+ * the same five columns, and the fifth (`judgeTokens`) is the one a host that
87
+ * forgot it would quietly under-report.
88
+ */
89
+ export interface JudgmentCost {
90
+ readonly judgments: number;
91
+ readonly memoHits: number;
92
+ readonly localLatencyMs: number;
93
+ readonly remoteLatencyMs: number;
94
+ readonly judgeTokens: number;
95
+ }
96
+ /**
97
+ * One judgment request: the window, plus the question it is put to.
98
+ *
99
+ * This is the whole of what a host is asked for when a judgment is bought. It is
100
+ * a value rather than a port because the host's only job is "ask the service and
101
+ * report what it said, latency included" — the memo key, the budget check, the
102
+ * latency split and the charge stay with the caller that owns the counters.
103
+ */
104
+ export interface JudgmentStep {
105
+ /** Why the run is judged, when the caller knows (a wait question). */
106
+ readonly goal: string | undefined;
107
+ /** The observed steps to judge, oldest first. */
108
+ readonly history: readonly ActionStep[];
109
+ }
110
+ /**
111
+ * Where in the run one judgment is being made.
112
+ *
113
+ * This is the value the four capabilities used to each spell their own accessor
114
+ * for (`position()`, `location()`, `turn()`, and two bare state reads). They
115
+ * disagreed because a port should not answer it: every host has these two
116
+ * numbers, every host means the same thing by them, and a judgment is *about*
117
+ * one place. So the place travels with the judgment — never through the port.
118
+ */
119
+ export interface JudgmentPosition {
120
+ /** The turn this judgment belongs to. */
121
+ turn: number;
122
+ /** The step this judgment belongs to. */
123
+ step: number;
124
+ }
125
+ /**
126
+ * The counters every judgment capability keeps, positioned at where it decides.
127
+ *
128
+ * The place is part of the state for the three capabilities whose state *is* the
129
+ * host's running record (the same object the trigger windows are kept in): the
130
+ * audit detail, the retention request and the verdict memo all quote it, so one
131
+ * source keeps them in step. The closing check is the exception, and the
132
+ * exception is the finding: its turn is the boundary it was asked at, which can
133
+ * be a turn no step has recorded yet, so it arrives as an input of that decision
134
+ * instead (see `orchestrateClosing`).
135
+ */
136
+ export interface JudgmentState extends BudgetState, JudgmentPosition {
137
+ }
138
+ /**
139
+ * What a capability that buys exactly one judgment asks its host for.
140
+ *
141
+ * The shape is one method over one value: the window and the question put to it
142
+ * ({@link JudgmentStep}). The host answers what the service said, latency
143
+ * included; the purchase around it — budget, memo, latency split, charge — is
144
+ * the shared layer's.
145
+ *
146
+ * A capability that buys *differently* still states its buys in this form, one
147
+ * member per request: closing answers `classify` and `verify`, pruning answers
148
+ * `judge`. The rule is that a port states the purchases it makes and never the
149
+ * transport behind them.
150
+ *
151
+ * @typeParam Answer - what this capability's service returns for one request.
152
+ */
153
+ export interface HostJudgmentPort<Answer> {
154
+ /**
155
+ * Buy one judgment about one step.
156
+ * @param step - the window to judge and the question it is asked in.
157
+ * @returns the service's answer, carrying the latency the split is measured on.
158
+ */
159
+ buy(step: JudgmentStep): Promise<Answer>;
160
+ }
161
+ /**
162
+ * What every orchestrated decision asks its host, whatever it decides.
163
+ *
164
+ * These four are the ones no capability can answer alone and no capability
165
+ * answers differently: the policy is the host's resolved config, the counters are
166
+ * the host's storage, the clock is the host's wall time, and the switch is the
167
+ * host's.
168
+ *
169
+ * @typeParam State - the counters this decision spends from. Must extend
170
+ * {@link BudgetState}, because the shared budget rules mutate it through one.
171
+ */
172
+ export interface HostDecisionPort<State extends BudgetState = BudgetState> {
173
+ /** The resolved policy in force right now (re-read per decision). */
174
+ policy(): PolicySnapshot;
175
+ /**
176
+ * The counters this decision spends from and books against.
177
+ *
178
+ * The shared layer mutates them in place through `core/policy`; a host that
179
+ * stores its counters elsewhere hands over the object it wants mutated and
180
+ * nothing else has to know where they live.
181
+ */
182
+ budget(): State;
183
+ /** The clock, for the local-latency split. */
184
+ clock(): ClockPort;
185
+ /** Whether the decision applies at all (master switch on, capability not off). */
186
+ serves(): boolean;
187
+ }
188
+ /**
189
+ * The three accounting channels the judgment capabilities share.
190
+ *
191
+ * Extended by stagnation, correction and closing. See the module documentation
192
+ * for why pruning is not one of them.
193
+ *
194
+ * @typeParam Charge - the judgment charge this capability bills.
195
+ * @typeParam Record - the plan this capability records when it acts.
196
+ */
197
+ export interface HostBillingPort<Charge = JudgmentCost, Record = unknown> {
198
+ /**
199
+ * Record one abandoned plan by reason.
200
+ *
201
+ * The charge is passed in because the record has to say what the refusal cost:
202
+ * a paid "not this" and a free "budget spent" are different answers, and a skip
203
+ * that reported both as free would understate the turn.
204
+ */
205
+ skip(reason: string, charge?: Charge): void;
206
+ /**
207
+ * Bill one judgment whose plan was abandoned after it was really made.
208
+ *
209
+ * A refusal before the judgment is bought costs nothing and is never billed
210
+ * here. One that refused *after* it ran did spend, so hiding it would understate
211
+ * what the turn cost.
212
+ */
213
+ chargeJudgment(charge: Charge): void;
214
+ /**
215
+ * Record one applied or observed plan.
216
+ *
217
+ * This is the one place a plan is billed: `plans` +1, `applied` +1 when it really
218
+ * took effect, and every column of the charge.
219
+ *
220
+ * @param plan - what the capability decided.
221
+ * @param applied - whether active mode executed it.
222
+ * @param charge - the judgment this decision rode on.
223
+ */
224
+ conclude(plan: Record, applied: boolean, charge: Charge): void;
225
+ }