dsh-boost 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +526 -0
  4. package/README.md +444 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +283 -0
  43. package/dist/hooks/llm-stream.js +1086 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +257 -0
  49. package/dist/hooks/post-execute.js +1950 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +25 -0
  64. package/dist/host/root.js +64 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +984 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +380 -0
  100. package/dist/tools/boost.js +801 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +130 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
@@ -0,0 +1,297 @@
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
+ /** JSON object, not `null` and not an array. */
66
+ function object(value) {
67
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
68
+ }
69
+ /**
70
+ * Escape a model-controlled string for literal use in a `RegExp`.
71
+ *
72
+ * `field` is data, not syntax: `a.*` must match the four characters `a.*` and
73
+ * not act as a pattern.
74
+ */
75
+ function escapeRegExp(value) {
76
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
77
+ }
78
+ /** `$scalar`: the whole trimmed text is one bare scalar token. */
79
+ const SCALAR = /^[A-Za-z0-9_+@.:/-]+$/;
80
+ /** `$single`: the whole trimmed text is a one-element single-quoted array. */
81
+ const SINGLE = /^\['[^']*'\]$/;
82
+ /**
83
+ * Line boundaries the scan recognises: LF, CR, CRLF (split twice,
84
+ * harmlessly), NEL (U+0085) and the Unicode line/paragraph separators
85
+ * U+2028/U+2029.
86
+ */
87
+ const LINE_TERMINATOR = /[\r\n\u0085\u2028\u2029]/;
88
+ /**
89
+ * Whether the quote that ended the capture was itself escaped.
90
+ *
91
+ * `name: "a\"b"` captures `a\`, because the regex cannot know that the `"` it
92
+ * stopped at was escaped. Binding that truncated prefix would hand the tool a
93
+ * value the receipt does not show, so an odd trailing run of backslashes
94
+ * invalidates the line. A Windows path such as `C:\x` ends in `x`, not a
95
+ * backslash, and still binds.
96
+ */
97
+ function escapedClosingQuote(value) {
98
+ let backslashes = 0;
99
+ for (let i = value.length - 1; i >= 0 && value[i] === '\\'; i--)
100
+ backslashes++;
101
+ return backslashes % 2 === 1;
102
+ }
103
+ /**
104
+ * The identifier form on one line: `field: "value"` or `field="value"`.
105
+ *
106
+ * Applied line by line: the split has removed every line terminator, so an
107
+ * anchored `\s*` cannot run into the next line's whitespace (it may still match
108
+ * in-line `\v`/`\f`). One anchored, non-global `exec` per line therefore cannot
109
+ * re-consume the rest of the receipt, which is what made the old cross-line
110
+ * global regex quadratic on a blank-line-heavy receipt.
111
+ *
112
+ * The value must be non-empty (`+`): an empty projected value is never a useful
113
+ * argument — it would reach a tool as `path: ""` and fail there, after the plan
114
+ * has already committed — so `name: ""` abstains and the plan falls back before
115
+ * anything runs.
116
+ */
117
+ function identifierPattern(field) {
118
+ return new RegExp('^\\s*' + escapeRegExp(field) + '\\s*[:=]\\s*"([^"]+)"');
119
+ }
120
+ /**
121
+ * Whole-text bare scalar; no spaces, quotes or newlines survive the match.
122
+ */
123
+ function scalarField(text) {
124
+ const value = text.trim();
125
+ return SCALAR.test(value) ? value : undefined;
126
+ }
127
+ /**
128
+ * Whole-text single-element string array whose value stays on one line.
129
+ *
130
+ * The whole-text anchoring makes the interior the entire value, so there is no
131
+ * truncated-prefix case: a backslash is literal text here, and `['C:\']` binds
132
+ * `C:\` exactly as the spec regex says.
133
+ */
134
+ function singleField(text) {
135
+ const trimmed = text.trim();
136
+ if (!SINGLE.test(trimmed))
137
+ return undefined;
138
+ // The pattern is anchored and matches exactly `['` + interior + `']`, so the
139
+ // value is the interior itself: no capture to narrow, and no way for the
140
+ // delimiters to survive.
141
+ const value = trimmed.slice(2, -2);
142
+ // An empty value is never a useful argument (it reaches a tool as
143
+ // `path: ""`), and the identifier form already refuses empty values; the
144
+ // whole-text form must apply the same rule (review row 65).
145
+ if (value.length === 0 || LINE_TERMINATOR.test(value))
146
+ return undefined;
147
+ return value;
148
+ }
149
+ /**
150
+ * One `field: "value"` line, exactly once.
151
+ *
152
+ * The right-hand side must be double-quoted, so `name=abc` yields no match and
153
+ * therefore abstains. Zero and two-plus matches both abstain: uniqueness is the
154
+ * entire defence against a crafted receipt that carries a second, fake value on
155
+ * another line. The scan stops at the second match, because the answer is
156
+ * `undefined` regardless of what follows.
157
+ */
158
+ function identifierField(text, field) {
159
+ const pattern = identifierPattern(field);
160
+ let found;
161
+ for (const line of text.split(LINE_TERMINATOR)) {
162
+ const match = pattern.exec(line);
163
+ if (match === null)
164
+ continue;
165
+ const value = match[1];
166
+ // `identifierPattern` carries one mandatory, non-empty group, so a missing
167
+ // capture is unreachable; treating it as "this line has no value" keeps
168
+ // the type honest instead of asserting it away.
169
+ if (value === undefined)
170
+ continue;
171
+ if (escapedClosingQuote(value))
172
+ return undefined;
173
+ if (found !== undefined)
174
+ return undefined;
175
+ found = value;
176
+ }
177
+ return found;
178
+ }
179
+ /**
180
+ * Project one field out of a receipt's canonical text.
181
+ *
182
+ * `undefined` always means "cannot use this"; callers turn it into `ambiguous`.
183
+ * Empty fields and unknown `$`-prefixed fields are rejected before touching the
184
+ * text, and identifier fields are matched literally.
185
+ */
186
+ export function extractField(text, field) {
187
+ if (typeof text !== 'string' || typeof field !== 'string' || field.length === 0)
188
+ return undefined;
189
+ if (field.startsWith('$')) {
190
+ if (field === '$scalar')
191
+ return scalarField(text);
192
+ if (field === '$single')
193
+ return singleField(text);
194
+ return undefined;
195
+ }
196
+ return identifierField(text, field);
197
+ }
198
+ /**
199
+ * Whether `value` is the sanctioned template shape, and nothing else.
200
+ *
201
+ * A plain object with exactly one own key, `$public`, whose value is an object
202
+ * with exactly the two string keys `after` and `field`. Extra keys on either
203
+ * level are rejected rather than silently dropped: this module only understands
204
+ * `after`/`field`, and a template with a third directive is not something the
205
+ * host may receive.
206
+ */
207
+ export function isTemplate(value) {
208
+ if (!object(value))
209
+ return false;
210
+ const outerKeys = Object.keys(value);
211
+ if (outerKeys.length !== 1 || outerKeys[0] !== '$public')
212
+ return false;
213
+ const inner = value.$public;
214
+ if (!object(inner))
215
+ return false;
216
+ const innerKeys = Object.keys(inner);
217
+ if (innerKeys.length !== 2 || !innerKeys.includes('after') || !innerKeys.includes('field'))
218
+ return false;
219
+ return typeof inner.after === 'string' && typeof inner.field === 'string';
220
+ }
221
+ /**
222
+ * Project one template's value from the receipts named by `after`.
223
+ *
224
+ * Check order is part of the contract: an absent graph node is `unresolvable`;
225
+ * then an errored/empty receipt is `missing-receipt`; then a receipt that is
226
+ * not exactly one text block is `not-single-text`; only then can projection
227
+ * fail as `ambiguous`.
228
+ */
229
+ function resolveTemplate(template, receipts) {
230
+ const { after, field } = template.$public;
231
+ const receipt = receipts.get(after);
232
+ if (receipt === undefined)
233
+ return { reason: 'unresolvable' };
234
+ if (receipt.isError || receipt.empty || receipt.text.length === 0)
235
+ return { reason: 'missing-receipt' };
236
+ if (receipt.textBlocks !== 1)
237
+ return { reason: 'not-single-text' };
238
+ const value = extractField(receipt.text, field);
239
+ if (value === undefined)
240
+ return { reason: 'ambiguous' };
241
+ return { value };
242
+ }
243
+ /**
244
+ * Bind one value: a template becomes a scalar, containers are rebuilt
245
+ * recursively, everything else is copied through unchanged.
246
+ *
247
+ * `Object.fromEntries` (rather than assignment) keeps an own `__proto__` key a
248
+ * data property, so rebuilding a hostile tree cannot pollute a prototype.
249
+ */
250
+ function bindValue(value, receipts) {
251
+ if (Array.isArray(value)) {
252
+ const items = [];
253
+ for (const item of value) {
254
+ const bound = bindValue(item, receipts);
255
+ if ('reason' in bound)
256
+ return bound;
257
+ items.push(bound.value);
258
+ }
259
+ return { value: items };
260
+ }
261
+ if (object(value)) {
262
+ if (Object.hasOwn(value, '$public')) {
263
+ if (!isTemplate(value))
264
+ return { reason: 'unresolvable' };
265
+ return resolveTemplate(value, receipts);
266
+ }
267
+ const entries = [];
268
+ for (const [key, child] of Object.entries(value)) {
269
+ const bound = bindValue(child, receipts);
270
+ if ('reason' in bound)
271
+ return bound;
272
+ entries.push([key, bound.value]);
273
+ }
274
+ return { value: Object.fromEntries(entries) };
275
+ }
276
+ return { value };
277
+ }
278
+ /**
279
+ * Bind every `$public` template in `args` against the receipts of earlier
280
+ * steps.
281
+ *
282
+ * The root object is checked separately and can never be a template: it is an
283
+ * argument object, while a template produces a scalar. The same check rejects a
284
+ * root that merely carries a `$public` key alongside other keys.
285
+ *
286
+ * Returns a fresh `args` tree on success, or one reason the whole plan must
287
+ * fall back to the model. There is no partial result and no mutation.
288
+ */
289
+ export function bindArgs(args, receipts) {
290
+ if (Object.hasOwn(args, '$public'))
291
+ return { ok: false, reason: 'unresolvable' };
292
+ const bound = bindValue(args, receipts);
293
+ if ('reason' in bound)
294
+ return { ok: false, reason: bound.reason };
295
+ return { ok: true, args: bound.value };
296
+ }
297
+ //# sourceMappingURL=binding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding.js","sourceRoot":"","sources":["../../src/gate/binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AAkBH,gDAAgD;AAChD,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;AAC7E,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,KAAa;IACjC,OAAO,KAAK,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAA;AACrD,CAAC;AAED,kEAAkE;AAClE,MAAM,MAAM,GAAG,uBAAuB,CAAA;AAEtC,8EAA8E;AAC9E,MAAM,MAAM,GAAG,eAAe,CAAA;AAE9B;;;;GAIG;AACH,MAAM,eAAe,GAAG,0BAA0B,CAAA;AAElD;;;;;;;;GAQG;AACH,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,WAAW,GAAG,CAAC,CAAA;IACnB,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE;QAAE,WAAW,EAAE,CAAA;IAC9E,OAAO,WAAW,GAAG,CAAC,KAAK,CAAC,CAAA;AAC9B,CAAC;AAED;;;;;;;;;;;;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E,cAAc,EAAE,CAAA;IAChF,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;IACvC,IAAI,QAAQ,IAAI,KAAK;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAA;IACjE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,KAAgC,EAAE,CAAA;AACnE,CAAC","sourcesContent":["/**\n * `$public` argument binding: the anti-forgery core of the gate.\n *\n * A plan is written by the model with literal arguments, except for values that\n * only exist after an earlier step has run. Those are written as a template\n * `{ \"$public\": { \"after\": \"A\", \"field\": \"name\" } }`, and this module fills the\n * template in from the named receipt. The point is mechanical projection: a\n * value that the model reads and then re-types can be steered by whatever the\n * value contains, so the value is copied from the receipt text instead of being\n * reproduced by the model.\n *\n * Uniqueness is the whole safety rule. A field is usable only when it appears\n * exactly once, as a quoted string, on its own line (`name: \"v\"` / `name=\"v\"`);\n * zero matches, two matches, or an unquoted right-hand side are all\n * `ambiguous`, and ambiguity means the slow path — never a guess. `$scalar`\n * and `$single` are whole-text forms, so they are unique by construction;\n * `$single` additionally refuses a value that spans a line.\n *\n * A line boundary is LF, CR, CRLF, NEL (U+0085), U+2028 or U+2029, so a\n * duplicate cannot hide behind one of these common separator conventions.\n * Identifier projection scans each line once with an anchored, non-global regex\n * instead of running one cross-line global regex: the latter re-consumes the\n * remaining whitespace at every line start, which is quadratic on a\n * blank-line-heavy receipt. The identifier form's closing quote must not be\n * escaped: a captured value ending in an odd run of backslashes means the quote\n * that ended the match was itself escaped, so the line abstains instead of\n * binding a truncated prefix (`C:\\x` ends in `x` and still binds).\n *\n * Two scoping consequences are deliberate: a second assignment later on the\n * same line is not counted (`name: \"a\" name: \"b\"` binds `a`), and a line whose\n * right-hand side is not double-quoted is not a match at all (`name: \"a\"`\n * followed by `name: b` binds `a`). In both cases the projected value is the\n * line-start quoted occurrence, so nothing attacker-chosen is projected.\n *\n * Within the gate's contract — `args` from `parsePlan`, receipts from\n * `canonicalise` — failures are values, never throws, and the order is fixed: a\n * missing graph node is `unresolvable`, an errored or empty receipt is\n * `missing-receipt`, a receipt that is not exactly one text block is\n * `not-single-text`, and a non-unique projection is `ambiguous`. The function\n * does not re-validate those inputs: a `null` receipt value, a `null` args, a\n * cyclic tree, or an array passed as `args` would throw or be miscast. All of\n * these are unreachable through `parsePlan`/`canonicalise`.\n *\n * Two containers fail closed. The root `args` object can never be a template\n * (`unresolvable`): a template replaces one value with a scalar, and an\n * argument object is not a scalar. Any other object that carries a `$public`\n * key but is not a well-formed template — extra keys alongside it, a\n * non-object value, extra keys inside it — is also `unresolvable`, so a\n * malformed template never reaches the host as a literal `$public` argument.\n * `field` is model-controlled, so it is regex-escaped, must be non-empty, and\n * may only start with `$` when it is exactly `$scalar` or `$single`.\n *\n * `textBlocks` (not `blocks.length`) decides `not-single-text`, because only\n * text blocks contribute to `text`. `empty` is defined by `canonicalise` as\n * `text.length === 0`; a receipt that contradicts that invariant (empty text\n * with `empty: false`) is treated as `missing-receipt` rather than projected,\n * since there is no text to project from and the contradiction is a producer\n * bug, not something to guess around.\n *\n * `args` comes from `JSON.parse`, so it is acyclic and already depth-capped by\n * plan parsing. Binding returns a fresh tree and never mutates its input.\n *\n * @module dsh-boost/gate/binding\n */\n\nimport type { CanonicalReceipt } from '../projection/canonicalise.js'\n\n/** The one well-formed template: a single `$public` key with two string fields. */\nexport type PublicTemplate = { $public: { after: 'root' | string; field: string } }\n\n/** Why a value could not be projected; every one is a fallback to the model. */\ntype BindFailure = 'ambiguous' | 'unresolvable' | 'missing-receipt' | 'not-single-text'\n\n/** A successful binding or the single reason it was abandoned. */\ntype BindResult =\n | { ok: true; args: Record<string, unknown> }\n | { ok: false; reason: BindFailure }\n\n/** Either a bound value or the reason the whole tree is abandoned. */\ntype Bound = { value: unknown } | { reason: BindFailure }\n\n/** JSON object, not `null` and not an array. */\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Escape a model-controlled string for literal use in a `RegExp`.\n *\n * `field` is data, not syntax: `a.*` must match the four characters `a.*` and\n * not act as a pattern.\n */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/** `$scalar`: the whole trimmed text is one bare scalar token. */\nconst SCALAR = /^[A-Za-z0-9_+@.:/-]+$/\n\n/** `$single`: the whole trimmed text is a one-element single-quoted array. */\nconst SINGLE = /^\\['[^']*'\\]$/\n\n/**\n * Line boundaries the scan recognises: LF, CR, CRLF (split twice,\n * harmlessly), NEL (U+0085) and the Unicode line/paragraph separators\n * U+2028/U+2029.\n */\nconst LINE_TERMINATOR = /[\\r\\n\\u0085\\u2028\\u2029]/\n\n/**\n * Whether the quote that ended the capture was itself escaped.\n *\n * `name: \"a\\\"b\"` captures `a\\`, because the regex cannot know that the `\"` it\n * stopped at was escaped. Binding that truncated prefix would hand the tool a\n * value the receipt does not show, so an odd trailing run of backslashes\n * invalidates the line. A Windows path such as `C:\\x` ends in `x`, not a\n * backslash, and still binds.\n */\nfunction escapedClosingQuote(value: string): boolean {\n let backslashes = 0\n for (let i = value.length - 1; i >= 0 && value[i] === '\\\\'; i--) backslashes++\n return backslashes % 2 === 1\n}\n\n/**\n * The identifier form on one line: `field: \"value\"` or `field=\"value\"`.\n *\n * Applied line by line: the split has removed every line terminator, so an\n * anchored `\\s*` cannot run into the next line's whitespace (it may still match\n * in-line `\\v`/`\\f`). One anchored, non-global `exec` per line therefore cannot\n * re-consume the rest of the receipt, which is what made the old cross-line\n * global regex quadratic on a blank-line-heavy receipt.\n *\n * The value must be non-empty (`+`): an empty projected value is never a useful\n * argument — it would reach a tool as `path: \"\"` and fail there, after the plan\n * has already committed — so `name: \"\"` abstains and the plan falls back before\n * anything runs.\n */\nfunction identifierPattern(field: string): RegExp {\n return new RegExp('^\\\\s*' + escapeRegExp(field) + '\\\\s*[:=]\\\\s*\"([^\"]+)\"')\n}\n\n/**\n * Whole-text bare scalar; no spaces, quotes or newlines survive the match.\n */\nfunction scalarField(text: string): string | undefined {\n const value = text.trim()\n return SCALAR.test(value) ? value : undefined\n}\n\n/**\n * Whole-text single-element string array whose value stays on one line.\n *\n * The whole-text anchoring makes the interior the entire value, so there is no\n * truncated-prefix case: a backslash is literal text here, and `['C:\\']` binds\n * `C:\\` exactly as the spec regex says.\n */\nfunction singleField(text: string): string | undefined {\n const trimmed = text.trim()\n if (!SINGLE.test(trimmed)) return undefined\n // The pattern is anchored and matches exactly `['` + interior + `']`, so the\n // value is the interior itself: no capture to narrow, and no way for the\n // delimiters to survive.\n const value = trimmed.slice(2, -2)\n // An empty value is never a useful argument (it reaches a tool as\n // `path: \"\"`), and the identifier form already refuses empty values; the\n // whole-text form must apply the same rule (review row 65).\n if (value.length === 0 || LINE_TERMINATOR.test(value)) return undefined\n return value\n}\n\n/**\n * One `field: \"value\"` line, exactly once.\n *\n * The right-hand side must be double-quoted, so `name=abc` yields no match and\n * therefore abstains. Zero and two-plus matches both abstain: uniqueness is the\n * entire defence against a crafted receipt that carries a second, fake value on\n * another line. The scan stops at the second match, because the answer is\n * `undefined` regardless of what follows.\n */\nfunction identifierField(text: string, field: string): string | undefined {\n const pattern = identifierPattern(field)\n let found: string | undefined\n for (const line of text.split(LINE_TERMINATOR)) {\n const match = pattern.exec(line)\n if (match === null) continue\n const value = match[1]\n // `identifierPattern` carries one mandatory, non-empty group, so a missing\n // capture is unreachable; treating it as \"this line has no value\" keeps\n // the type honest instead of asserting it away.\n if (value === undefined) continue\n if (escapedClosingQuote(value)) return undefined\n if (found !== undefined) return undefined\n found = value\n }\n return found\n}\n\n/**\n * Project one field out of a receipt's canonical text.\n *\n * `undefined` always means \"cannot use this\"; callers turn it into `ambiguous`.\n * Empty fields and unknown `$`-prefixed fields are rejected before touching the\n * text, and identifier fields are matched literally.\n */\nexport function extractField(text: string, field: string): string | undefined {\n if (typeof text !== 'string' || typeof field !== 'string' || field.length === 0) return undefined\n if (field.startsWith('$')) {\n if (field === '$scalar') return scalarField(text)\n if (field === '$single') return singleField(text)\n return undefined\n }\n return identifierField(text, field)\n}\n\n/**\n * Whether `value` is the sanctioned template shape, and nothing else.\n *\n * A plain object with exactly one own key, `$public`, whose value is an object\n * with exactly the two string keys `after` and `field`. Extra keys on either\n * level are rejected rather than silently dropped: this module only understands\n * `after`/`field`, and a template with a third directive is not something the\n * host may receive.\n */\nexport function isTemplate(value: unknown): value is PublicTemplate {\n if (!object(value)) return false\n const outerKeys = Object.keys(value)\n if (outerKeys.length !== 1 || outerKeys[0] !== '$public') return false\n const inner = value.$public\n if (!object(inner)) return false\n const innerKeys = Object.keys(inner)\n if (innerKeys.length !== 2 || !innerKeys.includes('after') || !innerKeys.includes('field')) return false\n return typeof inner.after === 'string' && typeof inner.field === 'string'\n}\n\n/**\n * Project one template's value from the receipts named by `after`.\n *\n * Check order is part of the contract: an absent graph node is `unresolvable`;\n * then an errored/empty receipt is `missing-receipt`; then a receipt that is\n * not exactly one text block is `not-single-text`; only then can projection\n * fail as `ambiguous`.\n */\nfunction resolveTemplate(\n template: PublicTemplate,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): Bound {\n const { after, field } = template.$public\n const receipt = receipts.get(after)\n if (receipt === undefined) return { reason: 'unresolvable' }\n if (receipt.isError || receipt.empty || receipt.text.length === 0) return { reason: 'missing-receipt' }\n if (receipt.textBlocks !== 1) return { reason: 'not-single-text' }\n const value = extractField(receipt.text, field)\n if (value === undefined) return { reason: 'ambiguous' }\n return { value }\n}\n\n/**\n * Bind one value: a template becomes a scalar, containers are rebuilt\n * recursively, everything else is copied through unchanged.\n *\n * `Object.fromEntries` (rather than assignment) keeps an own `__proto__` key a\n * data property, so rebuilding a hostile tree cannot pollute a prototype.\n */\nfunction bindValue(value: unknown, receipts: ReadonlyMap<string, CanonicalReceipt>): Bound {\n if (Array.isArray(value)) {\n const items: unknown[] = []\n for (const item of value) {\n const bound = bindValue(item, receipts)\n if ('reason' in bound) return bound\n items.push(bound.value)\n }\n return { value: items }\n }\n\n if (object(value)) {\n if (Object.hasOwn(value, '$public')) {\n if (!isTemplate(value)) return { reason: 'unresolvable' }\n return resolveTemplate(value, receipts)\n }\n const entries: Array<[string, unknown]> = []\n for (const [key, child] of Object.entries(value)) {\n const bound = bindValue(child, receipts)\n if ('reason' in bound) return bound\n entries.push([key, bound.value])\n }\n return { value: Object.fromEntries(entries) }\n }\n\n return { value }\n}\n\n/**\n * Bind every `$public` template in `args` against the receipts of earlier\n * steps.\n *\n * The root object is checked separately and can never be a template: it is an\n * argument object, while a template produces a scalar. The same check rejects a\n * root that merely carries a `$public` key alongside other keys.\n *\n * Returns a fresh `args` tree on success, or one reason the whole plan must\n * fall back to the model. There is no partial result and no mutation.\n */\nexport function bindArgs(\n args: Record<string, unknown>,\n receipts: ReadonlyMap<string, CanonicalReceipt>,\n): BindResult {\n if (Object.hasOwn(args, '$public')) return { ok: false, reason: 'unresolvable' }\n const bound = bindValue(args, receipts)\n if ('reason' in bound) return { ok: false, reason: bound.reason }\n return { ok: true, args: bound.value as Record<string, unknown> }\n}"]}
@@ -0,0 +1,82 @@
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;
@@ -0,0 +1,163 @@
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 { bindArgs } from './binding.js';
56
+ import { evaluateAll } from './guard.js';
57
+ import { isTrivial } from './plan.js';
58
+ /** The one fallback constructor, so every early exit has the same shape. */
59
+ function fallback(code) {
60
+ return { kind: 'fallback', code };
61
+ }
62
+ /**
63
+ * Whitelist filter (rule 1).
64
+ *
65
+ * Fails the pipeline only when there was something to filter: an empty plan
66
+ * must reach the trivial filter, where it is `guard-trivial`, not a whitelist
67
+ * rejection.
68
+ */
69
+ function whitelisted(whitelist) {
70
+ return (candidates) => {
71
+ const kept = candidates.filter((candidate) => whitelist.has(candidate.tool));
72
+ if (kept.length === 0 && candidates.length > 0)
73
+ return fallback('tool-not-whitelisted');
74
+ return kept;
75
+ };
76
+ }
77
+ /**
78
+ * Trivial-candidate filter (rule 3).
79
+ *
80
+ * `isTrivial` is true for the empty guard list too, so this filter also turns
81
+ * an empty plan into `guard-trivial`.
82
+ */
83
+ const nonTrivial = (candidates) => {
84
+ const kept = candidates.filter((candidate) => !isTrivial(candidate));
85
+ return kept.length === 0 ? fallback('guard-trivial') : kept;
86
+ };
87
+ /** Run filters left to right; the first decision ends the pipeline. */
88
+ function narrow(candidates, filters) {
89
+ let kept = candidates;
90
+ for (const filter of filters) {
91
+ const next = filter(kept);
92
+ if (!Array.isArray(next))
93
+ return next;
94
+ kept = next;
95
+ }
96
+ return kept;
97
+ }
98
+ /**
99
+ * Bind and verify each candidate (rule 4).
100
+ *
101
+ * Binding runs first: a candidate that cannot be bound is dropped before its
102
+ * guards are ever evaluated, and the failure reason is intentionally discarded
103
+ * — every dropped candidate is just one fewer choice, not a distinct fallback
104
+ * for the whole plan. Guards are receipt-local to `stepId`; when that receipt
105
+ * is absent nothing can be verified, so nothing survives.
106
+ */
107
+ function bindAndVerify(candidates, stepId, receipts) {
108
+ const receipt = receipts.get(stepId);
109
+ if (receipt === undefined)
110
+ return [];
111
+ const survivors = [];
112
+ for (const candidate of candidates) {
113
+ const bound = bindArgs(candidate.args, receipts);
114
+ if (!bound.ok)
115
+ continue;
116
+ if (!evaluateAll(candidate.guards, receipt).ok)
117
+ continue;
118
+ survivors.push({ candidate, args: bound.args });
119
+ }
120
+ return survivors;
121
+ }
122
+ /**
123
+ * Turn the survivor list into the decision (rule 5).
124
+ *
125
+ * Both outcomes carry the bound args, so the caller never has to bind again:
126
+ * `commit` returns them directly, `ask-selector` returns a fresh candidate per
127
+ * survivor and leaves the plan's objects untouched. The guard copy is one
128
+ * level deep per guard because every `Guard` form is flat — its only nested
129
+ * value, `json_equals.value`, is a scalar.
130
+ */
131
+ function resolve(survivors) {
132
+ const [only] = survivors;
133
+ if (only === undefined)
134
+ return fallback('no-candidate');
135
+ if (survivors.length > 1) {
136
+ return {
137
+ kind: 'ask-selector',
138
+ candidates: survivors.map((entry) => ({
139
+ ...entry.candidate,
140
+ args: entry.args,
141
+ guards: entry.candidate.guards.map((guard) => ({ ...guard })),
142
+ })),
143
+ };
144
+ }
145
+ return { kind: 'commit', candidateId: only.candidate.id, args: only.args };
146
+ }
147
+ /**
148
+ * Decide what to do with one parsed plan.
149
+ *
150
+ * `shadow` skips the whitelist filter (design §5.2-5) so the shadow week can
151
+ * record substitution potential for every tool family; everything else is the
152
+ * same path. The function is synchronous and side-effect free.
153
+ */
154
+ export function decide(input) {
155
+ const filters = input.shadow
156
+ ? [nonTrivial]
157
+ : [whitelisted(input.whitelist), nonTrivial];
158
+ const narrowed = narrow(input.plan.steps, filters);
159
+ if (!Array.isArray(narrowed))
160
+ return narrowed;
161
+ return resolve(bindAndVerify(narrowed, input.stepId, input.receipts));
162
+ }
163
+ //# sourceMappingURL=decide.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decide.js","sourceRoot":"","sources":["../../src/gate/decide.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;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,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAA;AACnC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,SAA8B;IACjD,OAAO,CAAC,UAAU,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAA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C,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"]}