opencode-self-improvement 0.15.18 → 0.15.20

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 (93) hide show
  1. package/README.md +4 -0
  2. package/package.json +4 -2
  3. package/src/capture/candidates.ts +17 -6
  4. package/src/capture/lag.ts +6 -2
  5. package/src/capture/prompt.ts +1 -1
  6. package/src/capture/runtime.ts +85 -21
  7. package/src/capture/session-model.ts +2 -1
  8. package/src/capture/transcript.ts +10 -4
  9. package/src/capture/triggers.ts +48 -14
  10. package/src/command/ensure.ts +6 -1
  11. package/src/consolidate/propose.ts +47 -17
  12. package/src/consolidate/render.ts +3 -1
  13. package/src/core/cmp-ts.ts +2 -2
  14. package/src/core/config/budgets.ts +0 -1
  15. package/src/core/config/paths.ts +2 -3
  16. package/src/core/hooks.ts +8 -3
  17. package/src/core/host.ts +8 -3
  18. package/src/core/logfmt/format.ts +20 -5
  19. package/src/core/logfmt/publish.ts +21 -4
  20. package/src/core/lru.ts +20 -20
  21. package/src/core/permissions.ts +21 -5
  22. package/src/core/runtime.ts +7 -3
  23. package/src/core/state.ts +12 -2
  24. package/src/core/time.ts +0 -1
  25. package/src/core/tokenize.ts +16 -5
  26. package/src/core/types.ts +8 -1
  27. package/src/events.ts +74 -18
  28. package/src/evidence/record.ts +29 -9
  29. package/src/gate/gate.ts +244 -94
  30. package/src/gate/resolver.ts +105 -20
  31. package/src/hits/ledger.ts +35 -10
  32. package/src/identity/host-events.ts +35 -11
  33. package/src/identity/repokey.ts +27 -9
  34. package/src/identity/session-context.ts +39 -8
  35. package/src/index.ts +108 -42
  36. package/src/init/detect.ts +62 -12
  37. package/src/init/run.ts +50 -11
  38. package/src/inject/anchor.ts +11 -5
  39. package/src/inject/attribution.ts +29 -6
  40. package/src/inject/budget.ts +9 -2
  41. package/src/inject/digest.ts +16 -8
  42. package/src/inject/epochs.ts +43 -15
  43. package/src/inject/pull.ts +11 -5
  44. package/src/inject/version.ts +10 -5
  45. package/src/portable/decay.ts +20 -9
  46. package/src/portable/export.ts +30 -10
  47. package/src/portable/import.ts +43 -12
  48. package/src/recall/relevant.ts +11 -5
  49. package/src/recall/score.ts +5 -3
  50. package/src/status/format.ts +8 -2
  51. package/src/status/metrics.ts +22 -6
  52. package/src/status/payload.ts +7 -2
  53. package/src/status/report.ts +63 -18
  54. package/src/status/write.ts +21 -7
  55. package/src/store/blocklist.ts +16 -4
  56. package/src/store/containment.ts +27 -8
  57. package/src/store/files/append.ts +57 -37
  58. package/src/store/files/deletions.ts +5 -2
  59. package/src/store/files/load.ts +37 -11
  60. package/src/store/files/prune.ts +18 -5
  61. package/src/store/files/snapshots.ts +6 -2
  62. package/src/store/files/supersede.ts +32 -12
  63. package/src/store/files/target.ts +4 -1
  64. package/src/store/lock.ts +10 -2
  65. package/src/store/model/visibility.ts +26 -6
  66. package/src/store/prune.ts +1 -1
  67. package/src/store/quarantine/quarantine.ts +36 -9
  68. package/src/store/quarantine/release.ts +9 -3
  69. package/src/store/secrets.ts +4 -2
  70. package/src/store/tombstones/rejection.ts +21 -5
  71. package/src/store/tombstones/tombstone.ts +48 -11
  72. package/src/store/undo.ts +43 -18
  73. package/src/tools/consolidate.ts +18 -8
  74. package/src/tools/decay.ts +37 -9
  75. package/src/tools/deps.ts +10 -2
  76. package/src/tools/evidence.ts +7 -4
  77. package/src/tools/export.ts +10 -4
  78. package/src/tools/forget.ts +15 -5
  79. package/src/tools/import.ts +16 -5
  80. package/src/tools/init.ts +13 -4
  81. package/src/tools/list.ts +12 -6
  82. package/src/tools/merge-review.ts +52 -20
  83. package/src/tools/recall.ts +17 -9
  84. package/src/tools/registry.ts +4 -1
  85. package/src/tools/remember.ts +21 -7
  86. package/src/tools/schema.ts +55 -18
  87. package/src/tools/status-tool.ts +29 -11
  88. package/src/tools/undo.ts +23 -8
  89. package/src/tools/update.ts +116 -40
  90. package/src/tui/panel.tsx +119 -30
  91. package/src/viewer/mutate.ts +57 -20
  92. package/src/viewer/rejections.ts +1 -1
  93. package/src/viewer/server.ts +88 -28
