opencode-self-improvement 0.22.2 → 0.23.1

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/init/run.ts CHANGED
@@ -1,18 +1,14 @@
1
1
  // run — split from src/init.ts (#168 domain restructure). Declaration bodies are unchanged.
2
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):
3
+ // and record an init stamp keyed on git HEAD. Deterministic (no model calls):
4
4
  // manifests are parsed locally and every write goes through the 4-gate pipeline
5
5
  // with the `trusted` flag (plugin-authored bookkeeping, not model claims).
6
6
  // Degrades gracefully when git is absent, so install-from-scratch still writes
7
7
  // script memories. The codebase-memory graph integration was removed (#231).
8
+ // The stamp is a file under the memory root, not a memory row (#374): see
9
+ // src/init/stamp.ts for why a row was forgeable.
8
10
  import { basename } from "node:path";
9
- import { loadAll } from "../store/files/load.ts";
10
- import { markSuperseded } from "../store/files/supersede.ts";
11
- import {
12
- isVisibleTo,
13
- readerFromSid,
14
- type Reader,
15
- } from "../store/model/visibility.ts";
11
+ import { readerFromSid } from "../store/model/visibility.ts";
16
12
  import { runWriteGate, type GateContext } from "../gate/gate.ts";
17
13
  import { captureEvidenceContext, record } from "../evidence/record.ts";
18
14
  import { writeEvidence, hasGateCheck } from "../capture/triggers.ts";
@@ -25,6 +21,8 @@ import {
25
21
  gitHead,
26
22
  gitRootOf,
27
23
  } from "./detect.ts";
24
+ import { type RetagResult, retagQuarantinedRows } from "./retag.ts";
25
+ import { readStamp, writeStampFile } from "./stamp.ts";
28
26
 
29
27
  export interface InitArgs {
30
28
  liveRoot: string;
@@ -47,33 +45,18 @@ export interface InitSummary {
47
45
  blocked: number;
48
46
  /** Written rows whose write_promoted audit line fell (#155 review). */
49
47
  unaudited?: number;
50
- }
51
-
52
- export interface InitStamp {
53
- ts: string;
54
- head: string;
55
- }
56
-
57
- export async function initStamp(
58
- scope: string,
59
- sid?: string,
60
- reader: Reader = readerFromSid(sid),
61
- ): Promise<InitStamp | null> {
62
- // Scope is a basename, so two different repos can share one
63
- // ("api" next to "api", a fork beside its upstream). Visibility filtering
64
- // makes each repo see only its own stamp — basename collisions no longer
65
- // alias init state between repos. The reader comes from the CALLER's
66
- // session, not from the global current after this await (#127).
67
- const mems = (await loadAll()).filter(
68
- (m) => !m.superseded_by && isVisibleTo(m, reader),
69
- );
70
- for (const m of mems) {
71
- if (m.type !== "context" || m.scope !== scope) continue;
72
- if (!m.tags?.some((t) => t === "init-stamp")) continue;
73
- const head = /head=([^ ,]+)/.exec(m.content)?.[1] ?? "-";
74
- return { ts: m.ts, head };
75
- }
76
- return null;
48
+ /** The stamp file could not be written; init must be re-run (#374). */
49
+ stampError?: string;
50
+ /** True when a pre-#374 store row was honoured and copied to the file. */
51
+ stampMigrated?: boolean;
52
+ /**
53
+ * A honoured pre-#374 row is still active: its retirement did not land
54
+ * (#376 review). The migration itself is durable; the row is inert either
55
+ * way, and the operator hears about it instead of reading a clean migration.
56
+ */
57
+ stampRetireError?: string;
58
+ /** Pre-#372 rows re-tagged by the injection screen (#375). */
59
+ retag?: RetagResult;
77
60
  }
78
61
 
79
62
  export async function runInit(args: InitArgs): Promise<InitSummary> {
@@ -98,11 +81,43 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
98
81
  trusted: true,
99
82
  };
100
83
 
101
- const prior = await initStamp(scope, args.sessionID, reader);
84
+ // #375: repair rows written before #372 screened init's output. This runs
85
+ // BEFORE the stamp check on purpose — the common poisoned store belongs to a
86
+ // repository init has already stamped, and returning early would leave the
87
+ // poisoned row live forever. The scan is one store read and five regexes per
88
+ // row; writes happen only on a hit.
89
+ const retag = await retagQuarantinedRows(gateCtx);
90
+
91
+ // The stamp is read from (and written to) a file named for the repository
92
+ // identity key, never from a row a model could write (#374). The write target
93
+ // already holds that identity, so the common path spends no git probes here.
94
+ // Scope is still a basename, so two "api" checkouts stay apart: the key, not
95
+ // the name, decides which stamp a repository reads.
96
+ const stampKeyHint = writeAt.ok ? writeAt.scope?.key : undefined;
97
+ const {
98
+ stamp: prior,
99
+ key: stampKey,
100
+ migrated,
101
+ stampError: migrateStampError,
102
+ retireError,
103
+ } = await readStamp(scope, root, stampKeyHint, args.sessionID, reader);
102
104
  if (prior && !force && prior.head === head) {
103
105
  await record(
104
106
  "init_skip",
105
- { scope, head, since: prior.ts },
107
+ {
108
+ scope,
109
+ head,
110
+ since: prior.ts,
111
+ migrated: migrated || undefined,
112
+ // #376 review: a migration that honoured the row but could not write the
113
+ // file, or could not retire it, is a fault the skip line has to carry.
114
+ // Without it every later init re-migrates and re-claims success with no
115
+ // audit trail saying the file was never there.
116
+ stamp_error: migrateStampError,
117
+ stamp_retire_error: retireError,
118
+ retagged: retag.retagged || undefined,
119
+ retag_blocked: retag.blocked || undefined,
120
+ },
106
121
  false,
107
122
  args.sessionID,
108
123
  evidenceContext,
@@ -117,6 +132,10 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
117
132
  written: 0,
118
133
  collapsed: 0,
119
134
  blocked: 0,
135
+ stampError: migrateStampError,
136
+ stampMigrated: migrated || undefined,
137
+ stampRetireError: retireError,
138
+ retag,
120
139
  };
121
140
  }
122
141
 
@@ -159,31 +178,12 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
159
178
  else blocked++;
160
179
  }
