opencode-self-improvement 0.22.2 → 0.23.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.22.2",
3
+ "version": "0.23.0",
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": {
@@ -128,6 +128,19 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
128
128
  : undefined;
129
129
  })()
130
130
  : undefined;
131
+ // Lesson citation (S1, learn-from-failure): shape-checked here, verified
132
+ // against the tool ledger by the runtime. Only a `blocker` may carry one.
133
+ // A newline would break the logfmt row, so flattenMemoryText must be a
134
+ // fixed point — the same discipline as `original` above.
135
+ const failure =
136
+ type === "blocker" && typeof o.failure === "string"
137
+ ? (() => {
138
+ const s = o.failure.trim();
139
+ return s && s.length <= 200 && flattenMemoryText(s) === s
140
+ ? s
141
+ : undefined;
142
+ })()
143
+ : undefined;
131
144
  out.push({
132
145
  ...(status
133
146
  ? { type, scope, content, status }
@@ -135,6 +148,7 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
135
148
  ...(kw ? { kw } : {}),
136
149
  ...(guided ? { guided: true, ...conflict } : {}),
137
150
  ...(original ? { original } : {}),
151
+ ...(failure ? { failure } : {}),
138
152
  });
139
153
  }
140
154
  return out;
@@ -0,0 +1,128 @@
1
+ // #393 AC 2: check an inferred claim against the working tree BEFORE storing it.
2
+ //
3
+ // The scope is deliberately narrow, and the measurement is why it is narrow.
4
+ // R4's poison rows claimed a fallback VAT rate for a fixture whose config leaves
5
+ // that rate UNSET: `findConstant(base4, "fallbackVatBps")` returns null. The tree
6
+ // does not contradict the poison — it is silent, and silence is exactly where a
7
+ // confident wrong row fits.
8
+ //
9
+ // - refusing when the tree CONTRADICTS a claim refuses nothing in R4;
10
+ // - refusing when the tree is SILENT also refuses the transport fact
11
+ // (empty store 0/5, seeded 5/5), which is the one measured benefit memory has.
12
+ //
13
+ // So this module answers three ways and only one of them refuses. "Undecidable"
14
+ // keeps the row — that is the transport case — and the row then rides injection
15
+ // labelled `[unverified]` (see store/model/provenance.ts), which is the part of
16
+ // #393 the evidence actually supports.
17
+
18
+ import { findConstant, valuesAgree } from "../recall/conflicts.ts";
19
+
20
+ export type ClaimVerdict = "agrees" | "contradicts" | "undecidable";
21
+
22
+ export interface ClaimHit {
23
+ verdict: ClaimVerdict;
24
+ /** The symbol the check resolved in the tree, when one resolved. */
25
+ ref?: string;
26
+ /** The number compared, when one was compared. */
27
+ claim?: string;
28
+ }
29
+
30
+ // A constant the row names, in the two shapes source uses: SCREAMING_CASE and a
31
+ // dotted camelCase member. Deliberately narrow — prose that merely mentions
32
+ // "rate" must not be resolved against a symbol.
33
+ //
34
+ // Built per call, NOT shared at module scope. A `g` regex carries `lastIndex`
35
+ // between calls, so a shared one starts the next row's scan wherever the last
36
+ // one stopped and silently returns "undecidable" for a claim it would have
37
+ // caught. That is a check whose result depends on the order of previous rows —
38
+ // the worst shape a gate can have, because it looks deterministic.
39
+ function symbols(): RegExp {
40
+ return /\b([A-Z][A-Z0-9_]{2,}|[A-Za-z_$][A-Za-z0-9_$]*\.[a-z][A-Za-z0-9_$]*)\b/g;
41
+ }
42
+ // How far after the symbol a number may sit and still count as THAT symbol's
43
+ // value. "VAT_BPS is 2150" yes; "VAT_BPS was added in 2024, the rate is 2150"
44
+ // compares 2024 and refuses on a coincidence, which is worse than not checking.
45
+ const WINDOW = 48;
46
+
47
+ /**
48
+ * Check an inferred row's numeric claim against the working tree by reading the
49
+ * claim OUT of its own prose.
50
+ *
51
+ * Capture's structured `ref`/`claim` fields ride user-guided rows only (see
52
+ * `capture/candidates.ts`), and the guided rows are exactly the ones this check
53
+ * must not touch — a user correcting a stale tree is the case where the tree is
54
+ * wrong. So an inferred row is checked on what it says, not on what it declared.
55
+ *
56
+ * Agrees when one resolvable symbol's value matches a nearby number; contradicts
57
+ * only when a resolvable symbol's value disagrees with EVERY number the row
58
+ * states near it; undecidable otherwise, which is the transport case and keeps
59
+ * the row.
60
+ */
61
+ export function claimVerdictFromContent(
62
+ repoDir: string | undefined,
63
+ content: string,
64
+ ): ClaimHit {
65
+ if (!repoDir || !content) return { verdict: "undecidable" };
66
+ const cache = new Map<string, string | undefined>();
67
+ let sawResolvable = false;
68
+ const SYMBOL = symbols();
69
+ let match: RegExpExecArray | null = SYMBOL.exec(content);
70
+ while (match) {
71
+ const ref = match[1] ?? "";
72
+ // Step past the whole match, not just the captured name: the `` lookahead
73
+ // means a name-length advance would re-find the same symbol forever.
74
+ SYMBOL.lastIndex = match.index + match[0].length;
75
+ if (!cache.has(ref)) {
76
+ const fact = findConstant(repoDir, ref);
77
+ cache.set(ref, fact ? String(fact.value) : undefined);
78
+ }
79
+ const code = cache.get(ref);
80
+ if (code !== undefined) {
81
+ sawResolvable = true;
82
+ const tail = content.slice(
83
+ match.index + ref.length,
84
+ match.index + ref.length + WINDOW,
85
+ );
86
+ // Compare against every number near the symbol: a row may state the value
87
+ // in two units and any one of them agreeing is enough to keep it.
88
+ // The sign is part of the number (review #399): "-2150" extracted as
89
+ // "2150" agreed with a tree declaring 2150 and shipped the row labelled
90
+ // [code-checked] — an opposite-signed value positively vouched for by a
91
+ // check. `valuesAgree` parses leading [+-] itself, so the extractor must
92
+ // not drop it. A hyphen separated by spaces stays a separator, not a
93
+ // sign: "2150 - 300 discount" still compares 2150.
94
+ const near = tail.match(/[-+]?\d+(?:\.\d+)?/g) ?? [];
95
+ let agreed = false;
96
+ for (const n of near) {
97
+ if (valuesAgree(n, code) === true) {
98
+ agreed = true;
99
+ return { verdict: "agrees", ref, claim: n };
100
+ }
101
+ }
102
+ if (!agreed && near.length) {
103
+ return { verdict: "contradicts", ref, claim: near[0] };
104
+ }
105
+ }
106
+ match = SYMBOL.exec(content);
107
+ }
108
+ void sawResolvable;
109
+ return { verdict: "undecidable" };
110
+ }
111
+
112
+ /**
113
+ * The declared-ref form, kept for callers that already carry a ref (the guided
114
+ * contradiction surface). Any uncertainty is `undecidable`, never `contradicts`.
115
+ */
116
+ export function claimVerdict(
117
+ repoDir: string | undefined,
118
+ ref: string,
119
+ claim: string,
120
+ ): ClaimVerdict {
121
+ if (!repoDir || !ref || !claim) return "undecidable";
122
+ const fact = findConstant(repoDir, ref);
123
+ if (!fact) return "undecidable";
124
+ const agree = valuesAgree(claim, String(fact.value));
125
+ if (agree === true) return "agrees";
126
+ if (agree === false) return "contradicts";
127
+ return "undecidable";
128
+ }
@@ -252,3 +252,55 @@ export function captureSignalSince(
252
252
  // signal-bearing turn still mines this one too.
253
253
  return { ok: false, why: "no-signal" };
254
254
  }
