opencode-self-improvement 0.30.0 → 0.30.2

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.
Files changed (105) hide show
  1. package/README.md +2 -4
  2. package/package.json +3 -2
  3. package/src/capture/available.ts +30 -31
  4. package/src/capture/candidates.ts +2 -2
  5. package/src/capture/checked.ts +3 -3
  6. package/src/capture/guided-rules.ts +1 -1
  7. package/src/capture/lag.ts +2 -2
  8. package/src/capture/policy.ts +7 -7
  9. package/src/capture/prompt.ts +4 -4
  10. package/src/capture/runtime.ts +86 -90
  11. package/src/capture/session-model.ts +2 -2
  12. package/src/capture/transcript.ts +5 -5
  13. package/src/capture/triggers.ts +7 -7
  14. package/src/consolidate/propose.ts +4 -4
  15. package/src/consolidate/render.ts +2 -2
  16. package/src/core/cmp-ts.ts +1 -1
  17. package/src/core/config/budgets.ts +1 -1
  18. package/src/core/config/paths.ts +1 -1
  19. package/src/core/guidance.ts +1 -1
  20. package/src/core/hooks.ts +4 -4
  21. package/src/core/host.ts +1 -1
  22. package/src/core/logfmt/format.ts +1 -1
  23. package/src/core/logfmt/publish.ts +1 -1
  24. package/src/core/logfmt/read.ts +1 -1
  25. package/src/core/lru.ts +1 -1
  26. package/src/core/state.ts +4 -4
  27. package/src/core/tags.ts +9 -10
  28. package/src/core/time.ts +1 -1
  29. package/src/core/tokenize.ts +1 -1
  30. package/src/events.ts +8 -8
  31. package/src/evidence/record.ts +10 -11
  32. package/src/gate/gate.ts +25 -25
  33. package/src/gate/value-conflict.ts +7 -8
  34. package/src/hits/ledger.ts +4 -4
  35. package/src/identity/host-events.ts +3 -3
  36. package/src/identity/repokey.ts +7 -7
  37. package/src/identity/session-context.ts +7 -7
  38. package/src/index.ts +6 -6
  39. package/src/init/detect.ts +3 -3
  40. package/src/init/format.ts +6 -6
  41. package/src/init/retag.ts +7 -7
  42. package/src/init/run.ts +18 -18
  43. package/src/init/stamp.ts +17 -17
  44. package/src/inject/anchor.ts +1 -1
  45. package/src/inject/budget.ts +1 -1
  46. package/src/inject/digest.ts +5 -5
  47. package/src/inject/epochs.ts +15 -15
  48. package/src/inject/format.ts +2 -2
  49. package/src/inject/pull.ts +3 -3
  50. package/src/inject/version.ts +1 -1
  51. package/src/portable/decay.ts +1 -1
  52. package/src/portable/export.ts +7 -7
  53. package/src/portable/import.ts +5 -5
  54. package/src/recall/conflicts.ts +1 -1
  55. package/src/recall/dedupe.ts +31 -55
  56. package/src/recall/gate.ts +19 -40
  57. package/src/recall/relevant.ts +11 -11
  58. package/src/recall/score.ts +14 -23
  59. package/src/recall/shared-terms.ts +1 -1
  60. package/src/status/format.ts +1 -1
  61. package/src/status/metrics.ts +5 -5
  62. package/src/status/payload.ts +4 -4
  63. package/src/status/report.ts +5 -5
  64. package/src/status/store-summary.ts +1 -1
  65. package/src/status/write.ts +3 -4
  66. package/src/store/blocklist.ts +1 -1
  67. package/src/store/files/append.ts +8 -8
  68. package/src/store/files/deletions.ts +3 -3
  69. package/src/store/files/load.ts +5 -5
  70. package/src/store/files/prune.ts +8 -8
  71. package/src/store/files/snapshots.ts +1 -1
  72. package/src/store/files/supersede.ts +11 -12
  73. package/src/store/files/target.ts +1 -1
  74. package/src/store/lock.ts +12 -12
  75. package/src/store/model/memory.ts +4 -4
  76. package/src/store/model/predicates.ts +2 -2
  77. package/src/store/model/provenance.ts +1 -1
  78. package/src/store/model/visibility.ts +4 -4
  79. package/src/store/prune.ts +1 -1
  80. package/src/store/quarantine/quarantine.ts +2 -2
  81. package/src/store/quarantine/release.ts +2 -2
  82. package/src/store/secrets.ts +1 -1
  83. package/src/store/tombstones/rejection.ts +1 -1
  84. package/src/store/tombstones/tombstone.ts +5 -5
  85. package/src/store/undo.ts +12 -12
  86. package/src/tools/consolidate.ts +1 -1
  87. package/src/tools/decay.ts +2 -2
  88. package/src/tools/deps.ts +1 -1
  89. package/src/tools/evidence.ts +4 -4
  90. package/src/tools/export.ts +1 -1
  91. package/src/tools/forget.ts +2 -2
  92. package/src/tools/import.ts +3 -3
  93. package/src/tools/init.ts +1 -1
  94. package/src/tools/list.ts +1 -1
  95. package/src/tools/merge-review.ts +11 -11
  96. package/src/tools/recall.ts +5 -5
  97. package/src/tools/registry.ts +2 -2
  98. package/src/tools/remember.ts +4 -4
  99. package/src/tools/schema.ts +4 -4
  100. package/src/tools/status-tool.ts +5 -5
  101. package/src/tools/undo.ts +4 -4
  102. package/src/tools/update.ts +18 -19
  103. package/src/viewer/mutate.ts +13 -13
  104. package/src/viewer/rejections.ts +1 -1
  105. package/src/viewer/server.ts +47 -49
