opencode-self-improvement 0.22.1 → 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/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",
@@ -1,6 +1,5 @@
1
1
  // GATE-1 resolver. Extracts embedded path/symbol refs from a memory/evidence
2
- // candidate and re-resolves them against the live source tree (and, when
3
- // OPENCODE_CBM_BIN is set, the codebase-memory-mcp file graph). Deterministic:
2
+ // candidate and re-resolves them against the live source tree. Deterministic:
4
3
  // regex + balanced-paren scanning, no model involvement.
5
4
  import { join } from "node:path";
6
5
  import { opendir } from "node:fs/promises";
@@ -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,15 +1,14 @@
1
1
  // detect — split from src/init.ts (#168 domain restructure). Declaration bodies are unchanged.
2
- // Repository init: ensure the codebase-memory graph exists for this repo and
3
- // re-derive build/test command memories through the write gate. Deterministic
4
- // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
5
- // are parsed locally, and every write goes through the 4-gate pipeline with the
6
- // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
7
- // gracefully when the binary or git is absent, so install-from-scratch still
8
- // writes script memories.
2
+ // Repository init: re-derive build/test command memories through the write gate.
3
+ // Deterministic (no model calls): manifests are parsed locally and every write
4
+ // goes through the 4-gate pipeline with the `trusted` flag (plugin-authored
5
+ // bookkeeping, not model claims). Degrades gracefully when git is absent, so
6
+ // install-from-scratch still writes script memories.
7
+ // The codebase-memory graph integration was removed (#231): no read or gate
8
+ // path ever consumed the index, and spawning a pinned third-party binary in
9
+ // the user's repository was a supply-chain surface with no consumer.
9
10
  import { join } from "node:path";
10
11
  import { existsSync } from "node:fs";
11
- import { cbmBin } from "../core/config/paths.ts";
12
- import { run } from "./run.ts";
13
12
 