161
180
 
162
- const stampContent = `Init stamp: repo=${scope}, head=${head}, scripts=${scripts.length}`;
163
- const stampOutcome = await runWriteGate(
164
- // Same screen as the script rows: the stamp interpolates the directory
165
- // basename, so an injection-shaped checkout name matches here too. Withheld
166
- // from recall, still readable by initStamp(), so idempotency is unaffected.
167
- quarantineCandidate({
168
- type: "context",
169
- scope,
170
- content: stampContent,
171
- tags: ["init-stamp"],
172
- }),
173
- gateCtx,
174
- );
175
- const stampTs = stampOutcome.ts ?? prior?.ts;
176
- if (stampOutcome.action === "promoted" && prior && stampOutcome.ts) {
177
- await markSuperseded(prior.ts, {
178
- superseded_by: stampOutcome.ts,
179
- reason: "init",
180
- });
181
- }
182
- if (
183
- stampOutcome.action === "promoted" &&
184
- stampOutcome.evidenceError !== undefined
185
- )
186
- unaudited++;
181
+ // The stamp is bookkeeping about this run, not a claim for the model to read,
182
+ // so it is a file rather than a gated row (#374). A fault is reported, never
183
+ // swallowed: the honest consequence is "init will run again", and saying so
184
+ // beats a stamp the operator believes was written.
185
+ const stampTs = new Date().toISOString();
186
+ const stampError = writeStampFile(stampKey, scope, root, head, stampTs);
187
187
 
