@hasna/hooks 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +31 -11
  2. package/bin/hooks/stop-review.js +17 -9
  3. package/bin/hooks-mcp.js +741 -311
  4. package/bin/index.js +1673 -634
  5. package/bin/native-safety-entry.js +2 -2
  6. package/bin/native-safety-worker.cjs +36 -34
  7. package/bin/release-manifest.json +297 -0
  8. package/bin/serve.js +577 -151
  9. package/dist/index.js +1813 -1178
  10. package/dist/lib/codex-safety-check.d.ts +1 -1
  11. package/dist/lib/error-events.d.ts +59 -0
  12. package/dist/lib/install-record.d.ts +136 -0
  13. package/dist/lib/manifest.d.ts +6 -0
  14. package/dist/lib/release-manifest.d.ts +162 -0
  15. package/dist/lib/store.d.ts +25 -2
  16. package/dist/openapi.d.ts +147 -0
  17. package/dist/registry-auth.d.ts +6 -1
  18. package/dist/registry-http.d.ts +2 -1
  19. package/dist/sdk/generated.d.ts +26 -0
  20. package/dist/sdk/index.js +14 -0
  21. package/hooks/codewith-native-common.ts +190 -6
  22. package/hooks/hook-signed-link-guard/README.md +46 -0
  23. package/hooks/hook-signed-link-guard/src/classify.ts +7 -3
  24. package/hooks/hook-signed-link-guard/src/jq.ts +205 -34
  25. package/hooks/hook-stop-review/README.md +5 -2
  26. package/hooks/hook-stop-review/src/jev.ts +9 -4
  27. package/hooks/hook-stop-review/src/policy.ts +7 -3
  28. package/hooks/hook-stop-review/src/runtime.ts +5 -4
  29. package/hooks/hook-trash-guard/README.md +9 -4
  30. package/hooks/hook-trash-guard/src/hook.ts +127 -10
  31. package/hooks/hook-workspace-repos-guard/src/hook.ts +27 -12
  32. package/hooks/pre-bash/README.md +47 -1
  33. package/hooks/pre-bash/src/hook.ts +168 -12
  34. package/hooks/shell-words.ts +40 -2
  35. package/package.json +3 -2
  36. package/scripts/build-release-manifest.ts +27 -0
  37. package/scripts/validate-package.ts +5 -1
  38. package/scripts/validate-release-manifest.ts +67 -0
@@ -21,6 +21,10 @@
21
21
  * safe when read directly from it;
22
22
  * - "unknown" arbitrary response JSON (the elements of an iteration, a whole
23
23
  * sub-object). Never safe to print;
24
+ * - "unknownRewritten" like "unknown", for a value a function re-encoded
25
+ * (`split`, `tojson`, `to_entries`, …) or anything iterated
26
+ * from one; a field read from it is a rewritten leaf. Only the
27
+ * letter-only gsub treats either differently: it refuses them.
24
28
  * - "tainted" a value the filter itself built from unsafe parts, or a
25
29
  * free-form container (`payload`, `inputs`, check `output`, …).
26
30
  * Its field names no longer describe its content, so nothing
@@ -34,6 +38,45 @@
34
38
  * Comments are refused: gojq continues a `#` comment across a
35
39
  * backslash-newline, which a line-based reading would get wrong.
36
40
  *
41
+ * Letter-only text (HO-00192): `gsub(R; S)` with literal arguments, where R
42
+ * is exactly a negated class of ASCII letters and spaces (`[^A-Za-z ]`,
43
+ * `[^a-zA-Z]`, `[^a-z ]`, optionally followed by `+`) and S holds only ASCII
44
+ * letters and spaces written without any backslash escape, removes every other
45
+ * character. Its output is ASCII letters and spaces, with no `:`, `/`, `.`,
46
+ * `?`, `=`, `%` or digit, and gets its own shape, "letters":
47
+ *
48
+ * - it may be printed, measured (`length`) or tested (`==`, `test`), but any
49
+ * step that could put removed characters back (`split`, `join`, `+`,
50
+ * interpolation, an array or object, a format, iteration, a field) makes
51
+ * it "tainted", so markers placed before the gsub cannot be swapped back
52
+ * after it;
53
+ * - its input must be a field reached from the response through field
54
+ * reads, iteration and indexing only (optionally through
55
+ * `ascii_downcase`, `ascii_upcase`, the trims or the type filters), or
56
+ * another letter-only gsub. A value that went through any other function
57
+ * (`split`, `join`, `tojson`, `to_entries`, `sort_by`, a format, …) or a
58
+ * slice of a field (`.body[0:1]`, a piece of it, with any bounds) stays
59
+ * marked "rewritten" through every later iteration and field read, and
60
+ * built values are tainted, so the body cannot be re-encoded into letters
61
+ * before the gsub and decoded from its output.
62
+ *
63
+ * Nothing else about gsub is admitted: no third (flags) argument, no
64
+ * interpolation, no other pattern; `sub`, which replaces only the first match,
65
+ * stays refused.
66
+ *
67
+ * Cut text (HO-00203): `split` and `indices` cut text into pieces or positions,
68
+ * and a slice of anything but the response root or a scalar field may be a
69
+ * piece of text ("piece" and the slice shape). Once text is cut, a filter can
70
+ * answer once per piece, so a test, comparison, measure or filter of a piece
71
+ * (`select`, `==`, `test`, `length`, `any`, `all`, `isempty`, …) spells the text
72
+ * out: `split("")[] | (select(. == "a") | "a"), …` printed a body byte for byte.
73
+ * Those are refused on cut input, and a value built from a piece, iterated
74
+ * from it or keyed by it stays cut. Iterating a slice reads whole elements,
75
+ * because only an array slice can be iterated. Slice bounds are evaluated like
76
+ * any expression. A fixed number of literal tests or positions of a whole text
77
+ * stays admitted: each answers once per response element, so the filter's own
78
+ * length bounds what they reveal.
79
+ *
37
80
  * Errors: a filter that errors prints gojq's error text, which carries at most
