sphica 0.6.52 → 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.
package/dist/deliver.js CHANGED
@@ -1,9 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // server/src/deliver.ts
4
- import fs9 from "node:fs";
5
- import os3 from "node:os";
6
- import path10 from "node:path";
4
+ import fs11 from "node:fs";
5
+ import path12 from "node:path";
7
6
  import { fileURLToPath as fileURLToPath2 } from "node:url";
8
7
 
9
8
  // server/node_modules/kysely/dist/util/object-utils.js
@@ -11081,8 +11080,49 @@ async function authorityOf(db, ids, asOf) {
11081
11080
 
11082
11081
  // server/src/capture.ts
11083
11082
  import { spawn as spawn2 } from "node:child_process";
11084
- import fs6 from "node:fs";
11085
- import path7 from "node:path";
11083
+ import fs8 from "node:fs";
11084
+ import path9 from "node:path";
11085
+
11086
+ // server/src/codex-log.ts
11087
+ import fs from "node:fs";
11088
+ import path2 from "node:path";
11089
+ var SESSION_META_BYTES = 256 * 1024;
11090
+ var text = (v) => typeof v === "string" ? v : null;
11091
+ function codexThread(input) {
11092
+ const file = input.transcript_path;
11093
+ if (typeof file !== "string" || !path2.isAbsolute(file))
11094
+ return null;
11095
+ let fd;
11096
+ try {
11097
+ if (!fs.lstatSync(file).isFile())
11098
+ return null;
11099
+ fd = fs.openSync(file, "r");
11100
+ const buffer = Buffer.alloc(SESSION_META_BYTES);
11101
+ const read = fs.readSync(fd, buffer, 0, SESSION_META_BYTES, 0);
11102
+ const end = buffer.subarray(0, read).indexOf(10);
11103
+ if (end < 0)
11104
+ return null;
11105
+ const line = JSON.parse(buffer.subarray(0, end).toString("utf8"));
11106
+ const payload = line?.payload;
11107
+ if (line?.type !== "session_meta" || !payload || typeof payload !== "object" || Array.isArray(payload))
11108
+ return null;
11109
+ const source = payload.source;
11110
+ return {
11111
+ id: text(payload.id),
11112
+ originator: text(payload.originator),
11113
+ threadSource: text(payload.thread_source),
11114
+ parent: text(payload.parent_thread_id),
11115
+ subagent: source && typeof source === "object" ? text(source.subagent) : null
11116
+ };
11117
+ } catch {
11118
+ return null;
11119
+ } finally {
11120
+ if (fd !== undefined)
11121
+ fs.closeSync(fd);
11122
+ }
11123
+ }
11124
+ var ownThread = (input, thread) => Boolean(input.session_id) && thread?.id === input.session_id && thread?.threadSource === "user";
11125
+ var childThread = (input, thread) => input.session_id && thread?.threadSource === "subagent" && thread.parent === input.session_id && thread.id !== null && thread.id !== input.session_id && /^[\x21-\x7e]{1,200}$/.test(thread.id) ? thread.id : null;
11086
11126
 
11087
11127
  // server/src/kysely-node-sqlite.ts
11088
11128
  var plain = (row) => {
@@ -11113,14 +11153,14 @@ function adapt(raw) {
11113
11153
  }
11114
11154
 
11115
11155
  // server/src/sqlite.ts
11116
- import fs3 from "node:fs";
11156
+ import fs4 from "node:fs";
11117
11157
  import os2 from "node:os";
11118
- import path4 from "node:path";
11158
+ import path5 from "node:path";
11119
11159
  import { constants as C, DatabaseSync } from "node:sqlite";
11120
11160
 
11121
11161
  // server/src/plugin.ts
11122
- import fs2 from "node:fs";
11123
- import path3 from "node:path";
11162
+ import fs3 from "node:fs";
11163
+ import path4 from "node:path";
11124
11164
  import { fileURLToPath } from "node:url";
11125
11165
 
11126
11166
  // server/node_modules/smol-toml/dist/error.js
@@ -11392,10 +11432,10 @@ var SHORT = new Set(["SessionEnd", "Interrupt"]);
11392
11432
 
11393
11433
  // server/src/git.ts
11394
11434
  import { execFileSync, spawn } from "node:child_process";
11395
- import fs from "node:fs";
11435
+ import fs2 from "node:fs";
11396
11436
  import os from "node:os";
11397
- import path2 from "node:path";
11398
- var gitHome = () => path2.join(os.homedir(), ".sphica", "git");
11437
+ import path3 from "node:path";
11438
+ var gitHome = () => path3.join(os.homedir(), ".sphica", "git");
11399
11439
  function gitEnv(extra = {}) {
11400
11440
  const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^GIT_/i.test(k)));
11401
11441
  return {
@@ -11407,7 +11447,7 @@ function gitEnv(extra = {}) {
11407
11447
  ...extra
11408
11448
  };
11409
11449
  }
11410
- var gitOptions = (hooks = path2.join(gitHome(), "hooks")) => [
11450
+ var gitOptions = (hooks = path3.join(gitHome(), "hooks")) => [
11411
11451
  "-c",
11412
11452
  "core.fsmonitor=",
11413
11453
  "-c",
@@ -11426,7 +11466,7 @@ var DIFF_OPTIONS = [
11426
11466
  ];
11427
11467
  function startDir() {
11428
11468
  const home = os.homedir();
11429
- return fs.statSync(home, { throwIfNoEntry: false })?.isDirectory() ? home : path2.dirname(process.execPath);
11469
+ return fs2.statSync(home, { throwIfNoEntry: false })?.isDirectory() ? home : path3.dirname(process.execPath);
11430
11470
  }
11431
11471
  function run(root, args, { max = 1024 * 1024, timeout = 1e4 } = {}) {
11432
11472
  return execFileSync("git", ["-C", root, ...gitOptions(), ...args], {
@@ -11438,7 +11478,7 @@ function run(root, args, { max = 1024 * 1024, timeout = 1e4 } = {}) {
11438
11478
  killSignal: "SIGKILL"
11439
11479
  });
11440
11480
  }
11441
- var text = (root, args, limits) => run(root, args, limits).toString("utf8");
11481
+ var text2 = (root, args, limits) => run(root, args, limits).toString("utf8");
11442
11482
  var list = (out) => out.split("\x00").filter(Boolean);
11443
11483
  function revision(rev) {
11444
11484
  if (!rev || rev.startsWith("-") || /[\0\n]/.test(rev))
@@ -11450,10 +11490,10 @@ function objectId(oid) {
11450
11490
  throw new Error(`not an object id: ${JSON.stringify(oid)}`);
11451
11491
  return oid;
11452
11492
  }
11453
- var topLevel = (dir, limits) => text(dir, ["rev-parse", "--show-toplevel"], limits).trim();
11454
- var commitOf = (root, rev, limits) => text(root, ["rev-parse", "--verify", "-q", `${revision(rev)}^{commit}`], limits).trim();
11455
- var baseRef = (root, which, limits) => text(root, which === "origin/HEAD" ? ["rev-parse", "--abbrev-ref", "origin/HEAD"] : ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], limits).trim();
11456
- var mergeBase = (root, a, b, limits) => text(root, ["merge-base", revision(a), revision(b)], limits).trim();
11493
+ var topLevel = (dir, limits) => text2(dir, ["rev-parse", "--show-toplevel"], limits).trim();
11494
+ var commitOf = (root, rev, limits) => text2(root, ["rev-parse", "--verify", "-q", `${revision(rev)}^{commit}`], limits).trim();
11495
+ var baseRef = (root, which, limits) => text2(root, which === "origin/HEAD" ? ["rev-parse", "--abbrev-ref", "origin/HEAD"] : ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], limits).trim();
11496
+ var mergeBase = (root, a, b, limits) => text2(root, ["merge-base", revision(a), revision(b)], limits).trim();
11457
11497
  function isAncestor(root, a, b, limits) {
11458
11498
  try {
11459
11499
  run(root, ["merge-base", "--is-ancestor", objectId(a), objectId(b)], limits);
@@ -11462,7 +11502,7 @@ function isAncestor(root, a, b, limits) {
11462
11502
  return false;
11463
11503
  }
11464
11504
  }
11465
- var commitDiffNames = (root, a, b, limits) => list(text(root, ["diff", ...DIFF_OPTIONS, "--name-only", "-z", objectId(a), objectId(b), "--"], limits));
11505
+ var commitDiffNames = (root, a, b, limits) => list(text2(root, ["diff", ...DIFF_OPTIONS, "--name-only", "-z", objectId(a), objectId(b), "--"], limits));
11466
11506
  function listFiles(root, kind, { pathspecs = [], ...limits } = {}) {
11467
11507
  const which = {
11468
11508
  tracked: ["--cached"],
@@ -11470,9 +11510,9 @@ function listFiles(root, kind, { pathspecs = [], ...limits } = {}) {
11470
11510
  "tracked-and-untracked": ["--cached", "--others", "--exclude-standard"],
11471
11511
  deleted: ["--deleted"]
11472
11512
  }[kind];
11473
- return list(text(root, ["ls-files", "-z", ...which, "--", ...pathspecs], limits));
11513
+ return list(text2(root, ["ls-files", "-z", ...which, "--", ...pathspecs], limits));
11474
11514
  }
11475
- var originUrl = (root, limits) => text(root, ["remote", "get-url", "origin"], limits).trim();
11515
+ var originUrl = (root, limits) => text2(root, ["remote", "get-url", "origin"], limits).trim();
11476
11516
  async function worktreeStatus(root, deadline) {
11477
11517
  const out = await inIsolation(root, [{ kind: "status" }], { deadline, max: 16 * 1024 * 1024 });
11478
11518
  return Array.isArray(out) ? out[0] ?? null : null;
@@ -11484,8 +11524,8 @@ async function worktreeDiff(root, from, { max, deadline }) {
11484
11524
  return out.length === 2 ? { patch: out[0] ?? "", names: list(out[1] ?? "") } : { unread: "failed" };
11485
11525
  }
11486
11526
  function workerFile() {
11487
- const js = path2.join(import.meta.dirname, "git-worker.js");
11488
- return fs.existsSync(js) ? js : path2.join(import.meta.dirname, "git-worker.ts");
11527
+ const js = path3.join(import.meta.dirname, "git-worker.js");
11528
+ return fs2.existsSync(js) ? js : path3.join(import.meta.dirname, "git-worker.ts");
11489
11529
  }
11490
11530
  function unreadOf(e) {
11491
11531
  const code = e?.code;
@@ -11573,11 +11613,11 @@ function inIsolation(root, ops, { deadline, max }) {
11573
11613
 
11574
11614
  // server/src/panel.ts
11575
11615
  import { stripVTControlCharacters, styleText } from "node:util";
11576
- var title = (text2) => `✦ ${text2}`;
11577
- var rule = (text2) => text2.split(`
11616
+ var title = (text3) => `✦ ${text3}`;
11617
+ var rule = (text3) => text3.split(`
11578
11618
  `).map((line) => line ? `│ ${line}` : "│").join(`
11579
11619
  `);
11580
- var foot = (text2) => `╰─ ${text2}`;
11620
+ var foot = (text3) => `╰─ ${text3}`;
11581
11621
  var panel = (head2, lines, end) => [title(head2), ...lines.map(rule), foot(end)].join(`
11582
11622
  `);
11583
11623
  var STRING_SEQUENCE = /\u001b[\]P_^X][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g;
@@ -11586,11 +11626,11 @@ var plain2 = (s) => visible(stripVTControlCharacters(s.replace(STRING_SEQUENCE,
11586
11626
  var inline = (s) => plain2(s).replace(/[\n\t]+/g, " ");
11587
11627
 
11588
11628
  // server/src/plugin.ts
11589
- var MANIFEST = path3.join(".claude-plugin", "plugin.json");
11629
+ var MANIFEST = path4.join(".claude-plugin", "plugin.json");
11590
11630
  var PACKAGE = "package.json";
11591
11631
  function versionAt(root) {
11592
11632
  try {
11593
- const m = JSON.parse(fs2.readFileSync(path3.join(root, MANIFEST), "utf8"));
11633
+ const m = JSON.parse(fs3.readFileSync(path4.join(root, MANIFEST), "utf8"));
11594
11634
  return m.name === "sphica" && typeof m.version === "string" ? m.version : null;
11595
11635
  } catch {
11596
11636
  return null;
@@ -11598,28 +11638,28 @@ function versionAt(root) {
11598
11638
  }
11599
11639
  function packageVersionAt(root) {
11600
11640
  try {
11601
- const m = JSON.parse(fs2.readFileSync(path3.join(root, PACKAGE), "utf8"));
11641
+ const m = JSON.parse(fs3.readFileSync(path4.join(root, PACKAGE), "utf8"));
11602
11642
  return m.name === "sphica" && typeof m.version === "string" ? m.version : null;
11603
11643
  } catch {
11604
11644
  return null;
11605
11645
  }
11606
11646
  }
11607
- var here = path3.dirname(fileURLToPath(import.meta.url));
11608
- var ROOT = [path3.join(here, ".."), path3.join(here, "..", "..", "plugin")].find((r) => versionAt(r) !== null) ?? path3.join(here, "..");
11647
+ var here = path4.dirname(fileURLToPath(import.meta.url));
11648
+ var ROOT = [path4.join(here, ".."), path4.join(here, "..", "..", "plugin")].find((r) => versionAt(r) !== null) ?? path4.join(here, "..");
11609
11649
  var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
11610
11650
 
11611
11651
  // server/src/sqlite.ts
11612
11652
  var SCHEMA_GENERATION = 2;
11613
11653
  var SCHEMA_REVISION = 12;
11614
- var sphicaHome = () => process.env.SPHICA_HOME || path4.join(os2.homedir(), ".sphica");
11615
- var dbFile = () => process.env.SPHICA_DB || path4.join(sphicaHome(), "sphica.db");
11654
+ var sphicaHome = () => process.env.SPHICA_HOME || path5.join(os2.homedir(), ".sphica");
11655
+ var dbFile = () => process.env.SPHICA_DB || path5.join(sphicaHome(), "sphica.db");
11616
11656
  function requireRuntime() {
11617
11657
  const proto = DatabaseSync.prototype;
11618
11658
  if (typeof proto.setAuthorizer !== "function" || typeof proto.enableDefensive !== "function")
11619
11659
  throw new Error(`Sphica needs Node 24.15 or later (this is ${process.version}). Upgrade Node.`);
11620
11660
  }
11621
11661
  function requireFile(file) {
11622
- if (!fs3.existsSync(file))
11662
+ if (!fs4.existsSync(file))
11623
11663
  throw new Error(`No database at ${file}. Create it with \`sphica init\`.`);
11624
11664
  }
11625
11665
  function prepare(raw, check, busyMs = 5000) {
@@ -11978,7 +12018,7 @@ function connectWriter(role, file = dbFile(), create = false, busyMs) {
11978
12018
  const raw = new DatabaseSync2(file);
11979
12019
  try {
11980
12020
  prepare(raw, create ? "none" : role === "ingest" || role === "forget" ? "revision" : "generation", busyMs);
11981
- raw.function("sphica_terms", { deterministic: true }, (text2) => terms(String(text2 ?? "")).join(" "));
12021
+ raw.function("sphica_terms", { deterministic: true }, (text3) => terms(String(text3 ?? "")).join(" "));
11982
12022
  } catch (e) {
11983
12023
  raw.close();
11984
12024
  throw e;
@@ -12012,10 +12052,32 @@ function openWriter(role, file = dbFile(), busyMs) {
12012
12052
  // server/src/knowledge.ts
12013
12053
  var sessionId = (projectId, host, externalId) => uuidFrom(String(projectId), host, externalId);
12014
12054
 
12055
+ // server/src/once.ts
12056
+ import fs5 from "node:fs";
12057
+ import os3 from "node:os";
12058
+ import path6 from "node:path";
12059
+ function markOnce(kind, key) {
12060
+ const user = (() => {
12061
+ try {
12062
+ return os3.userInfo().username;
12063
+ } catch {
12064
+ return String(process.getuid?.() ?? "user");
12065
+ }
12066
+ })();
12067
+ const dir = path6.join(os3.tmpdir(), `sphica-${sha256(user).toString("hex").slice(0, 12)}`, kind);
12068
+ try {
12069
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
12070
+ fs5.writeFileSync(path6.join(dir, sha256(key).toString("hex").slice(0, 24)), "", { flag: "wx" });
12071
+ return true;
12072
+ } catch (e) {
12073
+ return e.code !== "EEXIST";
12074
+ }
12075
+ }
12076
+
12015
12077
  // server/src/project.ts
12016
- import fs4 from "node:fs";
12017
- import path5 from "node:path";
12018
- var localFile = () => path5.join(sphicaHome(), "projects.json");
12078
+ import fs6 from "node:fs";
12079
+ import path7 from "node:path";
12080
+ var localFile = () => path7.join(sphicaHome(), "projects.json");
12019
12081
  var LOCAL_KEY = /^[a-z0-9][a-z0-9._-]*$/;
12020
12082
  function legacyRemote(url) {
12021
12083
  const raw = String(url ?? "").trim();
@@ -12054,7 +12116,7 @@ var top = (dir) => ask(() => topLevel(dir, { timeout: 5000 }));
12054
12116
  function localMap() {
12055
12117
  let raw;
12056
12118
  try {
12057
- raw = fs4.readFileSync(localFile(), "utf8");
12119
+ raw = fs6.readFileSync(localFile(), "utf8");
12058
12120
  } catch (e) {
12059
12121
  if (e.code === "ENOENT")
12060
12122
  return {};
@@ -12066,12 +12128,12 @@ function localMap() {
12066
12128
  } catch {
12067
12129
  m = null;
12068
12130
  }
12069
- if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path5.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
12131
+ if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path7.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
12070
12132
  throw new Error(`${localFile()} is not a valid JSON project table. Fix or delete it, then name the project again.`);
12071
12133
  return m;
12072
12134
  }
12073
12135
  function identify(dir) {
12074
- const given = path5.resolve(dir);
12136
+ const given = path7.resolve(dir);
12075
12137
  const found = top(given);
12076
12138
  const root = found || given;
12077
12139
  const legacy = found ? legacyRemote(ask(() => originUrl(root, { timeout: 5000 }))) : null;
@@ -12081,11 +12143,11 @@ function identify(dir) {
12081
12143
  return { key, legacyKey: `git:${legacy}`, root, name: remote.split("/").slice(1).join("/") || remote };
12082
12144
  }
12083
12145
  const map = localMap();
12084
- for (let d = root;; d = path5.dirname(d)) {
12146
+ for (let d = root;; d = path7.dirname(d)) {
12085
12147
  const local = map[d];
12086
12148
  if (local && LOCAL_KEY.test(local))
12087
12149
  return { key: `local:${local}`, legacyKey: `local:${local}`, root: d, name: local };
12088
- if (found || path5.dirname(d) === d)
12150
+ if (found || path7.dirname(d) === d)
12089
12151
  return null;
12090
12152
  }
12091
12153
  }
@@ -12094,11 +12156,11 @@ async function projectId(db, key) {
12094
12156
  return r?.id ?? null;
12095
12157
  }
12096
12158
  function relativeTo(root, file, cwd = root) {
12097
- const abs = path5.resolve(cwd, file);
12098
- const rel = path5.relative(root, abs);
12159
+ const abs = path7.resolve(cwd, file);
12160
+ const rel = path7.relative(root, abs);
12099
12161
  if (!rel || leaves(rel) || /\p{Cc}/u.test(rel))
12100
12162
  return null;
12101
- return rel.split(path5.sep).join("/");
12163
+ return rel.split(path7.sep).join("/");
12102
12164
  }
12103
12165
  function patchPaths(patch) {
12104
12166
  const out = [];
@@ -12112,8 +12174,8 @@ function patchPaths(patch) {
12112
12174
  }
12113
12175
 
12114
12176
  // server/src/worktree.ts
12115
- import fs5 from "node:fs";
12116
- import path6 from "node:path";
12177
+ import fs7 from "node:fs";
12178
+ import path8 from "node:path";
12117
12179
  var MAX_PATHS = 200;
12118
12180
  var LIMITS = { timeout: 5000, max: 16 * 1024 * 1024 };
12119
12181
  var STATUS_DEADLINE = 5000;
@@ -12138,7 +12200,7 @@ async function snapshot(root) {
12138
12200
  continue;
12139
12201
  let st;
12140
12202
  try {
12141
- st = fs5.lstatSync(path6.join(root, p), { throwIfNoEntry: false });
12203
+ st = fs7.lstatSync(path8.join(root, p), { throwIfNoEntry: false });
12142
12204
  } catch {
12143
12205
  st = undefined;
12144
12206
  }
@@ -12170,15 +12232,15 @@ function changed(root, before, after) {
12170
12232
  }
12171
12233
 
12172
12234
  // server/src/capture.ts
12173
- var spoolDir = () => path7.join(sphicaHome(), "spool");
12174
- var stateFile = () => path7.join(sphicaHome(), "capture.json");
12175
- var rejectedDir = () => path7.join(spoolDir(), "rejected");
12176
- var unregisteredDir = () => path7.join(spoolDir(), "unregistered");
12177
- var callsDir = () => path7.join(spoolDir(), "calls");
12178
- var callsRejectedDir = () => path7.join(callsDir(), "rejected");
12235
+ var spoolDir = () => path9.join(sphicaHome(), "spool");
12236
+ var stateFile = () => path9.join(sphicaHome(), "capture.json");
12237
+ var rejectedDir = () => path9.join(spoolDir(), "rejected");
12238
+ var unregisteredDir = () => path9.join(spoolDir(), "unregistered");
12239
+ var callsDir = () => path9.join(spoolDir(), "calls");
12240
+ var callsRejectedDir = () => path9.join(callsDir(), "rejected");
12179
12241
  var HOLD_DAYS = 30;
12180
12242
  var HOLD_MAX = 1000;
12181
- var baselineDir = () => path7.join(sphicaHome(), "worktree");
12243
+ var baselineDir = () => path9.join(sphicaHome(), "worktree");
12182
12244
  function current(raw) {
12183
12245
  const r = raw;
12184
12246
  if (typeof r.project !== "string")
@@ -12227,7 +12289,7 @@ ${z}`,
12227
12289
  function prune(held, removed = () => {}) {
12228
12290
  let files;
12229
12291
  try {
12230
- files = fs6.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
12292
+ files = fs8.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
12231
12293
  } catch {
12232
12294
  return;
12233
12295
  }
@@ -12235,26 +12297,26 @@ function prune(held, removed = () => {}) {
12235
12297
  const stale = files.filter((f) => Number(f.split("-")[0]) < cutoff);
12236
12298
  const over = files.slice(0, Math.max(0, files.length - HOLD_MAX));
12237
12299
  for (const f of new Set([...stale, ...over])) {
12238
- fs6.rmSync(path7.join(held, f), { force: true });
12300
+ fs8.rmSync(path9.join(held, f), { force: true });
12239
12301
  removed();
12240
12302
  }
12241
12303
  }
12242
12304
  function put(dir, record) {
12243
- fs6.mkdirSync(dir, { recursive: true, mode: 448 });
12305
+ fs8.mkdirSync(dir, { recursive: true, mode: 448 });
12244
12306
  const name = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 10)}.json`;
12245
- const tmp = path7.join(dir, `.${name}`);
12246
- fs6.writeFileSync(tmp, JSON.stringify(record), { mode: 384 });
12247
- fs6.renameSync(tmp, path7.join(dir, name));
12248
- return path7.join(dir, name);
12307
+ const tmp = path9.join(dir, `.${name}`);
12308
+ fs8.writeFileSync(tmp, JSON.stringify(record), { mode: 384 });
12309
+ fs8.renameSync(tmp, path9.join(dir, name));
12310
+ return path9.join(dir, name);
12249
12311
  }
12250
12312
  function spool(record) {
12251
12313
  put(spoolDir(), record);
12252
12314
  }
12253
12315
  var branchOf = (root) => {
12254
12316
  try {
12255
- const dotgit = path7.join(root, ".git");
12256
- const gitdir = fs6.statSync(dotgit).isFile() ? path7.resolve(root, fs6.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
12257
- const h = fs6.readFileSync(path7.join(gitdir, "HEAD"), "utf8").trim();
12317
+ const dotgit = path9.join(root, ".git");
12318
+ const gitdir = fs8.statSync(dotgit).isFile() ? path9.resolve(root, fs8.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
12319
+ const h = fs8.readFileSync(path9.join(gitdir, "HEAD"), "utf8").trim();
12258
12320
  return h.startsWith("ref: refs/heads/") ? h.slice("ref: refs/heads/".length) : null;
12259
12321
  } catch {
12260
12322
  return null;
@@ -12300,7 +12362,7 @@ Notes: ${notes.trim()}` : "";
12300
12362
  };
12301
12363
  }
12302
12364
  function captureNotice(file = dbFile()) {
12303
- if (!fs6.existsSync(file))
12365
+ if (!fs8.existsSync(file))
12304
12366
  return panel("sphica: no database, so conversations are not recorded", [file], "Create it with sphica init");
12305
12367
  const s = readState();
12306
12368
  if (s.unreadable)
@@ -12311,15 +12373,15 @@ function captureNotice(file = dbFile()) {
12311
12373
  return panel(`sphica: the database rejected ${plural(s.rejected, "record")}`, [rejectedDir(), `Move them back to ${spoolDir()} to resend`], "Fix them first, then check with sphica doctor");
12312
12374
  return null;
12313
12375
  }
12314
- var turnDir = (host, session) => path7.join(baselineDir(), digest(`${host}\x00${session}`));
12315
- var startFile = (dir, turn) => path7.join(dir, `${digest(turn)}.json`);
12376
+ var turnDir = (host, session) => path9.join(baselineDir(), digest(`${host}\x00${session}`));
12377
+ var startFile = (dir, turn) => path9.join(dir, `${digest(turn)}.json`);
12316
12378
  var isStart = (v) => {
12317
12379
  const s = v;
12318
12380
  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");
12319
12381
  };
12320
12382
  function readStart(file) {
12321
12383
  try {
12322
- const s = JSON.parse(fs6.readFileSync(file, "utf8"));
12384
+ const s = JSON.parse(fs8.readFileSync(file, "utf8"));
12323
12385
  return isStart(s) ? s : null;
12324
12386
  } catch {
12325
12387
  return null;
@@ -12328,7 +12390,7 @@ function readStart(file) {
12328
12390
  function readStarts(dir) {
12329
12391
  let names;
12330
12392
  try {
12331
- names = fs6.readdirSync(dir);
12393
+ names = fs8.readdirSync(dir);
12332
12394
  } catch (e) {
12333
12395
  return e.code === "ENOENT" ? [] : null;
12334
12396
  }
@@ -12336,7 +12398,7 @@ function readStarts(dir) {
12336
12398
  for (const name of names) {
12337
12399
  if (name.startsWith("."))
12338
12400
  continue;
12339
- const s = readStart(path7.join(dir, name));
12401
+ const s = readStart(path9.join(dir, name));
12340
12402
  if (!s)
12341
12403
  return null;
12342
12404
  starts.push(s);
@@ -12351,10 +12413,10 @@ function newestTurn(starts) {
12351
12413
  return at.length === 1 ? at[0]?.turn ?? null : null;
12352
12414
  }
12353
12415
  function writeStart(dir, s, file = startFile(dir, s.turn)) {
12354
- fs6.mkdirSync(dir, { recursive: true, mode: 448 });
12355
- const tmp = path7.join(dir, `.${path7.basename(file)}.${process.pid}.tmp`);
12356
- fs6.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
12357
- fs6.renameSync(tmp, file);
12416
+ fs8.mkdirSync(dir, { recursive: true, mode: 448 });
12417
+ const tmp = path9.join(dir, `.${path9.basename(file)}.${process.pid}.tmp`);
12418
+ fs8.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
12419
+ fs8.renameSync(tmp, file);
12358
12420
  }
12359
12421
  async function openTurn(dir, turn, root) {
12360
12422
  if (readStart(startFile(dir, turn))?.running)
@@ -12384,22 +12446,22 @@ function stopTurn(dir, turn) {
12384
12446
  }
12385
12447
  function pruneBaselines() {
12386
12448
  const cutoff = Date.now() - HOLD_DAYS * 24 * 60 * 60 * 1000;
12387
- const fresh = (file) => (fs6.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
12449
+ const fresh = (file) => (fs8.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
12388
12450
  let names;
12389
12451
  try {
12390
- names = fs6.readdirSync(baselineDir());
12452
+ names = fs8.readdirSync(baselineDir());
12391
12453
  } catch {
12392
12454
  return;
12393
12455
  }
12394
12456
  for (const name of names) {
12395
- const at = path7.join(baselineDir(), name);
12396
- if (!fs6.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
12457
+ const at = path9.join(baselineDir(), name);
12458
+ if (!fs8.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
12397
12459
  if (!fresh(at))
12398
- fs6.rmSync(at, { force: true });
12460
+ fs8.rmSync(at, { force: true });
12399
12461
  } else {
12400
- const files = fs6.readdirSync(at);
12401
- if (files.length && !files.some((f) => fresh(path7.join(at, f))))
12402
- fs6.rmSync(at, { recursive: true, force: true });
12462
+ const files = fs8.readdirSync(at);
12463
+ if (files.length && !files.some((f) => fresh(path9.join(at, f))))
12464
+ fs8.rmSync(at, { recursive: true, force: true });
12403
12465
  }
12404
12466
  }
12405
12467
  }
@@ -12417,22 +12479,36 @@ async function attemptAsync(fn) {
12417
12479
  return;
12418
12480
  }
12419
12481
  }
12482
+ function whoseTurn(host, input) {
12483
+ if (!isOwnerTurn(input, undefined, undefined, host === "codex" ? process.env.CODEX_THREAD_ID : undefined))
12484
+ return "other";
12485
+ if (host !== "codex")
12486
+ return "owner";
12487
+ const thread = codexThread(input);
12488
+ if (ownThread(input, thread))
12489
+ return "owner";
12490
+ return childThread(input, thread) === null ? "unconfirmed" : "other";
12491
+ }
12492
+ var unconfirmed = (input) => !markOnce("unconfirmed", `codex\x00${input.session_id}`) ? null : typeof input.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", [
12493
+ "Codex named no session log (as with --ephemeral), so Sphica cannot confirm these messages are yours"
12494
+ ], "To record a session, start Codex without --ephemeral");
12420
12495
  async function onHook(host, input) {
12421
12496
  const event = input.hook_event_name;
12422
- const owner = () => isOwnerTurn(input, undefined, undefined, host === "codex" ? process.env.CODEX_THREAD_ID : undefined);
12497
+ const whose = whoseTurn(host, input);
12498
+ if (whose !== "owner")
12499
+ return {
12500
+ flush: false,
12501
+ notice: whose === "unconfirmed" && event === "UserPromptSubmit" ? unconfirmed(input) : null
12502
+ };
12423
12503
  if (event === "SessionStart") {
12424
- if (!owner())
12425
- return { flush: false };
12426
12504
  const file = process.env.CLAUDE_ENV_FILE;
12427
12505
  if (file && input.session_id && /^[A-Za-z0-9_-]+$/.test(input.session_id)) {
12428
- fs6.appendFileSync(file, `export SPHICA_PARENT_SESSION=${input.session_id}
12506
+ fs8.appendFileSync(file, `export SPHICA_PARENT_SESSION=${input.session_id}
12429
12507
  `);
12430
12508
  }
12431
12509
  attempt(pruneBaselines);
12432
12510
  return { flush: false, notice: captureNotice() };
12433
12511
  }
12434
- if (!owner())
12435
- return { flush: false };
12436
12512
  if (event === "Interrupt") {
12437
12513
  const turn2 = input.prompt_id ?? input.turn_id;
12438
12514
  if (turn2)
@@ -12508,7 +12584,7 @@ async function onHook(host, input) {
12508
12584
  function readStateFile() {
12509
12585
  let raw = {};
12510
12586
  try {
12511
- const parsed = JSON.parse(fs6.readFileSync(stateFile(), "utf8"));
12587
+ const parsed = JSON.parse(fs8.readFileSync(stateFile(), "utf8"));
12512
12588
  if (parsed && typeof parsed === "object")
12513
12589
  raw = parsed;
12514
12590
  } catch {}
@@ -12522,7 +12598,7 @@ function readStateFile() {
12522
12598
  }
12523
12599
  function writeState(s) {
12524
12600
  try {
12525
- fs6.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
12601
+ fs8.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
12526
12602
  } catch {}
12527
12603
  }
12528
12604
  function readState() {
@@ -12538,7 +12614,7 @@ function readState() {
12538
12614
  }
12539
12615
  function listQueue(dir) {
12540
12616
  try {
12541
- const names = fs6.readdirSync(dir);
12617
+ const names = fs8.readdirSync(dir);
12542
12618
  return {
12543
12619
  files: names.filter((f) => f.endsWith(".json") && !f.startsWith(".")),
12544
12620
  temp: names.filter((f) => f.endsWith(".json") && f.startsWith(".")),
@@ -12550,25 +12626,25 @@ function listQueue(dir) {
12550
12626
  }
12551
12627
  }
12552
12628
  function lock() {
12553
- const file = path7.join(spoolDir(), ".lock");
12554
- fs6.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
12629
+ const file = path9.join(spoolDir(), ".lock");
12630
+ fs8.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
12555
12631
  for (let attempt2 = 0;attempt2 < 2; attempt2++) {
12556
12632
  try {
12557
- fs6.writeFileSync(file, String(process.pid), { flag: "wx", mode: 384 });
12633
+ fs8.writeFileSync(file, String(process.pid), { flag: "wx", mode: 384 });
12558
12634
  return () => {
12559
12635
  try {
12560
- if (fs6.readFileSync(file, "utf8") === String(process.pid))
12561
- fs6.rmSync(file, { force: true });
12636
+ if (fs8.readFileSync(file, "utf8") === String(process.pid))
12637
+ fs8.rmSync(file, { force: true });
12562
12638
  } catch {}
12563
12639
  };
12564
12640
  } catch (e) {
12565
12641
  if (e.code !== "EEXIST")
12566
12642
  throw e;
12567
12643
  }
12568
- const st = fs6.statSync(file, { throwIfNoEntry: false });
12644
+ const st = fs8.statSync(file, { throwIfNoEntry: false });
12569
12645
  if (!st)
12570
12646
  continue;
12571
- const holder = Number(fs6.readFileSync(file, "utf8") || 0);
12647
+ const holder = Number(fs8.readFileSync(file, "utf8") || 0);
12572
12648
  const fresh = Date.now() - st.mtimeMs < 5 * 60000;
12573
12649
  const alive = (() => {
12574
12650
  if (holder <= 0)
@@ -12581,7 +12657,7 @@ function lock() {
12581
12657
  })();
12582
12658
  if (alive && fresh)
12583
12659
  return null;
12584
- fs6.rmSync(file, { force: true });
12660
+ fs8.rmSync(file, { force: true });
12585
12661
  }
12586
12662
  return null;
12587
12663
  }
@@ -12680,23 +12756,23 @@ var REJECTED = new Set([18, 19, 20, 25]);
12680
12756
  var rejected = (e) => REJECTED.has(sqliteCode(e) ?? -1);
12681
12757
  var queued = (from) => {
12682
12758
  try {
12683
- return fs6.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
12759
+ return fs8.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
12684
12760
  } catch {
12685
12761
  return [];
12686
12762
  }
12687
12763
  };
12688
12764
  var CODE_NAMES = { 18: "TOOBIG", 19: "CONSTRAINT", 20: "MISMATCH", 25: "RANGE" };
12689
12765
  function setAside(from, name, dir, reason2) {
12690
- fs6.mkdirSync(dir, { recursive: true, mode: 448 });
12766
+ fs8.mkdirSync(dir, { recursive: true, mode: 448 });
12691
12767
  try {
12692
- fs6.renameSync(path7.join(from, name), path7.join(dir, name));
12768
+ fs8.renameSync(path9.join(from, name), path9.join(dir, name));
12693
12769
  } catch (e) {
12694
12770
  if (e.code === "ENOENT")
12695
12771
  return;
12696
12772
  throw e;
12697
12773
  }
12698
12774
  try {
12699
- fs6.writeFileSync(path7.join(dir, `${name}.reason`), reason2, { mode: 384 });
12775
+ fs8.writeFileSync(path9.join(dir, `${name}.reason`), reason2, { mode: 384 });
12700
12776
  } catch {}
12701
12777
  }
12702
12778
  async function sendBatch(db, names) {
@@ -12706,7 +12782,7 @@ async function sendBatch(db, names) {
12706
12782
  let raw;
12707
12783
  let r;
12708
12784
  try {
12709
- raw = JSON.parse(fs6.readFileSync(path7.join(from, name), "utf8"));
12785
+ raw = JSON.parse(fs8.readFileSync(path9.join(from, name), "utf8"));
12710
12786
  } catch {
12711
12787
  setAside(from, name, rejectedDir(), "unreadable");
12712
12788
  continue;
@@ -12720,7 +12796,7 @@ async function sendBatch(db, names) {
12720
12796
  if (r)
12721
12797
  records.push({ name, from, r });
12722
12798
  else
12723
- fs6.rmSync(path7.join(from, name), { force: true });
12799
+ fs8.rmSync(path9.join(from, name), { force: true });
12724
12800
  }
12725
12801
  let sent = 0;
12726
12802
  let strayed = [];
@@ -12748,12 +12824,12 @@ async function sendBatch(db, names) {
12748
12824
  for (const x of bad)
12749
12825
  setAside(x.from, x.name, rejectedDir(), x.why);
12750
12826
  if (strayed.length) {
12751
- fs6.mkdirSync(held, { recursive: true, mode: 448 });
12827
+ fs8.mkdirSync(held, { recursive: true, mode: 448 });
12752
12828
  for (const x of strayed) {
12753
12829
  if (x.from === held)
12754
12830
  continue;
12755
12831
  try {
12756
- fs6.renameSync(path7.join(x.from, x.name), path7.join(held, x.name));
12832
+ fs8.renameSync(path9.join(x.from, x.name), path9.join(held, x.name));
12757
12833
  } catch (e) {
12758
12834
  if (e.code !== "ENOENT")
12759
12835
  throw e;
@@ -12763,7 +12839,7 @@ async function sendBatch(db, names) {
12763
12839
  const moved = new Set([...bad, ...strayed].map((x) => x.name));
12764
12840
  for (const x of records)
12765
12841
  if (!moved.has(x.name))
12766
- fs6.rmSync(path7.join(x.from, x.name), { force: true });
12842
+ fs8.rmSync(path9.join(x.from, x.name), { force: true });
12767
12843
  return { sent, rejected: bad.length };
12768
12844
  }
12769
12845
  async function sendObservations(db, names) {
@@ -12774,16 +12850,16 @@ async function sendObservations(db, names) {
12774
12850
  };
12775
12851
  const rows = [];
12776
12852
  for (const { name, from } of names) {
12777
- let text2;
12853
+ let text3;
12778
12854
  try {
12779
- text2 = fs6.readFileSync(path7.join(from, name), "utf8");
12855
+ text3 = fs8.readFileSync(path9.join(from, name), "utf8");
12780
12856
  } catch {
12781
12857
  continue;
12782
12858
  }
12783
12859
  let o = null;
12784
12860
  let why = "unreadable";
12785
12861
  try {
12786
- o = observation(JSON.parse(text2));
12862
+ o = observation(JSON.parse(text3));
12787
12863
  why = "shape";
12788
12864
  } catch {}
12789
12865
  if (o)
@@ -12815,7 +12891,7 @@ async function sendObservations(db, names) {
12815
12891
  aside(x.name, why);
12816
12892
  else
12817
12893
  try {
12818
- fs6.rmSync(path7.join(callsDir(), x.name), { force: true });
12894
+ fs8.rmSync(path9.join(callsDir(), x.name), { force: true });
12819
12895
  } catch {}
12820
12896
  }
12821
12897
  return true;
@@ -12958,7 +13034,7 @@ async function observeRecordCall(file, input, owner, waitMs = OBSERVE_WAIT_MS) {
12958
13034
  }
12959
13035
  if (kept)
12960
13036
  try {
12961
- fs6.rmSync(kept, { force: true });
13037
+ fs8.rmSync(kept, { force: true });
12962
13038
  } catch {}
12963
13039
  }
12964
13040
  async function main() {
@@ -13018,13 +13094,13 @@ function gitPath(token, prefix) {
13018
13094
  }
13019
13095
  return prefix && out.startsWith(prefix) ? out.slice(prefix.length) : out;
13020
13096
  }
13021
- function parseDiff(text2) {
13097
+ function parseDiff(text3) {
13022
13098
  const files = [];
13023
- const at = (path8) => {
13024
- const found = files.find((f2) => f2.path === path8);
13099
+ const at = (path10) => {
13100
+ const found = files.find((f2) => f2.path === path10);
13025
13101
  if (found)
13026
13102
  return found;
13027
- const f = { path: path8, added: [], lines: [] };
13103
+ const f = { path: path10, added: [], lines: [] };
13028
13104
  files.push(f);
13029
13105
  return f;
13030
13106
  };
@@ -13038,7 +13114,7 @@ function parseDiff(text2) {
13038
13114
  at(block);
13039
13115
  block = null;
13040
13116
  };
13041
- const rows = text2.split(/\r?\n/);
13117
+ const rows = text3.split(/\r?\n/);
13042
13118
  for (const [i, raw] of rows.entries()) {
13043
13119
  if (cur && (oldLeft > 0 || newLeft > 0)) {
13044
13120
  if (raw.startsWith("+")) {
@@ -13135,13 +13211,18 @@ async function selectForReview(db, projectId2, files) {
13135
13211
  }
13136
13212
 
13137
13213
  // server/src/review-bridge.ts
13138
- import fs7 from "node:fs";
13139
- import path8 from "node:path";
13214
+ import fs9 from "node:fs";
13215
+ import path10 from "node:path";
13140
13216
  var NAME = /^[\w.:/-]{1,100}$/;
13141
13217
  var MAX_DIFF = 4 * 1024 * 1024;
13142
13218
  var DIFF_DEADLINE = 5000;
13143
13219
  var MAX_FILES = 500;
13144
13220
  var MAX_UNTRACKED_BYTES = 256 * 1024;
13221
+ var names = (list2) => (list2 ?? "").split(",").map((n) => n.trim().toLowerCase()).filter((n) => NAME.test(n));
13222
+ var isReview = (name, named) => {
13223
+ const lower = name.toLowerCase();
13224
+ return lower !== "sphica:review" && (named.includes(lower) || lower.includes("review"));
13225
+ };
13145
13226
  function reviewCall(input) {
13146
13227
  let name;
13147
13228
  let args;
@@ -13154,16 +13235,52 @@ function reviewCall(input) {
13154
13235
  }
13155
13236
  if (typeof name !== "string" || !NAME.test(name))
13156
13237
  return null;
13157
- const lower = name.toLowerCase();
13158
- if (lower === "sphica:review")
13159
- return null;
13160
- const names = (list2) => (list2 ?? "").split(",").map((n) => n.trim().toLowerCase()).filter((n) => NAME.test(n));
13161
13238
  const option = names(process.env.CLAUDE_PLUGIN_OPTION_REVIEW_COMMANDS);
13162
13239
  const named = option.length > 0 ? option : names(process.env.SPHICA_REVIEW_COMMANDS);
13163
- if (!named.includes(lower) && !lower.includes("review"))
13240
+ if (!isReview(name, named))
13164
13241
  return null;
13165
13242
  return { name, args: typeof args === "string" ? args.slice(0, 1000) : "" };
13166
13243
  }
13244
+ var NAMED_SKILL = /(?<!\S)\$([\w.:/-]{1,100})/g;
13245
+ var VARIABLE = /^[A-Z0-9_]+$/;
13246
+ var SKILL_FILE = /skills[\\/]([\w.-]{1,100})[\\/]SKILL\.md(?![\w.-])/g;
13247
+ var READERS = new Set(["cat", "head", "tail", "nl", "type", "get-content", "gc"]);
13248
+ var slashes = (p) => p.replaceAll("\\", "/");
13249
+ var NOT_PLAIN = /[;|&<>\n`]|\$\(/;
13250
+ var starts = (part) => (slashes(part.trim().split(/\s+/)[0] ?? "").split("/").pop() ?? "").toLowerCase().replace(/\.exe$/, "");
13251
+ function codexReviewCall(input, thread, own = []) {
13252
+ if (input.agent_id)
13253
+ return null;
13254
+ const named = names(process.env.SPHICA_REVIEW_COMMANDS);
13255
+ if (input.hook_event_name === "UserPromptSubmit") {
13256
+ if (childThread(input, thread) !== null)
13257
+ return thread?.subagent === "review" ? { name: "review", args: "" } : null;
13258
+ const prompt = typeof input.prompt === "string" ? input.prompt : "";
13259
+ for (const m of prompt.matchAll(NAMED_SKILL)) {
13260
+ const name = (m[1] ?? "").replace(/[.:/-]+$/, "");
13261
+ if (NAME.test(name) && !VARIABLE.test(name) && isReview(name, named))
13262
+ return { name, args: prompt.slice(0, 1000) };
13263
+ }
13264
+ return null;
13265
+ }
13266
+ if (input.hook_event_name !== "PreToolUse" || input.tool_name !== "Bash")
13267
+ return null;
13268
+ const command = input.tool_input?.command;
13269
+ if (typeof command !== "string")
13270
+ return null;
13271
+ const line = command.trim();
13272
+ if (NOT_PLAIN.test(line) || !READERS.has(starts(line)))
13273
+ return null;
13274
+ const mine = own.map(slashes);
13275
+ for (const m of line.matchAll(SKILL_FILE)) {
13276
+ const upTo = slashes(line.slice(0, m.index + m[0].length));
13277
+ if (mine.some((file) => upTo.endsWith(file)))
13278
+ continue;
13279
+ if (isReview(m[1] ?? "", named))
13280
+ return { name: m[1] ?? "", args: "" };
13281
+ }
13282
+ return null;
13283
+ }
13167
13284
  function unreadText(why) {
13168
13285
  if (why.unread === "refused")
13169
13286
  return `Sphica's git worker would not start, because ${refusalText(why.code)} (run sphica doctor in this work tree)`;
@@ -13171,26 +13288,31 @@ function unreadText(why) {
13171
13288
  return "the change could not be read (git failed or could not be started)";
13172
13289
  return "the change could not be read in time, or is too large to read (over 4 MB of diff or file names)";
13173
13290
  }
13174
- async function localChange(root, args) {
13291
+ async function localChange(root, args, until = Date.now() + DIFF_DEADLINE) {
13175
13292
  if (/^\s*#?\d+\s*$|(^|\s)#\d+\b|\/pull\/\d+/.test(args))
13176
13293
  return { problem: "it names a pull request, and Sphica sees only the local change" };
13177
- const until = Date.now() + DIFF_DEADLINE;
13178
13294
  const left = () => Math.max(1, until - Date.now());
13179
13295
  let base = "";
13296
+ let late = false;
13180
13297
  for (const which of ["origin/HEAD", "upstream"]) {
13181
13298
  try {
13182
13299
  base = baseRef(root, which, { timeout: left() });
13183
13300
  if (base)
13184
13301
  break;
13185
- } catch {}
13302
+ } catch (e) {
13303
+ late ||= unreadOf(e).unread === "timeout";
13304
+ }
13186
13305
  }
13187
13306
  if (!base)
13188
- return { problem: "there is no default branch (origin/HEAD) or upstream to compare with" };
13307
+ return {
13308
+ problem: late ? unreadText({ unread: "timeout" }) : "there is no default branch (origin/HEAD) or upstream to compare with"
13309
+ };
13189
13310
  let from;
13190
13311
  try {
13191
13312
  from = mergeBase(root, "HEAD", base, { timeout: left() });
13192
- } catch {
13193
- return { problem: `HEAD shares no history with ${base}` };
13313
+ } catch (e) {
13314
+ const why = unreadOf(e);
13315
+ return { problem: why.unread === "timeout" ? unreadText(why) : `HEAD shares no history with ${base}` };
13194
13316
  }
13195
13317
  const got = await worktreeDiff(root, from, { max: MAX_DIFF, deadline: left() });
13196
13318
  if ("unread" in got)
@@ -13201,36 +13323,46 @@ async function localChange(root, args) {
13201
13323
  } catch (e) {
13202
13324
  return { problem: unreadText(unreadOf(e)) };
13203
13325
  }
13204
- const { patch: diff, names } = got;
13326
+ const { patch: diff, names: names2 } = got;
13205
13327
  const files = parseDiff(diff);
13206
- for (const name of names)
13328
+ for (const name of names2)
13207
13329
  if (!files.some((f) => f.path === name))
13208
13330
  files.push({ path: name, added: [], lines: [] });
13209
13331
  if (files.length + untracked.length > MAX_FILES)
13210
13332
  return { problem: `the change has more than ${MAX_FILES} files` };
13211
- const read = [from, diff];
13212
- for (const rel of untracked) {
13213
- let text2 = "";
13333
+ const more = untrackedFiles(root, untracked, until);
13334
+ if (!more)
13335
+ return { problem: unreadText({ unread: "timeout" }) };
13336
+ files.push(...more.files);
13337
+ return { base, files, digest: sha256([from, diff, ...more.read].join("\x00")).toString("hex") };
13338
+ }
13339
+ function untrackedFiles(root, rels, until) {
13340
+ const files = [];
13341
+ const read = [];
13342
+ for (const rel of rels) {
13343
+ if (Date.now() >= until)
13344
+ return null;
13345
+ let text3 = "";
13214
13346
  try {
13215
- const file = path8.join(root, rel);
13216
- const st = fs7.lstatSync(file);
13347
+ const file = path10.join(root, rel);
13348
+ const st = fs9.lstatSync(file);
13217
13349
  if (st.isFile() && st.size <= MAX_UNTRACKED_BYTES)
13218
- text2 = fs7.readFileSync(file, "utf8");
13350
+ text3 = fs9.readFileSync(file, "utf8");
13219
13351
  } catch {}
13220
- const added = text2 ? text2.split(/\r?\n/) : [];
13352
+ const added = text3 ? text3.split(/\r?\n/) : [];
13221
13353
  files.push({ path: rel, added, lines: added.map((_, i) => i + 1) });
13222
- read.push(rel, text2);
13354
+ read.push(rel, text3);
13223
13355
  }
13224
- return { base, files, digest: sha256(read.join("\x00")).toString("hex") };
13356
+ return { files, read };
13225
13357
  }
13226
13358
 
13227
13359
  // server/src/shell-state.ts
13228
13360
  import { createHash } from "node:crypto";
13229
- import fs8 from "node:fs";
13230
- import path9 from "node:path";
13361
+ import fs10 from "node:fs";
13362
+ import path11 from "node:path";
13231
13363
  var READS = 3;
13232
13364
  var SNAPSHOT_LIFE_MS = 7 * 24 * 60 * 60 * 1000;
13233
- var dir = (...parts) => path9.join(sphicaHome(), "shell-state", ...parts);
13365
+ var dir = (...parts) => path11.join(sphicaHome(), "shell-state", ...parts);
13234
13366
  var sha = (s) => createHash("sha256").update(s).digest("hex");
13235
13367
  var signature = (st) => ({
13236
13368
  dev: String(st.dev),
@@ -13241,24 +13373,24 @@ var signature = (st) => ({
13241
13373
  });
13242
13374
  var same = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
13243
13375
  function inside(root, rel) {
13244
- const real = fs8.realpathSync.native(root);
13245
- const file = path9.resolve(root, rel);
13246
- if (leaves2(path9.relative(root, file)))
13376
+ const real = fs10.realpathSync.native(root);
13377
+ const file = path11.resolve(root, rel);
13378
+ if (leaves2(path11.relative(root, file)))
13247
13379
  return null;
13248
13380
  let probe = file;
13249
- while (!fs8.existsSync(probe)) {
13250
- const up = path9.dirname(probe);
13381
+ while (!fs10.existsSync(probe)) {
13382
+ const up = path11.dirname(probe);
13251
13383
  if (up === probe)
13252
13384
  return null;
13253
13385
  probe = up;
13254
13386
  }
13255
- return leaves2(path9.relative(real, fs8.realpathSync.native(probe))) ? null : file;
13387
+ return leaves2(path11.relative(real, fs10.realpathSync.native(probe))) ? null : file;
13256
13388
  }
13257
- var leaves2 = (rel) => rel === ".." || rel.startsWith(`..${path9.sep}`) || path9.isAbsolute(rel);
13258
- var cacheFile = (root) => dir("cache", `${sha(fs8.realpathSync.native(root))}.json`);
13389
+ var leaves2 = (rel) => rel === ".." || rel.startsWith(`..${path11.sep}`) || path11.isAbsolute(rel);
13390
+ var cacheFile = (root) => dir("cache", `${sha(fs10.realpathSync.native(root))}.json`);
13259
13391
  function loadCache(root) {
13260
13392
  try {
13261
- const raw = JSON.parse(fs8.readFileSync(cacheFile(root), "utf8"));
13393
+ const raw = JSON.parse(fs10.readFileSync(cacheFile(root), "utf8"));
13262
13394
  const out = new Map;
13263
13395
  if (raw && typeof raw === "object" && !Array.isArray(raw))
13264
13396
  for (const [k, v] of Object.entries(raw)) {
@@ -13272,11 +13404,11 @@ function loadCache(root) {
13272
13404
  }
13273
13405
  }
13274
13406
  var validSig = (s) => !!s && typeof s === "object" && ["dev", "ino", "size"].every((k) => /^\d+$/.test(String(s[k]))) && ["mtimeNs", "ctimeNs"].every((k) => /^-?\d+$/.test(String(s[k])));
13275
- function publish(file, text2) {
13276
- fs8.mkdirSync(path9.dirname(file), { recursive: true });
13407
+ function publish(file, text3) {
13408
+ fs10.mkdirSync(path11.dirname(file), { recursive: true });
13277
13409
  const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
13278
- fs8.writeFileSync(tmp, text2);
13279
- fs8.renameSync(tmp, file);
13410
+ fs10.writeFileSync(tmp, text3);
13411
+ fs10.renameSync(tmp, file);
13280
13412
  }
13281
13413
  function saveCache(root, cache, watched) {
13282
13414
  try {
@@ -13290,7 +13422,7 @@ function saveCache(root, cache, watched) {
13290
13422
  function readHash(fd, deadline) {
13291
13423
  const h = createHash("sha256");
13292
13424
  const buf = Buffer.allocUnsafe(1 << 20);
13293
- for (let n = fs8.readSync(fd, buf, 0, buf.length, null);n > 0; n = fs8.readSync(fd, buf, 0, buf.length, null)) {
13425
+ for (let n = fs10.readSync(fd, buf, 0, buf.length, null);n > 0; n = fs10.readSync(fd, buf, 0, buf.length, null)) {
13294
13426
  h.update(buf.subarray(0, n));
13295
13427
  if (Date.now() >= deadline)
13296
13428
  return "deadline";
@@ -13302,21 +13434,21 @@ var failed = (e) => {
13302
13434
  return code === "ENOENT" || code === "ENOTDIR" ? { kind: "missing" } : { kind: "unreadable", reason: String(code) };
13303
13435
  };
13304
13436
  function readOpened(root, file, fd, sig, deadline) {
13305
- const opened = fs8.fstatSync(fd, { bigint: true });
13437
+ const opened = fs10.fstatSync(fd, { bigint: true });
13306
13438
  if (!same(sig, signature(opened)))
13307
13439
  return "again";
13308
- const real = fs8.realpathSync.native(file);
13309
- if (leaves2(path9.relative(fs8.realpathSync.native(root), real)))
13440
+ const real = fs10.realpathSync.native(file);
13441
+ if (leaves2(path11.relative(fs10.realpathSync.native(root), real)))
13310
13442
  return { kind: "unreadable", reason: "outside the checkout" };
13311
- const there = fs8.lstatSync(real, { bigint: true });
13443
+ const there = fs10.lstatSync(real, { bigint: true });
13312
13444
  if (there.dev !== opened.dev || there.ino !== opened.ino)
13313
13445
  return "again";
13314
13446
  const hash = readHash(fd, deadline);
13315
13447
  if (hash === "deadline")
13316
13448
  return { kind: "unknown", reason: "deadline" };
13317
- if (!same(sig, signature(fs8.fstatSync(fd, { bigint: true }))))
13449
+ if (!same(sig, signature(fs10.fstatSync(fd, { bigint: true }))))
13318
13450
  return "again";
13319
- if (!same(sig, signature(fs8.lstatSync(file, { bigint: true }))))
13451
+ if (!same(sig, signature(fs10.lstatSync(file, { bigint: true }))))
13320
13452
  return "again";
13321
13453
  return { kind: "ok", sig, hash };
13322
13454
  }
@@ -13330,12 +13462,12 @@ function stateOf(root, rel, cache, deadline) {
13330
13462
  file = inside(root, rel);
13331
13463
  if (!file)
13332
13464
  return { kind: "unreadable", reason: "outside the checkout" };
13333
- before = fs8.lstatSync(file, { bigint: true });
13465
+ before = fs10.lstatSync(file, { bigint: true });
13334
13466
  if (before.isSymbolicLink()) {
13335
- file = fs8.realpathSync.native(file);
13336
- if (leaves2(path9.relative(fs8.realpathSync.native(root), file)))
13467
+ file = fs10.realpathSync.native(file);
13468
+ if (leaves2(path11.relative(fs10.realpathSync.native(root), file)))
13337
13469
  return { kind: "unreadable", reason: "outside the checkout" };
13338
- before = fs8.lstatSync(file, { bigint: true });
13470
+ before = fs10.lstatSync(file, { bigint: true });
13339
13471
  }
13340
13472
  } catch (e) {
13341
13473
  return failed(e);
@@ -13348,7 +13480,7 @@ function stateOf(root, rel, cache, deadline) {
13348
13480
  return { kind: "ok", sig, hash: cached.hash };
13349
13481
  let fd;
13350
13482
  try {
13351
- fd = fs8.openSync(file, "r");
13483
+ fd = fs10.openSync(file, "r");
13352
13484
  } catch (e) {
13353
13485
  if (e.code === "ENOENT")
13354
13486
  continue;
@@ -13360,7 +13492,7 @@ function stateOf(root, rel, cache, deadline) {
13360
13492
  } catch (e) {
13361
13493
  outcome = e.code === "ENOENT" ? "again" : failed(e);
13362
13494
  } finally {
13363
- fs8.closeSync(fd);
13495
+ fs10.closeSync(fd);
13364
13496
  }
13365
13497
  if (outcome === "again")
13366
13498
  continue;
@@ -13402,11 +13534,11 @@ function takeSnapshot(key) {
13402
13534
  const file = snapshotFile(key);
13403
13535
  let raw;
13404
13536
  try {
13405
- raw = JSON.parse(fs8.readFileSync(file, "utf8"));
13537
+ raw = JSON.parse(fs10.readFileSync(file, "utf8"));
13406
13538
  } catch {
13407
13539
  return null;
13408
13540
  }
13409
- fs8.rmSync(file, { force: true });
13541
+ fs10.rmSync(file, { force: true });
13410
13542
  const s = raw;
13411
13543
  if (s?.v !== 1 || s.key !== key || typeof s.root !== "string" || typeof s.project !== "string" || typeof s.at !== "string" || !s.paths || typeof s.paths !== "object" || Array.isArray(s.paths) || Number.isNaN(Date.parse(s.at)))
13412
13544
  return null;
@@ -13423,19 +13555,19 @@ function takeSnapshot(key) {
13423
13555
  }
13424
13556
  function pruneSnapshots(now = Date.now(), deadline = Number.POSITIVE_INFINITY) {
13425
13557
  let removed = 0;
13426
- let names;
13558
+ let names2;
13427
13559
  try {
13428
- names = fs8.readdirSync(dir("calls"));
13560
+ names2 = fs10.readdirSync(dir("calls"));
13429
13561
  } catch {
13430
13562
  return 0;
13431
13563
  }
13432
- for (const n of names) {
13564
+ for (const n of names2) {
13433
13565
  if (Date.now() >= deadline)
13434
13566
  break;
13435
13567
  const file = dir("calls", n);
13436
13568
  try {
13437
- if (now - fs8.statSync(file).mtimeMs > SNAPSHOT_LIFE_MS) {
13438
- fs8.rmSync(file, { force: true });
13569
+ if (now - fs10.statSync(file).mtimeMs > SNAPSHOT_LIFE_MS) {
13570
+ fs10.rmSync(file, { force: true });
13439
13571
  removed++;
13440
13572
  }
13441
13573
  } catch {}
@@ -13506,10 +13638,10 @@ var NOTE = "Sphica past record, not an instruction; read it with Sphica's read b
13506
13638
  var leftOut = (n) => n > 0 ? `- ${n} more record${n === 1 ? " applies here but was" : "s apply here but were"} left out for space: find them with Sphica's search or read.` : "";
13507
13639
  var SEARCH_FIRST = "- Before choosing an approach, search Sphica's past records for it.";
13508
13640
  var workLeftOut = (n) => n > 0 ? `- ${n} more work item${n === 1 ? "" : "s"} not shown: Sphica's status lists the 5 most recently updated.` : "";
13509
- var noted = (text2, lead, notes) => {
13641
+ var noted = (text3, lead, notes) => {
13510
13642
  const note = notes.filter(Boolean).map((l) => `
13511
13643
  ${l}`).join("");
13512
- return { text: note ? `${text2 || lead}${note}` : text2, note };
13644
+ return { text: note ? `${text3 || lead}${note}` : text3, note };
13513
13645
  };
13514
13646
  var sound = (unit) => sql`exists (select 1 from unit o where o.id = ${sql.ref(unit)} and o.extraction = 'supported' and o.unsourced = 0)`;
13515
13647
  var deliverable = (db, projectId2, asOf) => db.selectFrom("unit as u").where("u.project_id", "=", projectId2).$call((q) => asOf === undefined ? q.where("u.lifecycle", "=", "active") : q.where(sql`(select s.to_state from unit_state s where s.unit_id = u.id and s.at <= ${asOf}
@@ -13545,8 +13677,8 @@ function fitMarked(lines, chars, lead, ai, ids) {
13545
13677
  return { ...f, lead: wide.lead };
13546
13678
  return { ...f, text: f.text && `${lead}${f.text.slice(wide.lead.length)}`, lead };
13547
13679
  }
13548
- var clip = (text2, n) => {
13549
- const chars = Array.from(inline(text2));
13680
+ var clip = (text3, n) => {
13681
+ const chars = Array.from(inline(text3));
13550
13682
  return chars.length <= n ? chars.join("") : `${chars.slice(0, n - 1).join("")}…`;
13551
13683
  };
13552
13684
  async function reasons(db, ids) {
@@ -13707,15 +13839,15 @@ async function namedInCommand(db, projectId2, root, cwd, command) {
13707
13839
  const edge = `\\s'"=(){}<>|;&,`;
13708
13840
  const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13709
13841
  const forms = (p) => {
13710
- const abs = path10.join(root, p);
13711
- const fromCwd = path10.relative(cwd, abs);
13842
+ const abs = path12.join(root, p);
13843
+ const fromCwd = path12.relative(cwd, abs);
13712
13844
  const out = new Set;
13713
13845
  for (const f of [p, abs, leaves(fromCwd) ? "" : fromCwd])
13714
13846
  if (f)
13715
13847
  for (const sep of ["/", "\\"]) {
13716
13848
  const t = f.split(/[\\/]/).join(sep);
13717
13849
  out.add(t);
13718
- if (!path10.isAbsolute(f))
13850
+ if (!path12.isAbsolute(f))
13719
13851
  out.add(`.${sep}${t}`);
13720
13852
  }
13721
13853
  return [...out];
@@ -13724,7 +13856,7 @@ async function namedInCommand(db, projectId2, root, cwd, command) {
13724
13856
  }
13725
13857
  function pathNamed(prompt, root, rel) {
13726
13858
  const steps = (p) => p.split(/[\\/]/).map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]");
13727
- return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(path10.join(root, rel))})(?![A-Za-z0-9_$\\-/\\\\]|\\.[A-Za-z0-9_$])`).test(prompt);
13859
+ return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(path12.join(root, rel))})(?![A-Za-z0-9_$\\-/\\\\]|\\.[A-Za-z0-9_$])`).test(prompt);
13728
13860
  }
13729
13861
  function once(f) {
13730
13862
  const seen = new Map;
@@ -13735,10 +13867,10 @@ function once(f) {
13735
13867
  };
13736
13868
  }
13737
13869
  async function namedRecords(db, projectId2, root, prompt, asOf) {
13738
- const text2 = prompt.normalize("NFKC");
13739
- const lower = text2.toLowerCase();
13870
+ const text3 = prompt.normalize("NFKC");
13871
+ const lower = text3.toLowerCase();
13740
13872
  const word = (w, s) => s.includes(w) && new RegExp(`(?<![\\p{L}\\p{N}_$])${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}_$])`, "u").test(s);
13741
- const named2 = once((symbol) => symbol.length >= 3 && (/[^a-z]/.test(symbol) ? word(symbol, text2) : text2.includes(`${symbol}(`) || text2.includes(`\`${symbol}\``)));
13873
+ const named2 = once((symbol) => symbol.length >= 3 && (/[^a-z]/.test(symbol) ? word(symbol, text3) : text3.includes(`${symbol}(`) || text3.includes(`\`${symbol}\``)));
13742
13874
  const slashed = prompt.replaceAll("\\", "/");
13743
13875
  const pathIn = once((rel) => slashed.includes(rel) && pathNamed(prompt, root, rel));
13744
13876
  const optionIn = once((option) => option.length >= 3 && word(option.normalize("NFKC").toLowerCase(), lower));
@@ -13788,6 +13920,7 @@ async function onPrompt(db, projectId2, root, prompt) {
13788
13920
  }
13789
13921
  var SHELL_WRITE = "shell_write";
13790
13922
  var SNAPSHOT_MS = 3500;
13923
+ var REVIEW_MS = 3500;
13791
13924
  var SHELL_WRITE_ON = new Set(["on", "1", "true", "yes"]);
13792
13925
  var TRIAL_CAP = 10 * 1024 * 1024;
13793
13926
  function shellWriteDelivery() {
@@ -13800,58 +13933,41 @@ function shellWriteDelivery() {
13800
13933
  }
13801
13934
  function trialLog(line2) {
13802
13935
  try {
13803
- const file = path10.join(sphicaHome(), "shell-state", "trial.jsonl");
13804
- fs9.mkdirSync(path10.dirname(file), { recursive: true });
13805
- if ((fs9.statSync(file, { throwIfNoEntry: false })?.size ?? 0) >= TRIAL_CAP)
13806
- rotateTrial(path10.dirname(file), file);
13807
- fs9.appendFileSync(file, `${JSON.stringify({ at: iso(Date.now()), ...line2 })}
13936
+ const file = path12.join(sphicaHome(), "shell-state", "trial.jsonl");
13937
+ fs11.mkdirSync(path12.dirname(file), { recursive: true });
13938
+ if ((fs11.statSync(file, { throwIfNoEntry: false })?.size ?? 0) >= TRIAL_CAP)
13939
+ rotateTrial(path12.dirname(file), file);
13940
+ fs11.appendFileSync(file, `${JSON.stringify({ at: iso(Date.now()), ...line2 })}
13808
13941
  `);
13809
13942
  } catch {}
13810
13943
  }
13811
13944
  function rotateTrial(dir2, file) {
13812
13945
  try {
13813
- fs9.renameSync(file, path10.join(dir2, `trial.${Date.now()}.${process.pid}.jsonl`));
13814
- const archives = fs9.readdirSync(dir2).filter((n) => /^trial\.\d+\.\d+\.jsonl$/.test(n)).sort((a, b) => Number(b.split(".")[1]) - Number(a.split(".")[1]));
13946
+ fs11.renameSync(file, path12.join(dir2, `trial.${Date.now()}.${process.pid}.jsonl`));
13947
+ const archives = fs11.readdirSync(dir2).filter((n) => /^trial\.\d+\.\d+\.jsonl$/.test(n)).sort((a, b) => Number(b.split(".")[1]) - Number(a.split(".")[1]));
13815
13948
  let kept = 0;
13816
13949
  for (const n of archives) {
13817
- kept += fs9.statSync(path10.join(dir2, n), { throwIfNoEntry: false })?.size ?? 0;
13950
+ kept += fs11.statSync(path12.join(dir2, n), { throwIfNoEntry: false })?.size ?? 0;
13818
13951
  if (kept > 2 * TRIAL_CAP)
13819
- fs9.rmSync(path10.join(dir2, n), { force: true });
13952
+ fs11.rmSync(path12.join(dir2, n), { force: true });
13820
13953
  }
13821
13954
  } catch {}
13822
13955
  }
13823
13956
  var AUTO_TRACE_OFF = new Set(["off", "0", "false", "no"]);
13824
13957
  var AUTO_TRACE = (n, skill) => `- ${n} earlier session${n === 1 ? "" : "s"} of this project ${n === 1 ? "waits" : "wait"} to be traced. After the user's request is done, ${skill ? `read \`${skill}\` and run it` : "run the trace Skill"} on your own for the oldest (at most 2), as its "On your own" section says, without asking the user.`;
13825
- var SESSION_META_BYTES = 256 * 1024;
13826
13958
  function codexInteractive(input) {
13827
- const file = input.transcript_path;
13828
- if (!input.session_id || typeof file !== "string" || !path10.isAbsolute(file))
13829
- return false;
13830
- let fd;
13831
- try {
13832
- if (!fs9.lstatSync(file).isFile())
13833
- return false;
13834
- fd = fs9.openSync(file, "r");
13835
- const buffer = Buffer.alloc(SESSION_META_BYTES);
13836
- const read = fs9.readSync(fd, buffer, 0, SESSION_META_BYTES, 0);
13837
- const end = buffer.subarray(0, read).indexOf(10);
13838
- if (end < 0)
13839
- return false;
13840
- const line2 = JSON.parse(buffer.subarray(0, end).toString("utf8"));
13841
- const payload = line2?.payload;
13842
- return line2?.type === "session_meta" && payload?.id === input.session_id && payload.originator === "codex-tui" && payload.thread_source === "user";
13843
- } catch {
13844
- return false;
13845
- } finally {
13846
- if (fd !== undefined)
13847
- fs9.closeSync(fd);
13848
- }
13959
+ const thread = codexThread(input);
13960
+ return ownThread(input, thread) && thread?.originator === "codex-tui";
13849
13961
  }
13850
13962
  var namable = (file) => Buffer.byteLength(file) <= 1000 && !/[\p{Cc}`]/u.test(file) ? file : null;
13851
- function traceSkill(here2 = path10.dirname(fileURLToPath2(import.meta.url))) {
13852
- const file = [path10.join(here2, ".."), path10.join(here2, "..", "..", "plugin")].map((root) => path10.join(root, "skills", "trace", "SKILL.md")).find((f) => fs9.existsSync(f));
13963
+ var skillFile = (skill, here2) => [path12.join(here2, ".."), path12.join(here2, "..", "..", "plugin")].map((root) => path12.join(root, "skills", skill, "SKILL.md")).find((f) => fs11.existsSync(f));
13964
+ function traceSkill(here2 = path12.dirname(fileURLToPath2(import.meta.url))) {
13965
+ const file = skillFile("trace", here2);
13853
13966
  return file ? namable(file) : null;
13854
13967
  }
13968
+ var ownReview = () => [
13969
+ ...new Set([path12.dirname(fileURLToPath2(import.meta.url)), path12.dirname(path12.resolve(process.argv[1] ?? ""))].flatMap((here2) => skillFile("review", here2) ?? []))
13970
+ ];
13855
13971
  async function waiting(db, projectId2, place) {
13856
13972
  if (!place.owner)
13857
13973
  return "";
@@ -13862,7 +13978,7 @@ async function waiting(db, projectId2, place) {
13862
13978
  });
13863
13979
  if (!total)
13864
13980
  return "";
13865
- if (!markOnce("auto-trace", `${path10.resolve(place.file)}\x00${place.key}\x00${place.host}\x00${place.auto}`))
13981
+ if (!markOnce("auto-trace", `${path12.resolve(place.file)}\x00${place.key}\x00${place.host}\x00${place.auto}`))
13866
13982
  return "";
13867
13983
  return AUTO_TRACE(total, place.skill);
13868
13984
  }
@@ -13870,7 +13986,7 @@ async function waiting(db, projectId2, place) {
13870
13986
  if (!n)
13871
13987
  return "";
13872
13988
  const day = new Date().toLocaleDateString("sv-SE");
13873
- if (!markOnce("pending", `${path10.resolve(place.file)}\x00${place.key}\x00${day}`))
13989
+ if (!markOnce("pending", `${path12.resolve(place.file)}\x00${place.key}\x00${day}`))
13874
13990
  return "";
13875
13991
  const trace = place.host === "codex" ? "$sphica:trace" : "/sphica:trace";
13876
13992
  return `- ${n} session${n === 1 ? "" : "s"} waiting to be traced: run ${trace} pending.`;
@@ -13910,10 +14026,10 @@ async function atStart(db, projectId2, branch, place) {
13910
14026
  reason: null
13911
14027
  };
13912
14028
  }
13913
- async function beforeReview(db, projectId2, root, call) {
13914
- const change = await localChange(root, call.args);
13915
- const said = (text2, why) => ({
13916
- text: text2,
14029
+ async function beforeReview(db, projectId2, root, call, until) {
14030
+ const change = await localChange(root, call.args, until);
14031
+ const said = (text3, why) => ({
14032
+ text: text3,
13917
14033
  note: "",
13918
14034
  units: [],
13919
14035
  eligible: 0,
@@ -13950,23 +14066,6 @@ async function beforeReview(db, projectId2, root, call) {
13950
14066
  function toldBefore(session, key) {
13951
14067
  return !markOnce("review", `${session}\x00${key}`);
13952
14068
  }
13953
- function markOnce(kind, key) {
13954
- const user = (() => {
13955
- try {
13956
- return os3.userInfo().username;
13957
- } catch {
13958
- return String(process.getuid?.() ?? "user");
13959
- }
13960
- })();
13961
- const dir2 = path10.join(os3.tmpdir(), `sphica-${sha256(user).toString("hex").slice(0, 12)}`, kind);
13962
- try {
13963
- fs9.mkdirSync(dir2, { recursive: true, mode: 448 });
13964
- fs9.writeFileSync(path10.join(dir2, sha256(key).toString("hex").slice(0, 24)), "", { flag: "wx" });
13965
- return true;
13966
- } catch (e) {
13967
- return e.code !== "EEXIST";
13968
- }
13969
- }
13970
14069
  function onceUnavailable(session) {
13971
14070
  return markOnce("unavailable", session);
13972
14071
  }
@@ -14029,7 +14128,7 @@ async function lockedPlan(file, e, make, keep, logged = () => {}) {
14029
14128
  logged(wrote);
14030
14129
  return plan ?? make();
14031
14130
  }
14032
- async function snapshotCall(db, projectId2, place, host, input, started) {
14131
+ async function snapshotCall(db, projectId2, place, host, input, who, started) {
14033
14132
  const paths = await deliverablePaths(db, projectId2);
14034
14133
  const cache = loadCache(place.root);
14035
14134
  const states = takeStates(place.root, paths, cache, started + SNAPSHOT_MS);
@@ -14037,13 +14136,12 @@ async function snapshotCall(db, projectId2, place, host, input, started) {
14037
14136
  const expired = pruneSnapshots(Date.now(), started + SNAPSHOT_MS);
14038
14137
  if (expired)
14039
14138
  trialLog({ host, event: "snapshot_expired", count: expired });
14040
- const key = snapshotKey(host, String(input.session_id), agentOf(input), String(input.tool_use_id));
14139
+ const key = snapshotKey(host, String(input.session_id), who, String(input.tool_use_id));
14041
14140
  writeSnapshot({ v: 1, key, at: iso(started), root: place.root, project: place.key, paths: states });
14042
14141
  }
14043
- async function afterShell(input, host, file, started) {
14142
+ async function afterShell(input, host, agent, file, started) {
14044
14143
  if (!shellWriteDelivery() || !input.session_id || !input.tool_use_id)
14045
14144
  return "";
14046
- const agent = agentOf(input);
14047
14145
  const base = { host, session: input.session_id, agent, call: input.tool_use_id };
14048
14146
  let line2 = { ...base, event: "post_shell" };
14049
14147
  let db = null;
@@ -14067,7 +14165,7 @@ async function afterShell(input, host, file, started) {
14067
14165
  trialLog({ ...line2, delivered: [] });
14068
14166
  return "";
14069
14167
  }
14070
- if (!fs9.existsSync(file))
14168
+ if (!fs11.existsSync(file))
14071
14169
  throw new Error(`no database at ${file}`);
14072
14170
  db = openReader(file);
14073
14171
  const pid = await projectId(db, before.project);
@@ -14096,13 +14194,29 @@ async function afterShell(input, host, file, started) {
14096
14194
  await db?.destroy().catch(() => {});
14097
14195
  }
14098
14196
  }
14099
- async function deliver(input, host = "claude-code", file = dbFile()) {
14100
- const started = Date.now();
14197
+ async function deliver(input, host = "claude-code", file = dbFile(), started = Date.now()) {
14198
+ const thread = host === "codex" && !agentOf(input) ? codexThread(input) : null;
14199
+ const who = agentOf(input) ?? childThread(input, thread);
14200
+ if (host !== "codex")
14201
+ return deliverOne(input, host, file, started, who, reviewCall(input));
14202
+ const call = codexReviewCall(input, thread, input.hook_event_name === "PreToolUse" ? ownReview() : []);
14203
+ if (!call)
14204
+ return deliverOne(input, host, file, started, who, null);
14205
+ const place = identify(input.cwd ?? process.cwd());
14206
+ const rest = await deliverOne(input, host, file, started, who, null, { place });
14207
+ const review = await deliverOne(input, host, file, started, who, call, {
14208
+ place,
14209
+ reviewUntil: started + REVIEW_MS
14210
+ });
14211
+ return [review, rest].filter(Boolean).join(`
14212
+
14213
+ `);
14214
+ }
14215
+ async function deliverOne(input, host, file, started, who, call, known = {}) {
14101
14216
  const name = input.hook_event_name;
14102
14217
  if ((name === "PostToolUse" || name === "PostToolUseFailure") && SHELL_TOOLS.has(input.tool_name ?? ""))
14103
- return afterShell(input, host, file, started);
14104
- const snap = name === "PreToolUse" && SHELL_TOOLS.has(input.tool_name ?? "") && Boolean(input.tool_use_id) && shellWriteDelivery();
14105
- const call = reviewCall(input);
14218
+ return afterShell(input, host, who, file, started);
14219
+ const snap = !call && name === "PreToolUse" && SHELL_TOOLS.has(input.tool_name ?? "") && Boolean(input.tool_use_id) && shellWriteDelivery();
14106
14220
  const event = call ? "review" : name === "SessionStart" || name === "SubagentStart" ? "session_start" : name === "UserPromptSubmit" ? "prompt" : name === "PreToolUse" ? input.tool_name === "Read" || SHELL_TOOLS.has(input.tool_name ?? "") && !(host === "codex" && shellPatch(input)) ? "pre_read" : "pre_edit" : null;
14107
14221
  if (!event || !input.session_id)
14108
14222
  return "";
@@ -14112,30 +14226,30 @@ async function deliver(input, host = "claude-code", file = dbFile()) {
14112
14226
  return "";
14113
14227
  const ti = input.tool_input ?? {};
14114
14228
  const patch = host === "codex" && input.tool_name === "apply_patch" && typeof ti.command === "string" ? ti.command : host === "codex" ? shellPatch(input) : null;
14115
- const shell = SHELL_TOOLS.has(input.tool_name ?? "") && !patch && typeof ti.command === "string" ? ti.command : null;
14229
+ const shell = !call && SHELL_TOOLS.has(input.tool_name ?? "") && !patch && typeof ti.command === "string" ? ti.command : null;
14116
14230
  const targets = patch ? patchPaths2(patch) : [ti.file_path, ti.notebook_path].filter((p) => typeof p === "string").slice(0, 1);
14117
14231
  const onPath = event === "pre_edit" || event === "pre_read";
14118
14232
  if (onPath && !shell && !snap && (!(event === "pre_read" || patch || EDIT_TOOLS.has(input.tool_name ?? "")) || !targets.length))
14119
14233
  return "";
14120
- const place = identify(input.cwd ?? process.cwd());
14234
+ const place = known.place !== undefined ? known.place : identify(input.cwd ?? process.cwd());
14121
14235
  if (!place)
14122
14236
  return "";
14123
- let rels = targets.map((t) => path10.relative(place.root, path10.resolve(input.cwd ?? place.root, t))).filter((r) => r && !leaves(r)).map((r) => r.split(path10.sep).join("/"));
14237
+ let rels = targets.map((t) => path12.relative(place.root, path12.resolve(input.cwd ?? place.root, t))).filter((r) => r && !leaves(r)).map((r) => r.split(path12.sep).join("/"));
14124
14238
  if (onPath && !shell && !snap && !rels.length)
14125
14239
  return "";
14126
14240
  let db = null;
14127
14241
  try {
14128
- if (!fs9.existsSync(file))
14242
+ if (!fs11.existsSync(file))
14129
14243
  throw new Error(`no database at ${file}`);
14130
14244
  db = openReader(file);
14131
14245
  const pid = await projectId(db, place.key);
14132
14246
  if (pid === null)
14133
14247
  return "";
14134
14248
  if (snap)
14135
- await snapshotCall(db, pid, place, host, input, started).catch((e) => trialLog({
14249
+ await snapshotCall(db, pid, place, host, input, who, started).catch((e) => trialLog({
14136
14250
  host,
14137
14251
  session: input.session_id,
14138
- agent: agentOf(input),
14252
+ agent: who,
14139
14253
  call: input.tool_use_id,
14140
14254
  event: "snapshot_failed",
14141
14255
  error: head(reason(e), 200)
@@ -14157,7 +14271,7 @@ async function deliver(input, host = "claude-code", file = dbFile()) {
14157
14271
  const asksToTrace = name === "SessionStart" && input.source === "startup" && ![process.env.CLAUDE_PLUGIN_OPTION_AUTO_TRACE, process.env.SPHICA_AUTO_TRACE].some((v) => AUTO_TRACE_OFF.has((v ?? "").trim().toLowerCase()));
14158
14272
  const skill = asksToTrace && host === "codex" && codexInteractive(input) ? traceSkill() : null;
14159
14273
  const newInteractive = asksToTrace && (host === "claude-code" ? process.env.CLAUDE_CODE_ENTRYPOINT === "cli" : skill !== null);
14160
- const make = async () => event === "pre_edit" ? await beforeEdit(reader, pid, rels) : event === "pre_read" ? await beforeRead(reader, pid, rels, sessionId(pid, host, session), agentOf(input), shell ? "named" : "reading") : event === "prompt" ? await onPrompt(reader, pid, place.root, input.prompt ?? "") : call ? await beforeReview(reader, pid, place.root, call) : {
14274
+ const make = async () => event === "pre_edit" ? await beforeEdit(reader, pid, rels) : event === "pre_read" ? await beforeRead(reader, pid, rels, sessionId(pid, host, session), who, shell ? "named" : "reading") : event === "prompt" ? await onPrompt(reader, pid, place.root, input.prompt ?? "") : call ? await beforeReview(reader, pid, place.root, call, known.reviewUntil) : {
14161
14275
  ...await atStart(reader, pid, branchOf(place.root), {
14162
14276
  file,
14163
14277
  key: place.key,
@@ -14173,7 +14287,7 @@ async function deliver(input, host = "claude-code", file = dbFile()) {
14173
14287
  projectId: pid,
14174
14288
  host,
14175
14289
  external: session,
14176
- agent: agentOf(input),
14290
+ agent: who,
14177
14291
  event,
14178
14292
  branch: branchOf(place.root)
14179
14293
  };
@@ -14181,7 +14295,7 @@ async function deliver(input, host = "claude-code", file = dbFile()) {
14181
14295
  if (event === "pre_read" || event === "session_start")
14182
14296
  return (await lockedPlan(file, entry, make, keep)).text;
14183
14297
  const plan = await make();
14184
- if (call && plan.text && toldBefore(`${host}\x00${input.session_id}`, plan.once ?? plan.text))
14298
+ if (call && plan.text && toldBefore(`${host}\x00${input.session_id}${who === null ? "" : `\x00${who}`}`, plan.once ?? plan.text))
14185
14299
  return "";
14186
14300
  if (keep(plan))
14187
14301
  await log(file, entry, plan).catch(() => {});