188
188
  await record(
189
189
  "init_complete",
@@ -196,7 +196,21 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
196
196
  collapsed,
197
197
  blocked,
198
198
  unaudited,
199
- stamp: stampTs ?? "-",
199
+ stamp: stampError ? "-" : stampTs,
200
+ stamp_error: stampError,
201
+ // A migration that copied the row but could not retire it (#376 review).
202
+ stamp_retire_error: retireError,
203
+ migrated: migrated || undefined,
204
+ retagged: retag.retagged || undefined,
205
+ retag_blocked: retag.blocked || undefined,
206
+ retag_partial: retag.partial || undefined,
207
+ retag_failures: retag.failures.length
208
+ ? retag.failures.join("; ")
209
+ : undefined,
210
+ retag_remaining: retag.remaining || undefined,
211
+ retag_collateral: retag.collateral.length
212
+ ? retag.collateral.join(",")
213
+ : undefined,
200
214
  },
201
215
  false,
202
216
  args.sessionID,
@@ -208,11 +222,15 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
208
222
  root,
209
223
  head,
210
224
  scripts,
211
- stampTs,
225
+ stampTs: stampError ? (prior?.ts ?? undefined) : stampTs,
226
+ stampError,
227
+ stampMigrated: migrated || undefined,
228
+ stampRetireError: retireError,
212
229
  skipped: false,
213
230
  written,
214
231
  collapsed,
215
232
  blocked,
216
233
  unaudited,
234
+ retag,
217
235
  };
218
236
  }
