dsh-boost 0.0.0-stage → 0.1.1

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