opencode-self-improvement 0.18.1 → 0.20.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/README.md CHANGED
@@ -67,6 +67,7 @@ Zero configuration is the default. To tune, use the object form of the plugin en
67
67
  | --- | --- | --- |
68
68
  | `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull; trimmed at whole-memory boundaries. Env fallback: `OPENCODE_MEMORY_INJECT_BUDGET`. |
69
69
  | `frontierBudget` | `3 × injectBudget` | Character cap on the session-start open-threads block. A thread longer than the budget is not injected and is reported as omitted. Env fallback: `OPENCODE_MEMORY_FRONTIER_BUDGET`. |
70
+ | `contradictionSurface` | `true` | Experimental: compare guided constant claims with bounded source reads and render a class-specific CONFLICT verdict. Set `false` to skip code checks and retain plain guidance. See [Contradiction authority policy](#contradiction-authority-policy-experimental-349--351). |
70
71
  | `autoCapture` | `false` | Master switch for auto-capture, which is **experimental and has never fired on a verified live store** — see [Auto-capture is experimental](#auto-capture-is-experimental). Off by default, so the install stays zero-token. |
71
72
  | `captureModel` | — | `"provider/id"` model used for auto-capture. Required when `autoCapture` is on; missing or invalid disables capture with a startup warning. |
72
73
  | `captureMax` | `3` | Maximum candidates proposed per capture pass. |
@@ -118,6 +119,20 @@ Four gates run before anything is stored, and each emits an ordered evidence lin
118
119
 
119
120
  Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget` records a retirement, and `memory_undo` restores a snapshot. `memory_update` takes a `query` that picks the row — its id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it to update the newest entry of that scope and type. A `query` that matches nothing, or several rows, writes nothing and says so. A prose edit carries over ordinary tags, issue link, retrieval keywords, open/settled standing, and repository to the new row, while capture-only guidance provenance is removed — updating a `global` row from one machine keeps it global for every other. Naming a row an earlier update already superseded reports the duplicate when the live successor already holds that exact content; when only the metadata you name differs, the update runs against the successor instead of dead-ending. And a failure after the new row is durable is reported as `PARTIAL` — the message names what failed, the replacement stands on disk, and `memory_undo` (merge or force) brings the old row back.
120
121
 