255
+
256
+ /**
257
+ * Gate commands that ran in this window, FAILED, and were never followed by a
258
+ * PASS of the same family. This is the only thing a failure lesson may be about.
259
+ *
260
+ * The point is that a lesson must rest on the repo's own verdict, not on the
261
+ * model's impression of what went wrong. ReMe (Findings ACL 2026) found
262
+ * selective addition BEATS full addition, because one failed trajectory rarely
263
+ * carries enough context for a correct analysis and yields misguided
264
+ * experiences. So this store's failure mode is writing a wrong lesson, not
265
+ * missing a right one. An unattested lesson is a rumour, and the runtime drops
266
+ * the row.
267
+ *
268
+ * A recovered failure is excluded on purpose: FAIL then PASS means the agent
269
+ * fixed it, and "do not do what I just did" is only a lesson while the thing is
270
+ * still broken. `captureSignalSince` reads the same ledger for the opposite
271
+ * purpose — a recovery is the best REASON to capture, an unrecovered failure is
272
+ * the best thing to capture.
273
+ *
274
+ * One family's recovery does not attest away another family's failure: a
275
+ * session that got its tests green and its lint red still has an open lint
276
+ * failure.
277
+ *
278
+ * First-failure order, deduped by family, bounded — the block is prompt bytes on
279
+ * every capture, and a session with more than a handful of failing gates is not
280
+ * choosing between eight of them.
281
+ */
282
+ export function attestedGateFailures(
283
+ s: SessionState,
284
+ sinceTurn: number,
285
+ ): { cmd: string; arg?: string }[] {
286
+ // Same reasoning as captureSignalSince: with no turn tracking the window is
287
+ // meaningless rather than empty, and a policy that quietly stops reporting
288
+ // failures is the failure mode this file exists to avoid.
289
+ const tracked = s.turns > 0;
290
+ const out: { cmd: string; arg?: string }[] = [];
291
+ // Ledger order, not timestamps: `calls` is append-only, which is what
292
+ // captureSignalSince relies on for the same FAIL-then-PASS question, and it
293
+ // cannot be undone by two calls sharing a millisecond.
294
+ s.calls.forEach((c, i) => {
295
+ if (!c.gateCheck || c.status !== "FAIL" || !c.cmd) return;
296
+ if (tracked && (c.turn ?? 0) <= sinceTurn) return;
297
+ if (out.some((f) => f.cmd === c.cmd)) return;
298
+ if (out.length >= 8) return;
299
+ const recovered = s.calls
300
+ .slice(i + 1)
301
+ .some((l) => l.gateCheck && l.cmd === c.cmd && l.status === "PASS");
302
+ if (recovered) return;
303
+ out.push({ cmd: c.cmd, ...(c.arg ? { arg: c.arg } : {}) });
304
+ });
305
+ return out;
306
+ }
@@ -29,6 +29,17 @@ export interface CaptureCandidate {
29
29
  * so a stored original is the user's own words.
30
30
  */
31
31
  original?: string;
32
+ /**
33
+ * Lesson citation (S1, learn-from-failure): the failing command this
34
+ * `blocker` row is about. Present only on a lesson, and only ever copied from
35
+ * the ATTESTED FAILURES block the prompt was given — the runtime re-checks it
36
+ * against the tool ledger and drops the ROW when it does not appear there.
37
+ * Unlike a guided `original`, a failed check cannot keep the row and drop the
38
+ * field: an uncited lesson is not a lesson with a missing annotation, it is a
39
+ * guess about what is broken. Not stored — it is a write-time gate, so no row
40
+ * format changes.
41
+ */
42
+ failure?: string;
32
43
  }
33
44
 
34
45
  // Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
@@ -52,6 +63,7 @@ export function buildCapturePrompt(
52
63
  max = 3,
53
64
  userProse = "",
54
65
  known = "",
66
+ attested?: string[],
55
67
  ): string {
56
68
  const prose = redactSecrets(userProse).trim();
57
69
  const knownList = redactSecrets(known).trim();
@@ -94,6 +106,33 @@ export function buildCapturePrompt(
94
106
  '- The REQUESTS block is what the user asked for in THIS session. Most of it scopes the current job and expires with it. Mine a `preference` from it ONLY when it names a tool, package, format or convention that outlives the task ("we use bun here", "no semicolons"); never from wording that scopes this job ("only touch src/", "do not create tests").',
95
107
  ]
96
108
  : []),
