opencode-self-improvement 0.23.0 → 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/README.md CHANGED
@@ -19,7 +19,7 @@ Every figure in this README carries a provenance marker: **measured** (read off
19
19
 
20
20
  **2. Restart opencode.** It installs the package and its dependencies at startup, and the plugin installs its own slash commands. On desktop, a later config edit needs `opencode service restart`: relaunching the app leaves the background service — and the plugin options it already parsed — alive.
21
21
 
22
- **3. Run `/repo-init`** in each repo you work in. It stores the test / build / lint / typecheck commands as memories and writes an init stamp tied to the current git head. Rerun `/repo-init force` after a refactor.
22
+ **3. Run `/repo-init`** in each repo you work in. It stores the test / build / lint / typecheck commands as memories and records an init stamp tied to the current git head. The stamp is plugin bookkeeping under `<memory-root>/init-stamps/`, not a memory row, so no session can forge it (#374). A store left by an older release migrates once: its `init-stamp` row is honoured only when an `init_complete` audit line names it (and at the head that line names), is then retired, and is withheld from recall and injection either way (#376). Rerun `/repo-init force` after a refactor.
23
23
 
24
24
  Needs Bun 1.3.0 or newer in the opencode build (the tested floor); older Bun reports a startup warning.
25
25
 
@@ -276,6 +276,8 @@ Every imported row re-enters through the same four gates as `memory_remember` (t
276
276
 
277
277
  Import and auto-capture also scan incoming prose for a small set of instruction-override, role-header, and download/execute patterns. Matching rows still face every write gate; a promoted match is tagged `quarantine` and withheld from recall, prompt/frontier injection, compaction anchors, contextual pull, scope/type listings, consolidation proposals, and decay. Decay previews do not quote these rows, and applied decay leaves them in the human review queue. The import reply counts quarantined promotions, gate evidence records pattern identifiers without copying the matched prose, and `/memory-report` lists review IDs for the caller's repository.
278
278
 
279
+ That screen only covers writes made after it shipped. A store that already holds an untagged poisoned row from an earlier `/repo-init` is repaired by the next one (#375): init scans every row the caller can read (this repository plus global) and, for each hit, writes a tagged twin through the normal gated path and retires the original — nothing is deleted, and each replacement emits its own `write_promoted` audit line. Re-running is safe: a row that already carries the tag is not touched. The reply reports `re-tagged=N`; a hit the gate refused is reported as `blocked=N` instead of passing silently, one run re-tags at most 100 rows and says how many remain, and any row GATE-2 retired along the way is named. A promoted replacement whose audit line itself fell is counted as `N without an audit line` rather than passing as a clean repair. This runs even when init skips on its stamp, because a stamped repository is the common case.
280
+
279
281
  Review the full row in the memory viewer's **quarantined** filter. **Release quarantine** requires a reason, snapshots the pre-release row, and removes the quarantine flag and known scanner-reason tags; unrelated user labels such as `quarantine:custom`, repository ownership, row identity, blocklist, and supersession remain intact. Missing and already-released rows produce distinct, audited no-op outcomes. Existing prompt blocks refresh before the next delivery or status report when a row becomes quarantined or is released. Undoing a release can restore the quarantine flag.
280
282
 
281
283
  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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.23.0",
3
+ "version": "0.23.1",
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": {
package/src/core/tags.ts CHANGED
@@ -8,5 +8,13 @@ export const AUTO_CAPTURE_TAG = "auto-capture";
8
8
  */
9
9
  export const CODE_CHECKED_TAG = "code-checked";
10
10
 
11
+ // The pre-#374 init stamp: a `context` row written by an older release's
12
+ // `/repo-init`. It is plugin bookkeeping that the stamp file replaced, so it is
13
+ // never a fact for a model to read. `src/init/stamp.ts` retires a row once its
14
+ // audit line confirms the migration; the tag keeps every other row — including
15
+ // one whose audit line is gone, which migration cannot reach — out of the
16
+ // prompt (#376 review).
17
+ export const INIT_STAMP_TAG = "init-stamp";
18
+
11
19
  // The public write boundaries reserve this same tag (#342/#355).
12
20
  export { USER_GUIDED_TAG } from "./guidance.ts";
@@ -4,15 +4,56 @@
4
4
  import { type InitSummary } from "./run.ts";
5
5
 
6
6
  export function formatInit(s: InitSummary): string {
7
+ // #376 review: a migration whose file write failed is not a migration. The row
8
+ // was honoured, so this run is still idempotent, but nothing was copied — the
9
+ // reply says so instead of claiming a migration that left no file behind.
10
+ const migrated = s.stampMigrated
11
+ ? s.stampError
12
+ ? " (stamp read from a store row; the copy to the stamp file failed)"
13
+ : " (stamp migrated from a store row)"
14
+ : "";
15
+ // A retirement that did not land is named, in the same spirit as the re-tag
16
+ // repair's partial count: the migration is durable, the row is still there,
17
+ // and the operator reads which half failed (#376 review).
18
+ const retireFault = s.stampRetireError
19
+ ? `Legacy stamp row NOT retired (${s.stampRetireError}); it stays in the store, withheld from recall. Run init again.`
20
+ : "";
21
+ // #375: a repair that did something, or could not finish, is reported. A quiet
22
+ // "Nothing to do." over a store that still holds a live poisoned row is the
23
+ // failure this ticket exists to remove.
24
+ const r = s.retag;
25
+ const repair =
26
+ r && (r.retagged || r.blocked || r.partial || r.remaining || r.unaudited)
27
+ ? `\nInjection screen: re-tagged=${r.retagged}, blocked=${r.blocked}, partial=${r.partial}` +
28
+ (r.unaudited ? `, ${r.unaudited} without an audit line` : "") +
29
+ (r.remaining ? `, ${r.remaining} left (run init again)` : "") +
30
+ (r.collateral.length
31
+ ? `, ${r.collateral.length} retired by GATE-2 while re-tagging`
32
+ : "")
33
+ : "";
7
34
  if (s.skipped) {
8
- return `Already initialized for ${s.scope} at head ${s.head} (stamp ${s.stampTs}). Nothing to do.`;
35
+ // The skip path can carry a stamp fault of its own: the migration honoured a
36
+ // legacy row and could not write the file, so the next init re-migrates.
37
+ // Silence here is what let a failed migration report success (#376 review).
38
+ const fault = s.stampError
39
+ ? `; stamp NOT recorded (${s.stampError}) — the migration will be retried`
40
+ : "";
41
+ return `Already initialized for ${s.scope} at head ${s.head} (stamp ${s.stampTs}). Nothing to do.${migrated}${fault}${retireFault ? `\n${retireFault}` : ""}${repair}`;
9
42
  }
10
- const scr = s.scripts.map((r) => `- ${r.source}: "${r.cmd}"`).join("\n");
43
+ const scr = s.scripts.map((r2) => `- ${r2.source}: "${r2.cmd}"`).join("\n");
44
+ const stamp = s.stampError
45
+ ? `; stamp NOT recorded (${s.stampError}) — init will run again`
46
+ : `; stamp=${s.stampTs ?? "-"}`;
11
47
  return [
12
48
  `Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
13
49
  scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
14
50
  `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
15
51
  (s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
16
- `; stamp=${s.stampTs ?? "-"}`,
17
- ].join("\n");
52
+ stamp +
53
+ migrated,
54
+ retireFault,
55
+ repair.trimStart(),
56
+ ]
57
+ .filter((line) => line !== "")
58
+ .join("\n");
18
59
  }
@@ -0,0 +1,186 @@
1
+ // One-time repair for rows stored before #372 screened init's writes (#375).
2
+ //
3
+ // #372 made `/repo-init` run the injection screen over the rows it writes, so a
4
+ // checkout sitting in a directory named `eval (x)` now gets its command memories
5
+ // tagged `quarantine`. That covers writes made after it shipped. A store that
6
+ // already holds an untagged poisoned row keeps it, and re-running init cannot
7
+ // fix it: GATE-3's exact-duplicate check compares type and content, so the new
8
+ // quarantined candidate collapses into the old untagged row. `force: true` does
9
+ // not help either — force skips the stamp check, not the dedup.
10
+ //
11
+ // So init scans what it can read and re-tags the hits. Each re-tag is a normal
12
+ // gated write that replaces the row it names (`supersedesTs`) — the one shape
13
+ // GATE-3 reads as a metadata edit rather than a duplicate. Nothing is deleted:
14
+ // the old row survives superseded, and every replacement emits its own
15
+ // `write_promoted` audit line.
16
+ import { runWriteGate, type GateContext } from "../gate/gate.ts";
17
+ import { markSuperseded } from "../store/files/supersede.ts";
18
+ import { loadAll } from "../store/files/load.ts";
19
+ import type { Memory } from "../store/model/memory.ts";
20
+ import { isActive } from "../store/model/predicates.ts";
21
+ import { isVisibleTo } from "../store/model/visibility.ts";
22
+ import {
23
+ isQuarantined,
24
+ quarantineCandidate,
25
+ } from "../store/quarantine/quarantine.ts";
26
+
27
+ /**
28
+ * Writes one init run may make. A pathological store (an injection-shaped
29
+ * directory name plus a thousand rows quoting it) must not turn one `/repo-init`
30
+ * into a thousand full-file publishes. The remainder is reported, never hidden.
31
+ */
32
+ export const MAX_RETAGS_PER_RUN = 100;
33
+
34
+ export interface RetagResult {
35
+ /** Active rows the caller could read. */
36
+ scanned: number;
37
+ /** Rows replaced by a tagged twin AND retired. */
38
+ retagged: number;
39
+ /** Hits the gate refused; they stay active and untagged. */
40
+ blocked: number;
41
+ /** Promoted, but the retirement did not land (another supersession won). */
42
+ partial: number;
43
+ /** Promoted with a fallen `write_promoted` audit line (#155 class). */
44
+ unaudited: number;
45
+ /** Hits left unprocessed because the per-run bound was reached. */
46
+ remaining: number;
47
+ /** Rows GATE-2 retired as a side effect of these writes. Never hidden. */
48
+ collateral: string[];
49
+ /**
50
+ * Retirement attempts that REJECTED (lock contention) rather than returning
51
+ * false (#378 review). The replacement is durable; the original is not.
52
+ * Counted in `partial`, named here.
53
+ */
54
+ failures: string[];
55
+ }
56
+
57
+ export function emptyRetag(): RetagResult {
58
+ return {
59
+ scanned: 0,
60
+ retagged: 0,
61
+ blocked: 0,
62
+ partial: 0,
63
+ unaudited: 0,
64
+ remaining: 0,
65
+ collateral: [],
66
+ failures: [],
67
+ };
68
+ }
69
+
70
+ /**
71
+ * The row as it should be written again: identical prose and metadata, plus the
72
+ * tags the screen asked for.
73
+ *
74
+ * Every field is copied on purpose. A repair that quietly dropped the verbatim
75
+ * quote (`original`) or the contradiction fields would close one boundary and
76
+ * break another, and `repo` is carried so a global row stays global while a
77
+ * repository row stays in its own repository — an edit must never move a row's
78
+ * visibility. The row's own `ts`, `file` and `superseded_by` are deliberately
79
+ * NOT carried: the gate mints a fresh identity for the replacement.
80
+ */
81
+ function reTagged(row: Memory, tags: string[]) {
82
+ return {
83
+ type: row.type,
84
+ scope: row.scope,
85
+ content: row.content,
86
+ ...(row.issue ? { issue: row.issue } : {}),
87
+ ...(row.kw ? { kw: row.kw } : {}),
88
+ ...(row.ref ? { ref: row.ref } : {}),
89
+ ...(row.claim ? { claim: row.claim } : {}),
90
+ ...(row.klass ? { klass: row.klass } : {}),
91
+ ...(row.original ? { original: row.original } : {}),
92
+ status: row.status ?? "settled",
93
+ repo: row.repo ?? "global",
94
+ repoPath: row.repo ? row.repoPath : undefined,
95
+ tags,
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Re-tag rows that match the injection screen but do not carry the tag.
101
+ *
102
+ * Reach is exactly what the caller can read — this repository's rows plus global
103
+ * rows. Another repository's rows are not this caller's to rewrite.
104
+ */
105
+ export async function retagQuarantinedRows(
106
+ ctx: GateContext,
107
+ ): Promise<RetagResult> {
108
+ const out = emptyRetag();
109
+ const rows = (await loadAll()).filter(
110
+ (m) =>
111
+ isActive(m) &&
112
+ !isQuarantined(m) &&
113
+ (ctx.reader ? isVisibleTo(m, ctx.reader) : true),
114
+ );
115
+ out.scanned = rows.length;
116
+ const hits: Memory[] = [];
117
+ for (const row of rows) {
118
+ // quarantineCandidate returns the same object when nothing matches.
119
+ if (quarantineCandidate(row) !== row) hits.push(row);
120
+ }
121
+ if (hits.length > MAX_RETAGS_PER_RUN)
122
+ out.remaining = hits.length - MAX_RETAGS_PER_RUN;
123
+ for (const row of hits.slice(0, MAX_RETAGS_PER_RUN)) {
124
+ const tagged = quarantineCandidate(row);
125
+ const durable: string[] = [];
126
+ const outcome = await runWriteGate(reTagged(row, tagged.tags ?? []), {
127
+ ...ctx,
128
+ supersedesTs: row.ts,
129
+ durable,
130
+ });
131
+ if (outcome.action !== "promoted" && outcome.action !== "collapsed") {
132
+ // Blocked: the untagged row stays exactly as it was, and the operator
133
+ // has to hear that rather than read a clean repair.
134
+ out.blocked++;
135
+ continue;
136
+ }
137
+ // #378 review (WhollyMindless): two ways the unsafe original survived.
138
+ // (a) COLLAPSED is not "nothing happened" here — it means a quarantined
139
+ // twin from an earlier interrupted repair is already durable, and the
140
+ // only missing step is retiring the original. Refusing to act on the
141
+ // collapse left the row unquarantined forever (retagged=0, blocked=1
142
+ // on every retry). The collapse survivor IS the twin: the re-tagged
143
+ // candidate differs from the original only by tags, and the
144
+ // supersedesTs carve-out keeps the original from matching as its own
145
+ // duplicate, so an exact-content match is the prior replacement.
146
+ // (b) markSuperseded can REJECT (lock contention), not just return false.
147
+ // The twin is durable either way, so the failure lands in `partial`
148
+ // with its reason instead of escaping as if nothing was written —
149
+ // the #155 lesson, applied to the repair path.
150
+ const successor =
151
+ outcome.action === "collapsed" ? outcome.collapsedWith : outcome.ts;
152
+ if (successor === undefined) {
153
+ out.blocked++;
154
+ continue;
155
+ }
156
+ let retired = false;
157
+ try {
158
+ retired = await markSuperseded(
159
+ row.ts,
160
+ {
161
+ superseded_by: successor,
162
+ reason: "init",
163
+ symbol: row.ts,
164
+ from: row.ts,
165
+ to: successor,
166
+ },
167
+ durable,
168
+ );
169
+ } catch (err) {
170
+ out.failures.push(
171
+ `${row.ts}: ${err instanceof Error && err.message ? err.message : String(err)}`,
172
+ );
173
+ }
174
+ for (const ts of durable)
175
+ if (!out.collateral.includes(ts)) out.collateral.push(ts);
176
+ if (!retired) {
177
+ // The replacement IS durable. Name which half did not land, in the shape
178
+ // memory_update uses (#155), instead of counting a clean re-tag.
179
+ out.partial++;
180
+ continue;
181
+ }
182
+ out.retagged++;
183
+ if (outcome.evidenceError !== undefined) out.unaudited++;
184
+ }
185
+ return out;
186
+ }
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,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
  }
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);