38
81
  * a short fixed-length preview of the offending value (gojq truncates value
39
82
  * previews), too short to hold a signed link. Functions whose error text can
@@ -41,7 +84,9 @@
41
84
  * pattern) only accept literal arguments.
42
85
  */
43
86
 
44
- export type Shape = "safe" | "unknown" | "root" | "tainted" | { leaf: string } | { union: Shape[] };
87
+ export type Shape =
88
+ | "safe" | "letters" | "unknown" | "unknownRewritten" | "root" | "tainted" | "piece"
89
+ | { leaf: string; rewritten?: true } | { slice: Shape } | { union: Shape[] };
45
90
 
46
91
  export interface ProjectionOptions {
47
92
  /** Fields that are plain scalars when read directly from the response root. */
@@ -116,7 +161,7 @@ const FORMATS = new Set(["@text", "@json", "@csv", "@tsv", "@sh", "@base64", "@u
116
161
  type Token =
117
162
  | { t: "dot" }
118
163
  | { t: "field"; name: string }
119
- | { t: "str"; parts: Array<string | { src: string }> }
164
+ | { t: "str"; parts: Array<string | { src: string }>; escaped: boolean }
120
165
  | { t: "num" }
121
166
  | { t: "ident"; name: string }
122
167
  | { t: "fmt"; name: string }
@@ -126,14 +171,15 @@ class Unprovable extends Error {}
126
171
 
127
172
  const fail = (): never => { throw new Unprovable(); };
128
173
 
129
- function readString(src: string, start: number): { end: number; parts: Array<string | { src: string }> } {
174
+ function readString(src: string, start: number): { end: number; parts: Array<string | { src: string }>; escaped: boolean } {
130
175
  // src[start] === '"'
131
176
  const parts: Array<string | { src: string }> = [];
132
177
  let text = "";
178
+ let escaped = false; // a `\X` escape other than interpolation: its decoded text is not `X` in jq
133
179
  let i = start + 1;
134
180
  while (i < src.length) {
135
181
  const ch = src[i];
136
- if (ch === '"') { if (text) parts.push(text); return { end: i + 1, parts }; }
182
+ if (ch === '"') { if (text) parts.push(text); return { end: i + 1, parts, escaped }; }
137
183
  if (ch === "\\") {
138
184
  const next = src[i + 1];
139
185
  if (next === "(") {
@@ -154,6 +200,7 @@ function readString(src: string, start: number): { end: number; parts: Array<str
154
200
  continue;
155
201
  }
156
202
  if (next === undefined) fail();
203
+ escaped = true;
157
204
  text += next;
158
205
  i += 2;
159
206
  continue;
@@ -172,7 +219,7 @@ function tokenize(src: string): Token[] {
172
219
  const ch = src[i];
173
220
  if (/\s/.test(ch)) { i++; continue; }
174
221
  if (ch === "#") fail(); // comments are not supported (see the header)
175
- if (ch === '"') { const s = readString(src, i); out.push({ t: "str", parts: s.parts }); i = s.end; continue; }
222
+ if (ch === '"') { const s = readString(src, i); out.push({ t: "str", parts: s.parts, escaped: s.escaped }); i = s.end; continue; }
176
223
  if (ch === ".") {
177
224
  if (src[i + 1] === ".") fail(); // `..` recursion prints everything
178
225
  const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(src.slice(i + 1));
@@ -212,10 +259,10 @@ type Node =
212
259
  | { k: "field"; name: string; of?: Node }
213
260
  | { k: "iter"; of: Node }
214
261
  | { k: "index"; of: Node; key: Node }
215
- | { k: "slice"; of: Node }
262
+ | { k: "slice"; of: Node; bounds: Node[] }
216
263
  | { k: "opt"; of: Node }
217
264
  | { k: "lit" }
218
- | { k: "str"; parts: Node[]; text?: string }
265
+ | { k: "str"; parts: Node[]; text?: string; escaped?: true }
219
266
  | { k: "fmt"; name: string; str?: Node }
220
267
  | { k: "array"; of?: Node }
221
268
  | { k: "object"; entries: Array<{ key: "static"; value: Node }> }
@@ -228,7 +275,7 @@ type Node =
228
275
  | { k: "neg"; of: Node };
229
276
 
230
277
  /** Constructs outside the supported subset: control flow, bindings, I/O, recursion and path rewriting. */
231
- const REJECTED_KEYWORDS = new Set(["if", "then", "elif", "else", "end", "as", "def", "reduce", "foreach", "try", "catch", "label", "import", "include", "and", "or", "__loc__", "error", "input", "inputs", "debug", "stderr", "env", "halt", "halt_error", "input_filename", "input_line_number", "recurse", "paths", "leaf_paths", "getpath", "setpath", "delpaths", "del", "path", "splits", "sub", "gsub", "capture", "match", "scan", "keys", "keys_unsorted", "map_values", "with_entries", "tostream", "fromstream", "truncate_stream", "walk", "tonumber", "implode", "explode", "ascii", "fromjson"]);
278
+ const REJECTED_KEYWORDS = new Set(["if", "then", "elif", "else", "end", "as", "def", "reduce", "foreach", "try", "catch", "label", "import", "include", "and", "or", "__loc__", "error", "input", "inputs", "debug", "stderr", "env", "halt", "halt_error", "input_filename", "input_line_number", "recurse", "paths", "leaf_paths", "getpath", "setpath", "delpaths", "del", "path", "splits", "sub", "capture", "match", "scan", "keys", "keys_unsorted", "map_values", "with_entries", "tostream", "fromstream", "truncate_stream", "walk", "tonumber", "implode", "explode", "ascii", "fromjson"]);
232
279
 
233
280
  class Parser {
234
281
  private at = 0;
@@ -329,9 +376,9 @@ class Parser {
329
376
  private bracket(of: Node): Node {
330
377
  this.expectOp("[");
331
378
  if (this.isOp("]")) { this.at++; return { k: "iter", of }; }
332
- if (this.isOp(":")) { this.at++; if (!this.isOp("]")) this.pipe(); this.expectOp("]"); return { k: "slice", of }; }
379
+ if (this.isOp(":")) { this.at++; const bounds = this.isOp("]") ? [] : [this.pipe()]; this.expectOp("]"); return { k: "slice", of, bounds }; }
333
380
  const key = this.pipe();
334
- if (this.isOp(":")) { this.at++; if (!this.isOp("]")) this.pipe(); this.expectOp("]"); return { k: "slice", of }; }
381
+ if (this.isOp(":")) { this.at++; const bounds = this.isOp("]") ? [key] : [key, this.pipe()]; this.expectOp("]"); return { k: "slice", of, bounds }; }
335
382
  this.expectOp("]");
336
383
  return { k: "index", of, key };
337
384
  }
@@ -344,16 +391,16 @@ class Parser {
344
391
  case "dot": return { k: "dot" };
345
392
  case "field": return { k: "field", name: t.name };
346
393
  case "num": return { k: "lit" };
347
- case "str": return this.stringNode(t.parts);
394
+ case "str": return this.stringNode(t.parts, t.escaped);
348
395
  case "fmt": {
349
396
  if (!FORMATS.has(t.name)) fail();
350
397
  const next = this.peek();
351
- if (next?.t === "str") { this.at++; return { k: "fmt", name: t.name, str: this.stringNode(next.parts) }; }
398
+ if (next?.t === "str") { this.at++; return { k: "fmt", name: t.name, str: this.stringNode(next.parts, next.escaped) }; }
352
399
  return { k: "fmt", name: t.name };
353
400
  }
354
401
  case "ident": {
355
402
  if (REJECTED_KEYWORDS.has(t.name)) fail();
356
- if (t.name === "map" || OPAQUE_RESULT.has(t.name) || PASSTHROUGH.has(t.name)) {
403
+ if (t.name === "map" || t.name === "gsub" || OPAQUE_RESULT.has(t.name) || PASSTHROUGH.has(t.name)) {
357
404
  const args: Node[] = [];
358
405
  if (this.isOp("(")) {
359
406
  this.at++;
@@ -380,13 +427,14 @@ class Parser {
380
427
  return fail();
381
428
  }
382
429
 
383
- private stringNode(parts: Array<string | { src: string }>): Node {
430
+ private stringNode(parts: Array<string | { src: string }>, escaped: boolean): Node {
384
431
  const nodes: Node[] = [];
385
432
  for (const part of parts) {
386
433
  if (typeof part === "string") continue;
387
434
  nodes.push(new Parser(tokenize(part.src)).parse());
388
435
  }
389
- return nodes.length === 0 ? { k: "str", parts: nodes, text: parts.join("") } : { k: "str", parts: nodes };
436
+ if (nodes.length > 0) return { k: "str", parts: nodes };
437
+ return escaped ? { k: "str", parts: nodes, text: parts.join(""), escaped: true } : { k: "str", parts: nodes, text: parts.join("") };
390
438
  }
391
439
 
392
440
  private object(): Node {
@@ -413,11 +461,31 @@ class Parser {
413
461
 
414
462
  export function isFinalSafe(shape: Shape): boolean {
415
463
  if (typeof shape === "object" && "union" in shape) return shape.union.every(isFinalSafe);
416
- return shape === "safe" || (typeof shape === "object" && SCALAR_FIELDS.has(shape.leaf));
464
+ return shape === "safe" || shape === "letters" || (typeof shape === "object" && SCALAR_FIELDS.has(shape.leaf));
417
465
  }
418
466
 
419
- /** A value built from parts: safe only when every part is. */
420
- const combine = (...shapes: Shape[]): Shape => (shapes.every(isFinalSafe) ? "safe" : "tainted");
467
+ /** Whether `shape` may be printed AND used as material for a new value: everything final-safe except "letters". */
468
+ function isBuildingSafe(shape: Shape): boolean {
469
+ if (typeof shape === "object" && "union" in shape) return shape.union.every(isBuildingSafe);
470
+ return shape !== "letters" && isFinalSafe(shape);
471
+ }
472
+
473
+ /** Whether `shape`, or any member of it, is text cut into pieces (HO-00203): a piece, or a slice of unknown type. */
474
+ function isCut(shape: Shape): boolean {
475
+ if (typeof shape === "object" && "union" in shape) return shape.union.some(isCut);
476
+ return shape === "piece" || (typeof shape === "object" && "slice" in shape);
477
+ }
478
+
479
+ /** Refuse a test, comparison, measure or filter of cut text: its answers, one per piece, can spell the text out. */
480
+ function refuseCut(...shapes: Shape[]): void {
481
+ if (shapes.some(isCut)) fail();
482
+ }
483
+
484
+ /**
485
+ * A value built from parts: safe only when every part is. A letter-only gsub result is never material, and a value
486
+ * built from cut text stays cut, so wrapping a piece (`[.]`, `"\(.)"`, `{a: .}`) does not launder it.
487
+ */
488
+ const combine = (...shapes: Shape[]): Shape => (shapes.some(isCut) ? "piece" : shapes.every(isBuildingSafe) ? "safe" : "tainted");
421
489
 
422
490
  function union(...shapes: Shape[]): Shape {
423
491
  const flat: Shape[] = [];
@@ -435,9 +503,17 @@ function each(shape: Shape, f: (member: Shape) => Shape): Shape {
435
503
 
436
504
  const isFreeform = (shape: Shape) => typeof shape === "object" && "leaf" in shape && FREEFORM.has(shape.leaf);
437
505
 
438
- /** An element of `shape` (iteration, a numeric index, min/max/first/last). */
506
+ /** A value a function re-encoded, or anything iterated or read from one: a letter-only gsub refuses it (HO-00192). */
507
+ const isRewritten = (shape: Shape) => shape === "unknownRewritten" || (typeof shape === "object" && "leaf" in shape && shape.rewritten === true);
508
+
509
+ /**
510
+ * An element of `shape` (iteration, a numeric index, min/max/first/last). An element of cut text is a piece. A slice
511
+ * of unknown type is iterable only if it is an array, whose elements are whole: they read as the sliced value's.
512
+ */
439
513
  const element = (shape: Shape): Shape => each(shape, (member) =>
440
- member === "safe" ? "safe" : member === "tainted" || isFreeform(member) ? "tainted" : "unknown");
514
+ member === "piece" ? "piece" : typeof member === "object" && "slice" in member ? element(member.slice)
515
+ : member === "safe" ? "safe" : member === "tainted" || member === "letters" || isFreeform(member) ? "tainted"
516
+ : isRewritten(member) ? "unknownRewritten" : "unknown");
441
517
 
442
518
  function literalArg(node: Node): boolean {
443
519
  return node.k === "lit" || (node.k === "str" && node.parts.length === 0) || (node.k === "call" && ["true", "false", "null"].includes(node.name) && node.args.length === 0);
@@ -447,10 +523,13 @@ interface Scope { rootScalars: ReadonlySet<string> }
447
523
 
448
524
  function field(shape: Shape, name: string, scope: Scope): Shape {
449
525
  return each(shape, (member) => {
526
+ if (member === "piece") return "piece";
527
+ // Only an array or an object slice has fields, and then they read as the sliced value's.
528
+ if (typeof member === "object" && "slice" in member) return field(member.slice, name, scope);
450
529
  if (member === "safe" || member === "tainted") return member;
451
- if (isFreeform(member)) return "tainted";
530
+ if (member === "letters" || isFreeform(member)) return "tainted";
452
531
  if (member === "root" && scope.rootScalars.has(name)) return "safe";
453
- return { leaf: name };
532
+ return isRewritten(member) ? { leaf: name, rewritten: true } : { leaf: name };
454
533
  });
455
534
  }
456
535
 
@@ -462,29 +541,90 @@ function evaluate(node: Node, input: Shape, scope: Scope): Shape {
462
541
  case "index": {
463
542
  const base = evaluate(node.of, input, scope);
464
543
  if (node.key.k === "str" && node.key.text !== undefined) return field(base, node.key.text, scope); // .["name"] is .name
465
- if (node.key.k === "lit") return element(base);
466
- evaluate(node.key, input, scope);
467
- return "tainted"; // a computed key: which field is read is not known
544
+ // A literal index, negative included (`.[-1]` parses as the negation of a literal), picks one element.
545
+ if (node.key.k === "lit" || (node.key.k === "neg" && node.key.of.k === "lit")) return element(base);
546
+ // A computed key: which field is read is not known. Keyed by cut text, whether each piece names a field
547
+ // answers once per piece, so the result stays cut (HO-00203).
548
+ return isCut(evaluate(node.key, input, scope)) ? "piece" : "tainted";
549
+ }
550
+ // A slice of a string is a piece of it, so for the gsub it is re-encoded like any other rewrite (review 3, B1). A
551
+ // slice of the response root is a slice of its array: its elements stay whole.
552
+ case "slice": {
553
+ // The bounds are expressions over the same input: evaluated, so every construct in them is checked too.
554
+ for (const bound of node.bounds) evaluate(bound, input, scope);
555
+ return sliceOf(evaluate(node.of, input, scope));
468
556
  }
469
- case "slice": return each(evaluate(node.of, input, scope), (member) => (member === "root" ? "unknown" : isFreeform(member) ? "tainted" : member));
470
557
  case "opt": return evaluate(node.of, input, scope);
471
558
  case "lit": return "safe";
472
559
  case "str": return combine(...node.parts.map((part) => evaluate(part, input, scope)));
473
- case "fmt": return node.str ? evaluate(node.str, input, scope) : input;
560
+ case "fmt": return node.str ? evaluate(node.str, input, scope) : reencode(input);
474
561
  case "array": return node.of ? combine(evaluate(node.of, input, scope)) : "safe";
475
562
  case "object": return combine(...node.entries.map((entry) => evaluate(entry.value, input, scope)));
476
563
  case "pipe": return evaluate(node.b, evaluate(node.a, input, scope), scope);
477
564
  case "comma": return union(evaluate(node.a, input, scope), evaluate(node.b, input, scope));
478
565
  case "alt": return union(evaluate(node.a, input, scope), evaluate(node.b, input, scope));
479
- case "bool": evaluate(node.a, input, scope); evaluate(node.b, input, scope); return "safe";
566
+ case "bool": refuseCut(evaluate(node.a, input, scope), evaluate(node.b, input, scope)); return "safe";
480
567
  case "arith": return combine(evaluate(node.a, input, scope), evaluate(node.b, input, scope));
481
- case "neg": return evaluate(node.of, input, scope);
568
+ case "neg": return each(evaluate(node.of, input, scope), (member) => (member === "letters" ? "tainted" : member));
482
569
  case "call": return evaluateCall(node, input, scope);
483
570
  }
484
571
  }
485
572
 
486
- /** A function whose output re-encodes its input: the whole response stops being the root. */
487
- const passthrough = (input: Shape): Shape => each(input, (member) => (member === "root" ? "unknown" : isFreeform(member) ? "tainted" : member));
573
+ /** `gsub`'s pattern, when it is a negated class of ASCII letters and spaces only. */
574
+ const LETTER_ONLY_PATTERN = /^\[\^(?:A-Z|a-z| )+\]\+?$/;
575
+ /** `gsub`'s replacement, when it adds only ASCII letters and spaces. */
576
+ const LETTER_ONLY_REPLACEMENT = /^[A-Za-z ]*$/;
577
+
578
+ /** The literal text of a string argument without interpolation or escapes, else undefined. */
579
+ const literalText = (node: Node): string | undefined =>
580
+ (node.k === "str" && node.parts.length === 0 && !node.escaped ? node.text ?? "" : undefined);
581
+
582
+ /** Passthrough functions that change no character of a string beyond case or trimmed ends, or filter by type. */
583
+ const TEXT_PRESERVING = new Set([
584
+ "ascii_downcase", "ascii_upcase", "trim", "ltrim", "rtrim", "ltrimstr", "rtrimstr",
585
+ "values", "nulls", "strings", "numbers", "booleans", "arrays", "objects", "iterables", "scalars",
586
+ ]);
587
+
588
+ /**
589
+ * A function whose output re-encodes its input: the whole response stops being the root, a letter-only gsub
590
+ * result stops being letters only, and a field's text is marked rewritten (a letter-only gsub refuses it).
591
+ */
592
+ const reencode = (input: Shape, preserving = false): Shape => each(input, (member) => {
593
+ if (member === "piece") return "piece";
594
+ if (typeof member === "object" && "slice" in member) return { slice: reencode(member.slice, preserving) };
595
+ if (member === "letters" || isFreeform(member)) return "tainted";
596
+ if (!preserving && (member === "root" || member === "unknown")) return "unknownRewritten";
597
+ if (member === "root") return "unknown";
598
+ if (!preserving && typeof member === "object" && "leaf" in member) return { leaf: member.leaf, rewritten: true };
599
+ return member;
600
+ });
601
+ const passthrough = (input: Shape, name?: string): Shape => reencode(input, name !== undefined && TEXT_PRESERVING.has(name));
602
+
603
+ /** A scalar field: not free text, so cutting it carries no signed link and keeps the pre-HO-00203 shapes. */
604
+ const isScalarLeaf = (member: Shape) => typeof member === "object" && "leaf" in member && SCALAR_FIELDS.has(member.leaf);
605
+
606
+ /**
607
+ * `split` and `indices` cut text into pieces or positions (HO-00203). A safe value or a scalar field stays as before;
608
+ * anything else becomes a piece, and every later test, comparison, measure or filter of it is refused.
609
+ */
610
+ const cut = (input: Shape, kept: (member: Shape) => Shape): Shape => each(input, (member) =>
611
+ member === "safe" ? "safe" : isScalarLeaf(member) ? kept(member) : "piece");
612
+
613
+ /**
614
+ * A slice. Of the response root, it is a slice of its array, whose elements stay whole. Of a scalar field, it is as
615
+ * before. Of anything else it may be a piece of text or a slice of an array, which is known only at run time, so it is
616
+ * cut: it cannot be tested or filtered, but iterating it reads whole elements (HO-00203).
617
+ */
618
+ const sliceOf = (input: Shape): Shape => each(input, (member) =>
619
+ member === "root" ? "unknown" : member === "safe" ? "safe" : isScalarLeaf(member) ? reencode(member)
620
+ : member === "piece" ? "piece" : { slice: reencode(member) });
621
+
622
+ /** Input a letter-only gsub accepts: a field read directly, a literal, or another letter-only gsub's output. */
623
+ const gsubInputOk = (input: Shape): boolean => {
624
+ if (typeof input === "object" && "union" in input) return input.union.every(gsubInputOk);
625
+ if (input === "safe" || input === "letters") return true;
626
+ return typeof input === "object" && "leaf" in input && !input.rewritten && !FREEFORM.has(input.leaf);
627
+ };
488
628
 
489
629
  function evaluateCall(node: Extract<Node, { k: "call" }>, input: Shape, scope: Scope): Shape {
490
630
  const { name, args } = node;
@@ -494,7 +634,10 @@ function evaluateCall(node: Extract<Node, { k: "call" }>, input: Shape, scope: S
494
634
  if (args.length !== 1) fail();
495
635
  return combine(evaluate(args[0], element(input), scope));
496
636
  case "select":
637
+ // A filter's output is present or absent by its test: on cut text, a literal emitted after it (`select(. == "a")
638
+ // | "a"`) spells the text out one piece at a time (HO-00203).
497
639
  if (args.length !== 1) fail();
640
+ refuseCut(input);
498
641
  evaluate(args[0], input, scope);
499
642
  return input;
500
643
  case "limit":
@@ -520,12 +663,40 @@ function evaluateCall(node: Extract<Node, { k: "call" }>, input: Shape, scope: S
520
663
  return element(input);
521
664
  case "any":
522
665
  case "all":
666
+ // `any(c)` tests each element of the input; `any(g; c)` tests each output of `g`. The condition is evaluated on
667
+ // exactly that, so a comparison of cut text inside it is refused like any other (HO-00203).
668
+ refuseCut(input);
669
+ if (args.length === 1) evaluate(args[0], element(input), scope);
670
+ else if (args.length === 2) evaluate(args[1], evaluate(args[0], input, scope), scope);
671
+ else if (args.length !== 0) fail();
672
+ return "safe";
523
673
  case "isempty":
524
- for (const arg of args) evaluate(arg, "unknown", scope);
674
+ refuseCut(input);
675
+ for (const arg of args) evaluate(arg, input, scope);
525
676
  return "safe";
677
+ case "split":
678
+ if (args.length < 1 || args.length > 2) fail();
679
+ return cut(input, (member) => reencode(member));
680
+ case "indices":
681
+ // Every position of a string in the text: one call per character spells the text out (HO-00203).
682
+ if (args.length !== 1) fail();
683
+ return cut(input, () => "safe");
684
+ case "gsub": {
685
+ // Only the letter-only form (see the header): its output is ASCII letters and spaces, a shape of its own.
686
+ if (args.length !== 2) fail();
687
+ const pattern = literalText(args[0]);
688
+ const replacement = literalText(args[1]);
689
+ if (pattern === undefined || replacement === undefined) fail();
690
+ if (!LETTER_ONLY_PATTERN.test(pattern!) || !LETTER_ONLY_REPLACEMENT.test(replacement!)) fail();
691
+ if (!gsubInputOk(input)) fail();
692
+ return "letters";
693
+ }
694
+ }
695
+ if (OPAQUE_RESULT.has(name)) {
696
+ refuseCut(input);
697
+ return "safe";
526
698
  }
527
- if (OPAQUE_RESULT.has(name)) return "safe";
528
- if (PASSTHROUGH.has(name)) return passthrough(input);
699
+ if (PASSTHROUGH.has(name)) return passthrough(input, name);
529
700
  return fail();
530
701
  }
531
702
 
@@ -28,7 +28,8 @@ organization's vault reference in the published hook.
28
28
  The installed entry reads an owner-protected Hooks configuration from
29
29
  `<effective Hooks home>/config/stop-review.json`, or the explicit absolute
30
30
  `HOOKS_STOP_REVIEW_CONFIG` override. The schema is
31
- `hooks.stop-review-runtime.v1`: `enabled: true`, a selected `model`, the exact
31
+ `hooks.stop-review-runtime.v1`: `enabled: true`, an exact versioned `model`
32
+ (such as `jev-1.13.0`), the exact
32
33
  `instruction` `{id, version, sha256}`, absolute installed CLI paths in
33
34
  `commands` `{instructions, secrets}`, and a `secretsReference`. The optional
34
35
  `harness`, `codexHome` and `codexSocketPath` fields select native integration.
@@ -43,7 +44,9 @@ prompt text. Only then does `secrets exec` project `TYPESAFE_API_KEY` into the
43
44
  same retained hook entry's restricted `--assess-envelope` child. That child
44
45
  verifies the pinned source and request digest against the claim. It cannot
45
46
  inject a continuation or modify the native session. The parent validates its
46
- typed result and rechecks native freshness before delivery.
47
+ typed result and rechecks native freshness before delivery. Every evaluation path
48
+ requires the returned model to equal the selected version. Moving aliases and
49
+ mismatched responses make review unavailable, with no retry or fallback.
47
50
 
48
51
  Managed Instructions supplies the classification instructions and exact
49
52
  continuation text, with source ID, version and digest. There is no model-generated
@@ -10,6 +10,10 @@ const probability = (value: unknown): value is number =>
10
10
  const tokenCount = (value: unknown): value is number =>
11
11
  typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12
12
 
13
+ /** Stop-review thresholds apply to one explicit version, never a moving alias. */
14
+ export const isVersionedJevModel = (value: unknown): value is string =>
15
+ typeof value === "string" && value.length <= 104 && /^jev-(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.exec(value)?.[0] === value;
16
+
13
17
  /** Deliberately typed output: no model-authored continuation instructions or executable text. */
14
18
  export function buildJevRequest(envelope: StopReviewEnvelope, options: JevOptions): object {
15
19
  return {
@@ -24,8 +28,8 @@ export function buildJevRequest(envelope: StopReviewEnvelope, options: JevOption
24
28
  };
25
29
  }
26
30
 
27
- export function parseJevAssessment(value: unknown): JevAssessment | null {
28
- if (!isRecord(value) || typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) ||
31
+ export function parseJevAssessment(value: unknown, expectedModel: string): JevAssessment | null {
32
+ if (!isVersionedJevModel(expectedModel) || !isRecord(value) || value.model !== expectedModel ||
29
33
  !isRecord(value.answers) || !isRecord(value.usage)) return null;
30
34
  const { disposition, actionable, boundary } = value.answers;
31
35
  if (Object.keys(value.answers).sort().join(",") !== "actionable,boundary,disposition" ||
@@ -53,7 +57,8 @@ export function parseJevAssessment(value: unknown): JevAssessment | null {
53
57
  /** One request, fixed HTTPS origin, no redirects/retries, bounded response and duration. */
54
58
  export async function evaluateJev(envelope: StopReviewEnvelope, options: JevOptions): Promise<JevResult> {
55
59
  if (!options.apiKey?.trim()) return { ok: false, reason: "credential_unavailable" };
56
- if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(options.model)) return { ok: false, reason: "invalid_configuration" };
60
+ const model = options.model;
61
+ if (!isVersionedJevModel(model)) return { ok: false, reason: "invalid_configuration" };
57
62
  const timeoutMs = options.timeoutMs ?? 8_000;
58
63
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15_000) return { ok: false, reason: "invalid_configuration" };
59
64
  const body = JSON.stringify(buildJevRequest(envelope, options));
@@ -109,7 +114,7 @@ export async function evaluateJev(envelope: StopReviewEnvelope, options: JevOpti
109
114
  let decoded: unknown;
110
115
  try { decoded = JSON.parse(Buffer.concat(chunks).toString("utf8")); }
111
116
  catch { return { ok: false, reason: "invalid_provider_response" }; }
112
- const assessment = parseJevAssessment(decoded);
117
+ const assessment = parseJevAssessment(decoded, model);
113
118
  return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
114
119
  } catch {
115
120
  // Never serialize provider errors: their bodies/headers may echo credentials or private input.
@@ -1,4 +1,4 @@
1
- import { evaluateJev, parseJevAssessment } from "./jev";
1
+ import { evaluateJev, isVersionedJevModel, parseJevAssessment } from "./jev";
2
2
  import { STOP_CLASSES } from "./types";
3
3
  import type { StopReviewAdmission, StopRecommendationOptions, StopReviewEnvelope, StopReviewInstruction, StopReviewOptions, StopReviewReason, StopReviewResult } from "./types";
4
4
 
@@ -135,6 +135,10 @@ async function assessStop(input: unknown, options: StopReviewOptions | StopRecom
135
135
  if (gate) return stop(gate);
136
136
  if (!isStopReviewInstruction(options.instruction)) return stop("instruction_unavailable");
137
137
  if (options.externalContentApproved !== true) return stop("external_content_unapproved");
138
+ const model = options.model;
139
+ if (!isVersionedJevModel(model)) return stop("invalid_configuration");
140
+ const evaluationOptions = { ...options, model };
141
+ const evaluate = options.evaluate ?? evaluateJev;
138
142
  const current = async () => {
139
143
  let timer: ReturnType<typeof setTimeout>;
140
144
  try {
@@ -146,7 +150,7 @@ async function assessStop(input: unknown, options: StopReviewOptions | StopRecom
146
150
  };
147
151
  if (!parentGuarded && !await current()) return stop("stale_input");
148
152
  let assessed;
149
- try { assessed = await (options.evaluate ?? evaluateJev)(envelope, options); }
153
+ try { assessed = await evaluate(envelope, evaluationOptions); }
150
154
  catch { return { ...base, action: "unavailable", reason: "provider_unavailable" }; }
151
155
  // Capture can change while HTTP is outstanding. Never apply a decision to a new turn/context/goal.
152
156
  if ((!parentGuarded && !await current()) || stopPolicyGate(envelope, now(), max, gateOptions)) return stop("stale_input");
@@ -158,7 +162,7 @@ async function assessStop(input: unknown, options: StopReviewOptions | StopRecom
158
162
  const checked = parseJevAssessment({ model: assessment.model, answers: {
159
163
  disposition: { type: "choice", choice: assessment.classification, confidence: assessment.confidence, probabilities: assessment.probabilities },
160
164
  actionable: { type: "noul", noul: assessment.actionableProbability }, boundary: { type: "noul", noul: assessment.boundaryProbability },
161
- }, usage: { input_tokens: assessment.inputTokens, output_tokens: assessment.outputTokens } });
165
+ }, usage: { input_tokens: assessment.inputTokens, output_tokens: assessment.outputTokens } }, model);
162
166
  if (!checked) return { ...base, action: "unavailable", reason: "invalid_provider_response" };
163
167
  const provenance = { sourceId: options.instruction.sourceId, version: options.instruction.version, digest: options.instruction.digest };
164
168
  const result = { ...base, assessment, classification: assessment.classification, instruction: provenance };
@@ -5,7 +5,7 @@ import { isAbsolute, join } from "node:path";
5
5
  import { getEffectiveDataRoot, getHomeDir } from "../../../src/lib/app-home";
6
6
  import { restoreStopReviewClientContext, stopReviewClientContextRefused } from "../../../src/lib/stop-review-context";
7
7
  import { nativeChildEnv } from "../../../src/lib/native-child-env";
8
- import { buildJevRequest, evaluateJev, parseJevAssessment } from "./jev";
8
+ import { buildJevRequest, evaluateJev, isVersionedJevModel, parseJevAssessment } from "./jev";
9
9
  import { isStopReviewEnvelope, isStopReviewInstruction, recommendStop, reviewStop, stopPolicyGate } from "./policy";
10
10
  import type { CodexStopReviewAdmission, JevResult, ParentStopReviewAdmission, StopReviewAdmission, StopReviewEnvelope, StopReviewInstruction, StopReviewNativeTarget, StopReviewResult } from "./types";
11
11
 
@@ -37,7 +37,7 @@ const safePath = (value: unknown): value is string => typeof value === "string"
37
37
 
38
38
  export function parseRuntimeConfiguration(value: unknown): StopReviewRuntimeConfiguration | null {
39
39
  if (!record(value) || value.schema !== "hooks.stop-review-runtime.v1" || value.enabled !== true ||
40
- typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) ||
40
+ !isVersionedJevModel(value.model) ||
41
41
  !record(value.instruction) || typeof value.instruction.id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(value.instruction.id) ||
42
42
  !Number.isSafeInteger(value.instruction.version) || (value.instruction.version as number) < 1 ||
43
43
  typeof value.instruction.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.instruction.sha256) ||
@@ -237,7 +237,8 @@ export async function evaluateThroughSecrets(envelope: StopReviewEnvelope, instr
237
237
  config: StopReviewRuntimeConfiguration, env: NodeJS.ProcessEnv, entrypoint: string,
238
238
  run: RuntimeCommandRunner = runRuntimeCommand, admission?: StopReviewAdmission,
239
239
  nativeTarget?: StopReviewNativeTarget): Promise<JevResult> {
240
- if (stopReviewClientContextRefused(env)) return { ok: false, reason: "invalid_configuration" };
240
+ const model = config.model;
241
+ if (!isVersionedJevModel(model) || stopReviewClientContextRefused(env)) return { ok: false, reason: "invalid_configuration" };
241
242
  if (!safePath(entrypoint)) return { ok: false, reason: "invalid_configuration" };
242
243
  let canonical: string;
243
244
  try {
@@ -259,7 +260,7 @@ export async function evaluateThroughSecrets(envelope: StopReviewEnvelope, instr
259
260
  const assessment = parseJevAssessment({ model: a.model, answers: {
260
261
  disposition: { type: "choice", choice: a.classification, confidence: a.confidence, probabilities: a.probabilities },
261
262
  actionable: { type: "noul", noul: a.actionableProbability }, boundary: { type: "noul", noul: a.boundaryProbability },
262
- }, usage: { input_tokens: a.inputTokens, output_tokens: a.outputTokens } });
263
+ }, usage: { input_tokens: a.inputTokens, output_tokens: a.outputTokens } }, model);
263
264
  return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
264
265
  }
265
266
  const allowed = ["credential_unavailable", "invalid_configuration", "instruction_unavailable", "claim_unavailable", "invalid_input", "request_too_large", "response_too_large", "request_timeout", "provider_unavailable", "invalid_provider_response", "credential_rejected", "provider_rate_limited", "provider_request_refused", "provider_overloaded"];
@@ -124,10 +124,15 @@ rewritten, because that spelling moves the offsets a rewrite needs. Such words
124
124
  are found in one pass from the left and, beside that, from every `$'`
125
125
  (HO-00222). A `$'` that bash does not read as ANSI-C (inside quotes, in a
126
126
  comment or a here-document body) started a word in the first pass that ran to
127
- the real word's opening quote and hid it. Either pass can respell a `\'` that
128
- bash keeps outside such a word, which only ever adds a refusal. One known case
129
- since HO-00213: a delete after `x="$'it\'s'"`, where `$'` inside double quotes
130
- is not ANSI-C, is refused rather than rewritten into Trash.
127
+ the real word's opening quote and hid it. Such words are also found as bash
128
+ reads them (HO-00233), following backslashes, quotes, comments, here-document
129
+ bodies and substitutions: the pass from every `$'` also respelled an escaped
130
+ `\$'a\'` or a doubled `$$'a\'`, whose single-quoted string then never closed,
131
+ and a delete after the real word was hidden from every reading. Any pass can
132
+ respell a `\'` that bash keeps outside such a word, which only ever adds a
133
+ refusal. One known case since HO-00213: a delete after `x="$'it\'s'"`, where
134
+ `$'` inside double quotes is not ANSI-C, is refused rather than rewritten into
135
+ Trash.
131
136
 
132
137
  Each refusal carries a reason and a way forward: re-run the delete as
133
138
  `rm -- <path>`, which this hook intercepts and redirects.