dsh-boost 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +97 -33
- package/README.md +85 -32
- package/dist/gate/decide.js +33 -2
- package/dist/gate/decide.js.map +1 -1
- package/dist/hooks/llm-stream.js +129 -54
- package/dist/hooks/llm-stream.js.map +1 -1
- package/dist/hooks/post-execute.js +104 -21
- package/dist/hooks/post-execute.js.map +1 -1
- package/dist/hooks/session-state.js +18 -8
- package/dist/hooks/session-state.js.map +1 -1
- package/dist/index.js +371 -67
- package/dist/index.js.map +1 -1
- package/dist/scope/doc.js.map +1 -1
- package/dist/scope/store.js +24 -9
- package/dist/scope/store.js.map +1 -1
- package/package.json +8 -4
- package/dist/admission/fixed-cost.d.ts +0 -23
- package/dist/admission/ledger.d.ts +0 -113
- package/dist/admission/retrieval.d.ts +0 -65
- package/dist/admission/usage.d.ts +0 -75
- package/dist/config.d.ts +0 -43
- package/dist/gate/binding.d.ts +0 -113
- package/dist/gate/decide.d.ts +0 -82
- package/dist/gate/guard.d.ts +0 -69
- package/dist/gate/invalidate.d.ts +0 -112
- package/dist/gate/plan.d.ts +0 -86
- package/dist/hooks/clock.d.ts +0 -68
- package/dist/hooks/execute.d.ts +0 -79
- package/dist/hooks/llm-stream.d.ts +0 -283
- package/dist/hooks/pending.d.ts +0 -89
- package/dist/hooks/post-execute.d.ts +0 -257
- package/dist/hooks/session-state.d.ts +0 -158
- package/dist/hooks/synthesize.d.ts +0 -74
- package/dist/host/loader.d.ts +0 -23
- package/dist/host/platform.d.ts +0 -18
- package/dist/host/root.d.ts +0 -25
- package/dist/projection/apply.d.ts +0 -174
- package/dist/projection/canonicalise.d.ts +0 -43
- package/dist/projection/counters.d.ts +0 -65
- package/dist/projection/truncate.d.ts +0 -47
- package/dist/prompt/protocol.d.ts +0 -45
- package/dist/receipts/store.d.ts +0 -198
- package/dist/scope/doc.d.ts +0 -117
- package/dist/scope/resolve.d.ts +0 -91
- package/dist/scope/store.d.ts +0 -135
- package/dist/selector/jev.d.ts +0 -93
- package/dist/tools/boost.d.ts +0 -380
- package/dist/tools/family.d.ts +0 -26
package/README.en.md
CHANGED
|
@@ -11,7 +11,7 @@ read-only substitution**.
|
|
|
11
11
|
## What it does
|
|
12
12
|
|
|
13
13
|
DSH replays the whole history on every model request. Across the 300 longest sessions measured
|
|
14
|
-
locally (`npm run --silent stats` — without `--silent`, npm prints its `> dsh-boost@0.1.
|
|
14
|
+
locally (`npm run --silent stats` — without `--silent`, npm prints its `> dsh-boost@0.1.1 stats`
|
|
15
15
|
banner to stdout, so use `--silent` or `node scripts/session-stats.mjs` for machine-readable
|
|
16
16
|
output; snapshot at `2026-11-19T03:13:21Z`): 54,141 steps and 54,088 requests,
|
|
17
17
|
10,575,904,022 raw tokens in total. The mean is 195,340 tokens per step and 195,531 per request
|
|
@@ -38,6 +38,13 @@ The plugin does two things:
|
|
|
38
38
|
emit line-numbered or bare-path output that the identifier projection cannot match, so those
|
|
39
39
|
calls fall back to the model.
|
|
40
40
|
|
|
41
|
+
The multi-candidate selector **does not read a separate model configuration**: it reuses the
|
|
42
|
+
**boundary request's** `provider` / `model` / `reasoningEffort` (`rememberRoute` in
|
|
43
|
+
`src/index.ts`, fed mainly by `agent/pre-step`'s `modelSelection`, with the `agent/request`
|
|
44
|
+
resolution only as a fallback), so it is not necessarily a cheap model. To move it, either
|
|
45
|
+
change the model on the boundary session (the host routes per agent) or leave the plan with a
|
|
46
|
+
single candidate (one candidate never calls the selector).
|
|
47
|
+
|
|
41
48
|
The **ex-ante estimate** for v1 is **3.5% (lower bound) to 10.0% (ideal upper bound)** of raw
|
|
42
49
|
`totalTokens`; **3.5% is not a floor** — it is the lower bound of an offline estimate against a
|
|
43
50
|
300-session corpus, and its substitution component (2.70%) is a **ceiling** that must not be
|
|
@@ -51,8 +58,10 @@ replacing the range with measurements needs a denominator statistic that a later
|
|
|
51
58
|
|
|
52
59
|
## Requirements
|
|
53
60
|
|
|
54
|
-
- Node.js `>=24.9.0` and DSH
|
|
55
|
-
`
|
|
61
|
+
- Node.js `>=24.9.0` and DSH `>=0.2.2-rc.4 <0.2.3-0` (a **range**, not an exact pin: the host
|
|
62
|
+
evaluates it with `includePrerelease` semantics and disables the plugin on a miss, while
|
|
63
|
+
`0.2.2-rc.5` is byte-identical to rc.4 in every host package this plugin touches). Both live in
|
|
64
|
+
`package.json` `engines`; the Node floor matches the host `@deepseek-ai/dsh@0.2.2-rc.4`.
|
|
56
65
|
- **The package declares no peerDependencies**: installing it pulls in no `@deepseek-ai/*`
|
|
57
66
|
package, and the module loads without any of them; the runtime capabilities (`tokenMeter`,
|
|
58
67
|
`spillStore`, the estimator, the footer formatter) are provided by the DSH host process, and a
|
|
@@ -68,16 +77,28 @@ replacing the range with measurements needs a denominator statistic that a later
|
|
|
68
77
|
directory:
|
|
69
78
|
|
|
70
79
|
```bash
|
|
71
|
-
# install from the registry
|
|
72
|
-
|
|
80
|
+
# install from the registry: npmjs has latest = 0.1.1 (this repository's
|
|
81
|
+
# .npmrc and lockfile are pinned to npmjs too — see below)
|
|
82
|
+
dsh plugin --profile <name> add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/
|
|
73
83
|
|
|
74
84
|
# or from a local checkout (build first; dist/ is not committed)
|
|
75
85
|
npm run build
|
|
76
86
|
dsh plugin --profile <name> add /absolute/path/to/dsh-boost
|
|
77
87
|
```
|
|
78
88
|
|
|
79
|
-
For the web profile: `dsh plugin --profile web add dsh-boost@^0.1.
|
|
80
|
-
to pnpm, so pnpm must be on `PATH`.
|
|
89
|
+
For the web profile: `dsh plugin --profile web add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/`.
|
|
90
|
+
`dsh plugin` forwards the operation to pnpm, so pnpm must be on `PATH`.
|
|
91
|
+
|
|
92
|
+
> **The two registries carry different versions, so `^0.1.0` is not a safe pin.**
|
|
93
|
+
> `registry.npmjs.org` has three version records: `0.1.1` (current `latest`), `0.1.0`, and
|
|
94
|
+
> `0.0.0-stage`, a placeholder npm creates on a package's first publish. The
|
|
95
|
+
> `registry.npmmirror.com` currently has only `0.1.0` (its `latest` is 0.1.0 too) — this
|
|
96
|
+
> repository's `.npmrc` and lockfile are pinned to npmjs, but your global npm config may not be.
|
|
97
|
+
> The same `^0.1.0` therefore resolves to 0.1.1 on npmjs and to 0.1.0 on
|
|
98
|
+
> the mirror — and a mirror user installs a build missing ten of 0.1.1's fixes, several of which
|
|
99
|
+
> repair silent failures. Use `dsh-boost@^0.1.1` (or `@latest`), and pass
|
|
100
|
+
> `--registry=https://registry.npmjs.org/` explicitly when the registry matters; while the mirror
|
|
101
|
+
> has not synced 0.1.1, `@^0.1.1` without that flag fails to resolve.
|
|
81
102
|
|
|
82
103
|
The package is ESM (`"type": "module"`) and the `.` entry of `exports` also maps `require` /
|
|
83
104
|
`default`: on Node >= 24.9, `require('dsh-boost')` loads the very same code as `import`. Nothing
|
|
@@ -136,10 +157,14 @@ Then list the workspace to expose:
|
|
|
136
157
|
|
|
137
158
|
- `workspaceIds` are the host's workspace UUIDs, not paths; the host maps the agent's cwd to this
|
|
138
159
|
id through its workspace registry. **Finding the UUID is itself friction**: either ask the
|
|
139
|
-
host / dig through session records, or read `tables.workspaces` (the id ↔ path table) in
|
|
140
|
-
|
|
141
|
-
you
|
|
142
|
-
|
|
160
|
+
host / dig through session records, or read `tables.workspaces` (the id ↔ path table) in the
|
|
161
|
+
host's `<hostDshHome>/storages/workspace.json` yourself — v1 ships no command that does this
|
|
162
|
+
for you. The host resolves its home as "a non-empty `$DSH_HOME` (`~` expands) → `~/.dsh`", so
|
|
163
|
+
on a default install the file is `~/.dsh/storages/workspace.json`, **not**
|
|
164
|
+
`$DSH_HOME/storages/workspace.json` (unless `$DSH_HOME` is actually set). Note that
|
|
165
|
+
`config.dshHome` moves only the plugin's `<dshHome>/boost`, never this host file. If you cannot
|
|
166
|
+
find the UUID and this is a single-user machine, `"mode": "global"` widens the scope to every
|
|
167
|
+
*defined* workspace; sessions with no workspace stay invisible.
|
|
143
168
|
- `baseRevision` is `data.scope.revision` from the status you just read (`0` for the first write).
|
|
144
169
|
This is compare-and-swap: a stale revision returns `ERR_SCOPE_REVISION_CONFLICT`; read `status`
|
|
145
170
|
again and retry. When the caller's cancellation signal interrupts the write, the tool returns
|
|
@@ -206,9 +231,10 @@ nothing; it produces only the four ratios below.
|
|
|
206
231
|
Of those ratios, `saveableRatio`, `byFamily`, and `candidateRecall` can decide **whether the
|
|
207
232
|
substitution side is worth turning on**: how many substitution decisions the whitelist could
|
|
208
233
|
actually deliver, which tool families the hits land in, and how high candidate recall is — that
|
|
209
|
-
is, whether substitution would fire at all and where. They **cannot decide release**:
|
|
210
|
-
|
|
211
|
-
|
|
234
|
+
is, whether substitution would fire at all and where. They **cannot decide release**: v1 ships as
|
|
235
|
+
a normal release and does not gate on shadow-week savings — and that call was the
|
|
236
|
+
**implementer's** decision during design, not a user ruling. The user accepted a one-week shadow
|
|
237
|
+
period; they did not rule on whether shadow results should gate a release. They also **cannot measure savings**: the report has no total-token denominator, and
|
|
212
238
|
`retrievalUpperBound` is structurally `0` during the shadow week (it only counts applied
|
|
213
239
|
`projection:'on'` retrievals), so it cannot even bound projection's retrieval damage. Projection
|
|
214
240
|
is released on the visibility contract (the original stays retrievable through the footer) and
|
|
@@ -294,11 +320,11 @@ cap is 256 KiB, so `300000` prevents the family from triggering at all (there is
|
|
|
294
320
|
Characters are Unicode code points. Error receipts and receipts above 256 KiB are never projected.
|
|
295
321
|
|
|
296
322
|
The invariant is **not** `triggerChars >= headChars + tailChars + 1`. The real replacement is head
|
|
297
|
-
line + head + footer + tail + 3 newlines; the footer is produced by the host's `formatSpillNotice
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
`400 + 100 + 50 (head line) +
|
|
301
|
-
about
|
|
323
|
+
line + head + footer + tail + 3 newlines; the footer is produced by the host's `formatSpillNotice`.
|
|
324
|
+
With a 68-character locator and the host's fixed 66-character retrieval hint, a 3-digit
|
|
325
|
+
omitted-byte count gives 190 characters and a 5-digit count gives 192. With the grep/glob defaults
|
|
326
|
+
of 400+100: `400 + 100 + 50 (head line) + 190 (footer) + 3 = 743 > 700` (745 with a 5-digit count).
|
|
327
|
+
So a receipt just over 700 — up to about 743 — is judged cuttable by `truncate`, but `projectApply` assembles a replacement that is
|
|
302
328
|
not shorter than the original and returns the original. That is a dead band, not a net loss. The
|
|
303
329
|
runtime `assembled.length >= text.length` check guarantees projection never makes a receipt
|
|
304
330
|
longer; to remove the dead band, raise `triggerChars` to at least that sum (for example 800 for
|
|
@@ -358,23 +384,60 @@ set it falls back to `~/.dsh`; the assembly log prints the resolved `root=` (tha
|
|
|
358
384
|
|
|
359
385
|
- `scope.json` — the single source of truth for the exposure surface (version 2, with revision).
|
|
360
386
|
- `scope.lock` — the short-lived write lock, removed after a normal write.
|
|
361
|
-
- `receipts/<encoded-session>.jsonl` — append-only receipts.
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
`
|
|
371
|
-
|
|
387
|
+
- `receipts/<encoded-session>.jsonl` — append-only receipts. **A receipt is written per
|
|
388
|
+
decision, not per call**: a line appears only for a projection, a substitution decision
|
|
389
|
+
(including skips), or an out-of-scope `skip:no-scope`. A `write` / `edit` with no plan produces
|
|
390
|
+
**no receipt at all**, so its arguments are never recorded. Every line carries metadata, a
|
|
391
|
+
preview of the first 256 code points of the receipt (never the full stdout), and that call's
|
|
392
|
+
bound `args` (model-written: above 2048 code points they are stored as visibly truncated JSON
|
|
393
|
+
with an `args_truncated` flag; nesting deeper than 64 levels sets `args_depth_truncated` and
|
|
394
|
+
replaces the deeper subtree with `{ "truncated_depth": 64 }`). **Only substitution receipts**
|
|
395
|
+
also carry the plan goal (≤256 code points) and guards (≤8, each ≤300 code points):
|
|
396
|
+
`kind:'substitute'`, `kind:'substitute-settled'`, and `kind:'shadow'` with `code:'ok'`.
|
|
397
|
+
`kind:'shadow'` is not substitution-only — projection shadowing also writes `kind:'shadow'`,
|
|
398
|
+
but with `code:'projection-shadow'`, and that is a projection receipt with no plan evidence.
|
|
399
|
+
**Projection receipts** (`kind:'projection'`, `code:'projected'`, and the projection shadow)
|
|
400
|
+
carry `before` / `after` / `saved_projection_tokens` / `unit` / `estimate` / `horizon_steps`;
|
|
401
|
+
without a token meter only `estimate:'unknown'` is written and the three numeric fields are
|
|
402
|
+
omitted entirely. **Retrieval receipts** (`kind:'projection'`, `code:'projection-retrieval'`)
|
|
403
|
+
carry `locator` plus `retrieval_call_tokens` / `retrieval_content_tokens` / `retrieval_tokens`;
|
|
404
|
+
those three are written only when the retrieval was priced, and an unpriced one has
|
|
405
|
+
`estimate:'unknown'` with the fields omitted. `skip` receipts carry only `preview` and `args`
|
|
406
|
+
(`skip:no-scope` carries neither — just the tool name).
|
|
407
|
+
|
|
408
|
+
When the current shard exceeds 8 MiB or 20,000 lines, the next write first rotates it to
|
|
409
|
+
`<encoded-session>.1.jsonl`; only the current shard and its predecessor are kept (an older `.1`
|
|
410
|
+
is overwritten). `boost status` reads `.1` before the current shard. The 256-shard cap counts
|
|
411
|
+
**encoded session names**: a rotated `.1.jsonl` belongs to the same name and takes no extra
|
|
412
|
+
slot, though the scan reads both files under that name.
|
|
372
413
|
|
|
373
414
|
`boost status` replays the projection ledger at each receipt's own `horizon_steps`; a receipt
|
|
374
415
|
written before that field existed is replayed at the current horizon and counted in
|
|
375
416
|
`projection_horizon_reestimated`, while `projection_horizon_steps` reports the horizon currently
|
|
376
417
|
in effect (the minimum over live sessions, falling back to `horizonSteps` when no history exists).
|
|
377
418
|
|
|
419
|
+
`status.data` also carries several status and ledger fields that never appear in `degraded`:
|
|
420
|
+
|
|
421
|
+
- `receipts_stopped`: `true` once receipt writes have failed 3 times in a row. Substitution is then
|
|
422
|
+
refused **entirely** (fail closed — no further selector call or step budget is spent), projection
|
|
423
|
+
continues, and every ledger figure is the snapshot from before the writes stopped. The count
|
|
424
|
+
clears and the field returns to `false` after a write succeeds. This is the only place that says
|
|
425
|
+
"receipts have stopped" — there is no `degraded` code for it.
|
|
426
|
+
- `protocol_suppressed`: how many times the protocol section was dropped at assembly (invisible
|
|
427
|
+
workspace, a diagnostic assembly with no agent, and a `complete: true` override). Assembly runs
|
|
428
|
+
per request, so this only counts — it writes no receipt.
|
|
429
|
+
- `projection_locator_evictions`: locators dropped because of the per-session cap (512, oldest
|
|
430
|
+
first); above 0 means the retrieval ledger has losses.
|
|
431
|
+
- `projection_unknown_families`: calls carrying an `mcp__` prefix that reached projection but
|
|
432
|
+
matched no tool family; `projection_unknown_tools` is the retained unmapped tool names with
|
|
433
|
+
counts (at most 32), for spotting mapper gaps.
|
|
434
|
+
- `hasWorkspaceRegistry`: whether the host currently offers `workspaceRegistry`. The key is
|
|
435
|
+
**omitted** when nothing was probed — it is not `false`.
|
|
436
|
+
- `saved`: a camelCase ledger object for older consumers (`substitution` / `projectionGross` /
|
|
437
|
+
`projectionNet` / `retrievals`), derived from the same aggregation as the top-level snake_case
|
|
438
|
+
fields. A projection receipt written before T23b has no `saved_projection_tokens` and is priced
|
|
439
|
+
from its legacy `saved` field instead.
|
|
440
|
+
|
|
378
441
|
With `projection: 'on'`, the complete original is written to the host spill backend **before** the
|
|
379
442
|
replacement happens, and the footer locator can be read with `read` / `grep`. Projection never
|
|
380
443
|
discards the only copy; if the spill write fails, nothing is replaced (the receipt records
|
|
@@ -426,7 +489,7 @@ to load. `llm` is soft (only the selector uses it); when absent the selector fal
|
|
|
426
489
|
| `workspaceRegistry` | soft (`ctx.get('workspaceRegistry')`) | **The workspace is invisible**: a cwd can never map to a workspace id, so everything fails closed as invisible — no protocol section, projection and substitution all skipped, only `skip:no-scope` receipts accumulating; `status.degraded` reports `ERR_HOST_NO_WORKSPACE_REGISTRY`. This is the host-capability explanation **when a workspace should be visible**, not the only explanation for "installed but nothing happens": the shipped default `selected + []` is inert by design and reports no error; a missing token meter also refuses real substitution; a `complete: true` section also suppresses the protocol |
|
|
427
490
|
| `tokenMeter` | soft (`ctx.get('tokenMeter')`) | Substitution is refused; projection keeps working and its accounting records `unknown` (never a fabricated number); `status.degraded` reports `ERR_HOST_NO_TOKENMETER` |
|
|
428
491
|
| `spillStore` | soft (`ctx.get('spillStore')`) | With `projection: 'on'`, an over-limit receipt is not projected (evidence preserved) and the receipt records `projection-skipped:no-spill`; `status.degraded` reports `ERR_HOST_NO_SPILL` (the live probe only in on mode; a historical receipt reports it in any mode) |
|
|
429
|
-
| `@deepseek-ai/dsh-spill-policy/notice` | soft (dynamic import) | The spill backend exists but the footer renderer `formatSpillNotice` cannot be loaded/is absent: apply-mode projection cannot build its footer and skips every receipt (`projection-skipped:no-footer`); `status.degraded` reports `ERR_HOST_NO_SPILL_NOTICE`. This is a different absence from `ERR_HOST_NO_SPILL` (no spill backend at all) |
|
|
492
|
+
| `@deepseek-ai/dsh-spill-policy/notice` | soft (dynamic import) | The spill backend exists but the footer renderer `formatSpillNotice` cannot be loaded/is absent: apply-mode projection cannot build its footer and skips every receipt (`projection-skipped:no-footer`; a throw while rendering records `projection-skipped:footer-failed`); `status.degraded` reports `ERR_HOST_NO_SPILL_NOTICE`. This is a different absence from `ERR_HOST_NO_SPILL` (no spill backend at all) |
|
|
430
493
|
| (spill backend present but failing) | — | Every `saveText` is rejected: the receipt records `projection-skipped:spill-failed` and `status.degraded` reports **`ERR_HOST_SPILL_FAILING`**. This is a **third** state — neither "no backend" nor "no footer renderer" — and telling an operator to restore the spill package would send them after a package that is installed and failing |
|
|
431
494
|
| `@deepseek-ai/dsh-token-meter/estimate` | soft (dynamic import) | Fixed overhead cannot be measured, so `fixedOverheadTokens` is `'unknown'`; `status.degraded` reports `ERR_HOST_NO_ESTIMATOR` |
|
|
432
495
|
| `win32` platform | runtime `isPosixOnly()` check | Substitution is refused, projection still works; `status.degraded` reports `ERR_HOST_PLATFORM_UNSUPPORTED` |
|
|
@@ -481,7 +544,8 @@ evidence" degraded path would be unreachable.
|
|
|
481
544
|
does not produce it.
|
|
482
545
|
- **The shadow week saves nothing by design**: it only records (the protocol section is still
|
|
483
546
|
injected and the selector is still called); its output is four ratios, not saved tokens.
|
|
484
|
-
- **v1 does not judge "better results"**: there is a token ledger and a 20-task
|
|
547
|
+
- **v1 does not judge "better results"**: there is a token ledger and a **manual** 20-task
|
|
548
|
+
regression procedure (the task set does not ship with the package; see `docs/RELEASE.md` §3),
|
|
485
549
|
no quality metric; whether substituted outcomes are better is unjudgeable in v1.
|
|
486
550
|
- **Projection is truncation, not refinement**: it keeps the head and tail and drops the middle;
|
|
487
551
|
the before/after token difference in the ledger measures *shorter*, not *more relevant*. The
|
|
@@ -518,7 +582,7 @@ The source and docs live in the repository at
|
|
|
518
582
|
| [Design](docs/superpowers/specs/2026-11-18-dsh-token-efficiency-design.md) | Goals, evidence, architecture, contracts, measurement, risks, release shape |
|
|
519
583
|
| [Host contracts appendix](docs/superpowers/plans/2026-11-18-host-contracts.md) | Interface reference copied line by line from the host sources |
|
|
520
584
|
| [Three-tier delegation research](docs/research/2026-11-18-three-tier-delegation.md) | 25 primary sources on caching, routing thresholds, compression, and verification |
|
|
521
|
-
| [Release acceptance](docs/RELEASE.md) | The one-command `npm run verify:package` acceptance, the zero-peerDependencies state and install spec, the degradation-code matrix, the 20-task regression
|
|
585
|
+
| [Release acceptance](docs/RELEASE.md) | The one-command `npm run verify:package` acceptance, the zero-peerDependencies state and install spec, the degradation-code matrix, the 20-task regression procedure (manual; the task set does not ship), and the shadow week and stats recompute |
|
|
522
586
|
|
|
523
587
|
## License
|
|
524
588
|
|
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
## 它解决什么
|
|
9
9
|
|
|
10
10
|
DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的实测聚合(`npm run --silent stats`——不带
|
|
11
|
-
`--silent` 时 npm 会把 `> dsh-boost@0.1.
|
|
11
|
+
`--silent` 时 npm 会把 `> dsh-boost@0.1.1 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
|
|
12
12
|
`node scripts/session-stats.mjs`;快照时刻 `2026-11-19T03:13:21Z`):54,141 步、54,088 个请求,合计 10,575,904,022 raw token。按步均值
|
|
13
13
|
195,340 token,按请求均值 195,531、中位 187,681;97.01% 的输入是缓存读。工具回执是体积主体
|
|
14
14
|
(bash 61.75%、read 22.13%、ssh 10.01%),而下一步真正会用到的部分通常远小于回执本身。
|
|
@@ -26,6 +26,12 @@ DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的
|
|
|
26
26
|
(把上一步回执里的值直接搬进下一步参数)在实践中只对 `glob` 的单 token 输出有效;
|
|
27
27
|
`read` 与 `grep` 的输出带行号或是裸路径,标识符投影匹配不到,这些调用会退回模型。
|
|
28
28
|
|
|
29
|
+
多候选选择器**不读独立的模型配置**:它复用**边界请求**的 `provider` / `model` /
|
|
30
|
+
`reasoningEffort`(`src/index.ts` 的 `rememberRoute`,主来源是 `agent/pre-step` 的
|
|
31
|
+
`modelSelection`,`agent/request` 的解析结果只作回退),所以它不一定是廉价模型。要让它走
|
|
32
|
+
别的模型,只能在边界会话上换模型(宿主按 agent 选路由),或让计划只留一个候选(单候选
|
|
33
|
+
不调用选择器)。
|
|
34
|
+
|
|
29
35
|
v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**,按 raw `totalTokens` 计;
|
|
30
36
|
**3.5% 不是保底**——它是设计阶段对一个 300 会话语料做离线估算得到的下界,其中替换账的
|
|
31
37
|
2.70% 是**上限**,不能算进保底;诚实的净保底只有约 **0.4%**(投影侧毛额约 0.8% 减去每请求
|
|
@@ -36,8 +42,10 @@ v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**
|
|
|
36
42
|
|
|
37
43
|
## 前置条件
|
|
38
44
|
|
|
39
|
-
- Node.js `>=24.9.0`,DSH
|
|
40
|
-
`
|
|
45
|
+
- Node.js `>=24.9.0`,DSH `>=0.2.2-rc.4 <0.2.3-0`(**区间**,不是精确钉法;宿主按
|
|
46
|
+
`includePrerelease` 语义判定,不满足时会直接停用插件,而 `0.2.2-rc.5` 与本插件触及的宿主包
|
|
47
|
+
逐字节相同)。两者都在 `package.json` 的 `engines` 里;Node 下限对齐宿主
|
|
48
|
+
`@deepseek-ai/dsh@0.2.2-rc.4`。
|
|
41
49
|
- **本包不声明任何 peerDependencies**:安装它不会带出任何 `@deepseek-ai/*` 包,模块脱离它们也能
|
|
42
50
|
加载;运行时能力(`tokenMeter`、`spillStore`、估算器、页脚格式化器)由 DSH 宿主进程提供,
|
|
43
51
|
缺失时走降级(见「宿主依赖」)。
|
|
@@ -50,16 +58,26 @@ v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**
|
|
|
50
58
|
`dsh plugin` 要求指定 profile,剩下的参数原样转发给该 profile 目录里的 pnpm:
|
|
51
59
|
|
|
52
60
|
```bash
|
|
53
|
-
# 从 registry
|
|
54
|
-
|
|
61
|
+
# 从 registry 安装:npmjs 上的 latest 是 0.1.1(本仓库 .npmrc 与 lockfile
|
|
62
|
+
# 也已钉在 npmjs,见下)
|
|
63
|
+
dsh plugin --profile <name> add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/
|
|
55
64
|
|
|
56
65
|
# 或从本地 checkout 安装(先构建;dist/ 不入库)
|
|
57
66
|
npm run build
|
|
58
67
|
dsh plugin --profile <name> add /absolute/path/to/dsh-boost
|
|
59
68
|
```
|
|
60
69
|
|
|
61
|
-
例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.
|
|
62
|
-
|
|
70
|
+
例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.1 --registry=https://registry.npmjs.org/`。
|
|
71
|
+
`dsh plugin` 把操作转发给 pnpm,所以 pnpm 必须在 PATH 上。
|
|
72
|
+
|
|
73
|
+
> **两个 registry 的版本不同,`^0.1.0` 不是安全的钉法。** `registry.npmjs.org` 上有三条版本记录:
|
|
74
|
+
> `0.1.1`(当前 `latest`)、`0.1.0`,以及首次发布时 npm 自动创建的占位版本 `0.0.0-stage`。而
|
|
75
|
+
> `registry.npmmirror.com` 目前只有 `0.1.0`(它的 `latest` 也是 0.1.0)——本仓库已把 `.npmrc`
|
|
76
|
+
> 与 lockfile 改钉 npmjs,但你机器上的全局 npm 配置可能仍指向镜像。同一个
|
|
77
|
+
> `^0.1.0` 在 npmjs 解析到 0.1.1、在镜像解析到 0.1.0——镜像用户会装到缺少 0.1.1 十项修复的
|
|
78
|
+
> 构建,其中几项是静默失效修复。请用 `dsh-boost@^0.1.1`(或 `@latest`),并在意 registry 时
|
|
79
|
+
> 显式传 `--registry=https://registry.npmjs.org/`;镜像尚未同步 0.1.1 时,不带该 flag 的
|
|
80
|
+
> `@^0.1.1` 会解析失败。
|
|
63
81
|
|
|
64
82
|
包是 ESM(`"type": "module"`),`exports` 的 `.` 条目同时映射 `require` / `default`:Node ≥ 24.9
|
|
65
83
|
下 `require('dsh-boost')` 与 `import` 加载同一份代码,装好的包里**不做任何构建**(`files` 只带
|
|
@@ -83,7 +101,7 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
|
|
|
83
101
|
可以调用它来启用。
|
|
84
102
|
|
|
85
103
|
`boost` 是**模型工具,不是 shell 命令**——这个包没有 `bin`,启用全程都要在对话里让模型调用
|
|
86
|
-
它(status、scope-set、shadow 都是工具调用,没有 CLI 等价物)。例如:
|
|
104
|
+
它(status、scope-get、scope-set、shadow 都是工具调用,没有 CLI 等价物)。例如:
|
|
87
105
|
|
|
88
106
|
> 调用 boost 工具,参数 `{"cmd":"status"}`,把 JSON 结果给我。
|
|
89
107
|
|
|
@@ -112,10 +130,13 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
|
|
|
112
130
|
```
|
|
113
131
|
|
|
114
132
|
- `workspaceIds` 是宿主的 workspace UUID,不是路径;宿主通过 workspace registry 把 agent 的
|
|
115
|
-
cwd 映射成这个 id。**发现 UUID
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
133
|
+
cwd 映射成这个 id。**发现 UUID 本身有摩擦**:要么问宿主/翻会话记录,要么自己读宿主的
|
|
134
|
+
`<hostDshHome>/storages/workspace.json` 的 `tables.workspaces`(id ↔ path 的映射表)——v1
|
|
135
|
+
没有任何命令替你做这件事。宿主的 home 解析顺序是「非空 `$DSH_HOME`(`~` 会展开)→
|
|
136
|
+
`~/.dsh`」,所以默认安装下文件是 `~/.dsh/storages/workspace.json`,**不是**
|
|
137
|
+
`$DSH_HOME/storages/workspace.json`(除非 `$DSH_HOME` 真的设了)。注意 `config.dshHome`
|
|
138
|
+
只移动插件的 `<dshHome>/boost`,不会移动宿主的这个文件。找不到 UUID 且是单用户机器时,
|
|
139
|
+
可以用 `"mode": "global"` 放开到所有**已定义**的工作区;没有工作区的会话仍然不可见。
|
|
119
140
|
- `baseRevision` 取你刚读到的 `data.scope.revision`(首次写入是 `0`)。这是 compare-and-swap:
|
|
120
141
|
revision 过期会返回 `ERR_SCOPE_REVISION_CONFLICT`,重读 `status` 再试。调用被调用方的取消
|
|
121
142
|
信号打断时返回 `ERR_SCOPE_ABORTED`:锁已释放、`scope.json` 原样未动,重读 `revision` 重试
|
|
@@ -172,8 +193,9 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
|
|
|
172
193
|
|
|
173
194
|
其中 `saveableRatio`、`byFamily`、`candidateRecall` 能决定的是**替换侧是否值得打开**:
|
|
174
195
|
白名单能兑现多少替换决策、命中落在哪些工具族、候选集召回多高——也就是替换打开后会不会
|
|
175
|
-
|
|
176
|
-
|
|
196
|
+
真的触发、主要落在哪些族。它们**不能决定发布**:v1 按正常版本发布,不把影子期收益当发布
|
|
197
|
+
门;这个决定是**实现者在设计阶段做的,不是用户裁决**——用户只接受了为期一周的影子期,没有
|
|
198
|
+
裁定影子结果是否该当发布门。它们也**不能测出节省**:报告没有总 token 分母,
|
|
177
199
|
`retrievalUpperBound` 在影子期结构性为 `0`(它只统计 `projection:'on'` 的已应用投影取回),
|
|
178
200
|
连投影的取回损害都约束不了;投影的放行依据是可见性契约(原文可经页脚取回)与事后检测,
|
|
179
201
|
不是影子标签。
|
|
@@ -248,13 +270,13 @@ scope**:`boost` 工具 schema(399)只要插件装配就常驻——`boost`
|
|
|
248
270
|
字符按 Unicode 码点计。错误回执与超过 256 KiB 的回执不投影。
|
|
249
271
|
|
|
250
272
|
不变量不是 `triggerChars ≥ headChars + tailChars + 1`。真实替换串是 head line + head + 页脚 +
|
|
251
|
-
tail + 3 个换行;页脚由宿主 `formatSpillNotice`
|
|
252
|
-
|
|
253
|
-
`400 + 100 + 50(head line) +
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
locator 与数字位数浮动。
|
|
273
|
+
tail + 3 个换行;页脚由宿主 `formatSpillNotice` 生成:68 字符 locator 加宿主固定的 66 字符
|
|
274
|
+
retrieval hint 下,3 位省略字节数是 190 字符,5 位是 192 字符。grep/glob 默认 400+100 时:
|
|
275
|
+
`400 + 100 + 50(head line) + 190(页脚) + 3 = 743 > 700`(5 位计数则是 745)。于是刚过 700、
|
|
276
|
+
约 743 以下的回执会被 `truncate` 判定“可裁”,但 `projectApply` 组装后并不短于原文,直接返回
|
|
277
|
+
原文——这是死区,不是净亏。运行时的 `assembled.length >= text.length` 检查保证投影绝不会让
|
|
278
|
+
回执变长;要消除死区,把 `triggerChars` 提到至少这个和(例如 grep/glob 用 800),或缩小窗口。
|
|
279
|
+
页脚长度会随 locator 与数字位数浮动。
|
|
258
280
|
|
|
259
281
|
(`projection: 'shadow'` 定价只含 `(Omitted N bytes.)` 省略句,不含 locator/页脚全文,所以
|
|
260
282
|
影子账的 `after` 是下界;apply 路径在写入后还会再核对一次。)
|
|
@@ -305,20 +327,51 @@ plugin manager 才能把运行中的 entry 认成本包的行、通过 profile p
|
|
|
305
327
|
|
|
306
328
|
- `scope.json`——暴露面的唯一事实来源(version 2,带 revision)。
|
|
307
329
|
- `scope.lock`——写路径的短锁,正常写入结束后删除。
|
|
308
|
-
- `receipts/<encoded-session>.jsonl
|
|
309
|
-
|
|
330
|
+
- `receipts/<encoded-session>.jsonl`——追加式收据。**收据按“决定”写,不是每次调用都写**:
|
|
331
|
+
只有发生投影、替换决策(含 skip)或越界 `skip:no-scope` 时才落一行;一个没有计划的
|
|
332
|
+
`write` / `edit` 不产生任何收据,它的参数不会被记录。每行携带元数据、回执前 256 个码点的
|
|
333
|
+
preview(不存 stdout 全文)和该调用的绑定参数 `args`(模型所写:超过 2048 个码点时以
|
|
310
334
|
`args_truncated` 标记的截断 JSON 落盘;嵌套超过 64 层时以 `args_depth_truncated` 标记,
|
|
311
|
-
并把更深的子树换成 `{ "truncated_depth": 64 }
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
`
|
|
315
|
-
|
|
316
|
-
|
|
335
|
+
并把更深的子树换成 `{ "truncated_depth": 64 }`)。**只有替换类收据**另外携带计划 goal
|
|
336
|
+
(≤256 码点)与守卫(≤8 条,各 ≤300 码点):`kind:'substitute'`、
|
|
337
|
+
`kind:'substitute-settled'`,以及 `kind:'shadow'` 且 `code:'ok'` 的影子提交。
|
|
338
|
+
`kind:'shadow'` 不是替换专用——投影影子也写 `kind:'shadow'`,但带
|
|
339
|
+
`code:'projection-shadow'`,属于投影收据,没有 plan 证据。
|
|
340
|
+
**投影收据**(`kind:'projection'`、`code:'projected'`,以及投影影子)带 `before` /
|
|
341
|
+
`after` / `saved_projection_tokens` / `unit` / `estimate` / `horizon_steps`;没有 token
|
|
342
|
+
meter 时只有 `estimate:'unknown'`,三个数值字段整体省略。**取回收据**
|
|
343
|
+
(`kind:'projection'`、`code:'projection-retrieval'`)带 `locator` 与
|
|
344
|
+
`retrieval_call_tokens` / `retrieval_content_tokens` / `retrieval_tokens`;三个取回字段
|
|
345
|
+
只在这次取回被定价时写入,未定价时 `estimate` 为 `'unknown'`、字段省略。`skip` 收据只有
|
|
346
|
+
preview 与 args(`skip:no-scope` 连这两个都没有,只记工具名)。
|
|
347
|
+
|
|
348
|
+
当前分片超过 8 MiB 或 20,000 行时,下一次写入前轮转为 `<encoded-session>.1.jsonl`;只保留
|
|
349
|
+
当前分片和它的前一份(旧的 `.1` 被覆盖)。`boost status` 先读 `.1` 再读当前分片。256 分片
|
|
350
|
+
上限按**编码后的会话名**计数:轮转出的 `.1.jsonl` 与当前文件同属一个名字,不额外占名额,
|
|
351
|
+
但扫描会把该名字下的两份都读入。
|
|
317
352
|
|
|
318
353
|
`boost status` 的投影账按每条收据自己的 `horizon_steps` 重放;没有该字段的旧收据按当前
|
|
319
354
|
horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizon_steps` 报告当前
|
|
320
355
|
生效的 horizon(活动会话的最小值;没有历史时回落到 `horizonSteps`)。
|
|
321
356
|
|
|
357
|
+
`status.data` 里还有几个不在 `degraded` 里的状态/账目字段:
|
|
358
|
+
|
|
359
|
+
- `receipts_stopped`:收据连续写失败 3 次后为 `true`。此时替换被**整体拒绝**(fail-closed,
|
|
360
|
+
不再花选择器调用或预算),投影照常;所有账目是停写前的旧快照。恢复写盘并成功追加一行后
|
|
361
|
+
计数清零、该字段回到 `false`。它是唯一说出「收据已停写」的地方——没有对应的 `degraded` 码。
|
|
362
|
+
- `protocol_suppressed`:协议段在装配时被压掉的次数(不可见工作区、没有 agent 的诊断装配,
|
|
363
|
+
以及 `complete: true` 覆盖)。装配每请求都跑,所以只计数、不写收据。
|
|
364
|
+
- `projection_locator_evictions`:因每会话 locator 上限(512 个,最旧先丢)被丢弃的 locator
|
|
365
|
+
数;大于 0 表示取回账目有损。
|
|
366
|
+
- `projection_unknown_families`:带 `mcp__` 前缀、进入投影阶段但没有匹配到工具族的调用数;
|
|
367
|
+
`projection_unknown_tools` 是其中保留的未映射工具名及次数(最多 32 个),用来发现 mapper
|
|
368
|
+
缺口。
|
|
369
|
+
- `hasWorkspaceRegistry`:宿主当前是否提供 `workspaceRegistry`;没有探测到时该键**省略**,
|
|
370
|
+
不是 `false`。
|
|
371
|
+
- `saved`:兼容旧消费者的 camelCase 账目对象(`substitution` / `projectionGross` /
|
|
372
|
+
`projectionNet` / `retrievals`),与顶层 snake_case 字段由同一次聚合派生。旧投影收据
|
|
373
|
+
(pre-T23b)没有 `saved_projection_tokens` 时,按收据里的 legacy `saved` 字段回退计价。
|
|
374
|
+
|
|
322
375
|
`projection: 'on'` 时,完整原文在替换发生**之前**写入宿主的 spill 后端,页脚 locator 可以用
|
|
323
376
|
`read` / `grep` 取回。投影不会丢掉唯一副本;spill 写入失败就不替换(收据记
|
|
324
377
|
`projection-skipped:spill-failed`,页脚渲染失败记 `projection-skipped:footer-failed`;页脚
|
|
@@ -362,7 +415,7 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
|
|
|
362
415
|
| `workspaceRegistry` | 软(`ctx.get('workspaceRegistry')`) | **工作区不可见**:cwd 永远映射不到工作区 id,一切按 fail-closed 视为不可见——协议段不注入、投影与替换全部跳过,只有 `skip:no-scope` 收据在涨;`status.degraded` 带 `ERR_HOST_NO_WORKSPACE_REGISTRY`。这是**工作区本应可见却不可见**时的宿主能力解释,不是「装上了却什么都不发生」的唯一解释:默认 `selected + []` 按设计就是惰性的且不报错;缺 token meter 会拒绝真正的替换;`complete: true` 提示段会压掉协议段 |
|
|
363
416
|
| `tokenMeter` | 软(`ctx.get('tokenMeter')`) | 拒绝替换;投影仍可用,投影账记 `unknown`(不伪造数字);`status.degraded` 带 `ERR_HOST_NO_TOKENMETER` |
|
|
364
417
|
| `spillStore` | 软(`ctx.get('spillStore')`) | `projection: 'on'` 时超限回执不投影(保住证据),收据记 `projection-skipped:no-spill`;`status.degraded` 带 `ERR_HOST_NO_SPILL`(实时探测只在 on 模式;历史收据在任何模式下都会让它出现) |
|
|
365
|
-
| `@deepseek-ai/dsh-spill-policy/notice` | 软(动态 import) | spill 后端在,但页脚渲染器 `formatSpillNotice` 加载不到/不存在:apply 模式无法拼页脚,逐条跳过(收据 `projection-skipped:no-footer`),`status.degraded` 带 `ERR_HOST_NO_SPILL_NOTICE`。这与「没有 spill 后端」的 `ERR_HOST_NO_SPILL` 是两件事 |
|
|
418
|
+
| `@deepseek-ai/dsh-spill-policy/notice` | 软(动态 import) | spill 后端在,但页脚渲染器 `formatSpillNotice` 加载不到/不存在:apply 模式无法拼页脚,逐条跳过(收据 `projection-skipped:no-footer`;页脚渲染时抛错则记 `projection-skipped:footer-failed`),`status.degraded` 带 `ERR_HOST_NO_SPILL_NOTICE`。这与「没有 spill 后端」的 `ERR_HOST_NO_SPILL` 是两件事 |
|
|
366
419
|
| (spill 后端存在但写失败) | — | 每次 `saveText` 被拒:收据 `projection-skipped:spill-failed`,`status.degraded` 带 **`ERR_HOST_SPILL_FAILING`**。这是**第三种**状态,既不是「没有后端」也不是「没有页脚渲染器」——让操作者去「恢复 spill 包」会把一个已装好却报错的包当成没装 |
|
|
367
420
|
| `@deepseek-ai/dsh-token-meter/estimate` | 软(动态 import) | 固定开销无法测量,`fixedOverheadTokens` 为 `'unknown'`;`status.degraded` 带 `ERR_HOST_NO_ESTIMATOR` |
|
|
368
421
|
| `win32` 平台 | 运行时检查 `isPosixOnly()` | 拒绝替换,投影照常;`status.degraded` 带 `ERR_HOST_PLATFORM_UNSUPPORTED` |
|
|
@@ -406,7 +459,7 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
|
|
|
406
459
|
不产出它。
|
|
407
460
|
- **影子周按设计零节省**:只记账(协议段照注入、选择器照调用),它的产出是四个比例,
|
|
408
461
|
不是省下的 token。
|
|
409
|
-
- **v1 不评判「结果更好」**:只有 token
|
|
462
|
+
- **v1 不评判「结果更好」**:只有 token 账目和一套**人工**的 20 任务回退流程(任务集不随包发布,见 `docs/RELEASE.md` §3),没有任何质量指标;「替换后
|
|
410
463
|
结果质量」在 v1 是不可判的。
|
|
411
464
|
- **投影是截断,不是精炼**:它保留头尾、丢掉中段;账本里的 before/after token 差量的是
|
|
412
465
|
「变短」,不是「变相关」。被丢掉的中段可能正是下一步决策要用的内容——`projection: 'on'`
|
|
@@ -437,7 +490,7 @@ spill,报它只会制造噪音);但**收据通道**不看当前模式—
|
|
|
437
490
|
| [设计稿](docs/superpowers/specs/2026-11-18-dsh-token-efficiency-design.md) | 目标、证据、架构、契约、度量、风险、发布形态 |
|
|
438
491
|
| [宿主契约附录](docs/superpowers/plans/2026-11-18-host-contracts.md) | 逐条抄自宿主源码的接口准绳 |
|
|
439
492
|
| [三层委派研究](docs/research/2026-11-18-three-tier-delegation.md) | 缓存、路由阈值、压缩、校验的 25 条一手来源 |
|
|
440
|
-
| [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20
|
|
493
|
+
| [发布验收](docs/RELEASE.md) | `npm run verify:package` 一条命令验收、零 peerDependencies 现状与安装规格、降级码矩阵、20 任务回退流程(人工,任务集不随包发布)、影子周与统计复算 |
|
|
441
494
|
|
|
442
495
|
## 许可证
|
|
443
496
|
|
package/dist/gate/decide.js
CHANGED
|
@@ -22,7 +22,11 @@
|
|
|
22
22
|
* 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`
|
|
23
23
|
* has nothing to verify, so it is not substitution potential either. If
|
|
24
24
|
* every survivor is trivial (including the empty plan, vacuously), the
|
|
25
|
-
* answer is `guard-trivial`.
|
|
25
|
+
* answer is `guard-trivial`. **Step admission follows (row 7).** When the
|
|
26
|
+
* caller supplies this step's `ResolvedToolSet` predicate, a candidate whose
|
|
27
|
+
* tool it does not admit is dropped before the selector is paid for: the
|
|
28
|
+
* host would reject its dispatch with `UNKNOWN_TOOL`. An emptied list is the
|
|
29
|
+
* ordinary `no-candidate`.
|
|
26
30
|
* 3. **Bind, then guard, each remaining candidate in plan order.** Binding
|
|
27
31
|
* failure drops the candidate (it does not abort the plan); only a bound
|
|
28
32
|
* candidate has its guards evaluated. Guards read the receipt for
|
|
@@ -74,6 +78,29 @@ function whitelisted(whitelist) {
|
|
|
74
78
|
return kept;
|
|
75
79
|
};
|
|
76
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Step-admission filter (row 7).
|
|
83
|
+
*
|
|
84
|
+
* The host's `ResolvedToolSet` is this step's dispatch admission. A candidate
|
|
85
|
+
* whose tool it does not list would be rejected with `UNKNOWN_TOOL` after the
|
|
86
|
+
* plugin had already paid for the selector and taken a budget step, so it is
|
|
87
|
+
* dropped here, before both. An emptied list falls through to `no-candidate`:
|
|
88
|
+
* the plan had candidates and none survived, exactly like a failed guard.
|
|
89
|
+
*
|
|
90
|
+
* A throwing membership read drops that candidate: an unverifiable tool is not
|
|
91
|
+
* one this plugin may dispatch, and dropping under-reports instead of producing
|
|
92
|
+
* a call the host rejects.
|
|
93
|
+
*/
|
|
94
|
+
function admittedBy(admitted) {
|
|
95
|
+
return (candidates) => candidates.filter((candidate) => {
|
|
96
|
+
try {
|
|
97
|
+
return admitted(candidate.tool);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
77
104
|
/**
|
|
78
105
|
* Trivial-candidate filter (rule 3).
|
|
79
106
|
*
|
|
@@ -154,7 +181,11 @@ function resolve(survivors) {
|
|
|
154
181
|
export function decide(input) {
|
|
155
182
|
const filters = input.shadow
|
|
156
183
|
? [nonTrivial]
|
|
157
|
-
: [
|
|
184
|
+
: [
|
|
185
|
+
whitelisted(input.whitelist),
|
|
186
|
+
nonTrivial,
|
|
187
|
+
...(input.admitted === undefined ? [] : [admittedBy(input.admitted)]),
|
|
188
|
+
];
|
|
158
189
|
const narrowed = narrow(input.plan.steps, filters);
|
|
159
190
|
if (!Array.isArray(narrowed))
|
|
160
191
|
return narrowed;
|
package/dist/gate/decide.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decide.js","sourceRoot":"","sources":["../../src/gate/decide.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AAGH,OAAO,EAAE,QAAQ,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C,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;aAC9D,CAAC,CAAC;SACJ,CAAA;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAA;AAC5E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,MAAM,CAAC,KAMtB;IACC,MAAM,OAAO,GAAsB,KAAK,CAAC,MAAM;QAC7C,CAAC,CAAC,CAAC,UAAU,CAAC;QACd,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,UAAU,CAAC,CAAA;IAC9C,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAClD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC7C,OAAO,OAAO,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAA;AACvE,CAAC","sourcesContent":["/**\n * Substitution decision orchestration: one parsed plan in, one decision out.\n *\n * This is the point where the gate stops describing alternatives and says what\n * to do next: commit to exactly one candidate, ask the selector to choose among\n * several, or fall back to the ordinary model turn with a code saying why. It\n * is a pure function over the plan, the receipts collected so far and the\n * whitelist — no model call, no I/O, no mutation of its inputs.\n *\n * The rule that matters most: it never guesses. Zero viable candidates is a\n * fallback with a reason, never a best-effort pick, and a candidate that fails\n * binding or a guard is dropped without a reason of its own — the plan-level\n * fallback code is the only thing the caller needs.\n *\n * Order is fixed and load-bearing:\n *\n * 1. **Whitelist first.** A candidate whose tool is not whitelisted is never\n * committed and never reaches the selector (design §5.2-5). When the plan\n * had candidates and none survives, the answer is `tool-not-whitelisted`.\n * An empty plan is not a whitelist failure: it falls through and lands in\n * `guard-trivial`, because \"nothing to verify\" is what that code means.\n * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`\n * has nothing to verify, so it is not substitution potential either. If\n * every survivor is trivial (including the empty plan, vacuously), the\n * answer is `guard-trivial`.\n * 3. **Bind, then guard, each remaining candidate in plan order.** Binding\n * failure drops the candidate (it does not abort the plan); only a bound\n * candidate has its guards evaluated. Guards read the receipt for\n * `stepId` — the step that just arrived — and an absent receipt drops every\n * candidate rather than guessing one. A `$public` template naming a node\n * that does not exist is `unresolvable` inside binding, not a separate\n * existence check here: `receipts` only ever holds steps that already ran.\n * 4. **Count.** None → `no-candidate`; one → `commit` with the *bound* args;\n * several → `ask-selector` carrying each survivor as a fresh candidate whose\n * args are its bound tree. Every decision therefore hands the caller\n * executable args — the selector path and the commit path cannot diverge by\n * binding twice, and a `$public` template never leaves this module.\n *\n * Shadow mode (`shadow: true`) skips the whitelist. The shadow week records\n * substitution *potential* for every tool family (design §5.2-5: 影子期替换\n * 不设白名单,全量记账), and a whitelist-limited shadow would only ever measure\n * the read/grep/glob three. Trivial candidates are still dropped in shadow: a\n * trivial guard means there was nothing to verify, so it is not potential.\n *\n * The returned `ask-selector.candidates` is a new array of fresh candidate\n * objects: each carries the bound args and a copied `guards` array whose guard\n * objects are copied too, so neither the plan's candidate objects, their args,\n * nor their guards can be changed through the decision. (`args` is the only\n * thing that reaches the tool call; the guard copy makes the isolation claim\n * true at every depth the caller can reach.) `commit.args` is the same freshly\n * bound tree. A `$public` template never survives into a decision.\n *\n * @module dsh-boost/gate/decide\n */\n\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport { bindArgs } from './binding.js'\nimport { evaluateAll } from './guard.js'\nimport { isTrivial, type Candidate, type Plan } from './plan.js'\n\n/** What the gate decided to do with the plan. */\nexport type Decision =\n | { kind: 'commit'; candidateId: string; args: Record<string, unknown> }\n | { kind: 'ask-selector'; candidates: Candidate[] }\n | { kind: 'fallback'; code: string }\n\n/** A filter narrows the candidate list, or ends the pipeline with a decision. */\ntype Filter = (candidates: Candidate[]) => Candidate[] | Decision\n\n/** One candidate that passed binding and its guards, with the args to run it. */\ninterface Viable {\n candidate: Candidate\n args: Record<string, unknown>\n}\n\n/** The one fallback constructor, so every early exit has the same shape. */\nfunction fallback(code: string): Decision {\n return { kind: 'fallback', code }\n}\n\n/**\n * Whitelist filter (rule 1).\n *\n * Fails the pipeline only when there was something to filter: an empty plan\n * must reach the trivial filter, where it is `guard-trivial`, not a whitelist\n * rejection.\n */\nfunction whitelisted(whitelist: ReadonlySet<string>): Filter {\n return (candidates) => {\n const kept = candidates.filter((candidate) => whitelist.has(candidate.tool))\n if (kept.length === 0 && candidates.length > 0) return fallback('tool-not-whitelisted')\n return kept\n }\n}\n\n/**\n * Trivial-candidate filter (rule 3).\n *\n * `isTrivial` is true for the empty guard list too, so this filter also turns\n * an empty plan into `guard-trivial`.\n */\nconst nonTrivial: Filter = (candidates) => {\n const kept = candidates.filter((candidate) => !isTrivial(candidate))\n return kept.length === 0 ? fallback('guard-trivial') : kept\n}\n\n/** Run filters left to right; the first decision ends the pipeline. */\nfunction narrow(candidates: Candidate[], filters: readonly Filter[]): Candidate[] | Decision {\n let kept = candidates\n for (const filter of filters) {\n const next = filter(kept)\n if (!Array.isArray(next)) return next\n kept = next\n }\n return kept\n}\n\n/**\n * Bind and verify each candidate (rule 4).\n *\n * Binding runs first: a candidate that cannot be bound is dropped before its\n * guards are ever evaluated, and the failure reason is intentionally discarded\n * — every dropped candidate is just one fewer choice, not a distinct fallback\n * for the whole plan. Guards are receipt-local to `stepId`; when that receipt\n * is absent nothing can be verified, so nothing survives.\n */\nfunction bindAndVerify(\n candidates: Candidate[],\n stepId: string,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): Viable[] {\n const receipt = receipts.get(stepId)\n if (receipt === undefined) return []\n const survivors: Viable[] = []\n for (const candidate of candidates) {\n const bound = bindArgs(candidate.args, receipts)\n if (!bound.ok) continue\n if (!evaluateAll(candidate.guards, receipt).ok) continue\n survivors.push({ candidate, args: bound.args })\n }\n return survivors\n}\n\n/**\n * Turn the survivor list into the decision (rule 5).\n *\n * Both outcomes carry the bound args, so the caller never has to bind again:\n * `commit` returns them directly, `ask-selector` returns a fresh candidate per\n * survivor and leaves the plan's objects untouched. The guard copy is one\n * level deep per guard because every `Guard` form is flat — its only nested\n * value, `json_equals.value`, is a scalar.\n */\nfunction resolve(survivors: Viable[]): Decision {\n const [only] = survivors\n if (only === undefined) return fallback('no-candidate')\n if (survivors.length > 1) {\n return {\n kind: 'ask-selector',\n candidates: survivors.map((entry) => ({\n ...entry.candidate,\n args: entry.args,\n guards: entry.candidate.guards.map((guard) => ({ ...guard })),\n })),\n }\n }\n return { kind: 'commit', candidateId: only.candidate.id, args: only.args }\n}\n\n/**\n * Decide what to do with one parsed plan.\n *\n * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can\n * record substitution potential for every tool family; everything else is the\n * same path. The function is synchronous and side-effect free.\n */\nexport function decide(input: {\n plan: Plan\n stepId: string\n receipts: ReadonlyMap<string, CanonicalReceipt>\n whitelist: ReadonlySet<string>\n shadow?: boolean\n}): Decision {\n const filters: readonly Filter[] = input.shadow\n ? [nonTrivial]\n : [whitelisted(input.whitelist), nonTrivial]\n const narrowed = narrow(input.plan.steps, filters)\n if (!Array.isArray(narrowed)) return narrowed\n return resolve(bindAndVerify(narrowed, input.stepId, input.receipts))\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decide.js","sourceRoot":"","sources":["../../src/gate/decide.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,SAAS,EAA6B,MAAM,WAAW,CAAA;AAiBhE,4EAA4E;AAC5E,SAAS,QAAQ,CAAC,IAAY;IAC5B,OAA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B,IAAI,EAAE,KAAK,CAAC,IAAI;gBAChB,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;aAC9D,CAAC,CAAC;SACJ,CAAA;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAA;AAC5E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,MAAM,CAAC,KAgBtB;IACC,MAAM,OAAO,GAAsB,KAAK,CAAC,MAAM;QAC7C,CAAC,CAAC,CAAC,UAAU,CAAC;QACd,CAAC,CAAC;YACE,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC;YAC5B,UAAU;YACV,GAAG,CAAC,KAAK,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;SACtE,CAAA;IACL,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAClD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC7C,OAAO,OAAO,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAA;AACvE,CAAC","sourcesContent":["/**\n * Substitution decision orchestration: one parsed plan in, one decision out.\n *\n * This is the point where the gate stops describing alternatives and says what\n * to do next: commit to exactly one candidate, ask the selector to choose among\n * several, or fall back to the ordinary model turn with a code saying why. It\n * is a pure function over the plan, the receipts collected so far and the\n * whitelist — no model call, no I/O, no mutation of its inputs.\n *\n * The rule that matters most: it never guesses. Zero viable candidates is a\n * fallback with a reason, never a best-effort pick, and a candidate that fails\n * binding or a guard is dropped without a reason of its own — the plan-level\n * fallback code is the only thing the caller needs.\n *\n * Order is fixed and load-bearing:\n *\n * 1. **Whitelist first.** A candidate whose tool is not whitelisted is never\n * committed and never reaches the selector (design §5.2-5). When the plan\n * had candidates and none survives, the answer is `tool-not-whitelisted`.\n * An empty plan is not a whitelist failure: it falls through and lands in\n * `guard-trivial`, because \"nothing to verify\" is what that code means.\n * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`\n * has nothing to verify, so it is not substitution potential either. If\n * every survivor is trivial (including the empty plan, vacuously), the\n * answer is `guard-trivial`. **Step admission follows (row 7).** When the\n * caller supplies this step's `ResolvedToolSet` predicate, a candidate whose\n * tool it does not admit is dropped before the selector is paid for: the\n * host would reject its dispatch with `UNKNOWN_TOOL`. An emptied list is the\n * ordinary `no-candidate`.\n * 3. **Bind, then guard, each remaining candidate in plan order.** Binding\n * failure drops the candidate (it does not abort the plan); only a bound\n * candidate has its guards evaluated. Guards read the receipt for\n * `stepId` — the step that just arrived — and an absent receipt drops every\n * candidate rather than guessing one. A `$public` template naming a node\n * that does not exist is `unresolvable` inside binding, not a separate\n * existence check here: `receipts` only ever holds steps that already ran.\n * 4. **Count.** None → `no-candidate`; one → `commit` with the *bound* args;\n * several → `ask-selector` carrying each survivor as a fresh candidate whose\n * args are its bound tree. Every decision therefore hands the caller\n * executable args — the selector path and the commit path cannot diverge by\n * binding twice, and a `$public` template never leaves this module.\n *\n * Shadow mode (`shadow: true`) skips the whitelist. The shadow week records\n * substitution *potential* for every tool family (design §5.2-5: 影子期替换\n * 不设白名单,全量记账), and a whitelist-limited shadow would only ever measure\n * the read/grep/glob three. Trivial candidates are still dropped in shadow: a\n * trivial guard means there was nothing to verify, so it is not potential.\n *\n * The returned `ask-selector.candidates` is a new array of fresh candidate\n * objects: each carries the bound args and a copied `guards` array whose guard\n * objects are copied too, so neither the plan's candidate objects, their args,\n * nor their guards can be changed through the decision. (`args` is the only\n * thing that reaches the tool call; the guard copy makes the isolation claim\n * true at every depth the caller can reach.) `commit.args` is the same freshly\n * bound tree. A `$public` template never survives into a decision.\n *\n * @module dsh-boost/gate/decide\n */\n\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\nimport { bindArgs } from './binding.js'\nimport { evaluateAll } from './guard.js'\nimport { isTrivial, type Candidate, type Plan } from './plan.js'\n\n/** What the gate decided to do with the plan. */\nexport type Decision =\n | { kind: 'commit'; candidateId: string; args: Record<string, unknown> }\n | { kind: 'ask-selector'; candidates: Candidate[] }\n | { kind: 'fallback'; code: string }\n\n/** A filter narrows the candidate list, or ends the pipeline with a decision. */\ntype Filter = (candidates: Candidate[]) => Candidate[] | Decision\n\n/** One candidate that passed binding and its guards, with the args to run it. */\ninterface Viable {\n candidate: Candidate\n args: Record<string, unknown>\n}\n\n/** The one fallback constructor, so every early exit has the same shape. */\nfunction fallback(code: string): Decision {\n return { kind: 'fallback', code }\n}\n\n/**\n * Whitelist filter (rule 1).\n *\n * Fails the pipeline only when there was something to filter: an empty plan\n * must reach the trivial filter, where it is `guard-trivial`, not a whitelist\n * rejection.\n */\nfunction whitelisted(whitelist: ReadonlySet<string>): Filter {\n return (candidates) => {\n const kept = candidates.filter((candidate) => whitelist.has(candidate.tool))\n if (kept.length === 0 && candidates.length > 0) return fallback('tool-not-whitelisted')\n return kept\n }\n}\n\n/**\n * Step-admission filter (row 7).\n *\n * The host's `ResolvedToolSet` is this step's dispatch admission. A candidate\n * whose tool it does not list would be rejected with `UNKNOWN_TOOL` after the\n * plugin had already paid for the selector and taken a budget step, so it is\n * dropped here, before both. An emptied list falls through to `no-candidate`:\n * the plan had candidates and none survived, exactly like a failed guard.\n *\n * A throwing membership read drops that candidate: an unverifiable tool is not\n * one this plugin may dispatch, and dropping under-reports instead of producing\n * a call the host rejects.\n */\nfunction admittedBy(admitted: (tool: string) => boolean): Filter {\n return (candidates) =>\n candidates.filter((candidate) => {\n try {\n return admitted(candidate.tool)\n } catch {\n return false\n }\n })\n}\n\n/**\n * Trivial-candidate filter (rule 3).\n *\n * `isTrivial` is true for the empty guard list too, so this filter also turns\n * an empty plan into `guard-trivial`.\n */\nconst nonTrivial: Filter = (candidates) => {\n const kept = candidates.filter((candidate) => !isTrivial(candidate))\n return kept.length === 0 ? fallback('guard-trivial') : kept\n}\n\n/** Run filters left to right; the first decision ends the pipeline. */\nfunction narrow(candidates: Candidate[], filters: readonly Filter[]): Candidate[] | Decision {\n let kept = candidates\n for (const filter of filters) {\n const next = filter(kept)\n if (!Array.isArray(next)) return next\n kept = next\n }\n return kept\n}\n\n/**\n * Bind and verify each candidate (rule 4).\n *\n * Binding runs first: a candidate that cannot be bound is dropped before its\n * guards are ever evaluated, and the failure reason is intentionally discarded\n * — every dropped candidate is just one fewer choice, not a distinct fallback\n * for the whole plan. Guards are receipt-local to `stepId`; when that receipt\n * is absent nothing can be verified, so nothing survives.\n */\nfunction bindAndVerify(\n candidates: Candidate[],\n stepId: string,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): Viable[] {\n const receipt = receipts.get(stepId)\n if (receipt === undefined) return []\n const survivors: Viable[] = []\n for (const candidate of candidates) {\n const bound = bindArgs(candidate.args, receipts)\n if (!bound.ok) continue\n if (!evaluateAll(candidate.guards, receipt).ok) continue\n survivors.push({ candidate, args: bound.args })\n }\n return survivors\n}\n\n/**\n * Turn the survivor list into the decision (rule 5).\n *\n * Both outcomes carry the bound args, so the caller never has to bind again:\n * `commit` returns them directly, `ask-selector` returns a fresh candidate per\n * survivor and leaves the plan's objects untouched. The guard copy is one\n * level deep per guard because every `Guard` form is flat — its only nested\n * value, `json_equals.value`, is a scalar.\n */\nfunction resolve(survivors: Viable[]): Decision {\n const [only] = survivors\n if (only === undefined) return fallback('no-candidate')\n if (survivors.length > 1) {\n return {\n kind: 'ask-selector',\n candidates: survivors.map((entry) => ({\n ...entry.candidate,\n args: entry.args,\n guards: entry.candidate.guards.map((guard) => ({ ...guard })),\n })),\n }\n }\n return { kind: 'commit', candidateId: only.candidate.id, args: only.args }\n}\n\n/**\n * Decide what to do with one parsed plan.\n *\n * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can\n * record substitution potential for every tool family; everything else is the\n * same path. The function is synchronous and side-effect free.\n */\nexport function decide(input: {\n plan: Plan\n stepId: string\n receipts: ReadonlyMap<string, CanonicalReceipt>\n whitelist: ReadonlySet<string>\n shadow?: boolean\n /**\n * Whether this step's `ResolvedToolSet` admits a tool (row 7).\n *\n * `undefined` means the admission evidence is unavailable (an embedded or\n * legacy call site); the caller proceeds and records the missing evidence\n * itself, because refusing on absence would silently disable substitution on\n * paths it cannot enumerate. Shadow mode ignores the predicate: shadow\n * measures potential, not dispatchability.\n */\n admitted?: (tool: string) => boolean\n}): Decision {\n const filters: readonly Filter[] = input.shadow\n ? [nonTrivial]\n : [\n whitelisted(input.whitelist),\n nonTrivial,\n ...(input.admitted === undefined ? [] : [admittedBy(input.admitted)]),\n ]\n const narrowed = narrow(input.plan.steps, filters)\n if (!Array.isArray(narrowed)) return narrowed\n return resolve(bindAndVerify(narrowed, input.stepId, input.receipts))\n}\n"]}
|