opencode-self-improvement 0.14.17 → 0.14.19

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.ts CHANGED
@@ -11,7 +11,7 @@ import { cbmBin } from "./config.ts";
11
11
  import { isVisibleTo, loadAll, markSuperseded, readerFromSid } from "./memory.ts";
12
12
  import { runWriteGate, type GateContext } from "./gates.ts";
13
13
  import { record } from "./evidence.ts";
14
- import { evidenceCalls, hasGateCheck } from "./triggers.ts";
14
+ import { writeEvidence, hasGateCheck } from "./triggers.ts";
15
15
  import { getCurrent } from "./state.ts";
16
16
 
17
17
  export interface ScriptRecord {
@@ -47,6 +47,8 @@ export interface InitSummary {
47
47
  written: number;
48
48
  collapsed: number;
49
49
  blocked: number;
50
+ /** Written rows whose write_promoted audit line fell (#155 review). */
51
+ unaudited?: number;
50
52
  }
51
53
 
52
54
  const NOTABLE_KEYS = ["test", "e2e", "lint", "typecheck", "check", "build", "format"];
@@ -214,7 +216,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
214
216
 
215
217
  const gateCtx: GateContext = {
216
218
  liveRoot: root,
217
- evidenceCalls: evidenceCalls(args.sessionID ?? getCurrent().sid),
219
+ ...writeEvidence(args.sessionID ?? getCurrent().sid),
218
220
  hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
219
221
  // Stamps land on the caller's session even though runInit awaits git
220
222
  // probing before the gate writes (#127 / #121's write-side root cause).
@@ -247,14 +249,19 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
247
249
  let written = 0;
248
250
  let collapsed = 0;
249
251
  let blocked = 0;
252
+ // Promoted rows whose write_promoted audit line fell (#155 review: the
253
+ // fault must be visible to every writer, bookkeeping included).
254
+ let unaudited = 0;
250
255
  for (const s of scripts) {
251
256
  const content = `${scope} ${s.key} command: run "${s.cmd}" from the repo root (${s.source}).`;
252
257
  const outcome = await runWriteGate(
253
258
  { type: "pattern", scope, content, tags: ["init", s.source] },
254
259
  gateCtx,
255
260
  );
256
- if (outcome.action === "promoted") written++;
257
- else if (outcome.action === "collapsed") collapsed++;
261
+ if (outcome.action === "promoted") {
262
+ written++;
263
+ if (outcome.evidenceError !== undefined) unaudited++;
264
+ } else if (outcome.action === "collapsed") collapsed++;
258
265
  else blocked++;
259
266
  }
260
267
 
@@ -267,6 +274,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
267
274
  if (stampOutcome.action === "promoted" && prior && stampOutcome.ts) {
268
275
  await markSuperseded(prior.ts, { superseded_by: stampOutcome.ts, reason: "init" });
269
276
  }
277
+ if (stampOutcome.action === "promoted" && stampOutcome.evidenceError !== undefined) unaudited++;
270
278
 
271
279
  await record(
272
280
  "init_complete",
@@ -280,6 +288,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
280
288
  written,
281
289
  collapsed,
282
290
  blocked,
291
+ unaudited,
283
292
  stamp: stampTs ?? "-",
284
293
  },
285
294
  false,
@@ -296,6 +305,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
296
305
  written,
297
306
  collapsed,
298
307
  blocked,
308
+ unaudited,
299
309
  };
300
310
  }
301
311
 
@@ -308,6 +318,8 @@ export function formatInit(s: InitSummary): string {
308
318
  `Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
309
319
  `Graph: ${s.graph.action}${s.graph.name ? ` (${s.graph.name})` : ""} [mode=${s.graph.mode}]`,
310
320
  scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
311
- `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}; stamp=${s.stampTs ?? "-"}`,
321
+ `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
322
+ (s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
323
+ `; stamp=${s.stampTs ?? "-"}`,
312
324
  ].join("\n");
