sphica 0.6.51 → 0.6.53

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.
@@ -34726,14 +34726,17 @@ var record3 = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ?
34726
34726
  function callerOf(meta3, env = process.env) {
34727
34727
  const codex = record3(record3(meta3)?.["x-codex-turn-metadata"]);
34728
34728
  if (codex) {
34729
+ const session2 = text(codex.session_id);
34730
+ const source = text(codex.thread_source);
34729
34731
  const trigger = text(codex.turn_trigger);
34732
+ const own2 = session2 !== null && session2 === text(codex.thread_id) && source === "user";
34730
34733
  return {
34731
34734
  host: "codex",
34732
- session: text(codex.session_id),
34733
- turn: text(codex.turn_id),
34735
+ session: session2,
34736
+ turn: own2 ? text(codex.turn_id) : null,
34734
34737
  toolUseId: null,
34735
- mode: trigger === "exec" ? "headless" : "unknown",
34736
- raw: trigger
34738
+ mode: trigger === "exec" ? "headless" : own2 && trigger === "user" ? "interactive" : "unknown",
34739
+ raw: own2 || trigger === null && source === null ? trigger : text(`${trigger ?? "none"}:${source ?? "none"}`)
34737
34740
  };
34738
34741
  }
34739
34742
  const toolUseId = text(record3(meta3)?.["claudecode/toolUseId"]);
@@ -46767,8 +46770,49 @@ async function authorityOf(db, ids, asOf) {
46767
46770
 
46768
46771
  // server/src/capture.ts
46769
46772
  import { spawn as spawn2 } from "node:child_process";
46770
- import fs7 from "node:fs";
46771
- import path7 from "node:path";
46773
+ import fs9 from "node:fs";
46774
+ import path9 from "node:path";
46775
+
46776
+ // server/src/codex-log.ts
46777
+ import fs4 from "node:fs";
46778
+ import path4 from "node:path";
46779
+ var SESSION_META_BYTES = 256 * 1024;
46780
+ var text3 = (v) => typeof v === "string" ? v : null;
46781
+ function codexThread(input2) {
46782
+ const file2 = input2.transcript_path;
46783
+ if (typeof file2 !== "string" || !path4.isAbsolute(file2))
46784
+ return null;
46785
+ let fd;
46786
+ try {
46787
+ if (!fs4.lstatSync(file2).isFile())
46788
+ return null;
46789
+ fd = fs4.openSync(file2, "r");
46790
+ const buffer = Buffer.alloc(SESSION_META_BYTES);
46791
+ const read = fs4.readSync(fd, buffer, 0, SESSION_META_BYTES, 0);
46792
+ const end = buffer.subarray(0, read).indexOf(10);
46793
+ if (end < 0)
46794
+ return null;
46795
+ const line = JSON.parse(buffer.subarray(0, end).toString("utf8"));
46796
+ const payload = line?.payload;
46797
+ if (line?.type !== "session_meta" || !payload || typeof payload !== "object" || Array.isArray(payload))
46798
+ return null;
46799
+ const source = payload.source;
46800
+ return {
46801
+ id: text3(payload.id),
46802
+ originator: text3(payload.originator),
46803
+ threadSource: text3(payload.thread_source),
46804
+ parent: text3(payload.parent_thread_id),
46805
+ subagent: source && typeof source === "object" ? text3(source.subagent) : null
46806
+ };
46807
+ } catch {
46808
+ return null;
46809
+ } finally {
46810
+ if (fd !== undefined)
46811
+ fs4.closeSync(fd);
46812
+ }
46813
+ }
46814
+ var ownThread = (input2, thread) => Boolean(input2.session_id) && thread?.id === input2.session_id && thread?.threadSource === "user";
46815
+ var childThread = (input2, thread) => input2.session_id && thread?.threadSource === "subagent" && thread.parent === input2.session_id && thread.id !== null && thread.id !== input2.session_id && /^[\x21-\x7e]{1,200}$/.test(thread.id) ? thread.id : null;
46772
46816
 
46773
46817
  // server/src/knowledge.ts
46774
46818
  var UNIT_KINDS = [
@@ -46795,25 +46839,47 @@ var FIELD_TYPES = ["text", "enum", "integer", "date"];
46795
46839
  var HOSTS = ["claude-code", "codex"];
46796
46840
  var sessionId = (projectId, host, externalId) => uuidFrom(String(projectId), host, externalId);
46797
46841
 
46798
- // server/src/project.ts
46842
+ // server/src/once.ts
46799
46843
  import fs5 from "node:fs";
46844
+ import os3 from "node:os";
46800
46845
  import path5 from "node:path";
46846
+ function markOnce(kind, key) {
46847
+ const user = (() => {
46848
+ try {
46849
+ return os3.userInfo().username;
46850
+ } catch {
46851
+ return String(process.getuid?.() ?? "user");
46852
+ }
46853
+ })();
46854
+ const dir = path5.join(os3.tmpdir(), `sphica-${sha256(user).toString("hex").slice(0, 12)}`, kind);
46855
+ try {
46856
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
46857
+ fs5.writeFileSync(path5.join(dir, sha256(key).toString("hex").slice(0, 24)), "", { flag: "wx" });
46858
+ return true;
46859
+ } catch (e) {
46860
+ return e.code !== "EEXIST";
46861
+ }
46862
+ }
46863
+
46864
+ // server/src/project.ts
46865
+ import fs7 from "node:fs";
46866
+ import path7 from "node:path";
46801
46867
  import { fileURLToPath as fileURLToPath2 } from "node:url";
46802
46868
 
46803
46869
  // server/src/anchors.ts
46804
46870
  import crypto2 from "node:crypto";
46805
- import fs4 from "node:fs";
46806
- import path4 from "node:path";
46871
+ import fs6 from "node:fs";
46872
+ import path6 from "node:path";
46807
46873
  var MAX_BYTES = 2 * 1024 * 1024;
46808
- var leaves = (rel) => rel === ".." || rel.startsWith(`..${path4.sep}`) || path4.isAbsolute(rel);
46874
+ var leaves = (rel) => rel === ".." || rel.startsWith(`..${path6.sep}`) || path6.isAbsolute(rel);
46809
46875
  var literal3 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46810
46876
  function readBytes(root, rel) {
46811
- const abs = path4.join(root, rel);
46812
- if (leaves(path4.relative(root, abs)))
46877
+ const abs = path6.join(root, rel);
46878
+ if (leaves(path6.relative(root, abs)))
46813
46879
  return;
46814
46880
  let st;
46815
46881
  try {
46816
- st = fs4.lstatSync(abs, { throwIfNoEntry: false });
46882
+ st = fs6.lstatSync(abs, { throwIfNoEntry: false });
46817
46883
  } catch (e) {
46818
46884
  return e.code === "ENOTDIR" ? null : undefined;
46819
46885
  }
@@ -46822,10 +46888,10 @@ function readBytes(root, rel) {
46822
46888
  if (!st.isFile() || st.size > MAX_BYTES)
46823
46889
  return;
46824
46890
  try {
46825
- const inside = path4.relative(fs4.realpathSync(root), fs4.realpathSync(abs));
46891
+ const inside = path6.relative(fs6.realpathSync(root), fs6.realpathSync(abs));
46826
46892
  if (leaves(inside))
46827
46893
  return;
46828
- const buf = fs4.readFileSync(abs);
46894
+ const buf = fs6.readFileSync(abs);
46829
46895
  return buf.includes(0) ? undefined : buf;
46830
46896
  } catch {
46831
46897
  return;
@@ -46837,25 +46903,25 @@ function readRepoText(root, rel) {
46837
46903
  return { text: buf, hash: buf === null ? "absent" : "unreadable" };
46838
46904
  return { text: buf.toString("utf8"), hash: crypto2.createHash("sha256").update(buf).digest("hex") };
46839
46905
  }
46840
- function findSymbol(text3, symbol2) {
46906
+ function findSymbol(text4, symbol2) {
46841
46907
  const re = new RegExp(`(?<![\\w$])${literal3(symbol2)}(?![\\w$])`);
46842
- const lines = text3.split(/\r?\n/);
46908
+ const lines = text4.split(/\r?\n/);
46843
46909
  return { lines, i: lines.findIndex((l) => re.test(l)) };
46844
46910
  }
46845
- function swallowed(text3, symbol2) {
46911
+ function swallowed(text4, symbol2) {
46846
46912
  if (mask(symbol2) !== symbol2)
46847
46913
  return true;
46848
- if (text3 === undefined)
46914
+ if (text4 === undefined)
46849
46915
  return true;
46850
- if (text3 === null)
46916
+ if (text4 === null)
46851
46917
  return false;
46852
46918
  const re = new RegExp(`(?<![\\w$])${literal3(symbol2)}(?![\\w$])`, "g");
46853
46919
  let raw = 0;
46854
- for (let m = re.exec(text3);m; m = re.exec(text3))
46920
+ for (let m = re.exec(text4);m; m = re.exec(text4))
46855
46921
  raw++;
46856
46922
  if (raw === 0)
46857
46923
  return false;
46858
- const masked = mask(text3);
46924
+ const masked = mask(text4);
46859
46925
  const holes = placeholderRanges(masked);
46860
46926
  let h = 0;
46861
46927
  let kept = 0;
@@ -46868,14 +46934,14 @@ function swallowed(text3, symbol2) {
46868
46934
  }
46869
46935
  return kept !== raw;
46870
46936
  }
46871
- function masksSymbolIn(text3, symbol2) {
46937
+ function masksSymbolIn(text4, symbol2) {
46872
46938
  const trimmed = symbol2.trim();
46873
- return swallowed(text3, symbol2) || trimmed !== symbol2 && trimmed !== "" && swallowed(text3, trimmed);
46939
+ return swallowed(text4, symbol2) || trimmed !== symbol2 && trimmed !== "" && swallowed(text4, trimmed);
46874
46940
  }
46875
- function locateIn(text3, symbol2) {
46876
- if (typeof text3 !== "string")
46941
+ function locateIn(text4, symbol2) {
46942
+ if (typeof text4 !== "string")
46877
46943
  return null;
46878
- const { lines, i } = findSymbol(text3, symbol2);
46944
+ const { lines, i } = findSymbol(text4, symbol2);
46879
46945
  if (i < 0)
46880
46946
  return null;
46881
46947
  const line = lines[i] ?? "";
@@ -46895,20 +46961,20 @@ ${l}`).join("");
46895
46961
  function fileState(root, rel) {
46896
46962
  if (!root)
46897
46963
  return "unknown";
46898
- if (leaves(path4.relative(root, path4.join(root, rel))))
46964
+ if (leaves(path6.relative(root, path6.join(root, rel))))
46899
46965
  return "unknown";
46900
46966
  let realRoot;
46901
46967
  try {
46902
- realRoot = fs4.realpathSync(root);
46968
+ realRoot = fs6.realpathSync(root);
46903
46969
  } catch {
46904
46970
  return "unknown";
46905
46971
  }
46906
46972
  let at = root;
46907
46973
  for (const part of rel.split("/")) {
46908
- at = path4.join(at, part);
46974
+ at = path6.join(at, part);
46909
46975
  let st;
46910
46976
  try {
46911
- st = fs4.lstatSync(at, { throwIfNoEntry: false });
46977
+ st = fs6.lstatSync(at, { throwIfNoEntry: false });
46912
46978
  } catch (e) {
46913
46979
  if (e.code === "ENOTDIR")
46914
46980
  return "gone";
@@ -46918,7 +46984,7 @@ function fileState(root, rel) {
46918
46984
  return "gone";
46919
46985
  if (st.isSymbolicLink()) {
46920
46986
  try {
46921
- if (leaves(path4.relative(realRoot, fs4.realpathSync(at))))
46987
+ if (leaves(path6.relative(realRoot, fs6.realpathSync(at))))
46922
46988
  return "unknown";
46923
46989
  } catch {
46924
46990
  return "unknown";
@@ -46932,7 +46998,7 @@ function pathKind(root, rel) {
46932
46998
  if (state !== "present" || !root)
46933
46999
  return state === "gone" ? "gone" : "unknown";
46934
47000
  try {
46935
- const st = fs4.statSync(path4.join(root, rel));
47001
+ const st = fs6.statSync(path6.join(root, rel));
46936
47002
  return st.isFile() ? "file" : st.isDirectory() ? "directory" : "unknown";
46937
47003
  } catch {
46938
47004
  return "unknown";
@@ -46940,7 +47006,7 @@ function pathKind(root, rel) {
46940
47006
  }
46941
47007
 
46942
47008
  // server/src/project.ts
46943
- var localFile = () => path5.join(sphicaHome(), "projects.json");
47009
+ var localFile = () => path7.join(sphicaHome(), "projects.json");
46944
47010
  var LOCAL_KEY = /^[a-z0-9][a-z0-9._-]*$/;
46945
47011
  function legacyRemote(url2) {
46946
47012
  const raw = String(url2 ?? "").trim();
@@ -46979,7 +47045,7 @@ var top = (dir) => ask(() => topLevel(dir, { timeout: 5000 }));
46979
47045
  function localMap() {
46980
47046
  let raw;
46981
47047
  try {
46982
- raw = fs5.readFileSync(localFile(), "utf8");
47048
+ raw = fs7.readFileSync(localFile(), "utf8");
46983
47049
  } catch (e) {
46984
47050
  if (e.code === "ENOENT")
46985
47051
  return {};
@@ -46991,12 +47057,12 @@ function localMap() {
46991
47057
  } catch {
46992
47058
  m = null;
46993
47059
  }
46994
- if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path5.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
47060
+ if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path7.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
46995
47061
  throw new Error(`${localFile()} is not a valid JSON project table. Fix or delete it, then name the project again.`);
46996
47062
  return m;
46997
47063
  }
46998
47064
  function identify(dir) {
46999
- const given = path5.resolve(dir);
47065
+ const given = path7.resolve(dir);
47000
47066
  const found = top(given);
47001
47067
  const root = found || given;
47002
47068
  const legacy = found ? legacyRemote(ask(() => originUrl(root, { timeout: 5000 }))) : null;
@@ -47006,11 +47072,11 @@ function identify(dir) {
47006
47072
  return { key, legacyKey: `git:${legacy}`, root, name: remote.split("/").slice(1).join("/") || remote };
47007
47073
  }
47008
47074
  const map3 = localMap();
47009
- for (let d = root;; d = path5.dirname(d)) {
47075
+ for (let d = root;; d = path7.dirname(d)) {
47010
47076
  const local = map3[d];
47011
47077
  if (local && LOCAL_KEY.test(local))
47012
47078
  return { key: `local:${local}`, legacyKey: `local:${local}`, root: d, name: local };
47013
- if (found || path5.dirname(d) === d)
47079
+ if (found || path7.dirname(d) === d)
47014
47080
  return null;
47015
47081
  }
47016
47082
  }
@@ -47039,11 +47105,11 @@ async function projectId(db, key) {
47039
47105
  return r?.id ?? null;
47040
47106
  }
47041
47107
  function relativeTo(root, file2, cwd = root) {
47042
- const abs = path5.resolve(cwd, file2);
47043
- const rel = path5.relative(root, abs);
47108
+ const abs = path7.resolve(cwd, file2);
47109
+ const rel = path7.relative(root, abs);
47044
47110
  if (!rel || leaves(rel) || /\p{Cc}/u.test(rel))
47045
47111
  return null;
47046
- return rel.split(path5.sep).join("/");
47112
+ return rel.split(path7.sep).join("/");
47047
47113
  }
47048
47114
  function patchPaths(patch) {
47049
47115
  const out = [];
@@ -47057,8 +47123,8 @@ function patchPaths(patch) {
47057
47123
  }
47058
47124
 
47059
47125
  // server/src/worktree.ts
47060
- import fs6 from "node:fs";
47061
- import path6 from "node:path";
47126
+ import fs8 from "node:fs";
47127
+ import path8 from "node:path";
47062
47128
  var MAX_PATHS = 200;
47063
47129
  var LIMITS = { timeout: 5000, max: 16 * 1024 * 1024 };
47064
47130
  var STATUS_DEADLINE = 5000;
@@ -47083,7 +47149,7 @@ async function snapshot(root) {
47083
47149
  continue;
47084
47150
  let st;
47085
47151
  try {
47086
- st = fs6.lstatSync(path6.join(root, p), { throwIfNoEntry: false });
47152
+ st = fs8.lstatSync(path8.join(root, p), { throwIfNoEntry: false });
47087
47153
  } catch {
47088
47154
  st = undefined;
47089
47155
  }
@@ -47115,15 +47181,15 @@ function changed(root, before, after) {
47115
47181
  }
47116
47182
 
47117
47183
  // server/src/capture.ts
47118
- var spoolDir = () => path7.join(sphicaHome(), "spool");
47119
- var stateFile = () => path7.join(sphicaHome(), "capture.json");
47120
- var rejectedDir = () => path7.join(spoolDir(), "rejected");
47121
- var unregisteredDir = () => path7.join(spoolDir(), "unregistered");
47122
- var callsDir = () => path7.join(spoolDir(), "calls");
47123
- var callsRejectedDir = () => path7.join(callsDir(), "rejected");
47184
+ var spoolDir = () => path9.join(sphicaHome(), "spool");
47185
+ var stateFile = () => path9.join(sphicaHome(), "capture.json");
47186
+ var rejectedDir = () => path9.join(spoolDir(), "rejected");
47187
+ var unregisteredDir = () => path9.join(spoolDir(), "unregistered");
47188
+ var callsDir = () => path9.join(spoolDir(), "calls");
47189
+ var callsRejectedDir = () => path9.join(callsDir(), "rejected");
47124
47190
  var HOLD_DAYS = 30;
47125
47191
  var HOLD_MAX = 1000;
47126
- var baselineDir = () => path7.join(sphicaHome(), "worktree");
47192
+ var baselineDir = () => path9.join(sphicaHome(), "worktree");
47127
47193
  function current(raw) {
47128
47194
  const r = raw;
47129
47195
  if (typeof r.project !== "string")
@@ -47172,7 +47238,7 @@ ${z2}`,
47172
47238
  function prune(held, removed = () => {}) {
47173
47239
  let files;
47174
47240
  try {
47175
- files = fs7.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
47241
+ files = fs9.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
47176
47242
  } catch {
47177
47243
  return;
47178
47244
  }
@@ -47180,26 +47246,26 @@ function prune(held, removed = () => {}) {
47180
47246
  const stale = files.filter((f) => Number(f.split("-")[0]) < cutoff);
47181
47247
  const over = files.slice(0, Math.max(0, files.length - HOLD_MAX));
47182
47248
  for (const f of new Set([...stale, ...over])) {
47183
- fs7.rmSync(path7.join(held, f), { force: true });
47249
+ fs9.rmSync(path9.join(held, f), { force: true });
47184
47250
  removed();
47185
47251
  }
47186
47252
  }
47187
47253
  function put(dir, record4) {
47188
- fs7.mkdirSync(dir, { recursive: true, mode: 448 });
47254
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
47189
47255
  const name = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 10)}.json`;
47190
- const tmp = path7.join(dir, `.${name}`);
47191
- fs7.writeFileSync(tmp, JSON.stringify(record4), { mode: 384 });
47192
- fs7.renameSync(tmp, path7.join(dir, name));
47193
- return path7.join(dir, name);
47256
+ const tmp = path9.join(dir, `.${name}`);
47257
+ fs9.writeFileSync(tmp, JSON.stringify(record4), { mode: 384 });
47258
+ fs9.renameSync(tmp, path9.join(dir, name));
47259
+ return path9.join(dir, name);
47194
47260
  }
47195
47261
  function spool(record4) {
47196
47262
  put(spoolDir(), record4);
47197
47263
  }
47198
47264
  var branchOf = (root) => {
47199
47265
  try {
47200
- const dotgit = path7.join(root, ".git");
47201
- const gitdir = fs7.statSync(dotgit).isFile() ? path7.resolve(root, fs7.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
47202
- const h = fs7.readFileSync(path7.join(gitdir, "HEAD"), "utf8").trim();
47266
+ const dotgit = path9.join(root, ".git");
47267
+ const gitdir = fs9.statSync(dotgit).isFile() ? path9.resolve(root, fs9.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
47268
+ const h = fs9.readFileSync(path9.join(gitdir, "HEAD"), "utf8").trim();
47203
47269
  return h.startsWith("ref: refs/heads/") ? h.slice("ref: refs/heads/".length) : null;
47204
47270
  } catch {
47205
47271
  return null;
@@ -47245,7 +47311,7 @@ Notes: ${notes.trim()}` : "";
47245
47311
  };
47246
47312
  }
47247
47313
  function captureNotice(file2 = dbFile()) {
47248
- if (!fs7.existsSync(file2))
47314
+ if (!fs9.existsSync(file2))
47249
47315
  return panel("sphica: no database, so conversations are not recorded", [file2], "Create it with sphica init");
47250
47316
  const s = readState();
47251
47317
  if (s.unreadable)
@@ -47256,15 +47322,15 @@ function captureNotice(file2 = dbFile()) {
47256
47322
  return panel(`sphica: the database rejected ${plural2(s.rejected, "record")}`, [rejectedDir(), `Move them back to ${spoolDir()} to resend`], "Fix them first, then check with sphica doctor");
47257
47323
  return null;
47258
47324
  }
47259
- var turnDir = (host, session) => path7.join(baselineDir(), digest(`${host}\x00${session}`));
47260
- var startFile = (dir, turn) => path7.join(dir, `${digest(turn)}.json`);
47325
+ var turnDir = (host, session) => path9.join(baselineDir(), digest(`${host}\x00${session}`));
47326
+ var startFile = (dir, turn) => path9.join(dir, `${digest(turn)}.json`);
47261
47327
  var isStart = (v) => {
47262
47328
  const s = v;
47263
47329
  return !!s && typeof s === "object" && typeof s.turn === "string" && typeof s.running === "boolean" && (s.seq === null || Number.isSafeInteger(s.seq)) && (s.entries === null || typeof s.entries === "object" && !Array.isArray(s.entries)) && (s.head === null || typeof s.head === "string");
47264
47330
  };
47265
47331
  function readStart(file2) {
47266
47332
  try {
47267
- const s = JSON.parse(fs7.readFileSync(file2, "utf8"));
47333
+ const s = JSON.parse(fs9.readFileSync(file2, "utf8"));
47268
47334
  return isStart(s) ? s : null;
47269
47335
  } catch {
47270
47336
  return null;
@@ -47273,7 +47339,7 @@ function readStart(file2) {
47273
47339
  function readStarts(dir) {
47274
47340
  let names;
47275
47341
  try {
47276
- names = fs7.readdirSync(dir);
47342
+ names = fs9.readdirSync(dir);
47277
47343
  } catch (e) {
47278
47344
  return e.code === "ENOENT" ? [] : null;
47279
47345
  }
@@ -47281,7 +47347,7 @@ function readStarts(dir) {
47281
47347
  for (const name of names) {
47282
47348
  if (name.startsWith("."))
47283
47349
  continue;
47284
- const s = readStart(path7.join(dir, name));
47350
+ const s = readStart(path9.join(dir, name));
47285
47351
  if (!s)
47286
47352
  return null;
47287
47353
  starts2.push(s);
@@ -47296,10 +47362,10 @@ function newestTurn(starts2) {
47296
47362
  return at.length === 1 ? at[0]?.turn ?? null : null;
47297
47363
  }
47298
47364
  function writeStart(dir, s, file2 = startFile(dir, s.turn)) {
47299
- fs7.mkdirSync(dir, { recursive: true, mode: 448 });
47300
- const tmp = path7.join(dir, `.${path7.basename(file2)}.${process.pid}.tmp`);
47301
- fs7.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
47302
- fs7.renameSync(tmp, file2);
47365
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
47366
+ const tmp = path9.join(dir, `.${path9.basename(file2)}.${process.pid}.tmp`);
47367
+ fs9.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
47368
+ fs9.renameSync(tmp, file2);
47303
47369
  }
47304
47370
  async function openTurn(dir, turn, root) {
47305
47371
  if (readStart(startFile(dir, turn))?.running)
@@ -47329,22 +47395,22 @@ function stopTurn(dir, turn) {
47329
47395
  }
47330
47396
  function pruneBaselines() {
47331
47397
  const cutoff = Date.now() - HOLD_DAYS * 24 * 60 * 60 * 1000;
47332
- const fresh = (file2) => (fs7.statSync(file2, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
47398
+ const fresh = (file2) => (fs9.statSync(file2, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
47333
47399
  let names;
47334
47400
  try {
47335
- names = fs7.readdirSync(baselineDir());
47401
+ names = fs9.readdirSync(baselineDir());
47336
47402
  } catch {
47337
47403
  return;
47338
47404
  }
47339
47405
  for (const name of names) {
47340
- const at = path7.join(baselineDir(), name);
47341
- if (!fs7.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
47406
+ const at = path9.join(baselineDir(), name);
47407
+ if (!fs9.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
47342
47408
  if (!fresh(at))
47343
- fs7.rmSync(at, { force: true });
47409
+ fs9.rmSync(at, { force: true });
47344
47410
  } else {
47345
- const files = fs7.readdirSync(at);
47346
- if (files.length && !files.some((f) => fresh(path7.join(at, f))))
47347
- fs7.rmSync(at, { recursive: true, force: true });
47411
+ const files = fs9.readdirSync(at);
47412
+ if (files.length && !files.some((f) => fresh(path9.join(at, f))))
47413
+ fs9.rmSync(at, { recursive: true, force: true });
47348
47414
  }
47349
47415
  }
47350
47416
  }
@@ -47362,22 +47428,36 @@ async function attemptAsync(fn) {
47362
47428
  return;
47363
47429
  }
47364
47430
  }
47431
+ function whoseTurn(host, input2) {
47432
+ if (!isOwnerTurn(input2, undefined, undefined, host === "codex" ? process.env.CODEX_THREAD_ID : undefined))
47433
+ return "other";
47434
+ if (host !== "codex")
47435
+ return "owner";
47436
+ const thread = codexThread(input2);
47437
+ if (ownThread(input2, thread))
47438
+ return "owner";
47439
+ return childThread(input2, thread) === null ? "unconfirmed" : "other";
47440
+ }
47441
+ var unconfirmed = (input2) => !markOnce("unconfirmed", `codex\x00${input2.session_id}`) ? null : typeof input2.transcript_path === "string" ? panel("sphica: this Codex session is not recorded", ["Its session log does not show that these messages are yours"], "Update Sphica and Codex; if it stays, report it") : panel("sphica: this Codex session is not recorded", [
47442
+ "Codex named no session log (as with --ephemeral), so Sphica cannot confirm these messages are yours"
47443
+ ], "To record a session, start Codex without --ephemeral");
47365
47444
  async function onHook(host, input2) {
47366
47445
  const event = input2.hook_event_name;
47367
- const owner = () => isOwnerTurn(input2, undefined, undefined, host === "codex" ? process.env.CODEX_THREAD_ID : undefined);
47446
+ const whose = whoseTurn(host, input2);
47447
+ if (whose !== "owner")
47448
+ return {
47449
+ flush: false,
47450
+ notice: whose === "unconfirmed" && event === "UserPromptSubmit" ? unconfirmed(input2) : null
47451
+ };
47368
47452
  if (event === "SessionStart") {
47369
- if (!owner())
47370
- return { flush: false };
47371
47453
  const file2 = process.env.CLAUDE_ENV_FILE;
47372
47454
  if (file2 && input2.session_id && /^[A-Za-z0-9_-]+$/.test(input2.session_id)) {
47373
- fs7.appendFileSync(file2, `export SPHICA_PARENT_SESSION=${input2.session_id}
47455
+ fs9.appendFileSync(file2, `export SPHICA_PARENT_SESSION=${input2.session_id}
47374
47456
  `);
47375
47457
  }
47376
47458
  attempt(pruneBaselines);
47377
47459
  return { flush: false, notice: captureNotice() };
47378
47460
  }
47379
- if (!owner())
47380
- return { flush: false };
47381
47461
  if (event === "Interrupt") {
47382
47462
  const turn2 = input2.prompt_id ?? input2.turn_id;
47383
47463
  if (turn2)
@@ -47453,7 +47533,7 @@ async function onHook(host, input2) {
47453
47533
  function readStateFile() {
47454
47534
  let raw = {};
47455
47535
  try {
47456
- const parsed = JSON.parse(fs7.readFileSync(stateFile(), "utf8"));
47536
+ const parsed = JSON.parse(fs9.readFileSync(stateFile(), "utf8"));
47457
47537
  if (parsed && typeof parsed === "object")
47458
47538
  raw = parsed;
47459
47539
  } catch {}
@@ -47467,7 +47547,7 @@ function readStateFile() {
47467
47547
  }
47468
47548
  function writeState(s) {
47469
47549
  try {
47470
- fs7.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
47550
+ fs9.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
47471
47551
  } catch {}
47472
47552
  }
47473
47553
  function readState() {
@@ -47483,7 +47563,7 @@ function readState() {
47483
47563
  }
47484
47564
  function listQueue(dir) {
47485
47565
  try {
47486
- const names = fs7.readdirSync(dir);
47566
+ const names = fs9.readdirSync(dir);
47487
47567
  return {
47488
47568
  files: names.filter((f) => f.endsWith(".json") && !f.startsWith(".")),
47489
47569
  temp: names.filter((f) => f.endsWith(".json") && f.startsWith(".")),
@@ -47495,25 +47575,25 @@ function listQueue(dir) {
47495
47575
  }
47496
47576
  }
47497
47577
  function lock() {
47498
- const file2 = path7.join(spoolDir(), ".lock");
47499
- fs7.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
47578
+ const file2 = path9.join(spoolDir(), ".lock");
47579
+ fs9.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
47500
47580
  for (let attempt2 = 0;attempt2 < 2; attempt2++) {
47501
47581
  try {
47502
- fs7.writeFileSync(file2, String(process.pid), { flag: "wx", mode: 384 });
47582
+ fs9.writeFileSync(file2, String(process.pid), { flag: "wx", mode: 384 });
47503
47583
  return () => {
47504
47584
  try {
47505
- if (fs7.readFileSync(file2, "utf8") === String(process.pid))
47506
- fs7.rmSync(file2, { force: true });
47585
+ if (fs9.readFileSync(file2, "utf8") === String(process.pid))
47586
+ fs9.rmSync(file2, { force: true });
47507
47587
  } catch {}
47508
47588
  };
47509
47589
  } catch (e) {
47510
47590
  if (e.code !== "EEXIST")
47511
47591
  throw e;
47512
47592
  }
47513
- const st = fs7.statSync(file2, { throwIfNoEntry: false });
47593
+ const st = fs9.statSync(file2, { throwIfNoEntry: false });
47514
47594
  if (!st)
47515
47595
  continue;
47516
- const holder = Number(fs7.readFileSync(file2, "utf8") || 0);
47596
+ const holder = Number(fs9.readFileSync(file2, "utf8") || 0);
47517
47597
  const fresh = Date.now() - st.mtimeMs < 5 * 60000;
47518
47598
  const alive = (() => {
47519
47599
  if (holder <= 0)
@@ -47526,7 +47606,7 @@ function lock() {
47526
47606
  })();
47527
47607
  if (alive && fresh)
47528
47608
  return null;
47529
- fs7.rmSync(file2, { force: true });
47609
+ fs9.rmSync(file2, { force: true });
47530
47610
  }
47531
47611
  return null;
47532
47612
  }
@@ -47626,23 +47706,23 @@ var REJECTED = new Set([18, 19, 20, 25]);
47626
47706
  var rejected = (e) => REJECTED.has(sqliteCode(e) ?? -1);
47627
47707
  var queued = (from) => {
47628
47708
  try {
47629
- return fs7.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
47709
+ return fs9.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
47630
47710
  } catch {
47631
47711
  return [];
47632
47712
  }
47633
47713
  };
47634
47714
  var CODE_NAMES = { 18: "TOOBIG", 19: "CONSTRAINT", 20: "MISMATCH", 25: "RANGE" };
47635
47715
  function setAside(from, name, dir, reason2) {
47636
- fs7.mkdirSync(dir, { recursive: true, mode: 448 });
47716
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
47637
47717
  try {
47638
- fs7.renameSync(path7.join(from, name), path7.join(dir, name));
47718
+ fs9.renameSync(path9.join(from, name), path9.join(dir, name));
47639
47719
  } catch (e) {
47640
47720
  if (e.code === "ENOENT")
47641
47721
  return;
47642
47722
  throw e;
47643
47723
  }
47644
47724
  try {
47645
- fs7.writeFileSync(path7.join(dir, `${name}.reason`), reason2, { mode: 384 });
47725
+ fs9.writeFileSync(path9.join(dir, `${name}.reason`), reason2, { mode: 384 });
47646
47726
  } catch {}
47647
47727
  }
47648
47728
  async function sendBatch(db, names) {
@@ -47652,7 +47732,7 @@ async function sendBatch(db, names) {
47652
47732
  let raw;
47653
47733
  let r;
47654
47734
  try {
47655
- raw = JSON.parse(fs7.readFileSync(path7.join(from, name), "utf8"));
47735
+ raw = JSON.parse(fs9.readFileSync(path9.join(from, name), "utf8"));
47656
47736
  } catch {
47657
47737
  setAside(from, name, rejectedDir(), "unreadable");
47658
47738
  continue;
@@ -47666,7 +47746,7 @@ async function sendBatch(db, names) {
47666
47746
  if (r)
47667
47747
  records.push({ name, from, r });
47668
47748
  else
47669
- fs7.rmSync(path7.join(from, name), { force: true });
47749
+ fs9.rmSync(path9.join(from, name), { force: true });
47670
47750
  }
47671
47751
  let sent = 0;
47672
47752
  let strayed = [];
@@ -47694,12 +47774,12 @@ async function sendBatch(db, names) {
47694
47774
  for (const x of bad)
47695
47775
  setAside(x.from, x.name, rejectedDir(), x.why);
47696
47776
  if (strayed.length) {
47697
- fs7.mkdirSync(held, { recursive: true, mode: 448 });
47777
+ fs9.mkdirSync(held, { recursive: true, mode: 448 });
47698
47778
  for (const x of strayed) {
47699
47779
  if (x.from === held)
47700
47780
  continue;
47701
47781
  try {
47702
- fs7.renameSync(path7.join(x.from, x.name), path7.join(held, x.name));
47782
+ fs9.renameSync(path9.join(x.from, x.name), path9.join(held, x.name));
47703
47783
  } catch (e) {
47704
47784
  if (e.code !== "ENOENT")
47705
47785
  throw e;
@@ -47709,7 +47789,7 @@ async function sendBatch(db, names) {
47709
47789
  const moved = new Set([...bad, ...strayed].map((x) => x.name));
47710
47790
  for (const x of records)
47711
47791
  if (!moved.has(x.name))
47712
- fs7.rmSync(path7.join(x.from, x.name), { force: true });
47792
+ fs9.rmSync(path9.join(x.from, x.name), { force: true });
47713
47793
  return { sent, rejected: bad.length };
47714
47794
  }
47715
47795
  async function sendObservations(db, names) {
@@ -47720,16 +47800,16 @@ async function sendObservations(db, names) {
47720
47800
  };
47721
47801
  const rows = [];
47722
47802
  for (const { name, from } of names) {
47723
- let text3;
47803
+ let text4;
47724
47804
  try {
47725
- text3 = fs7.readFileSync(path7.join(from, name), "utf8");
47805
+ text4 = fs9.readFileSync(path9.join(from, name), "utf8");
47726
47806
  } catch {
47727
47807
  continue;
47728
47808
  }
47729
47809
  let o = null;
47730
47810
  let why = "unreadable";
47731
47811
  try {
47732
- o = observation(JSON.parse(text3));
47812
+ o = observation(JSON.parse(text4));
47733
47813
  why = "shape";
47734
47814
  } catch {}
47735
47815
  if (o)
@@ -47761,7 +47841,7 @@ async function sendObservations(db, names) {
47761
47841
  aside(x.name, why);
47762
47842
  else
47763
47843
  try {
47764
- fs7.rmSync(path7.join(callsDir(), x.name), { force: true });
47844
+ fs9.rmSync(path9.join(callsDir(), x.name), { force: true });
47765
47845
  } catch {}
47766
47846
  }
47767
47847
  return true;
@@ -47904,7 +47984,7 @@ async function observeRecordCall(file2, input2, owner, waitMs = OBSERVE_WAIT_MS)
47904
47984
  }
47905
47985
  if (kept)
47906
47986
  try {
47907
- fs7.rmSync(kept, { force: true });
47987
+ fs9.rmSync(kept, { force: true });
47908
47988
  } catch {}
47909
47989
  }
47910
47990
  async function main() {
@@ -47982,8 +48062,8 @@ var plainEnv = () => ({
47982
48062
  CLICOLOR_FORCE: "0"
47983
48063
  });
47984
48064
  var ghCwd = startDir;
47985
- var gh = (repo, timeout = 60000) => async (path8, all = false) => {
47986
- const { stdout } = await exec("gh", ["api", `repos/${repo}/${path8}`, ...HOST, ...all ? ["--paginate", "--slurp"] : []], {
48065
+ var gh = (repo, timeout = 60000) => async (path10, all = false) => {
48066
+ const { stdout } = await exec("gh", ["api", `repos/${repo}/${path10}`, ...HOST, ...all ? ["--paginate", "--slurp"] : []], {
47987
48067
  encoding: "utf8",
47988
48068
  maxBuffer: MAX_RESPONSE,
47989
48069
  timeout,
@@ -47992,9 +48072,9 @@ var gh = (repo, timeout = 60000) => async (path8, all = false) => {
47992
48072
  cwd: ghCwd()
47993
48073
  }).catch((e) => {
47994
48074
  if (e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
47995
- throw new Error(`${path8.split("?")[0]} is too large to read (over ${MAX_RESPONSE / 1024 / 1024} MB)`);
48075
+ throw new Error(`${path10.split("?")[0]} is too large to read (over ${MAX_RESPONSE / 1024 / 1024} MB)`);
47996
48076
  if (e.killed)
47997
- throw new Error(`${path8.split("?")[0]} did not answer within ${timeout / 1000} seconds`);
48077
+ throw new Error(`${path10.split("?")[0]} did not answer within ${timeout / 1000} seconds`);
47998
48078
  throw e;
47999
48079
  });
48000
48080
  const parsed = JSON.parse(stdout);
@@ -48840,34 +48920,34 @@ var instructionFile = (relative) => {
48840
48920
  var KEY = /^[a-z0-9][a-z0-9._/-]{0,63}$/;
48841
48921
  var FIELD_NAME2 = /^[a-z][a-z0-9_]{0,39}$/;
48842
48922
  var SOURCE_REF = /^s[1-9][0-9]{0,15}$/;
48843
- var text3 = (max) => exports_external.string().trim().min(1).max(max);
48923
+ var text4 = (max) => exports_external.string().trim().min(1).max(max);
48844
48924
  var Quote = exports_external.object({ source: exports_external.string().regex(SOURCE_REF, "cite a source ref such as s12"), quote: exports_external.string() }).strict();
48845
48925
  var Evidence = Quote.extend({
48846
48926
  role: exports_external.enum(EVIDENCE_ROLES).exclude(["reconsiders"]),
48847
- reported_speaker: text3(100).optional()
48927
+ reported_speaker: text4(100).optional()
48848
48928
  }).strict();
48849
48929
  var Unit = exports_external.object({
48850
48930
  key: exports_external.string().regex(KEY, "use lowercase letters, digits, and . _ - / (at most 64)"),
48851
48931
  kind: exports_external.enum(UNIT_KINDS),
48852
48932
  stance: exports_external.enum(STANCES).optional(),
48853
- text: text3(2000),
48854
- why: text3(2000).optional(),
48855
- scope_note: text3(1000).optional(),
48856
- revisit_when: text3(1000).optional(),
48857
- no_code_surface: text3(500).optional(),
48933
+ text: text4(2000),
48934
+ why: text4(2000).optional(),
48935
+ scope_note: text4(1000).optional(),
48936
+ revisit_when: text4(1000).optional(),
48937
+ no_code_surface: text4(500).optional(),
48858
48938
  options: exports_external.array(exports_external.object({
48859
- text: text3(500),
48939
+ text: text4(500),
48860
48940
  outcome: exports_external.enum(OPTION_OUTCOMES),
48861
- why: text3(2000).optional(),
48862
- reconsider_when: text3(1000).optional(),
48941
+ why: text4(2000).optional(),
48942
+ reconsider_when: text4(1000).optional(),
48863
48943
  reconsider_quote: Quote.optional(),
48864
48944
  evidence: exports_external.array(Evidence.partial({ role: true })).max(10).default([])
48865
48945
  }).strict()).max(12).default([]),
48866
48946
  evidence: exports_external.array(Evidence).max(20).default([]),
48867
48947
  adoption: exports_external.array(Quote).max(5).default([]),
48868
48948
  anchors: exports_external.array(exports_external.object({
48869
- path: text3(500),
48870
- symbol: text3(200).optional(),
48949
+ path: text4(500),
48950
+ symbol: text4(200).optional(),
48871
48951
  role: exports_external.enum(["applies_to", "evidence"]),
48872
48952
  commit: exports_external.string().regex(/^[0-9a-f]{40}$/, "a full 40-character commit sha").optional(),
48873
48953
  lines: exports_external.tuple([exports_external.number().int().positive(), exports_external.number().int().positive()]).optional()
@@ -48878,25 +48958,25 @@ var Unit = exports_external.object({
48878
48958
  answers: exports_external.array(exports_external.string().min(1)).max(5).default([]),
48879
48959
  fields: exports_external.array(exports_external.object({
48880
48960
  name: exports_external.string().regex(FIELD_NAME2, "a defined field name"),
48881
- value: text3(200),
48961
+ value: text4(200),
48882
48962
  quote: Quote
48883
48963
  }).strict()).max(12).default([])
48884
48964
  }).strict();
48885
48965
  var FieldDef = exports_external.object({
48886
48966
  name: exports_external.string().regex(FIELD_NAME2, "a lowercase letter, then lowercase letters, digits, and _ (at most 40)"),
48887
48967
  type: exports_external.enum(FIELD_TYPES),
48888
- label: text3(100),
48889
- description: text3(500),
48890
- enum: exports_external.array(text3(100)).min(1).max(30).optional(),
48968
+ label: text4(100),
48969
+ description: text4(500),
48970
+ enum: exports_external.array(text4(100)).min(1).max(30).optional(),
48891
48971
  kinds: exports_external.array(exports_external.enum(UNIT_KINDS)).max(UNIT_KINDS.length).default([]),
48892
48972
  quote: Quote
48893
48973
  }).strict();
48894
48974
  var Work = exports_external.object({
48895
48975
  key: exports_external.string().regex(KEY),
48896
- title: text3(200).optional(),
48897
- goal: text3(1000).optional(),
48898
- current: text3(2000).optional(),
48899
- next: exports_external.array(text3(500)).max(10).optional(),
48976
+ title: text4(200).optional(),
48977
+ goal: text4(1000).optional(),
48978
+ current: text4(2000).optional(),
48979
+ next: exports_external.array(text4(500)).max(10).optional(),
48900
48980
  status: exports_external.enum(WORK_STATUSES).optional()
48901
48981
  }).strict();
48902
48982
  var Record = exports_external.object({
@@ -49333,8 +49413,8 @@ function valueInQuote(type, value, quote) {
49333
49413
  return standsAlone(quote, value);
49334
49414
  return [...quote.matchAll(NUMBER)].some((m) => m[0].replace(/^\+/, "").replaceAll(",", "") === value);
49335
49415
  }
49336
- var ciPath = (path8) => {
49337
- const p = path8.toLowerCase().replace(/\/+$/, "");
49416
+ var ciPath = (path10) => {
49417
+ const p = path10.toLowerCase().replace(/\/+$/, "");
49338
49418
  return p === ".github" || p === ".github/workflows" || p.startsWith(".github/workflows/");
49339
49419
  };
49340
49420
  async function agentRefusal(db, u, x, s, evidence, anchors) {
@@ -49347,7 +49427,7 @@ async function agentRefusal(db, u, x, s, evidence, anchors) {
49347
49427
  if (!evidence.some((e) => e.role === "decides" && e.source === x.source && e.start === x.start && e.end === x.end))
49348
49428
  return "quote the same words as decides evidence: the AI choosing, not reporting, proposing, or asking";
49349
49429
  const governs = anchors.filter((a) => a.role === "applies_to").map((a) => a.path);
49350
- const bound = anchors.map((a) => a.path).find((path8) => instructionFile(path8) || ciPath(path8));
49430
+ const bound = anchors.map((a) => a.path).find((path10) => instructionFile(path10) || ciPath(path10));
49351
49431
  if (bound)
49352
49432
  return `${bound} holds rules or CI agents follow; only the owner adopts decisions about it`;
49353
49433
  if (await db.selectFrom("agent_ineligible_source").select("source_id").where("source_id", "=", x.source).executeTakeFirst())
@@ -49809,12 +49889,12 @@ function readExcerpt(root, file3) {
49809
49889
  if (privateKeyRanges(buf.toString("utf8")).some(([s, e]) => s < to && e > from && (s < from || e > to)))
49810
49890
  throw new Error(`${p} lines ${a}-${b} are inside a private key; cite lines outside it`);
49811
49891
  const raw = buf.subarray(from, to).toString("utf8");
49812
- const text4 = mask(raw);
49892
+ const text5 = mask(raw);
49813
49893
  const before = buf.subarray(0, from).toString("utf8");
49814
49894
  const after = buf.subarray(to).toString("utf8");
49815
- if (mask(before + raw) !== mask(before) + text4 || mask(raw + after) !== text4 + mask(after))
49895
+ if (mask(before + raw) !== mask(before) + text5 || mask(raw + after) !== text5 + mask(after))
49816
49896
  throw new Error(`${p} lines ${a}-${b} cut through text Sphica masks; cite more lines around it`);
49817
- return { path: p, commit, blob, size, lines: [a, b], raw, text: text4 };
49897
+ return { path: p, commit, blob, size, lines: [a, b], raw, text: text5 };
49818
49898
  }
49819
49899
  var excerptKey = (file3) => JSON.stringify([file3.path, file3.commit, file3.lines]);
49820
49900
  function excerptOf(facts, file3) {
@@ -50311,12 +50391,12 @@ ${c.errors.map((e) => ` ${e}`).join(`
50311
50391
  var CONTROL_SEQUENCE = /(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]?/;
50312
50392
  var HIDDEN = new RegExp(`${STRING_SEQUENCE.source}|${CONTROL_SEQUENCE.source}`, "g");
50313
50393
  function sequences(all) {
50314
- const text4 = all.toString("utf8");
50394
+ const text5 = all.toString("utf8");
50315
50395
  const out = [];
50316
50396
  let index = 0;
50317
50397
  let at = 0;
50318
- for (const m of text4.matchAll(HIDDEN)) {
50319
- at += bytes(text4.slice(index, m.index));
50398
+ for (const m of text5.matchAll(HIDDEN)) {
50399
+ at += bytes(text5.slice(index, m.index));
50320
50400
  index = m.index + m[0].length;
50321
50401
  if (plain2(m[0]) === "")
50322
50402
  out.push([at, at + bytes(m[0])]);
@@ -50330,11 +50410,11 @@ function cutEnd(all, hide2, from, room) {
50330
50410
  const end = inside ? inside[0] > from ? inside[0] : inside[1] : cut;
50331
50411
  return bytes(plain2(all.subarray(from, end).toString("utf8"))) > Math.max(room, 0) ? cut : end;
50332
50412
  }
50333
- function shownStart(text4, room) {
50334
- const whole = plain2(text4);
50413
+ function shownStart(text5, room) {
50414
+ const whole = plain2(text5);
50335
50415
  if (bytes(whole) <= room)
50336
- return { text: whole, end: bytes(text4), whole: true };
50337
- const all = Buffer.from(text4, "utf8");
50416
+ return { text: whole, end: bytes(text5), whole: true };
50417
+ const all = Buffer.from(text5, "utf8");
50338
50418
  const end = cutEnd(all, sequences(all), 0, room);
50339
50419
  return { text: plain2(all.subarray(0, end).toString("utf8")), end, whole: false };
50340
50420
  }
@@ -50853,12 +50933,12 @@ async function contextText(db, id, projectId2, root, after, auto = false, signal
50853
50933
  const heading = label(end);
50854
50934
  const max = room - (heading ? bytes(heading) + 1 : 0);
50855
50935
  const body = entry(it, context ? Math.min(CONTEXT_BYTES, max) : max);
50856
- const text4 = heading ? `${heading}
50936
+ const text5 = heading ? `${heading}
50857
50937
  ${body}` : body;
50858
- if (page2.length && used + bytes(text4) + 1 > room)
50938
+ if (page2.length && used + bytes(text5) + 1 > room)
50859
50939
  break;
50860
- page2.push({ id: it.id, text: text4, context });
50861
- used += bytes(text4) + 1;
50940
+ page2.push({ id: it.id, text: text5, context });
50941
+ used += bytes(text5) + 1;
50862
50942
  }
50863
50943
  const left = items.length - end;
50864
50944
  const nextNo = pageNo + (page2.some((x) => !x.context) ? 1 : 0);
@@ -51114,28 +51194,28 @@ async function saveText(db, id, projectId2, root, record4, probe, call) {
51114
51194
  lines: errors3.map((x) => `✗ ${x}`)
51115
51195
  }));
51116
51196
  });
51117
- const text4 = firstPage({
51197
+ const text5 = firstPage({
51118
51198
  kind: "save",
51119
51199
  projectId: projectId2,
51120
51200
  lead: ["✓ saved", ...tally(done.saved, done.changes, done.lines)],
51121
51201
  lines: done.lines
51122
51202
  });
51123
51203
  shownTo.delete(id);
51124
- return text4;
51204
+ return text5;
51125
51205
  }
51126
51206
 
51127
51207
  // server/src/backups.ts
51128
- import fs8 from "node:fs";
51129
- import path8 from "node:path";
51130
- var backupDir = (file3 = dbFile()) => path8.join(path8.dirname(file3), "backups");
51131
- var stem = (file3) => path8.basename(file3).replace(/\.db$/, "");
51208
+ import fs10 from "node:fs";
51209
+ import path10 from "node:path";
51210
+ var backupDir = (file3 = dbFile()) => path10.join(path10.dirname(file3), "backups");
51211
+ var stem = (file3) => path10.basename(file3).replace(/\.db$/, "");
51132
51212
  var pattern = (file3) => new RegExp(`^${stem(file3).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.rev\\d+\\.(\\d{8}T\\d{9}Z)\\.\\d+\\.db$`);
51133
51213
  function backups(file3 = dbFile()) {
51134
51214
  const dir = backupDir(file3);
51135
- if (!fs8.existsSync(dir))
51215
+ if (!fs10.existsSync(dir))
51136
51216
  return [];
51137
51217
  const named = pattern(file3);
51138
- return fs8.readdirSync(dir).filter((f) => named.test(f)).sort((a, b) => (named.exec(b)?.[1] ?? "").localeCompare(named.exec(a)?.[1] ?? "") || b.localeCompare(a)).map((f) => path8.join(dir, f));
51218
+ return fs10.readdirSync(dir).filter((f) => named.test(f)).sort((a, b) => (named.exec(b)?.[1] ?? "").localeCompare(named.exec(a)?.[1] ?? "") || b.localeCompare(a)).map((f) => path10.join(dir, f));
51139
51219
  }
51140
51220
 
51141
51221
  // server/src/forget.ts
@@ -51304,14 +51384,14 @@ function forgetWords(o, file3) {
51304
51384
  }
51305
51385
  function forgetQuestion(o, file3) {
51306
51386
  const w = forgetWords(o, file3);
51307
- const text4 = (kept) => [
51387
+ const text5 = (kept) => [
51308
51388
  `Forget ${plural2(o.sources.length, "source")} for good?`,
51309
51389
  ...w.must,
51310
51390
  ...w.records.slice(0, kept),
51311
51391
  ...kept < w.records.length ? [`and ${plural2(w.records.length - kept, "more record")}: forget_preview lists every one`] : []
51312
51392
  ].join(`
51313
51393
  `);
51314
- return text4(fitCount(w.records, READ_BUDGET, text4));
51394
+ return text5(fitCount(w.records, READ_BUDGET, text5));
51315
51395
  }
51316
51396
 
51317
51397
  // server/src/stdio-limit.ts
@@ -51358,7 +51438,8 @@ async function projectOf(cwd, meta3) {
51358
51438
  }
51359
51439
  async function called(name, cwd, meta3) {
51360
51440
  const p = await projectOf(cwd, meta3);
51361
- return { p, call: await logCall(conn(), p.projectId, name, callerOf(meta3)) };
51441
+ const by = callerOf(meta3);
51442
+ return { p, by, call: await logCall(conn(), p.projectId, name, by) };
51362
51443
  }
51363
51444
  var tool = (fn) => fn().then((t) => reply(t), (e) => reply(e instanceof RecordRefused ? e.message : `Sphica: ${head(reason(e), 2000)}`, true));
51364
51445
  var server = new McpServer({ name: "sphica-record", version: versionAt(ROOT) ?? "unknown" }, {
@@ -51382,7 +51463,9 @@ server.registerTool("trace_pending", {
51382
51463
  inputSchema: exports_external.object({ auto: AUTO, cwd: CWD }).strict(),
51383
51464
  annotations: READ
51384
51465
  }, async (a, extra) => tool(async () => {
51385
- const { p, call } = await called("trace_pending", a.cwd, extra._meta);
51466
+ const { p, by, call } = await called("trace_pending", a.cwd, extra._meta);
51467
+ if (a.auto && by.host === "codex" && by.mode !== "interactive")
51468
+ return "Sphica did not see a person start this Codex turn in the session's own thread (a child thread, codex exec, or a client it does not know), so the automatic trace does nothing this time.";
51386
51469
  const skip = a.auto ? await callSession(conn(), call) : undefined;
51387
51470
  return pendingText(conn(), p.projectId, undefined, { auto: a.auto, skip });
51388
51471
  }));
@@ -51487,7 +51570,7 @@ server.registerTool("forget_apply", {
51487
51570
  if (n > 0) {
51488
51571
  const refused2 = (why) => new Error(`${why}, so nothing was forgotten`);
51489
51572
  if (!server.server.getClientCapabilities()?.elicitation)
51490
- throw refused2("This host cannot ask you directly (run /sphica:forget in Claude Code)");
51573
+ throw refused2("This host cannot ask you directly (run forget in an interactive Claude Code or Codex session)");
51491
51574
  let answer;
51492
51575
  try {
51493
51576
  answer = await server.server.elicitInput({