@@ -1,4 +1,4 @@
1
- // The memory_remember tool, extracted from index.ts (#168). Schema, description
1
+ // The memory_remember tool, extracted from index.ts. Schema, description
2
2
  // and handler are byte-identical to the pre-split source; closure access arrives
3
3
  // through ToolDeps.
4
4
  import type { ToolRegister } from "./deps.ts";
@@ -36,7 +36,7 @@ export const register: ToolRegister = (editor, deps) => {
36
36
  };
37
37
  await bindSessionIdentity(sid);
38
38
  // An explicit global write needs no repository owner; anything else
39
- // does (#152).
39
+ // does.
40
40
  if (!args.global) {
41
41
  const ownerless = ownerlessWriter(sid);
42
42
  if (ownerless)
@@ -44,7 +44,7 @@ export const register: ToolRegister = (editor, deps) => {
44
44
  }
45
45
  const outcome = await runWriteGate(candidate, gateContext(sid));
46
46
  // A durable row whose audit line fell is NOT a clean success
47
- // (#155 review): the reply says what is missing where it is
47
+ // the reply says what is missing where it is
48
48
  // missing, and the row itself stands.
49
49
  if (outcome.action === "promoted")
50
50
  return {
@@ -54,7 +54,7 @@ export const register: ToolRegister = (editor, deps) => {
54
54
  return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
55
55
  return {
56
56
  content: `Write blocked at GATE (${outcome.reason}). ${
57
- // #268 F1: the catch-all must name the filter a reader needs.
57
+ // F1: the catch-all must name the filter a reader needs.
58
58
  // `ev` matches the EVENT type (`write_blocked`), never the block
59
59
  // reason — a session that guesses the reason gets "No evidence"
60
60
  // while the row is in the log. Keep the `ev=write_blocked`
@@ -35,7 +35,7 @@ const memoryField = z
35
35
  message: "must not contain control characters",
36
36
  });
37
37
 
38
- // Retrieval keywords (#40). The shape cap mirrors MAX_KEYWORDS in memory.ts,
38
+ // Retrieval keywords. The shape cap mirrors MAX_KEYWORDS in memory.ts,
39
39
  // which is the authority at write time (it also lowercases, de-dupes and drops
40
40
  // over-long entries rather than rejecting the write).
41
41
  const keywordList = z
@@ -233,7 +233,7 @@ export const ReleaseQuarantineBody = z.object({
233
233
  ts: isoTs,
234
234
  reason: z.string().trim().min(1),
235
235
  });
236
- // #35: lift a value-keyed rejection. `ch` is the 12-hex content hash the gate's
236
+ // lift a value-keyed rejection. `ch` is the 12-hex content hash the gate's
237
237
  // block hint names, and the same identifier a `dedup_rejected` evidence line
238
238
  // carries — so a human can act on either without reading the store by hand.
239
239
  export const UnrejectBody = z.object({
@@ -241,10 +241,10 @@ export const UnrejectBody = z.object({
241
241
  });
242
242
  // Strict fields by intent: String(body.x ?? "") coercion once let unvalidated
243
243
  // POSTs append rows with empty type/scope/content.
244
- // repo/repoPath (#129): the origin stamp of the DELETED row, replayed from the
244
+ // repo/repoPath: the origin stamp of the DELETED row, replayed from the
245
245
  // audit line so a restore-entry keeps the row's original visibility instead of
246
246
  // silently landing global. Both absent = the documented legacy global restore.
247
- // ts (#207): identity of the deleted row. The server resolves the row's
247
+ // ts: identity of the deleted row. The server resolves the row's
248
248
  // metadata (tags/kw/issue/status, and the origin stamp) from the deletion
249
249
  // audit line itself — by ts when present, falling back to type/scope/content
250
250
  // when that ts matches no audit line, else directly by type/scope/content —
@@ -1,4 +1,4 @@
1
- // The memory_status tool, extracted from index.ts (#168).
1
+ // The memory_status tool, extracted from index.ts.
2
2
  // Closure access arrives through ToolDeps.
3
3
  import type { ToolRegister } from "./deps.ts";
4
4
  import { readLedger } from "../hits/ledger.ts";
@@ -37,7 +37,7 @@ export const register: ToolRegister = (editor, deps) => {
37
37
  const status = sid === "?" ? null : await sessions.buildPayload(sid);
38
38
  const all = await loadAll();
39
39
  const malformed = malformedCount();
40
- // Use ledger (#42): how much of the store has never been surfaced.
40
+ // Use ledger: how much of the store has never been surfaced.
41
41
  // Reported, never acted on — retirement is a decision, not a metric.
42
42
  const ledger = await readLedger();
43
43
  const { active: act, counts: store } = summarizeStore(
@@ -45,7 +45,7 @@ export const register: ToolRegister = (editor, deps) => {
45
45
  ledger,
46
46
  malformed,
47
47
  );
48
- // Self-metrics (#44): what the store costs, how fast it grows, and how
48
+ // Self-metrics: what the store costs, how fast it grows, and how
49
49
  // stale a capture is when it fires. Same rule as above — the numbers
50
50
  // are the point, not a verdict on them.
51
51
  store.bytes = act.reduce(
@@ -58,7 +58,7 @@ export const register: ToolRegister = (editor, deps) => {
58
58
  store.rowsPerDay = rowsPerDay(act) ?? undefined;
59
59
  const evidenceLines = await captureLagLines();
60
60
  store.captureLag = captureLag(evidenceLines);
61
- // #387: the plugin's own model calls, billed. Same evidence read, so
61
+ // the plugin's own model calls, billed. Same evidence read, so
62
62
  // the number cannot disagree with the lag line above it.
63
63
  store.captureCost = captureCost(evidenceLines);
64
64
  return {
@@ -69,7 +69,7 @@ export const register: ToolRegister = (editor, deps) => {
69
69
  quarantined: act
70
70
  .filter((m) => isVisibleTo(m, reportReader) && isQuarantined(m))
71
71
  .map((m) => ({ ts: m.ts, patterns: quarantineReasons(m) })),
72
- // #138: capture state read from the same evidence window, so the
72
+ // capture state read from the same evidence window, so the
73
73
  // chat surface distinguishes off / misconfigured / inert / alive.
74
74
  capture: captureHealth(evidenceLines),
75
75
  }),
package/src/tools/undo.ts CHANGED
@@ -1,4 +1,4 @@
1
- // The memory_undo tool, extracted from index.ts (#168). Schema, description
1
+ // The memory_undo tool, extracted from index.ts. Schema, description
2
2
  // and handler are byte-identical to the pre-split source; closure access arrives
3
3
  // through ToolDeps.
4
4
  import type { ToolRegister } from "./deps.ts";
@@ -19,14 +19,14 @@ export const register: ToolRegister = (editor, deps) => {
19
19
  async execute(args, context): Promise<{ content: string }> {
20
20
  if (args.snapshot) {
21
21
  const mode = args.force ? "force" : args.merge ? "merge" : "check";
22
- // Day files are shared across repositories (#153): the rollback
22
+ // Day files are shared across repositories: the rollback
23
23
  // carries the CALLER's reader, so rows another repo owns survive
24
24
  // untouched in every mode instead of riding the snapshot wholesale.
25
25
  const { sid } = toolIds(context);
26
- // Identity before ownership partitioning (#260): the caller's
26
+ // Identity before ownership partitioning: the caller's
27
27
  // repository must be resolved from the host before the Reader
28
28
  // decides which lines are foreign, exactly as merge and forget now
29
- // do; the day file is shared (#153) and a wrong reader is a write
29
+ // do; the day file is shared and a wrong reader is a write
30
30
  // into another repository's history.
31
31
  await bindSessionIdentity(sid);
32
32
  const res = await restoreSnapshot(
@@ -1,4 +1,4 @@
1
- // The memory_update tool, extracted from index.ts (#168). Schema, description
1
+ // The memory_update tool, extracted from index.ts. Schema, description
2
2
  // and handler are byte-identical to the pre-split source; closure access arrives
3
3
  // through ToolDeps.
4
4
 
@@ -55,8 +55,7 @@ export const register: ToolRegister = (editor, deps) => {
55
55
  // then re-resolves under the lock, finds its target already retired,
56
56
  // and writes nothing — the documented fail-closed contract.
57
57
  // Flips once a replacement row is durable, so the catch below can
58
- // never claim "Nothing was written" about a write that happened
59
- // (#155's lie).
58
+ // never claim "Nothing was written" about a write that happened.
60
59
  let mutated = false;
61
60
  // The gate's durable steps: rows GATE-2 retired before a later
62
61
  // failure (round-3 probe 3). Non-empty means "Nothing was written"
@@ -79,7 +78,7 @@ export const register: ToolRegister = (editor, deps) => {
79
78
  // row happened to be newest in this scope+type.
80
79
  let resolved = resolveMemoryTarget(prior, args.query);
81
80
  if (resolved.status === "not_found") {
82
- // Naming a SUPERSEDED row is not a miss (#155): the retry
81
+ // Naming a SUPERSEDED row is not a miss: the retry
83
82
  // after a partial update lands here, and when that row's
84
83
  // active successor already carries exactly this content the
85
84
  // honest verdict is the duplicate one, not a dead end. Two
@@ -169,19 +168,19 @@ export const register: ToolRegister = (editor, deps) => {
169
168
  };
170
169
  }
171
170
  const target = resolved.target;
172
- // A prose edit is not a metadata reset (#154): fields the
171
+ // A prose edit is not a metadata reset: fields the
173
172
  // call does not name carry over from the row being
174
173
  // replaced, so updating an imported row can no longer
175
174
  // launder away its provenance or issue link. kw follows
176
175
  // the same rule with an override: omitted keeps the
177
176
  // target's, provided replaces. The carry completes to the
178
- // five fields of the #129 viewer precedent: STATUS (an
177
+ // five fields of the viewer precedent: STATUS (an
179
178
  // open frontier row stays open) and REPO (updating a
180
179
  // global row from one repository must not re-house it out
181
180
  // of every other repository's view — "an edit must never
182
181
  // widen visibility", and it must never narrow it either).
183
- // These are also the fields the collapse-completion judges
184
- // (review round 3): the fold asks whether the survivor
182
+ // These are also the fields the collapse-completion judges: the
183
+ // fold asks whether the survivor
185
184
  // already carries the REQUESTED state — not the pre-edit
186
185
  // target's. An update naming kw:["new-alias"] is not
187
186
  // "already standing" on a row holding ["old-alias"].
@@ -220,12 +219,12 @@ export const register: ToolRegister = (editor, deps) => {
220
219
  // The merge_review PARTIAL shape (156e887) applied to
221
220
  // update: the replacement IS durable, so the message says
222
221
  // exactly which follow-up step failed and what a retry does
223
- // (#155 — never claim "Nothing was written" from here).
222
+ // ( — never claim "Nothing was written" from here).
224
223
  const partial = (why: string) => ({
225
224
  content:
226
225
  `memory_update PARTIAL: replacement ${replacement} IS on disk (memory_undo merge or force ` +
227
226
  `restores ${retired}), but ${why}. Re-running this update reports the duplicate.` +
228
- // #215 narrowed a single-row supersede to the day file its ts
227
+ // narrowed a single-row supersede to the day file its ts
229
228
  // names, so a busy file now faults HERE instead of faulting
230
229
  // somewhere in the gate's sweep. The gate may still have
231
230
  // retired OTHER rows at GATE-2 (drift, canonical) before that
@@ -276,7 +275,7 @@ export const register: ToolRegister = (editor, deps) => {
276
275
  content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}`,
277
276
  };
278
277
  if (outcome.action === "collapsed") {
279
- // Completion (#155 convergence): when a retry collapses
278
+ // Completion ( convergence): when a retry collapses
280
279
  // because an ACTIVE row already holds exactly this content
281
280
  // while the row it NAMES is still active (the supersede
282
281
  // step of an earlier PARTIAL attempt never landed), the
@@ -284,7 +283,7 @@ export const register: ToolRegister = (editor, deps) => {
284
283
  // survivor's favor — a bare "Duplicate ignored" would leave
285
284
  // two active rows forever and a retry that never converges.
286
285
  // first-call-wins makes this safe to attempt on any path.
287
- // But the fold must not INVERT #154 (review): retiring the
286
+ // But the fold must not INVERT (review): retiring the
288
287
  // named row is loss-free only when the survivor already
289
288
  // carries what the named row carries — the SAME predicate
290
289
  // GATE-3 uses to call same-prose-different-metadata an
@@ -296,7 +295,7 @@ export const register: ToolRegister = (editor, deps) => {
296
295
  // a human (or an update on the survivor) decides.
297
296
  const survivorTs = outcome.collapsedWith;
298
297
  if (target && survivorTs && survivorTs !== target.ts) {
299
- // #175: the gate can observe a session move after this call captured
298
+ // the gate can observe a session move after this call captured
300
299
  // its reader. Recheck before trusting or describing the survivor.
301
300
  const survivor = (await loadAll()).find(
302
301
  (m) =>
@@ -305,17 +304,17 @@ export const register: ToolRegister = (editor, deps) => {
305
304
  isVisibleTo(m, reader),
306
305
  );
307
306
  if (survivor) {
308
- // #175: private rows are visible by key OR path. Equal keys alone
307
+ // private rows are visible by key OR path. Equal keys alone
309
308
  // can drop another checkout's access after an origin change.
310
309
  // For global rows, isVisibleTo ignores paths.
311
310
  // Match raw paths like isVisibleTo; filesystem aliases need not
312
311
  // grant the same readers access. This restricts automatic folds;
313
- // explicit merge_review authorizes both seats under #131 instead.
312
+ // explicit merge_review authorizes both seats under instead.
314
313
  const samePathVisibility =
315
314
  requested.repo === "global" ||
316
315
  (target.repoPath ?? "") === (survivor.repoPath ?? "");
317
316
  // The predicate is the REQUESTED state vs the survivor
318
- // (round 3): content equality is already proven by the
317
+ // content equality is already proven by the
319
318
  // collapse, so the fold is loss-free only when the
320
319
  // survivor also carries the metadata THIS call asked
321
320
  // for — and stands where the target stands for readers
@@ -406,13 +405,13 @@ export const register: ToolRegister = (editor, deps) => {
406
405
  );
407
406
  } catch (err) {
408
407
  // Everything that still throws here was PRE-WRITE for THIS call's
409
- // replacement: the fail-closed lock timeout, the #152 choke-point
408
+ // replacement: the fail-closed lock timeout, the choke-point
410
409
  // refusal, an evidence fault BEFORE the append. Post-append audit
411
410
  // failures no longer reach this catch — the gate reports them on
412
- // the promoted outcome (#155). mutated is the belt-and-braces
411
+ // the promoted outcome. mutated is the belt-and-braces
413
412
  // truth check: a future post-write throw must report a partial,
414
413
  // never a clean nothing. And gateDurable closes the last gap
415
- // (round 3): the gate may have RETIRED OTHER rows at GATE-2
414
+ // the gate may have RETIRED OTHER rows at GATE-2
416
415
  // before the fault that got here — those tombstones are on disk,
417
416
  // and naming them beats the "Nothing was written" premise.
418
417
  const msg =
@@ -69,7 +69,7 @@ async function findMemory(ts: string): Promise<Memory> {
69
69
  // Non-destructive edit: snapshot the pre-state, supersede the old entry, then
70
70
  // append the edited replacement (added ONLY because the edit requires it).
71
71
  //
72
- // ORIGIN PRESERVATION (#129): the replacement carries the target's repo stamp
72
+ // ORIGIN PRESERVATION: the replacement carries the target's repo stamp
73
73
  // verbatim. The viewer is an ADMIN entry point with no repository scope of
74
74
  // its own; letting appendMemory resolve the stamp from that null scope used
75
75
  // to leave every edited row unstamped — i.e. silently GLOBAL, recallable and
@@ -93,7 +93,7 @@ export async function editMemory(input: EditInput): Promise<MutationResult> {
93
93
  type: input.type || target.type,
94
94
  scope: input.scope || target.scope,
95
95
  content: input.content,
96
- // Omitted metadata survives the edit (#129): the usual UI sends
96
+ // Omitted metadata survives the edit: the usual UI sends
97
97
  // type/scope/content/reason, and dropping the old issue/tags/kw erased
98
98
  // import/auto-capture provenance and retrieval aliases from a row whose
99
99
  // prose only got a typo fix.
@@ -128,7 +128,7 @@ export async function editMemory(input: EditInput): Promise<MutationResult> {
128
128
  reason: input.reason,
129
129
  snapshot: snapshot[0] ?? "-",
130
130
  op: "write",
131
- // #305: the line inherits the target's repository, so a repo-B edit is
131
+ // the line inherits the target's repository, so a repo-B edit is
132
132
  // private to B (and admin), never a global broadcast of the reason.
133
133
  ...targetRepoFields(target),
134
134
  });
@@ -183,7 +183,7 @@ export async function deleteMemory(
183
183
  snapshot: snapshot[0] ?? "-",
184
184
  audit: deletionsFile(),
185
185
  tool: "memory_viewer",
186
- // #305: same inheritance as viewer_edit — a delete of a private row is
186
+ // same inheritance as viewer_edit — a delete of a private row is
187
187
  // not a globally readable event.
188
188
  ...targetRepoFields(target),
189
189
  });
@@ -214,13 +214,13 @@ async function audit(
214
214
  type: mem.type,
215
215
  scope: mem.scope,
216
216
  content: mem.content,
217
- // Origin survives the audit record (#129): the viewer's restore-entry
217
+ // Origin survives the audit record: the viewer's restore-entry
218
218
  // path reads these lines, and a restore of a repo-private row must be
219
219
  // able to re-stamp what was deleted. A line with no stamp is the
220
220
  // legacy/unstamped case — restore leaves it global, as documented.
221
221
  repo: mem.repo,
222
222
  repoPath: mem.repoPath,
223
- // #207: tags (which carry quarantine), kw, issue and status survive the
223
+ // tags (which carry quarantine), kw, issue and status survive the
224
224
  // same way, so restoring a deleted row cannot silently release
225
225
  // quarantine or drop provenance. Absent metadata writes nothing — the
226
226
  // legacy fallback the restore path documents.
@@ -228,14 +228,14 @@ async function audit(
228
228
  kw: mem.kw?.length ? mem.kw.join(",") : undefined,
229
229
  issue: mem.issue,
230
230
  status: mem.status,
231
- // Same write-boundary rule as evidence (#128): an audit reason is
231
+ // Same write-boundary rule as evidence: an audit reason is
232
232
  // human prose and must not persist a recognized credential.
233
233
  reason: redactSecrets(reason),
234
234
  }),
235
235
  );
236
236
  }
237
237
 
238
- // F1 on #308: the origin lookup must NOT go through loadAll(). loadAll
238
+ // The origin lookup must NOT go through loadAll(). loadAll
239
239
  // intentionally hides blocklisted rows, but releaseQuarantine scans the raw
240
240
  // day files and acts on them anyway — so a blocked private row released from
241
241
  // the viewer resolved to no target, and its evidence line fell back to the
@@ -270,9 +270,9 @@ export async function releaseQuarantinedMemory(
270
270
  // is pinned by the route rejection test; direct callers still need this one.
271
271
  requireReason(reason);
272
272
  // Resolve the target's origin BEFORE releasing so the audit line can
273
- // inherit it (#305). A not_found noop has no row — no origin exists to
273
+ // inherit it. A not_found noop has no row — no origin exists to
274
274
  // carry, and the line names nothing private, so it stays unstamped. The
275
- // lookup is unfiltered (F1 on #308): a blocklisted row is still a row the
275
+ // lookup is unfiltered (F1 on): a blocklisted row is still a row the
276
276
  // release below can act on, and its evidence must carry its repo.
277
277
  const target = await findTargetOrigin(ts);
278
278
  const outcome = await releaseQuarantine(ts);
@@ -303,7 +303,7 @@ export async function releaseQuarantinedMemory(
303
303
  }
304
304
 
305
305
  // Blocking is a human rejection, so it tombstones the VALUE as well as hiding
306
- // the row (#35): without that, re-ingesting the source stores the same content
306
+ // the row: without that, re-ingesting the source stores the same content
307
307
  // again under a fresh `ts` and the block silently stops protecting anything.
308
308
  // Order matters — the block is what the operator asked for and lands first; a
309
309
  // failure to tombstone leaves the row hidden (no data loss) rather than the
@@ -329,7 +329,7 @@ export async function blockMemory(input: {
329
329
  // back in view. The tombstone is keyed on the value, so this withdraws the
330
330
  // rejection of that content wherever else a copy of it was blocked; that is the
331
331
  // same decision the tombstone made when it was written.
332
- // The lift is conditional on an actual un-block (#209): a no-op on a row that
332
+ // The lift is conditional on an actual un-block: a no-op on a row that
333
333
  // was never blocked must not withdraw the rejection still guarding a blocked
334
334
  // identical copy, which would let the value be re-ingested.
335
335
  export async function unblockMemory(ts: string): Promise<boolean> {
@@ -340,7 +340,7 @@ export async function unblockMemory(ts: string): Promise<boolean> {
340
340
  return true;
341
341
  }
342
342
 
343
- // The explicit un-tombstone escape hatch (#35): lifts a rejection recorded by
343
+ // The explicit un-tombstone escape hatch: lifts a rejection recorded by
344
344
  // `forget`, which has no row left to un-block. Human-only — this is reachable
345
345
  // from the viewer and deliberately from NO plugin tool, so a session whose
346
346
  // write was refused cannot clear its own refusal and retry in the same turn.
@@ -1,5 +1,5 @@
1
1
  // Viewer writes are deliberate admin edits, independent of model grounding
2
- // gates. They still honor value rejections until an explicit release (#222).
2
+ // gates. They still honor value rejections until an explicit release.
3
3
  import { redactSecrets } from "../store/secrets.ts";
4
4
  import { probeRejection } from "../store/tombstones/rejection.ts";
5
5
 
@@ -4,7 +4,7 @@
4
4
  // through the same loadAll() used by recall/inject (so blocked entries are
5
5
  // hidden), and all mutations are non-destructive (snapshot + audit + supersede).
6
6
  // I2: serves only file data; never writes into any repo.
7
- // #223: a non-loopback bind or allowed host mints a startup token (0600, in
7
+ // A non-loopback bind or allowed host mints a startup token (0600, in
8
8
  // the store root) and every request must present it; loopback stays open.
9
9
  import { basename, join } from "node:path";
10
10
  import { linkSync, readFileSync, renameSync, rmSync } from "node:fs";
@@ -104,11 +104,10 @@ function isLoopbackHostname(name: string): boolean {
104
104
  return host === "::1" || host === "0:0:0:0:0:0:0:1";
105
105
  }
106
106
 
107
- // #223: exposure without authentication was the defect — with a non-loopback
108
- // bind (or an allowed non-loopback name) every read and mutation was open HTTP
109
- // for the whole LAN. A token is now minted at startup and every request must
110
- // present it: the Host/Origin layer stays as the CSRF defence it always was,
111
- // but it is no longer the only thing between the LAN and the store.
107
+ // A non-loopback bind or allowed host must not expose the store as open HTTP:
108
+ // a token is minted at startup and every request must present it. The
109
+ // Host/Origin layer stays as the CSRF defence it always was, but it is not
110
+ // the only thing between the LAN and the store.
112
111
  const TOKEN_FILE = "viewer.token";
113
112
  const TOKEN_COOKIE = "osi-viewer";
114
113
  const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
@@ -120,26 +119,25 @@ function tokenPath(): string {
120
119
  // Reuse a token already in the file so a restart does not invalidate URLs a
121
120
  // human has open (and two viewers sharing a store share one token); mint a
122
121
  // fresh one otherwise. Concurrent first starts — same process or separate
123
- // processes — must agree on ONE token (F1, #223 review): the claim is an
124
- // atomic hard-link of a fully-written 0600 temp, so exactly one starter's
125
- // content lands at the path (link(2) refuses an existing target), and every
126
- // loser reads back the winner's complete token instead of overwriting the
127
- // file with its own.
122
+ // processes — must agree on ONE token: the claim is an atomic hard-link of a
123
+ // fully-written 0600 temp, so exactly one starter's content lands at the path
124
+ // (link(2) refuses an existing target), and every loser reads back the
125
+ // winner's complete token instead of overwriting the file with its own.
128
126
  //
129
- // F1 residual (#223 review round 2): the hard-link claim solves an ABSENT
130
- // file, not a CORRUPT one — two starters that both read the same corrupt
131
- // winner used to replace it unconditionally, disagreeing on Linux and
132
- // throwing EPERM on Windows. Recovery is now serialized twice over: within
133
- // one process every mint runs through this promise chain, so the second
134
- // starter re-reads the repaired file instead of racing the repair; across
135
- // processes an O_EXCL lock file elects one repairman and the others adopt
136
- // its token. A replacement is never unconditional.
127
+ // The hard-link claim solves an ABSENT file, not a CORRUPT one. Replacing a
128
+ // corrupt file unconditionally makes concurrent starters disagree on Linux and
129
+ // throw EPERM on Windows, so recovery is serialized twice over: within one
130
+ // process every mint runs through this promise chain, so the second starter
131
+ // re-reads the repaired file instead of racing the repair; across processes an
132
+ // O_EXCL lock file elects one repairman and the others adopt its token. A
133
+ // replacement is never unconditional.
137
134
  //
138
- // F3 (#223 review round 2): the reuse path must enforce the 0600 contract
139
- // too. preparePrivateFile tightens an existing file to owner-only (keeping
140
- // owner bits, refusing a final-component symlink), so a token file left
141
- // world-readable is repaired before it is accepted — restoring what the
142
- // round-1 early return bypassed.
135
+ // The reuse path enforces the 0600 contract too. preparePrivateFile tightens
136
+ // an existing file to owner-only (keeping owner bits, refusing a
137
+ // final-component symlink), so a token file left world-readable is repaired
138
+ // before it is accepted.
139
+ //
140
+ // History: docs/adr/0004.
143
141
  let mintTail: Promise<unknown> = Promise.resolve();
144
142
 
145
143
  function mintViewerToken(): Promise<string> {
@@ -183,16 +181,16 @@ async function mintTokenOnce(): Promise<string> {
183
181
  }
184
182
 
185
183
  // Repair a corrupt token file: exactly one starter replaces the file and the
186
- // rest adopt its token (F1 residual, #223 review). The repair also keeps Windows
187
- // from renaming onto a file a rival starter is mid-read — the observed EPERM.
184
+ // rest adopt its token. The repair also keeps Windows from renaming onto a
185
+ // file a rival starter is mid-read — the EPERM that motivated it.
186
+ //
187
+ // It takes the STORE's lock. Lock state must not live in a directory entry:
188
+ // on Windows an O_EXCL marker outlives the holder whenever a third-party
189
+ // handle is open without FILE_SHARE_DELETE, and an age-based steal cannot
190
+ // rescue that case because the steal is itself an unlink subject to the same
191
+ // refusal — a viewer that hit it could never start again.
188
192
  //
189
- // It takes the STORE's lock to do it. It used to take its own O_EXCL
190
- // `.recover` file, which is the #407 shape exactly: the state of the lock lived
191
- // in a directory entry, and on Windows that entry outlives the holder whenever
192
- // a third-party handle is open without FILE_SHARE_DELETE. The age-based steal
193
- // here could not rescue that case either, because the steal is itself an unlink
194
- // and the same refusal applies to it — a viewer that hit it could never start
195
- // again.
193
+ // History: docs/adr/0004.
196
194
  async function recoverCorruptToken(
197
195
  path: string,
198
196
  tmp: string,
@@ -220,8 +218,8 @@ function tokenMatches(candidate: string, expected: string): boolean {
220
218
 
221
219
  // No decodeURIComponent: the cookie is a fixed-hex token we mint and set
222
220
  // verbatim, and decoding junk like `osi-viewer=%` throws URIError on the
223
- // auth path — a 500 where a malformed credential must simply be refused
224
- // (N1, #223 review). The raw value cannot match, so it falls through to 401.
221
+ // auth path — a 500 where a malformed credential must simply be refused.
222
+ // The raw value cannot match, so it falls through to 401.
225
223
  function cookieValue(req: Request, name: string): string | null {
226
224
  for (const part of (req.headers.get("cookie") ?? "").split(";")) {
227
225
  const eq = part.indexOf("=");
@@ -270,11 +268,11 @@ interface Row {
270
268
  scope: string;
271
269
  content: string;
272
270
  reason?: string;
273
- // Origin stamp (#129): what the row carried when it was deleted, so the
271
+ // Origin stamp: what the row carried when it was deleted, so the
274
272
  // restore-entry round trip can restore the row's ORIGINAL visibility.
275
273
  repo?: string;
276
274
  repoPath?: string;
277
- // #207: the deleted row's metadata, read back from the audit line, so the
275
+ // the deleted row's metadata, read back from the audit line, so the
278
276
  // deleted-entry UI can show WHAT is being restored — in particular whether
279
277
  // it is quarantined. Only deletion rows carry these; blocked rows do not.
280
278
  tags?: string[];
@@ -291,7 +289,7 @@ function splitScalar(value: unknown): string[] | undefined {
291
289
  : undefined;
292
290
  }
293
291
 
294
- // The metadata a deletion audit line carries for the deleted row (#207).
292
+ // The metadata a deletion audit line carries for the deleted row.
295
293
  // Kept out of the client contract: restore resolves it here, from the store's
296
294
  // own record, rather than trusting replayed bytes.
297
295
  interface DeletionMeta {
@@ -336,7 +334,7 @@ async function deletedRows(): Promise<Row[]> {
336
334
  content: String(f.content ?? ""),
337
335
  reason: String(f.reason ?? ""),
338
336
  ...meta,
339
- // #207: the operator must SEE that a deleted row was quarantined —
337
+ // the operator must SEE that a deleted row was quarantined —
340
338
  // restoring it must not read as a way to release quarantine.
341
339
  ...(meta.tags
342
340
  ? { quarantined: isQuarantined({ tags: meta.tags }) }
@@ -346,9 +344,9 @@ async function deletedRows(): Promise<Row[]> {
346
344
  }
347
345
 
348
346
  // The authoritative record of what a deleted row carried, keyed by the deleted
349
- // row's ts (#207). The LAST matching line wins: a row edited then deleted has
350
- // its newest state last, and that is the state a restore re-adds. Lines
351
- // written before #207 carry no metadata — the documented fallback.
347
+ // row's ts. The LAST matching line wins: a row edited then deleted has
348
+ // its newest state last, and that is the state a restore re-adds. Audit lines
349
+ // written before deletion metadata existed carry none — the documented fallback.
352
350
  async function deletionAuditFor(ts: string): Promise<DeletionMeta | undefined> {
353
351
  let found: DeletionMeta | undefined;
354
352
  for (const line of await readLines(deletionsFile())) {
@@ -359,7 +357,7 @@ async function deletionAuditFor(ts: string): Promise<DeletionMeta | undefined> {
359
357
  return found;
360
358
  }
361
359
 
362
- // Same record, keyed by the deleted row's identity instead of its ts (#207 F2).
360
+ // Same record, keyed by the deleted row's identity instead of its ts.
363
361
  // A restore request that omits ts is a legacy REQUEST, not a legacy record:
364
362
  // if the audit carries a matching line, that line is still the authoritative
365
363
  // copy of what the row carried, and resolving it here closes the laundering
@@ -460,7 +458,7 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
460
458
  const bootstrap =
461
459
  url.pathname === "/" ? url.searchParams.get("token") : null;
462
460
  // Validate every presentation instead of taking the first PRESENT
463
- // one (F2, #223 review): a stale cookie from before a supported
461
+ // one (F2): a stale cookie from before a supported
464
462
  // token regeneration must not shadow the freshly printed bootstrap
465
463
  // URL. A request with no valid credential is still refused.
466
464
  const accepted =
@@ -532,7 +530,7 @@ async function loaded(): Promise<Record<string, unknown>> {
532
530
  })),
533
531
  blocked,
534
532
  deleted,
535
- // #35: the value-keyed rejections. Hashes and metadata only — the store
533
+ // the value-keyed rejections. Hashes and metadata only — the store
536
534
  // never held the prose, so there is nothing to reveal here either. The
537
535
  // sketch is omitted: it is matching machinery, not something a reader can
538
536
  // act on.
@@ -626,7 +624,7 @@ async function unblockRoute(
626
624
  return json({ unblocked: await unblockMemory(body.ts) });
627
625
  }
628
626
 
629
- // The only way a rejection is ever lifted (#35). Human-only: the plugin exposes
627
+ // The only way a rejection is ever lifted. Human-only: the plugin exposes
630
628
  // no tool for this, so a session whose write was refused cannot clear the
631
629
  // refusal and re-submit the rejected value.
632
630
  async function unrejectRoute(
@@ -639,7 +637,7 @@ async function restoreEntryRoute(
639
637
  body: z.infer<typeof RestoreEntryBody>,
640
638
  ): Promise<Response> {
641
639
  await assertViewerWriteAllowed(body.content);
642
- // #207: every field that controls visibility or provenance is resolved from
640
+ // every field that controls visibility or provenance is resolved from
643
641
  // the audit line itself — the store's own record — so a restore cannot
644
642
  // silently release quarantine (the quarantine tags come back with the row;
645
643
  // releasing it stays the deliberate, reason-required release-quarantine
@@ -649,8 +647,8 @@ async function restoreEntryRoute(
649
647
  // before any fallback: an unknown explicit ts is an unresolved identity, not
650
648
  // permission to replay (F2 residual). Without ts the lookup is by
651
649
  // type/scope/content directly. Either way, omitting or missing ts cannot
652
- // launder a KNOWN quarantined row back to injectable (F2). The client-replay
653
- // fallback (#129 origin stamp, no metadata) survives only for rows the audit
650
+ // launder a KNOWN quarantined row back to injectable (F2). The origin-stamp
651
+ // fallback (no metadata) survives only for rows the audit
654
652
  // does not carry at all — a legacy record, not a legacy request.
655
653
  const src =
656
654
  (body.ts && (await deletionAuditFor(body.ts))) ||