sphica 0.6.42 → 0.6.43

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 fs7 from "node:fs";
5
- import os2 from "node:os";
6
- import path8 from "node:path";
4
+ import fs8 from "node:fs";
5
+ import os3 from "node:os";
6
+ import path9 from "node:path";
7
7
 
8
8
  // server/src/anchors.ts
9
9
  import path from "node:path";
@@ -11078,9 +11078,9 @@ async function authorityOf(db, ids, asOf) {
11078
11078
  }
11079
11079
 
11080
11080
  // server/src/capture.ts
11081
- import { spawn } from "node:child_process";
11082
- import fs5 from "node:fs";
11083
- import path6 from "node:path";
11081
+ import { spawn as spawn2 } from "node:child_process";
11082
+ import fs6 from "node:fs";
11083
+ import path7 from "node:path";
11084
11084
 
11085
11085
  // server/src/kysely-node-sqlite.ts
11086
11086
  var plain = (row) => {
@@ -11111,14 +11111,14 @@ function adapt(raw) {
11111
11111
  }
11112
11112
 
11113
11113
  // server/src/sqlite.ts
11114
- import fs2 from "node:fs";
11115
- import os from "node:os";
11116
- import path3 from "node:path";
11114
+ import fs3 from "node:fs";
11115
+ import os2 from "node:os";
11116
+ import path4 from "node:path";
11117
11117
  import { constants as C, DatabaseSync } from "node:sqlite";
11118
11118
 
11119
11119
  // server/src/plugin.ts
11120
- import fs from "node:fs";
11121
- import path2 from "node:path";
11120
+ import fs2 from "node:fs";
11121
+ import path3 from "node:path";
11122
11122
  import { fileURLToPath } from "node:url";
11123
11123
 
11124
11124
  // server/node_modules/smol-toml/dist/error.js
@@ -11388,13 +11388,173 @@ var NO_MATCHER = new Set(["UserPromptSubmit", "Stop", "Interrupt"]);
11388
11388
  var CONTEXT = new Set(["PreToolUse", "PostToolUse", "SessionStart", "UserPromptSubmit", "SubagentStart"]);
11389
11389
  var SHORT = new Set(["SessionEnd", "Interrupt"]);
11390
11390
 
11391
+ // server/src/git.ts
11392
+ import { execFileSync, spawn } from "node:child_process";
11393
+ import fs from "node:fs";
11394
+ import os from "node:os";
11395
+ import path2 from "node:path";
11396
+ var gitHome = () => path2.join(os.homedir(), ".sphica", "git");
11397
+ function gitEnv(extra = {}) {
11398
+ const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^GIT_/i.test(k)));
11399
+ return {
11400
+ ...env,
11401
+ GIT_ALLOW_PROTOCOL: "",
11402
+ GIT_NO_LAZY_FETCH: "1",
11403
+ GIT_TERMINAL_PROMPT: "0",
11404
+ GIT_NO_REPLACE_OBJECTS: "1",
11405
+ ...extra
11406
+ };
11407
+ }
11408
+ var gitOptions = (hooks = path2.join(gitHome(), "hooks")) => [
11409
+ "-c",
11410
+ "core.fsmonitor=",
11411
+ "-c",
11412
+ `core.hooksPath=${hooks}`,
11413
+ "-c",
11414
+ "core.quotePath=false",
11415
+ "--no-pager",
11416
+ "--no-optional-locks"
11417
+ ];
11418
+ var DIFF_OPTIONS = [
11419
+ "--no-color",
11420
+ "--no-ext-diff",
11421
+ "--no-textconv",
11422
+ "--ignore-submodules=dirty",
11423
+ "--submodule=short"
11424
+ ];
11425
+ function startDir() {
11426
+ const home = os.homedir();
11427
+ return fs.statSync(home, { throwIfNoEntry: false })?.isDirectory() ? home : path2.dirname(process.execPath);
11428
+ }
11429
+ function run(root, args, { max = 1024 * 1024, timeout = 1e4 } = {}) {
11430
+ return execFileSync("git", ["-C", root, ...gitOptions(), ...args], {
11431
+ cwd: startDir(),
11432
+ env: gitEnv(),
11433
+ maxBuffer: max,
11434
+ stdio: ["ignore", "pipe", "ignore"],
11435
+ timeout,
11436
+ killSignal: "SIGKILL"
11437
+ });
11438
+ }
11439
+ var text = (root, args, limits) => run(root, args, limits).toString("utf8");
11440
+ var list = (out) => out.split("\x00").filter(Boolean);
11441
+ function revision(rev) {
11442
+ if (!rev || rev.startsWith("-") || /[\0\n]/.test(rev))
11443
+ throw new Error(`not a revision: ${JSON.stringify(rev)}`);
11444
+ return rev;
11445
+ }
11446
+ function objectId(oid) {
11447
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(oid))
11448
+ throw new Error(`not an object id: ${JSON.stringify(oid)}`);
11449
+ return oid;
11450
+ }
11451
+ var topLevel = (dir, limits) => text(dir, ["rev-parse", "--show-toplevel"], limits).trim();
11452
+ var commitOf = (root, rev, limits) => text(root, ["rev-parse", "--verify", "-q", `${revision(rev)}^{commit}`], limits).trim();
11453
+ 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();
11454
+ var mergeBase = (root, a, b, limits) => text(root, ["merge-base", revision(a), revision(b)], limits).trim();
11455
+ function isAncestor(root, a, b, limits) {
11456
+ try {
11457
+ run(root, ["merge-base", "--is-ancestor", objectId(a), objectId(b)], limits);
11458
+ return true;
11459
+ } catch {
11460
+ return false;
11461
+ }
11462
+ }
11463
+ var commitDiffNames = (root, a, b, limits) => list(text(root, ["diff", ...DIFF_OPTIONS, "--name-only", "-z", objectId(a), objectId(b), "--"], limits));
11464
+ function listFiles(root, kind, { pathspecs = [], ...limits } = {}) {
11465
+ const which = {
11466
+ tracked: ["--cached"],
11467
+ untracked: ["--others", "--exclude-standard"],
11468
+ "tracked-and-untracked": ["--cached", "--others", "--exclude-standard"],
11469
+ deleted: ["--deleted"]
11470
+ }[kind];
11471
+ return list(text(root, ["ls-files", "-z", ...which, "--", ...pathspecs], limits));
11472
+ }
11473
+ var originUrl = (root, limits) => text(root, ["remote", "get-url", "origin"], limits).trim();
11474
+ async function worktreeStatus(root, deadline) {
11475
+ const out = await inIsolation(root, [{ kind: "status" }], { deadline, max: 16 * 1024 * 1024 });
11476
+ return out?.[0] ?? null;
11477
+ }
11478
+ async function worktreeDiff(root, from, { max, deadline }) {
11479
+ const out = await inIsolation(root, [{ kind: "diff", from: objectId(from) }], { deadline, max });
11480
+ return out && out.length === 2 ? { patch: out[0] ?? "", names: list(out[1] ?? "") } : null;
11481
+ }
11482
+ function workerFile() {
11483
+ const js = path2.join(import.meta.dirname, "git-worker.js");
11484
+ return fs.existsSync(js) ? js : path2.join(import.meta.dirname, "git-worker.ts");
11485
+ }
11486
+ function inIsolation(root, ops, { deadline, max }) {
11487
+ return new Promise((resolve) => {
11488
+ let child;
11489
+ try {
11490
+ child = spawn(process.execPath, [workerFile()], {
11491
+ cwd: startDir(),
11492
+ stdio: ["pipe", "pipe", "ignore"],
11493
+ windowsHide: true,
11494
+ detached: process.platform !== "win32"
11495
+ });
11496
+ } catch {
11497
+ resolve(null);
11498
+ return;
11499
+ }
11500
+ const chunks = [];
11501
+ let size = 0;
11502
+ let done = false;
11503
+ const finish = (out) => {
11504
+ if (done)
11505
+ return;
11506
+ done = true;
11507
+ clearTimeout(timer);
11508
+ if (out === null) {
11509
+ try {
11510
+ if (process.platform !== "win32" && child.pid)
11511
+ process.kill(-child.pid, "SIGKILL");
11512
+ else
11513
+ child.kill("SIGKILL");
11514
+ } catch {
11515
+ child.kill("SIGKILL");
11516
+ }
11517
+ child.stdin?.destroy();
11518
+ child.stdout?.destroy();
11519
+ child.unref();
11520
+ }
11521
+ resolve(out);
11522
+ };
11523
+ const timer = setTimeout(() => finish(null), deadline);
11524
+ const cap = 6 * max * Math.max(1, ops.length * 2) + 64 * 1024;
11525
+ child.stdout?.on("data", (c) => {
11526
+ size += c.length;
11527
+ if (size > cap)
11528
+ finish(null);
11529
+ else
11530
+ chunks.push(c);
11531
+ });
11532
+ child.on("error", () => finish(null));
11533
+ child.on("close", () => {
11534
+ try {
11535
+ const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
11536
+ finish(result.ok ? result.out : null);
11537
+ } catch {
11538
+ finish(null);
11539
+ }
11540
+ });
11541
+ child.stdin?.on("error", () => finish(null));
11542
+ child.stdin?.end(JSON.stringify({
11543
+ root,
11544
+ ops,
11545
+ max,
11546
+ until: Date.now() + Math.floor(deadline * 0.8)
11547
+ }));
11548
+ });
11549
+ }
11550
+
11391
11551
  // server/src/panel.ts
