dsh-boost 0.1.0 → 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.
Files changed (54) hide show
  1. package/README.en.md +184 -70
  2. package/README.md +148 -59
  3. package/dist/gate/decide.js +33 -2
  4. package/dist/gate/decide.js.map +1 -1
  5. package/dist/hooks/llm-stream.js +242 -89
  6. package/dist/hooks/llm-stream.js.map +1 -1
  7. package/dist/hooks/post-execute.js +282 -25
  8. package/dist/hooks/post-execute.js.map +1 -1
  9. package/dist/hooks/session-state.js +18 -8
  10. package/dist/hooks/session-state.js.map +1 -1
  11. package/dist/host/root.js +22 -1
  12. package/dist/host/root.js.map +1 -1
  13. package/dist/index.js +494 -72
  14. package/dist/index.js.map +1 -1
  15. package/dist/scope/doc.js.map +1 -1
  16. package/dist/scope/store.js +24 -9
  17. package/dist/scope/store.js.map +1 -1
  18. package/dist/tools/boost.js +37 -4
  19. package/dist/tools/boost.js.map +1 -1
  20. package/dist/types.d.ts +18 -1
  21. package/dist/types.js.map +1 -1
  22. package/package.json +10 -6
  23. package/dist/admission/fixed-cost.d.ts +0 -23
  24. package/dist/admission/ledger.d.ts +0 -113
  25. package/dist/admission/retrieval.d.ts +0 -65
  26. package/dist/admission/usage.d.ts +0 -75
  27. package/dist/config.d.ts +0 -43
  28. package/dist/gate/binding.d.ts +0 -113
  29. package/dist/gate/decide.d.ts +0 -82
  30. package/dist/gate/guard.d.ts +0 -69
  31. package/dist/gate/invalidate.d.ts +0 -112
  32. package/dist/gate/plan.d.ts +0 -86
  33. package/dist/hooks/clock.d.ts +0 -68
  34. package/dist/hooks/execute.d.ts +0 -79
  35. package/dist/hooks/llm-stream.d.ts +0 -276
  36. package/dist/hooks/pending.d.ts +0 -89
  37. package/dist/hooks/post-execute.d.ts +0 -247
  38. package/dist/hooks/session-state.d.ts +0 -158
  39. package/dist/hooks/synthesize.d.ts +0 -74
  40. package/dist/host/loader.d.ts +0 -23
  41. package/dist/host/platform.d.ts +0 -18
  42. package/dist/host/root.d.ts +0 -18
  43. package/dist/projection/apply.d.ts +0 -174
  44. package/dist/projection/canonicalise.d.ts +0 -43
  45. package/dist/projection/counters.d.ts +0 -65
  46. package/dist/projection/truncate.d.ts +0 -47
  47. package/dist/prompt/protocol.d.ts +0 -45
  48. package/dist/receipts/store.d.ts +0 -198
  49. package/dist/scope/doc.d.ts +0 -117
  50. package/dist/scope/resolve.d.ts +0 -91
  51. package/dist/scope/store.d.ts +0 -135
  52. package/dist/selector/jev.d.ts +0 -93
  53. package/dist/tools/boost.d.ts +0 -367
  54. package/dist/tools/family.d.ts +0 -26