14
13
  export interface ScriptRecord {
15
14
  key: string;
@@ -17,15 +16,6 @@ export interface ScriptRecord {
17
16
  source: string;
18
17
  }
19
18
 
20
- export interface GraphStatus {
21
- // "disabled": graph indexing is opt-in (OPENCODE_MEMORY_GRAPH=1) and was
22
- // not requested — the default. No spawn occurs and nothing is lost: no
23
- // read or gate path consumes the index (see #323).
24
- action: "disabled" | "indexed" | "unavailable" | "index-failed";
25
- name?: string;
26
- mode: string;
27
- }
28
-
29
19
  const NOTABLE_KEYS = [
30
20
  "test",
31
21
  "e2e",
@@ -146,62 +136,3 @@ export async function detectScripts(root: string): Promise<ScriptRecord[]> {
146
136
  await detectLangManifests(root, records);
147
137
  return records.slice(0, 8);
148
138
  }
149
-
150
- async function cbmProject(
151
- bin: string,
152
- root: string,
153
- ): Promise<{ name: string } | null> {
154
- const r = await run(
155
- [
156
- bin,
157
- "cli",
158
- "--quiet",
159
- "list_projects",
160
- "--format",
161
- "json",
162
- "--metadata-only",
163
- ],
164
- root,
165
- );
166
- if (!r.ok || !r.out) return null;
167
- try {
168
- const env = JSON.parse(r.out) as {
169
- projects?: { name: string; root_path: string }[];
170
- };
171
- const hit = env.projects?.find((p) => p.root_path === root);
172
- return hit ? { name: hit.name } : null;
173
- } catch {
174
- return null;
175
- }
176
- }
177
-
178
- export async function ensureGraph(
179
- root: string,
180
- mode: string,
181
- force: boolean,
182
- ): Promise<GraphStatus> {
183
- const bin = cbmBin() ?? "codebase-memory-mcp";
184
- const existing = await cbmProject(bin, root);
185
- if (existing && !force)
186
- return { action: "indexed", name: existing.name, mode };
187
- const r = await run(
188
- [
189
- bin,
190
- "cli",
191
- "--quiet",
192
- "index_repository",
193
- "--repo-path",
194
- root,
195
- "--mode",
196
- mode,
197
- ],
198
- root,
199
- );
200
- if (!r.ok) return { action: "unavailable", mode };
201
- const after = await cbmProject(bin, root);
202
- return {
203
- action: after ? "indexed" : "index-failed",
204
- name: after?.name,
205
- mode,
206
- };
207
- }
@@ -1,12 +1,6 @@
1
1
  // format — split from src/init.ts (#168 domain restructure). Declaration bodies are unchanged.
2
- // Repository init: ensure the codebase-memory graph exists for this repo and
3
- // re-derive build/test command memories through the write gate. Deterministic
4
- // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
5
- // are parsed locally, and every write goes through the 4-gate pipeline with the
6
- // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
7
- // gracefully when the binary or git is absent, so install-from-scratch still
8
- // writes script memories.
9
- import { join } from "node:path";
2
+ // Repository init: renders the runInit summary for the tool reply. The
3
+ // codebase-memory graph line is gone with the graph integration (#231).
10
4
  import { type InitSummary } from "./run.ts";
11
5
 
12
6
  export function formatInit(s: InitSummary): string {
@@ -16,7 +10,6 @@ export function formatInit(s: InitSummary): string {
16
10
  const scr = s.scripts.map((r) => `- ${r.source}: "${r.cmd}"`).join("\n");
17
11
  return [
18
12
  `Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
19
- `Graph: ${s.graph.action}${s.graph.name ? ` (${s.graph.name})` : ""} [mode=${s.graph.mode}]`,
20
13
  scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
21
14
  `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
22
15
  (s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
package/src/init/run.ts CHANGED
@@ -1,12 +1,10 @@
1
1
  // run — split from src/init.ts (#168 domain restructure). Declaration bodies are unchanged.
2
- // Repository init: re-derive build/test command memories through the write
3
- // gate, and — only when opted in via OPENCODE_MEMORY_GRAPH=1 (#323) — ensure
4
- // the codebase-memory graph exists for this repo. Deterministic
5
- // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
6
- // are parsed locally, and every write goes through the 4-gate pipeline with the
7
- // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
8
- // gracefully when the binary or git is absent, so install-from-scratch still
9
- // writes script memories.
2
+ // Repository init: re-derive build/test command memories through the write gate
3
+ // and store an init stamp keyed on git HEAD. Deterministic (no model calls):
4
+ // manifests are parsed locally and every write goes through the 4-gate pipeline
5
+ // with the `trusted` flag (plugin-authored bookkeeping, not model claims).
6
+ // Degrades gracefully when git is absent, so install-from-scratch still writes
7
+ // script memories. The codebase-memory graph integration was removed (#231).
10
8
  import { basename } from "node:path";
11
9
  import { loadAll } from "../store/files/load.ts";
12
10
  import { markSuperseded } from "../store/files/supersede.ts";
@@ -20,13 +18,10 @@ import { captureEvidenceContext, record } from "../evidence/record.ts";
20
18
  import { writeEvidence, hasGateCheck } from "../capture/triggers.ts";
21
19
  import { writeTarget } from "../identity/repokey.ts";
22
20
  import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
23
- import { graphEnabled } from "../core/config/paths.ts";
24
21
  import { getCurrent } from "../core/state.ts";
25
22
  import {
26
- type GraphStatus,
27
23
  type ScriptRecord,
28
24
  detectScripts,
29
- ensureGraph,
30
25
  gitHead,
31
26
  gitRootOf,
32
27
  } from "./detect.ts";
@@ -34,7 +29,6 @@ import {
34
29
  export interface InitArgs {
35
30
  liveRoot: string;
36
31
  force?: boolean;
37
- mode?: string;
38
32
  // The calling session (#127): rows this writes are stamped for the CALLER,
39
33
  // resolved after runInit's own awaits (git probing) rather than from the
40
34
  // ambient current, which a concurrent session may have moved.
@@ -45,7 +39,6 @@ export interface InitSummary {
45
39
  scope: string;
46
40
  root: string;
47
41
  head: string;
48
- graph: GraphStatus;
49
42
  scripts: ScriptRecord[];
50
43
  stampTs?: string;
51
44
  skipped: boolean;
@@ -56,23 +49,6 @@ export interface InitSummary {
56
49
  unaudited?: number;
57
50
  }
58
51
 
59
- export async function run(
60
- cmd: string[],
61
- cwd: string,
62
- ): Promise<{ ok: boolean; out: string }> {
63
- try {
64
- const p = Bun.spawn(cmd, { cwd, stdout: "pipe", stderr: "pipe" });
65
- const [so, se] = await Promise.all([
66
- new Response(p.stdout).text(),
67
- new Response(p.stderr).text(),
68
- ]);
69
- const code = await p.exited;
70
- return { ok: code === 0, out: (so || se || "").trim() };
71
- } catch {
72
- return { ok: false, out: "" };
73
- }
74
- }
75
-
76
52
  export interface InitStamp {
77
53
  ts: string;
78
54
  head: string;
@@ -108,7 +84,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
108
84
  const scope = basename(root) || basename(args.liveRoot);
109
85
  const head = await gitHead(root);
110
86
  const force = Boolean(args.force);
111
- const mode = args.mode ?? "moderate";
112
87
 
113
88
  const gateCtx: GateContext = {
114
89
  liveRoot: root,
@@ -136,11 +111,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
136
111
  scope,
137
112
  root,
138
113
  head,
139
- // A skipped init reports what THIS build would do, not what the prior
140
- // stamp's build did: on a disabled build nothing is indexed (#323).
141
- graph: graphEnabled()
142
- ? { action: "indexed", mode }
143
- : { action: "disabled", mode },
144
114
  scripts: [],
145
115
  stampTs: prior.ts,
146
116
  skipped: true,
@@ -152,19 +122,12 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
152
122
 
153
123
  await record(
154
124
  "init_start",
155
- { scope, head, force, mode },
125
+ { scope, head, force },
156
126
  false,
157
127
  args.sessionID,
158
128
  evidenceContext,
159
129
  );
160
130
 
161
- // Graph indexing is opt-in (#323). Measured on the benchmark: 11.5-26s per
162
- // init on the first-write critical path, it failed in 29 of 32 real inits,
163
- // and no read or gate path consumes the index (gate evidence is identical
164
- // with it present or absent). Skip the spawn unless explicitly requested.
165
- const graph: GraphStatus = graphEnabled()
166
- ? await ensureGraph(root, mode, force)
167
- : { action: "disabled", mode };
168
131
  const scripts = await detectScripts(root);
169
132
 
170
133
  let written = 0;
@@ -196,7 +159,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
196
159
  else blocked++;
197
160
  }
198
161
 
199
- const stampContent = `Init stamp: repo=${scope}, head=${head}, graph=${graph.action}, mode=${graph.mode}, scripts=${scripts.length}`;
162
+ const stampContent = `Init stamp: repo=${scope}, head=${head}, scripts=${scripts.length}`;
200
163
  const stampOutcome = await runWriteGate(
201
164
  // Same screen as the script rows: the stamp interpolates the directory
202
165
  // basename, so an injection-shaped checkout name matches here too. Withheld
@@ -228,8 +191,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
228
191
  scope,
229
192
  head,
230
193
  force,
231
- mode,
232
- graph: graph.action,
233
194
  scripts: scripts.length,
234
195
  written,
235
196
  collapsed,
@@ -246,7 +207,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
246
207
  scope,
247
208
  root,
248
209
  head,
249
- graph,
250
210
  scripts,
251
211
  stampTs,
252
212
  skipped: false,
@@ -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
  }