11392
11552
  import { stripVTControlCharacters, styleText } from "node:util";
11393
- var title = (text) => `✦ ${text}`;
11394
- var rule = (text) => text.split(`
11553
+ var title = (text2) => `✦ ${text2}`;
11554
+ var rule = (text2) => text2.split(`
11395
11555
  `).map((line) => line ? `│ ${line}` : "│").join(`
11396
11556
  `);
11397
- var foot = (text) => `╰─ ${text}`;
11557
+ var foot = (text2) => `╰─ ${text2}`;
11398
11558
  var panel = (head2, lines, end) => [title(head2), ...lines.map(rule), foot(end)].join(`
11399
11559
  `);
11400
11560
  var STRING_SEQUENCE = /\u001b[\]P_^X][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g;
@@ -11403,11 +11563,11 @@ var plain2 = (s) => visible(stripVTControlCharacters(s.replace(STRING_SEQUENCE,
11403
11563
  var inline = (s) => plain2(s).replace(/[\n\t]+/g, " ");
11404
11564
 
11405
11565
  // server/src/plugin.ts
11406
- var MANIFEST = path2.join(".claude-plugin", "plugin.json");
11566
+ var MANIFEST = path3.join(".claude-plugin", "plugin.json");
11407
11567
  var PACKAGE = "package.json";
11408
11568
  function versionAt(root) {
11409
11569
  try {
11410
- const m = JSON.parse(fs.readFileSync(path2.join(root, MANIFEST), "utf8"));
11570
+ const m = JSON.parse(fs2.readFileSync(path3.join(root, MANIFEST), "utf8"));
11411
11571
  return m.name === "sphica" && typeof m.version === "string" ? m.version : null;
11412
11572
  } catch {
11413
11573
  return null;
@@ -11415,28 +11575,28 @@ function versionAt(root) {
11415
11575
  }
11416
11576
  function packageVersionAt(root) {
11417
11577
  try {
11418
- const m = JSON.parse(fs.readFileSync(path2.join(root, PACKAGE), "utf8"));
11578
+ const m = JSON.parse(fs2.readFileSync(path3.join(root, PACKAGE), "utf8"));
11419
11579
  return m.name === "sphica" && typeof m.version === "string" ? m.version : null;
11420
11580
  } catch {
11421
11581
  return null;
11422
11582
  }
11423
11583
  }
11424
- var here = path2.dirname(fileURLToPath(import.meta.url));
11425
- var ROOT = [path2.join(here, ".."), path2.join(here, "..", "..", "plugin")].find((r) => versionAt(r) !== null) ?? path2.join(here, "..");
11584
+ var here = path3.dirname(fileURLToPath(import.meta.url));
11585
+ var ROOT = [path3.join(here, ".."), path3.join(here, "..", "..", "plugin")].find((r) => versionAt(r) !== null) ?? path3.join(here, "..");
11426
11586
  var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
11427
11587
 
11428
11588
  // server/src/sqlite.ts
11429
11589
  var SCHEMA_GENERATION = 2;
11430
11590
  var SCHEMA_REVISION = 12;
11431
- var sphicaHome = () => process.env.SPHICA_HOME || path3.join(os.homedir(), ".sphica");
11432
- var dbFile = () => process.env.SPHICA_DB || path3.join(sphicaHome(), "sphica.db");
11591
+ var sphicaHome = () => process.env.SPHICA_HOME || path4.join(os2.homedir(), ".sphica");
11592
+ var dbFile = () => process.env.SPHICA_DB || path4.join(sphicaHome(), "sphica.db");
11433
11593
  function requireRuntime() {
11434
11594
  const proto = DatabaseSync.prototype;
11435
11595
  if (typeof proto.setAuthorizer !== "function" || typeof proto.enableDefensive !== "function")
11436
11596
  throw new Error(`Sphica needs Node 24.15 or later (this is ${process.version}). Upgrade Node.`);
11437
11597
  }
11438
11598
  function requireFile(file) {
11439
- if (!fs2.existsSync(file))
11599
+ if (!fs3.existsSync(file))
11440
11600
  throw new Error(`No database at ${file}. Create it with \`sphica init\`.`);
11441
11601
  }
