opencode-self-improvement 0.34.1 → 0.34.3

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.
@@ -10,8 +10,10 @@ modulo case, wrapping and markup — or whose only content is a command the
10
10
  project's own gates declare, is REFUSED at capture time and logged on the
11
11
  `auto_capture_restatable` evidence line, which names the file or the gate.
12
12
  The figure-subset invariant bounds both paths: a refusal claims the passage it
13
- cites states EVERY figure the candidate states, as whole tokens (`1.5`,
14
- `1.4.3`, `10.20.30.40` are single figures) — on the text path that passage is
13
+ cites states EVERY figure the candidate states, as whole tokens compared by
14
+ canonical value (`1.5`, `1.4.3`, `10.20.30.40` and `1,024` are single figures,
15
+ and `1,024` and `1024` are the same figure once the grouping comma is
16
+ dropped) — on the text path that passage is
15
17
  the region the match covered, not the tree at large, since a figure in another
16
18
  sentence is another sentence's business — and on the gate path the figures are
17
19
  compared against the declared command, never against the candidate's own
@@ -29,11 +31,13 @@ is not enough: `--target staging --fallback canary` declared against
29
31
  `--target canary --fallback staging` has every word present and the pairing
30
32
  wrong. One relation, both paths.
31
33
 
32
- Atomicity is the spine, not another guard. A figure is one token wherever the
33
- matcher reads it — `tokens()` treats `.` as a word character, so `1.5`, `1.4.3`
34
- and the `11.` of a sentence ending on one are single figures — therefore the
35
- claim splitter never cuts inside a figure and a match is admitted only when no
36
- figure run crosses either edge of it. Half-figures are what every earlier round
34
+ Atomicity is the spine, not another guard. A figure is one definition wherever
35
+ the matcher reads it: the figure grammar exported from `core/tokenize.ts` makes
36
+ a digit-bearing word run, where `.` and `,` belong to it only between digits —
37
+ `1.5`, `1.4.3` and `1,024` are single figures, and the `.` that ends a sentence
38
+ on one is prose, so `1.5.` states the figure `1.5` — therefore the claim
39
+ splitter never cuts inside a figure and a match is admitted only when no figure
40
+ run crosses either edge of it. Half-figures are what every earlier round
37
41
  kept meeting from a different angle: a claim ending at the `3` of `3.12` is cut,
38
42
  then re-tokenized by the region slice as a figure the tree never states. Judging
39
43
  the boundary makes that shape unrepresentable rather than merely unvouched. The
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.34.1",
3
+ "version": "0.34.3",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -55,6 +55,7 @@ import { lstatSync, readFileSync } from "node:fs";
55
55
  import { join, relative } from "node:path";