313
- }
325
+ }
package/src/inject.ts CHANGED
@@ -1,12 +1,9 @@
1
- // Context surfaces. The system digest is TINY (≤2 lines): durable knowledge is
2
- // pulled on demand, not pushed wholesale. Deterministic memory-first injection
3
- // rides chat.message (synthetic parts), so relevant knowledge is in the model's
4
- // context before it chooses any tool. Contextual pull rides grep/glob/read
5
- // results. Evidence is never injected. Open threads (status=
6
- // "open") get a single capped frontier block in the digest so planning sessions
7
- // start at the previous session's frontier instead of re-deriving it.
1
+ // Context surfaces: a small system digest, a capped open-thread frontier, and
2
+ // relevance-ranked memory frozen per epoch by src/index.ts. These ride the
3
+ // session context hook's system parts. Contextual pull appends relevant memory
4
+ // to grep/glob/read results. Evidence is never injected.
8
5
  import { createHash } from "node:crypto";
9
- import { isActive, loadAll, readerFromSid, visibleTo, visibleHere, type Memory } from "./memory.ts";
6
+ import { isActive, loadAll, readerFromSid, visibleTo, type Memory } from "./memory.ts";
10
7
  import { record } from "./evidence.ts";
11
8
  import { dateStr, frontierBudget, injectBudget } from "./config.ts";
12
9
  import { bracketList } from "./logfmt.ts";
