dsh-boost 0.0.0-stage → 0.1.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 (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +476 -0
  4. package/README.md +408 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +276 -0
  43. package/dist/hooks/llm-stream.js +1008 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +247 -0
  49. package/dist/hooks/post-execute.js +1776 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +18 -0
  64. package/dist/host/root.js +43 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +866 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +367 -0
  100. package/dist/tools/boost.js +768 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +113 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
@@ -0,0 +1,768 @@
1
+ import { measureFixedOverhead } from '../admission/fixed-cost.js';
2
+ import { DEFAULT_CONFIG } from '../config.js';
3
+ import { isPosixOnly } from '../host/platform.js';
4
+ import { ERR_SCOPE_ABORTED, ERR_SCOPE_FUTURE_VERSION, ERR_SCOPE_LOCKED, ERR_SCOPE_PARSE_FAILED, ERR_SCOPE_READ_FAILED, ERR_SCOPE_REVISION_CONFLICT, ERR_SCOPE_UNKNOWN_VERSION, } from '../scope/doc.js';
5
+ /** Stable failure code: `cmd` names no subcommand this tool implements. */
6
+ const ERR_BOOST_UNKNOWN_CMD = 'ERR_BOOST_UNKNOWN_CMD';
7
+ /** Stable failure code: a required argument (`baseRevision`) is missing or malformed. */
8
+ const ERR_BOOST_INVALID_ARGS = 'ERR_BOOST_INVALID_ARGS';
9
+ /** Stable failure code: `body` is not a valid, writable scope patch. */
10
+ const ERR_BOOST_INVALID_BODY = 'ERR_BOOST_INVALID_BODY';
11
+ /** Stable failure code: an unexpected internal failure, so the tool still answers. */
12
+ const ERR_BOOST_INTERNAL = 'ERR_BOOST_INTERNAL';
13
+ /** Every scope failure code, for passing the store's codes through unchanged. */
14
+ const SCOPE_CODES = new Set([
15
+ ERR_SCOPE_UNKNOWN_VERSION,
16
+ ERR_SCOPE_FUTURE_VERSION,
17
+ ERR_SCOPE_PARSE_FAILED,
18
+ ERR_SCOPE_READ_FAILED,
19
+ ERR_SCOPE_REVISION_CONFLICT,
20
+ ERR_SCOPE_LOCKED,
21
+ ERR_SCOPE_ABORTED,
22
+ ]);
23
+ /** Stable host degradation codes (design §9; the frozen set `status` reports). */
24
+ const ERR_HOST_NO_SPILL = 'ERR_HOST_NO_SPILL';
25
+ /**
26
+ * Stable degradation code: the host spill-notice module has no footer renderer.
27
+ *
28
+ * Apply-mode projection cannot compose its footer without `formatSpillNotice`,
29
+ * so every receipt is left intact and recorded as
30
+ * `projection-skipped:no-footer`. That is a host-level absence, not an ordinary
31
+ * "not worth it" skip: without this code `status` reported a healthy spill path
32
+ * while projection silently never ran. Its producer is the receipt stream
33
+ * (there is no service probe — the module is reached by `import()` only).
34
+ */
35
+ const ERR_HOST_NO_SPILL_NOTICE = 'ERR_HOST_NO_SPILL_NOTICE';
36
+ const ERR_HOST_NO_TOKENMETER = 'ERR_HOST_NO_TOKENMETER';
37
+ const ERR_HOST_NO_ESTIMATOR = 'ERR_HOST_NO_ESTIMATOR';
38
+ const ERR_HOST_PLATFORM_UNSUPPORTED = 'ERR_HOST_PLATFORM_UNSUPPORTED';
39
+ const ERR_HOST_NO_WORKSPACE_REGISTRY = 'ERR_HOST_NO_WORKSPACE_REGISTRY';
40
+ /**
41
+ * Stable degradation code: at least one receipt shard could not be read.
42
+ *
43
+ * `status` scans every shard; a single unreadable file (EACCES, or a directory
44
+ * named `x.jsonl`) must leave the healthy shards readable and the tool
45
+ * answering. `ReceiptStore.readErrors()` is the one live source: the store
46
+ * contains the failure per shard and the count describes its last whole-store
47
+ * scan, so repairing the shard and re-running `status` drops the code.
48
+ */
49
+ const ERR_RECEIPTS_UNREADABLE = 'ERR_RECEIPTS_UNREADABLE';
50
+ /**
51
+ * Stable degradation code: the whole-store scan hit the 256-shard cap.
52
+ *
53
+ * The totals then cover only the first 256 sorted shards: under-counting is
54
+ * the safe direction, but presenting that as a total is not. The code marks
55
+ * the figures as a lower bound; `ReceiptStore.scanTruncated()` is its source.
56
+ */
57
+ const ERR_RECEIPTS_TRUNCATED = 'ERR_RECEIPTS_TRUNCATED';
58
+ /**
59
+ * Stable degradation code: the final system prompt did not carry the protocol
60
+ * section because a `complete: true` section replaced the assembly.
61
+ *
62
+ * Detected on the outgoing request (`llm/stream`), not at assembly time: the
63
+ * host restores the complete section after the waterfall, so only the request
64
+ * shows the loss. Substitution is refused for the affected request because the
65
+ * model was never taught the plan grammar (review row 12).
66
+ */
67
+ const ERR_HOST_COMPLETE_SECTION = 'ERR_HOST_COMPLETE_SECTION';
68
+ /**
69
+ * Receipt codes that mean the host is degraded, mapped to the stable code
70
+ * `status` reports.
71
+ *
72
+ * `projection-skipped:no-spill` is the code the projection path records when
73
+ * the spill backend is absent (design §5.4), so it is the real producer behind
74
+ * `ERR_HOST_NO_SPILL`. The same code is also derived from the host probe when
75
+ * `projection: 'on'`; the two channels are deduplicated, not mutually exclusive.
76
+ *
77
+ * `projection-skipped:no-footer` is a different absence with a different fix:
78
+ * the spill backend exists but the host spill-notice module does not render a
79
+ * footer, so `projectApply` refuses to replace anything. Mapping it to
80
+ * `ERR_HOST_NO_SPILL_NOTICE` is what keeps the plugin's headline feature from
81
+ * being silently off while `status` calls the spill path healthy.
82
+ */
83
+ const RECEIPT_DEGRADATION = [
84
+ { code: 'projection-skipped:no-spill', degraded: ERR_HOST_NO_SPILL },
85
+ { code: 'projection-skipped:no-footer', degraded: ERR_HOST_NO_SPILL_NOTICE },
86
+ // The substitution refusal writes the stable code itself, so a status built
87
+ // without host facts still reports the reason the decision path recorded.
88
+ { code: ERR_HOST_NO_TOKENMETER, degraded: ERR_HOST_NO_TOKENMETER },
89
+ ];
90
+ /** The scope document's caller-writable fields. Everything else is store-owned. */
91
+ const PATCH_FIELDS = ['mode', 'workspaceIds', 'shadow', 'projection'];
92
+ /** Fields a caller must never set: the store owns one, the format fixes the other. */
93
+ const RESERVED_FIELDS = ['version', 'revision'];
94
+ /**
95
+ * The replay horizon one projection receipt was measured under.
96
+ *
97
+ * The decision path writes `horizon_steps` on every projection receipt it
98
+ * produces. A receipt from before that field existed is replayed at the
99
+ * current horizon and flagged as re-estimated, so `status` can tell the
100
+ * operator how much of the net is measured rather than re-valued. A malformed
101
+ * value is treated as absent, never trusted.
102
+ */
103
+ function replayOf(receipt, fallback) {
104
+ const raw = receipt.horizon_steps;
105
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw >= 0) {
106
+ return { horizon: Math.floor(raw), reestimated: false };
107
+ }
108
+ return { horizon: fallback, reestimated: true };
109
+ }
110
+ /**
111
+ * The receipt aggregation behind `status`, kept separate from the document
112
+ * read so the accounting has one home and one test surface.
113
+ *
114
+ * `scan()` is called with no session id on purpose: `skip:no-scope` receipts
115
+ * are not owned by one shard. The no-agent case writes the empty session id;
116
+ * the cold-judgement path writes the real session id, once per tool call by
117
+ * design (design §5.5:377), which is expected in unscoped workspaces and will
118
+ * dominate their shards — not a leak. Only a whole-store scan sees both.
119
+ *
120
+ * Unreadable shards are the store's concern: `scan()` skips them and
121
+ * `readErrors()` reports the count, so `status` has exactly one source for
122
+ * `ERR_RECEIPTS_UNREADABLE` and a throwing store is an internal failure, not a
123
+ * second degradation channel.
124
+ *
125
+ * The replay sums are computed here, per receipt, from each receipt's own
126
+ * `horizon_steps`. A receipt written before that field existed is replayed at
127
+ * `fallbackHorizon` (the current horizon) and counted in
128
+ * `horizonReestimated`, so the report can say how much of the net is measured
129
+ * rather than re-estimated.
130
+ */
131
+ async function aggregate(receipts, fallbackHorizon) {
132
+ const counts = Object.create(null);
133
+ let substitution = 0;
134
+ let projectionGross = 0;
135
+ let projectionGrossReplay = 0;
136
+ let retrievalContentReplay = 0;
137
+ let horizonReestimated = 0;
138
+ let unpricedProjections = 0;
139
+ let retrievalTokens = 0;
140
+ let retrievalContentTokens = 0;
141
+ let retrievalCallTokens = 0;
142
+ let retrievals = 0;
143
+ let unpricedRetrievals = 0;
144
+ let legacyRetrievals = 0;
145
+ let legacyRetrievalCost = 0;
146
+ for await (const receipt of receipts.scan()) {
147
+ // A receipt is untrusted text from a file: `counts` has no prototype so a
148
+ // code of `toString` or `__proto__` is an ordinary numeric key, never a
149
+ // string concatenation and never a dropped assignment.
150
+ if (typeof receipt.code === 'string') {
151
+ counts[receipt.code] = (counts[receipt.code] ?? 0) + 1;
152
+ }
153
+ // Only the settled line carries a measured saving; the synth-time line is
154
+ // an event and is already visible in `counts`.
155
+ if (receipt.kind === 'substitute-settled') {
156
+ const saved = receipt.saved_input_tokens;
157
+ if (typeof saved === 'number' && Number.isFinite(saved))
158
+ substitution += saved;
159
+ }
160
+ if (receipt.kind !== 'projection')
161
+ continue;
162
+ const replay = replayOf(receipt, fallbackHorizon);
163
+ if (receipt.unit === 'raw' && receipt.call_was_retrieval !== true && receipt.retrieved !== true) {
164
+ // T23b/T26 write `saved_projection_tokens`; `saved` is the pre-T23b
165
+ // spelling this consumer accepted first. Never estimate a value here.
166
+ // A retrieval's own projection is excluded from gross: its visible
167
+ // window is charged as retrieval content instead (review I3).
168
+ const saved = receipt.saved_projection_tokens ?? receipt.saved;
169
+ if (typeof saved === 'number' && Number.isFinite(saved)) {
170
+ projectionGross += saved;
171
+ projectionGrossReplay += saved * (1 + replay.horizon);
172
+ if (replay.reestimated)
173
+ horizonReestimated += 1;
174
+ }
175
+ // A meterless projection carries `estimate:'unknown'` and no saved
176
+ // figure. Reporting the remaining numeric sum as the gross would present
177
+ // an unmeasured effect as zero (review R4).
178
+ else
179
+ unpricedProjections += 1;
180
+ }
181
+ if (receipt.retrieved !== true)
182
+ continue;
183
+ retrievals += 1;
184
+ const total = receipt.retrieval_tokens;
185
+ const call = receipt.retrieval_call_tokens;
186
+ const content = receipt.retrieval_content_tokens;
187
+ if (typeof total === 'number' &&
188
+ Number.isFinite(total) &&
189
+ total >= 0 &&
190
+ typeof call === 'number' &&
191
+ Number.isFinite(call) &&
192
+ call >= 0 &&
193
+ typeof content === 'number' &&
194
+ Number.isFinite(content) &&
195
+ content >= 0 &&
196
+ total === call + content) {
197
+ retrievalTokens += total;
198
+ retrievalCallTokens += call;
199
+ retrievalContentTokens += content;
200
+ retrievalContentReplay += content * (1 + replay.horizon);
201
+ if (replay.reestimated)
202
+ horizonReestimated += 1;
203
+ continue;
204
+ }
205
+ // Pre-schema receipts (written before the split) carry only the old
206
+ // already-replayed `retrievalCost` total. Subtracting it directly from the
207
+ // replayed net avoids counting it as free (review R6). Its own projection,
208
+ // if any, predates the `call_was_retrieval` marker and cannot be identified
209
+ // from the file; that is documented in the report.
210
+ const legacy = receipt.retrievalCost;
211
+ if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy >= 0) {
212
+ legacyRetrievals += 1;
213
+ legacyRetrievalCost += legacy;
214
+ retrievalTokens += legacy;
215
+ continue;
216
+ }
217
+ // Neither schema: the cost is unknown, not zero. The net is reported as
218
+ // `'unknown'` rather than silently treating the retrieval as free.
219
+ unpricedRetrievals += 1;
220
+ }
221
+ const degraded = RECEIPT_DEGRADATION.filter(entry => counts[entry.code] !== undefined).map(entry => entry.degraded);
222
+ return {
223
+ counts,
224
+ substitution,
225
+ projectionGross,
226
+ projectionGrossReplay,
227
+ retrievalContentReplay,
228
+ horizonReestimated,
229
+ unpricedProjections,
230
+ retrievalTokens,
231
+ retrievalContentTokens,
232
+ retrievalCallTokens,
233
+ retrievals,
234
+ unpricedRetrievals,
235
+ legacyRetrievals,
236
+ legacyRetrievalCost,
237
+ degraded,
238
+ };
239
+ }
240
+ /**
241
+ * The fixed overhead measurement, never a thrown status.
242
+ *
243
+ * The production deps carry the promise `apply` started at load; the default
244
+ * is the same memoised measurement, so a direct `runBoost` (a unit test or a
245
+ * host that built the tool itself) still reports a real number. A rejection or
246
+ * an invalid breakdown is `'unknown'`, for the same reason the estimator's own
247
+ * failure is.
248
+ */
249
+ async function fixedOverheadOf(deps) {
250
+ try {
251
+ const value = await (deps.fixedOverhead ?? measureBoostFixedOverhead)();
252
+ if (value === 'unknown')
253
+ return 'unknown';
254
+ const { protocolTokens, toolSchemaTokens, totalTokens } = value;
255
+ if (!Number.isFinite(protocolTokens) ||
256
+ !Number.isFinite(toolSchemaTokens) ||
257
+ !Number.isFinite(totalTokens) ||
258
+ protocolTokens < 0 ||
259
+ toolSchemaTokens < 0 ||
260
+ totalTokens !== protocolTokens + toolSchemaTokens) {
261
+ return 'unknown';
262
+ }
263
+ return value;
264
+ }
265
+ catch {
266
+ return 'unknown';
267
+ }
268
+ }
269
+ /** The configured replay horizon, or the design default when absent/malformed. */
270
+ function horizonOf(deps) {
271
+ const raw = deps.horizonSteps;
272
+ return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0
273
+ ? Math.floor(raw)
274
+ : DEFAULT_CONFIG.horizonSteps;
275
+ }
276
+ /** The label for the assembly's estimator; unprobed is honestly `unknown`. */
277
+ function estimateKindOf(deps) {
278
+ const kind = deps.estimateKind;
279
+ return kind === 'host' || kind === 'unknown' ? kind : 'unknown';
280
+ }
281
+ /**
282
+ * Whether the receipt store has stopped writing, fail-closed.
283
+ *
284
+ * Mirrors `receiptsStopped` in `src/hooks/llm-stream.ts` for the control tool's
285
+ * own store reference: a partial store is "not stopped", and a store that
286
+ * throws cannot record evidence, which is what stopped means.
287
+ */
288
+ function receiptsStopped(store) {
289
+ try {
290
+ if (store == null || typeof store.stopped !== 'function')
291
+ return false;
292
+ return store.stopped() === true;
293
+ }
294
+ catch {
295
+ return true;
296
+ }
297
+ }
298
+ /** Whether the last whole-store scan stopped at the shard cap, never thrown. */
299
+ function receiptsTruncatedOf(deps) {
300
+ try {
301
+ if (deps.receiptsTruncated !== undefined)
302
+ return deps.receiptsTruncated() === true;
303
+ // The store owns the fact; the override exists for a fake counter. Reading
304
+ // the store directly keeps a hand-built `runBoost` (no measured deps) from
305
+ // silently losing the code.
306
+ return deps.receipts.scanTruncated() === true;
307
+ }
308
+ catch {
309
+ return false;
310
+ }
311
+ }
312
+ /** Skipped shard reads, from the override or the store's own reading. */
313
+ function receiptReadErrorsOf(deps) {
314
+ if (deps.receiptReadErrors !== undefined)
315
+ return counterOf(deps.receiptReadErrors);
316
+ try {
317
+ return counterOf(() => deps.receipts.readErrors());
318
+ }
319
+ catch {
320
+ return 0;
321
+ }
322
+ }
323
+ /** A monotonic status counter, never a thrown status. */
324
+ function counterOf(read) {
325
+ try {
326
+ const value = read?.();
327
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
328
+ ? Math.floor(value)
329
+ : 0;
330
+ }
331
+ catch {
332
+ return 0;
333
+ }
334
+ }
335
+ /** A bounded unmapped-tool map, never a thrown status. */
336
+ function toolCountsOf(read) {
337
+ // Build through a Map: `counts['__proto__'] = n` on a plain object would
338
+ // mutate its prototype, and tool names come from the host. `fromEntries` is
339
+ // an own-property copy, so the returned object has the normal prototype and
340
+ // deep-equality consumers see a plain record.
341
+ const counts = new Map();
342
+ try {
343
+ const value = read?.();
344
+ if (value === null || typeof value !== 'object')
345
+ return {};
346
+ for (const [name, count] of Object.entries(value)) {
347
+ if (typeof count === 'number' && Number.isFinite(count) && count >= 0)
348
+ counts.set(name, count);
349
+ }
350
+ }
351
+ catch {
352
+ // A foreign counter is evidence, not a failure.
353
+ }
354
+ return Object.fromEntries(counts);
355
+ }
356
+ /**
357
+ * The stable degradation codes for one status call.
358
+ *
359
+ * Inputs are the receipt-observed codes, the scope read's stable code, and the
360
+ * host facts. Receipt codes are already mapped; the scope store's internal
361
+ * `scope-degraded` label is deliberately **not** copied — the report's contract
362
+ * is stable codes only. Order is deterministic (receipts, scope, host) and the
363
+ * result is deduplicated, so one condition observed through two channels
364
+ * appears once.
365
+ *
366
+ * Two different absences stay distinct: `ERR_HOST_NO_TOKENMETER` is the
367
+ * **service** (`ctx.get('tokenMeter')`) being absent, which refuses
368
+ * substitution; `ERR_HOST_NO_ESTIMATOR` is the pure estimate package being
369
+ * unreachable, which makes the fixed-overhead figure `'unknown'`. A host with
370
+ * the package but no service reports the latter only.
371
+ *
372
+ * `when` on `tools.register` has been part of `ToolRegistrationOptions` since
373
+ * the oldest host line this plugin declares, so there is no "host without
374
+ * step-level `when`" to report: probing it would evaluate every other plugin's
375
+ * predicate against a fabricated `Agent`, and a fact that can never be true is
376
+ * a claim, not a measurement. `apply` registers unconditionally instead.
377
+ */
378
+ function degradationCodes(observed, read, host, fixedOverhead) {
379
+ const codes = [...observed];
380
+ if (read.degraded !== undefined)
381
+ codes.push(read.code ?? ERR_SCOPE_READ_FAILED);
382
+ if (!isPosixOnly())
383
+ codes.push(ERR_HOST_PLATFORM_UNSUPPORTED);
384
+ if (host?.hasTokenMeter === false)
385
+ codes.push(ERR_HOST_NO_TOKENMETER);
386
+ if (fixedOverhead === 'unknown')
387
+ codes.push(ERR_HOST_NO_ESTIMATOR);
388
+ // `spillStore` matters only in apply mode; shadow mode never touches it
389
+ // (design §5.4), so reporting it while projection is `shadow` would be noise.
390
+ if (host?.hasSpill === false && read.doc.projection === 'on')
391
+ codes.push(ERR_HOST_NO_SPILL);
392
+ if (host?.hasWorkspaceRegistry === false)
393
+ codes.push(ERR_HOST_NO_WORKSPACE_REGISTRY);
394
+ return [...new Set(codes)];
395
+ }
396
+ /** `status`: the scope document plus the receipt ledgers, never a failure. */
397
+ async function statusCommand(deps) {
398
+ const read = await deps.scope.read();
399
+ const horizon = horizonOf(deps);
400
+ // Each receipt replays at its own horizon; `horizon` is only the fallback for
401
+ // receipts that predate the field, and `horizonReestimated` counts them.
402
+ const totals = await aggregate(deps.receipts, horizon);
403
+ const fixedOverhead = await fixedOverheadOf(deps);
404
+ const degraded = degradationCodes(totals.degraded, read, deps.host, fixedOverhead);
405
+ // A shard the scan could not read is evidence, not a status failure: the
406
+ // healthy shards were counted and the operator gets a stable code saying the
407
+ // ledger is incomplete. `readErrors()` is the only producer; it counts skips
408
+ // since the last fully readable whole-store scan, so a repaired shard clears
409
+ // the code.
410
+ if (receiptReadErrorsOf(deps) > 0 && !degraded.includes(ERR_RECEIPTS_UNREADABLE)) {
411
+ degraded.push(ERR_RECEIPTS_UNREADABLE);
412
+ }
413
+ // The scan cap makes every figure a lower bound over the first 256 sorted
414
+ // shards. Under-counting is safe, but it must not be presented as a total.
415
+ if (receiptsTruncatedOf(deps) && !degraded.includes(ERR_RECEIPTS_TRUNCATED)) {
416
+ degraded.push(ERR_RECEIPTS_TRUNCATED);
417
+ }
418
+ // A complete prompt section silently removed the protocol from the request:
419
+ // the workspace is visible but substitution cannot be taught, so the operator
420
+ // must see why the plugin is inert.
421
+ if (counterOf(deps.completeSectionSuppressions) > 0)
422
+ degraded.push(ERR_HOST_COMPLETE_SECTION);
423
+ const estimateKind = estimateKindOf(deps);
424
+ // Meterless projections have `estimate:'unknown'` receipts with no saved
425
+ // figure. Reporting the numeric sum of the rest as 0/0 would be
426
+ // indistinguishable from "projection had no effect" (review R4).
427
+ const meterlessEvidence = totals.unpricedProjections > 0;
428
+ const grossOneTime = meterlessEvidence ? 'unknown' : totals.projectionGross;
429
+ const grossReplay = grossOneTime === 'unknown' ? 'unknown' : totals.projectionGrossReplay;
430
+ // A retrieval's own projection is excluded from gross; its content replays
431
+ // with the gross, its call block is charged once, and a legacy cost was
432
+ // already replay-aware (review I3/R6). An unpriced retrieval makes the whole
433
+ // net unknown rather than free (review R3).
434
+ const netUnknown = meterlessEvidence || totals.unpricedRetrievals > 0;
435
+ const projectionNet = netUnknown
436
+ ? 'unknown'
437
+ : totals.projectionGrossReplay -
438
+ totals.retrievalContentReplay -
439
+ totals.retrievalCallTokens -
440
+ totals.legacyRetrievalCost;
441
+ const saved = {
442
+ substitution: totals.substitution,
443
+ projectionGross: grossReplay,
444
+ projectionNet,
445
+ retrievals: totals.retrievals,
446
+ };
447
+ const data = {
448
+ scope: {
449
+ mode: read.doc.mode,
450
+ workspaceIds: read.doc.workspaceIds,
451
+ revision: read.doc.revision,
452
+ },
453
+ shadow: read.doc.shadow,
454
+ projection: read.doc.projection,
455
+ saved,
456
+ counts: totals.counts,
457
+ degraded,
458
+ fixedOverheadTokens: fixedOverhead === 'unknown' ? 'unknown' : fixedOverhead.totalTokens,
459
+ fixedOverhead,
460
+ estimate_kind: estimateKind,
461
+ projection_horizon_steps: horizon,
462
+ projection_horizon_reestimated: totals.horizonReestimated,
463
+ projection_gross_tokens: grossOneTime,
464
+ projection_gross_replay_tokens: grossReplay,
465
+ projection_retrieval_tokens: totals.retrievalTokens,
466
+ projection_retrieval_content_tokens: totals.retrievalContentTokens,
467
+ projection_retrieval_call_tokens: totals.retrievalCallTokens,
468
+ projection_unpriced_projections: totals.unpricedProjections,
469
+ projection_unpriced_retrievals: totals.unpricedRetrievals,
470
+ projection_legacy_retrievals: totals.legacyRetrievals,
471
+ projection_retrievals: totals.retrievals,
472
+ projection_net_tokens: projectionNet,
473
+ projection_locator_evictions: counterOf(deps.locatorEvictions),
474
+ projection_unknown_families: counterOf(deps.unknownFamilies),
475
+ projection_unknown_tools: toolCountsOf(deps.unknownTools),
476
+ protocol_suppressed: counterOf(deps.protocolSuppressed),
477
+ receipts_stopped: receiptsStopped(deps.receipts),
478
+ // An absent host fact is "not probed", not `false`: `undefined` is not a
479
+ // legal JSON value, so the key is omitted rather than handed to the host
480
+ // boundary (review row 35).
481
+ ...(deps.host?.hasWorkspaceRegistry === undefined
482
+ ? {}
483
+ : { hasWorkspaceRegistry: deps.host.hasWorkspaceRegistry }),
484
+ };
485
+ return { ok: true, data };
486
+ }
487
+ /** `scope-get`: a faithful read; a degraded read is a stable tool failure. */
488
+ async function scopeGetCommand(deps) {
489
+ const read = await deps.scope.read();
490
+ if (read.degraded !== undefined)
491
+ return { ok: false, code: read.code ?? ERR_SCOPE_READ_FAILED };
492
+ return { ok: true, data: read.doc };
493
+ }
494
+ /** Whether a value can be a caller-supplied base revision. */
495
+ function isRevision(value) {
496
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0;
497
+ }
498
+ /** Whether `value` is one of the three projection modes. */
499
+ function isProjectionMode(value) {
500
+ return value === 'off' || value === 'shadow' || value === 'on';
501
+ }
502
+ /**
503
+ * Validate a `scope-set` body and prune it to the writable fields.
504
+ *
505
+ * Reserved fields are checked **first**: the store persists whatever `mutate`
506
+ * returns, so a body carrying `version` or `revision` must be refused before a
507
+ * patch is built, not stripped and written as if the caller's intent were
508
+ * merely advisory. Unknown keys are pruned; a known key with a wrong type is
509
+ * rejected, never coerced.
510
+ */
511
+ function scopePatchOf(body) {
512
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
513
+ return { ok: false, code: ERR_BOOST_INVALID_BODY };
514
+ }
515
+ const source = body;
516
+ const has = (key) => Object.prototype.hasOwnProperty.call(source, key);
517
+ if (RESERVED_FIELDS.some(has))
518
+ return { ok: false, code: ERR_BOOST_INVALID_BODY };
519
+ const patch = {};
520
+ if (has('mode')) {
521
+ if (source.mode !== 'selected' && source.mode !== 'global') {
522
+ return { ok: false, code: ERR_BOOST_INVALID_BODY };
523
+ }
524
+ patch.mode = source.mode;
525
+ }
526
+ if (has('workspaceIds')) {
527
+ const ids = source.workspaceIds;
528
+ if (!Array.isArray(ids) || !ids.every(id => typeof id === 'string')) {
529
+ return { ok: false, code: ERR_BOOST_INVALID_BODY };
530
+ }
531
+ patch.workspaceIds = [...ids];
532
+ }
533
+ if (has('shadow')) {
534
+ if (typeof source.shadow !== 'boolean')
535
+ return { ok: false, code: ERR_BOOST_INVALID_BODY };
536
+ patch.shadow = source.shadow;
537
+ }
538
+ if (has('projection')) {
539
+ if (!isProjectionMode(source.projection))
540
+ return { ok: false, code: ERR_BOOST_INVALID_BODY };
541
+ patch.projection = source.projection;
542
+ }
543
+ return { ok: true, patch };
544
+ }
545
+ /** The store's stable code, or undefined for anything else (which never escapes). */
546
+ function scopeCodeOf(error) {
547
+ if (typeof error !== 'object' || error === null || !('code' in error))
548
+ return undefined;
549
+ const code = error.code;
550
+ return typeof code === 'string' && SCOPE_CODES.has(code) ? code : undefined;
551
+ }
552
+ /**
553
+ * One compare-and-swap write shared by `scope-set` and `shadow`.
554
+ *
555
+ * `version: 2` is forced even though `ScopeStore.write` bases a corrupt or
556
+ * v1 file on `DEFAULT_SCOPE`: the invariant must hold at the mutation boundary,
557
+ * where the store's "persist whatever `mutate` returns" contract makes it
558
+ * binding. `revision` is deliberately absent — the store owns it.
559
+ */
560
+ async function writeScope(scope, mutate, baseRevision, signal) {
561
+ try {
562
+ const doc = await scope.write(mutate, baseRevision, { signal });
563
+ return { ok: true, data: doc };
564
+ }
565
+ catch (error) {
566
+ const code = scopeCodeOf(error);
567
+ if (code !== undefined)
568
+ return { ok: false, code };
569
+ throw error;
570
+ }
571
+ }
572
+ /** `scope-set`: validate, prune, then write with compare-and-swap. */
573
+ async function scopeSetCommand(deps, args) {
574
+ const parsed = scopePatchOf(args.body);
575
+ if (!parsed.ok)
576
+ return parsed;
577
+ if (!isRevision(args.baseRevision))
578
+ return { ok: false, code: ERR_BOOST_INVALID_ARGS };
579
+ const patch = parsed.patch;
580
+ return writeScope(deps.scope, doc => ({ ...doc, ...patch, version: 2 }), args.baseRevision, deps.signal);
581
+ }
582
+ /**
583
+ * `shadow`: the shadow-week switch, independent of `projection`.
584
+ *
585
+ * A version 1 document is **not** upgraded here. The store can carry a v1
586
+ * document through a write, but design §5.5 makes `scope-set` the explicit
587
+ * upgrade path: the other write refuses with the degraded read's stable code so
588
+ * the operator performs the documented upgrade instead of a blind rewrite.
589
+ */
590
+ async function shadowCommand(deps, args) {
591
+ if (typeof args.body !== 'boolean')
592
+ return { ok: false, code: ERR_BOOST_INVALID_BODY };
593
+ if (!isRevision(args.baseRevision))
594
+ return { ok: false, code: ERR_BOOST_INVALID_ARGS };
595
+ const current = await deps.scope.read();
596
+ if (current.code === ERR_SCOPE_UNKNOWN_VERSION) {
597
+ return { ok: false, code: ERR_SCOPE_UNKNOWN_VERSION };
598
+ }
599
+ const shadow = args.body;
600
+ return writeScope(deps.scope, doc => ({ ...doc, shadow }), args.baseRevision, deps.signal);
601
+ }
602
+ /** One handler per subcommand; the table is the dispatch and the documentation. */
603
+ const COMMANDS = {
604
+ status: statusCommand,
605
+ 'scope-get': scopeGetCommand,
606
+ 'scope-set': scopeSetCommand,
607
+ shadow: shadowCommand,
608
+ };
609
+ /**
610
+ * Run one `boost` invocation. Pure orchestration over the two stores.
611
+ *
612
+ * Failures are values: an unknown command, an invalid body or a store code all
613
+ * come back as `{ ok: false, code }`. The `try` covers the argument read as
614
+ * well as the handler, so a null call or an argument object with a throwing
615
+ * getter answers a stable code instead of throwing. The catch exists only so
616
+ * an unexpected store failure cannot turn the user's only control surface into
617
+ * a thrown tool error; it is not an expected path.
618
+ */
619
+ export async function runBoost(input) {
620
+ try {
621
+ const signal = input?.signal;
622
+ if (signal?.aborted === true)
623
+ return { ok: false, code: ERR_SCOPE_ABORTED };
624
+ const args = input?.args;
625
+ const cmd = args?.cmd;
626
+ const handler = typeof cmd === 'string' && Object.prototype.hasOwnProperty.call(COMMANDS, cmd)
627
+ ? COMMANDS[cmd]
628
+ : undefined;
629
+ if (handler === undefined)
630
+ return { ok: false, code: ERR_BOOST_UNKNOWN_CMD };
631
+ return await handler(input, args);
632
+ }
633
+ catch {
634
+ return { ok: false, code: ERR_BOOST_INTERNAL };
635
+ }
636
+ }
637
+ /**
638
+ * The host's cancellation signal, or `undefined` for any other shape.
639
+ *
640
+ * `exec` crosses the host boundary and is untrusted here: a plain object with
641
+ * an `aborted` boolean and an `addEventListener` function is the documented
642
+ * `AbortSignal` contract this code relies on, and anything else is ignored
643
+ * rather than dereferenced (a foreign host must not make `boost` throw).
644
+ */
645
+ function signalOf(exec) {
646
+ const candidate = exec?.signal;
647
+ if (typeof candidate !== 'object' || candidate === null)
648
+ return undefined;
649
+ const signal = candidate;
650
+ if (typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function') {
651
+ return undefined;
652
+ }
653
+ return candidate;
654
+ }
655
+ /** Model-facing description: what each command does and what it returns. */
656
+ const DESCRIPTION = [
657
+ 'Inspect or change dsh-boost state. Commands:',
658
+ 'status reports the scope document, both switches, receipt counts per code, both ledgers (substitution; projection net with its retrieval count), the measured fixed overhead, and the degraded codes;',
659
+ 'scope-get reads the full scope document;',
660
+ 'scope-set replaces the given fields with compare-and-swap; body = { mode?, workspaceIds?, shadow?, projection? }; version and revision are store-owned and rejected;',
661
+ 'shadow persists the shadow-week switch; body = boolean; it refuses a version 1 document with ERR_SCOPE_UNKNOWN_VERSION — run scope-set once to upgrade it.',
662
+ 'scope-set and shadow require the baseRevision last seen via status or scope-get; a stale one fails with ERR_SCOPE_REVISION_CONFLICT. Failures are { ok:false, code } values, never thrown.',
663
+ ].join(' ');
664
+ /** The argument schema shown to the model; `status`/`scope-get` need only `cmd`. */
665
+ const PARAMETERS = {
666
+ type: 'object',
667
+ properties: {
668
+ cmd: {
669
+ type: 'string',
670
+ enum: ['status', 'scope-get', 'scope-set', 'shadow'],
671
+ description: 'Which boost operation to run.',
672
+ },
673
+ body: {
674
+ description: 'scope-set: the desired scope fields (unknown keys are pruned, version/revision rejected). shadow: the desired boolean.',
675
+ oneOf: [
676
+ {
677
+ type: 'object',
678
+ properties: {
679
+ mode: { type: 'string', enum: ['selected', 'global'] },
680
+ workspaceIds: { type: 'array', items: { type: 'string' } },
681
+ shadow: { type: 'boolean' },
682
+ projection: { type: 'string', enum: ['off', 'shadow', 'on'] },
683
+ },
684
+ },
685
+ { type: 'boolean' },
686
+ ],
687
+ },
688
+ baseRevision: {
689
+ // `minimum` is outside the host's enforced JSON-Schema subset; the
690
+ // runtime check in `isRevision` is the authority for `>= 0` (row 45).
691
+ type: 'integer',
692
+ description: 'Required by scope-set and shadow: the revision last seen (a non-negative integer).',
693
+ },
694
+ },
695
+ required: ['cmd'],
696
+ additionalProperties: false,
697
+ };
698
+ /**
699
+ * The model-visible part of the `boost` tool definition.
700
+ *
701
+ * This is the second half of the fixed-overhead budget: `estimateToolsTokens`
702
+ * prices the schema the model receives every request. `output` is a host-side
703
+ * envelope and is not part of the request's tool list, so it is excluded.
704
+ */
705
+ function boostSchema() {
706
+ return { name: 'boost', description: DESCRIPTION, parameters: PARAMETERS };
707
+ }
708
+ /** The one memoised protocol + schema measurement, shared by startup and status. */
709
+ let boostFixedOverhead;
710
+ /**
711
+ * The startup probe `apply` fires once and `status` awaits.
712
+ *
713
+ * Memoised per process: a status call must report the same number the startup
714
+ * measured, and must not re-import or re-price the schema.
715
+ */
716
+ export function measureBoostFixedOverhead() {
717
+ boostFixedOverhead ??= measureFixedOverhead(boostSchema());
718
+ return boostFixedOverhead;
719
+ }
720
+ /**
721
+ * The canonical output envelope. The host validates every successful return
722
+ * against this schema, and a failure is a successful call whose value is
723
+ * `{ ok: false, code }` (the tool never throws its stable codes), so both
724
+ * branches are declared.
725
+ */
726
+ const OUTPUT_SCHEMA = {
727
+ oneOf: [
728
+ {
729
+ type: 'object',
730
+ properties: {
731
+ ok: { type: 'boolean', const: true },
732
+ data: {},
733
+ },
734
+ required: ['ok', 'data'],
735
+ additionalProperties: false,
736
+ },
737
+ {
738
+ type: 'object',
739
+ properties: {
740
+ ok: { type: 'boolean', const: false },
741
+ code: { type: 'string' },
742
+ },
743
+ required: ['ok', 'code'],
744
+ additionalProperties: false,
745
+ },
746
+ ],
747
+ };
748
+ /** Render the canonical envelope as one text block; `JSON.stringify` is the format. */
749
+ function renderResult(_args, value) {
750
+ return [{ type: 'text', text: JSON.stringify(value) ?? 'undefined' }];
751
+ }
752
+ /**
753
+ * Build the host tool definition.
754
+ *
755
+ * `output: { schema, render }` is mandatory in the host's `ToolDefinition`;
756
+ * a definition missing it is rejected at registration. `execute` reuses
757
+ * `runBoost`, so the tool and the pure orchestration cannot drift.
758
+ */
759
+ export function boostTool(deps) {
760
+ return {
761
+ name: 'boost',
762
+ description: DESCRIPTION,
763
+ parameters: PARAMETERS,
764
+ output: { schema: OUTPUT_SCHEMA, render: renderResult },
765
+ execute: (args, exec) => runBoost({ args: args, ...deps, signal: signalOf(exec) }),
766
+ };
767
+ }
768
+ //# sourceMappingURL=boost.js.map