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