@@ -1,19 +1,28 @@
1
1
  // Per-setup injection epochs. Host event parsing and identity binding stay in
2
2
  // index.ts; this module owns frozen bytes, refresh decisions, and their status.
3
- import { loadAll, malformedCount } from "../store/files/load.ts"
4
- import { type Memory } from "../store/model/memory.ts"
5
- import { isInjectable } from "../store/model/predicates.ts"
3
+ import { loadAll, malformedCount } from "../store/files/load.ts";
4
+ import { type Memory } from "../store/model/memory.ts";
5
+ import { isInjectable } from "../store/model/predicates.ts";
6
6
  import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
7
7
  import { SESSION_CAP, SessionLru } from "../core/lru.ts";
8
8
  import { record } from "../evidence/record.ts";
9
- import { capToBudget, injectedRows } from "./budget.ts"
10
- import { systemDigest } from "./digest.ts"
11
- import { storeVersion } from "./version.ts"
9
+ import { capToBudget, injectedRows } from "./budget.ts";
10
+ import { systemDigest } from "./digest.ts";
11
+ import { storeVersion } from "./version.ts";
12
12
  import { selectRelevant } from "../recall/relevant.ts";
13
- import { attributeSession, deriveMemoryRefs, type MemoryRefs } from "./attribution.ts";
13
+ import {
14
+ attributeSession,
15
+ deriveMemoryRefs,
16
+ type MemoryRefs,
17
+ } from "./attribution.ts";
14
18
  import { readLedger, useSignals } from "../hits/ledger.ts";
15
19
  import { summarizeStore } from "../status/store-summary.ts";
16
- import { emptyStats, type Measured, type SessionStats, type StatusPayload } from "../status/payload.ts"
20
+ import {
21
+ emptyStats,
22
+ type Measured,
23
+ type SessionStats,
24
+ type StatusPayload,
25
+ } from "../status/payload.ts";
17
26
  import { writeStatus } from "../status/write.ts";
18
27
  import { callsFor } from "../capture/triggers.ts";
19
28
  import { authoredFor } from "../core/state.ts";