56
56
  import {
57
57
  POL_NEG,
58
+ figureExtent,
58
59
  numericTokens,
59
60
  polaritySigns,
60
61
  tokens,
@@ -232,30 +233,14 @@ function cueNegated(text: string): boolean {
232
233
  return NEGATION.test(text);
233
234
  }
234
235
 
235
- /**
236
- * VETO 2: a figure the matched DECLARATION does not carry.
237
- *
238
- * `core/tokenize.ts` states the rule and `store/tombstones/tombstone.ts`
239
- * measures it on this repo's own data: a correction scores HIGHER than an honest
240
- * rewording, so overlap alone cannot separate "the same fact again" from "the
241
- * fact has changed". On the declared-command path the manifest states only that
242
- * a command exists, so any number the row asserts has to be in the DECLARED
243
- * command — `gate.label` — or the row is new. The comparison text is never the
244
- * candidate's own spans: a row whose command span carries a flag value
245
- * (`--timeout 5000`) would supply the figure that clears its own veto, and the
246
- * declaration, not the row, is what must vouch for the number.
247
- * `numericTokens` keeps dotted numbers whole, so versions and addresses are
248
- * single figures and cannot be assembled out of separate integers.
249
- */
250
- function introducesNewNumber(text: string, matched: string): boolean {
251
- const known = new Set(numericTokens(matched));
252
- for (const n of numericTokens(text)) if (!known.has(n)) return true;
253
- return false;
254
- }
255
-
256
236
  /**
257
237
  * True when every figure `text` states appears in `known` as a whole token —
258
- * the veto-2 rule, now aimed at the matched region. `claims()` no longer splits
238
+ * the figure rule behind both figure checks, aimed at the matched region on the
239
+ * tracked path and at the vouching declarations on the gate path.
240
+ * `core/tokenize.ts` states the grammar and `store/tombstones/tombstone.ts`
241
+ * measures why a figure is checked at all: a correction scores HIGHER than an
242
+ * honest rewording, so overlap alone cannot separate "the same fact again" from
243
+ * "the fact has changed". `claims()` no longer splits
259
244
  * inside a figure and `findClause` admits no hit that cuts one, so a figure the
260
245
  * tree never states (`1.5`, `1.4.3`, `10.20.30.40`) cannot reassemble from
261
246
  * fragments of separate sentences; this check stays as the second net, because
@@ -355,13 +340,22 @@ interface Slice {
355
340
  /** Declared gates: a command the project already runs, and where it is declared. */
356
341
  interface Gate {
357
342
  label: string;
343
+ /** Citation only: the file and the kind of declaration a refusal names. */
358
344
  where: string;
359
345
  /**
360
- * True for a step among siblings — a Makefile recipe, a workflow `run:` line.
361
- * Those share one `where` across the whole file while stating nothing about
362
- * each other, so the label is all the declaration it has.
346
+ * Declaration identity. Gates that state the SAME declaration share a group,
347
+ * and only a group member vouches for another: a script's name and its
348
+ * command share one, so `--prod` written in the command vouches for `--prod`
349
+ * in the row. A step among siblings — a Makefile recipe, a workflow `run:`
350
+ * line — gets a group no sibling joins, because those share a `where` across
351
+ * the whole file while stating nothing about each other. The group is part of
352
+ * the contract every declaration kind answers for: a kind whose `where`
353
+ * names a FILE must derive the group per declaration, because reusing the
354
+ * file-wide `where` as the group lets one step's operands vouch for another
355
+ * step's row — a refusal that loses a fact. A required field forces the
356
+ * question at the call site; an optional flag defaults past it.
363
357
  */
364
- solo?: boolean;
358
+ group: string;
365
359
  }
366
360
 
367
361
  function readTracked(repoDir: string, file: string): string | null {
@@ -381,9 +375,9 @@ function skipPath(file: string): boolean {
381
375
 
382
376
  function parseGates(repoDir: string, files: string[]): Gate[] {
383
377
  const gates: Gate[] = [];
384
- const add = (label: string, where: string, solo = false) => {
378
+ const add = (label: string, where: string, group: string) => {
385
379
  const n = norm(label);
386
- if (n.length >= 2 && n.length <= 80) gates.push({ label: n, where, solo });
380
+ if (n.length >= 2 && n.length <= 80) gates.push({ label: n, where, group });
387
381
  };
388
382
  for (const file of files) {
389
383
  if (skipPath(file)) continue;
@@ -401,8 +395,9 @@ function parseGates(repoDir: string, files: string[]): Gate[] {
401
395
  try {
402
396
  const pkg = JSON.parse(text) as { scripts?: Record<string, string> };
403
397
  for (const [name, cmd] of Object.entries(pkg.scripts ?? {})) {
404
- add(name, `${file} scripts.${name}`);
405
- if (typeof cmd === "string") add(cmd, `${file} scripts.${name}`);
398
+ const where = `${file} scripts.${name}`;
399
+ add(name, where, where);
400
+ if (typeof cmd === "string") add(cmd, where, where);
406
401
  }
407
402
  } catch {
408
403
  // An unparseable manifest is not evidence of absence.
@@ -412,15 +407,19 @@ function parseGates(repoDir: string, files: string[]): Gate[] {
412
407
  if (base === "Makefile" || base === "makefile" || base === "justfile") {
413
408
  for (const line of text.split("\n")) {
414
409
  const target = /^([A-Za-z0-9_.%-]+)\s*:(?!=)/.exec(line);
415
- if (target?.[1]) add(target[1], `${file} target ${target[1]}`);
410
+ if (target?.[1]) {
411
+ const where = `${file} target ${target[1]}`;
412
+ add(target[1], where, where);
413
+ }
416
414
  const recipe = /^\t+([^\s].*)$/.exec(line);
417
- if (recipe?.[1]) add(recipe[1], `${file} recipe`, true);
415
+ if (recipe?.[1])
416
+ add(recipe[1], `${file} recipe`, `${file} recipe ${norm(recipe[1])}`);
418
417
  }
419
418
  continue;
420
419
  }
421
420
  for (const line of text.split("\n")) {
422
421
  const run = /^\s*-?\s*run:\s*["']?(.+?)["']?\s*$/.exec(line);
423
- if (run?.[1]) add(run[1], `${file} run`, true);
422
+ if (run?.[1]) add(run[1], `${file} run`, `${file} run ${norm(run[1])}`);
424
423
  }
425
424
  }
426
425
  return gates;
@@ -452,20 +451,18 @@ function runners(span: string): string[] {
452
451
  }
453
452
 
454
453
  /**
455
- * The labels that vouch for a declaration: the matched one, plus those sharing
456
- * its `where` when that `where` names ONE command. A script declaration states
457
- * its name and its command together, so `--prod` written in the command vouches
458
- * for `--prod` in the row. A step-kind `where` names a FILE — every recipe in a
454
+ * The labels that vouch for a declaration: every gate in its GROUP. A script
455
+ * declaration states its name and its command together, so `--prod` written in
456
+ * the command vouches for `--prod` in the row. The union is keyed on the group,
457
+ * never on `where`: a step-kind `where` names a FILE — every recipe in a
459
458
  * Makefile, every `run:` in a workflow — and siblings state nothing about each
460
- * other, so there the matched label alone vouches.
459
+ * other, so each step's group holds only itself. Keying on `where` let a new
460
+ * declaration kind inherit a file-wide union by forgetting a flag, and a
461
+ * file-wide union vouches for a refusal with another step's operands.
461
462
  */
462
463
  function vouchLabels(gate: Gate, gates: Gate[]): string[] {
463
464
  const out: string[] = [];
464
- for (const g of gates) {
465
- if (g.where !== gate.where) continue;
466
- if (gate.solo && g.label !== gate.label) continue;
467
- out.push(g.label);
468
- }
465
+ for (const g of gates) if (g.group === gate.group) out.push(g.label);
469
466
  return out;
470
467
  }
471
468
 
@@ -512,28 +509,21 @@ function contiguousIn(operand: string[], labels: string[]): boolean {
512
509
  * So the gate path asks the tree path's question — contiguity, not presence.
513
510
  * The operand must be a contiguous token run inside a vouching label; the empty
514
511
  * operand is the bare invocation, which the declaration states on its own.
512
+ * Each span asks its OWN declarations: one shared label set let a second,
513
+ * unrelated mention lend its operands to the first, and the candidate run and
514
+ * the labels it settles against must come from the SAME declaration —
515
+ * stripping one label and testing the remainder against another's command is
516
+ * the shared lookup in a new coat.
515
517
  * Anything the check cannot establish — the label not located, values swapped,
516
518
  * flags reordered, an operand broken by a word the declaration omits — keeps
517
519
  * the row. Reordering valueless flags keeps too: order-irrelevance is not a
518
520
  * thing a token comparison can prove, a wrong keep costs a row, and a wrong
519
521
  * refusal costs a fact.
520
522
  */
521
- function operandsDeclared(spans: string[], gate: Gate, gates: Gate[]): boolean {
522
- for (const span of spans) {
523
- const matched = gateHit([span], gates) ?? gate;
524
- // Each span vouches with its OWN declaration. One shared label set let a
525
- // second, unrelated mention lend its operands to the first: with `build:
526
- // "compiler"` and `deploy: "deploy-tool publish --target staging …"`, the
527
- // row `Run \`npm run deploy\`. Run \`npm run build -- --target staging\`.`
528
- // checked the build operand against the deploy command, which happens to
529
- // contain it, and the bare deploy mention hid the build information.
530
- const candidates = operandCandidates(span, matched);
531
- if (candidates.length === 0) return false;
532
- const labels = vouchLabels(matched, gates);
533
- if (!candidates.some((o) => o.length === 0 || contiguousIn(o, labels)))
534
- return false;
535
- }
536
- return true;
523
+ function operandSettled(span: string, gate: Gate, gates: Gate[]): boolean {
524
+ const candidates = operandCandidates(span, gate);
525
+ const labels = vouchLabels(gate, gates);
526
+ return candidates.some((o) => o.length === 0 || contiguousIn(o, labels));
537
527
  }
538
528
 
539
529
  // Matching is positional, never substring. A gate named `all` must not refuse a
@@ -541,22 +531,27 @@ function operandsDeclared(spans: string[], gate: Gate, gates: Gate[]): boolean {
541
531
  // "the test suite". So a single-word gate (a script name, a make target) only
542
532
  // matches the OPERAND position — the first token after the runner is stripped —
543
533
  // and a multi-word gate (a declared command) matches whole.
544
- function gateHit(spans: string[], gates: Gate[]): Gate | null {
545
- for (const span of spans) {
546
- for (const form of runners(span)) {
547
- const first = form.split(" ")[0] ?? "";
548
- for (const g of gates) {
549
- if (form === g.label) return g;
550
- if (!g.label.includes(" ") && first === g.label) return g;
551
- if (
552
- g.label.includes(" ") &&
553
- (form.startsWith(`${g.label} `) || form.endsWith(` ${g.label}`))
554
- )
555
- return g;
556
- }
534
+ //
535
+ // Every match is returned, not the first: which file `git ls-files` lists
536
+ // first is not evidence, and a span declared in a CI step AND in a manifest
537
+ // script rests on both. An empty result means the span states no declared
538
+ // command.
539
+ function gateHits(span: string, gates: Gate[]): Gate[] {
540
+ const out: Gate[] = [];
541
+ for (const form of runners(span)) {
542
+ const first = form.split(" ")[0] ?? "";
543
+ for (const g of gates) {
544
+ if (out.includes(g)) continue;
545
+ if (form === g.label) out.push(g);
546
+ else if (!g.label.includes(" ") && first === g.label) out.push(g);
547
+ else if (
548
+ g.label.includes(" ") &&
549
+ (form.startsWith(`${g.label} `) || form.endsWith(` ${g.label}`))
550
+ )
551
+ out.push(g);
557
552
  }
558
553
  }
559
- return null;
554
+ return out;
560
555
  }
561
556
 
562
557
  /**
@@ -573,9 +568,10 @@ function gateHit(spans: string[], gates: Gate[]): Gate | null {
573
568
  * A split never falls inside a figure. Splitting `1.5` at its dot produced two
574
569
  * claims that each matched their own sentence and reassembled into a figure the
575
570
  * tree never states, and the same fragments let a claim end mid-number in the
576
- * tree. `tokens()` reads `.` as a word character, so the boundary waits for the
577
- * figure run to end — including the sentence dot a figure ends on, which belongs
578
- * to that token (`numericTokens("The cost is 11.")` is `["11."]`). A claim that
571
+ * tree. The boundary waits for `figureExtent`'s figure run to end — including
572
+ * the sentence dot a figure ends on, which the splitter treats as run territory
573
+ * even though the figure's canonical value excludes it
574
+ * (`numericTokens("The cost is 11.")` is `["11"]`). A claim that
579
575
  * therefore spans a sentence boundary is fail-open: a longer claim is harder to
580
576
  * match, so the rule can only remove refusals.
581
577
  */
@@ -592,14 +588,14 @@ function claims(text: string): string[] {
592
588
  return out;
593
589
  }
594
590
 
595
- /** The assertion boundaries, minus a `.` that sits inside a figure. */
591
+ /** The assertion boundaries, minus a `.` that sits inside a figure run. */
596
592
  function splitClaims(text: string): string[] {
597
593
  const parts: string[] = [];
598
594
  let from = 0;
599
595
  for (let i = 0; i < text.length; i++) {
600
596
  const c = text.charCodeAt(i);
601
597
  if (c !== 46 && c !== 59 && c !== 58 && c !== 10) continue;
602
- if (c === 46 && figureRun(text, i)) continue;
598
+ if (c === 46 && figureExtent(text, i)) continue;
603
599
  parts.push(text.slice(from, i));
604
600
  from = i + 1;
605
601
  }
@@ -683,6 +679,27 @@ function warnsAgainst(prefix: string): boolean {
683
679
  return WARNS_AGAINST.test(prefix);
684
680
  }
685
681
 
682
+ /**
683
+ * Does a hit cover every figure it touches, whole? A clause ending at the `3`
684
+ * of `3.12`, or starting at the `5` of `30.5`, cuts a figure in half, and the
685
+ * half re-tokenizes as a whole figure the tree never states: `3` is not in a
686
+ * README that says `Requires Python 3.12`, it is what slicing leaves behind.
687
+ * Word boundaries do not settle this — `.` is a word character to the tokenizer
688
+ * and a sentence boundary to the claim splitter, and the two disagree exactly
689
+ * inside a number. So a hit is admitted only when no figure run crosses either
690
+ * edge, which makes a half-figure unrepresentable rather than merely unvouched.
691
+ * The edges are `figureExtent`'s, from `core/tokenize.ts` — the same definition
692
+ * `numericTokens` compares with, so the boundary this veto admits and the set
693
+ * the refusal vouches cannot disagree.
694
+ */
695
+ function hitCoversFigures(hay: string, start: number, end: number): boolean {
696
+ for (const pos of [start - 1, end]) {
697
+ const run = figureExtent(hay, pos);
698
+ if (run && (run.start < start || run.end > end)) return false;
699
+ }
700
+ return true;
701
+ }
702
+
686
703
  /**
687
704
  * Where the tree states `clause` as its own words, in a sentence of the same
688
705
  * polarity. -1 means "not available".
@@ -701,55 +718,6 @@ function warnsAgainst(prefix: string): boolean {
701
718
  * A reversed clause is not evidence of availability, and every uncertainty in
702
719
  * this file keeps the candidate.
703
720
  */
704
- function isTokenChar(code: number): boolean {
705
- return (
706
- (code >= 48 && code <= 57) || // 0-9
707
- (code >= 97 && code <= 122) || // a-z, after norm()
708
- code === 95 || // _
709
- code === 46 // .
710
- );
711
- }
712
-
713
- /**
714
- * The extent of the token `tokens()` would read at `pos`, when that token
715
- * states a digit. `tokens()` splits on `[^a-z0-9_.]+`, so a dot is a word
716
- * character: `1.5`, `1.4.3` and `10.20.30.40` are single tokens, and so is the
717
- * `11.` of a sentence that ends on one. Nothing else in this file may decide
718
- * where a figure begins or ends, because the same definition is what the figure
719
- * subset check compares with.
720
- */
721
- function figureRun(
722
- text: string,
723
- pos: number,
724
- ): { start: number; end: number } | null {
725
- if (pos < 0 || pos >= text.length || !isTokenChar(text.charCodeAt(pos)))
726
- return null;
727
- let start = pos;
728
- while (start > 0 && isTokenChar(text.charCodeAt(start - 1))) start--;
729
- let end = pos;
730
- while (end + 1 < text.length && isTokenChar(text.charCodeAt(end + 1))) end++;
731
- if (!/[0-9]/.test(text.slice(start, end + 1))) return null;
732
- return { start, end: end + 1 };
733
- }
734
-
735
- /**
736
- * Does a hit cover every figure it touches, whole? A clause ending at the `3`
737
- * of `3.12`, or starting at the `5` of `30.5`, cuts a figure in half, and the
738
- * half re-tokenizes as a whole figure the tree never states: `3` is not in a
739
- * README that says `Requires Python 3.12`, it is what slicing leaves behind.
740
- * Word boundaries do not settle this — `.` is a word character to the tokenizer
741
- * and a sentence boundary to the claim splitter, and the two disagree exactly
742
- * inside a number. So a hit is admitted only when no figure run crosses either
743
- * edge, which makes a half-figure unrepresentable rather than merely unvouched.
744
- */
745
- function hitCoversFigures(hay: string, start: number, end: number): boolean {
746
- for (const pos of [start - 1, end]) {
747
- const run = figureRun(hay, pos);
748
- if (run && (run.start < start || run.end > end)) return false;
749
- }
750
- return true;
751
- }
752
-
753
721
  function findClause(hay: string, clause: string, start = 0): number {
754
722
  const reversed = cueNegated(clause);
755
723
  for (let from = start; ; ) {
@@ -987,8 +955,8 @@ export function availabilityIndex(
987
955
  // 3. otherwise, every assertion left in it is one the tracked files
988
956
  // state themselves.
989
957
  const spans = statedCommands(content);
990
- const gate = gateHit(spans, gates);
991
- if (gate) {
958
+ const hits = spans.map((s) => gateHits(s, gates));
959
+ if (hits.some((h) => h.length > 0)) {
992
960
  // VETOES. The manifest states that a command EXISTS. It does not
993
961
  // state that the command is safe, allowed, or finished, and it carries
994
962
  // no figure. So a sentence that forbids the command, or a number the
@@ -1000,24 +968,70 @@ export function availabilityIndex(
1000
968
  // veto-only shape: the vocabulary never has to be perfect, because a
1001
969
  // miss keeps the row instead of deleting it.
1002
970
  if (forbidsCommand(content, spans)) return null;
1003
- // The comparison text is the DECLARED command, never the candidate's
1004
- // spans: a span carrying `--timeout 5000` would vouch for its own
1005
- // figure, and the manifest states no such number.
1006
- if (introducesNewNumber(content, gate.label)) return null;
1007
- // The strip below removes the ENTIRE span, so what the span carries has
1008
- // to be settled here or it is erased before anything reads it.
1009
- if (!operandsDeclared(spans, gate, gates)) return null;
1010
- const undeclared = spans.some((s) => gateHit([s], gates) === null);
971
+ // VETOES 2 AND 3, per span and per declaration. A span settles
972
+ // against ONE declaration that carries BOTH dimensions: every figure
973
+ // the span states appears among the figures of that declaration's
974
+ // group, and its operand is a contiguous token run inside the same
975
+ // group. The two dimensions stay distinct checks — figures ask
976
+ // set membership, operands ask contiguity and pairing, and collapsing
977
+ // one into the other reopens the pairing hole the contiguity comment
978
+ // above records. What changed is the unit: never one label chosen by
979
+ // scan order, and never the union of two declarations that merely
980
+ // both match the span — a row citing one command is not answered by
981
+ // two commands' figures pooled together. A row that spells
982
+ // `npm run deploy --replicas 3` against
983
+ // `"deploy": "deploy-tool publish --replicas 3"` settles against the
984
+ // deploy declaration, whose command carries the figure, instead of
985
+ // the bare name, which carries none and kept the row for the wrong
986
+ // reason. The comparison text is still the DECLARED command, never
987
+ // the candidate's spans: a span carrying `--timeout 5000` would vouch
988
+ // for its own figure, and the declaration, not the row, is what must
989
+ // vouch for a number.
990
+ const settledBy: Gate[][] = spans.map(() => []);
991
+ for (let i = 0; i < spans.length; i++) {
992
+ for (const g of hits[i]) {
993
+ const known = new Set<string>();
994
+ for (const label of vouchLabels(g, gates))
995
+ for (const n of numericTokens(label)) known.add(n);
996
+ if (!figuresWithin(spans[i], known)) continue;
997
+ if (operandSettled(spans[i], g, gates)) settledBy[i].push(g);
998
+ }
999
+ // No declaration carries the span — undeclared, or operands or
1000
+ // figures the declaration does not state. The strip below removes
1001
+ // the ENTIRE span, so what the span carries has to be settled here
1002
+ // or it is erased before anything reads it.
1003
+ if (settledBy[i].length === 0) return null;
1004
+ }
1011
1005
  let residual = content;
1012
1006
  for (const span of spans) residual = residual.split(span).join(" ");
1013
1007
  const rest = claims(norm(residual));
1014
- if (
1015
- !undeclared &&
1016
- (rest.length === 0 || restatedContiguously(haystack, rest) !== null)
1017
- ) {
1008
+ const restRegion =
1009
+ rest.length === 0 ? null : restatedContiguously(haystack, rest);
1010
+ if (rest.length === 0 || restRegion !== null) {
1011
+ // A figure outside every quoted command is prose, and prose settles
1012
+ // against the passage this refusal cites for it — the same region
1013
+ // the tracked path answers with. A figure no cited passage states is
1014
+ // a claim the tree does not make, and where there is no region at
1015
+ // all nothing vouched for the prose: both keep the row.
1016
+ const outside = numericTokens(residual);
1017
+ if (outside.length > 0) {
1018
+ if (restRegion === null) return null;
1019
+ const stated = new Set(
1020
+ numericTokens(haystack.slice(restRegion.start, restRegion.end)),
1021
+ );
1022
+ if (!outside.every((n) => stated.has(n))) return null;
1023
+ }
1024
+ // The refusal rested on the declarations that settled each span,
1025
+ // so it cites exactly those: naming one file for a row resting on
1026
+ // two is not evidence, and naming a declaration that settled
1027
+ // nothing sends the auditor to the wrong line.
1028
+ const cited: string[] = [];
1029
+ for (const s of settledBy)
1030
+ for (const g of s)
1031
+ if (!cited.includes(g.where)) cited.push(g.where);
1018
1032
  return {
1019
1033
  reason: "declared_gate",
1020
- where: gate.where,
1034
+ where: cited.join(", "),
1021
1035
  matched: safeWhole.slice(0, 120),
1022
1036
  };
1023
1037
  }
@@ -31,10 +31,100 @@ export const STOPWORDS: ReadonlySet<string> = new Set([
31
31
  ]);
32
32
 
33
33
  export function tokens(text: string): string[] {
34
- return text
35
- .toLowerCase()
36
- .split(/[^a-z0-9_.]+/)
37
- .filter((t) => t.length > 0);
34
+ const lower = text.toLowerCase();
35
+ const out: string[] = [];
36
+ let start = -1;
37
+ for (let i = 0; i <= lower.length; i++) {
38
+ const word = i < lower.length && isWordChar(lower.charCodeAt(i));
39
+ if (word && start < 0) start = i;
40
+ else if (!word && start >= 0) {
41
+ out.push(lower.slice(start, i));
42
+ start = -1;
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // One figure grammar, stated once.
50
+ //
51
+ // A figure is a word run that carries a digit — `30`, `3.12`, `9ae0998`,
52
+ // `1,024` — where `.` and `,` belong to the run only while the run keeps
53
+ // reading as a number: a separator joins when a digit sits on each side
54
+ // (`1,024`, `1.4.3`), and a `.` that merely ends a sentence is prose, not the
55
+ // tail of the figure (`1.5.` states `1.5`). `tokens()` alone is not this: it
56
+ // splits `1,024` at the comma and glues the sentence dot of `1.5.` onto the
57
+ // figure, and a matcher that reads those two edges differently in two places
58
+ // will refuse a truncation of `1` as a restatement of `1,024` while keeping a
59
+ // verbatim restatement of `1.5`. Every decision about where a figure begins or
60
+ // ends — the availability matcher's claim splitter, its hit-coverage veto and
61
+ // the figure-subset check below — reads `figureExtent`, so the edges cannot
62
+ // drift apart.
63
+ // ---------------------------------------------------------------------------
64
+
65
+ const CODE_COMMA = 44;
66
+ const CODE_DOT = 46;
67
+ const CODE_ZERO = 48;
68
+ const CODE_NINE = 57;
69
+ const CODE_UPPER_A = 65;
70
+ const CODE_UPPER_Z = 90;
71
+ const CODE_LOWER_A = 97;
72
+ const CODE_LOWER_Z = 122;
73
+ const CODE_UNDERSCORE = 95;
74
+
75
+ function isDigit(code: number): boolean {
76
+ return code >= CODE_ZERO && code <= CODE_NINE;
77
+ }
78
+
79
+ /** A character `tokens()` keeps inside a token: a digit, a letter, `_` or `.`.
80
+ * This char class IS the split rule — `tokens()` splits wherever it is false. */
81
+ export function isWordChar(code: number): boolean {
82
+ return (
83
+ isDigit(code) ||
84
+ (code >= CODE_LOWER_A && code <= CODE_LOWER_Z) ||
85
+ (code >= CODE_UPPER_A && code <= CODE_UPPER_Z) ||
86
+ code === CODE_UNDERSCORE ||
87
+ code === CODE_DOT
88
+ );
89
+ }
90
+
91
+ /** Does the `,` at `i` join two digits, making `1,024` one figure? */
92
+ function joinsDigits(text: string, i: number): boolean {
93
+ return (
94
+ text.charCodeAt(i) === CODE_COMMA &&
95
+ i > 0 &&
96
+ i + 1 < text.length &&
97
+ isDigit(text.charCodeAt(i - 1)) &&
98
+ isDigit(text.charCodeAt(i + 1))
99
+ );
100
+ }
101
+
102
+ function isRunChar(text: string, i: number): boolean {
103
+ return isWordChar(text.charCodeAt(i)) || joinsDigits(text, i);
104
+ }
105
+
106
+ /**
107
+ * The extent of the figure at `pos`, or null when `pos` is not part of one.
108
+ * A figure is the maximal run of word characters around `pos` — joined across
109
+ * a `,` between digits — that carries a digit, with the dots of a sentence
110
+ * ending trimmed: `1,024`, `1.4.3` and `9ae0998` are figures; the `.` that
111
+ * closes `The ratio is 1.5.` is not part of one, so the extent of the run at
112
+ * that dot is `1.5`, not `1.5.`.
113
+ */
114
+ export function figureExtent(
115
+ text: string,
116
+ pos: number,
117
+ ): { start: number; end: number } | null {
118
+ if (pos < 0 || pos >= text.length || !isRunChar(text, pos)) return null;
119
+ let start = pos;
120
+ while (start > 0 && isRunChar(text, start - 1)) start--;
121
+ let end = pos + 1;
122
+ while (end < text.length && isRunChar(text, end)) end++;
123
+ while (end > start && text.charCodeAt(end - 1) === CODE_DOT) end--;
124
+ if (end === start) return null;
125
+ for (let i = start; i < end; i++)
126
+ if (isDigit(text.charCodeAt(i))) return { start, end };
127
+ return null;
38
128
  }
39
129
 
40
130
  // Case-preserving tokens, for reporting asserted values back to the user.
@@ -70,11 +160,27 @@ export function jaccard(a: string[], b: string[]): number {
70
160
  // number or its sign are not the same words.
71
161
  // ---------------------------------------------------------------------------
72
162
 
73
- /** Every token carrying a digit, deduped and sorted: the quantities, versions,
74
- * ids and durations a statement asserts ("30", "3.19", "9ae0998"). A change
75
- * here is a different fact, not a rephrasing. */
163
+ /** Every figure a statement asserts, deduped, sorted and canonical: the
164
+ * quantities, versions, ids and durations carried by `figureExtent` runs,
165
+ * with grouping commas removed so `1,024` reads as `1024` and a sentence dot
166
+ * excluded so `1.5.` reads as `1.5`. Two texts state the same figure exactly
167
+ * when their canonical values match; a figure cannot be assembled out of
168
+ * separate integers because only a run the text itself states is read. A
169
+ * change here is a different fact, not a rephrasing. */
76
170
  export function numericTokens(text: string): string[] {
77
- return [...new Set(tokens(text).filter((t) => /\d/.test(t)))].sort();
171
+ const lower = text.toLowerCase();
172
+ const out = new Set<string>();
173
+ for (let i = 0; i < lower.length; ) {
174
+ // A digit anchors the whole run, including any identifier prefix.
175
+ const ext = isDigit(lower.charCodeAt(i)) ? figureExtent(lower, i) : null;
176
+ if (ext === null) {
177
+ i++;
178
+ continue;
179
+ }
180
+ out.add(lower.slice(ext.start, ext.end).replace(/,/g, ""));
181
+ i = Math.max(ext.end, i + 1);
182
+ }
183
+ return [...out].sort();
78
184
  }
79
185
 
80
186
  export const POL_POS = "pos";