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
@@ -32,7 +32,10 @@ export interface Gate1Result {
32
32
  missingPaths: string[];
33
33
  }
34
34
 
35
- export function balancedParen(text: string, openIdx: number): { inner: string; end: number } | null {
35
+ export function balancedParen(
36
+ text: string,
37
+ openIdx: number,
38
+ ): { inner: string; end: number } | null {
36
39
  if (text[openIdx] !== "(") return null;
37
40
  let depth = 0;
38
41
  let quote: string | null = null;
@@ -62,10 +65,45 @@ const CALL_RE = /([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+)\s*\(/g;
62
65
  // is a file reference followed by parenthetical prose, not a call to a method
63
66
  // named `json`.
64
67
  const FILE_EXT = new Set([
65
- "json", "jsonc", "jsonl", "logfmt", "md", "mdx", "ts", "tsx", "js", "jsx",
66
- "mjs", "cjs", "py", "go", "rs", "rb", "java", "kt", "sh", "bash", "zsh",
67
- "yaml", "yml", "toml", "ini", "conf", "cfg", "txt", "csv", "html", "htm",
68
- "css", "scss", "xml", "sql", "tf", "lock", "log", "env",
68
+ "json",
69
+ "jsonc",
70
+ "jsonl",
71
+ "logfmt",
72
+ "md",
73
+ "mdx",
74
+ "ts",
75
+ "tsx",
76
+ "js",
77
+ "jsx",
78
+ "mjs",
79
+ "cjs",
80
+ "py",
81
+ "go",
82
+ "rs",
83
+ "rb",
84
+ "java",
85
+ "kt",
86
+ "sh",
87
+ "bash",
88
+ "zsh",
89
+ "yaml",
90
+ "yml",
91
+ "toml",
92
+ "ini",
93
+ "conf",
94
+ "cfg",
95
+ "txt",
96
+ "csv",
97
+ "html",
98
+ "htm",
99
+ "css",
100
+ "scss",
101
+ "xml",
102
+ "sql",
103
+ "tf",
104
+ "lock",
105
+ "log",
106
+ "env",
69
107
  ]);
70
108
 
71
109
  // Parenthetical PROSE is not a code call signature. A code-like arg list is
@@ -119,7 +157,8 @@ export function extractCallForms(content: string): CallForm[] {
119
157
  // as `Button.ts` and `config.json` as `config.js`, and the existence check then
120
158
  // blocked real files. `.tsx.snap` and `.js.map` are other files, not refs; a
121
159
  // sentence-ending `.` still ends the ref.
122
- const PATH_RE = /[A-Za-z0-9_@./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)(?!\w|\.\w)(?::\d+)?/g;
160
+ const PATH_RE =
161
+ /[A-Za-z0-9_@./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)(?!\w|\.\w)(?::\d+)?/g;
123
162
 
124
163
  export function extractPathRefs(content: string): string[] {
125
164
  if (content.length > REGEX_SCAN_MAX_CHARS) return [];
@@ -140,7 +179,12 @@ export function checkablePathRefs(content: string): string[] {
140
179
  const prev = m.index && m.index > 0 ? content[m.index - 1] : "";
141
180
  if (prev === "$" || prev === "~" || prev === "/") continue;
142
181
  if (!ref.includes("/")) continue;
143
- if (ref.includes("//") || ref.startsWith("/") || ref.split("/").includes("..")) continue;
182
+ if (
183
+ ref.includes("//") ||
184
+ ref.startsWith("/") ||
185
+ ref.split("/").includes("..")
186
+ )
187
+ continue;
144
188
  // A dotted first segment reads as a hostname (opencode.ai/x/index.ts), not
145
189
  // a repo directory. `.` itself is the legitimate relative root prefix.
146
190
  const first = ref.split("/")[0];
@@ -154,7 +198,10 @@ async function isDirectory(path: string): Promise<boolean> {
154
198
  try {
155
199
  // A listing that yields even one entry proves liveRoot is a real tree;
156
200
  // a missing path throws ENOENT/ENOTDIR and fails open (nothing verifiable).
157
- for (const _ of new Bun.Glob("*").scanSync({ onlyFiles: false, cwd: path })) {
201
+ for (const _ of new Bun.Glob("*").scanSync({
202
+ onlyFiles: false,
203
+ cwd: path,
204
+ })) {
158
205
  void _;
159
206
  return true;
160
207
  }
@@ -253,7 +300,11 @@ function relRank(rel: string): number {
253
300
  // in a gate run instead of a glob pass per extension per call form. Semantics
254
301
  // match Bun.Glob defaults: dot entries are skipped, symlinks (file or dir)
255
302
  // are neither listed nor traversed, extensions match case-sensitively.
256
- async function walkSources(absDir: string, relDir: string, out: string[]): Promise<void> {
303
+ async function walkSources(
304
+ absDir: string,
305
+ relDir: string,
306
+ out: string[],
307
+ ): Promise<void> {
257
308
  let dh: Awaited<ReturnType<typeof opendir>>;
258
309
  try {
259
310
  dh = await opendir(absDir);
@@ -265,11 +316,16 @@ async function walkSources(absDir: string, relDir: string, out: string[]): Promi
265
316
  if (ent.name.startsWith(".")) continue;
266
317
  if (ent.isDirectory()) {
267
318
  if (!SKIP_DIRS.includes(ent.name)) {
268
- await walkSources(join(absDir, ent.name), relDir ? `${relDir}/${ent.name}` : ent.name, out);
319
+ await walkSources(
320
+ join(absDir, ent.name),
321
+ relDir ? `${relDir}/${ent.name}` : ent.name,
322
+ out,
323
+ );
269
324
  }
270
325
  } else if (ent.isFile()) {
271
326
  const dot = ent.name.lastIndexOf(".");
272
- if (dot > 0 && SOURCE_EXTS.includes(ent.name.slice(dot + 1))) out.push(relDir ? `${relDir}/${ent.name}` : ent.name);
327
+ if (dot > 0 && SOURCE_EXTS.includes(ent.name.slice(dot + 1)))
328
+ out.push(relDir ? `${relDir}/${ent.name}` : ent.name);
273
329
  }
274
330
  }
275
331
  } catch {
@@ -298,7 +354,10 @@ export interface TreeIndex {
298
354
  export async function buildTreeIndex(liveRoot: string): Promise<TreeIndex> {
299
355
  const out: string[] = [];
300
356
  await walkSources(liveRoot, "", out);
301
- return { files: [...new Set(out)].filter((f) => relRank(f) < Infinity), texts: new Map() };
357
+ return {
358
+ files: [...new Set(out)].filter((f) => relRank(f) < Infinity),
359
+ texts: new Map(),
360
+ };
302
361
  }
303
362
 
304
363
  export type LazyTree = () => Promise<TreeIndex>;
@@ -345,7 +404,12 @@ export async function findLiveCall(
345
404
  const tiebreak = (a: string, b: string) => a.localeCompare(b);
346
405
  if (fileHint) {
347
406
  const h = fileHint.toLowerCase();
348
- files.sort((a, b) => relRank(a) - relRank(b) || hintBoost(b, h) - hintBoost(a, h) || tiebreak(a, b));
407
+ files.sort(
408
+ (a, b) =>
409
+ relRank(a) - relRank(b) ||
410
+ hintBoost(b, h) - hintBoost(a, h) ||
411
+ tiebreak(a, b),
412
+ );
349
413
  } else {
350
414
  files.sort((a, b) => relRank(a) - relRank(b) || tiebreak(a, b));
351
415
  }
@@ -358,7 +422,9 @@ export async function findLiveCall(
358
422
  const CHUNK = 32;
359
423
  for (let i = 0; i < files.length; i += CHUNK) {
360
424
  const chunk = files.slice(i, i + CHUNK);
361
- const texts = await Promise.all(chunk.map((rel) => textOf(index, join(liveRoot, rel))));
425
+ const texts = await Promise.all(
426
+ chunk.map((rel) => textOf(index, join(liveRoot, rel))),
427
+ );
362
428
  for (let j = 0; j < chunk.length; j++) {
363
429
  const text = texts[j];
364
430
  if (text === null || !text.includes(name)) continue;
@@ -374,7 +440,8 @@ export async function findLiveCall(
374
440
  if (callMatch) {
375
441
  const idx = text.indexOf("(", callMatch.index);
376
442
  const paren = idx >= 0 ? balancedParen(text, idx) : null;
377
- if (paren) fallback = { file: join(liveRoot, rel), argsText: paren.inner };
443
+ if (paren)
444
+ fallback = { file: join(liveRoot, rel), argsText: paren.inner };
378
445
  }
379
446
  }
380
447
  }
@@ -383,7 +450,10 @@ export async function findLiveCall(
383
450
  }
384
451
 
385
452
  // The signature a memory/evidence already embeds for `symbol` in `scope`.
386
- export function indexedSignature(symbol: string, scope: Memory[]): CallForm | null {
453
+ export function indexedSignature(
454
+ symbol: string,
455
+ scope: Memory[],
456
+ ): CallForm | null {
387
457
  for (const m of scope) {
388
458
  for (const form of extractCallForms(m.content)) {
389
459
  if (form.symbol === symbol) return form;
@@ -406,7 +476,14 @@ export async function gate1(input: ResolveInput): Promise<Gate1Result> {
406
476
  const forms = extractCallForms(input.content);
407
477
  const pathRefs = extractPathRefs(input.content);
408
478
  const refs = forms.length + pathRefs.length;
409
- if (refs === 0) return { refs: 0, resolved: [], drift: null, candidateStale: false, missingPaths: [] };
479
+ if (refs === 0)
480
+ return {
481
+ refs: 0,
482
+ resolved: [],
483
+ drift: null,
484
+ candidateStale: false,
485
+ missingPaths: [],
486
+ };
410
487
 
411
488
  let drift: DriftInfo | null = null;
412
489
  const resolved: string[] = [];
@@ -417,7 +494,8 @@ export async function gate1(input: ResolveInput): Promise<Gate1Result> {
417
494
  const missingPaths: string[] = [];
418
495
  if (await isDirectory(input.liveRoot)) {
419
496
  for (const ref of checkablePathRefs(input.content)) {
420
- if (!(await Bun.file(join(input.liveRoot, ref)).exists())) missingPaths.push(ref);
497
+ if (!(await Bun.file(join(input.liveRoot, ref)).exists()))
498
+ missingPaths.push(ref);
421
499
  }
422
500
  }
423
501
 
@@ -425,11 +503,18 @@ export async function gate1(input: ResolveInput): Promise<Gate1Result> {
425
503
  const tree = await (input.tree ?? memoTree(input.liveRoot))();
426
504
  for (const form of forms) {
427
505
  resolved.push(form.symbol);
428
- const live = await findLiveCall(form.name, form.fileHint, input.liveRoot, tree);
506
+ const live = await findLiveCall(
507
+ form.name,
508
+ form.fileHint,
509
+ input.liveRoot,
510
+ tree,
511
+ );
429
512
  if (!live) continue;
430
513
  const indexed = indexedSignature(form.symbol, input.scopeMemories);
431
514
  const candidateDiffers = !sameArgs(form.argsText, live.argsText);
432
- const indexedDiffers = indexed ? !sameArgs(indexed.argsText, live.argsText) : false;
515
+ const indexedDiffers = indexed
516
+ ? !sameArgs(indexed.argsText, live.argsText)
517
+ : false;
433
518
  if (candidateDiffers) {
434
519
  drift = {
435
520
  symbol: form.symbol,
@@ -17,8 +17,12 @@
17
17
  import { readFile, stat } from "node:fs/promises";
18
18
  import { join } from "node:path";
19
19
  import { HITS_FILENAME, memoryRoot } from "../core/config/paths.ts";
20
- import { bracketList, formatLine, parseLine } from "../core/logfmt/format.ts"
21
- import { appendLog, fileIdentity, writeAtomic } from "../core/logfmt/publish.ts"
20
+ import { bracketList, formatLine, parseLine } from "../core/logfmt/format.ts";
21
+ import {
22
+ appendLog,
23
+ fileIdentity,
24
+ writeAtomic,
25
+ } from "../core/logfmt/publish.ts";
22
26
  import { readLines } from "../core/logfmt/read.ts";
23
27
  import type { UseSignals } from "../recall/relevant.ts";
24
28
  import { withStoreLock, LOCK_WRITE } from "../store/lock.ts";
@@ -67,7 +71,8 @@ const inFlight = new Set<string>();
67
71
  /** Clear completed-attempt cooldowns. Tests must await all writes first:
68
72
  * clearing reservations cannot cancel I/O or isolate a still-running writer. */
69
73
  export function resetHitThrottle(): void {
70
- if (inFlight.size) throw new Error("await pending recordHits calls before resetHitThrottle");
74
+ if (inFlight.size)
75
+ throw new Error("await pending recordHits calls before resetHitThrottle");
71
76
  nextAttempt.clear();
72
77
  }
73
78
 
@@ -84,8 +89,14 @@ async function rotateIfNeeded(): Promise<void> {
84
89
  // Windows the rename can be refused by a reader's handle, and the retry is
85
90
  // only safe while nothing else moved this file.
86
91
  const since = await fileIdentity(hitsFile());
87
- const lines = (await readFile(hitsFile(), "utf8")).split("\n").filter((l) => l.trim());
88
- await writeAtomic(hitsFile(), lines.slice(Math.floor(lines.length / 2)).join("\n") + "\n", since);
92
+ const lines = (await readFile(hitsFile(), "utf8"))
93
+ .split("\n")
94
+ .filter((l) => l.trim());
95
+ await writeAtomic(
96
+ hitsFile(),
97
+ lines.slice(Math.floor(lines.length / 2)).join("\n") + "\n",
98
+ since,
99
+ );
89
100
  }
90
101
 
91
102
  /**
@@ -117,7 +128,9 @@ export async function recordHits(
117
128
  src: source,
118
129
  sid,
119
130
  mem: bracketList(ids),
120
- ...(terms.length ? { terms: bracketList(terms.slice(0, MAX_LOGGED_TERMS)) } : {}),
131
+ ...(terms.length
132
+ ? { terms: bracketList(terms.slice(0, MAX_LOGGED_TERMS)) }
133
+ : {}),
121
134
  });
122
135
  inFlight.add(key);
123
136
  let cooldown = RETRY_BACKOFF_MS;
@@ -141,7 +154,8 @@ export async function recordHits(
141
154
  nextAttempt.set(key, now + cooldown);
142
155
  // Bound both successful and failed keys with the existing eviction cap.
143
156
  if (nextAttempt.size > 2000) {
144
- for (const k of [...nextAttempt.keys()].slice(0, 1000)) nextAttempt.delete(k);
157
+ for (const k of [...nextAttempt.keys()].slice(0, 1000))
158
+ nextAttempt.delete(k);
145
159
  }
146
160
  inFlight.delete(key);
147
161
  }
@@ -216,7 +230,11 @@ export async function readReads(): Promise<ReadSet[]> {
216
230
  }
217
231
 
218
232
  /** Rows the ledger has NEVER seen used, plus the honest since-qualifier. */
219
- export function neverRetrieved(rows: Memory[], ledger: UseLedger, days = 30): Memory[] {
233
+ export function neverRetrieved(
234
+ rows: Memory[],
235
+ ledger: UseLedger,
236
+ days = 30,
237
+ ): Memory[] {
220
238
  const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
221
239
  return rows.filter((m) => {
222
240
  const u = ledger.byRow.get(m.ts);
@@ -225,7 +243,11 @@ export function neverRetrieved(rows: Memory[], ledger: UseLedger, days = 30): Me
225
243
  }
226
244
 
227
245
  /** Active rows used at least once inside the window. */
228
- export function usedRecently(rows: Memory[], ledger: UseLedger, days = 30): number {
246
+ export function usedRecently(
247
+ rows: Memory[],
248
+ ledger: UseLedger,
249
+ days = 30,
250
+ ): number {
229
251
  const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
230
252
  return rows.filter((m) => {
231
253
  const u = ledger.byRow.get(m.ts);
@@ -242,7 +264,10 @@ export function usedRecently(rows: Memory[], ledger: UseLedger, days = 30): numb
242
264
  const LEDGER_TTL_MS = 60_000;
243
265
  let ledgerCache: { at: number; ledger: UseLedger } | null = null;
244
266
 
245
- export async function useSignals(ttlMs = LEDGER_TTL_MS, now = Date.now()): Promise<UseSignals> {
267
+ export async function useSignals(
268
+ ttlMs = LEDGER_TTL_MS,
269
+ now = Date.now(),
270
+ ): Promise<UseSignals> {
246
271
  if (!ledgerCache || now - ledgerCache.at > ttlMs) {
247
272
  ledgerCache = { at: now, ledger: await readLedger() };
248
273
  }
@@ -1,7 +1,9 @@
1
1
  // Compatibility boundary for host payloads. These adapters only read data;
2
2
  // repository binding, ambient fallbacks, clocks, and I/O belong to the caller.
3
3
  function fields(value: unknown): Record<string, unknown> {
4
- return value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
4
+ return value !== null && typeof value === "object"
5
+ ? (value as Record<string, unknown>)
6
+ : {};
5
7
  }
6
8
 
7
9
  export interface ToolIdentity {
@@ -13,7 +15,8 @@ export interface ToolIdentity {
13
15
  export function toolIdentity(context: unknown): ToolIdentity {
14
16
  const { sessionID, id } = fields(context);
15
17
  return {
16
- sessionID: typeof sessionID === "string" && sessionID ? sessionID : undefined,
18
+ sessionID:
19
+ typeof sessionID === "string" && sessionID ? sessionID : undefined,
17
20
  callID: typeof id === "string" && id ? id : undefined,
18
21
  };
19
22
  }
@@ -32,24 +35,40 @@ export const IDENTITY_EVENT_TYPES: readonly string[] = Object.freeze([
32
35
  ]);
33
36
 
34
37
  /** A directory-less identity still lets the caller resolve the session row. */
35
- export function sessionIdentityEvent(raw: unknown): SessionIdentity | undefined {
38
+ export function sessionIdentityEvent(
39
+ raw: unknown,
40
+ ): SessionIdentity | undefined {
36
41
  const event = fields(raw);
37
- if (typeof event.type !== "string" || !IDENTITY_EVENT_TYPES.includes(event.type)) return undefined;
42
+ if (
43
+ typeof event.type !== "string" ||
44
+ !IDENTITY_EVENT_TYPES.includes(event.type)
45
+ )
46
+ return undefined;
38
47
  const data = fields(event.data ?? event.properties);
39
48
  const info = fields(data.info ?? data);
40
49
  const sessionID = info.sessionID ?? data.sessionID;
41
- const directory = fields(info.location).directory ?? fields(data.location).directory
42
- ?? fields(event.location).directory ?? info.directory;
50
+ const directory =
51
+ fields(info.location).directory ??
52
+ fields(data.location).directory ??
53
+ fields(event.location).directory ??
54
+ info.directory;
43
55
  if (typeof sessionID !== "string") return undefined;
44
- return { sessionID, directory: typeof directory === "string" ? directory : undefined };
56
+ return {
57
+ sessionID,
58
+ directory: typeof directory === "string" ? directory : undefined,
59
+ };
45
60
  }
46
61
 
47
62
  /** Legacy context messages sometimes carry location directly or inside info. */
48
- export function sessionDirectoryFromMessages(messages: unknown): string | undefined {
63
+ export function sessionDirectoryFromMessages(
64
+ messages: unknown,
65
+ ): string | undefined {
49
66
  if (!Array.isArray(messages)) return undefined;
50
67
  for (const message of messages) {
51
68
  const row = fields(message);
52
- const directory = fields(row.location).directory ?? fields(fields(row.info).location).directory;
69
+ const directory =
70
+ fields(row.location).directory ??
71
+ fields(fields(row.info).location).directory;
53
72
  if (typeof directory === "string" && directory) return directory;
54
73
  }
55
74
  return undefined;
@@ -77,7 +96,9 @@ export function sessionUsageEvent(raw: unknown): SessionUsage | undefined {
77
96
  if (event.type === "session.usage.updated") {
78
97
  info = fields(event.data);
79
98
  } else if (event.type === "message.updated") {
80
- info = fields(fields(event.properties).info ?? event.info ?? fields(event.data).info);
99
+ info = fields(
100
+ fields(event.properties).info ?? event.info ?? fields(event.data).info,
101
+ );
81
102
  if (info.role !== "assistant") return undefined;
82
103
  } else {
83
104
  return undefined;
@@ -96,6 +117,9 @@ export function sessionUsageEvent(raw: unknown): SessionUsage | undefined {
96
117
  /** Session ID envelopes accepted by capture; trigger selection stays separate. */
97
118
  export function captureSessionID(raw: unknown): string | undefined {
98
119
  const event = fields(raw);
99
- const sessionID = fields(event.data).sessionID ?? event.sessionID ?? fields(event.properties).sessionID;
120
+ const sessionID =
121
+ fields(event.data).sessionID ??
122
+ event.sessionID ??
123
+ fields(event.properties).sessionID;
100
124
  return typeof sessionID === "string" ? sessionID : undefined;
101
125
  }
@@ -86,7 +86,9 @@ function statOrNull(p: string) {
86
86
  // uncased descendants: lstat("Foo/123") would still follow a symlink at Foo,
87
87
  // whereas lstat("Foo") lets the caller distinguish that alias from a real
88
88
  // case-insensitive lookup. Index 0 stays untouched for Windows drive letters.
89
- function caseProbePair(p: string): { original: string; flipped: string } | null {
89
+ function caseProbePair(
90
+ p: string,
91
+ ): { original: string; flipped: string } | null {
90
92
  for (let i = p.length - 1; i > 0; i--) {
91
93
  const c = p[i];
92
94
  const f = c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase();
@@ -122,8 +124,11 @@ export function isCaseInsensitivePath(dir: string): boolean | null {
122
124
  try {
123
125
  const original = lstatSync(pair.original);
124
126
  const flipped = lstatSync(pair.flipped);
125
- ans = !original.isSymbolicLink() && !flipped.isSymbolicLink()
126
- && original.dev === flipped.dev && original.ino === flipped.ino;
127
+ ans =
128
+ !original.isSymbolicLink() &&
129
+ !flipped.isSymbolicLink() &&
130
+ original.dev === flipped.dev &&
131
+ original.ino === flipped.ino;
127
132
  } catch {
128
133
  // Missing or unreadable alternate spelling cannot justify folding.
129
134
  }
@@ -152,7 +157,9 @@ export function normalizeDirPath(p: string): string {
152
157
  // deleted/unreadable mid-resolve: hash the given spelling rather than throw
153
158
  }
154
159
  r = r.replace(/\\/g, "/").replace(/\/+$/, "");
155
- const fold = isCaseInsensitivePath(r) ?? (process.platform === "win32" || process.platform === "darwin");
160
+ const fold =
161
+ isCaseInsensitivePath(r) ??
162
+ (process.platform === "win32" || process.platform === "darwin");
156
163
  if (fold) r = r.toLowerCase();
157
164
  return r || "/";
158
165
  }
@@ -160,11 +167,18 @@ export function normalizeDirPath(p: string): string {
160
167
  // Resolve the current repo from any start dir (never throws; a non-git dir
161
168
  // simply scopes by the hash of its own normalized path).
162
169
  export function resolveRepo(startDir: string): RepoScope {
163
- const path = git(["git", "rev-parse", "--show-toplevel"], startDir) ?? startDir;
170
+ const path =
171
+ git(["git", "rev-parse", "--show-toplevel"], startDir) ?? startDir;
164
172
  const remote = git(["git", "remote", "get-url", "origin"], path);
165
173
  const key = remote
166
- ? createHash("sha1").update(normalizeRemote(remote)).digest("hex").slice(0, 12)
167
- : createHash("sha1").update(normalizeDirPath(path)).digest("hex").slice(0, 12);
174
+ ? createHash("sha1")
175
+ .update(normalizeRemote(remote))
176
+ .digest("hex")
177
+ .slice(0, 12)
178
+ : createHash("sha1")
179
+ .update(normalizeDirPath(path))
180
+ .digest("hex")
181
+ .slice(0, 12);
168
182
  return { key, path };
169
183
  }
170
184
 
@@ -189,7 +203,8 @@ export function rememberSessionDir(sid: string, dir: string): void {
189
203
  const prev = bySession.get(sid);
190
204
  if (prev && prev.dir === dir) return;
191
205
  bySession.set(sid, { dir, scope: scopeForDir(dir) });
192
- while (bySession.size > SESSION_CAP) bySession.delete(bySession.keys().next().value as string);
206
+ while (bySession.size > SESSION_CAP)
207
+ bySession.delete(bySession.keys().next().value as string);
193
208
  }
194
209
 
195
210
  // A binding learned from a fallback, not from the session's own identity. A
@@ -200,7 +215,10 @@ export function rememberSessionDir(sid: string, dir: string): void {
200
215
  // stream or the session-row API always replaces a provisional binding.
201
216
  const provisional = new Set<string>();
202
217
 
203
- export function bindSessionProvisional(sid: string, dir: string | undefined): void {
218
+ export function bindSessionProvisional(
219
+ sid: string,
220
+ dir: string | undefined,
221
+ ): void {
204
222
  if (!sid || sid === "?" || !dir || bySession.has(sid)) return;
205
223
  rememberSessionDir(sid, dir);
206
224
  provisional.add(sid);
@@ -6,9 +6,23 @@ import { unresolvedWriteMessage } from "../store/files/append.ts";
6
6
  import { readerFromSid } from "../store/model/visibility.ts";
7
7
  import { getCurrent } from "../core/state.ts";
8
8
  import { SESSION_CAP, SessionLru } from "../core/lru.ts";
9
- import { writeEvidence, hasGateCheck, hasEngagement } from "../capture/triggers.ts";
10
- import { bindSessionProvisional, writeTarget, sessionDir, sessionDirFirm, rememberSessionDir } from "./repokey.ts";
11
- import { toolIdentity, sessionDirectoryFromMessages, sessionDirectoryFromRow } from "./host-events.ts";
9
+ import {
10
+ writeEvidence,
11
+ hasGateCheck,
12
+ hasEngagement,
13
+ } from "../capture/triggers.ts";
14
+ import {
15
+ bindSessionProvisional,
16
+ writeTarget,
17
+ sessionDir,
18
+ sessionDirFirm,
19
+ rememberSessionDir,
20
+ } from "./repokey.ts";
21
+ import {
22
+ toolIdentity,
23
+ sessionDirectoryFromMessages,
24
+ sessionDirectoryFromRow,
25
+ } from "./host-events.ts";
12
26
 
13
27
  interface SessionLookupHost {
14
28
  session?: {
@@ -19,7 +33,10 @@ interface SessionLookupHost {
19
33
 
20
34
  export function createSessionContext(
21
35
  ctx: SessionLookupHost,
22
- { instanceDir, liveRoot }: { instanceDir: string | undefined; liveRoot: string },
36
+ {
37
+ instanceDir,
38
+ liveRoot,
39
+ }: { instanceDir: string | undefined; liveRoot: string },
23
40
  ) {
24
41
  const gateContext = (sid?: string): GateContext => {
25
42
  // Every session-scoped member resolves for the CALLER's session when it
@@ -61,7 +78,10 @@ export function createSessionContext(
61
78
  return target.ok ? null : target.sid;
62
79
  };
63
80
 
64
- const refuseOwnerlessWrite = async (sid: string, op: string): Promise<{ content: string }> => {
81
+ const refuseOwnerlessWrite = async (
82
+ sid: string,
83
+ op: string,
84
+ ): Promise<{ content: string }> => {
65
85
  await record("write_refused", { op }, true, sid);
66
86
  return { content: unresolvedWriteMessage(sid) };
67
87
  };
@@ -97,7 +117,9 @@ export function createSessionContext(
97
117
  // below is what actually resolves serve-host sessions.
98
118
  // One-shot: never overwrites an event-bound entry.
99
119
  const messageBindings = new Map<string, Promise<void>>();
100
- async function bindSessionFromMessages(sid: string | undefined): Promise<void> {
120
+ async function bindSessionFromMessages(
121
+ sid: string | undefined,
122
+ ): Promise<void> {
101
123
  if (!sid || sid === "?" || sessionDirFirm(sid)) return;
102
124
  const pending = messageBindings.get(sid);
103
125
  if (pending) return pending;
@@ -128,7 +150,9 @@ export function createSessionContext(
128
150
  // lookup per session; a miss is remembered so a host without the API is
129
151
  // not re-asked on every turn (bounded LRU, same cap as the scope cache).
130
152
  const apiBindTried = new Set<string>();
131
- const apiBindOrder = new SessionLru(SESSION_CAP, (evicted) => apiBindTried.delete(evicted));
153
+ const apiBindOrder = new SessionLru(SESSION_CAP, (evicted) =>
154
+ apiBindTried.delete(evicted),
155
+ );
132
156
  const apiBindings = new Map<string, Promise<void>>();
133
157
  async function bindSessionFromApi(sid: string | undefined): Promise<void> {
134
158
  if (!sid || sid === "?" || sessionDirFirm(sid)) return;
@@ -169,5 +193,12 @@ export function createSessionContext(
169
193
  bindSessionProvisional(sid, instanceDir);
170
194
  }
171
195
 
172
- return { gateContext, ownerlessWriter, refuseOwnerlessWrite, toolIds, bindSessionFromApi, bindSessionIdentity };
196
+ return {
197
+ gateContext,
198
+ ownerlessWriter,
199
+ refuseOwnerlessWrite,
200
+ toolIds,
201
+ bindSessionFromApi,
202
+ bindSessionIdentity,
203
+ };
173
204
  }