122
+ ### Contradiction authority policy (experimental, #349 / #351)
123
+
124
+ `contradictionSurface` defaults to `true`; set it to `false` to keep plain guidance without code checks. Guided capture can attach a declared constant's `ref`, the user's value as `claim`, and an authority `klass`:
125
+
126
+ | Captured statement | Class | Verdict on a detected conflict |
127
+ | --- | --- | --- |
128
+ | User states the required value for a declared constant | `spec` | The user is the authority; change the constant to the stated requirement. |
129
+ | User describes how working code behaves | `behavior` | Code is the authority; keep the constant and raise the mismatch with the user. |
130
+ | Authority is unclear | Omit `klass` | Keep plain guidance and its staleness caveat; emit no CONFLICT verdict. |
131
+
132
+ The code check accepts a unique top-level `const` with a literal value. Comments, string examples, local declarations and computed expressions cannot establish an authority verdict. The scan is limited to 300 source files, 256 KiB per file and depth 3, preferring `src/`; it does not follow source links or resolve imports. Ambiguous declarations, unreadable/invalid source, exhausted budgets or an undecidable claim keep the plain guidance and staleness caveat. The JavaScript/TypeScript parser loads only when a row needs a code check; explicit opt-out never loads it. Use attribution keeps the stored row's identity and prose while coverage counts only references present in the delivered text.
133
+
134
+ Accepted residual: a user-stated **wrong spec** still classifies as `spec`. Its verdict follows that stated requirement even if it breaks the current tests. The plugin does not infer hidden-suite authority or silently override the user's requirement. Asking an oracle or inventing an extra authority class is outside this contract. Capture classification can be wrong; a code comparison verifies a value mismatch, not the user's intent. Per the [maintainer's rollout decision](https://github.com/abogartz/opencode-self-improvement/pull/363#pullrequestreview-5819556342), the default is ON for full benchmarking after merge and can be revisited. The seat-model and merged-main confidence runs in #350–#352 remain outstanding; enabling the feature is not a claim that those benchmarks passed.
135
+
121
136
  ## Repo scoping
122
137
 
123
138
  Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
@@ -264,7 +279,7 @@ Review the full row in the memory viewer's **quarantined** filter. **Release qua
264
279
 
265
280
  This is a heuristic review queue, not a complete prompt-injection detector: legitimate documentation or quoted code can match. Markdown-bold role headers and download-then-`&&`-execute forms are recognized, but alternate role delimiters such as `[INST]` / `<<SYS>>`, base64-to-shell pipelines, paraphrased instructions, and indirect execution can evade it. Direct `memory_remember` and human viewer edits are explicit writes and are not automatically scanned: a session with that tool still has a prose channel, mitigated by the existing framing and provenance rather than quarantine. Those defenses still apply to released rows.
266
281
 
267
- Always-ride guidance priority is reserved to auto-capture provenance. `memory_remember`, `memory_update` replacements, and JSONL imports silently remove `user-guided` (including comma-delimited tag entries) before the write gate; their field allowlists also exclude `ref`, `claim`, and `klass`. Ordinary tags and prose can still promote normally, but a portable file, even with an export header, cannot attest that the local user stated it. The capture path owns guidance metadata; this boundary protection does not authenticate a directly edited store or guarantee that a capture model classified a statement correctly. This reservation is in place before the opt-in hint/contradiction channel lands (#342, #349).
282
+ Always-ride guidance priority is reserved to auto-capture provenance. `memory_remember`, `memory_update` replacements, and JSONL imports silently remove `user-guided` (including comma-delimited tag entries) before the write gate; their field allowlists also exclude `ref`, `claim`, and `klass`. Ordinary tags and prose can still promote normally, but a portable file, even with an export header, cannot attest that the local user stated it. The capture path owns guidance metadata; this boundary protection does not authenticate a directly edited store or guarantee that a capture model classified a statement correctly. The reservation applies to guidance priority and contradiction verdicts (#342, #349).
268
283
 
269
284
  The viewer is a trusted admin editor: its edits and deleted-entry restores do not run the model-facing grounding or deduplication gates, but they honor the same exact and near-match value rejections. Rejected edits leave the original row, snapshots and edit audit unchanged; rejected restores append nothing. The refusal names the rejection hash so you can explicitly lift it under **Rejections → un-reject** before retrying. Corrected numeric values and polarity changes retain the rejection check's existing exceptions. This check does not change whole-snapshot rollback policy.
270
285
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.18.1",
3
+ "version": "0.20.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": {
@@ -75,6 +75,7 @@
75
75
  "lint": "biome lint && bun run format:check"
76
76
  },
77
77
  "dependencies": {
78
+ "@babel/parser": "7.29.9",
78
79
  "zod": "4.6.7"
79
80
  }
80
81
  }
@@ -92,13 +92,36 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
92
92
  o.status === "open" || o.status === "settled" ? o.status : undefined;
93
93
  // A bad kw list costs the row its keywords, never the row itself.
94
94
  const kw = cleanKeywords(o.kw);
95
+ // Hint channel (#335): only a literal true counts; junk yields an
96
+ // untagged row, the same shape an agent-derived fact has.
95
97
  const guided = o.guided === true;
98
+ // Contradiction surface (POC): ref/claim/klass ride guided rows only.
99
+ // Local checks keep this module store-free; appendMemory normalises
100
+ // again, so this only has to stay junk-proof.
101
+ const conflict =
102
+ guided && o && typeof o === "object"
103
+ ? {
104
+ ...(typeof o.ref === "string" &&
105
+ /^[A-Za-z_][A-Za-z0-9_]{1,63}$/.test(o.ref)
106
+ ? { ref: o.ref }
107
+ : {}),
108
+ ...(typeof o.claim === "string" &&
109
+ o.claim.trim() &&
110
+ o.claim.trim().length <= 32 &&
111
+ flattenMemoryText(o.claim.trim()) === o.claim.trim()
112
+ ? { claim: o.claim.trim() }
113
+ : {}),
114
+ ...(o.klass === "spec" || o.klass === "behavior"
115
+ ? { klass: o.klass as "spec" | "behavior" }
116
+ : {}),
117
+ }
118
+ : {};
96
119
  out.push({
97
120
  ...(status
98
121
  ? { type, scope, content, status }
99
122
  : { type, scope, content }),
100
123
  ...(kw ? { kw } : {}),
101
- ...(guided ? { guided: true } : {}),
124
+ ...(guided ? { guided: true, ...conflict } : {}),
102
125
  });
103
126
  }
104
127
  return out;
@@ -17,6 +17,10 @@ export interface CaptureCandidate {
17
17
  kw?: string[];
18
18
  /** Literal true only when the user stated the fact, not agent inference. */
19
19
  guided?: boolean;
20
+ /** Optional literal comparison metadata, retained only for guided rows. */
21
+ ref?: string;
22
+ claim?: string;
23
+ klass?: "spec" | "behavior";
20
24
  }
21
25
 
22
26
  // Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
@@ -39,8 +43,10 @@ export function buildCapturePrompt(
39
43
  transcript: string,
40
44
  max = 3,
41
45
  userProse = "",
46
+ known = "",
42
47
  ): string {
43
48
  const prose = redactSecrets(userProse).trim();
49
+ const knownList = redactSecrets(known).trim();
44
50
  return [
45
51
  "You mine one coding-agent session transcript for durable memories worth keeping across future sessions.",
46
52
  "",
@@ -54,8 +60,19 @@ export function buildCapturePrompt(
54
60
  "- content: one self-contained fact, 20-600 characters, useful in a NEW session.",
55
61
  "- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.",
56
62
  "- guided: true ONLY when the user STATED this fact in their own words — a value, rate, number, rule or correction that appears in a user: line or the REQUESTS block. Omit guided for anything the agent discovered by itself.",
63
+ '- When guided AND the value names a declared code symbol, also output "ref": that symbol exactly as declared (e.g. "TAX_RATE"), "claim": the user\'s value alone (e.g. "0.0825", at most 32 characters), and "klass": "spec" when the user is the authority on the value (a rate, a requirement) or "behavior" when the row describes how working code behaves. Omit all three when no single declared constant is involved.',
64
+ '- If it is unclear whether the user is specifying a requirement or describing working code, omit "klass". Never guess authority; an unclassified row remains plain guidance without a conflict verdict.',
65
+ '- Worked example (only when the user actually states this requirement): user says "The constant TAX_RATE in src/pricing.ts must be 0.0825." Emit:',
66
+ '{"type":"context","scope":"pricing","content":"The constant TAX_RATE in src/pricing.ts must be 0.0825.","kw":["TAX_RATE","sales tax"],"guided":true,"ref":"TAX_RATE","claim":"0.0825","klass":"spec"}',
67
+ "- A guided row states the user's value or rule and NOTHING more: never claim what hidden tests, graders or suites 'encode' — you cannot see them, and the claim makes the row impossible to check.",
57
68
  "- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
58
69
  "- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
70
+ ...(knownList
71
+ ? [
72
+ "- Already stored for this repo — do NOT output these or restatements of them:",
73
+ knownList,
74
+ ]
75
+ : []),
59
76
  ...(prose
60
77
  ? [
61
78
  // The brief is its own block, so the rule about it is its own too.
@@ -14,6 +14,15 @@ import { buildCapturePrompt } from "./prompt.ts";
14
14
  import { type SessionModelRef, sessionModel } from "./session-model.ts";
15
15
  import { flattenTranscript, splitTranscript } from "./transcript.ts";
16
16
  import { AUTO_CAPTURE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
17
+ import { loadAll } from "../store/files/load.ts";
18
+ import { isInjectable } from "../store/model/predicates.ts";
19
+ import {
20
+ readerFromSid,
21
+ visibleTo,
22
+ type Reader,
23
+ } from "../store/model/visibility.ts";
24
+ import { flattenMemoryText } from "../store/sanitize.ts";
25
+ import { cmpTs } from "../core/cmp-ts.ts";
17
26
 
18
27
  interface CaptureHost {
19
28
  options?: Record<string, unknown>;
@@ -43,6 +52,34 @@ interface CaptureDependencies {
43
52
  // distinction the auto_capture_compaction_* evidence lines carry.
44
53
  const CAPTURE_COMPACT_TAG = "auto_capture_compaction";
45
54
 
55
+ async function knownRowsFor(reader: Reader): Promise<string> {
56
+ try {
57
+ const rows = visibleTo(await loadAll(), reader)
58
+ .filter(isInjectable)
59
+ .sort((a, b) => cmpTs(b.ts, a.ts))
60
+ .slice(0, 15);
61
+ const lines: string[] = [];
62
+ let length = 0;
63
+ for (const row of rows) {
64
+ // Scrub complete legacy values before cropping, or a token prefix can
65
+ // fall outside the window and leave an unrecognizable secret fragment.
66
+ const scope = flattenMemoryText(redactSecrets(row.scope));
67
+ const content = flattenMemoryText(redactSecrets(row.content)).slice(
68
+ 0,
69
+ 90,
70
+ );
71
+ const line = `- ${scope}: ${content}`;
72
+ if (length + line.length > 1400) break;
73
+ lines.push(line);
74
+ length += line.length + 1;
75
+ }
76
+ return lines.join("\n");
77
+ } catch {
78
+ // The write gate still deduplicates when this optional context is absent.
79
+ return "";
80
+ }
81
+ }
82
+
46
83
  // Auto-capture cooldown, shared by EVERY setup() registration (#108): setup
47
84
  // runs for more than one location, and per-closure cooldown maps made those
48
85
  // registrations strangers - one compaction could pay for two model calls on
@@ -215,6 +252,7 @@ export function configureAutoCapture(
215
252
  gate?: GateContext,
216
253
  ): Promise<void> {
217
254
  const captureGate = gate ?? bindCapture(sid);
255
+ const captureReader = captureGate.reader ?? readerFromSid(sid);
218
256
  // #139: resolve the model BEFORE any skip so every capture evidence
219
257
  // line below can carry model= (cost attributable to a named model —
220
258
  // the real answer to the cost-surprise concern that justified the
@@ -304,6 +342,7 @@ export function configureAutoCapture(
304
342
  redactSecrets(work).slice(-7000),
305
343
  captureMax,
306
344
  redactSecrets(userProse).slice(-1500),
345
+ await knownRowsFor(captureReader),
307
346
  ),
308
347
  });
309
348
  const text = typeof out === "string" ? out : (out?.text ?? "");
@@ -319,6 +358,9 @@ export function configureAutoCapture(
319
358
  content: c.content,
320
359
  ...(c.status ? { status: c.status } : {}),
321
360
  ...(c.kw ? { kw: c.kw } : {}),
361
+ ...(c.ref ? { ref: c.ref } : {}),
362
+ ...(c.claim ? { claim: c.claim } : {}),
363
+ ...(c.klass ? { klass: c.klass } : {}),
322
364
  tags: [
323
365
  AUTO_CAPTURE_TAG,
324
366
  ...(trigger === "compaction" ? [CAPTURE_COMPACT_TAG] : []),
@@ -363,6 +405,16 @@ export function configureAutoCapture(
363
405
  reason: outcome.reason ?? "",
364
406
  audit_error: outcome.evidenceError,
365
407
  model: modelTag,
408
+ ...(outcome.action === "promoted" && c.guided
409
+ ? {
410
+ conflict:
411
+ c.ref && c.claim && c.klass
412
+ ? "full"
413
+ : c.ref || c.claim || c.klass
414
+ ? "partial"
415
+ : "absent",
416
+ }
417
+ : {}),
366
418
  },
367
419
  false,
368
420
  sid,
package/src/gate/gate.ts CHANGED
@@ -55,6 +55,9 @@ export interface WriteCandidate {
55
55
  // (trim/lowercase/cap) at promotion, so a caller may hand junk without
56
56
  // changing the verdict the prose deserves.
57
57
  kw?: string[];
58
+ ref?: string;
59
+ claim?: string;
60
+ klass?: "spec" | "behavior";
58
61
  status?: "open" | "settled";
59
62
  // "global" = cross-project (memory_remember global:true; imports carry a
60
63
  // row's origin stamp). Any other value (including undefined) is resolved by
@@ -407,6 +410,8 @@ export async function runWriteGate(
407
410
  candidate.tags?.some(containsSecret) ? "tags" : undefined,
408
411
  candidate.kw?.some(containsSecret) ? "kw" : undefined,
409
412
  containsSecret(candidate.issue) ? "issue" : undefined,
413
+ containsSecret(candidate.ref) ? "ref" : undefined,
414
+ containsSecret(candidate.claim) ? "claim" : undefined,
410
415
  ].filter((field): field is string => field !== undefined);
411
416
  if (credentialMetadata.length) {
412
417
  await recBlocked(
package/src/index.ts CHANGED
@@ -204,6 +204,8 @@ const impl = {
204
204
  const sessions = createInjectionEpochs({
205
205
  budget,
206
206
  frontierBudget: openBudget,
207
+ // Code-check guided claims by default; explicit false opts out.
208
+ contradictionSurface: ctx.options?.contradictionSurface !== false,
207
209
  measuredTurns,
208
210
  noteHits: (sid, rows, query) => noteHits("inject", sid, rows, query),
209
211
  });
@@ -59,9 +59,15 @@ export function cappedFrontier(
59
59
  // pre-budget candidates — or it would credit the model with paths and commands
60
60
  // it was never shown. capToBudget keeps whole lines verbatim, so a candidate is
61
61
  // present iff its rendered line is a substring of the block.
62
- export function injectedRows(block: string, candidates: Memory[]): Memory[] {
62
+ export function injectedRows(
63
+ block: string,
64
+ candidates: Memory[],
65
+ rendered?: ReadonlyMap<Memory, Memory>,
66
+ ): Memory[] {
63
67
  if (!block) return [];
64
- return candidates.filter((m) => block.includes(formatMemory(m)));
68
+ return candidates.filter((m) =>
69
+ block.includes(formatMemory(rendered?.get(m) ?? m)),
70
+ );
65
71
  }
66
72
 
67
73
  // Trim an injection block to `budget` characters at WHOLE-line boundaries:
@@ -30,6 +30,11 @@ import { authoredFor } from "../core/state.ts";
30
30
  interface InjectionEpochOptions {
31
31
  budget: number;
32
32
  frontierBudget: number;
33
+ /**
34
+ * Contradiction surface (POC): code-check guided rows at render time.
35
+ * Enabled by default; `contradictionSurface: false` skips workspace checks.
36
+ */
37
+ contradictionSurface?: boolean;
33
38
  // The host listener records usage. Eviction must still drop it with the
34
39
  // epoch and request counters, so no measurement outlives its tracked session.
35
40
  measuredTurns: Pick<Map<string, Measured>, "get" | "delete">;
@@ -39,6 +44,7 @@ interface InjectionEpochOptions {
39
44
  export function createInjectionEpochs({
40
45
  budget,
41
46
  frontierBudget: openBudget,
47
+ contradictionSurface = true,
42
48
  measuredTurns,
43
49
  noteHits,
44
50
  }: InjectionEpochOptions) {
@@ -176,6 +182,11 @@ export function createInjectionEpochs({
176
182
  promptOverride ??
177
183
  (sid === undefined ? "" : (latestPrompt.get(sid) ?? ""));
178
184
  // Widen the candidate pool, then cap: the budget decides what rides.
185
+ // The guided cap (#335) rides user-stated rows ahead of the lexical picks;
186
+ // the char budget below still bounds the whole block. The conflict check
187
+ // reads the session's OWN repo directory (its reader's scope) — never an
188
+ // ambient one (#127's rule applies to code reads too).
189
+ const reader = readerFromSid(sid);
179
190
  const sel = await selectRelevant(
180
191
  prompt,
181
192
  5,
@@ -183,18 +194,30 @@ export function createInjectionEpochs({
183
194
  await useSignals(),
184
195
  undefined,
185
196
  {
186
- // The reserved capture provenance rides first, even on unrelated prompts.
187
- // capToBudget still bounds all rendered rows together.
188
197
  guidedCap: 3,
198
+ ...(contradictionSurface
199
+ ? {
200
+ conflictCheck: true,
201
+ ...(reader.kind === "repo" ? { repoDir: reader.scope.path } : {}),
202
+ }
203
+ : {}),
189
204
  },
190
205
  );
191
206
  const block = sel.block ? capToBudget(sel.block, budget) : "";
192
207
  // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
193
208
  // for attribution. Derived from the budget-surviving rows, not the wider
194
209
  // candidate pool — crediting paths the model never saw would overclaim.
195
- const rode = injectedRows(block, sel.selected);
210
+ const rode = injectedRows(block, sel.selected, sel.rendered);
196
211
  const prefix = [...parts, block].join("\u0000");
197
- return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
212
+ // Ledger terms/identities belong to the stored rows, but coverage refs
213
+ // must describe only the text the model actually received.
214
+ return {
215
+ parts,
216
+ block,
217
+ prefix,
218
+ rode,
219
+ refs: deriveMemoryRefs(rode.map((m) => sel.rendered.get(m) ?? m)),
220
+ };
198
221
  };
199
222
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
200
223
  if (!latestPrompt.has(sid)) return;
@@ -0,0 +1,247 @@
1
+ // Contradiction surface (POC, bench FINDINGS §4). A user-guided row may
2
+ // declare ref (the code symbol its value is about), claim (the user's value)
3
+ // and klass (who holds authority). At render time the plugin reads the code —
4
+ // bounded, deterministic, NO model call — and a collision renders ONE flagged
5
+ // CONFLICT line whose Action is fixed by the class: behavior class trusts the
6
+ // code, spec class fixes it. #345 measured the alternative twice: a wrong
7
+ // guided row made the agent rewrite a correct constant (raw row) and the
8
+ // framing-only fix stayed a coin flip (2 harms in 5). The class rule held 6/6.
9
+ import {
10
+ closeSync,
11
+ fstatSync,
12
+ lstatSync,
13
+ openSync,
14
+ readSync,
15
+ readdirSync,
16
+ type Dirent,
17
+ } from "node:fs";
18
+ import { createRequire } from "node:module";
19
+ import { extname, join, relative } from "node:path";
20
+ import type { Expression } from "@babel/types";
21
+ import { type Memory } from "../store/model/memory.ts";
22
+
23
+ export interface CodeFact {
24
+ /** Repo-relative path where the declaration was read. */
25
+ file: string;
26
+ /** The declared literal, verbatim (trimmed). */
27
+ value: string;
28
+ }
29
+
30
+ // Bounded source scan: cap files, bytes per file, and directory depth. When
31
+ // a relevant source cannot be decided, keep the row's plain caveat.
32
+ const MAX_FILES = 300;
33
+ const MAX_FILE_BYTES = 256 * 1024;
34
+ const SCAN_DEPTH = 3;
35
+ const EXTENSIONS = new Set([".ts", ".tsx", ".js", ".mjs", ".cjs"]);
36
+ const SKIP_DIRS = new Set([
37
+ "node_modules",
38
+ ".git",
39
+ "dist",
40
+ "build",
41
+ ".opencode",
42
+ ]);
43
+
44
+ function walk(dir: string, depth: number, out: string[]): void {
45
+ if (depth > SCAN_DEPTH || out.length > MAX_FILES) return;
46
+ let entries: Dirent[];
47
+ try {
48
+ // Never turn a src/ link or a linked child into an out-of-repo code fact.
49
+ if (!lstatSync(dir).isDirectory()) return;
50
+ entries = readdirSync(dir, { withFileTypes: true });
51
+ } catch {
52
+ return;
53
+ }
54
+ for (const e of entries.sort((a, b) =>
55
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0,
56
+ )) {
57
+ if (out.length > MAX_FILES) return;
58
+ if (e.isDirectory()) {
59
+ if (!SKIP_DIRS.has(e.name) && !e.name.startsWith("."))
60
+ walk(join(dir, e.name), depth + 1, out);
61
+ } else if (e.isFile()) {
62
+ const dot = e.name.lastIndexOf(".");
63
+ if (dot >= 0 && EXTENSIONS.has(e.name.slice(dot)))
64
+ out.push(join(dir, e.name));
65
+ }
66
+ }
67
+ }
68
+
69
+ // Load the parser only for an actual code check, never on the opt-out path.
70
+ const require = createRequire(import.meta.url);
71
+ let parser: typeof import("@babel/parser") | undefined;
72
+ const sourceParser = (): typeof import("@babel/parser") =>
73
+ (parser ??= require("@babel/parser"));
74
+
75
+ function literalValue(
76
+ node: Expression | null | undefined,
77
+ ): string | number | boolean | null | undefined {
78
+ if (!node) return undefined;
79
+ switch (node.type) {
80
+ case "StringLiteral":
81
+ case "BooleanLiteral":
82
+ return node.value;
83
+ case "NullLiteral":
84
+ return null;
85
+ case "NumericLiteral":
86
+ return Number.isFinite(node.value) ? node.value : undefined;
87
+ case "UnaryExpression": {
88
+ if (
89
+ node.argument.type !== "NumericLiteral" ||
90
+ !["+", "-"].includes(node.operator)
91
+ )
92
+ return undefined;
93
+ const value = (node.operator === "-" ? -1 : 1) * node.argument.value;
94
+ return Number.isFinite(value) ? value : undefined;
95
+ }
96
+ default:
97
+ return undefined;
98
+ }
99
+ }
100
+
101
+ /** null = target found but undecidable; undefined = no top-level declaration. */
102
+ function declaration(
103
+ text: string,
104
+ file: string,
105
+ ref: string,
106
+ ): string | null | undefined {
107
+ const extension = extname(file);
108
+ const plugins: import("@babel/parser").ParserPlugin[] = [];
109
+ if (extension === ".ts" || extension === ".tsx") plugins.push("typescript");
110
+ if (extension === ".tsx") plugins.push("jsx");
111
+ const tree = sourceParser().parse(text, {
112
+ sourceType: "unambiguous",
113
+ plugins,
114
+ });
115
+ let found: string | undefined;
116
+ for (const statement of tree.program.body) {
117
+ const candidate =
118
+ statement.type === "ExportNamedDeclaration"
119
+ ? statement.declaration
120
+ : statement;
121
+ if (candidate?.type !== "VariableDeclaration" || candidate.kind !== "const")
122
+ continue;
123
+ for (const binding of candidate.declarations) {
124
+ if (binding.id.type !== "Identifier" || binding.id.name !== ref) continue;
125
+ if (
126
+ found !== undefined ||
127
+ literalValue(binding.init) === undefined ||
128
+ binding.init?.start == null ||
129
+ binding.init.end == null
130
+ )
131
+ return null;
132
+ found = text.slice(binding.init.start, binding.init.end);
133
+ }
134
+ }
135
+ return found;
136
+ }
137
+
138
+ function readBounded(file: string): string | undefined {
139
+ const fd = openSync(file, "r");
140
+ try {
141
+ const stat = fstatSync(fd);
142
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return undefined;
143
+ // Bound the read too: a file growing after stat cannot make this path
144
+ // allocate/read an arbitrarily large source file.
145
+ const bytes = Buffer.alloc(MAX_FILE_BYTES + 1);
146
+ let length = 0;
147
+ while (length < bytes.length) {
148
+ const count = readSync(fd, bytes, length, bytes.length - length, length);
149
+ if (!count) break;
150
+ length += count;
151
+ }
152
+ return length > MAX_FILE_BYTES
153
+ ? undefined
154
+ : bytes.toString("utf8", 0, length);
155
+ } finally {
156
+ closeSync(fd);
157
+ }
158
+ }
159
+
160
+ /**
161
+ * A unique top-level `const REF = <literal>` in the bounded scan (src/
162
+ * preferred, whole repo fallback). Comments/strings are never declarations.
163
+ * Duplicate names, invalid source and computed initializers cannot decide —
164
+ * a behavior implemented as computed logic is deliberately not guessed: the
165
+ * caller keeps the plain row and its verify-against-code caveat instead.
166
+ */
167
+ export function findConstant(dir: string, ref: string): CodeFact | null {
168
+ const files: string[] = [];
169
+ walk(join(dir, "src"), 0, files);
170
+ if (!files.length) walk(dir, 0, files);
171
+ if (files.length > MAX_FILES) return null;
172
+ let fact: CodeFact | null = null;
173
+ for (const f of files) {
174
+ try {
175
+ const text = readBounded(f);
176
+ if (text === undefined) return null;
177
+ if (!text.includes(ref) && !text.includes("\\u")) continue;
178
+ const value = declaration(text, f, ref);
179
+ if (value === null || (value !== undefined && fact)) return null;
180
+ if (value !== undefined) fact = { file: relative(dir, f), value };
181
+ } catch {
182
+ // A relevant unreadable/invalid source is not evidence of absence.
183
+ return null;
184
+ }
185
+ }
186
+ return fact;
187
+ }
188
+
189
+ /**
190
+ * Numeric-aware agreement: "$50.00" == "50", "0.0825" == "0.0825", and a
191
+ * percent claim matches the fraction it names ("8.25%" == "0.0825"). String
192
+ * whitespace is significant. Undefined means the claim cannot decide the
193
+ * observed literal's value — the caller must keep plain guidance.
194
+ */
195
+ export function valuesAgree(claim: string, code: string): boolean | undefined {
196
+ try {
197
+ const observed = literalValue(sourceParser().parseExpression(code));
198
+ if (observed === undefined) return undefined;
199
+ let stated = claim.trim();
200
+ if (stated.startsWith('"') || stated.startsWith("'")) {
201
+ const decoded = literalValue(sourceParser().parseExpression(stated));
202
+ if (typeof decoded !== "string") return undefined;
203
+ stated = decoded;
204
+ }
205
+ const numeric = (s: string): number | undefined => {
206
+ if (
207
+ !/^[+-]?\$?(?:(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?%?$/i.test(
208
+ s,
209
+ )
210
+ )
211
+ return undefined;
212
+ const [mantissa, exponent = "0"] = s.replace(/[$,%]/g, "").split(/e/i);
213
+ // Shift before converting: dividing an already-rounded float (8.2/100)
214
+ // invents a mismatch with the literal 0.082.
215
+ const n = Number(
216
+ `${mantissa}e${Number(exponent) - (s.endsWith("%") ? 2 : 0)}`,
217
+ );
218
+ return Number.isFinite(n) ? n : undefined;
219
+ };
220
+ const value = numeric(stated);
221
+ if (typeof observed === "number")
222
+ return value === undefined ? undefined : value === observed;
223
+ if (typeof observed === "string") {
224
+ const n = numeric(observed);
225
+ return n !== undefined && value !== undefined
226
+ ? n === value
227
+ : stated === observed;
228
+ }
229
+ if (observed === null) return stated === "null" ? true : undefined;
230
+ return stated === "true" || stated === "false"
231
+ ? (stated === "true") === observed
232
+ : undefined;
233
+ } catch {
234
+ return undefined;
235
+ }
236
+ }
237
+
238
+ /** The one flagged object: both facts, the provenance, the FIXED verdict. */
239
+ export function conflictLine(m: Memory, fact: CodeFact): string {
240
+ return (
241
+ `CONFLICT (${m.ref}). Memory: ${m.claim} — user-stated, never verified. ` +
242
+ `Code today: ${m.ref} = ${fact.value} (observed in ${fact.file}). ` +
243
+ (m.klass === "spec"
244
+ ? `Class: spec — the user is the authority on this value. Action: the code is the bug; fix ${m.ref} to ${m.claim}.`
245
+ : `Class: behavior — working code is the authority. Action: trust the code; do not edit ${m.ref}; if the remembered rule looks intentional, raise it with the user instead.`)
246
+ );
247
+ }
@@ -5,7 +5,8 @@ import { isInjectable } from "../store/model/predicates.ts";
5
5
  import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
6
6
  import { FRAME } from "../inject/budget.ts";
7
7
  import { formatMemory } from "../inject/format.ts";
8
- import { USER_GUIDED_TAG } from "../core/guidance.ts";
8
+ import { conflictLine, findConstant, valuesAgree } from "./conflicts.ts";
9
+ import { USER_GUIDED_TAG } from "../core/tags.ts";
9
10
  import { cmpTs } from "../core/cmp-ts.ts";
10
11
  import { scoreMemories } from "./score.ts";
11
12
 
@@ -59,6 +60,18 @@ export interface SelectOptions {
59
60
  * and pull leave this off and stay query-driven.
60
61
  */
61
62
  guidedCap?: number;
63
+ /**
64
+ * Contradiction surface (POC): when true, a user-guided row that declares
65
+ * ref/claim/klass is code-checked at render time. A collision replaces the
66
+ * row's rendered text with one flagged CONFLICT line whose Action is fixed
67
+ * by the class. Detection is a bounded file scan — deterministic, no model.
68
+ */
69
+ conflictCheck?: boolean;
70
+ /**
71
+ * Repo directory the code check reads. Absent (or a non-repo reader) means
72
+ * no check: rows render plainly, exactly as before the feature.
73
+ */
74
+ repoDir?: string;
62
75
  }
63
76
 
64
77
  /** Row carries the hint-channel tag (written by capture for user-stated facts). */
@@ -76,6 +89,15 @@ export function isUserGuided(m: Memory): boolean {
76
89
  const GUIDED_CAVEAT =
77
90
  "; user-stated guidance may be stale — verify against the current code before changing behavior it contradicts";
78
91
 
92
+ // Measured (arm F run 2.1): with a code-checked CONFLICT row riding, the
93
+ // plain caveat plus a captured "trust code over docs" row pushed the agent
94
+ // to file the CONFLICT row with the stale-doc decoys — the blanket rule beat
95
+ // the specific verdict. When a CONFLICT row rides, the header states the
96
+ // verification is ALREADY done and its Action governs; the staleness warning
97
+ // stays for everything else.
98
+ const CONFLICT_CAVEAT =
99
+ "; CONFLICT rows were code-checked against this repo's current source — follow their Action; other user-stated guidance may be stale, verify against the current code before changing behavior it contradicts";
100
+
79
101
  export async function selectRelevant(
80
102
  message: string,
81
103
  limit = 3,
@@ -83,7 +105,11 @@ export async function selectRelevant(
83
105
  use?: UseSignals,
84
106
  sid?: string,
85
107
  opts?: SelectOptions,
86
- ): Promise<{ block: string; selected: Memory[] }> {
108
+ ): Promise<{
109
+ block: string;
110
+ selected: Memory[];
111
+ rendered: ReadonlyMap<Memory, Memory>;
112
+ }> {
87
113
  // Repo-scoped: model-facing reads see the caller's repo + global rows
88
114
  // (their session when one was threaded, #127).
89
115
  const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(
@@ -96,13 +122,30 @@ export async function selectRelevant(
96
122
  .sort((a, b) => cmpTs(b.ts, a.ts))
97
123
  .slice(0, cap)
98
124
  : [];
125
+ // Contradiction surface: code-check the guided rows that declared a ref.
126
+ // Only the RENDERED row changes (a shallow copy carries the CONFLICT text);
127
+ // `selected` keeps the originals, so the use ledger and attribution still
128
+ // key on stored rows. No collision (or no code found, or a computed value
129
+ // the parser cannot decide) leaves the row plain — fail-open to the row,
130
+ // never fail-shut on injection.
131
+ const rendered = new Map<Memory, Memory>();
132
+ if (opts?.conflictCheck && opts.repoDir && guided.length) {
133
+ for (const m of guided) {
134
+ if (!m.ref || !m.claim || !m.klass) continue;
135
+ const fact = findConstant(opts.repoDir!, m.ref);
136
+ if (!fact || valuesAgree(m.claim, fact.value) !== false) continue;
137
+ rendered.set(m, { ...m, content: conflictLine(m, fact) });
138
+ }
139
+ }
99
140
  const text = message.trim();
100
141
  const top = text ? scoreMemories(text, mems, limit, use) : [];
101
142
  const merged = [...guided, ...top.filter((m) => !guided.includes(m))];
102
- if (!merged.length) return { block: "", selected: [] };
143
+ if (!merged.length) return { block: "", selected: [], rendered };
144
+ const hasConflict = rendered.size > 0;
103
145
  return {
104
- block: `## Relevant durable memory${FRAME}${guided.length ? GUIDED_CAVEAT : ""}\n${merged.map(formatMemory).join("\n")}`,
146
+ block: `## Relevant durable memory${FRAME}${guided.length ? (hasConflict ? CONFLICT_CAVEAT : GUIDED_CAVEAT) : ""}\n${merged.map((m) => formatMemory(rendered.get(m) ?? m)).join("\n")}`,
105
147
  selected: merged,
148
+ rendered,
106
149
  };
107
150
  }
108
151
 
@@ -13,6 +13,7 @@ import { flattenMemoryText } from "../sanitize.ts";
13
13
  import {
14
14
  MAX_CONTENT_CHARS,
15
15
  type MemoryStatus,
16
+ normalizeConflictFields,
16
17
  normalizeKeywords,
17
18
  } from "../model/memory.ts";
18
19
 
@@ -25,6 +26,13 @@ export interface AppendMemoryInput {
25
26
  /** Retrieval keywords (#40); normalised and capped by appendMemory. */
26
27
  kw?: string[];
27
28
  status?: MemoryStatus;
29
+ /**
30
+ * Contradiction surface (POC): guided row's code symbol / user's value /
31
+ * authority class. Normalised by appendMemory; junk drops the fields only.
32
+ */
33
+ ref?: string;
34
+ claim?: string;
35
+ klass?: "spec" | "behavior";
28
36
  // "global" for explicit cross-project writes; imports may carry a validated
29
37
  // same-repo origin stamp (see portable.ts). Any missing value is resolved by
30
38
  // appendMemory against the live repo scope.
@@ -109,6 +117,8 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
109
117
  input.tags?.some(containsSecret) ? "tags" : undefined,
110
118
  input.kw?.some(containsSecret) ? "kw" : undefined,
111
119
  containsSecret(input.issue) ? "issue" : undefined,
120
+ containsSecret(input.ref) ? "ref" : undefined,
121
+ containsSecret(input.claim) ? "claim" : undefined,
112
122
  ].filter((field): field is string => field !== undefined);
113
123
  if (credentialMetadata.length) {
114
124
  throw new Error(
@@ -168,6 +178,7 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
168
178
  ts = new Date(new Date(ts).getTime() + 1).toISOString();
169
179
  }
170
180
  const kw = normalizeKeywords(input.kw);
181
+ const conflict = normalizeConflictFields(input);
171
182
  const line = formatLine({
172
183
  ts,
173
184
  type: input.type,
@@ -177,6 +188,7 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
177
188
  tags: input.tags?.length ? input.tags.join(",") : undefined,
178
189
  kw: kw?.join(","),
179
190
  status: input.status,
191
+ ...conflict,
180
192
  repo,
181
193
  repoPath,
182
194
  });
@@ -79,6 +79,15 @@ export function toMemory(
79
79
  typeof fields.superseded_by === "string"
80
80
  ? fields.superseded_by
81
81
  : undefined,
82
+ ref: typeof fields.ref === "string" && fields.ref ? fields.ref : undefined,
83
+ claim:
84
+ typeof fields.claim === "string" && fields.claim
85
+ ? fields.claim
86
+ : undefined,
87
+ klass:
88
+ fields.klass === "spec" || fields.klass === "behavior"
89
+ ? fields.klass
90
+ : undefined,
82
91
  reason: typeof fields.reason === "string" ? fields.reason : undefined,
83
92
  status:
84
93
  fields.status === "open" || fields.status === "settled"
@@ -1,5 +1,7 @@
1
1
  // memory — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
 
3
+ import { flattenMemoryText } from "../sanitize.ts";
4
+
3
5
  export type MemoryStatus = "open" | "settled";
4
6
 
5
7
  // Hard ceiling on stored content. No entry point may persist a line longer
@@ -41,6 +43,32 @@ export function normalizeKeywords(kw: unknown): string[] | undefined {
41
43
  return out.length ? out : undefined;
42
44
  }
43
45
 
46
+ /** A conflict ref names a code identifier, not a path or expression. */
47
+ const CONFLICT_REF_RE = /^[A-Za-z_][A-Za-z0-9_]{1,63}$/;
48
+
49
+ export const MAX_CLAIM_CHARS = 32;
50
+
51
+ /**
52
+ * Normalise the contradiction-surface fields of a guided candidate. TOTAL on
53
+ * purpose, like keywords: a junk ref/claim/klass drops the fields, never the
54
+ * row — the prose still deserved storage, it just cannot be code-checked.
55
+ */
56
+ export function normalizeConflictFields(o: {
57
+ ref?: unknown;
58
+ claim?: unknown;
59
+ klass?: unknown;
60
+ }): { ref?: string; claim?: string; klass?: "spec" | "behavior" } {
61
+ const out: { ref?: string; claim?: string; klass?: "spec" | "behavior" } = {};
62
+ if (typeof o.ref === "string" && CONFLICT_REF_RE.test(o.ref)) out.ref = o.ref;
63
+ if (typeof o.claim === "string") {
64
+ const c = o.claim.trim();
65
+ if (c && c.length <= MAX_CLAIM_CHARS && flattenMemoryText(c) === c)
66
+ out.claim = c;
67
+ }
68
+ if (o.klass === "spec" || o.klass === "behavior") out.klass = o.klass;
69
+ return out;
70
+ }
71
+
44
72
  export interface Memory {
45
73
  ts: string;
46
74
  type: string;
@@ -64,6 +92,15 @@ export interface Memory {
64
92
  // in isVisibleHere().
65
93
  repo?: string;
66
94
  repoPath?: string;
95
+ // Contradiction surface (POC, bench FINDINGS §4): a user-guided row may
96
+ // name the code symbol (ref) its value (claim) is about and who holds
97
+ // authority (klass). Injection reads the code at render time — deterministically,
98
+ // no model call — and a collision renders one CONFLICT line whose Action is
99
+ // fixed by the class: behavior class trusts the code, spec class fixes it.
100
+ // #345 measured the alternative: a wrong guided row rewrote correct code.
101
+ ref?: string;
102
+ claim?: string;
103
+ klass?: "spec" | "behavior";
67
104
  file: string;
68
105
  index: number;
69
106
  }