109
+ // S1 (learn-from-failure). Measured on the bench: a session that failed
110
+ // after 574 s and 33,287 tokens wrote ONE row, and it was a paraphrase of
111
+ // the task brief. The prompt asked for "blockers hit" in a list of seven
112
+ // words and never mentioned failure, so there was nothing to answer. What
113
+ // makes this safe rather than noisy is that the failure list is not the
114
+ // model's recollection — it is read from the tool ledger, and a lesson
115
+ // whose citation is not in it is dropped before the write gate.
116
+ ...(attested
117
+ ? attested.length
118
+ ? [
119
+ "ATTESTED FAILURES (commands that ran in this session and FAILED, with no later pass. This is measured from the tool ledger, not your impression — it is the ONLY evidence of failure you have, and the only thing a lesson may be about):",
120
+ ...attested.map((f) => ` - ${f}`),
121
+ "",
122
+ '- The most valuable thing a session that did not finish can teach a future one is what does not work. For each failure above worth a lesson, emit one row with type "blocker" whose content is a rule in the form: when <condition>, avoid <action>. Name a file or symbol, so the rule can be checked against the code later.',
123
+ '- Every such row MUST carry "failure": the failing command, copied ONLY from the list above and EXACTLY as written there. A citation taken from anywhere else, or no citation at all, means the row is refused and dropped — never invent a failure, never cite one that later passed.',
124
+ "- Say what was attempted and what the evidence showed. Do not state a cause you did not prove, and do not store the fix you did not verify: an unverified fix riding a later session is worse than no memory at all.",
125
+ "- Emit no `blocker` for anything that did not fail here — not a style opinion, not a step that merely took a while, not the task brief.",
126
+ "",
127
+ ]
128
+ : [
129
+ // Explicit, because silence here reads as "no lesson-worthy failure
130
+ // occurred", which is a different claim: this session ran no gate at
131
+ // all, or every gate it ran passed.
132
+ "No command failed in this session: emit no `blocker` lesson row.",
133
+ "",
134
+ ]
135
+ : []),
97
136
  // Permission to emit fewer rows is what bounds deliberation. On the
98
137
  // reproducing fixture the same seat went 1,095 -> 3,084 completion tokens
99
138
  // and 19.7s -> 63.2s with this line removed, and the same rows out. It
@@ -3,7 +3,11 @@
3
3
  import type { Cleanup } from "@opencode/plugin/promise/plugin";
4
4
  import { cmpTs } from "../core/cmp-ts.ts";
5
5
  import { session, setCurrent } from "../core/state.ts";