@@ -1,65 +0,0 @@
1
- /**
2
- * Projection retrieval accounting: the denominator of `projection_net_tokens`.
3
- *
4
- * The projection ledger's gross saving is what the plugin removed from the
5
- * history; the net saving must subtract what the model spent reading the
6
- * spilled original back. `projection_retrievals` counts those reads (design
7
- * §5.3), and its producer is the `read`/`grep` call that names one of this
8
- * session's spill locators. A retrieval that is not counted would make every
9
- * projection look free, which is why this is a ledger and not a statistic.
10
- *
11
- * The matcher is pure — `(params, locators) → boolean` — so the hook can call
12
- * it against the locators recorded when a receipt was actually spilled. The
13
- * per-session ledger is deliberately small and bounded: it keeps the most
14
- * recent {@link MAX_LOCATORS_PER_SESSION} locators, because a long session
15
- * projects far more artifacts than its model ever reads back and the ledger is
16
- * an audit aid, not a cache of the spill store.
17
- *
18
- * @module dsh-boost/admission/retrieval
19
- */
20
- /**
21
- * Whether a tool call's arguments name one of the given spill locators.
22
- *
23
- * Total by construction: malformed, cyclic or hostile arguments return `false`
24
- * rather than throwing, because this runs inside the host's `post-execute`
25
- * waterfall where a throw would replace the tool result with an error.
26
- */
27
- export declare function recordRetrieval(params: unknown, locators: ReadonlySet<string>): boolean;
28
- /**
29
- * The spill locators a session's projected receipts left behind.
30
- *
31
- * One instance belongs to the plugin instance; `apply` passes it through
32
- * `HookDeps` and `clearSession` drops a session's set on `session/disposed`, so
33
- * a disposed session cannot leak locators into the next one.
34
- */
35
- export declare class RetrievalLedger {
36
- private readonly bySession;
37
- /** Locators dropped by the cap, across every session; exposed by status. */
38
- private evictedCount;
39
- /** Remember one applied projection's locator; `true` when it was new. */
40
- record(sessionId: string, locator: string): boolean;
41
- /** The locators currently remembered for `sessionId` (empty when unknown). */
42
- locatorsOf(sessionId: string): ReadonlySet<string>;
43
- /**
44
- * The matched locator for this call, or `undefined` when it is not a retrieval.
45
- *
46
- * Goes through the exported {@link recordRetrieval} predicate first, so the
47
- * production hook and the documented obligation share one decision; the
48
- * second walk only runs on a hit and is what puts the locator on the receipt.
49
- */
50
- locate(sessionId: string, params: unknown): string | undefined;
51
- /** Whether this call retrieves a spilled artifact. */
52
- hit(sessionId: string, params: unknown): boolean;
53
- /** Drop one session's locators (session end). */
54
- clear(sessionId: string): void;
55
- /** Number of sessions currently holding locators. */
56
- size(): number;
57
- /**
58
- * Locators the cap has dropped since process start.
59
- *
60
- * A silent eviction would make later re-reads uncounted and flatter the net
61
- * account; status reports this so an operator can see the ledger is lossy
62
- * rather than assume every retrieval was seen.
63
- */
64
- evictions(): number;
65
- }
@@ -1,75 +0,0 @@
1
- /**
2
- * Usage pairing: turn two consecutive model requests into the measured saving
3
- * of one substitution (design §5.3).
4
- *
5
- * When the plugin substitutes a call, the model is not asked for that step, so
6
- * the next real request replays a shorter history. The saving is therefore
7
- * measured as the size of that next request — `input + cacheRead`, because the
8
- * host reports `inputTokens` excluding cache reads — never estimated. A missing
9
- * next request is `'unknown'`; an interpolated number would be indistinguishable
10
- * from a measurement once written to a receipt.
11
- *
12
- * The ledger keeps two request slots plus a mark: `latest`, the first request
13
- * after the mark, and the mark itself — which holds the request that preceded
14
- * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no
15
- * timers, no I/O, no host calls.
16
- *
17
- * @module dsh-boost/admission/usage
18
- */
19
- /** One model request's raw counts, mapped from the `llm/stream` usage chunk. */
20
- export interface Usage {
21
- input: number;
22
- cacheRead: number;
23
- output: number;
24
- }
25
- /**
26
- * Pairs two consecutive model requests around one substitution.
27
- *
28
- * The pairing target is the FIRST request after the mark, never the latest:
29
- * when a caller forgets to settle, a later unrelated request must not be
30
- * attributed to the substitution. `settle()` consumes the mark and clears the
31
- * pairing slots; `last()` is a pure reader and survives it.
32
- */
33
- export declare class UsageLedger {
34
- private latest;
35
- private hasMark;
36
- private beforeMark;
37
- private afterMark;
38
- private candidateId;
39
- /**
40
- * Record one real request. The first request after a mark claims the pairing
41
- * slot and keeps it; later requests only advance `last()`.
42
- */
43
- request(u: Usage): void;
44
- /** Most recent request, or `undefined` before the first one. Never consumes. */
45
- last(): Usage | undefined;
46
- /**
47
- * Record that a substitution just happened.
48
- *
49
- * `candidateId` is kept only so the caller can pair `settle()` with the right
50
- * substitution receipt (`pendingCandidateId()`); it never changes the
51
- * arithmetic. A new mark discards any unconsumed pairing and starts over from
52
- * the current latest request.
53
- */
54
- markSubstituted(candidateId: string): void;
55
- /** Id of the pending mark, or `undefined` before a mark and after `settle()`. */
56
- pendingCandidateId(): string | undefined;
57
- /**
58
- * Consume the mark and report the substitution's measured cost.
59
- *
60
- * `saved_input_tokens` is the first after-mark request's `input + cacheRead`;
61
- * `output_tokens` is that request's `output`, a third count that is never
62
- * folded into input. Both are `'unknown'` when no usable request arrived after
63
- * the mark — never a copy of the previous request's numbers. `cache_hit_delta`
64
- * is the after-mark hit rate minus the pre-mark hit rate, `null` when either
65
- * side cannot be told (a `null` delta means "cannot tell", not zero).
66
- *
67
- * A second `settle()` has nothing left to consume and reports the same
68
- * `'unknown'` / `null`.
69
- */
70
- settle(): {
71
- saved_input_tokens: number | 'unknown';
72
- cache_hit_delta: number | null;
73
- output_tokens: number | 'unknown';
74
- };
75
- }
package/dist/config.d.ts DELETED
@@ -1,43 +0,0 @@
1
- /**
2
- * Configuration defaults and resolution.
3
- *
4
- * The host's patch replaces the plugin `config` wholesale (design §11), so a
5
- * missing key never means "keep the previous value": `resolveConfig` merges the
6
- * host object over `DEFAULT_CONFIG` one key at a time. A key whose value is
7
- * malformed falls back to its own default rather than raising — a bad overlay
8
- * degrades to design defaults, it does not break plugin loading.
9
- *
10
- * ## Validation
11
- *
12
- * A finite number is not automatically a usable value. Negative or fractional
13
- * projection windows, budgets and counts are rejected or clamped here rather
14
- * than flowing into the decision path: a negative `triggerChars` would make
15
- * every receipt a candidate and a negative `selector.maxTokens` would reach the
16
- * selector LLM. Every repair is reported through the optional callback so the
17
- * operator sees the effective value instead of a silent fallback, and
18
- * `projection.*.headChars + tailChars` must stay below `triggerChars` (design
19
- * §5.3: a window at or above the trigger cannot cut anything).
20
- *
21
- * Unknown keys are ignored: hosts may hand a superset of `BoostConfig`.
22
- *
23
- * @module dsh-boost/config
24
- */
25
- import type { BoostConfig } from './types.js';
26
- /** Design defaults; must stay verbatim in sync with `cordis.patch.yml` (§5.3). */
27
- export declare const DEFAULT_CONFIG: BoostConfig;
28
- /** Receives one human-readable line per repaired configuration key. */
29
- export type ConfigRepair = (message: string) => void;
30
- /**
31
- * Turn whatever the host hands `apply` into a complete `BoostConfig`.
32
- *
33
- * Always returns a fresh deep copy, so callers cannot mutate `DEFAULT_CONFIG`.
34
- * Non-object input resolves to the defaults. `onRepair` receives one line per
35
- * key that was rejected, clamped or repaired; it is never called for a valid
36
- * value.
37
- *
38
- * Total: it never throws. The host hands `apply` an arbitrary object, so a
39
- * throwing getter anywhere in the tree (or a throwing `onRepair` sink) aborts
40
- * the resolution and returns a fresh copy of `DEFAULT_CONFIG` rather than
41
- * escaping as a plugin-load failure (review row 68).
42
- */
43
- export declare function resolveConfig(raw: unknown, onRepair?: ConfigRepair): BoostConfig;
@@ -1,113 +0,0 @@
1
- /**
2
- * `$public` argument binding: the anti-forgery core of the gate.
3
- *
4
- * A plan is written by the model with literal arguments, except for values that
5
- * only exist after an earlier step has run. Those are written as a template
6
- * `{ "$public": { "after": "A", "field": "name" } }`, and this module fills the
7
- * template in from the named receipt. The point is mechanical projection: a
8
- * value that the model reads and then re-types can be steered by whatever the
9
- * value contains, so the value is copied from the receipt text instead of being
10
- * reproduced by the model.
11
- *
12
- * Uniqueness is the whole safety rule. A field is usable only when it appears
13
- * exactly once, as a quoted string, on its own line (`name: "v"` / `name="v"`);
14
- * zero matches, two matches, or an unquoted right-hand side are all
15
- * `ambiguous`, and ambiguity means the slow path — never a guess. `$scalar`
16
- * and `$single` are whole-text forms, so they are unique by construction;
17
- * `$single` additionally refuses a value that spans a line.
18
- *
19
- * A line boundary is LF, CR, CRLF, NEL (U+0085), U+2028 or U+2029, so a
20
- * duplicate cannot hide behind one of these common separator conventions.
21
- * Identifier projection scans each line once with an anchored, non-global regex
22
- * instead of running one cross-line global regex: the latter re-consumes the
23
- * remaining whitespace at every line start, which is quadratic on a
24
- * blank-line-heavy receipt. The identifier form's closing quote must not be
25
- * escaped: a captured value ending in an odd run of backslashes means the quote
26
- * that ended the match was itself escaped, so the line abstains instead of
27
- * binding a truncated prefix (`C:\x` ends in `x` and still binds).
28
- *
29
- * Two scoping consequences are deliberate: a second assignment later on the
30
- * same line is not counted (`name: "a" name: "b"` binds `a`), and a line whose
31
- * right-hand side is not double-quoted is not a match at all (`name: "a"`
32
- * followed by `name: b` binds `a`). In both cases the projected value is the
33
- * line-start quoted occurrence, so nothing attacker-chosen is projected.
34
- *
35
- * Within the gate's contract — `args` from `parsePlan`, receipts from
36
- * `canonicalise` — failures are values, never throws, and the order is fixed: a
37
- * missing graph node is `unresolvable`, an errored or empty receipt is
38
- * `missing-receipt`, a receipt that is not exactly one text block is
39
- * `not-single-text`, and a non-unique projection is `ambiguous`. The function
40
- * does not re-validate those inputs: a `null` receipt value, a `null` args, a
41
- * cyclic tree, or an array passed as `args` would throw or be miscast. All of
42
- * these are unreachable through `parsePlan`/`canonicalise`.
43
- *
44
- * Two containers fail closed. The root `args` object can never be a template
45
- * (`unresolvable`): a template replaces one value with a scalar, and an
46
- * argument object is not a scalar. Any other object that carries a `$public`
47
- * key but is not a well-formed template — extra keys alongside it, a
48
- * non-object value, extra keys inside it — is also `unresolvable`, so a
49
- * malformed template never reaches the host as a literal `$public` argument.
50
- * `field` is model-controlled, so it is regex-escaped, must be non-empty, and
51
- * may only start with `$` when it is exactly `$scalar` or `$single`.
52
- *
53
- * `textBlocks` (not `blocks.length`) decides `not-single-text`, because only
54
- * text blocks contribute to `text`. `empty` is defined by `canonicalise` as
55
- * `text.length === 0`; a receipt that contradicts that invariant (empty text
56
- * with `empty: false`) is treated as `missing-receipt` rather than projected,
57
- * since there is no text to project from and the contradiction is a producer
58
- * bug, not something to guess around.
59
- *
60
- * `args` comes from `JSON.parse`, so it is acyclic and already depth-capped by
61
- * plan parsing. Binding returns a fresh tree and never mutates its input.
62
- *
63
- * @module dsh-boost/gate/binding
64
- */
65
- import type { CanonicalReceipt } from '../projection/canonicalise.js';
66
- /** The one well-formed template: a single `$public` key with two string fields. */
67
- export type PublicTemplate = {
68
- $public: {
69
- after: 'root' | string;
70
- field: string;
71
- };
72
- };
73
- /** Why a value could not be projected; every one is a fallback to the model. */
74
- type BindFailure = 'ambiguous' | 'unresolvable' | 'missing-receipt' | 'not-single-text';
75
- /** A successful binding or the single reason it was abandoned. */
76
- type BindResult = {
77
- ok: true;
78
- args: Record<string, unknown>;
79
- } | {
80
- ok: false;
81
- reason: BindFailure;
82
- };
83
- /**
84
- * Project one field out of a receipt's canonical text.
85
- *
86
- * `undefined` always means "cannot use this"; callers turn it into `ambiguous`.
87
- * Empty fields and unknown `$`-prefixed fields are rejected before touching the
88
- * text, and identifier fields are matched literally.
89
- */
90
- export declare function extractField(text: string, field: string): string | undefined;
91
- /**
92
- * Whether `value` is the sanctioned template shape, and nothing else.
93
- *
94
- * A plain object with exactly one own key, `$public`, whose value is an object
95
- * with exactly the two string keys `after` and `field`. Extra keys on either
96
- * level are rejected rather than silently dropped: this module only understands
97
- * `after`/`field`, and a template with a third directive is not something the
98
- * host may receive.
99
- */
100
- export declare function isTemplate(value: unknown): value is PublicTemplate;
101
- /**
102
- * Bind every `$public` template in `args` against the receipts of earlier
103
- * steps.
104
- *
105
- * The root object is checked separately and can never be a template: it is an
106
- * argument object, while a template produces a scalar. The same check rejects a
107
- * root that merely carries a `$public` key alongside other keys.
108
- *
109
- * Returns a fresh `args` tree on success, or one reason the whole plan must
110
- * fall back to the model. There is no partial result and no mutation.
111
- */
112
- export declare function bindArgs(args: Record<string, unknown>, receipts: ReadonlyMap<string, CanonicalReceipt>): BindResult;
113
- export {};
@@ -1,82 +0,0 @@
1
- /**
2
- * Substitution decision orchestration: one parsed plan in, one decision out.
3
- *
4
- * This is the point where the gate stops describing alternatives and says what
5
- * to do next: commit to exactly one candidate, ask the selector to choose among
6
- * several, or fall back to the ordinary model turn with a code saying why. It
7
- * is a pure function over the plan, the receipts collected so far and the
8
- * whitelist — no model call, no I/O, no mutation of its inputs.
9
- *
10
- * The rule that matters most: it never guesses. Zero viable candidates is a
11
- * fallback with a reason, never a best-effort pick, and a candidate that fails
12
- * binding or a guard is dropped without a reason of its own — the plan-level
13
- * fallback code is the only thing the caller needs.
14
- *
15
- * Order is fixed and load-bearing:
16
- *
17
- * 1. **Whitelist first.** A candidate whose tool is not whitelisted is never
18
- * committed and never reaches the selector (design §5.2-5). When the plan
19
- * had candidates and none survives, the answer is `tool-not-whitelisted`.
20
- * An empty plan is not a whitelist failure: it falls through and lands in
21
- * `guard-trivial`, because "nothing to verify" is what that code means.
22
- * 2. **Trivial candidates next.** A candidate whose guards are only `ok: true`
23
- * has nothing to verify, so it is not substitution potential either. If
24
- * every survivor is trivial (including the empty plan, vacuously), the
25
- * answer is `guard-trivial`.
26
- * 3. **Bind, then guard, each remaining candidate in plan order.** Binding
27
- * failure drops the candidate (it does not abort the plan); only a bound
28
- * candidate has its guards evaluated. Guards read the receipt for
29
- * `stepId` — the step that just arrived — and an absent receipt drops every
30
- * candidate rather than guessing one. A `$public` template naming a node
31
- * that does not exist is `unresolvable` inside binding, not a separate
32
- * existence check here: `receipts` only ever holds steps that already ran.
33
- * 4. **Count.** None → `no-candidate`; one → `commit` with the *bound* args;
34
- * several → `ask-selector` carrying each survivor as a fresh candidate whose
35
- * args are its bound tree. Every decision therefore hands the caller
36
- * executable args — the selector path and the commit path cannot diverge by
37
- * binding twice, and a `$public` template never leaves this module.
38
- *
39
- * Shadow mode (`shadow: true`) skips the whitelist. The shadow week records
40
- * substitution *potential* for every tool family (design §5.2-5: 影子期替换
41
- * 不设白名单,全量记账), and a whitelist-limited shadow would only ever measure
42
- * the read/grep/glob three. Trivial candidates are still dropped in shadow: a
43
- * trivial guard means there was nothing to verify, so it is not potential.
44
- *
45
- * The returned `ask-selector.candidates` is a new array of fresh candidate
46
- * objects: each carries the bound args and a copied `guards` array whose guard
47
- * objects are copied too, so neither the plan's candidate objects, their args,
48
- * nor their guards can be changed through the decision. (`args` is the only
49
- * thing that reaches the tool call; the guard copy makes the isolation claim
50
- * true at every depth the caller can reach.) `commit.args` is the same freshly
51
- * bound tree. A `$public` template never survives into a decision.
52
- *
53
- * @module dsh-boost/gate/decide
54
- */
55
- import type { CanonicalReceipt } from '../projection/canonicalise.js';
56
- import { type Candidate, type Plan } from './plan.js';
57
- /** What the gate decided to do with the plan. */
58
- export type Decision = {
59
- kind: 'commit';
60
- candidateId: string;
61
- args: Record<string, unknown>;
62
- } | {
63
- kind: 'ask-selector';
64
- candidates: Candidate[];
65
- } | {
66
- kind: 'fallback';
67
- code: string;
68
- };
69
- /**
70
- * Decide what to do with one parsed plan.
71
- *
72
- * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can
73
- * record substitution potential for every tool family; everything else is the
74
- * same path. The function is synchronous and side-effect free.
75
- */
76
- export declare function decide(input: {
77
- plan: Plan;
78
- stepId: string;
79
- receipts: ReadonlyMap<string, CanonicalReceipt>;
80
- whitelist: ReadonlySet<string>;
81
- shadow?: boolean;
82
- }): Decision;
@@ -1,69 +0,0 @@
1
- /**
2
- * Guard evaluation: the zero-token admission check on a receipt.
3
- *
4
- * A guard is a predicate over the canonical receipt a call produced. It is the
5
- * only verification the fast path gets, so the rule is fail-closed: every
6
- * ambiguity — a pointer that is not RFC 6901, a segment that cannot name an
7
- * array element, a path that runs into a scalar, a value of the wrong type —
8
- * is `fail`, never `pass`, and no path throws.
9
- *
10
- * `ok` reads `isError`, never the text, and only a literal `ok: true` passes.
11
- * `text_contains` / `text_not_contains` are byte-faithful, case-sensitive
12
- * `String#includes` checks on the canonical text: no trim, no normalisation,
13
- * no regex.
14
- *
15
- * The evaluators do not rely on `parsePlan` having rejected bad guards: within
16
- * the forms, `ok` must be literally `true`, an empty `text_contains` operand
17
- * is a `fail` rather than vacuously true (`text_not_contains: ''` is already
18
- * vacuously false), and a non-object guard is a `fail` instead of a throw.
19
- *
20
- * `json_equals` parses the whole text as JSON and walks the pointer by hand.
21
- * A pointer is `''` (the whole document) or starts with `/`; anything else is
22
- * malformed. Resolution follows only own properties (`Object.hasOwn`), so
23
- * `/__proto__` and `/constructor` cannot read an inherited value. An array
24
- * accepts only canonical decimal indices (`0`, `12` — not `01`, `1.0`, `-`,
25
- * ` 1` or `+1`) that are inside its length, and a segment applied to a
26
- * non-container fails. Escapes are RFC 6901: `~1` is `/` and `~0` is `~`
27
- * (`~01` is therefore the literal `~1`), and any other `~` sequence is
28
- * malformed even when the raw segment is a real key.
29
- *
30
- * Comparison is `===`, deliberately not `==`: `1` is not `'1'`, and `true` is
31
- * not `1`. JSON cannot produce `NaN`, and `null`, arrays and objects can never
32
- * equal a `string | number | boolean`, so a resolved value of one of those
33
- * kinds fails. A JSON parse error is a `fail` value, not an exception.
34
- *
35
- * `GuardResult` includes `'unknown'` because the task interface names it, but
36
- * no v1 guard form is undecidable: this module returns only `'pass'` or
37
- * `'fail'`. There is no fifth form (`exit_code` / `stderr_empty` are forbidden
38
- * by design §5.2), so a guard matching none of the four forms fails closed.
39
- *
40
- * Within the gate's contract, guards come from `parsePlan` (exactly one form
41
- * key per guard) and receipts from `canonicalise`; the defensive checks above
42
- * are this module's floor, not a full re-validation of either input. A receipt
43
- * is never projected here — guards read the canonical original.
44
- *
45
- * @module dsh-boost/gate/guard
46
- */
47
- import type { CanonicalReceipt } from '../projection/canonicalise.js';
48
- import type { Guard } from './plan.js';
49
- /**
50
- * Outcome of one guard. `'unknown'` is part of the agreed interface but is
51
- * never produced: every guard form v1 accepts is decidable.
52
- */
53
- export type GuardResult = 'pass' | 'fail' | 'unknown';
54
- /**
55
- * Evaluate one guard. Dispatch is by presence of the form key, so a guard
56
- * matching none of the four forms falls through to `fail` instead of passing.
57
- * A non-object guard fails before dispatch: the `in` operator would throw, and
58
- * throwing would abort the turn instead of falling back to the model.
59
- */
60
- export declare function evaluateGuard(g: Guard, r: CanonicalReceipt): GuardResult;
61
- /**
62
- * Evaluate guards left to right and stop at the first failure. An empty list
63
- * passes vacuously. `failed` is the exact guard object passed in, so a caller
64
- * can identify which guard rejected the receipt.
65
- */
66
- export declare function evaluateAll(guards: Guard[], r: CanonicalReceipt): {
67
- ok: boolean;
68
- failed?: Guard;
69
- };
@@ -1,112 +0,0 @@
1
- /**
2
- * External invalidation sources and the double-projection guard.
3
- *
4
- * These are **pure predicates over a text the caller supplies**. They do not
5
- * read the session, the history, or any host service, and they cannot by
6
- * themselves observe that the host rewrote anything: only a caller that holds
7
- * the anchored receipt's current text can.
8
- *
9
- * The host has two external rewrite sources (design §5.2-7):
10
- *
11
- * - the tool-result pruner replaces an oversized **session surface node's**
12
- * middle in place with a fixed marker, at a step boundary before a model
13
- * request;
14
- * - compaction replaces older history with a summary, so a stored anchor no
15
- * longer names any text the model can see.
16
- *
17
- * Either way the anchor is stale: projecting from it would emit a value out of
18
- * text the model can no longer see, and a guard evaluated against the old text
19
- * would claim a check the model never gets. Both must abandon the decision and
20
- * fall back to the main model (design §5.2-3).
21
- *
22
- * **Where each source is observable.** The pruner never touches the object
23
- * flowing through the `tools/post-execute` waterfall — it rewrites surface
24
- * nodes before a model request (`dsh-compaction-basic`). A `post-execute`
25
- * listener therefore cannot see the pruner's output, and `looksPruned` there
26
- * only catches a receipt whose **tool output itself** happens to contain the
27
- * 39-byte literal (for example, a `read` of a session log). That is a safe
28
- * conservative outcome, not pruner detection. The caller that can observe a
29
- * pruned or compacted receipt is the **model-request path** (`llm/stream`,
30
- * `options.messages`); the stream hook owns that identity check with its own
31
- * anchor probes plus `looksPruned` below. Nothing here claims the
32
- * post-execute call site detects the host pruner or compaction.
33
- *
34
- * The second guard is independent and simpler: a receipt that already carries
35
- * the host spill footer has been retained once already, so projecting it again
36
- * would hide the original twice and point the model at a second-hand footer.
37
- * The notice predicate is injected rather than imported — the host's spill
38
- * policy is an optional peer and its recognition rule belongs to the caller.
39
- *
40
- * Everything here is pure: a string comparison, a predicate call, and a plain
41
- * session-keyed map with no persistence, timers, or I/O. The hook that consumes
42
- * these functions must never throw (the host turns a throwing listener into a
43
- * tool error and loses the real output, `dsh-tools/lib/pipeline.js:538-550`),
44
- * so the hook wraps the calls; these functions themselves are total — a
45
- * malformed anchor record yields `undefined`, never a `TypeError`.
46
- *
47
- * @module dsh-boost/gate/invalidate
48
- */
49
- /**
50
- * The host pruner's exact replacement marker.
51
- *
52
- * Verified against the installed package rather than copied from the plan:
53
- * `@deepseek-ai/dsh-compaction-tool-result-pruner@0.2.2-rc.4`, source
54
- * `src/config.ts:7` (`export const PRUNE_MARKER = '\n\n[... tool result middle
55
- * pruned ...]\n\n'`), compiled as `lib/index.js:8`. It matches the plan's
56
- * literal exactly. Do not "clean up" the surrounding blank lines: they are part
57
- * of the injected span and of this comparison.
58
- */
59
- export declare const PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
60
- /**
61
- * What the decision path remembers about one substitution step.
62
- *
63
- * `anchors` maps a receipt id to the canonical original text as it arrived;
64
- * `stepId` names the step the anchors belong to. This is an anchor record, not
65
- * a dispatch queue: the pending-substitution queue stores its own entry, and
66
- * the same post-execute decision writes both.
67
- */
68
- export interface ReceiptAnchors {
69
- stepId: string;
70
- anchors: Record<string, string>;
71
- }
72
- /**
73
- * Per-session receipt anchors.
74
- *
75
- * A plain `Map` behind three methods: no persistence, no timers, no I/O. It is
76
- * written by the decision path and read by the invalidation check, both in
77
- * `post-execute`; Task 23b fills it.
78
- */
79
- export declare class AnchorStore {
80
- private readonly bySession;
81
- /** Remember `a` as the pending anchors for `sessionId`, replacing any earlier record. */
82
- set(sessionId: string, a: ReceiptAnchors): void;
83
- /** The pending anchors for `sessionId`, or `undefined` when there is none. */
84
- get(sessionId: string): ReceiptAnchors | undefined;
85
- /** Drop the pending anchors for `sessionId`; clearing an absent key is a no-op. */
86
- clear(sessionId: string): void;
87
- }
88
- /**
89
- * Whether this text contains the host pruner's marker.
90
- *
91
- * Exactly `text.includes(PRUNE_MARKER)` — no prefix matching, no regex, no
92
- * trimming. This is the whole detection: a caller that can see a pruned
93
- * surface node (the model-request path) uses it, while a caller that cannot
94
- * (post-execute) only catches a tool output that literally contains the marker.
95
- * If the host ever changes the wording this returns `false` and detection fails
96
- * in the safe direction: at worst the plugin prunes one more time than needed,
97
- * and a stale anchor is never let through, because an anchor/text mismatch
98
- * still raises `compaction-reset` on the path that can establish the identity.
99
- * A near miss in ordinary output is likewise not a prune, so text that merely
100
- * looks like the marker is left alone.
101
- */
102
- export declare function looksPruned(text: string): boolean;
103
- /**
104
- * Whether the receipt already carries the host spill footer.
105
- *
106
- * The answer is the injected predicate's: the caller owns the recognition rule
107
- * (Task 23b/T25 supply the host's `hasSpillNotice` through a dynamic import),
108
- * and this module must not import `@deepseek-ai/dsh-spill-policy` — it is an
109
- * optional peer, and a static import would make the degraded path unreachable.
110
- * Injecting it also keeps the guard testable without a host.
111
- */
112
- export declare function alreadySpilled(text: string, hasNotice: (t: string) => boolean): boolean;
@@ -1,86 +0,0 @@
1
- /**
2
- * Plan parsing: model-written text becomes typed candidates.
3
- *
4
- * The model may write one `<CHISEL_PLAN>` block listing candidate tool calls.
5
- * This module is the only place that text becomes data; guard evaluation,
6
- * binding and the selector all trust what it returns, so parsing is strict:
7
- * a document either yields a fully validated plan or exactly one error code
8
- * (`no-plan`, `bad-json`, `bad-shape`). Nothing is ever thrown and no partial
9
- * plan escapes.
10
- *
11
- * Only the first block counts. The block is located with two linear `indexOf`
12
- * scans (opening tag, then the next closing tag); a pathological document with
13
- * many unterminated openers must not stall the event loop. A second block is
14
- * ignored even when the first is malformed, and an opening tag without its
15
- * closing tag is not a block at all (`no-plan`).
16
- *
17
- * "Only literals" is enforced against what JSON can carry: `JSON.parse` cannot
18
- * produce a function, so the rule reduces to "`args` may contain no
19
- * `$`-prefixed key other than `$public`". That restriction covers the whole
20
- * `args` tree, including inside a `$public` subtree; the sanctioned template
21
- * (`{ after, field }`, with `$scalar`/`$single` as *values*) has no nested
22
- * `$`-prefixed key, so the two rules never conflict. The `$public` subtree is
23
- * otherwise preserved verbatim: its `after`/`field` semantics are validated by
24
- * binding (task 12), not here. A root-level `$public` (the whole `args` object
25
- * replaced by a scalar) is also left to binding to reject.
26
- *
27
- * Candidate ids are single capital ASCII letters (`A`–`Z`) because the
28
- * selector answers with exactly one character equal to a candidate id; that
29
- * also means a plan with more than 26 candidates is rejected. `tool` must be
30
- * non-empty after trimming. `args` is capped at 64 levels of nesting and may
31
- * not use the prototype-affecting keys `__proto__`, `constructor` or
32
- * `prototype`: those collide in receipt hashing today and would pollute any
33
- * future merge of `args`.
34
- *
35
- * @module dsh-boost/gate/plan
36
- */
37
- /** A deterministic receipt predicate. `ok` alone is trivial (design §5.2). */
38
- export type Guard = {
39
- ok: true;
40
- } | {
41
- text_contains: string;
42
- } | {
43
- text_not_contains: string;
44
- } | {
45
- json_equals: {
46
- pointer: string;
47
- value: string | number | boolean;
48
- };
49
- };
50
- /** One tool call the model proposed. */
51
- export interface Candidate {
52
- id: string;
53
- tool: string;
54
- args: Record<string, unknown>;
55
- guards: Guard[];
56
- }
57
- /** A parsed plan: documentation plus the candidate steps. */
58
- export interface Plan {
59
- goal: string;
60
- steps: Candidate[];
61
- }
62
- /** Why a document did not yield a plan. */
63
- type PlanError = 'no-plan' | 'bad-json' | 'bad-shape';
64
- /**
65
- * Parse the first `<CHISEL_PLAN>` block out of one model response.
66
- *
67
- * Returns `{ plan }` only when the whole block is understood: a non-empty
68
- * `steps` array whose ids are unique capital letters, each with a non-empty
69
- * tool, a literal `args` object and decodable guards. Everything else collapses
70
- * to one error code, so callers can never act on half a plan. `goal` is
71
- * documentation: a missing or non-string value becomes `''`, never an error.
72
- */
73
- export declare function parsePlan(text: string): {
74
- plan: Plan;
75
- } | {
76
- error: PlanError;
77
- };
78
- /**
79
- * Whether a candidate has nothing to check.
80
- *
81
- * True when every guard is `{ ok: true }`, including the empty array: nothing
82
- * to check means nothing to check. Any non-`ok` guard makes the candidate
83
- * non-trivial, which is what substitution requires (design §5.2, `guard-trivial`).
84
- */
85
- export declare function isTrivial(c: Candidate): boolean;
86
- export {};