@@ -0,0 +1,313 @@
1
+ // Per-setup injection epochs. Host event parsing and identity binding stay in
2
+ // index.ts; this module owns frozen bytes, refresh decisions, and their status.
3
+ import { isActive, isVisibleTo, loadAll, malformedCount, readerFromSid, type Memory } from "./memory.ts";
4
+ import { SESSION_CAP, SessionLru } from "./sessions.ts";
5
+ import { record } from "./evidence.ts";
6
+ import {
7
+ capToBudget,
8
+ injectedRows,
9
+ selectRelevant,
10
+ storeVersion,
11
+ systemDigest,
12
+ } from "./inject.ts";
13
+ import { attributeSession, deriveMemoryRefs, type MemoryRefs } from "./attribution.ts";
14
+ import { neverRetrieved, readLedger, useSignals } from "./hits.ts";
15
+ import { emptyStats, writeStatus, type Measured, type SessionStats, type StatusPayload } from "./status.ts";
16
+ import { callsFor } from "./triggers.ts";
17
+ import { authoredFor } from "./state.ts";
18
+
19
+ interface InjectionEpochOptions {
20
+ budget: number;
21
+ frontierBudget: number;
22
+ // The host listener records usage. Eviction must still drop it with the
23
+ // epoch and request counters, so no measurement outlives its tracked session.
24
+ measuredTurns: Pick<Map<string, Measured>, "get" | "delete">;
25
+ noteHits: (sid: string, rows: Memory[], query: string) => Promise<void>;
26
+ }
27
+
28
+ export function createInjectionEpochs({
29
+ budget,
30
+ frontierBudget: openBudget,
31
+ measuredTurns,
32
+ noteHits,
33
+ }: InjectionEpochOptions) {
34
+ // Per-session frozen injection epochs: the whole memory section (digest +
35
+ // frontier + relevance) plus the store fingerprint it was rendered from.
36
+ // Recomputed on the first prompt of a tracked session, when injectable rows
37
+ // change, or after a compaction (see the prompt/context/compaction hooks).
38
+ // The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
39
+ // (issue #162): a write that changes nothing the model is shown must not
40
+ // cost the next request a full re-prefill. And a pure addition the session
41
+ // wrote itself does not move them either (#165) — see refreshEpoch. The
42
+ // shared LRU below may evict the whole session state; a later prompt starts
43
+ // it fresh.
44
+ const epoch = new Map<
45
+ string,
46
+ {
47
+ version: string;
48
+ /** Frozen standing digest + frontier + convergence parts, in push order. */
49
+ parts: string[];
50
+ /** The budgeted relevance block the surfaces report against injectBudget. */
51
+ block: string;
52
+ /** Comparison key: every byte of the memory section, joined. */
53
+ prefix: string;
54
+ /**
55
+ * Rows THIS session had already authored when these bytes were rendered
56
+ * (#165). The riding-bytes test subtracts everything authored after this
57
+ * snapshot; if what remains renders identically, the whole difference is
58
+ * the session's own additions and the bytes keep riding.
59
+ */
60
+ ownRows: Set<string>;
61
+ /**
62
+ * The prompt these bytes were scored against. The counterfactual below
63
+ * has to re-score the SAME inputs, or a topic change between the freeze
64
+ * and the next write would look like a content change — and the epoch
65
+ * would pay for a refresh it deliberately refuses to do on a prompt.
66
+ */
67
+ prompt: string;
68
+ at: string;
69
+ reason: "first" | "store_changed";
70
+ refs: MemoryRefs;
71
+ }
72
+ >();
73
+ // Latest user prompt per tracked session. A changed store is re-scored
74
+ // against it even when the change happened during a tool loop with no new
75
+ // prompt. It is evicted together with the epoch and session ledgers.
76
+ const latestPrompt = new Map<string, string>();
77
+ // Recomputes since server start: every one invalidated a prompt cache, so
78
+ // it is the honest cost number the surfaces show (status files / tools).
79
+ let epochRecomputes = 0;
80
+
81
+ // Per-session ledger, incremented at the injection decision below. Status
82
+ // combines it with the host listener's measured usage, either on disk (TUI)
83
+ // or directly through memory_status.
84
+ const sessionStats = new Map<string, SessionStats>();
85
+ // Epoch, prompt, counters, and host measurements are evicted together.
86
+ const sessions = new SessionLru(SESSION_CAP, (sid) => {
87
+ epoch.delete(sid);
88
+ latestPrompt.delete(sid);
89
+ sessionStats.delete(sid);
90
+ measuredTurns.delete(sid);
91
+ });
92
+ const statsFor = (sid: string): SessionStats => {
93
+ let st = sessionStats.get(sid);
94
+ if (!st) {
95
+ st = emptyStats();
96
+ sessionStats.set(sid, st);
97
+ }
98
+ return st;
99
+ };
100
+
101
+ // Build the full status snapshot for one session, or null before its first
102
+ // epoch. Store counts are computed fresh so every flush is current.
103
+ const buildPayload = async (sid: string): Promise<StatusPayload | null> => {
104
+ const ep = epoch.get(sid);
105
+ if (!ep) return null;
106
+ const all = await loadAll();
107
+ const act = all.filter(isActive);
108
+ const led = await readLedger();
109
+ return {
110
+ at: ep.at,
111
+ sessionID: sid,
112
+ reason: ep.reason,
113
+ recomputes: epochRecomputes,
114
+ block: ep.block,
115
+ blockChars: ep.block.length,
116
+ sectionChars: ep.prefix.length,
117
+ budget,
118
+ store: {
119
+ active: act.length,
120
+ superseded: all.length - act.length,
121
+ open: act.filter((m) => m.status === "open").length,
122
+ scopes: new Set(act.map((m) => m.scope)).size,
123
+ malformed: malformedCount(),
124
+ neverRetrieved: neverRetrieved(act, led).length,
125
+ ledgerSince: led.since,
126
+ },
127
+ stats: statsFor(sid),
128
+ measured: measuredTurns.get(sid) ?? null,
129
+ attribution: attributeSession(callsFor(sid), ep.refs),
130
+ };
131
+ };
132
+ const flushStatus = (sid: string): Promise<void> =>
133
+ buildPayload(sid).then((p) => (p ? writeStatus(p) : undefined));
134
+
135
+ // Called when a prompt arrives (to keep status surfaces current) and again
136
+ // at the injection decision on every model request. The latter keeps
137
+ // removals fail-closed: an out-of-band redaction or a block during a tool
138
+ // loop cannot ride one more request waiting for another user prompt.
139
+ // The caller's sid is resolved to an immutable Reader BEFORE the store
140
+ // read (#127): while loadAll awaits, another session's hooks may dispatch
141
+ // and move the ambient current; filtering with THAT leaks the other
142
+ // session's repo into this one's system prompt.
143
+ const injectableRows = async (sid?: string): Promise<Memory[]> => {
144
+ const reader = readerFromSid(sid);
145
+ return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
146
+ };
147
+ // Render the COMPLETE memory section for one request: the standing digest,
148
+ // the open-thread frontier and the convergence line (all from systemDigest),
149
+ // followed by this epoch's relevance block. The parts are exactly what gets
150
+ // pushed onto `event.system`; their join is the byte key the epoch compares
151
+ // against, so "did the cache-critical prefix change?" is answered by the
152
+ // bytes the model would actually see and never by a proxy (issue #162).
153
+ const buildMemorySection = async (
154
+ sid: string | undefined,
155
+ mems: Memory[],
156
+ promptOverride?: string,
157
+ ): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
158
+ const parts: string[] = [];
159
+ await systemDigest(
160
+ { sessionID: sid },
161
+ { system: parts },
162
+ { rows: mems, frontierBudget: openBudget },
163
+ );
164
+ const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
165
+ // Widen the candidate pool, then cap: the budget decides what rides.
166
+ const sel = await selectRelevant(prompt, 5, mems, await useSignals());
167
+ const block = sel.block ? capToBudget(sel.block, budget) : "";
168
+ // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
169
+ // for attribution. Derived from the budget-surviving rows, not the wider
170
+ // candidate pool — crediting paths the model never saw would overclaim.
171
+ const rode = injectedRows(block, sel.selected);
172
+ const prefix = [...parts, block].join("\u0000");
173
+ return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
174
+ };
175
+ const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
176
+ if (!latestPrompt.has(sid)) return;
177
+ const mems = rows ?? (await injectableRows(sid));
178
+ const version = await storeVersion(mems);
179
+ const cached = epoch.get(sid);
180
+ // Cheap pre-check: no injectable row moved, so the frozen bytes still
181
+ // stand. Skips re-scoring and the use-ledger write on ordinary turns.
182
+ if (cached?.version === version) return;
183
+ const built = await buildMemorySection(sid, mems);
184
+ // The store moved. A write that changes nothing RENDERED — a row that is
185
+ // not relevant to this prompt, supersession elsewhere, a scope the reader
186
+ // never sees rendered identically — must not cost this session a prompt
187
+ // cache. Adopt the new fingerprint, keep riding the same bytes, emit
188
+ // nothing: an invalidation has to mean bytes actually moved.
189
+ if (cached && cached.prefix === built.prefix) {
190
+ epoch.set(sid, { ...cached, version });
191
+ return;
192
+ }
193
+ // Riding bytes (#165): a pure addition this session wrote itself is
194
+ // information it already has — the model produced it, it is in the
195
+ // transcript. Re-render the section with every row authored SINCE these
196
+ // bytes were frozen taken back out: if it comes back byte-identical, the
197
+ // entire difference is attributable to the session's own additions and
198
+ // the frozen bytes keep riding. Everything else survives into that render
199
+ // and still busts — a riding row removed or rewritten (blocklist,
200
+ // hand-redaction, forget, supersession, decay), another session's row, a
201
+ // viewer edit, an import, a moved convergence line.
202
+ if (cached) {
203
+ const mine = authoredFor(sid);
204
+ const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
205
+ if (extra.length) {
206
+ const back = await buildMemorySection(
207
+ sid,
208
+ mems.filter((m) => !extra.some((e) => e.ts === m.ts)),
209
+ cached.prompt,
210
+ );
211
+ if (back.prefix === cached.prefix) {
212
+ epoch.set(sid, { ...cached, version });
213
+ return;
214
+ }
215
+ }
216
+ }
217
+ const prompt = latestPrompt.get(sid) ?? "";
218
+ // Use ledger (#42): the rows that actually rode the block, credited with
219
+ // the terms the prompt and those rows shared (never the prompt itself).
220
+ // Only once the build is ADOPTED — a discarded rebuild must not credit
221
+ // rows that were already offered under the frozen epoch.
222
+ await noteHits(sid, built.rode, prompt);
223
+ const at = new Date().toISOString();
224
+ const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
225
+ epoch.set(sid, {
226
+ version,
227
+ parts: built.parts,
228
+ block: built.block,
229
+ prefix: built.prefix,
230
+ ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
231
+ prompt,
232
+ at,
233
+ reason,
234
+ refs: built.refs,
235
+ });
236
+ await record(
237
+ "epoch_recompute",
238
+ {
239
+ session: sid,
240
+ reason,
241
+ chars: built.block.length,
242
+ },
243
+ false,
244
+ );
245
+ epochRecomputes++;
246
+ // Ledger: a store_changed recompute of a live epoch is an
247
+ // invalidation (the first epoch of a session busts nothing). The
248
+ // epoch request count restarts with the new block.
249
+ const st = statsFor(sid);
250
+ st.epochRequests = 0;
251
+ if (reason === "store_changed") {
252
+ st.invalidations++;
253
+ st.lastInvalidation = { at, reason };
254
+ }
255
+ // Status hand-off for the terminal panel (src/tui.tsx) and any
256
+ // out-of-process surface. Best-effort; never breaks injection.
257
+ await flushStatus(sid);
258
+ };
259
+
260
+ // Push each part in the original order. Accounting follows delivery so a
261
+ // throwing host callback leaves request accounting unchanged.
262
+ const deliver = async (sid: string | undefined, push: (text: string) => void): Promise<void> => {
263
+ const mems = await injectableRows(sid);
264
+ if (typeof sid === "string") await refreshEpoch(sid, mems);
265
+ // Deliver the FROZEN memory section. Every byte pushed onto the system
266
+ // prompt comes from the epoch, so between busts the provider sees an
267
+ // identical prefix and serves the conversation from cache (issue #162).
268
+ // A session with no epoch yet (no prompt recorded, or evicted from the
269
+ // LRU) still gets the standing digest, built fresh and uncached.
270
+ const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
271
+ if (ep) {
272
+ for (const text of ep.parts) push(text);
273
+ } else {
274
+ const parts: string[] = [];
275
+ await systemDigest(
276
+ { sessionID: sid },
277
+ { system: parts },
278
+ { rows: mems, frontierBudget: openBudget },
279
+ );
280
+ for (const text of parts) push(text);
281
+ }
282
+ // This epoch's relevance-ranked memory, also on the system channel —
283
+ // the UI never renders system parts, unlike appended prompt text.
284
+ const knowledge = ep?.block;
285
+ if (knowledge) push(knowledge);
286
+ // Count AT THE INJECTION DECISION so badge/panel numbers match exactly
287
+ // what rode this request (a later abort still rode the bytes — known
288
+ // and documented). Abstained = the epoch exists but its block is empty.
289
+ if (typeof sid === "string") {
290
+ const st = statsFor(sid);
291
+ st.requests++;
292
+ st.epochRequests++;
293
+ if (knowledge) st.cumChars += knowledge.length;
294
+ else if (epoch.has(sid)) st.abstained++;
295
+ }
296
+ };
297
+
298
+ return {
299
+ // Setup touches the LRU at the same points as identity/usage handling.
300
+ touch: (sid: string): void => sessions.touch(sid),
301
+ async prompt(sid: string, text: string): Promise<void> {
302
+ latestPrompt.set(sid, text);
303
+ await refreshEpoch(sid);
304
+ },
305
+ deliver,
306
+ invalidate(sid: string): void {
307
+ epoch.delete(sid);
308
+ latestPrompt.delete(sid);
309
+ },
310
+ buildPayload,
311
+ flushStatus,
312
+ };
313
+ }
package/src/memory.ts CHANGED
@@ -396,7 +396,7 @@ async function stampRow(
396
396
  // Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
397
397
  // Idempotent: a second call is a no-op, so no double `superseded_by`.
398
398
  export async function markSuperseded(ts: string, fields: SupersedeFields): Promise<boolean> {
399
- return (await markManySuperseded([{ ts, fields }])) > 0;
399
+ return (await markManySupersededReport([{ ts, fields }])).marked.length > 0;
400
400
  }
401
401
 
402
402
  // Batch supersession (#61): one lock acquisition, one read, one snapshot and
@@ -408,56 +408,68 @@ export async function markSuperseded(ts: string, fields: SupersedeFields): Promi
408
408
  // so a repeat run marks nothing and writes nothing. Duplicate ts entries in
409
409
  // one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
410
410
  // Returns the number of rows actually marked.
411
- export async function markManySuperseded(
411
+ export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[]): Promise<number> {
412
+ return (await markManySupersededReport(entries)).marked.length;
413
+ }
414
+
415
+ // Same operation, reporting WHICH rows retired rather than how many (#158
416
+ // round 3): the write gate needs the ids to keep a durable-mutation ledger,
417
+ // because a failed audit line after a persisted retirement must still be able
418
+ // to name what actually landed. Skipped-by-the-batch rows (already retired
419
+ // out of band) are absent from `marked` — the ledger never claims a retirement
420
+ // this call did not perform.
421
+ export async function markManySupersededReport(
412
422
  entries: { ts: string; fields: SupersedeFields }[],
413
- ): Promise<number> {
414
- if (entries.length === 0) return 0;
423
+ ): Promise<{ marked: string[] }> {
424
+ if (entries.length === 0) return { marked: [] };
415
425
  const wanted = new Map<string, SupersedeFields>();
416
426
  for (const e of entries) if (!wanted.has(e.ts)) wanted.set(e.ts, e.fields);
417
- let marked = 0;
427
+ const marked: string[] = [];
418
428
  for (const file of await memoryFiles()) {
419
- marked += await withStoreLock(
420
- file,
421
- async () => {
429
+ marked.push(
430
+ ...(await withStoreLock(
431
+ file,
432
+ async () => {
422
433
  // #106: identity BEFORE the read, like every other whole-file
423
434
  // read-modify-write (#89's contract) - the publish below may retry a
424
435
  // Windows handover only while the destination still matches this.
425
- const since = await fileIdentity(file);
426
- const lines = await readLines(file);
427
- let touched = 0;
428
- for (let i = 0; i < lines.length; i++) {
429
- const parsed = parseLine(lines[i]);
430
- if (!parsed || typeof parsed.superseded_by === "string") continue;
431
- const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
432
- if (!fields) continue;
433
- // Whole line rewritten, not extended: an old-format line comes out in
434
- // the current format with its values unchanged (as markSuperseded did).
435
- // The one exception is SECRET SCRUB (#128, review probe 4): the
436
- // fields a merge/decay/update copies into the loser's row carry
437
- // caller-authored prose (the rotation note "key ghp_... rotated"),
438
- // and content already scrubs at this same boundary (line 260). The
439
- // durable row must not be the one place a credential survives when
440
- // the evidence line beside it was cleaned.
441
- const clean: SupersedeFields = { ...fields };
442
- for (const k of Object.keys(clean)) {
443
- const v = (clean as unknown as Record<string, unknown>)[k];
444
- if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
436
+ const since = await fileIdentity(file);
437
+ const lines = await readLines(file);
438
+ const ids: string[] = [];
439
+ for (let i = 0; i < lines.length; i++) {
440
+ const parsed = parseLine(lines[i]);
441
+ if (!parsed || typeof parsed.superseded_by === "string") continue;
442
+ const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
443
+ if (!fields) continue;
444
+ // Whole line rewritten, not extended: an old-format line comes out in
445
+ // the current format with its values unchanged (as markSuperseded did).
446
+ // The one exception is SECRET SCRUB (#128, review probe 4): the
447
+ // fields a merge/decay/update copies into the loser's row carry
448
+ // caller-authored prose (the rotation note "key ghp_... rotated"),
449
+ // and content already scrubs at this same boundary (line 260). The
450
+ // durable row must not be the one place a credential survives when
451
+ // the evidence line beside it was cleaned.
452
+ const clean: SupersedeFields = { ...fields };
453
+ for (const k of Object.keys(clean)) {
454
+ const v = (clean as unknown as Record<string, unknown>)[k];
455
+ if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
456
+ }
457
+ lines[i] = formatLine({ ...parsed, ...clean });
458
+ ids.push(parsed.ts as string);
445
459
  }
446
- lines[i] = formatLine({ ...parsed, ...clean });
447
- touched++;
448
- }
449
- if (touched === 0) return 0;
450
- await snapshotBefore(file);
451
- await writeAtomic(file, lines.join("\n") + "\n", since);
452
- return touched;
453
- },
454
- LOCK_WRITE,
460
+ if (ids.length === 0) return [];
461
+ await snapshotBefore(file);
462
+ await writeAtomic(file, lines.join("\n") + "\n", since);
463
+ return ids;
464
+ },
465
+ LOCK_WRITE,
466
+ ))
455
467
  );
456
468
  }
457
469
  // A ts that appears in several files (should not exist - append mints unique
458
470
  // ts) retires in EVERY file here, where the row-by-row loop retired only the
459
471
  // first; both are conservation-safe, this one is the more honest tombstone.
460
- return marked;
472
+ return { marked };
461
473
  }
462
474
 
463
475
  // Drop a row's supersession markers IN PLACE (snapshot-first), making it active
package/src/portable.ts CHANGED
@@ -194,6 +194,10 @@ export interface ImportTally {
194
194
  skipped: number;
195
195
  /** Open rows downgraded because the file cannot grant that frontier scope. */
196
196
  downgraded: number;
197
+ /** Promoted rows whose write_promoted audit line failed to land (#155 review). */
198
+ unaudited: number;
199
+ /** First audit-fault message, so the reply can name what went wrong. */
200
+ auditError?: string;
197
201
  }
198
202
 
199
203
  // Recognize the export header line (see EXPORT_HEADER). A version NEWER than
@@ -277,7 +281,7 @@ function parseRow(line: string): WriteCandidate | null {
277
281
  // day files, snapshots and the blocklist, none of which are import formats.
278
282
  export async function importMemories(
279
283
  path: string,
280
- gate: (c: WriteCandidate) => Promise<{ action: string }>,
284
+ gate: (c: WriteCandidate) => Promise<{ action: string; evidenceError?: string }>,
281
285
  // The importing session, captured at tool entry (#127): "the importing
282
286
  // session's current repo" must be the CALLER's repo even though this loop
283
287
  // awaits the gate on every row, during which a concurrent session can move
@@ -297,7 +301,7 @@ export async function importMemories(
297
301
  }
298
302
  const file = Bun.file(target);
299
303
  if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
300
- const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
304
+ const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
301
305
  // #152: the importing session's repository is resolved BEFORE the first row,
302
306
  // through the writer rule rather than the ambient one. An unresolved named
303
307
  // session has no write target, and half a file re-stamped into whatever
@@ -339,8 +343,13 @@ export async function importMemories(
339
343
  tally.downgraded++;
340
344
  }
341
345
  const outcome = await gate(c);
342
- if (outcome.action === "promoted") tally.promoted++;
343
- else if (outcome.action === "collapsed") tally.collapsed++;
346
+ if (outcome.action === "promoted") {
347
+ tally.promoted++;
348
+ if (outcome.evidenceError !== undefined) {
349
+ tally.unaudited++;
350
+ tally.auditError ??= outcome.evidenceError;
351
+ }
352
+ } else if (outcome.action === "collapsed") tally.collapsed++;
344
353
  else tally.blocked++;
345
354
  }
346
355
  return tally;
package/src/resolver.ts CHANGED
@@ -229,9 +229,8 @@ export function displayCall(name: string, argsText: string): string {
229
229
  return `${name}(${normalizeArgs(argsText)})`;
230
230
  }
231
231
 
232
- // Deterministic source-tree scan used by GATE-1 live resolution. Excludes junk
233
- // that poisons signature comparison: node_modules (type-decl .d.ts files often
234
- // carry empty or spread args), build output (dist/lib), and VCS dirs. Prefers
232
+ // Deterministic GATE-1 source scan excludes dependencies, VCS dirs, and .d.ts
233
+ // declarations (which often carry empty or spread args). Prefers
235
234
  // files under src/ over build output, .ts/.tsx sources over compiled .js, and
236
235
  // case-insensitively ranks basenames matching the call's fileHint first so
237
236
  // `MeshBuilder.CreateBox` resolves to `meshbuilder.pure.ts` instead of a
@@ -245,7 +244,6 @@ function relRank(rel: string): number {
245
244
  if (rel.endsWith(".d.ts")) return Infinity;
246
245
  let rank = 0;
247
246
  if (seg.includes("src")) rank -= 100;
248
- if (rel.endsWith(".d.ts")) rank += 1000;
249
247
  if (seg.some((s) => ["dist", "build", "out", "lib"].includes(s))) rank += 50;
250
248
  if (/\.(js|mjs|cjs)$/.test(rel)) rank += 10;
251
249
  return rank;
package/src/schema.ts CHANGED
@@ -93,7 +93,10 @@ export const UpdateArgs = z.object({
93
93
  "Row selector: id (ts), clock fragment, or unique content substring. Omit to target the newest active row of scope+type.",
94
94
  )
95
95
  .optional(),
96
- status: z.enum(STATUSES).optional(),
96
+ status: z
97
+ .enum(STATUSES)
98
+ .describe("Settled or open; omitted keeps the target row's standing (an open frontier row stays open)")
99
+ .optional(),
97
100
  });
98
101
 
99
102
  export const ForgetArgs = z.object({
package/src/state.ts CHANGED
@@ -35,6 +35,14 @@ export interface SessionState {
35
35
  cmd: string;
36
36
  chain: ToolResult[];
37
37
  } | null;
38
+ // Bounded provenance for write telemetry (#163), independent of the full
39
+ // calls ledger used by grounding, attribution, and convergence.
40
+ writeEvidence?: {
41
+ recent: string[];
42
+ gateCheck?: string;
43
+ gateRecovery?: [string, string, string];
44
+ toolRecovery?: [string, string];
45
+ };
38
46
  // Session-convergence tracking (time-to-frontier): completed-message count,
39
47
  // first activity time, and the first memory_recall that surfaced an open
40
48
  // thread. Deterministic: derived only from queued messages and tool results.