@@ -0,0 +1,306 @@
1
+ // The init stamp: plugin-internal bookkeeping for /repo-init idempotency.
2
+ //
3
+ // It deliberately does NOT live in the memory store (#374). A store row is
4
+ // reachable through `memory_remember` and `memory_import`, and nothing reserved
5
+ // the `init-stamp` tag, so any session could write a `context` row naming the
6
+ // current short HEAD and make every later `memory_init` answer "Already
7
+ // initialized" for that commit — silently, with no line saying why. Moving the
8
+ // stamp to a file under the memory root that only src/init/ reads and writes
9
+ // closes that door, and it takes the row out of `memory_recall`, export and the
10
+ // viewer, where internal state was never meant to be read.
11
+ //
12
+ // A one-time migration keeps checkouts initialized by an older release from
13
+ // re-running init. Honouring "any row that looks like a stamp" is exactly the
14
+ // forgery this ticket removes, so the migration honours a legacy row only when an
15
+ // `init_complete` evidence line names its ts. Evidence is written only by the
16
+ // plugin's own record() — no tool hands a session a write path to it — so the
17
+ // pairing says a real init audited that row. A legacy row with no matching audit
18
+ // is ignored, and init re-runs: idempotent, cheap, and the safe answer to a
19
+ // provenance the plugin cannot check. A row that passes the pairing is copied to
20
+ // the file and then retired, and the head it is copied at is the head that
21
+ // evidence line names — never the head the row's own prose claims (#376 review).
22
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { memoryRoot } from "../core/config/paths.ts";
25
+ import { INIT_STAMP_TAG } from "../core/tags.ts";
26
+ import { preparePrivateFile, tightenDirectory } from "../core/permissions.ts";
27
+ import { parseLine } from "../core/logfmt/format.ts";
28
+ import { readLines } from "../core/logfmt/read.ts";
29
+ import { evidenceFileFor } from "../evidence/record.ts";
30
+ import { resolveRepo } from "../identity/repokey.ts";
31
+ import { loadAll } from "../store/files/load.ts";
32
+ import { markSuperseded } from "../store/files/supersede.ts";
33
+ import {
34
+ isVisibleTo,
35
+ readerFromSid,
36
+ type Reader,
37
+ } from "../store/model/visibility.ts";
38
+
39
+ export interface InitStamp {
40
+ ts: string;
41
+ head: string;
42
+ }
43
+
44
+ /** Where the stamps live. A sibling directory of the day files, never one of them. */
45
+ export function stampDir(): string {
46
+ return join(memoryRoot(), "init-stamps");
47
+ }
48
+
49
+ // The file name is the repository identity key: a 12-hex-char token derived from
50
+ // the normalized origin (or the normalized path when there is no origin), so it
51
+ // survives a re-clone and never aliases two checkouts that merely share a
52
+ // directory basename. Validated anyway — a component the plugin did not mint is
53
+ // not authority to write outside the stamp directory.
54
+ function stampPath(key: string): string | null {
55
+ if (!/^[0-9a-f]{12}$/.test(key)) return null;
56
+ return join(stampDir(), `${key}.json`);
57
+ }
58
+
59
+ /**
60
+ * A stamp file's contents, checked against the file it came from.
61
+ *
62
+ * `key` must equal the file name: the name is the repository identity, so a file
63
+ * that landed in the wrong slot (a hand-edited store, a copy from another
64
+ * checkout) is not this repository's stamp. `scope` and `path` are descriptive
65
+ * only — nothing here locates state from them — so they are not validated.
66
+ */
67
+ function parseStamp(raw: string, key: string): InitStamp | null {
68
+ let data: unknown;
69
+ try {
70
+ data = JSON.parse(raw);
71
+ } catch {
72
+ return null;
73
+ }
74
+ if (typeof data !== "object" || data === null) return null;
75
+ const {
76
+ ts,
77
+ head,
78
+ key: fileKey,
79
+ } = data as {
80
+ ts?: unknown;
81
+ head?: unknown;
82
+ key?: unknown;
83
+ };
84
+ if (typeof ts !== "string" || typeof head !== "string") return null;
85
+ if (!ts || !head) return null;
86
+ if (fileKey !== key) return null;
87
+ return { ts, head };
88
+ }
89
+
90
+ function readStampFile(key: string): InitStamp | null {
91
+ const path = stampPath(key);
92
+ if (!path) return null;
93
+ let raw: string;
94
+ try {
95
+ raw = readFileSync(path, "utf8");
96
+ } catch {
97
+ // Absent, unreadable, or a directory. A file that cannot be read is treated
98
+ // like no stamp at all: init is idempotent, so re-running it is cheap, while
99
+ // trusting a stamp the plugin cannot parse is not.
100
+ return null;
101
+ }
102
+ return parseStamp(raw, key);
103
+ }
104
+
105
+ /**
106
+ * The day files an `init_complete` line for this row could live in.
107
+ *
108
+ * `appendMemory` stamps the row with the millisecond it mints; `record()` writes
109
+ * the evidence line to whatever day it is when the line lands. An init that
110
+ * starts at 23:59:59.999 and finishes after midnight splits the pair across two
111
+ * day files, so the row's own day is not enough — the following day has to be
112
+ * read too, or that migration is silently lost every night around midnight
113
+ * (#376 review).
114
+ */
115
+ function auditDays(ts: string): string[] {
116
+ const day = /^(\d{4}-\d{2}-\d{2})T/.exec(ts)?.[1];
117
+ if (!day) return [];
118
+ const next = new Date(`${day}T12:00:00.000Z`);
119
+ if (Number.isNaN(next.getTime())) return [day];
120
+ next.setUTCDate(next.getUTCDate() + 1);
121
+ return [day, next.toISOString().slice(0, 10)];
122
+ }
123
+
124
+ /**
125
+ * Did a real init audit this row, and at which head? The pre-#374 run wrote
126
+ * `stamp=<row ts>` and `head=<head>` into its `init_complete` evidence line, so
127
+ * the pairing is the provenance the row itself cannot supply. Parsed
128
+ * field-by-field: a value that merely contains the text cannot satisfy it.
129
+ *
130
+ * The head comes from the EVIDENCE LINE, never from the row's prose (#376
131
+ * review). `appendMemory` mints `ts` at millisecond resolution and `runInit`
132
+ * mints its stamp timestamp the same way, so two concurrent writes can land on
133
+ * the same millisecond — 42 of 480 rows did in the review's probe. Pairing on
134
+ * `stamp === ts` alone would then let a row that names one head retire a
135
+ * repository's idempotency at a different head, which is the forgery #374 was
136
+ * opened to close. Returns null when no line names this ts with a usable head.
137
+ */
138
+ async function initAuditHead(ts: string): Promise<string | null> {
139
+ for (const day of auditDays(ts)) {
140
+ const file = evidenceFileFor(day);
141
+ if (!file) continue;
142
+ let lines: string[];
143
+ try {
144
+ lines = await readLines(file);
145
+ } catch {
146
+ continue;
147
+ }
148
+ for (const line of lines) {
149
+ const fields = parseLine(line);
150
+ if (!fields) continue;
151
+ if (fields.ev !== "init_complete" || fields.stamp !== ts) continue;
152
+ const head = fields.head;
153
+ if (typeof head !== "string" || !head) continue;
154
+ return head;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ /** The pre-#374 stamp: a `context` row in this scope tagged `init-stamp`. */
161
+ async function legacyStampRow(
162
+ scope: string,
163
+ reader: Reader,
164
+ ): Promise<InitStamp | null> {
165
+ const mems = (await loadAll()).filter(
166
+ (m) => !m.superseded_by && isVisibleTo(m, reader),
167
+ );
168
+ for (const m of mems) {
169
+ if (m.type !== "context" || m.scope !== scope) continue;
170
+ if (!m.tags?.some((t) => t === INIT_STAMP_TAG)) continue;
171
+ const head = await initAuditHead(m.ts);
172
+ if (head === null) continue;
173
+ return { ts: m.ts, head };
174
+ }
175
+ return null;
176
+ }
177
+
178
+ export interface StampRead {
179
+ stamp: InitStamp | null;
180
+ /** The repository identity key the stamp file is (or would be) named for. */
181
+ key: string;
182
+ /** True when a pre-#374 store row was honoured and copied to the file. */
183
+ migrated: boolean;
184
+ /**
185
+ * The migration copy could not be written (#376 review). The row was still
186
+ * honoured, so init stays idempotent for this run, but nothing was recorded:
187
+ * the caller must report it the way a failed stamp write is reported, or every
188
+ * later init re-migrates and re-claims success.
189
+ */
190
+ stampError?: string;
191
+ /**
192
+ * The honoured row is still active (#376 review): its retirement was refused
193
+ * or threw. The migration is not lost — the file answers the next read — but
194
+ * the store keeps a row the operator should hear about.
195
+ */
196
+ retireError?: string;
197
+ }
198
+
199
+ /**
200
+ * The stamp for one repository.
201
+ *
202
+ * `root` is the repository root init resolved. `keyHint` is the identity the
203
+ * caller already holds (its write target), so a normal init pays no second pair
204
+ * of git probes; with neither, identity is resolved from `root`.
205
+ *
206
+ * Order: the file, then one audited legacy row (honoured once, then migrated).
207
+ * Returns `stamp: null` when neither applies.
208
+ */
209
+ export async function readStamp(
210
+ scope: string,
211
+ root: string,
212
+ keyHint?: string,
213
+ sid?: string,
214
+ reader: Reader = readerFromSid(sid),
215
+ ): Promise<StampRead> {
216
+ const key =
217
+ keyHint && /^[0-9a-f]{12}$/.test(keyHint) ? keyHint : resolveRepo(root).key;
218
+ const file = readStampFile(key);
219
+ if (file) return { stamp: file, key, migrated: false };
220
+ const legacy = await legacyStampRow(scope, reader);
221
+ if (!legacy) return { stamp: null, key, migrated: false };
222
+ const stampError = writeStampFile(key, scope, root, legacy.head, legacy.ts);
223
+ return {
224
+ stamp: legacy,
225
+ key,
226
+ migrated: true,
227
+ ...(stampError ? { stampError } : {}),
228
+ ...(await retireLegacyStampRow(legacy.ts)),
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Retire the row a migration just copied (#376 review). The stamp lives in the
234
+ * file now, so leaving the row active would keep a piece of plugin bookkeeping in
235
+ * the store as an ordinary row; `isInjectable` already withholds the tag from
236
+ * every model-facing read, and this takes it out of the store's active set too.
237
+ *
238
+ * A refusal never undoes the migration: the copy above is what makes init
239
+ * idempotent, and the row is inert either way. The reason is returned for the
240
+ * caller to report, in the same shape retag.ts uses for a retirement that did
241
+ * not land — the operator hears which half failed instead of reading a clean
242
+ * migration.
243
+ */
244
+ async function retireLegacyStampRow(
245
+ ts: string,
246
+ ): Promise<{ retireError?: string }> {
247
+ try {
248
+ const retired = await markSuperseded(ts, {
249
+ superseded_by: "init-stamp-file",
250
+ reason: "init",
251
+ });
252
+ if (retired) return {};
253
+ // Idempotence means the row was already retired out of band, or it is gone.
254
+ // Either way the store did not take the retirement this run asked for.
255
+ return { retireError: `${ts}: retirement did not land` };
256
+ } catch (err) {
257
+ return {
258
+ retireError: `${ts}: ${
259
+ err instanceof Error && err.message ? err.message : String(err)
260
+ }`,
261
+ };
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Record that `scope` was initialized at `head`.
267
+ *
268
+ * Best-effort by contract: a store on a read-only mount must not fail an init
269
+ * whose command rows already landed, so a fault is returned for the caller to
270
+ * report rather than thrown. The consequence of a fault is one re-run of an
271
+ * idempotent command, never a silently skipped init.
272
+ */
273
+ export function writeStampFile(
274
+ key: string,
275
+ scope: string,
276
+ root: string,
277
+ head: string,
278
+ ts: string,
279
+ ): string | undefined {
280
+ const path = stampPath(key);
281
+ if (!path) return "stamp key is not a repository identity token";
282
+ try {
283
+ mkdirSync(stampDir(), { recursive: true, mode: 0o700 });
284
+ tightenDirectory(stampDir());
285
+ preparePrivateFile(path);
286
+ // Per-call temp name (#89): two inits on one store must never rename each
287
+ // other's half-written temp over a stamp.
288
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
289
+ writeFileSync(
290
+ tmp,
291
+ `${JSON.stringify({ key, scope, path: root, head, ts })}\n`,
292
+ {
293
+ mode: 0o600,
294
+ },
295
+ );
296
+ renameSync(tmp, path);
297
+ return undefined;
298
+ } catch (err) {
299
+ return err instanceof Error && err.message ? err.message : String(err);
300
+ }
301
+ }
302
+
303
+ /** The identity key init stamps a repository under (exported for tests). */
304
+ export function stampKey(root: string): string {
305
+ return resolveRepo(root).key;
306
+ }
@@ -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
  }
@@ -1,4 +1,5 @@
1
1
  // predicates — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
2
+ import { INIT_STAMP_TAG } from "../../core/tags.ts";
2
3
  import { isQuarantined } from "../quarantine/quarantine.ts";
3
4
  import type { Memory } from "./memory.ts";
4
5
 
@@ -7,6 +8,17 @@ export function isActive(m: Memory): boolean {
7
8
  }
8
9
 
9
10
  // Quarantine remains durable and reviewable; only model-facing reads withhold it.
11
+ // The legacy `init-stamp` tag joins it (#376 review). A pre-#374 stamp row is
12
+ // plugin bookkeeping, and migration only retires a row whose `init_complete`
13
+ // audit line survives; in a store where that line is gone the row stays active
14
+ // forever, so the tag itself has to keep it off the prompt. This is the one
15
+ // predicate every model-facing read uses, so injection, recall, list, digest and
16
+ // the capture context all withhold it together. Store reads that are NOT
17
+ // model-facing — the viewer, memory_forget, memory_undo, export — still see it.
10
18
  export function isInjectable(m: Memory): boolean {
11
- return isActive(m) && !isQuarantined(m);
19
+ return (
20
+ isActive(m) &&
21
+ !isQuarantined(m) &&
22
+ m.tags?.includes(INIT_STAMP_TAG) !== true
23
+ );
12
24
  }
@@ -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
+ }
package/src/tools/init.ts CHANGED
@@ -19,7 +19,7 @@ export const register: ToolRegister = (editor, deps) => {
19
19
  validated(InitArgs, {
20
20
  name: "memory_init",
21
21
  description:
22
- "Initialize repository memory: re-derives build/lint/test/typecheck command memories through the write gate and stores an init stamp keyed on git HEAD. Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
22
+ "Initialize repository memory: re-derives build/lint/test/typecheck command memories through the write gate and records an init stamp keyed on git HEAD. The stamp is plugin bookkeeping under <memory-root>/init-stamps/, not a memory row, so no session can forge it (#374). Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
23
23
  options: direct,
24
24
  async execute(args, context): Promise<{ content: string }> {
25
25
  const { sid } = toolIds(context);