11442
11602
  function prepare(raw, check, busyMs = 5000) {
@@ -11555,9 +11715,9 @@ function sqliteCode(e) {
11555
11715
  function byUnit(rows) {
11556
11716
  const out = new Map;
11557
11717
  for (const r of rows) {
11558
- const list = out.get(r.unit_id);
11559
- if (list)
11560
- list.push(r);
11718
+ const list2 = out.get(r.unit_id);
11719
+ if (list2)
11720
+ list2.push(r);
11561
11721
  else
11562
11722
  out.set(r.unit_id, [r]);
11563
11723
  }
@@ -11795,7 +11955,7 @@ function connectWriter(role, file = dbFile(), create = false, busyMs) {
11795
11955
  const raw = new DatabaseSync2(file);
11796
11956
  try {
11797
11957
  prepare(raw, create ? "none" : role === "ingest" || role === "forget" ? "revision" : "generation", busyMs);
11798
- raw.function("sphica_terms", { deterministic: true }, (text) => terms(String(text ?? "")).join(" "));
11958
+ raw.function("sphica_terms", { deterministic: true }, (text2) => terms(String(text2 ?? "")).join(" "));
11799
11959
  } catch (e) {
11800
11960
  raw.close();
11801
11961
  throw e;
@@ -11830,10 +11990,9 @@ function openWriter(role, file = dbFile(), busyMs) {
11830
11990
  var sessionId = (projectId, host, externalId) => uuidFrom(String(projectId), host, externalId);
11831
11991
 
11832
11992
  // server/src/project.ts
11833
- import { execFileSync } from "node:child_process";
11834
- import fs3 from "node:fs";
11835
- import path4 from "node:path";
11836
- var localFile = () => path4.join(sphicaHome(), "projects.json");
11993
+ import fs4 from "node:fs";
11994
+ import path5 from "node:path";
11995
+ var localFile = () => path5.join(sphicaHome(), "projects.json");
11837
11996
  var LOCAL_KEY = /^[a-z0-9][a-z0-9._-]*$/;
11838
11997
  function legacyRemote(url) {
11839
11998
  const raw = String(url ?? "").trim();
@@ -11861,21 +12020,18 @@ function normalizeKey(key) {
11861
12020
  const host = fold(cut < 0 ? rest : rest.slice(0, cut));
11862
12021
  return host === "github.com" ? fold(key) : `git:${host}${cut < 0 ? "" : rest.slice(cut)}`;
11863
12022
  }
11864
- var git = (dir, ...args) => {
12023
+ var ask = (fn) => {
11865
12024
  try {
11866
- return execFileSync("git", ["-C", dir, ...args], {
11867
- encoding: "utf8",
11868
- stdio: ["ignore", "pipe", "ignore"],
11869
- timeout: 5000
11870
- }).trim();
12025
+ return fn() || null;
11871
12026
  } catch {
11872
12027
  return null;
11873
12028
  }
11874
12029
  };
12030
+ var top = (dir) => ask(() => topLevel(dir, { timeout: 5000 }));
11875
12031
  function localMap() {
11876
12032
  let raw;
11877
12033
  try {
11878
- raw = fs3.readFileSync(localFile(), "utf8");
12034
+ raw = fs4.readFileSync(localFile(), "utf8");
11879
12035
  } catch (e) {
11880
12036
  if (e.code === "ENOENT")
11881
12037
  return {};
@@ -11887,26 +12043,26 @@ function localMap() {
11887
12043
  } catch {
11888
12044
  m = null;
11889
12045
  }
11890
- if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path4.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
12046
+ if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path5.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
11891
12047
  throw new Error(`${localFile()} is not a valid JSON project table. Fix or delete it, then name the project again.`);
11892
12048
  return m;
11893
12049
  }
11894
12050
  function identify(dir) {
11895
- const given = path4.resolve(dir);
11896
- const top = git(given, "rev-parse", "--show-toplevel");
11897
- const root = top || given;
11898
- const legacy = top ? legacyRemote(git(root, "remote", "get-url", "origin")) : null;
12051
+ const given = path5.resolve(dir);
12052
+ const found = top(given);
12053
+ const root = found || given;
12054
+ const legacy = found ? legacyRemote(ask(() => originUrl(root, { timeout: 5000 }))) : null;
11899
12055
  if (legacy) {
11900
12056
  const key = normalizeKey(`git:${legacy}`);
11901
12057
  const remote = key.slice(4);
11902
12058
  return { key, legacyKey: `git:${legacy}`, root, name: remote.split("/").slice(1).join("/") || remote };
11903
12059
  }
11904
12060
  const map = localMap();
11905
- for (let d = root;; d = path4.dirname(d)) {
12061
+ for (let d = root;; d = path5.dirname(d)) {
11906
12062
  const local = map[d];
11907
12063
  if (local && LOCAL_KEY.test(local))
11908
12064
  return { key: `local:${local}`, legacyKey: `local:${local}`, root: d, name: local };
11909
- if (top || path4.dirname(d) === d)
12065
+ if (found || path5.dirname(d) === d)
11910
12066
  return null;
11911
12067
  }
11912
12068
  }
@@ -11915,11 +12071,11 @@ async function projectId(db, key) {
11915
12071
  return r?.id ?? null;
11916
12072
  }
11917
12073
  function relativeTo(root, file, cwd = root) {
11918
- const abs = path4.resolve(cwd, file);
11919
- const rel = path4.relative(root, abs);
12074
+ const abs = path5.resolve(cwd, file);
12075
+ const rel = path5.relative(root, abs);
11920
12076
  if (!rel || leaves(rel) || /\p{Cc}/u.test(rel))
11921
12077
  return null;
11922
- return rel.split(path4.sep).join("/");
12078
+ return rel.split(path5.sep).join("/");
11923
12079
  }
11924
12080
  function patchPaths(patch) {
11925
12081
  const out = [];
@@ -11933,25 +12089,15 @@ function patchPaths(patch) {
11933
12089
  }
11934
12090
 
11935
12091
  // server/src/worktree.ts
11936
- import { execFileSync as execFileSync2 } from "node:child_process";
11937
- import fs4 from "node:fs";
11938
- import path5 from "node:path";
12092
+ import fs5 from "node:fs";
12093
+ import path6 from "node:path";
11939
12094
  var MAX_PATHS = 200;
11940
- var git2 = (root, args) => {
11941
- try {
11942
- return execFileSync2("git", ["-C", root, ...args], {
11943
- encoding: "utf8",
11944
- stdio: ["ignore", "pipe", "ignore"],
11945
- timeout: 5000,
11946
- maxBuffer: 16 * 1024 * 1024
11947
- });
11948
- } catch {
11949
- return null;
11950
- }
11951
- };
12095
+ var LIMITS = { timeout: 5000, max: 16 * 1024 * 1024 };
12096
+ var STATUS_DEADLINE = 5000;
11952
12097
  var usable = (p) => p !== "" && !p.includes("\\") && !/\p{Cc}/u.test(p);
11953
- function snapshot(root) {
11954
- const out = git2(root, ["status", "--porcelain=v2", "-z", "--untracked-files=all"]);
12098
+ async function snapshot(root) {
12099
+ const until = Date.now() + STATUS_DEADLINE;
12100
+ const out = await worktreeStatus(root, STATUS_DEADLINE);
11955
12101
  if (out === null)
11956
12102
  return null;
11957
12103
  const fields = out.split("\x00");
@@ -11969,13 +12115,18 @@ function snapshot(root) {
11969
12115
  continue;
11970
12116
  let st;
11971
12117
  try {
11972
- st = fs4.lstatSync(path5.join(root, p), { throwIfNoEntry: false });
12118
+ st = fs5.lstatSync(path6.join(root, p), { throwIfNoEntry: false });
11973
12119
  } catch {
11974
12120
  st = undefined;
11975
12121
  }
11976
12122
  entries[p] = `${parts.slice(0, skip).join(" ")} ${st ? `${st.size}:${st.mtimeMs}` : "gone"}`;
11977
12123
  }
11978
- const head2 = git2(root, ["rev-parse", "--verify", "-q", "HEAD"])?.trim() || null;
12124
+ let head2 = null;
12125
+ try {
12126
+ const left = until - Date.now();
12127
+ if (left > 0)
12128
+ head2 = commitOf(root, "HEAD", { ...LIMITS, timeout: left }) || null;
12129
+ } catch {}
11979
12130
  return { head: head2, entries };
11980
12131
  }
11981
12132
  function changed(root, before, after) {
@@ -11983,8 +12134,12 @@ function changed(root, before, after) {
11983
12134
  for (const p of new Set([...Object.keys(before.entries), ...Object.keys(after.entries)]))
11984
12135
  if (before.entries[p] !== after.entries[p])
11985
12136
  paths.add(p);
11986
- if (before.head && after.head && before.head !== after.head && git2(root, ["merge-base", "--is-ancestor", before.head, after.head]) !== null) {
11987
- for (const p of (git2(root, ["diff", "--name-only", "-z", before.head, after.head]) ?? "").split("\x00"))
12137
+ if (before.head && after.head && before.head !== after.head && isAncestor(root, before.head, after.head, LIMITS)) {
12138
+ let between = [];
12139
+ try {
12140
+ between = commitDiffNames(root, before.head, after.head, LIMITS);
12141
+ } catch {}
12142
+ for (const p of between)
11988
12143
  if (usable(p))
11989
12144
  paths.add(p);
11990
12145
  }
@@ -11992,15 +12147,15 @@ function changed(root, before, after) {
11992
12147
  }
11993
12148
 
11994
12149
  // server/src/capture.ts
11995
- var spoolDir = () => path6.join(sphicaHome(), "spool");
11996
- var stateFile = () => path6.join(sphicaHome(), "capture.json");
11997
- var rejectedDir = () => path6.join(spoolDir(), "rejected");
11998
- var unregisteredDir = () => path6.join(spoolDir(), "unregistered");
11999
- var callsDir = () => path6.join(spoolDir(), "calls");
12000
- var callsRejectedDir = () => path6.join(callsDir(), "rejected");
12150
+ var spoolDir = () => path7.join(sphicaHome(), "spool");
12151
+ var stateFile = () => path7.join(sphicaHome(), "capture.json");
12152
+ var rejectedDir = () => path7.join(spoolDir(), "rejected");
12153
+ var unregisteredDir = () => path7.join(spoolDir(), "unregistered");
12154
+ var callsDir = () => path7.join(spoolDir(), "calls");
12155
+ var callsRejectedDir = () => path7.join(callsDir(), "rejected");
12001
12156
  var HOLD_DAYS = 30;
12002
12157
  var HOLD_MAX = 1000;
12003
- var baselineDir = () => path6.join(sphicaHome(), "worktree");
12158
+ var baselineDir = () => path7.join(sphicaHome(), "worktree");
12004
12159
  function current(raw) {
12005
12160
  const r = raw;
12006
12161
  if (typeof r.project !== "string")
@@ -12049,7 +12204,7 @@ ${z}`,
12049
12204
  function prune(held, removed = () => {}) {
12050
12205
  let files;
12051
12206
  try {
12052
- files = fs5.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
12207
+ files = fs6.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
12053
12208
  } catch {
12054
12209
  return;
12055
12210
  }
@@ -12057,26 +12212,26 @@ function prune(held, removed = () => {}) {
12057
12212
  const stale = files.filter((f) => Number(f.split("-")[0]) < cutoff);
12058
12213
  const over = files.slice(0, Math.max(0, files.length - HOLD_MAX));
12059
12214
  for (const f of new Set([...stale, ...over])) {
12060
- fs5.rmSync(path6.join(held, f), { force: true });
12215
+ fs6.rmSync(path7.join(held, f), { force: true });
12061
12216
  removed();
12062
12217
  }
12063
12218
  }
12064
12219
  function put(dir, record) {
12065
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
12220
+ fs6.mkdirSync(dir, { recursive: true, mode: 448 });
12066
12221
  const name = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 10)}.json`;
12067
- const tmp = path6.join(dir, `.${name}`);
12068
- fs5.writeFileSync(tmp, JSON.stringify(record), { mode: 384 });
12069
- fs5.renameSync(tmp, path6.join(dir, name));
12070
- return path6.join(dir, name);
12222
+ const tmp = path7.join(dir, `.${name}`);
12223
+ fs6.writeFileSync(tmp, JSON.stringify(record), { mode: 384 });
12224
+ fs6.renameSync(tmp, path7.join(dir, name));
12225
+ return path7.join(dir, name);
12071
12226
  }
12072
12227
  function spool(record) {
12073
12228
  put(spoolDir(), record);
12074
12229
  }
12075
12230
  var branchOf = (root) => {
12076
12231
  try {
12077
- const dotgit = path6.join(root, ".git");
12078
- const gitdir = fs5.statSync(dotgit).isFile() ? path6.resolve(root, fs5.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
12079
- const h = fs5.readFileSync(path6.join(gitdir, "HEAD"), "utf8").trim();
12232
+ const dotgit = path7.join(root, ".git");
12233
+ const gitdir = fs6.statSync(dotgit).isFile() ? path7.resolve(root, fs6.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
12234
+ const h = fs6.readFileSync(path7.join(gitdir, "HEAD"), "utf8").trim();
12080
12235
  return h.startsWith("ref: refs/heads/") ? h.slice("ref: refs/heads/".length) : null;
12081
12236
  } catch {
12082
12237
  return null;
@@ -12122,7 +12277,7 @@ Notes: ${notes.trim()}` : "";
12122
12277
  };
12123
12278
  }
12124
12279
  function captureNotice(file = dbFile()) {
12125
- if (!fs5.existsSync(file))
12280
+ if (!fs6.existsSync(file))
12126
12281
  return panel("sphica: no database, so conversations are not recorded", [file], "Create it with sphica init");
12127
12282
  const s = readState();
12128
12283
  if (s.unreadable)
@@ -12133,15 +12288,15 @@ function captureNotice(file = dbFile()) {
12133
12288
  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");
12134
12289
  return null;
12135
12290
  }
12136
- var turnDir = (host, session) => path6.join(baselineDir(), digest(`${host}\x00${session}`));
12137
- var startFile = (dir, turn) => path6.join(dir, `${digest(turn)}.json`);
12291
+ var turnDir = (host, session) => path7.join(baselineDir(), digest(`${host}\x00${session}`));
12292
+ var startFile = (dir, turn) => path7.join(dir, `${digest(turn)}.json`);
12138
12293
  var isStart = (v) => {
12139
12294
  const s = v;
12140
12295
  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");
12141
12296
  };
12142
12297
  function readStart(file) {
12143
12298
  try {
12144
- const s = JSON.parse(fs5.readFileSync(file, "utf8"));
12299
+ const s = JSON.parse(fs6.readFileSync(file, "utf8"));
12145
12300
  return isStart(s) ? s : null;
12146
12301
  } catch {
12147
12302
  return null;
@@ -12150,7 +12305,7 @@ function readStart(file) {
12150
12305
  function readStarts(dir) {
12151
12306
  let names;
12152
12307
  try {
12153
- names = fs5.readdirSync(dir);
12308
+ names = fs6.readdirSync(dir);
12154
12309
  } catch (e) {
12155
12310
  return e.code === "ENOENT" ? [] : null;
12156
12311
  }
@@ -12158,7 +12313,7 @@ function readStarts(dir) {
12158
12313
  for (const name of names) {
12159
12314
  if (name.startsWith("."))
12160
12315
  continue;
12161
- const s = readStart(path6.join(dir, name));
12316
+ const s = readStart(path7.join(dir, name));
12162
12317
  if (!s)
12163
12318
  return null;
12164
12319
  starts.push(s);
@@ -12168,30 +12323,30 @@ function readStarts(dir) {
12168
12323
  function newestTurn(starts) {
12169
12324
  if (!starts?.length || starts.some((s) => s.seq === null))
12170
12325
  return null;
12171
- const top = Math.max(...starts.map((s) => s.seq));
12172
- const at = starts.filter((s) => s.seq === top);
12326
+ const top2 = Math.max(...starts.map((s) => s.seq));
12327
+ const at = starts.filter((s) => s.seq === top2);
12173
12328
  return at.length === 1 ? at[0]?.turn ?? null : null;
12174
12329
  }
12175
12330
  function writeStart(dir, s, file = startFile(dir, s.turn)) {
12176
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
12177
- const tmp = path6.join(dir, `.${path6.basename(file)}.${process.pid}.tmp`);
12178
- fs5.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
12179
- fs5.renameSync(tmp, file);
12331
+ fs6.mkdirSync(dir, { recursive: true, mode: 448 });
12332
+ const tmp = path7.join(dir, `.${path7.basename(file)}.${process.pid}.tmp`);
12333
+ fs6.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
12334
+ fs6.renameSync(tmp, file);
12180
12335
  }
12181
- function openTurn(dir, turn, root) {
12336
+ async function openTurn(dir, turn, root) {
12182
12337
  if (readStart(startFile(dir, turn))?.running)
12183
12338
  return null;
12184
12339
  const starts = readStarts(dir);
12185
12340
  const seq = starts && !starts.some((s) => s.seq === null) ? Math.max(0, ...starts.map((s) => s.seq)) + 1 : null;
12186
- const now = snapshot(root);
12341
+ const now = await snapshot(root);
12187
12342
  return () => writeStart(dir, { head: now?.head ?? null, entries: now?.entries ?? null, running: true, turn, seq });
12188
12343
  }
12189
- function closeTurn(dir, turn, root) {
12344
+ async function closeTurn(dir, turn, root) {
12190
12345
  const own = readStart(startFile(dir, turn));
12191
12346
  if (!own?.entries)
12192
12347
  return null;
12193
12348
  const before = { head: own.head, entries: own.entries };
12194
- const now = snapshot(root);
12349
+ const now = await snapshot(root);
12195
12350
  return () => {
12196
12351
  if (newestTurn(readStarts(dir)) !== turn || JSON.stringify(readStart(startFile(dir, turn))) !== JSON.stringify(own))
12197
12352
  return [];
@@ -12206,22 +12361,22 @@ function stopTurn(dir, turn) {
12206
12361
  }
12207
12362
  function pruneBaselines() {
12208
12363
  const cutoff = Date.now() - HOLD_DAYS * 24 * 60 * 60 * 1000;
12209
- const fresh = (file) => (fs5.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
12364
+ const fresh = (file) => (fs6.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
12210
12365
  let names;
12211
12366
  try {
12212
- names = fs5.readdirSync(baselineDir());
12367
+ names = fs6.readdirSync(baselineDir());
12213
12368
  } catch {
12214
12369
  return;
12215
12370
  }
12216
12371
  for (const name of names) {
12217
- const at = path6.join(baselineDir(), name);
12218
- if (!fs5.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
12372
+ const at = path7.join(baselineDir(), name);
12373
+ if (!fs6.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
12219
12374
  if (!fresh(at))
12220
- fs5.rmSync(at, { force: true });
12375
+ fs6.rmSync(at, { force: true });
12221
12376
  } else {
12222
- const files = fs5.readdirSync(at);
12223
- if (files.length && !files.some((f) => fresh(path6.join(at, f))))
12224
- fs5.rmSync(at, { recursive: true, force: true });
12377
+ const files = fs6.readdirSync(at);
12378
+ if (files.length && !files.some((f) => fresh(path7.join(at, f))))
12379
+ fs6.rmSync(at, { recursive: true, force: true });
12225
12380
  }
12226
12381
  }
12227
12382
  }
@@ -12232,7 +12387,14 @@ function attempt(fn) {
12232
12387
  return;
12233
12388
  }
12234
12389
  }
12235
- function onHook(host, input) {
12390
+ async function attemptAsync(fn) {
12391
+ try {
12392
+ return await fn();
12393
+ } catch {
12394
+ return;
12395
+ }
12396
+ }
12397
+ async function onHook(host, input) {
12236
12398
  const event = input.hook_event_name;
12237
12399
  const owner = () => isOwnerTurn(input, undefined, undefined, host === "codex" ? process.env.CODEX_THREAD_ID : undefined);
12238
12400
  if (event === "SessionStart") {
@@ -12240,7 +12402,7 @@ function onHook(host, input) {
12240
12402
  return { flush: false };
12241
12403
  const file = process.env.CLAUDE_ENV_FILE;
12242
12404
  if (file && input.session_id && /^[A-Za-z0-9_-]+$/.test(input.session_id)) {
12243
- fs5.appendFileSync(file, `export SPHICA_PARENT_SESSION=${input.session_id}
12405
+ fs6.appendFileSync(file, `export SPHICA_PARENT_SESSION=${input.session_id}
12244
12406
  `);
12245
12407
  }
12246
12408
  attempt(pruneBaselines);
@@ -12284,12 +12446,12 @@ function onHook(host, input) {
12284
12446
  say(`${turn}:owner`, "owner", prompt);
12285
12447
  }
12286
12448
  if (event === "UserPromptSubmit")
12287
- attempt(() => openTurn(dir, turn, place.root)?.());
12449
+ await attemptAsync(async () => (await openTurn(dir, turn, place.root))?.());
12288
12450
  if (event === "Stop") {
12289
12451
  if (input.last_assistant_message)
12290
12452
  say(`${turn}:assistant`, "assistant", input.last_assistant_message);
12291
- const paths = attempt(() => {
12292
- const finish = closeTurn(dir, turn, place.root);
12453
+ const paths = await attemptAsync(async () => {
12454
+ const finish = await closeTurn(dir, turn, place.root);
12293
12455
  if (finish)
12294
12456
  return finish();
12295
12457
  stopTurn(dir, turn);
@@ -12323,7 +12485,7 @@ function onHook(host, input) {
12323
12485
  function readStateFile() {
12324
12486
  let raw = {};
12325
12487
  try {
12326
- const parsed = JSON.parse(fs5.readFileSync(stateFile(), "utf8"));
12488
+ const parsed = JSON.parse(fs6.readFileSync(stateFile(), "utf8"));
12327
12489
  if (parsed && typeof parsed === "object")
12328
12490
  raw = parsed;
12329
12491
  } catch {}
@@ -12337,7 +12499,7 @@ function readStateFile() {
12337
12499
  }
12338
12500
  function writeState(s) {
12339
12501
  try {
12340
- fs5.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
12502
+ fs6.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
12341
12503
  } catch {}
12342
12504
  }
12343
12505
  function readState() {
@@ -12353,7 +12515,7 @@ function readState() {
12353
12515
  }
12354
12516
  function listQueue(dir) {
12355
12517
  try {
12356
- const names = fs5.readdirSync(dir);
12518
+ const names = fs6.readdirSync(dir);
12357
12519
  return {
12358
12520
  files: names.filter((f) => f.endsWith(".json") && !f.startsWith(".")),
12359
12521
  temp: names.filter((f) => f.endsWith(".json") && f.startsWith(".")),
@@ -12365,25 +12527,25 @@ function listQueue(dir) {
12365
12527
  }
12366
12528
  }
12367
12529
  function lock() {
12368
- const file = path6.join(spoolDir(), ".lock");
12369
- fs5.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
12530
+ const file = path7.join(spoolDir(), ".lock");
12531
+ fs6.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
12370
12532
  for (let attempt2 = 0;attempt2 < 2; attempt2++) {
12371
12533
  try {
12372
- fs5.writeFileSync(file, String(process.pid), { flag: "wx", mode: 384 });
12534
+ fs6.writeFileSync(file, String(process.pid), { flag: "wx", mode: 384 });
12373
12535
  return () => {
12374
12536
  try {
12375
- if (fs5.readFileSync(file, "utf8") === String(process.pid))
12376
- fs5.rmSync(file, { force: true });
12537
+ if (fs6.readFileSync(file, "utf8") === String(process.pid))
12538
+ fs6.rmSync(file, { force: true });
12377
12539
  } catch {}
12378
12540
  };
12379
12541
  } catch (e) {
12380
12542
  if (e.code !== "EEXIST")
12381
12543
  throw e;
12382
12544
  }
12383
- const st = fs5.statSync(file, { throwIfNoEntry: false });
12545
+ const st = fs6.statSync(file, { throwIfNoEntry: false });
12384
12546
  if (!st)
12385
12547
  continue;
12386
- const holder = Number(fs5.readFileSync(file, "utf8") || 0);
12548
+ const holder = Number(fs6.readFileSync(file, "utf8") || 0);
12387
12549
  const fresh = Date.now() - st.mtimeMs < 5 * 60000;
12388
12550
  const alive = (() => {
12389
12551
  if (holder <= 0)
@@ -12396,7 +12558,7 @@ function lock() {
12396
12558
  })();
12397
12559
  if (alive && fresh)
12398
12560
  return null;
12399
- fs5.rmSync(file, { force: true });
12561
+ fs6.rmSync(file, { force: true });
12400
12562
  }
12401
12563
  return null;
12402
12564
  }
@@ -12495,23 +12657,23 @@ var REJECTED = new Set([18, 19, 20, 25]);
12495
12657
  var rejected = (e) => REJECTED.has(sqliteCode(e) ?? -1);
12496
12658
  var queued = (from) => {
12497
12659
  try {
12498
- return fs5.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
12660
+ return fs6.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
12499
12661
  } catch {
12500
12662
  return [];
12501
12663
  }
12502
12664
  };
12503
12665
  var CODE_NAMES = { 18: "TOOBIG", 19: "CONSTRAINT", 20: "MISMATCH", 25: "RANGE" };
12504
12666
  function setAside(from, name, dir, reason2) {
12505
- fs5.mkdirSync(dir, { recursive: true, mode: 448 });
12667
+ fs6.mkdirSync(dir, { recursive: true, mode: 448 });
12506
12668
  try {
12507
- fs5.renameSync(path6.join(from, name), path6.join(dir, name));
12669
+ fs6.renameSync(path7.join(from, name), path7.join(dir, name));
12508
12670
  } catch (e) {
12509
12671
  if (e.code === "ENOENT")
12510
12672
  return;
12511
12673
  throw e;
12512
12674
  }
12513
12675
  try {
12514
- fs5.writeFileSync(path6.join(dir, `${name}.reason`), reason2, { mode: 384 });
12676
+ fs6.writeFileSync(path7.join(dir, `${name}.reason`), reason2, { mode: 384 });
12515
12677
  } catch {}
12516
12678
  }
12517
12679
  async function sendBatch(db, names) {
@@ -12521,7 +12683,7 @@ async function sendBatch(db, names) {
12521
12683
  let raw;
12522
12684
  let r;
12523
12685
  try {
12524
- raw = JSON.parse(fs5.readFileSync(path6.join(from, name), "utf8"));
12686
+ raw = JSON.parse(fs6.readFileSync(path7.join(from, name), "utf8"));
12525
12687
  } catch {
12526
12688
  setAside(from, name, rejectedDir(), "unreadable");
12527
12689
  continue;
@@ -12535,7 +12697,7 @@ async function sendBatch(db, names) {
12535
12697
  if (r)
12536
12698
  records.push({ name, from, r });
12537
12699
  else
12538
- fs5.rmSync(path6.join(from, name), { force: true });
12700
+ fs6.rmSync(path7.join(from, name), { force: true });
12539
12701
  }
12540
12702
  let sent = 0;
12541
12703
  let strayed = [];
@@ -12563,12 +12725,12 @@ async function sendBatch(db, names) {
12563
12725
  for (const x of bad)
12564
12726
  setAside(x.from, x.name, rejectedDir(), x.why);
12565
12727
  if (strayed.length) {
12566
- fs5.mkdirSync(held, { recursive: true, mode: 448 });
12728
+ fs6.mkdirSync(held, { recursive: true, mode: 448 });
12567
12729
  for (const x of strayed) {
12568
12730
  if (x.from === held)
12569
12731
  continue;
12570
12732
  try {
12571
- fs5.renameSync(path6.join(x.from, x.name), path6.join(held, x.name));
12733
+ fs6.renameSync(path7.join(x.from, x.name), path7.join(held, x.name));
12572
12734
  } catch (e) {
12573
12735
  if (e.code !== "ENOENT")
12574
12736
  throw e;
@@ -12578,7 +12740,7 @@ async function sendBatch(db, names) {
12578
12740
  const moved = new Set([...bad, ...strayed].map((x) => x.name));
12579
12741
  for (const x of records)
12580
12742
  if (!moved.has(x.name))
12581
- fs5.rmSync(path6.join(x.from, x.name), { force: true });
12743
+ fs6.rmSync(path7.join(x.from, x.name), { force: true });
12582
12744
  return { sent, rejected: bad.length };
12583
12745
  }
12584
12746
  async function sendObservations(db, names) {
@@ -12589,16 +12751,16 @@ async function sendObservations(db, names) {
12589
12751
  };
12590
12752
  const rows = [];
12591
12753
  for (const { name, from } of names) {
12592
- let text;
12754
+ let text2;
12593
12755
  try {
12594
- text = fs5.readFileSync(path6.join(from, name), "utf8");
12756
+ text2 = fs6.readFileSync(path7.join(from, name), "utf8");
12595
12757
  } catch {
12596
12758
  continue;
12597
12759
  }
12598
12760
  let o = null;
12599
12761
  let why = "unreadable";
12600
12762
  try {
12601
- o = observation(JSON.parse(text));
12763
+ o = observation(JSON.parse(text2));
12602
12764
  why = "shape";
12603
12765
  } catch {}
12604
12766
  if (o)
@@ -12630,7 +12792,7 @@ async function sendObservations(db, names) {
12630
12792
  aside(x.name, why);
12631
12793
  else
12632
12794
  try {
12633
- fs5.rmSync(path6.join(callsDir(), x.name), { force: true });
12795
+ fs6.rmSync(path7.join(callsDir(), x.name), { force: true });
12634
12796
  } catch {}
12635
12797
  }
12636
12798
  return true;
@@ -12773,7 +12935,7 @@ async function observeRecordCall(file, input, owner, waitMs = OBSERVE_WAIT_MS) {
12773
12935
  }
12774
12936
  if (kept)
12775
12937
  try {
12776
- fs5.rmSync(kept, { force: true });
12938
+ fs6.rmSync(kept, { force: true });
12777
12939
  } catch {}
12778
12940
  }
12779
12941
  async function main() {
@@ -12789,11 +12951,11 @@ async function main() {
12789
12951
  }
12790
12952
  if (host === "codex" && input.hook_event_name === "Stop")
12791
12953
  process.stdout.write("{}");
12792
- const { flush: send, notice } = onHook(host, input);
12954
+ const { flush: send, notice } = await onHook(host, input);
12793
12955
  if (notice)
12794
12956
  process.stdout.write(JSON.stringify({ systemMessage: notice }));
12795
12957
  if (send)
12796
- spawn(process.execPath, [process.argv[1] ?? "", "--flush"], {
12958
+ spawn2(process.execPath, [process.argv[1] ?? "", "--flush"], {
12797
12959
  detached: true,
12798
12960
  stdio: "ignore",
12799
12961
  windowsHide: true
@@ -12835,13 +12997,13 @@ function gitPath(token, prefix) {
12835
12997
  }
12836
12998
  return prefix && out.startsWith(prefix) ? out.slice(prefix.length) : out;
12837
12999
  }
12838
- function parseDiff(text) {
13000
+ function parseDiff(text2) {
12839
13001
  const files = [];
12840
- const at = (path7) => {
12841
- const found = files.find((f2) => f2.path === path7);
13002
+ const at = (path8) => {
13003
+ const found = files.find((f2) => f2.path === path8);
12842
13004
  if (found)
12843
13005
  return found;
12844
- const f = { path: path7, added: [], lines: [] };
13006
+ const f = { path: path8, added: [], lines: [] };
12845
13007
  files.push(f);
12846
13008
  return f;
12847
13009
  };
@@ -12855,7 +13017,7 @@ function parseDiff(text) {
12855
13017
  at(block);
12856
13018
  block = null;
12857
13019
  };
12858
- const rows = text.split(/\r?\n/);
13020
+ const rows = text2.split(/\r?\n/);
12859
13021
  for (const [i, raw] of rows.entries()) {
12860
13022
  if (cur && (oldLeft > 0 || newLeft > 0)) {
12861
13023
  if (raw.startsWith("+")) {
@@ -12952,11 +13114,11 @@ async function selectForReview(db, projectId2, files) {
12952
13114
  }
12953
13115
 
12954
13116
  // server/src/review-bridge.ts
12955
- import { execFileSync as execFileSync3 } from "node:child_process";
12956
- import fs6 from "node:fs";
12957
- import path7 from "node:path";
13117
+ import fs7 from "node:fs";
13118
+ import path8 from "node:path";
12958
13119
  var NAME = /^[\w.:/-]{1,100}$/;
12959
13120
  var MAX_DIFF = 4 * 1024 * 1024;
13121
+ var DIFF_DEADLINE = 5000;
12960
13122
  var MAX_FILES = 500;
12961
13123
  var MAX_UNTRACKED_BYTES = 256 * 1024;
12962
13124
  function reviewCall(input) {
@@ -12974,28 +13136,22 @@ function reviewCall(input) {
12974
13136
  const lower = name.toLowerCase();
12975
13137
  if (lower === "sphica:review")
12976
13138
  return null;
12977
- const names = (list) => (list ?? "").split(",").map((n) => n.trim().toLowerCase()).filter((n) => NAME.test(n));
13139
+ const names = (list2) => (list2 ?? "").split(",").map((n) => n.trim().toLowerCase()).filter((n) => NAME.test(n));
12978
13140
  const option = names(process.env.CLAUDE_PLUGIN_OPTION_REVIEW_COMMANDS);
12979
13141
  const named = option.length > 0 ? option : names(process.env.SPHICA_REVIEW_COMMANDS);
12980
13142
  if (!named.includes(lower) && !lower.includes("review"))
12981
13143
  return null;
12982
13144
  return { name, args: typeof args === "string" ? args.slice(0, 1000) : "" };
12983
13145
  }
12984
- var git3 = (root, args, maxBuffer = 1024 * 1024) => execFileSync3("git", ["-C", root, "-c", "core.quotePath=false", ...args], {
12985
- encoding: "utf8",
12986
- stdio: ["ignore", "pipe", "ignore"],
12987
- maxBuffer
12988
- });
12989
- function localChange(root, args) {
13146
+ async function localChange(root, args) {
12990
13147
  if (/^\s*#?\d+\s*$|(^|\s)#\d+\b|\/pull\/\d+/.test(args))
12991
13148
  return { problem: "it names a pull request, and Sphica sees only the local change" };
13149
+ const until = Date.now() + DIFF_DEADLINE;
13150
+ const left = () => Math.max(1, until - Date.now());
12992
13151
  let base = "";
12993
- for (const ref of [
12994
- ["--abbrev-ref", "origin/HEAD"],
12995
- ["--abbrev-ref", "--symbolic-full-name", "@{upstream}"]
12996
- ]) {
13152
+ for (const which of ["origin/HEAD", "upstream"]) {
12997
13153
  try {
12998
- base = git3(root, ["rev-parse", ...ref]).trim();
13154
+ base = baseRef(root, which, { timeout: left() });
12999
13155
  if (base)
13000
13156
  break;
13001
13157
  } catch {}
@@ -13004,28 +13160,22 @@ function localChange(root, args) {
13004
13160
  return { problem: "there is no default branch (origin/HEAD) or upstream to compare with" };
13005
13161
  let from;
13006
13162
  try {
13007
- from = git3(root, ["merge-base", "HEAD", base]).trim();
13163
+ from = mergeBase(root, "HEAD", base, { timeout: left() });
13008
13164
  } catch {
13009
13165
  return { problem: `HEAD shares no history with ${base}` };
13010
13166
  }
13011
- let diff;
13012
- let names;
13167
+ const got = await worktreeDiff(root, from, { max: MAX_DIFF, deadline: left() });
13013
13168
  let untracked;
13014
13169
  try {
13015
- const plain3 = [
13016
- "--no-color",
13017
- "--no-ext-diff",
13018
- "--no-textconv",
13019
- "--no-renames",
13020
- "--src-prefix=a/",
13021
- "--dst-prefix=b/"
13022
- ];
13023
- diff = git3(root, ["diff", ...plain3, from], MAX_DIFF);
13024
- names = git3(root, ["diff", "--name-only", "-z", "--no-renames", from], MAX_DIFF).split("\x00").filter(Boolean);
13025
- untracked = git3(root, ["ls-files", "--others", "--exclude-standard", "-z"], MAX_DIFF).split("\x00").filter(Boolean);
13170
+ if (!got)
13171
+ throw new Error("no diff");
13172
+ untracked = listFiles(root, "untracked", { max: MAX_DIFF, timeout: left() });
13026
13173
  } catch {
13027
- return { problem: "the change is too large to read (over 4 MB of diff or file names)" };
13174
+ return {
13175
+ problem: "the change could not be read in time, or is too large to read (over 4 MB of diff or file names)"
13176
+ };
13028
13177
  }
13178
+ const { patch: diff, names } = got;
13029
13179
  const files = parseDiff(diff);
13030
13180
  for (const name of names)
13031
13181
  if (!files.some((f) => f.path === name))
@@ -13034,16 +13184,16 @@ function localChange(root, args) {
13034
13184
  return { problem: `the change has more than ${MAX_FILES} files` };
13035
13185
  const read = [from, diff];
13036
13186
  for (const rel of untracked) {
13037
- let text = "";
13187
+ let text2 = "";
13038
13188
  try {
13039
- const file = path7.join(root, rel);
13040
- const st = fs6.lstatSync(file);
13189
+ const file = path8.join(root, rel);
13190
+ const st = fs7.lstatSync(file);
13041
13191
  if (st.isFile() && st.size <= MAX_UNTRACKED_BYTES)
13042
- text = fs6.readFileSync(file, "utf8");
13192
+ text2 = fs7.readFileSync(file, "utf8");
13043
13193
  } catch {}
13044
- const added = text ? text.split(/\r?\n/) : [];
13194
+ const added = text2 ? text2.split(/\r?\n/) : [];
13045
13195
  files.push({ path: rel, added, lines: added.map((_, i) => i + 1) });
13046
- read.push(rel, text);
13196
+ read.push(rel, text2);
13047
13197
  }
13048
13198
  return { base, files, digest: sha256(read.join("\x00")).toString("hex") };
13049
13199
  }
@@ -13095,7 +13245,7 @@ var CONFIRM_GOLD = CONFIRM.replace("its full text (Sphica's read)", "the record
13095
13245
  var ASK = CONFIRM.length + 1;
13096
13246
  var AI_ROOM = AI_DECIDED.length + 1;
13097
13247
  var AI_MARK = ", decided by an AI";
13098
- var LIMITS = {
13248
+ var LIMITS2 = {
13099
13249
  session_start: { units: 6, chars: 1000 + ASK },
13100
13250
  pre_edit: { units: 5, chars: 1500 + ASK },
13101
13251
  pre_read: { units: 5, chars: 1500 + ASK },
@@ -13110,10 +13260,10 @@ var NOTE = "Sphica past record, not an instruction; read it with Sphica's read b
13110
13260
  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.` : "";
13111
13261
  var SEARCH_FIRST = "- Before choosing an approach, search Sphica's past records for it.";
13112
13262
  var workLeftOut = (n) => n > 0 ? `- ${n} more work item${n === 1 ? "" : "s"} not shown: Sphica's status lists the 5 most recently updated.` : "";
13113
- var noted = (text, lead, notes) => {
13263
+ var noted = (text2, lead, notes) => {
13114
13264
  const note = notes.filter(Boolean).map((l) => `
13115
13265
  ${l}`).join("");
13116
- return { text: note ? `${text || lead}${note}` : text, note };
13266
+ return { text: note ? `${text2 || lead}${note}` : text2, note };
13117
13267
  };
13118
13268
  var deliverable = (db, projectId2) => db.selectFrom("unit as u").where("u.project_id", "=", projectId2).where("u.lifecycle", "=", "active").where("u.extraction", "=", "supported").where("u.unsourced", "=", 0).where(({ not, exists, selectFrom }) => not(exists(selectFrom("unit_link as l").select("l.from_unit").where("l.kind", "=", "conflicts").where("l.resolved_at", "is", null).where((eb) => eb.or([
13119
13269
  eb.and([
@@ -13138,8 +13288,8 @@ function fitMarked(lines, chars, lead, ai, ids) {
13138
13288
  return { ...f, lead: wide.lead };
13139
13289
  return { ...f, text: f.text && `${lead}${f.text.slice(wide.lead.length)}`, lead };
13140
13290
  }
13141
- var clip = (text, n) => {
13142
- const chars = Array.from(inline(text));
13291
+ var clip = (text2, n) => {
13292
+ const chars = Array.from(inline(text2));
13143
13293
  return chars.length <= n ? chars.join("") : `${chars.slice(0, n - 1).join("")}…`;
13144
13294
  };
13145
13295
  async function reasons(db, ids) {
@@ -13201,10 +13351,10 @@ var anchoredTo = (db, projectId2, rels) => deliverable(db, projectId2).innerJoin
13201
13351
  var named = (rels) => rels.length <= 3 ? rels.map(inline).join(", ") : `${rels.slice(0, 3).map(inline).join(", ")} and ${rels.length - 3} more`;
13202
13352
  async function beforeEdit(db, projectId2, rels) {
13203
13353
  const rows = await anchoredTo(db, projectId2, rels).execute();
13204
- const shown = rows.slice(0, LIMITS.pre_edit.units);
13354
+ const shown = rows.slice(0, LIMITS2.pre_edit.units);
13205
13355
  const why = await reasons(db, shown.map((u) => u.id));
13206
13356
  const ai = await aiDecided(db, shown.map((u) => u.id));
13207
- const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), LIMITS.pre_edit.chars, `Active decisions applying to ${named(rels)} (current code relevance unverified). ${CONFIRM} ${NOTE}:`, ai, shown.map((u) => u.id));
13357
+ const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), LIMITS2.pre_edit.chars, `Active decisions applying to ${named(rels)} (current code relevance unverified). ${CONFIRM} ${NOTE}:`, ai, shown.map((u) => u.id));
13208
13358
  const omitted = rows.length - shown.length + f.omitted;
13209
13359
  return {
13210
13360
  ...noted(f.text, f.lead, [leftOut(omitted)]),
@@ -13235,11 +13385,11 @@ async function beforeRead(db, projectId2, rels, session, agent, how) {
13235
13385
  const seen = new Set(sent.map((r) => r.unit_id));
13236
13386
  const readUnits = sent.filter((r) => r.event === "pre_read").length;
13237
13387
  const rows = (await anchoredTo(db, projectId2, rels).where("u.kind", "in", ["decision", "constraint"]).execute()).filter((u) => !seen.has(u.id));
13238
- const room = Math.min(LIMITS.pre_read.units, READ_SESSION.units - readUnits);
13388
+ const room = Math.min(LIMITS2.pre_read.units, READ_SESSION.units - readUnits);
13239
13389
  const shown = rows.slice(0, Math.max(room, 0));
13240
13390
  const why = await reasons(db, shown.map((u) => u.id));
13241
13391
  const ai = await aiDecided(db, shown.map((u) => u.id));
13242
- const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), Math.min(LIMITS.pre_read.chars, READ_SESSION.chars + ASK - spent.reduce((n, r) => {
13392
+ const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), Math.min(LIMITS2.pre_read.chars, READ_SESSION.chars + ASK - spent.reduce((n, r) => {
13243
13393
  const ai2 = marked.get(r.id) ?? 0;
13244
13394
  return n + Math.max(r.chars - ASK - (ai2 ? AI_ROOM + ai2 * AI_MARK.length : 0), 0);
13245
13395
  }, 0)), `Active decisions applying to ${named(rels)}, which ${how === "reading" ? "you are reading" : "this command names"} (current code relevance unverified). ${CONFIRM} ${NOTE}:`, ai, shown.map((u) => u.id));
@@ -13272,15 +13422,15 @@ async function namedInCommand(db, projectId2, root, cwd, command) {
13272
13422
  const edge = `\\s'"=(){}<>|;&,`;
13273
13423
  const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13274
13424
  const forms = (p) => {
13275
- const abs = path8.join(root, p);
13276
- const fromCwd = path8.relative(cwd, abs);
13425
+ const abs = path9.join(root, p);
13426
+ const fromCwd = path9.relative(cwd, abs);
13277
13427
  const out = new Set;
13278
13428
  for (const f of [p, abs, leaves(fromCwd) ? "" : fromCwd])
13279
13429
  if (f)
13280
13430
  for (const sep of ["/", "\\"]) {
13281
13431
  const t = f.split(/[\\/]/).join(sep);
13282
13432
  out.add(t);
13283
- if (!path8.isAbsolute(f))
13433
+ if (!path9.isAbsolute(f))
13284
13434
  out.add(`.${sep}${t}`);
13285
13435
  }
13286
13436
  return [...out];
@@ -13289,7 +13439,7 @@ async function namedInCommand(db, projectId2, root, cwd, command) {
13289
13439
  }
13290
13440
  function pathNamed(prompt, root, rel) {
13291
13441
  const steps = (p) => p.split(/[\\/]/).map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]");
13292
- return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(path8.join(root, rel))})(?![A-Za-z0-9_$\\-/\\\\]|\\.[A-Za-z0-9_$])`).test(prompt);
13442
+ return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(path9.join(root, rel))})(?![A-Za-z0-9_$\\-/\\\\]|\\.[A-Za-z0-9_$])`).test(prompt);
13293
13443
  }
13294
13444
  function once(f) {
13295
13445
  const seen = new Map;
@@ -13300,10 +13450,10 @@ function once(f) {
13300
13450
  };
13301
13451
  }
13302
13452
  async function onPrompt(db, projectId2, root, prompt) {
13303
- const text = prompt.normalize("NFKC");
13304
- const lower = text.toLowerCase();
13453
+ const text2 = prompt.normalize("NFKC");
13454
+ const lower = text2.toLowerCase();
13305
13455
  const word = (w, s) => s.includes(w) && new RegExp(`(?<![\\p{L}\\p{N}_$])${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}_$])`, "u").test(s);
13306
- const named2 = once((symbol) => symbol.length >= 3 && (/[^a-z]/.test(symbol) ? word(symbol, text) : text.includes(`${symbol}(`) || text.includes(`\`${symbol}\``)));
13456
+ const named2 = once((symbol) => symbol.length >= 3 && (/[^a-z]/.test(symbol) ? word(symbol, text2) : text2.includes(`${symbol}(`) || text2.includes(`\`${symbol}\``)));
13307
13457
  const slashed = prompt.replaceAll("\\", "/");
13308
13458
  const pathIn = once((rel) => slashed.includes(rel) && pathNamed(prompt, root, rel));
13309
13459
  const optionIn = once((option) => option.length >= 3 && word(option.normalize("NFKC").toLowerCase(), lower));
@@ -13322,9 +13472,9 @@ async function onPrompt(db, projectId2, root, prompt) {
13322
13472
  else if (o)
13323
13473
  hits.push({ u, why: ` [names the ${o.outcome} option ${inline(o.text)}]` });
13324
13474
  }
13325
- const shown = hits.slice(0, LIMITS.prompt.units);
13475
+ const shown = hits.slice(0, LIMITS2.prompt.units);
13326
13476
  const ai = await aiDecided(db, shown.map((h) => h.u.id));
13327
- const wide = withAi(CONFIRM, LIMITS.prompt.chars, ai);
13477
+ const wide = withAi(CONFIRM, LIMITS2.prompt.chars, ai);
13328
13478
  const lines = shown.map((h) => `${NOTE}: ${line(h.u, h.why, ai.has(h.u.id)).slice(2)}`);
13329
13479
  const kept = [];
13330
13480
  let used = wide.lead.length + 1;
@@ -13335,10 +13485,10 @@ async function onPrompt(db, projectId2, root, prompt) {
13335
13485
  kept.push(l);
13336
13486
  used += cost + 1;
13337
13487
  }
13338
- const ask = shown.slice(0, kept.length).some((h) => ai.has(h.u.id)) ? wide.lead : CONFIRM;
13488
+ const ask2 = shown.slice(0, kept.length).some((h) => ai.has(h.u.id)) ? wide.lead : CONFIRM;
13339
13489
  return {
13340
- ...noted(kept.length ? [ask, ...kept].join(`
13341
- `) : "", ask, [leftOut(hits.length - kept.length)]),
13490
+ ...noted(kept.length ? [ask2, ...kept].join(`
13491
+ `) : "", ask2, [leftOut(hits.length - kept.length)]),
13342
13492
  units: shown.slice(0, kept.length).map((h) => h.u.id),
13343
13493
  eligible: hits.length,
13344
13494
  omitted: hits.length - kept.length,
@@ -13358,7 +13508,7 @@ async function waiting(db, projectId2, place) {
13358
13508
  });
13359
13509
  if (!total)
13360
13510
  return "";
13361
- if (!markOnce("auto-trace", `${path8.resolve(place.file)}\x00${place.key}\x00${place.host}\x00${place.auto}`))
13511
+ if (!markOnce("auto-trace", `${path9.resolve(place.file)}\x00${place.key}\x00${place.host}\x00${place.auto}`))
13362
13512
  return "";
13363
13513
  return AUTO_TRACE(total);
13364
13514
  }
@@ -13366,7 +13516,7 @@ async function waiting(db, projectId2, place) {
13366
13516
  if (!n)
13367
13517
  return "";
13368
13518
  const day = new Date().toLocaleDateString("sv-SE");
13369
- if (!markOnce("pending", `${path8.resolve(place.file)}\x00${place.key}\x00${day}`))
13519
+ if (!markOnce("pending", `${path9.resolve(place.file)}\x00${place.key}\x00${day}`))
13370
13520
  return "";
13371
13521
  const trace = place.host === "codex" ? "$sphica:trace" : "/sphica:trace";
13372
13522
  return `- ${n} session${n === 1 ? "" : "s"} waiting to be traced: run ${trace} pending.`;
@@ -13388,7 +13538,7 @@ async function atStart(db, projectId2, branch, place) {
13388
13538
  }),
13389
13539
  ...broad.map((u) => line(u, "", ai.has(u.id)))
13390
13540
  ];
13391
- const f = fitMarked(lines, LIMITS.session_start.chars, `Sphica: this project's current work and standing constraints. ${CONFIRM} ${NOTE}:`, ai, [...work.map(() => null), ...broad.map((u) => u.id)]);
13541
+ const f = fitMarked(lines, LIMITS2.session_start.chars, `Sphica: this project's current work and standing constraints. ${CONFIRM} ${NOTE}:`, ai, [...work.map(() => null), ...broad.map((u) => u.id)]);
13392
13542
  const shownUnits = f.kept.flatMap((i) => i >= work.length ? broad[i - work.length]?.id ?? [] : []);
13393
13543
  const workLeft = Math.max((workTotal ?? 0) - f.kept.filter((i) => i < work.length).length, 0);
13394
13544
  const broadLeft = Math.max((broadTotal ?? 0) - shownUnits.length, 0);
@@ -13407,9 +13557,9 @@ async function atStart(db, projectId2, branch, place) {
13407
13557
  };
13408
13558
  }
13409
13559
  async function beforeReview(db, projectId2, root, call) {
13410
- const change = localChange(root, call.args);
13411
- const said = (text, why) => ({
13412
- text,
13560
+ const change = await localChange(root, call.args);
13561
+ const said = (text2, why) => ({
13562
+ text: text2,
13413
13563
  note: "",
13414
13564
  units: [],
13415
13565
  eligible: 0,
@@ -13429,9 +13579,9 @@ async function beforeReview(db, projectId2, root, call) {
13429
13579
  const checked = `checked ${n} changed path${n === 1 ? "" : "s"} against ${base}`;
13430
13580
  if (!rows.length)
13431
13581
  return { ...said(`Sphica ${checked}: no active recorded decision applies.`, null), once: once2 };
13432
- const shown = rows.slice(0, LIMITS.review.units);
13582
+ const shown = rows.slice(0, LIMITS2.review.units);
13433
13583
  const ai = await aiDecided(db, shown.map((u) => u.id));
13434
- const f = fitMarked(shown.map((u) => line(u, ` [${inline(u.because)}]`, ai.has(u.id))), LIMITS.review.chars, `Sphica: past decisions that apply to this change (${checked}). ${NOTE}; compare the change against each:`, ai, shown.map((u) => u.id));
13584
+ const f = fitMarked(shown.map((u) => line(u, ` [${inline(u.because)}]`, ai.has(u.id))), LIMITS2.review.chars, `Sphica: past decisions that apply to this change (${checked}). ${NOTE}; compare the change against each:`, ai, shown.map((u) => u.id));
13435
13585
  const omitted = rows.length - shown.length + f.omitted;
13436
13586
  return {
13437
13587
  ...noted(f.text, f.lead, [leftOut(omitted)]),
@@ -13449,15 +13599,15 @@ function toldBefore(session, key) {
13449
13599
  function markOnce(kind, key) {
13450
13600
  const user = (() => {
13451
13601
  try {
13452
- return os2.userInfo().username;
13602
+ return os3.userInfo().username;
13453
13603
  } catch {
13454
13604
  return String(process.getuid?.() ?? "user");
13455
13605
  }
13456
13606
  })();
13457
- const dir = path8.join(os2.tmpdir(), `sphica-${sha256(user).toString("hex").slice(0, 12)}`, kind);
13607
+ const dir = path9.join(os3.tmpdir(), `sphica-${sha256(user).toString("hex").slice(0, 12)}`, kind);
13458
13608
  try {
13459
- fs7.mkdirSync(dir, { recursive: true, mode: 448 });
13460
- fs7.writeFileSync(path8.join(dir, sha256(key).toString("hex").slice(0, 24)), "", { flag: "wx" });
13609
+ fs8.mkdirSync(dir, { recursive: true, mode: 448 });
13610
+ fs8.writeFileSync(path9.join(dir, sha256(key).toString("hex").slice(0, 24)), "", { flag: "wx" });
13461
13611
  return true;
13462
13612
  } catch (e) {
13463
13613
  return e.code !== "EEXIST";
@@ -13540,12 +13690,12 @@ async function deliver(input, host = "claude-code", file = dbFile()) {
13540
13690
  const place = identify(input.cwd ?? process.cwd());
13541
13691
  if (!place)
13542
13692
  return "";
13543
- let rels = targets.map((t) => path8.relative(place.root, path8.resolve(input.cwd ?? place.root, t))).filter((r) => r && !leaves(r)).map((r) => r.split(path8.sep).join("/"));
13693
+ let rels = targets.map((t) => path9.relative(place.root, path9.resolve(input.cwd ?? place.root, t))).filter((r) => r && !leaves(r)).map((r) => r.split(path9.sep).join("/"));
13544
13694
  if (onPath && !shell && !rels.length)
13545
13695
  return "";
13546
13696
  let db = null;
13547
13697
  try {
13548
- if (!fs7.existsSync(file))
13698
+ if (!fs8.existsSync(file))
13549
13699
  throw new Error(`no database at ${file}`);
13550
13700
  db = openReader(file);
13551
13701
  const pid = await projectId(db, place.key);