@@ -135,7 +144,9 @@ export function createInjectionEpochs({
135
144
  // session's repo into this one's system prompt.
136
145
  const injectableRows = async (sid?: string): Promise<Memory[]> => {
137
146
  const reader = readerFromSid(sid);
138
- return (await loadAll()).filter((m) => isInjectable(m) && isVisibleTo(m, reader));
147
+ return (await loadAll()).filter(
148
+ (m) => isInjectable(m) && isVisibleTo(m, reader),
149
+ );
139
150
  };
140
151
  // Render the COMPLETE memory section for one request: the standing digest,
141
152
  // the open-thread frontier and the convergence line (all from systemDigest),
@@ -147,14 +158,22 @@ export function createInjectionEpochs({
147
158
  sid: string | undefined,
148
159
  mems: Memory[],
149
160
  promptOverride?: string,
150
- ): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
161
+ ): Promise<{
162
+ parts: string[];
163
+ block: string;
164
+ prefix: string;
165
+ rode: Memory[];
166
+ refs: MemoryRefs;
167
+ }> => {
151
168
  const parts: string[] = [];
152
169
  await systemDigest(
153
170
  { sessionID: sid },
154
171
  { system: parts },
155
172
  { rows: mems, frontierBudget: openBudget },
156
173
  );
157
- const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
174
+ const prompt =
175
+ promptOverride ??
176
+ (sid === undefined ? "" : (latestPrompt.get(sid) ?? ""));
158
177
  // Widen the candidate pool, then cap: the budget decides what rides.
159
178
  const sel = await selectRelevant(prompt, 5, mems, await useSignals());
160
179
  const block = sel.block ? capToBudget(sel.block, budget) : "";
@@ -194,7 +213,9 @@ export function createInjectionEpochs({
194
213
  // viewer edit, an import, a moved convergence line.
195
214
  if (cached) {
196
215
  const mine = authoredFor(sid);
197
- const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
216
+ const extra = mems.filter(
217
+ (m) => mine.has(m.ts) && !cached.ownRows.has(m.ts),
218
+ );
198
219
  if (extra.length) {
199
220
  const back = await buildMemorySection(
200
221
  sid,
@@ -214,13 +235,17 @@ export function createInjectionEpochs({
214
235
  // rows that were already offered under the frozen epoch.
215
236
  await noteHits(sid, built.rode, prompt);
216
237
  const at = new Date().toISOString();
217
- const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
238
+ const reason: "first" | "store_changed" = cached
239
+ ? "store_changed"
240
+ : "first";
218
241
  epoch.set(sid, {
219
242
  version,
220
243
  parts: built.parts,
221
244
  block: built.block,
222
245
  prefix: built.prefix,
223
- ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
246
+ ownRows: new Set(
247
+ mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts),
248
+ ),
224
249
  prompt,
225
250
  at,
226
251
  reason,
@@ -252,7 +277,10 @@ export function createInjectionEpochs({
252
277
 
253
278
  // Push each part in the original order. Accounting follows delivery so a
254
279
  // throwing host callback leaves request accounting unchanged.
255
- const deliver = async (sid: string | undefined, push: (text: string) => void): Promise<void> => {
280
+ const deliver = async (
281
+ sid: string | undefined,
282
+ push: (text: string) => void,
283
+ ): Promise<void> => {
256
284
  const mems = await injectableRows(sid);
257
285
  if (typeof sid === "string") await refreshEpoch(sid, mems);
258
286
  // Deliver the FROZEN memory section. Every byte pushed onto the system
@@ -1,7 +1,7 @@
1
1
  // pull — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
2
- import { loadAll } from "../store/files/load.ts"
3
- import { type Memory } from "../store/model/memory.ts"
4
- import { isInjectable } from "../store/model/predicates.ts"
2
+ import { loadAll } from "../store/files/load.ts";
3
+ import { type Memory } from "../store/model/memory.ts";
4
+ import { isInjectable } from "../store/model/predicates.ts";
5
5
  import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
6
6
  import { injectBudget } from "../core/config/budgets.ts";
7
7
  import { FRAME, capToBudget, injectedRows } from "./budget.ts";
@@ -37,11 +37,17 @@ export async function contextualPull(
37
37
  if (!term) return [];
38
38
  // Repo-scoped: model-facing reads see the CALLER's repo + global rows —
39
39
  // the pull's own sessionID, resolved before the store read (#127).
40
- const mems = visibleTo((await loadAll()).filter(isInjectable), readerFromSid(input.sessionID));
40
+ const mems = visibleTo(
41
+ (await loadAll()).filter(isInjectable),
42
+ readerFromSid(input.sessionID),
43
+ );
41
44
  const top = scoreMemories(term, mems, 3, use);
42
45
  if (!top.length) return [];
43
46
  // Held to the injection budget too: three long rows were ~12 KB per call.
44
- const block = capToBudget(`## Related durable memory (pull)${FRAME}\n${top.map(formatMemory).join("\n")}`, budget);
47
+ const block = capToBudget(
48
+ `## Related durable memory (pull)${FRAME}\n${top.map(formatMemory).join("\n")}`,
49
+ budget,
50
+ );
45
51
  if (block && typeof output.output === "string") {
46
52
  output.output += `\n${block}`;
47
53
  // What the ledger counts is what actually rode the result — the budget can
@@ -4,9 +4,9 @@
4
4
  // session context hook's system parts. Contextual pull appends relevant memory
5
5
  // to grep/glob/read results. Evidence is never injected.
6
6
  import { createHash } from "node:crypto";
7
- import { loadAll } from "../store/files/load.ts"
8
- import { type Memory } from "../store/model/memory.ts"
9
- import { isInjectable } from "../store/model/predicates.ts"
7
+ import { loadAll } from "../store/files/load.ts";
8
+ import { type Memory } from "../store/model/memory.ts";
9
+ import { isInjectable } from "../store/model/predicates.ts";
10
10
  import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
11
11
  import { cmpTs } from "../core/cmp-ts.ts";
12
12
  import { formatMemory } from "./format.ts";
@@ -16,9 +16,14 @@ import { formatMemory } from "./format.ts";
16
16
  // changes and supersession all invalidate an epoch, while evidence, hidden
17
17
  // rows and non-rendered metadata do not. This is only a linear hash over rows
18
18
  // loadAll() already had to read and parse for the request.
19
- export async function storeVersion(rows?: Memory[], sid?: string): Promise<string> {
19
+ export async function storeVersion(
20
+ rows?: Memory[],
21
+ sid?: string,
22
+ ): Promise<string> {
20
23
  // Repo-scoped: model-facing reads see the caller's repo + global rows.
21
- const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(isInjectable);
24
+ const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(
25
+ isInjectable,
26
+ );
22
27
  if (!mems.length) return "0:";
23
28
  let max = "";
24
29
  const hash = createHash("sha256");
@@ -1,20 +1,31 @@
1
1
  // decay — split from src/portable.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
  import { open } from "node:fs/promises";
3
- import { loadAll } from "../store/files/load.ts"
4
- import { type Memory } from "../store/model/memory.ts"
5
- import { isInjectable } from "../store/model/predicates.ts"
3
+ import { loadAll } from "../store/files/load.ts";
4
+ import { type Memory } from "../store/model/memory.ts";
5
+ import { isInjectable } from "../store/model/predicates.ts";
6
6
  import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
7
7
 
8
8
  // --- decay support --------------------------------------------------------------
9
9
 
10
10
  // Active open threads with ts older than `days` days, oldest first (both sides
11
11
  // are UTC-Z ISO strings, so plain lexicographic compare is correct).
12
- export async function findStaleOpen(days: number, sid?: string): Promise<Memory[]> {
12
+ export async function findStaleOpen(
13
+ days: number,
14
+ sid?: string,
15
+ ): Promise<Memory[]> {
13
16
  const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
14
17
  const reader = readerFromSid(sid);
15
- return (await loadAll())
16
- // Decay is repo-scoped: running it here must not retire
17
- // another repo's open threads.
18
- .filter((m) => isInjectable(m) && isVisibleTo(m, reader) && m.status === "open" && m.ts < cutoff)
19
- .sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));
18
+ return (
19
+ (await loadAll())
20
+ // Decay is repo-scoped: running it here must not retire
21
+ // another repo's open threads.
22
+ .filter(
23
+ (m) =>
24
+ isInjectable(m) &&
25
+ isVisibleTo(m, reader) &&
26
+ m.status === "open" &&
27
+ m.ts < cutoff,
28
+ )
29
+ .sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0))
30
+ );
20
31
  }
@@ -8,11 +8,15 @@ import { constants } from "node:fs";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import { mkdir, open } from "node:fs/promises";
10
10
  import { dirname, join } from "node:path";
11
- import { allowOutsideStorePaths, exportsDir, memoryRoot } from "../core/config/paths.ts";
11
+ import {
12
+ allowOutsideStorePaths,
13
+ exportsDir,
14
+ memoryRoot,
15
+ } from "../core/config/paths.ts";
12
16
  import { resolveContained } from "../store/containment.ts";
13
- import { loadAll } from "../store/files/load.ts"
14
- import { redactSecrets } from "../store/secrets.ts"
15
- import { isActive } from "../store/model/predicates.ts"
17
+ import { loadAll } from "../store/files/load.ts";
18
+ import { redactSecrets } from "../store/secrets.ts";
19
+ import { isActive } from "../store/model/predicates.ts";
16
20
  import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
17
21
 
18
22
  // --- export -------------------------------------------------------------------
@@ -83,7 +87,8 @@ async function resolveExportTarget(file: string | undefined): Promise<string> {
83
87
  // copy outside the store on the argument-free call — the one a model reaches
84
88
  // without knowing anything about the layout. Under the operator escape hatch
85
89
  // there is nothing to check, so the plain join is what remains.
86
- if (file === undefined && allowOutside) return join(exportsDir(), `${stamp()}.jsonl`);
90
+ if (file === undefined && allowOutside)
91
+ return join(exportsDir(), `${stamp()}.jsonl`);
87
92
  return resolveContained(file ?? `${stamp()}.jsonl`, exportsDir(), opts);
88
93
  }
89
94
 
@@ -101,7 +106,11 @@ async function resolveExportTarget(file: string | undefined): Promise<string> {
101
106
  // Exported so the flag itself can be pinned: the containment layer refuses an
102
107
  // existing link long before this runs, so the only way to test O_NOFOLLOW
103
108
  // without racing is to call the writer directly.
104
- export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
109
+ export async function writeExport(
110
+ path: string,
111
+ text: string,
112
+ exclusive = false,
113
+ ): Promise<void> {
105
114
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
106
115
  // exclusive = a default destination WE chose: create it or fail, never
107
116
  // silently replace another export's file. An explicit caller-supplied
@@ -138,10 +147,14 @@ export async function writeExport(path: string, text: string, exclusive = false)
138
147
  // The destination is model-supplied, so it is resolved and confined BEFORE the
139
148
  // store is read: a rejected export must not leave a file behind, and must not
140
149
  // be a way to learn how many rows matched either.
141
- export async function exportMemories(opts: ExportOptions = {}): Promise<ExportResult> {
150
+ export async function exportMemories(
151
+ opts: ExportOptions = {},
152
+ ): Promise<ExportResult> {
142
153
  const path = await resolveExportTarget(opts.file);
143
154
  const reader = readerFromSid(opts.sessionID);
144
- let mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
155
+ let mems = (await loadAll())
156
+ .filter(isActive)
157
+ .filter((m) => isVisibleTo(m, reader));
145
158
  if (opts.scope) mems = mems.filter((m) => m.scope === opts.scope);
146
159
  const header = JSON.stringify({
147
160
  _export: EXPORT_HEADER,
@@ -170,13 +183,20 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
170
183
  }),
171
184
  );
172
185
  try {
173
- await writeExport(path, `${[header, ...lines].join("\n")}\n`, opts.file === undefined);
186
+ await writeExport(
187
+ path,
188
+ `${[header, ...lines].join("\n")}\n`,
189
+ opts.file === undefined,
190
+ );
174
191
  } catch (err) {
175
192
  // Past containment, so this is not an existence oracle: `path` is one the
176
193
  // plugin chose or already validated. The errno stays, because it is the
177
194
  // operator's only diagnostic — but in our sentence rather than the runtime's,
178
195
  // so a model-facing tool result never carries a raw stack-adjacent string.
179
- const code = err instanceof Error && "code" in err ? String(err.code) : "unknown error";
196
+ const code =
197
+ err instanceof Error && "code" in err
198
+ ? String(err.code)
199
+ : "unknown error";
180
200
  throw new Error(`memory_export could not write ${path} (${code})`);
181
201
  }
182
202
  return { path, count: mems.length };
@@ -2,7 +2,10 @@
2
2
  import { open, readFile } from "node:fs/promises";
3
3
  import { allowOutsideStorePaths, memoryRoot } from "../core/config/paths.ts";
4
4
  import { resolveContained } from "../store/containment.ts";
5
- import { isQuarantined, quarantineCandidate } from "../store/quarantine/quarantine.ts";
5
+ import {
6
+ isQuarantined,
7
+ quarantineCandidate,
8
+ } from "../store/quarantine/quarantine.ts";
6
9
  import { UnresolvedWriterError } from "../store/files/append.ts";
7
10
  import { writeTarget } from "../identity/repokey.ts";
8
11
  import { getCurrent } from "../core/state.ts";
@@ -40,26 +43,39 @@ function parseRow(line: string): WriteCandidate | null {
40
43
  }
41
44
  if (!row || typeof row !== "object" || Array.isArray(row)) return null;
42
45
  const r = row as Record<string, unknown>;
43
- if (typeof r.type !== "string" || !(TYPES as readonly string[]).includes(r.type)) return null;
46
+ if (
47
+ typeof r.type !== "string" ||
48
+ !(TYPES as readonly string[]).includes(r.type)
49
+ )
50
+ return null;
44
51
  if (typeof r.scope !== "string" || !r.scope.trim()) return null;
45
52
  if (flattenMemoryText(r.scope) !== r.scope) return null;
46
53
  if (typeof r.content !== "string" || !r.content.trim()) return null;
47
54
  if (
48
55
  Array.isArray(r.tags) &&
49
56
  r.tags.some((t) => typeof t === "string" && flattenMemoryText(t) !== t)
50
- ) return null;
51
- if (typeof r.issue === "string" && flattenMemoryText(r.issue) !== r.issue) return null;
57
+ )
58
+ return null;
59
+ if (typeof r.issue === "string" && flattenMemoryText(r.issue) !== r.issue)
60
+ return null;
52
61
  // Keywords widen recall only, so a malformed entry costs them, never the row
53
62
  // (contrast scope/content, where a bad value makes the line malformed).
54
63
  const kw = Array.isArray(r.kw)
55
64
  ? r.kw.filter(
56
65
  (k): k is string =>
57
- typeof k === "string" && !!k.trim() && flattenMemoryText(k.trim()) === k.trim(),
66
+ typeof k === "string" &&
67
+ !!k.trim() &&
68
+ flattenMemoryText(k.trim()) === k.trim(),
58
69
  )
59
70
  : undefined;
60
- const c: WriteCandidate = { type: r.type, scope: r.scope, content: r.content };
71
+ const c: WriteCandidate = {
72
+ type: r.type,
73
+ scope: r.scope,
74
+ content: r.content,
75
+ };
61
76
  if (r.status === "open" || r.status === "settled") c.status = r.status;
62
- if (Array.isArray(r.tags) && r.tags.every((t) => typeof t === "string")) c.tags = r.tags;
77
+ if (Array.isArray(r.tags) && r.tags.every((t) => typeof t === "string"))
78
+ c.tags = r.tags;
63
79
  if (kw?.length) c.kw = kw;
64
80
  if (typeof r.issue === "string" && r.issue) c.issue = r.issue;
65
81
  // Origin stamps survive an export/import hop (repokey.ts): a row written
@@ -92,7 +108,9 @@ function parseRow(line: string): WriteCandidate | null {
92
108
  // day files, snapshots and the blocklist, none of which are import formats.
93
109
  export async function importMemories(
94
110
  path: string,
95
- gate: (c: WriteCandidate) => Promise<{ action: string; evidenceError?: string }>,
111
+ gate: (
112
+ c: WriteCandidate,
113
+ ) => Promise<{ action: string; evidenceError?: string }>,
96
114
  // The importing session, captured at tool entry (#127): "the importing
97
115
  // session's current repo" must be the CALLER's repo even though this loop
98
116
  // awaits the gate on every row, during which a concurrent session can move
@@ -112,16 +130,26 @@ export async function importMemories(
112
130
  allowOutside: allowOutsideStorePaths(),
113
131
  });
114
132
  if (!target.toLowerCase().endsWith(".jsonl")) {
115
- throw new Error(`memory_import file must be a .jsonl export (got "${path}")`);
133
+ throw new Error(
134
+ `memory_import file must be a .jsonl export (got "${path}")`,
135
+ );
116
136
  }
117
137
  let text: string;
118
138
  try {
119
139
  text = await readFile(target, "utf8");
120
140
  } catch (err) {
121
- if ((err as NodeJS.ErrnoException).code === "ENOENT") throw new Error(`import file not found: ${target}`);
141
+ if ((err as NodeJS.ErrnoException).code === "ENOENT")
142
+ throw new Error(`import file not found: ${target}`);
122
143
  throw err;
123
144
  }
124
- const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
145
+ const tally: ImportTally = {
146
+ promoted: 0,
147
+ collapsed: 0,
148
+ blocked: 0,
149
+ skipped: 0,
150
+ downgraded: 0,
151
+ unaudited: 0,
152
+ };
125
153
  // Preserve file-validation error precedence, but reject an unresolved owner
126
154
  // before gating any row. Resolution happened at entry, not at this await.
127
155
  if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
@@ -154,7 +182,10 @@ export async function importMemories(
154
182
  if (c.repo !== currentScope.key) delete c.repo;
155
183
  if (c.repoPath !== currentScope.path) delete c.repoPath;
156
184
  }
157
- if (c.status === "open" && (!allowFrontier || claimedGlobal || (hadStamp && !currentScope))) {
185
+ if (
186
+ c.status === "open" &&
187
+ (!allowFrontier || claimedGlobal || (hadStamp && !currentScope))
188
+ ) {
158
189
  c.status = "settled";
159
190
  tally.downgraded++;
160
191
  }
@@ -1,7 +1,7 @@
1
1
  // relevant — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
2
- import { loadAll } from "../store/files/load.ts"
3
- import { type Memory } from "../store/model/memory.ts"
4
- import { isInjectable } from "../store/model/predicates.ts"
2
+ import { loadAll } from "../store/files/load.ts";
3
+ import { type Memory } from "../store/model/memory.ts";
4
+ import { isInjectable } from "../store/model/predicates.ts";
5
5
  import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
6
6
  import { FRAME } from "../inject/budget.ts";
7
7
  import { formatMemory } from "../inject/format.ts";
@@ -58,7 +58,9 @@ export async function selectRelevant(
58
58
  if (!text) return { block: "", selected: [] };
59
59
  // Repo-scoped: model-facing reads see the caller's repo + global rows
60
60
  // (their session when one was threaded, #127).
61
- const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(isInjectable);
61
+ const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(
62
+ isInjectable,
63
+ );
62
64
  const top = scoreMemories(text, mems, limit, use);
63
65
  if (!top.length) return { block: "", selected: [] };
64
66
  return {
@@ -67,6 +69,10 @@ export async function selectRelevant(
67
69
  };
68
70
  }
69
71
 
70
- export async function relevantKnowledge(message: string, limit = 3, rows?: Memory[]): Promise<string> {
72
+ export async function relevantKnowledge(
73
+ message: string,
74
+ limit = 3,
75
+ rows?: Memory[],
76
+ ): Promise<string> {
71
77
  return (await selectRelevant(message, limit, rows)).block;
72
78
  }
@@ -1,6 +1,6 @@
1
1
  // score — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
2
- import { loadAll } from "../store/files/load.ts"
3
- import { type Memory } from "../store/model/memory.ts"
2
+ import { loadAll } from "../store/files/load.ts";
3
+ import { type Memory } from "../store/model/memory.ts";
4
4
  import { isInjectable } from "../store/model/predicates.ts";
5
5
  import { cmpTs } from "../core/cmp-ts.ts";
6
6
  import { type UseSignals, useBoost } from "./relevant.ts";
@@ -19,7 +19,9 @@ export function words(text: string): string[] {
19
19
  // Memory-side tokens are never filtered: a memory stating "the" must not
20
20
  // gain or lose rank from it, only queries drive matching.
21
21
  export const QUERY_STOPWORDS = new Set(
22
- "a an and are at be but by can did do does for from had has have how i in into is it its me my no not of on or our so than that the their them then there these they this to us was we were what when where which who why will with you your run runs getting want needs right back yet also just still ever should would could might may must shall ought nothing something anything everything thing things".split(" "),
22
+ "a an and are at be but by can did do does for from had has have how i in into is it its me my no not of on or our so than that the their them then there these they this to us was we were what when where which who why will with you your run runs getting want needs right back yet also just still ever should would could might may must shall ought nothing something anything everything thing things".split(
23
+ " ",
24
+ ),
23
25
  );
24
26
 
25
27
  // A free-text prompt long enough to carry >= this many content tokens must
@@ -32,11 +32,17 @@ export function fmtCount(n: number): string {
32
32
  }
33
33
 
34
34
  /** Session-wide prompt-cache hit rate from measured usage; null = nothing measured. */
35
- export function cacheRate(m?: Measured | null): { read: number; prompt: number; pct: number } | null {
35
+ export function cacheRate(
36
+ m?: Measured | null,
37
+ ): { read: number; prompt: number; pct: number } | null {
36
38
  if (!m) return null;
37
39
  const prompt = (m.input || 0) + (m.read || 0) + (m.write || 0);
38
40
  if (prompt <= 0) return null;
39
- return { read: m.read || 0, prompt, pct: Math.round(((m.read || 0) / prompt) * 100) };
41
+ return {
42
+ read: m.read || 0,
43
+ prompt,
44
+ pct: Math.round(((m.read || 0) / prompt) * 100),
45
+ };
40
46
  }
41
47
 
42
48
  /**
@@ -1,7 +1,7 @@
1
1
  // metrics — split from src/status.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
  import { join } from "node:path";
3
3
  import { evidenceDir } from "../core/config/paths.ts";
4
- import { parseLine } from "../core/logfmt/format.ts"
4
+ import { parseLine } from "../core/logfmt/format.ts";
5
5
  import { readLines } from "../core/logfmt/read.ts";
6
6
 
7
7
  /**
@@ -9,7 +9,10 @@ import { readLines } from "../core/logfmt/read.ts";
9
9
  * line is younger than the window, or there is no ledger at all. Every "never
10
10
  * retrieved" surface must carry this qualifier when it returns true.
11
11
  */
12
- export function ledgerIsYoung(ledgerSince: string | null | undefined, now = Date.now()): boolean {
12
+ export function ledgerIsYoung(
13
+ ledgerSince: string | null | undefined,
14
+ now = Date.now(),
15
+ ): boolean {
13
16
  if (!ledgerSince) return true;
14
17
  return ledgerSince > new Date(now - 30 * 86_400_000).toISOString();
15
18
  }
@@ -18,12 +21,19 @@ export function ledgerIsYoung(ledgerSince: string | null | undefined, now = Date
18
21
  export function percentile(values: number[], q: number): number | null {
19
22
  if (!values.length) return null;
20
23
  const sorted = [...values].sort((a, b) => a - b);
21
- const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1));
24
+ const idx = Math.min(
25
+ sorted.length - 1,
26
+ Math.max(0, Math.ceil(q * sorted.length) - 1),
27
+ );
22
28
  return sorted[idx];
23
29
  }
24
30
 
25
31
  /** Rows created per day across `days`, counting only days the store saw activity. */
26
- export function rowsPerDay(rows: { ts: string }[], days = 30, now = Date.now()): number | null {
32
+ export function rowsPerDay(
33
+ rows: { ts: string }[],
34
+ days = 30,
35
+ now = Date.now(),
36
+ ): number | null {
27
37
  if (!rows.length) return null;
28
38
  const cutoff = new Date(now - days * 86_400_000).toISOString().slice(0, 10);
29
39
  const inWindow = rows.filter((m) => m.ts.slice(0, 10) >= cutoff);
@@ -38,7 +48,11 @@ export function rowsPerDay(rows: { ts: string }[], days = 30, now = Date.now()):
38
48
  * no timestamped message) are counted in `n` only through their outcome, never
39
49
  * as a zero lag.
40
50
  */
41
- export function captureLag(lines: string[], days = 30, now = Date.now()): { p50: number; p95: number; n: number } {
51
+ export function captureLag(
52
+ lines: string[],
53
+ days = 30,
54
+ now = Date.now(),
55
+ ): { p50: number; p95: number; n: number } {
42
56
  const cutoff = new Date(now - days * 86_400_000).toISOString();
43
57
  const lags: number[] = [];
44
58
  for (const line of lines) {
@@ -58,7 +72,9 @@ export async function captureLagLines(days = 30): Promise<string[]> {
58
72
  const dir = evidenceDir();
59
73
  const out: string[] = [];
60
74
  for (let d = 0; d < days; d++) {
61
- const day = new Date(Date.now() - d * 86_400_000).toISOString().split("T")[0]!;
75
+ const day = new Date(Date.now() - d * 86_400_000)
76
+ .toISOString()
77
+ .split("T")[0]!;
62
78
  out.push(...(await readLines(join(dir, `${day}.logfmt`))));
63
79
  }
64
80
  return out;
@@ -122,7 +122,10 @@ export interface BlockedRow {
122
122
  // by mtime (newest survive; a re-written session refreshes its mtime).
123
123
  export const SESSION_FILE_CAP = 32;
124
124
 
125
- export async function writeJson(path: string, p: StatusPayload): Promise<boolean> {
125
+ export async function writeJson(
126
+ path: string,
127
+ p: StatusPayload,
128
+ ): Promise<boolean> {
126
129
  try {
127
130
  preparePrivateFile(path);
128
131
  await Bun.write(path, JSON.stringify(p, null, 2) + "\n");
@@ -134,7 +137,9 @@ export async function writeJson(path: string, p: StatusPayload): Promise<boolean
134
137
 
135
138
  export async function readJson(path: string): Promise<StatusPayload | null> {
136
139
  try {
137
- const v: unknown = JSON.parse((await readFile(path, "utf8")).replace(/^\uFEFF/, ""));
140
+ const v: unknown = JSON.parse(
141
+ (await readFile(path, "utf8")).replace(/^\uFEFF/, ""),
142
+ );
138
143
  if (!v || typeof v !== "object") return null;
139
144
  const p = v as Partial<StatusPayload>;
140
145
  if (typeof p.at !== "string" || typeof p.block !== "string") return null;