6
- import { AUTO_CAPTURE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
6
+ import {
7
+ AUTO_CAPTURE_TAG,
8
+ CODE_CHECKED_TAG,
9
+ USER_GUIDED_TAG,
10
+ } from "../core/tags.ts";
7
11
  import { record, recordCaptureLag } from "../evidence/record.ts";
8
12
  import { type GateContext, runWriteGate } from "../gate/gate.ts";
9
13
  import { captureSessionID } from "../identity/host-events.ts";
@@ -19,6 +23,7 @@ import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
19
23
  import { flattenMemoryText } from "../store/sanitize.ts";
20
24
  import { redactSecrets } from "../store/secrets.ts";
21
25
  import { parseCandidates, parseModelRef } from "./candidates.ts";
26
+ import { claimVerdictFromContent } from "./checked.ts";
22
27
  import {
23
28
  findGuidedQuotes,
24
29
  mergeGuidedCandidates,
@@ -28,6 +33,7 @@ import {
28
33
  import { lagSince } from "./lag.ts";
29
34
  import {
30
35
  advanceCaptureCursor,
36
+ attestedGateFailures,
31
37
  captureCursor,
32
38
  captureSignalSince,
33
39
  deltaMessages,
@@ -481,6 +487,40 @@ export function configureAutoCapture(
481
487
  // into a teardown (#211).
482
488
  const knownRows = await knownRowsFor(captureReader);
483
489
  if (controller.signal.aborted) return;
490
+ // S1: the ledger's unrecovered gate failures, in the same window the
491
+ // signal policy just approved. Rendered into the prompt so the model
492
+ // can cite one, and kept here so the citation can be checked against
493
+ // the ledger rather than against the model's retelling. `undefined`,
494
+ // not `[]`, means "this caller does not know about lessons" and leaves
495
+ // the prompt byte-identical to before; an empty array is a statement
496
+ // that nothing failed, and the prompt says so.
497
+ const attested = attestedGateFailures(session(sid), cursor.turn).map(
498
+ (f) =>
499
+ // Review #384 finding 1: ledger args are raw tool input. A failing
500
+ // `bun test --token=sk-...` put the credential verbatim into the
501
+ // ATTESTED FAILURES block — the transcript scrub does not cover
502
+ // this input. Redact at construction, so the prompt renders the
503
+ // safe string AND the citation check compares against the same
504
+ // representation the model was shown.
505
+ redactSecrets(f.arg ? `${f.cmd} — ${f.arg}` : f.cmd),
506
+ );
507
+ // Review #384 finding 2: `lessonHay.includes(cite)` accepted a lesson
508
+ // citing `tsc` when the only failure was `bun test
509
+ // --test-name-pattern tsc` — substring presence cannot establish that
510
+ // the cited command ran. The list renders `cmd — arg`; a faithful
511
+ // citation copies a COMPLETE displayed field, so membership is tested
512
+ // against each whole entry, its cmd, and its arg — never a fragment.
513
+ // `tsc` is none of those for that failure and is refused; the cmd-only
514
+ // citation the prompt's own example uses still passes.
515
+ const lessonSet = new Set<string>();
516
+ for (const f of attested) {
517
+ lessonSet.add(normWs(f).toLowerCase());
518
+ const sep = f.lastIndexOf(" — ");
519
+ if (sep > 0) {
520
+ lessonSet.add(normWs(f.slice(0, sep)).toLowerCase());
521
+ lessonSet.add(normWs(f.slice(sep + 3)).toLowerCase());
522
+ }
523
+ }
484
524
  const out = await generateApi.text({
485
525
  model,
486
526
  // Redact the COMPLETE transcript, THEN apply the character budget
@@ -493,6 +533,7 @@ export function configureAutoCapture(
493
533
  captureMax,
494
534
  redactSecrets(userProse).slice(-1500),
495
535
  knownRows,
536
+ attested,
496
537
  ),
497
538
  });
498
539
  const text = typeof out === "string" ? out : (out?.text ?? "");
@@ -586,10 +627,83 @@ export function configureAutoCapture(
586
627
  c.original = undefined;
587
628
  }
588
629
  }
630
+ // S1 (learn-from-failure): a row that CITES a failing command is
631
+ // claiming to be a lesson, and the claim is checked against the ledger,
632
+ // not against the model's retelling. ReMe (Findings ACL 2026) found
633
+ // selective addition beats full addition because one failed trajectory
634
+ // rarely carries enough context for a correct analysis — so the way
635
+ // this feature fails is by storing a wrong rule, and a rule about a
636
+ // failure that never happened (or that the agent already fixed) is the
637
+ // worst version of it: it rides every later session as an instruction.
638
+ //
639
+ // The gate is monotone. Only a row carrying `failure` makes the claim,
640
+ // so an ordinary `blocker` note — a type this capture path has always
641
+ // written — is untouched. Refusing every uncited blocker would delete
642
+ // rows the store has always kept, and a provenance fix does not buy a
643
+ // recall loss here.
644
+ let lessonsKept = 0;
645
+ let lessonsRefused = 0;
646
+ candidates = candidates.filter((c) => {
647
+ if (c.failure === undefined) return true;
648
+ const cite = normWs(c.failure).toLowerCase();
649
+ if (cite && lessonSet.has(cite)) {
650
+ lessonsKept++;
651
+ return true;
652
+ }
653
+ lessonsRefused++;
654
+ return false;
655
+ });
656
+ if (lessonsKept || lessonsRefused)
657
+ await record(
658
+ "auto_capture_lessons",
659
+ {
660
+ session: sid,
661
+ trigger,
662
+ kept: lessonsKept,
663
+ refused: lessonsRefused,
664
+ attested: attested.length,
665
+ ...(modelTag ? { model: modelTag } : {}),
666
+ },
667
+ false,
668
+ sid,
669
+ captureGate.evidenceContext,
670
+ );
589
671
  for (const c of candidates) {
590
672
  // Between candidates, never inside a gate run: a supersession that
591
673
  // half-applied is a store the next session cannot trust.
592
674
  if (controller.signal.aborted) return;
675
+ // #393 AC 2: a numeric claim capture INFERRED (the user did not state
676
+ // it) that names a constant the tree also names is checked before it
677
+ // is stored. Only a contradiction refuses; "undecidable" is the
678
+ // transport case and keeps the row, labelled.
679
+ const claim = c.guided
680
+ ? { verdict: "undecidable" as const }
681
+ : claimVerdictFromContent(
682
+ captureReader.kind === "repo"
683
+ ? captureReader.scope.path
684
+ : undefined,
685
+ c.content,
686
+ );
687
+ const verdict = claim.verdict;
688
+ if (verdict === "contradicts") {
689
+ await record(
690
+ "auto_capture_contradiction",
691
+ {
692
+ session: sid,
693
+ trigger,
694
+ type: c.type,
695
+ scope: redactSecrets(c.scope),
696
+ reason: "claim_contradicts_tree",
697
+ where: claim.ref ?? "",
698
+ matched: claim.claim ?? "",
699
+ ...(modelTag ? { model: modelTag } : {}),
700
+ },
701
+ false,
702
+ sid,
703
+ captureGate.evidenceContext,
704
+ );
705
+ continue;
706
+ }
593
707
  const original = c.original;
594
708
  const durable: string[] = [];
595
709
  let outcome: Awaited<ReturnType<typeof runWriteGate>>;
@@ -610,6 +724,11 @@ export function configureAutoCapture(
610
724
  ...(original ? { original } : {}),
611
725
  tags: [
612
726
  AUTO_CAPTURE_TAG,
727
+ // #393: the ONE case that earns `[code-checked]` — an inferred
728
+ // numeric claim that agreed with the tree. Absent everywhere
729
+ // else, which is what makes `[unverified]` mean something
730
+ // instead of decorate everything.
731
+ ...(verdict === "agrees" ? [CODE_CHECKED_TAG] : []),
613
732
  ...(trigger === "compaction" ? [CAPTURE_COMPACT_TAG] : []),
614
733
  ...(c.guided ? [USER_GUIDED_TAG] : []),
615
734
  ],
@@ -93,9 +93,23 @@ export function hasEngagement(sid: string): boolean {
93
93
  return session(sid).sawEngagement;
94
94
  }
95
95
 
96
+ // A gate is a command whose exit status is the repo's own verdict on the work:
97
+ // a test run, a typecheck, a lint, a build. `gateRecovered` (FAIL then PASS of
98
+ // the same family) is the strongest capture signal there is, and attested
99
+ // failure lessons are keyed on it.
100
+ //
101
+ // `test` was missing from this table, so `bun test`, `npm test` and `pytest`
102
+ // registered as no gate at all: a session could go red-green-red and the ledger
103
+ // would never see it. The matcher is anchored on the RUNNER rather than on the
104
+ // word, because the word appears everywhere in a repo that has a test directory
105
+ // — `ls src/test` and `cat test/fixtures/a.json` are not test runs.
96
106
  const GATE_CMDS: [RegExp, string][] = [
97
107
  [/vitest/, "vitest"],
98
108
  [/playwright/, "playwright"],
109
+ [/(?:^|[\s;&|(])(?:bun|npm|pnpm|yarn|deno|npx)\s+(?:run\s+)?test\b/, "test"],
110
+ [/(?:^|[\s;&|(])(?:pytest|py\.test)\b/, "test"],
111
+ [/(?:^|[\s;&|(])go\s+test\b/, "test"],
112
+ [/(?:^|[\s;&|(])make\s+test\b/, "test"],
99
113
  [/lint/, "lint"],
100
114
  [/build:source|tsc\b/, "tsc"],
101
115
  ];
package/src/core/tags.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  /** Auto-capture provenance, shared by capture and retrieval. */
2
2
  export const AUTO_CAPTURE_TAG = "auto-capture";
3
3
 
4
+ /**
5
+ * #393: a capture candidate whose numeric claim was CHECKED against the working
6
+ * tree and agreed. Absent on every other row, which is what makes the injected
7
+ * `[unverified]` marker mean something rather than decorate everything.
8
+ */
9
+ export const CODE_CHECKED_TAG = "code-checked";
10
+
4
11
  // The public write boundaries reserve this same tag (#342/#355).
5
12
  export { USER_GUIDED_TAG } from "./guidance.ts";
package/src/gate/gate.ts CHANGED
@@ -10,6 +10,7 @@ import { canonicalFile, memoryRoot } from "../core/config/paths.ts";
10
10
  import { bracketList, parseLine } from "../core/logfmt/format.ts";
11
11
  import { readLines } from "../core/logfmt/read.ts";
12
12
  import { appendMemory } from "../store/files/append.ts";
13
+ import { valueConflicts } from "./value-conflict.ts";
13
14
  import { loadScope } from "../store/files/load.ts";
14
15
  import { snapshotFiles } from "../store/files/snapshots.ts";
15
16
  import {
@@ -905,6 +906,19 @@ export async function runWriteGate(
905
906
  return { action: "collapsed", chain, collapsedWith: collapseMatch.ts };
906
907
  }
907
908
 
909
+ // #390 plan: live rows the incoming row CORRECTS, computed before the append
910
+ // because the retirement pointer must name the ts the append creates — and
911
+ // the marking must wait until the append actually lands, or a blocked write
912
+ // would delete the old value with no successor behind it. An open planning
913
+ // row and a quarantined row never retire settled facts.
914
+ const conflictPlan =
915
+ (candidate.status ?? "settled") === "settled" && !isQuarantined(candidate)
916
+ ? valueConflicts(
917
+ candidate,
918
+ active.filter((m) => m.ts !== ctx.supersedesTs),
919
+ )
920
+ : [];
921
+
908
922
  // The write is specifically promoted on engagement (no refs, no gate check,
909
923
  // not canonical, not an open object). Emitted so the precedent is auditable.
910
924
  const groundedByEngagement =
@@ -950,6 +964,41 @@ export async function runWriteGate(
950
964
  // outcome carries the error instead.
951
965
  let evidenceError: string | undefined;
952
966
  try {
967
+ // #390 apply: the append landed, so the retired rows now have a named
968
+ // successor. Ledger first (markManySupersededReport appends to ctx.durable
969
+ // after each publish), evidence only for rows THIS call actually retired
970
+ // (#208's attribution rule) — a row retired out-of-band belongs to the
971
+ // other session's chain.
972
+ if (conflictPlan.length > 0) {
973
+ const { marked } = await markManySupersededReport(
974
+ conflictPlan.map((c) => ({
975
+ ts: c.ts,
976
+ fields: {
977
+ superseded_by: ts,
978
+ reason: "numeric_conflict",
979
+ symbol: c.symbol,
980
+ from: c.from,
981
+ to: c.to,
982
+ },
983
+ })),
984
+ ctx.durable,
985
+ );
986
+ const retired = new Set(marked);
987
+ for (const c of conflictPlan) {
988
+ if (!retired.has(c.ts)) continue;
989
+ if (!supersededTs) supersededTs = c.ts;
990
+ await rec("superseded_by", {
991
+ gate: 2,
992
+ mem: c.ts,
993
+ target: ts,
994
+ reason: "numeric_conflict",
995
+ symbol: c.symbol,
996
+ from: c.from,
997
+ to: c.to,
998
+ chain,
999
+ });
1000
+ }
1001
+ }
953
1002
  await rec("write_promoted", {
954
1003
  gate: 4,
955
1004
  op: "write",
@@ -0,0 +1,300 @@
1
+ // Row-vs-row numeric conflict (#390): a correction must retire the row it
2
+ // corrects IN THE DATA, not only in its wording.
3
+ //
4
+ // R3 (`results-stale-x5/`, values 2150 → 1900) showed the store keeping BOTH
5
+ // values, the correction winning only because a language model happened to
6
+ // write "this supersedes the earlier 2150 bps figure" and retrieval happened
7
+ // to prefer it. R3c narrowed the real exposure: with a 30-day gap the newer
8
+ // row wins 10/10 either order; the failure is the same-instant tie (3/10) and
9
+ // any retrieval that surfaces the stale row alone. GATE-3 rivalry never fires
10
+ // here because it only competes `decision`/`preference` rows, and corrections
11
+ // of remembered facts are `context`/`learning`.
12
+ //
13
+ // This retires the older row at write time with an explicit `superseded_by`
14
+ // pointer, so injection cannot carry the stale value alone — superseded rows
15
+ // fail `isInjectable`. It changes no outcome that timestamp resolution had
16
+ // already settled (R3c: newer wins 10/10); it makes the win structural.
17
+ //
18
+ // The guard is threefold, because a retirement destroys nothing but hides the
19
+ // row from every future session:
20
+ // 1. anchor — both rows must name the SAME symbol token (SCREAMING_CASE or
21
+ // a dotted member). "max_retries is 3" and "timeout is 30" in one scope
22
+ // share no anchor and coexist.
23
+ // 2. value — the numbers attached to that anchor must actually disagree
24
+ // (`valuesAgree === false`); "21.5%" and "2150" are one fact restated.
25
+ // 3. sentence — with the numbers stripped, the two rows must say the SAME
26
+ // thing (#400 review round 2, WhollyMindless). Every non-numeric word
27
+ // outside a closed ignore list (prose glue, copulas) must appear in BOTH
28
+ // rows or in a closed EDITORIAL set — words that narrate the act of
29
+ // correcting ("corrected", "actually", "supersedes") and nothing about
30
+ // the fact. One unmatched content word and the rows coexist.
31
+ // This replaces the old jaccard floor (0.71 let "3 in production" retire
32
+ // "5 in staging") AND the environment dictionary (empty qualifier sets
33
+ // let "3 for tenant Alpha" retire "5 for tenant Beta" — a dictionary can
34
+ // never establish same-context, because the qualifier vocabulary is
35
+ // open: tenants, regions, editions, customers). Same-context is now
36
+ // ESTABLISHED, not looked up: a difference the words cannot explain is
37
+ // a difference in the fact. Retirement requires the correction to be
38
+ // the only thing that changed; anything coexisting is the pre-#390
39
+ // state — both rows inject, retrieval prefers the newer — never a
40
+ // hidden fact.
41
+ import { USER_GUIDED_TAG } from "../core/tags.ts";
42
+ import { STOPWORDS, tokens } from "../core/tokenize.ts";
43
+ import type { Memory } from "../store/model/memory.ts";
44
+ import { valuesAgree } from "../recall/conflicts.ts";
45
+
46
+ export interface ValueConflict {
47
+ /** The live row to retire. */
48
+ ts: string;
49
+ symbol: string;
50
+ /** The number the retiring row asserted. */
51
+ from: string;
52
+ /** The number the incoming row asserts. */
53
+ to: string;
54
+ }
55
+
56
+ // How far after a symbol a number may sit and still be that symbol's value.
57
+ // Same window as the capture claim check (#393) on purpose: one rule for
58
+ // "this number belongs to this name".
59
+ const WINDOW = 48;
60
+
61
+ // Words carrying no qualifying information: prose glue (the shared GATE-3
62
+ // stopword set) plus copulas/auxiliaries, so "was 3" -> "is now 5" stays one
63
+ // correction. "should" stays OUT: desired-vs-actual is a real distinction.
64
+ const IGNORE: ReadonlySet<string> = new Set([
65
+ ...STOPWORDS,
66
+ "was",
67
+ "were",
68
+ "be",
69
+ "been",
70
+ "being",
71
+ "am",
72
+ "do",
73
+ "does",
74
+ "did",
75
+ "has",
76
+ "have",
77
+ "had",
78
+ ]);
79
+
80
+ // Words that narrate the ACT of correcting without qualifying the fact.
81
+ // Closed and small on purpose: every word here says "this replaced something"
82
+ // and nothing about WHICH fact. A qualifier can never hide in this set
83
+ // because the set names no dimension of the world.
84
+ const EDITORIAL: ReadonlySet<string> = new Set([
85
+ "corrected",
86
+ "correction",
87
+ "actually",
88
+ "now",
89
+ "updated",
90
+ "update",
91
+ "previously",
92
+ "earlier",
93
+ "supersedes",
94
+ "superseded",
95
+ "fixed",
96
+ "typo",
97
+ "wrong",
98
+ "incorrectly",
99
+ "mistake",
100
+ "rather",
101
+ "instead",
102
+ ]);
103
+
104
+ /**
105
+ * The qualifying content of a row with ONE occurrence removed: the number
106
+ * the given symbol asserts, excised by POSITION before tokenizing. Numbers
107
+ * otherwise STAY (#400 review rounds 3 and 4, WhollyMindless): "tenant 101"
108
+ * and "tenant 202" are distinguished only by digits, and a literal skip of
109
+ * the compared value also skipped a qualifier carrying the same literal —
110
+ * "is 3 for tenant 3" lost its tenant when the 3 was skipped globally.
111
+ * Position is the only distinction between "the value being corrected" and
112
+ * "a qualifier that happens to repeat it": the asserted number is the first
113
+ * within WINDOW after the symbol (falling back to before), exactly what
114
+ * symbolValues reads.
115
+ */
116
+ function residualTokens(
117
+ content: string,
118
+ excise: readonly [number, number] | undefined,
119
+ ): { set: Set<string>; list: string[]; full: string[] } {
120
+ const cut = excise
121
+ ? `${content.slice(0, excise[0])} ${content.slice(excise[1])}`
122
+ : content;
123
+ const full: string[] = [];
124
+ const list: string[] = [];
125
+ for (const t of tokens(cut)) {
126
+ const bare = t.replace(/^\.+|\.+$/g, "");
127
+ if (!bare) continue;
128
+ full.push(bare);
129
+ if (!IGNORE.has(bare)) list.push(bare);
130
+ }
131
+ return { set: new Set(list), list, full };
132
+ }
133
+
134
+ /**
135
+ * Guard 3: the correction must be the ONLY thing that changed. Every word
136
+ * one row says and the other does not must be editorial narration; a single
137
+ * content word unique to one row ("production", "tenant", "alpha", "v2",
138
+ * "101") means the rows qualify different facts, and nothing retires.
139
+ *
140
+ * A unique NUMBER is additionally excused when it reads as a citation of
141
+ * the other row's value: it equals the other side's asserted value (sign
142
+ * dropped — tokens() strips signs, so a sign flip retires through the value
143
+ * guard, never here) AND its preceding word is not a content word. "was
144
+ * 2150" cites; "tenant 5" qualifies. That keeps R3's correction shape
145
+ * ("...is 1900 basis points, was 2150." retires 2150) while a swapped pair
146
+ * like "is 3 for tenant 5" / "is 5 for tenant 3" — where each extra number
147
+ * is a qualifier, not a citation — coexists.
148
+ */
149
+ function sameSentenceExceptValue(
150
+ a: { set: Set<string>; list: string[]; full: string[] },
151
+ b: { set: Set<string>; list: string[]; full: string[] },
152
+ aAsserted: string,
153
+ bAsserted: string,
154
+ ): boolean {
155
+ const numeric = (t: string) => /^\d+(?:\.\d+)?$/.test(t);
156
+ const cited = (
157
+ side: { set: Set<string>; list: string[]; full: string[] },
158
+ t: string,
159
+ otherAsserted: string,
160
+ ) => {
161
+ if (!numeric(t) || t !== otherAsserted.replace(/^[-+]/, "")) return false;
162
+ // Adjacency is read on the RAW token stream: "was 2150" cites even
163
+ // though "was" is prose glue, and "tenant 5" qualifies — the filter
164
+ // that serves the comparison would erase exactly this distinction.
165
+ const i = side.full.indexOf(t);
166
+ if (i === 0) return true;
167
+ const prev = side.full[i - 1] ?? "";
168
+ return IGNORE.has(prev) || EDITORIAL.has(prev);
169
+ };
170
+ for (const t of a.set)
171
+ if (!b.set.has(t) && !EDITORIAL.has(t) && !cited(a, t, bAsserted))
172
+ return false;
173
+ for (const t of b.set)
174
+ if (!a.set.has(t) && !EDITORIAL.has(t) && !cited(b, t, aAsserted))
175
+ return false;
176
+ return true;
177
+ }
178
+
179
+ /** Escape a symbol for literal use in a RegExp. */
180
+ const reLiteral = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
181
+
182
+ /**
183
+ * Where the symbol asserts its value: the span of the first number within
184
+ * WINDOW after the symbol (falling back to before), mirroring symbolValues
185
+ * exactly — same search, first symbol match that yields a number.
186
+ */
187
+ function assertedValueSpan(
188
+ content: string,
189
+ sym: string,
190
+ ): [number, number] | undefined {
191
+ const SYMBOL = new RegExp(`\\b${reLiteral(sym)}\\b`, "g");
192
+ let match: RegExpExecArray | null = SYMBOL.exec(content);
193
+ while (match) {
194
+ const afterStart = match.index + match[0].length;
195
+ const after = content.slice(afterStart, afterStart + WINDOW);
196
+ const numAfter = after.match(/[-+]?\d+(?:\.\d+)?/);
197
+ if (numAfter) {
198
+ const at = afterStart + (numAfter.index ?? 0);
199
+ return [at, at + numAfter[0].length];
200
+ }
201
+ const beforeStart = Math.max(0, match.index - WINDOW);
202
+ const before = content.slice(beforeStart, match.index);
203
+ const numBefore = before.match(/[-+]?\d+(?:\.\d+)?/);
204
+ if (numBefore) {
205
+ const at = beforeStart + (numBefore.index ?? 0);
206
+ return [at, at + numBefore[0].length];
207
+ }
208
+ match = SYMBOL.exec(content);
209
+ }
210
+ return undefined;
211
+ }
212
+
213
+ /**
214
+ * The value each symbol in a row asserts: the first number within WINDOW
215
+ * after the symbol (falling back to the first before it). Built per call —
216
+ * a module-level `g` regex carries `lastIndex` between calls, which made the
217
+ * #393 check depend on which row was checked last.
218
+ *
219
+ * The sign is part of the value: "-5" and "5" disagree (#399's class — an
220
+ * unsigned extractor grants agreement across a sign flip).
221
+ */
222
+ export function symbolValues(content: string): Map<string, string> {
223
+ const out = new Map<string, string>();
224
+ const SYMBOL =
225
+ /\b([A-Z][A-Z0-9_]{2,}|[A-Za-z_$][A-Za-z0-9_$]*\.[a-z][A-Za-z0-9_$]*)\b/g;
226
+ let match: RegExpExecArray | null = SYMBOL.exec(content);
227
+ while (match) {
228
+ const sym = match[1] ?? "";
229
+ const after = content.slice(
230
+ match.index + match[0].length,
231
+ match.index + match[0].length + WINDOW,
232
+ );
233
+ const before = content.slice(
234
+ Math.max(0, match.index - WINDOW),
235
+ match.index,
236
+ );
237
+ const num =
238
+ after.match(/[-+]?\d+(?:\.\d+)?/)?.[0] ??
239
+ before.match(/[-+]?\d+(?:\.\d+)?/)?.[0];
240
+ if (num !== undefined && !out.has(sym)) out.set(sym, num);
241
+ match = SYMBOL.exec(content);
242
+ }
243
+ return out;
244
+ }
245
+
246
+ /**
247
+ * Which live rows the incoming candidate corrects. The caller passes rows
248
+ * already filtered to the candidate's scope, type-compared here.
249
+ *
250
+ * Guided rows are protected from inferred writes: a captured inference must
251
+ * not bury what the user stated — the user is the stronger claim. A guided
252
+ * candidate may retire anything, including a stale guided row.
253
+ */
254
+ export function valueConflicts(
255
+ candidate: { type: string; content: string; tags?: string[] },
256
+ live: readonly Memory[],
257
+ ): ValueConflict[] {
258
+ const guided = candidate.tags?.includes(USER_GUIDED_TAG) === true;
259
+ const mine = symbolValues(candidate.content);
260
+ if (mine.size === 0) return [];
261
+ const out: ValueConflict[] = [];
262
+ for (const m of live) {
263
+ if (m.superseded_by) continue;
264
+ if (m.type !== candidate.type) continue;
265
+ if (!guided && m.tags?.includes(USER_GUIDED_TAG)) continue;
266
+ const theirs = symbolValues(m.content);
267
+ if (theirs.size === 0) continue;
268
+ let hit: { symbol: string; from: string } | undefined;
269
+ for (const [sym, val] of theirs) {
270
+ const said = mine.get(sym);
271
+ if (said === undefined) continue;
272
+ if (valuesAgree(said, val) === false) {
273
+ hit = { symbol: sym, from: val };
274
+ break;
275
+ }
276
+ }
277
+ if (!hit) continue;
278
+ // Excise each side's asserted occurrence of the hit symbol's value,
279
+ // then require the rest of the two sentences to match.
280
+ if (
281
+ !sameSentenceExceptValue(
282
+ residualTokens(
283
+ candidate.content,
284
+ assertedValueSpan(candidate.content, hit.symbol),
285
+ ),
286
+ residualTokens(m.content, assertedValueSpan(m.content, hit.symbol)),
287
+ mine.get(hit.symbol) ?? "",
288
+ hit.from,
289
+ )
290
+ )
291
+ continue;
292
+ out.push({
293
+ ts: m.ts,
294
+ symbol: hit.symbol,
295
+ from: hit.from,
296
+ to: mine.get(hit.symbol) ?? "",
297
+ });
298
+ }
299
+ return out;
300
+ }
@@ -1,5 +1,6 @@
1
1
  // format — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
  import { type Memory } from "../store/model/memory.ts";
3
+ import { provenanceMarker, provenanceOf } from "../store/model/provenance.ts";
3
4
  import { flattenMemoryText } from "../store/sanitize.ts";
4
5
  import { capToBudget } from "./budget.ts";
5
6
 
@@ -20,6 +21,13 @@ export function formatMemory(m: Memory): string {
20
21
  const tag = m.status === "open" ? " [open]" : "";
21
22
  const via = PROVENANCE_TAGS.filter((t) => m.tags?.includes(t));
22
23
  const src = via.length ? ` [via ${via.join("+")}]` : "";
24
+ // #393: the discount the reader needs. `[via auto-capture]` says where a row
25
+ // came from; this says whether anything OUTSIDE that source ever agreed with
26
+ // it. R4 measured the cost of not saying so: one plausible wrong row shipped a
27
+ // wrong artifact in 4/5 runs with no uncertainty flagged, while an empty store
28
+ // declined to invent a value at all. Rendered as a separate token so the
29
+ // existing `[via …]` contract is untouched.
30
+ const trust = provenanceMarker(provenanceOf(m.tags));
23
31
  // One memory is ONE line in every injected block: the store round-trips real
24
32
  // newlines, so a planted "\n## Fake header" would forge its own section and
25
33
  // escape the framing (and throw capToBudget's line accounting off). Line
@@ -35,5 +43,5 @@ export function formatMemory(m: Memory): string {
35
43
  const quote = m.original
36
44
  ? ` (user said: "${flattenMemoryText(m.original)}")`
37
45
  : "";
38
- return `- [${date}]${tag}${src} ${type}/${scope}: ${content}${quote}`;
46
+ return `- [${date}]${tag}${src}${trust} ${type}/${scope}: ${content}${quote}`;
39
47
  }
@@ -0,0 +1,79 @@
1
+ // Provenance: how a row was obtained (#393).
2
+ //
3
+ // R4 (`benchmark-tests/ocsi/results-poison-x5/`, n=5) is why this exists. With an
4
+ // empty store the agent produced no artifact in 3 of 5 runs and never invented a
5
+ // rate — the honest failure. With ONE plausible wrong row it shipped a WRONG
6
+ // artifact in 4 of 5 (2475, 2100, 3100, 1750) and flagged no uncertainty in any
7
+ // run. A false row is not neutral: it converts "I cannot proceed" into "I shipped
8
+ // something wrong". The rows used were real capture output with the values and
9
+ // targets swapped, so this is the same shape, same confidence, same specificity —
10
+ // not a strawman.
11
+ //
12
+ // The fix cannot be "check it against the tree", and the measurement says so:
13
+ // `findConstant(base4, "fallbackVatBps")` returns null — the fixture leaves the
14
+ // value UNSET, which is precisely why the poison had somewhere to go. A check that
15
+ // refuses a claim when the tree contradicts it refuses nothing here, and a check
16
+ // that refuses when the tree is silent also refuses the transport fact (empty
17
+ // store 0/5, seeded 5/5), which is the one measured benefit memory has.
18
+ //
19
+ // So provenance is a LABEL the reader discounts by, not a filter that decides.
20
+ // It is derived, and the derivation is total. A rule of the form "a row with no
21
+ // provenance is not injected" is only safe if nothing falls through it, and the
22
+ // real store says why: of 1014 rows, 109 carry `auto-capture`, 18 carry
23
+ // `user-guided`, none carry `import`, and **905 carry none of those** — they came
24
+ // through the tool path, which is a provenance and not an absence of one.
25
+ // Excluding untagged rows would have dropped 89% of the store from injection,
26
+ // which is a recall loss wearing a safety badge.
27
+
28
+ export type Provenance =
29
+ /** The user said it; the row may carry the verbatim quote. */
30
+ | "user-stated"
31
+ /** Mined from a transcript by auto-capture. Untrusted until checked. */
32
+ | "capture-inferred"
33
+ /** Arrived through `memory_import` from a file another machine produced. */
34
+ | "imported"
35
+ /** Written by the agent or the user through a tool, in this repo. */
36
+ | "elicited";
37
+
38
+ export interface ProvenanceInfo {
39
+ kind: Provenance;
40
+ /**
41
+ * True when the row has been checked against something outside the text that
42
+ * produced it — today, a numeric claim that agreed with the working tree.
43
+ * This is the bit the injected line turns into `[code-checked]` versus
44
+ * `[unverified]`.
45
+ */
46
+ checked: boolean;
47
+ }
48
+
49
+ /**
50
+ * Total by construction: every row gets a class, so injection never loses a row
51
+ * to a missing label. Order matters — a guided row that capture also mined is
52
+ * USER-stated, because the user's authority is the stronger claim of the two.
53
+ */
54
+ export function provenanceOf(
55
+ tags: readonly string[] | undefined,
56
+ ): ProvenanceInfo {
57
+ const t = tags ?? [];
58
+ if (t.includes("user-guided")) return { kind: "user-stated", checked: false };
59
+ if (t.includes("import")) return { kind: "imported", checked: false };
60
+ if (t.includes("auto-capture"))
61
+ return { kind: "capture-inferred", checked: t.includes("code-checked") };
62
+ return { kind: "elicited", checked: false };
63
+ }
64
+
65
+ /**
66
+ * The marker that rides the injected line. Kept SHORT and kept SEPARATE from the
67
+ * existing `[via …]` marker, whose exact text several tests pin: those tests are
68
+ * the reason this is an appended token and not a rewrite.
69
+ *
70
+ * `elicited` and `user-stated` render nothing. Both are the user's own authority
71
+ * in this repository, and decorating 905 of 1014 rows with a warning would teach
72
+ * the model to ignore the warning.
73
+ */
74
+ export function provenanceMarker(info: ProvenanceInfo): string {
75
+ if (info.checked) return " [code-checked]";
76
+ if (info.kind === "capture-inferred") return " [unverified]";
77
+ if (info.kind === "imported") return "";
78
+ return "";
79
+ }