sphica 0.6.41 → 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/cli.js CHANGED
@@ -92,8 +92,8 @@ var require_src = __commonJS(function(exports, module) {
92
92
  });
93
93
 
94
94
  // server/src/cli.ts
95
- import fs10 from "node:fs";
96
- import path10 from "node:path";
95
+ import fs11 from "node:fs";
96
+ import path11 from "node:path";
97
97
 
98
98
  // server/node_modules/@clack/core/dist/index.mjs
99
99
  import { stdout, stdin } from "node:process";
@@ -2966,8 +2966,8 @@ async function run(app, inputs, context) {
2966
2966
  }
2967
2967
 
2968
2968
  // server/src/admin.ts
2969
- import fs9 from "node:fs";
2970
- import path9 from "node:path";
2969
+ import fs10 from "node:fs";
2970
+ import path10 from "node:path";
2971
2971
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
2972
2972
 
2973
2973
  // server/src/assets.ts
@@ -2991,20 +2991,20 @@ function dbDir(from = here()) {
2991
2991
  }
2992
2992
 
2993
2993
  // server/src/backups.ts
2994
+ import fs5 from "node:fs";
2995
+ import path5 from "node:path";
2996
+
2997
+ // server/src/sqlite.ts
2994
2998
  import fs4 from "node:fs";
2999
+ import os3 from "node:os";
2995
3000
  import path4 from "node:path";
3001
+ import { constants as C, DatabaseSync } from "node:sqlite";
2996
3002
 
2997
- // server/src/sqlite.ts
3003
+ // server/src/plugin.ts
3004
+ import { execFileSync as execFileSync2 } from "node:child_process";
2998
3005
  import fs3 from "node:fs";
2999
3006
  import os2 from "node:os";
3000
3007
  import path3 from "node:path";
3001
- import { constants as C, DatabaseSync } from "node:sqlite";
3002
-
3003
- // server/src/plugin.ts
3004
- import { execFileSync } from "node:child_process";
3005
- import fs2 from "node:fs";
3006
- import os from "node:os";
3007
- import path2 from "node:path";
3008
3008
  import { fileURLToPath as fileURLToPath2 } from "node:url";
3009
3009
 
3010
3010
  // server/src/codex-trust.ts
@@ -4110,6 +4110,160 @@ function hookTrust(hooksJson, pluginId, relativePath, platform, states) {
4110
4110
  return { hooks };
4111
4111
  }
4112
4112
 
4113
+ // server/src/git.ts
4114
+ import { execFileSync, spawn } from "node:child_process";
4115
+ import fs2 from "node:fs";
4116
+ import os from "node:os";
4117
+ import path2 from "node:path";
4118
+ var gitHome = () => path2.join(os.homedir(), ".sphica", "git");
4119
+ function gitEnv(extra = {}) {
4120
+ const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^GIT_/i.test(k)));
4121
+ return {
4122
+ ...env,
4123
+ GIT_ALLOW_PROTOCOL: "",
4124
+ GIT_NO_LAZY_FETCH: "1",
4125
+ GIT_TERMINAL_PROMPT: "0",
4126
+ GIT_NO_REPLACE_OBJECTS: "1",
4127
+ ...extra
4128
+ };
4129
+ }
4130
+ var gitOptions = (hooks = path2.join(gitHome(), "hooks")) => [
4131
+ "-c",
4132
+ "core.fsmonitor=",
4133
+ "-c",
4134
+ `core.hooksPath=${hooks}`,
4135
+ "-c",
4136
+ "core.quotePath=false",
4137
+ "--no-pager",
4138
+ "--no-optional-locks"
4139
+ ];
4140
+ var DIFF_OPTIONS = [
4141
+ "--no-color",
4142
+ "--no-ext-diff",
4143
+ "--no-textconv",
4144
+ "--ignore-submodules=dirty",
4145
+ "--submodule=short"
4146
+ ];
4147
+ function startDir() {
4148
+ const home = os.homedir();
4149
+ return fs2.statSync(home, { throwIfNoEntry: false })?.isDirectory() ? home : path2.dirname(process.execPath);
4150
+ }
4151
+ function run2(root, args, { max = 1024 * 1024, timeout = 1e4 } = {}) {
4152
+ return execFileSync("git", ["-C", root, ...gitOptions(), ...args], {
4153
+ cwd: startDir(),
4154
+ env: gitEnv(),
4155
+ maxBuffer: max,
4156
+ stdio: ["ignore", "pipe", "ignore"],
4157
+ timeout,
4158
+ killSignal: "SIGKILL"
4159
+ });
4160
+ }
4161
+ var text = (root, args, limits) => run2(root, args, limits).toString("utf8");
4162
+ var list = (out) => out.split("\x00").filter(Boolean);
4163
+ function revision(rev) {
4164
+ if (!rev || rev.startsWith("-") || /[\0\n]/.test(rev))
4165
+ throw new Error(`not a revision: ${JSON.stringify(rev)}`);
4166
+ return rev;
4167
+ }
4168
+ function objectId(oid) {
4169
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(oid))
4170
+ throw new Error(`not an object id: ${JSON.stringify(oid)}`);
4171
+ return oid;
4172
+ }
4173
+ var topLevel = (dir, limits) => text(dir, ["rev-parse", "--show-toplevel"], limits).trim();
4174
+ var commitOf = (root, rev, limits) => text(root, ["rev-parse", "--verify", "-q", `${revision(rev)}^{commit}`], limits).trim();
4175
+ function isAncestor(root, a2, b, limits) {
4176
+ try {
4177
+ run2(root, ["merge-base", "--is-ancestor", objectId(a2), objectId(b)], limits);
4178
+ return true;
4179
+ } catch {
4180
+ return false;
4181
+ }
4182
+ }
4183
+ var commitDiffNames = (root, a2, b, limits) => list(text(root, ["diff", ...DIFF_OPTIONS, "--name-only", "-z", objectId(a2), objectId(b), "--"], limits));
4184
+ function listFiles(root, kind, { pathspecs = [], ...limits } = {}) {
4185
+ const which = {
4186
+ tracked: ["--cached"],
4187
+ untracked: ["--others", "--exclude-standard"],
4188
+ "tracked-and-untracked": ["--cached", "--others", "--exclude-standard"],
4189
+ deleted: ["--deleted"]
4190
+ }[kind];
4191
+ return list(text(root, ["ls-files", "-z", ...which, "--", ...pathspecs], limits));
4192
+ }
4193
+ var originUrl = (root, limits) => text(root, ["remote", "get-url", "origin"], limits).trim();
4194
+ async function worktreeStatus(root, deadline) {
4195
+ const out = await inIsolation(root, [{ kind: "status" }], { deadline, max: 16 * 1024 * 1024 });
4196
+ return out?.[0] ?? null;
4197
+ }
4198
+ function workerFile() {
4199
+ const js = path2.join(import.meta.dirname, "git-worker.js");
4200
+ return fs2.existsSync(js) ? js : path2.join(import.meta.dirname, "git-worker.ts");
4201
+ }
4202
+ function inIsolation(root, ops, { deadline, max }) {
4203
+ return new Promise((resolve) => {
4204
+ let child;
4205
+ try {
4206
+ child = spawn(process.execPath, [workerFile()], {
4207
+ cwd: startDir(),
4208
+ stdio: ["pipe", "pipe", "ignore"],
4209
+ windowsHide: true,
4210
+ detached: process.platform !== "win32"
4211
+ });
4212
+ } catch {
4213
+ resolve(null);
4214
+ return;
4215
+ }
4216
+ const chunks = [];
4217
+ let size = 0;
4218
+ let done = false;
4219
+ const finish = (out) => {
4220
+ if (done)
4221
+ return;
4222
+ done = true;
4223
+ clearTimeout(timer);
4224
+ if (out === null) {
4225
+ try {
4226
+ if (process.platform !== "win32" && child.pid)
4227
+ process.kill(-child.pid, "SIGKILL");
4228
+ else
4229
+ child.kill("SIGKILL");
4230
+ } catch {
4231
+ child.kill("SIGKILL");
4232
+ }
4233
+ child.stdin?.destroy();
4234
+ child.stdout?.destroy();
4235
+ child.unref();
4236
+ }
4237
+ resolve(out);
4238
+ };
4239
+ const timer = setTimeout(() => finish(null), deadline);
4240
+ const cap = 6 * max * Math.max(1, ops.length * 2) + 64 * 1024;
4241
+ child.stdout?.on("data", (c) => {
4242
+ size += c.length;
4243
+ if (size > cap)
4244
+ finish(null);
4245
+ else
4246
+ chunks.push(c);
4247
+ });
4248
+ child.on("error", () => finish(null));
4249
+ child.on("close", () => {
4250
+ try {
4251
+ const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
4252
+ finish(result.ok ? result.out : null);
4253
+ } catch {
4254
+ finish(null);
4255
+ }
4256
+ });
4257
+ child.stdin?.on("error", () => finish(null));
4258
+ child.stdin?.end(JSON.stringify({
4259
+ root,
4260
+ ops,
4261
+ max,
4262
+ until: Date.now() + Math.floor(deadline * 0.8)
4263
+ }));
4264
+ });
4265
+ }
4266
+
4113
4267
  // server/src/panel.ts
4114
4268
  import { stripVTControlCharacters as stripVTControlCharacters2, styleText as styleText2 } from "node:util";
4115
4269
 
@@ -4140,8 +4294,8 @@ function singular(w) {
4140
4294
  return w.slice(0, -1);
4141
4295
  return w.endsWith("s") && !/(?:ss|us|is)$/.test(w) ? w.slice(0, -1) : w;
4142
4296
  }
4143
- function terms(text, parts = true) {
4144
- const nfkc = text.normalize("NFKC");
4297
+ function terms(text2, parts = true) {
4298
+ const nfkc = text2.normalize("NFKC");
4145
4299
  const norm = nfkc.toLowerCase();
4146
4300
  const out = [];
4147
4301
  const keep = (w) => {
@@ -4282,9 +4436,9 @@ var MAX_QUOTED = 4096;
4282
4436
  var BARE_HEAD = /[^\s"',;)]{1,256}/y;
4283
4437
  var BARE_REST = /[^\s"',;)]*/y;
4284
4438
  var NEXT_PARAM = /&[A-Za-z_][\w.-]*=/;
4285
- var bareAt = (re, text, at) => {
4439
+ var bareAt = (re, text2, at) => {
4286
4440
  re.lastIndex = at;
4287
- const v = re.exec(text)?.[0] ?? "";
4441
+ const v = re.exec(text2)?.[0] ?? "";
4288
4442
  const cut = v.search(NEXT_PARAM);
4289
4443
  return cut < 0 ? v : v.slice(0, cut);
4290
4444
  };
@@ -4297,49 +4451,49 @@ function secretValue(quoted, v) {
4297
4451
  return false;
4298
4452
  return !/\s/.test(v) || v.split(/\s+/).some((w) => /\d/.test(w) && /[A-Za-z]/.test(w));
4299
4453
  }
4300
- function maskFields(text) {
4454
+ function maskFields(text2) {
4301
4455
  let out = "";
4302
4456
  let last = 0;
4303
4457
  FIELD_NAME.lastIndex = 0;
4304
- for (let m = FIELD_NAME.exec(text);m; m = FIELD_NAME.exec(text)) {
4458
+ for (let m = FIELD_NAME.exec(text2);m; m = FIELD_NAME.exec(text2)) {
4305
4459
  const at = m.index + m[0].length;
4306
- const q = text[at];
4460
+ const q = text2[at];
4307
4461
  let quote = "";
4308
4462
  let value;
4309
4463
  if (q === '"' || q === "'") {
4310
- const close = text.indexOf(q, at + 1);
4464
+ const close = text2.indexOf(q, at + 1);
4311
4465
  if (close < 0 || close - at - 1 > MAX_QUOTED)
4312
4466
  continue;
4313
- value = text.slice(at + 1, close);
4467
+ value = text2.slice(at + 1, close);
4314
4468
  if (value.includes(`
4315
4469
  `))
4316
4470
  continue;
4317
4471
  quote = q;
4318
4472
  } else {
4319
- value = bareAt(BARE_HEAD, text, at);
4473
+ value = bareAt(BARE_HEAD, text2, at);
4320
4474
  }
4321
4475
  if (!secretValue(quote !== "", value))
4322
4476
  continue;
4323
4477
  if (!quote && value.length === 256)
4324
- value += bareAt(BARE_REST, text, at + 256);
4325
- out += `${text.slice(last, at)}${quote}[redacted]`;
4478
+ value += bareAt(BARE_REST, text2, at + 256);
4479
+ out += `${text2.slice(last, at)}${quote}[redacted]`;
4326
4480
  last = at + quote.length + value.length;
4327
4481
  FIELD_NAME.lastIndex = last;
4328
4482
  }
4329
- return out + text.slice(last);
4483
+ return out + text2.slice(last);
4330
4484
  }
4331
4485
  var MYSQL_COMMAND = /\bmysql(?:dump|admin)?\b(?:'[^'\n]*'|"[^"\n]*"|[^\n;&|\\'"]|\\\r?\n|\\(?!\r?\n))*/g;
4332
4486
  var MYSQL_PASSWORD = /(\s-p)(?:'[^'\n]*'|"[^"\n]*"|(?=[^\s-])\S+)/;
4333
4487
  var URL_CREDENTIALS = /\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?|https?):\/\/[^:\s/@]*:)[^\s/]*@([^@\s/?#]+)/g;
4334
4488
  var KEY_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY-----/g;
4335
4489
  var KEY_END = /-----END [A-Z ]*PRIVATE KEY-----/g;
4336
- function keyBlocks(text) {
4337
- const ends = [...text.matchAll(KEY_END)].map((m) => [m.index, m.index + m[0].length]);
4490
+ function keyBlocks(text2) {
4491
+ const ends = [...text2.matchAll(KEY_END)].map((m) => [m.index, m.index + m[0].length]);
4338
4492
  const out = [];
4339
4493
  let last = 0;
4340
4494
  let e = 0;
4341
4495
  if (ends.length > 0)
4342
- for (const m of text.matchAll(KEY_BEGIN)) {
4496
+ for (const m of text2.matchAll(KEY_BEGIN)) {
4343
4497
  const after = m.index + m[0].length;
4344
4498
  if (m.index < last)
4345
4499
  continue;
@@ -4353,17 +4507,17 @@ function keyBlocks(text) {
4353
4507
  }
4354
4508
  return out;
4355
4509
  }
4356
- function maskPrivateKeys(text) {
4510
+ function maskPrivateKeys(text2) {
4357
4511
  let out = "";
4358
4512
  let last = 0;
4359
- for (const [a2, b] of keyBlocks(text)) {
4360
- out += `${text.slice(last, a2)}[redacted: private key]`;
4513
+ for (const [a2, b] of keyBlocks(text2)) {
4514
+ out += `${text2.slice(last, a2)}[redacted: private key]`;
4361
4515
  last = b;
4362
4516
  }
4363
- return out + text.slice(last);
4517
+ return out + text2.slice(last);
4364
4518
  }
4365
- function mask(text) {
4366
- let out = maskFields(maskPrivateKeys(text).replace(URL_CREDENTIALS, "$1[redacted]@$2").replace(AUTH_HEADER, "$1[redacted]").replace(HEADER_BEARER, "$1[redacted]").replace(ENV_ASSIGN, "$1$2[redacted]")).replace(MYSQL_COMMAND, (command) => command.replace(MYSQL_PASSWORD, "$1[redacted]"));
4519
+ function mask(text2) {
4520
+ let out = maskFields(maskPrivateKeys(text2).replace(URL_CREDENTIALS, "$1[redacted]@$2").replace(AUTH_HEADER, "$1[redacted]").replace(HEADER_BEARER, "$1[redacted]").replace(ENV_ASSIGN, "$1$2[redacted]")).replace(MYSQL_COMMAND, (command) => command.replace(MYSQL_PASSWORD, "$1[redacted]"));
4367
4521
  for (const [re, what] of SECRETS)
4368
4522
  out = out.replace(re, `[redacted: ${what}]`);
4369
4523
  return out;
@@ -4393,28 +4547,28 @@ var MARKS = {
4393
4547
  };
4394
4548
  var colored = () => Boolean(process.stdout.isTTY && process.stderr.isTTY);
4395
4549
  var mark = (m) => colored() ? styleText2(MARKS[m][1], MARKS[m][0]) : MARKS[m][0];
4396
- var faint = (text) => colored() ? styleText2("dim", text) : text;
4397
- var caution = (text) => colored() ? styleText2("yellow", text) : text;
4398
- var title = (text) => `✦ ${text}`;
4399
- var rule = (text) => text.split(`
4550
+ var faint = (text2) => colored() ? styleText2("dim", text2) : text2;
4551
+ var caution = (text2) => colored() ? styleText2("yellow", text2) : text2;
4552
+ var title = (text2) => `✦ ${text2}`;
4553
+ var rule = (text2) => text2.split(`
4400
4554
  `).map((line) => line ? `│ ${line}` : "│").join(`
4401
4555
  `);
4402
- var foot = (text) => `╰─ ${text}`;
4556
+ var foot = (text2) => `╰─ ${text2}`;
4403
4557
  var panel = (head2, lines, end) => [title(head2), ...lines.map(rule), foot(end)].join(`
4404
4558
  `);
4405
4559
  var STRING_SEQUENCE = /\u001b[\]P_^X][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g;
4406
4560
  var plain = (s) => visible(stripVTControlCharacters2(s.replace(STRING_SEQUENCE, "")).replace(/\r\n?|[\v\f\u0085\p{Zl}\p{Zp}]/gu, `
4407
4561
  `).replace(/(?![\t\n])\p{Cc}/gu, ""));
4408
4562
  var inline = (s) => plain(s).replace(/[\n\t]+/g, " ");
4409
- var width = (text) => [...text].reduce((w, c) => w + ((c.codePointAt(0) ?? 0) > 255 ? 2 : 1), 0);
4410
- var pad = (text, to) => text + " ".repeat(Math.max(1, to - width(text)));
4563
+ var width = (text2) => [...text2].reduce((w, c) => w + ((c.codePointAt(0) ?? 0) > 255 ? 2 : 1), 0);
4564
+ var pad = (text2, to) => text2 + " ".repeat(Math.max(1, to - width(text2)));
4411
4565
 
4412
4566
  // server/src/plugin.ts
4413
- var MANIFEST = path2.join(".claude-plugin", "plugin.json");
4567
+ var MANIFEST = path3.join(".claude-plugin", "plugin.json");
4414
4568
  var PACKAGE = "package.json";
4415
4569
  function versionAt(root) {
4416
4570
  try {
4417
- const m = JSON.parse(fs2.readFileSync(path2.join(root, MANIFEST), "utf8"));
4571
+ const m = JSON.parse(fs3.readFileSync(path3.join(root, MANIFEST), "utf8"));
4418
4572
  return m.name === "sphica" && typeof m.version === "string" ? m.version : null;
4419
4573
  } catch {
4420
4574
  return null;
@@ -4422,18 +4576,18 @@ function versionAt(root) {
4422
4576
  }
4423
4577
  function packageVersionAt(root) {
4424
4578
  try {
4425
- const m = JSON.parse(fs2.readFileSync(path2.join(root, PACKAGE), "utf8"));
4579
+ const m = JSON.parse(fs3.readFileSync(path3.join(root, PACKAGE), "utf8"));
4426
4580
  return m.name === "sphica" && typeof m.version === "string" ? m.version : null;
4427
4581
  } catch {
4428
4582
  return null;
4429
4583
  }
4430
4584
  }
4431
- var here2 = path2.dirname(fileURLToPath2(import.meta.url));
4432
- var ROOT = [path2.join(here2, ".."), path2.join(here2, "..", "..", "plugin")].find((r2) => versionAt(r2) !== null) ?? path2.join(here2, "..");
4585
+ var here2 = path3.dirname(fileURLToPath2(import.meta.url));
4586
+ var ROOT = [path3.join(here2, ".."), path3.join(here2, "..", "..", "plugin")].find((r2) => versionAt(r2) !== null) ?? path3.join(here2, "..");
4433
4587
  function rootState(root) {
4434
- if (!fs2.existsSync(path2.join(root, MANIFEST)))
4588
+ if (!fs3.existsSync(path3.join(root, MANIFEST)))
4435
4589
  return "gone";
4436
- if (fs2.existsSync(path2.join(root, ".orphaned_at")))
4590
+ if (fs3.existsSync(path3.join(root, ".orphaned_at")))
4437
4591
  return "orphaned";
4438
4592
  return "ok";
4439
4593
  }
@@ -4451,24 +4605,21 @@ var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
4451
4605
  var GENERATED = /^(dist|db)\/|^THIRD_PARTY_NOTICES\.md$|^README\.md$/;
4452
4606
  var JUNK = /^\.DS_Store$|\.sw[a-p]$|~$/;
4453
4607
  function distributed(root, tracked) {
4454
- const walk = (dir) => fs2.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
4608
+ const walk = (dir) => fs3.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
4455
4609
  if (dir === root && HOST_MARKS.has(e.name))
4456
4610
  return [];
4457
- const abs = path2.join(dir, e.name);
4458
- return e.isDirectory() ? walk(abs) : e.isFile() ? [path2.relative(root, abs)] : [];
4611
+ const abs = path3.join(dir, e.name);
4612
+ return e.isDirectory() ? walk(abs) : e.isFile() ? [path3.relative(root, abs)] : [];
4459
4613
  });
4460
4614
  let rels;
4461
4615
  if (tracked) {
4462
4616
  try {
4463
- rels = execFileSync("git", ["-C", root, "ls-files", "-z"], {
4464
- encoding: "utf8",
4465
- stdio: ["ignore", "pipe", "ignore"]
4466
- }).split("\x00").filter((rel) => rel && fs2.existsSync(path2.join(root, rel)));
4467
- rels = [...rels, ...walk(root).filter((rel) => GENERATED.test(rel) && !JUNK.test(path2.basename(rel)))];
4617
+ rels = listFiles(root, "tracked").filter((rel) => fs3.existsSync(path3.join(root, rel)));
4618
+ rels = [...rels, ...walk(root).filter((rel) => GENERATED.test(rel) && !JUNK.test(path3.basename(rel)))];
4468
4619
  } catch {}
4469
4620
  }
4470
4621
  rels ??= walk(root);
4471
- return new Map(rels.filter((rel) => path2.basename(rel) !== ".DS_Store").map((rel) => [rel, path2.join(root, rel)]));
4622
+ return new Map(rels.filter((rel) => path3.basename(rel) !== ".DS_Store").map((rel) => [rel, path3.join(root, rel)]));
4472
4623
  }
4473
4624
  function differingFiles(a2, b, { tracked = false } = {}) {
4474
4625
  const x = distributed(a2, tracked);
@@ -4476,7 +4627,7 @@ function differingFiles(a2, b, { tracked = false } = {}) {
4476
4627
  return [...new Set([...x.keys(), ...y2.keys()])].filter((rel) => {
4477
4628
  const p = x.get(rel);
4478
4629
  const q = y2.get(rel);
4479
- return !p || !q || !fs2.readFileSync(p).equals(fs2.readFileSync(q));
4630
+ return !p || !q || !fs3.readFileSync(p).equals(fs3.readFileSync(q));
4480
4631
  }).sort();
4481
4632
  }
4482
4633
  function parsePs(out) {
@@ -4492,11 +4643,11 @@ function parsePs(out) {
4492
4643
  }
4493
4644
  function cwdOf(pid) {
4494
4645
  try {
4495
- const link = fs2.readlinkSync(`/proc/${pid}/cwd`);
4646
+ const link = fs3.readlinkSync(`/proc/${pid}/cwd`);
4496
4647
  return { dir: link.replace(/ \(deleted\)$/, ""), replaced: link.endsWith(" (deleted)") };
4497
4648
  } catch {}
4498
4649
  try {
4499
- const out = execFileSync("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fin"], {
4650
+ const out = execFileSync2("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fin"], {
4500
4651
  encoding: "utf8",
4501
4652
  stdio: ["ignore", "pipe", "ignore"],
4502
4653
  timeout: 1e4
@@ -4508,7 +4659,7 @@ function cwdOf(pid) {
4508
4659
  return null;
4509
4660
  let now;
4510
4661
  try {
4511
- now = String(fs2.statSync(dir).ino);
4662
+ now = String(fs3.statSync(dir).ino);
4512
4663
  } catch {}
4513
4664
  const held = field("i");
4514
4665
  return { dir, replaced: now !== undefined && held !== undefined && now !== held };
@@ -4520,15 +4671,15 @@ var CLAUDE_CODE_MIN = "2.1.139";
4520
4671
  var CACHED = /\/plugins\/cache\/[^/]+\/sphica\/[^/]+$/;
4521
4672
  var unknown = (i2) => typeof i2 === "object" && i2 !== null && ("unknown" in i2);
4522
4673
  function npmCli(execPath, platform) {
4523
- const dir = path2.dirname(execPath);
4524
- const at = platform === "win32" ? path2.join(dir, "node_modules", "npm", "bin", "npm-cli.js") : path2.resolve(dir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js");
4525
- return fs2.existsSync(at) ? at : null;
4674
+ const dir = path3.dirname(execPath);
4675
+ const at = platform === "win32" ? path3.join(dir, "node_modules", "npm", "bin", "npm-cli.js") : path3.resolve(dir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js");
4676
+ return fs3.existsSync(at) ? at : null;
4526
4677
  }
4527
4678
  function findExe(name, pathEnv, platform) {
4528
- const sep = platform === "win32" ? ";" : path2.delimiter;
4679
+ const sep = platform === "win32" ? ";" : path3.delimiter;
4529
4680
  for (const dir of pathEnv.split(sep).filter(Boolean)) {
4530
- const at = path2.join(dir, `${name}.exe`);
4531
- if (fs2.existsSync(at))
4681
+ const at = path3.join(dir, `${name}.exe`);
4682
+ if (fs3.existsSync(at))
4532
4683
  return at;
4533
4684
  }
4534
4685
  return null;
@@ -4539,19 +4690,19 @@ function observe(cwdRoot, platform = process.platform, env = process.env, execPa
4539
4690
  packageVersion: packageVersionAt(root),
4540
4691
  root
4541
4692
  });
4542
- const repository = [path2.dirname(ROOT), cwdRoot].filter((d) => fs2.existsSync(path2.join(d, ".claude-plugin", "marketplace.json"))).map((d) => install(path2.join(d, "plugin"))).find((r2) => r2.version !== null) ?? null;
4693
+ const repository = [path3.dirname(ROOT), cwdRoot].filter((d) => fs3.existsSync(path3.join(d, ".claude-plugin", "marketplace.json"))).map((d) => install(path3.join(d, "plugin"))).find((r2) => r2.version !== null) ?? null;
4543
4694
  let claude;
4544
4695
  const claudeExe = platform === "win32" ? findExe("claude", env.PATH ?? env.Path ?? "", platform) : "claude";
4545
4696
  if (!claudeExe)
4546
4697
  claude = { unknown: "no claude.exe on PATH (an npm install puts claude.cmd there)" };
4547
4698
  else
4548
4699
  try {
4549
- const list = JSON.parse(execFileSync(claudeExe, ["plugin", "list", "--json"], {
4700
+ const list2 = JSON.parse(execFileSync2(claudeExe, ["plugin", "list", "--json"], {
4550
4701
  encoding: "utf8",
4551
4702
  stdio: ["ignore", "pipe", "ignore"],
4552
4703
  timeout: 30000
4553
4704
  }));
4554
- const m = list.find((p) => p.id.startsWith("sphica@") && p.scope === "user");
4705
+ const m = list2.find((p) => p.id.startsWith("sphica@") && p.scope === "user");
4555
4706
  claude = m?.installPath ? { version: m.version ?? null, root: m.installPath } : null;
4556
4707
  } catch {
4557
4708
  claude = { unknown: "claude plugin list --json failed" };
@@ -4559,23 +4710,23 @@ function observe(cwdRoot, platform = process.platform, env = process.env, execPa
4559
4710
  let claudeVersion;
4560
4711
  if (claudeExe)
4561
4712
  try {
4562
- const out = execFileSync(claudeExe, ["--version"], {
4713
+ const out = execFileSync2(claudeExe, ["--version"], {
4563
4714
  encoding: "utf8",
4564
4715
  stdio: ["ignore", "pipe", "ignore"],
4565
4716
  timeout: 1e4
4566
4717
  });
4567
4718
  claudeVersion = /^\s*(\d+\.\d+\.\d+)/.exec(out)?.[1];
4568
4719
  } catch {}
4569
- let codexHome = env.CODEX_HOME ?? path2.join(os.homedir(), ".codex");
4720
+ let codexHome = env.CODEX_HOME ?? path3.join(os2.homedir(), ".codex");
4570
4721
  try {
4571
- codexHome = fs2.realpathSync(codexHome);
4722
+ codexHome = fs3.realpathSync(codexHome);
4572
4723
  } catch {}
4573
- const codexCache = path2.join(codexHome, "plugins", "cache");
4724
+ const codexCache = path3.join(codexHome, "plugins", "cache");
4574
4725
  const codex = [];
4575
4726
  const markets = [];
4576
4727
  for (const market of safeDirs(codexCache)) {
4577
- for (const v of safeDirs(path2.join(codexCache, market, "sphica"))) {
4578
- codex.push(install(path2.join(codexCache, market, "sphica", v)));
4728
+ for (const v of safeDirs(path3.join(codexCache, market, "sphica"))) {
4729
+ codex.push(install(path3.join(codexCache, market, "sphica", v)));
4579
4730
  markets.push(market);
4580
4731
  }
4581
4732
  }
@@ -4589,25 +4740,25 @@ function observe(cwdRoot, platform = process.platform, env = process.env, execPa
4589
4740
  running = { unknown: "not checked on Windows" };
4590
4741
  else
4591
4742
  try {
4592
- const out = execFileSync("ps", ["-U", String(process.getuid?.()), "-o", "pid=,lstart=,args="], {
4743
+ const out = execFileSync2("ps", ["-U", String(process.getuid?.()), "-o", "pid=,lstart=,args="], {
4593
4744
  encoding: "utf8",
4594
4745
  stdio: ["ignore", "pipe", "ignore"],
4595
4746
  env: { ...process.env, LC_ALL: "C" },
4596
4747
  timeout: 1e4
4597
4748
  });
4598
4749
  running = parsePs(out).flatMap((p) => {
4599
- const cwd = path2.isAbsolute(p.script) ? { dir: "/", replaced: false } : cwdOf(p.pid);
4750
+ const cwd = path3.isAbsolute(p.script) ? { dir: "/", replaced: false } : cwdOf(p.pid);
4600
4751
  if (!cwd)
4601
4752
  return [{ pid: p.pid, started: p.started, root: null, version: null }];
4602
- const root = path2.dirname(path2.dirname(path2.resolve(cwd.dir, p.script)));
4753
+ const root = path3.dirname(path3.dirname(path3.resolve(cwd.dir, p.script)));
4603
4754
  const cached = CACHED.test(root);
4604
4755
  const now = versionAt(root);
4605
4756
  if (now === null && !cached)
4606
4757
  return [];
4607
- let version2 = cwd.replaced || now === null ? cached ? path2.basename(root) : null : now;
4758
+ let version2 = cwd.replaced || now === null ? cached ? path3.basename(root) : null : now;
4608
4759
  if (!cached && version2 !== null) {
4609
4760
  try {
4610
- const touched = Math.max(...[path2.join("dist", "mcp.js"), MANIFEST].map((f) => fs2.statSync(path2.join(root, f)).mtimeMs));
4761
+ const touched = Math.max(...[path3.join("dist", "mcp.js"), MANIFEST].map((f) => fs3.statSync(path3.join(root, f)).mtimeMs));
4611
4762
  if (touched > p.started.getTime())
4612
4763
  version2 = null;
4613
4764
  } catch {
@@ -4626,13 +4777,13 @@ function observe(cwdRoot, platform = process.platform, env = process.env, execPa
4626
4777
  else
4627
4778
  try {
4628
4779
  const [cmd, args] = cli ? [execPath, [cli, "root", "-g"]] : ["npm", ["root", "-g"]];
4629
- const out = execFileSync(cmd, args, {
4780
+ const out = execFileSync2(cmd, args, {
4630
4781
  encoding: "utf8",
4631
4782
  stdio: ["ignore", "pipe", "ignore"],
4632
4783
  timeout: 1e4
4633
4784
  });
4634
- const at = path2.join(out.trim(), "sphica");
4635
- if (fs2.existsSync(at))
4785
+ const at = path3.join(out.trim(), "sphica");
4786
+ if (fs3.existsSync(at))
4636
4787
  global = install(at);
4637
4788
  } catch {
4638
4789
  global = { unknown: "npm root -g failed" };
@@ -4655,13 +4806,13 @@ function codexCommand(platform, env, execPath) {
4655
4806
  const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
4656
4807
  for (const dir of (env.PATH ?? env.Path ?? "").split(";").filter(Boolean))
4657
4808
  for (const ext of exts) {
4658
- const at = path2.join(dir, `codex${ext.toLowerCase()}`);
4659
- if (!fs2.existsSync(at))
4809
+ const at = path3.join(dir, `codex${ext.toLowerCase()}`);
4810
+ if (!fs3.existsSync(at))
4660
4811
  continue;
4661
4812
  if (ext.toLowerCase() === ".exe")
4662
4813
  return [at, ["--version"]];
4663
- const js = path2.join(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
4664
- return fs2.existsSync(js) ? [execPath, [js, "--version"]] : null;
4814
+ const js = path3.join(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
4815
+ return fs3.existsSync(js) ? [execPath, [js, "--version"]] : null;
4665
4816
  }
4666
4817
  return null;
4667
4818
  }
@@ -4671,7 +4822,7 @@ function codexHookTrust(root, pluginId, codexHome, platform, env, execPath) {
4671
4822
  return { unknown: "no codex.exe, or codex.js beside codex.cmd, on PATH" };
4672
4823
  let version2;
4673
4824
  try {
4674
- const out = execFileSync(command[0], command[1], {
4825
+ const out = execFileSync2(command[0], command[1], {
4675
4826
  encoding: "utf8",
4676
4827
  env,
4677
4828
  stdio: ["ignore", "pipe", "ignore"],
@@ -4689,26 +4840,26 @@ function codexHookTrust(root, pluginId, codexHome, platform, env, execPath) {
4689
4840
  };
4690
4841
  let file;
4691
4842
  try {
4692
- const manifest = JSON.parse(fs2.readFileSync(path2.join(root, ".codex-plugin", "plugin.json"), "utf8"));
4843
+ const manifest = JSON.parse(fs3.readFileSync(path3.join(root, ".codex-plugin", "plugin.json"), "utf8"));
4693
4844
  if (typeof manifest.hooks !== "string")
4694
4845
  return { unknown: "the Codex plugin manifest names no hooks file" };
4695
- file = path2.resolve(root, manifest.hooks);
4846
+ file = path3.resolve(root, manifest.hooks);
4696
4847
  } catch {
4697
4848
  return { unknown: "the Codex plugin manifest could not be read" };
4698
4849
  }
4699
- const relative = path2.relative(root, file);
4700
- if (!relative || relative.startsWith("..") || path2.isAbsolute(relative))
4850
+ const relative = path3.relative(root, file);
4851
+ if (!relative || relative.startsWith("..") || path3.isAbsolute(relative))
4701
4852
  return { unknown: "the hooks file is outside the plugin" };
4702
4853
  let hooksJson;
4703
4854
  try {
4704
- hooksJson = fs2.readFileSync(file, "utf8");
4855
+ hooksJson = fs3.readFileSync(file, "utf8");
4705
4856
  } catch {
4706
4857
  return { unknown: "the hooks file could not be read" };
4707
4858
  }
4708
- const config = path2.join(codexHome, "config.toml");
4859
+ const config = path3.join(codexHome, "config.toml");
4709
4860
  let toml;
4710
4861
  try {
4711
- toml = fs2.readFileSync(config, "utf8");
4862
+ toml = fs3.readFileSync(config, "utf8");
4712
4863
  } catch (e) {
4713
4864
  if (e.code !== "ENOENT")
4714
4865
  return { unknown: "config.toml could not be read" };
@@ -4717,12 +4868,12 @@ function codexHookTrust(root, pluginId, codexHome, platform, env, execPath) {
4717
4868
  const states = readHookStates(toml);
4718
4869
  if (!(states instanceof Map))
4719
4870
  return states;
4720
- const trust = hookTrust(hooksJson, pluginId, relative.split(path2.sep).join("/"), platform, states);
4871
+ const trust = hookTrust(hooksJson, pluginId, relative.split(path3.sep).join("/"), platform, states);
4721
4872
  return "unknown" in trust ? trust : { config, hooks: trust.hooks };
4722
4873
  }
4723
4874
  function safeDirs(dir) {
4724
4875
  try {
4725
- return fs2.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
4876
+ return fs3.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
4726
4877
  } catch {
4727
4878
  return [];
4728
4879
  }
@@ -4747,14 +4898,14 @@ function report(s, now = new Date) {
4747
4898
  const issues = [];
4748
4899
  const failures = [];
4749
4900
  const todo = new Set;
4750
- const home = os.homedir();
4901
+ const home = os2.homedir();
4751
4902
  const short = (p) => p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p;
4752
- const say = (m, label, text) => {
4903
+ const say = (m, label, text2) => {
4753
4904
  if (m === "warn" || m === "fail")
4754
4905
  issues.push(label);
4755
4906
  if (m === "fail")
4756
4907
  failures.push(label);
4757
- lines.push(` ${mark(m)} ${pad(label, 19)}${text}`);
4908
+ lines.push(` ${mark(m)} ${pad(label, 19)}${text2}`);
4758
4909
  };
4759
4910
  const row = (label, i2, note, aside = "", m = note ? "warn" : "ok") => {
4760
4911
  const version2 = pad(i2?.version ?? "unknown", 9);
@@ -4784,7 +4935,7 @@ ${indent}${caution(note)}` : ""}`);
4784
4935
  say("none", "npm i -g CLI", `unknown (${s.global.unknown})`);
4785
4936
  else if (s.global === null)
4786
4937
  say("none", "npm i -g CLI", "not installed");
4787
- else if (s.global && path2.resolve(s.global.root) !== path2.resolve(s.cli.root)) {
4938
+ else if (s.global && path3.resolve(s.global.root) !== path3.resolve(s.cli.root)) {
4788
4939
  const { note, update } = packageAgainst(s.global);
4789
4940
  if (update)
4790
4941
  todo.add("global");
@@ -4794,7 +4945,7 @@ ${indent}${caution(note)}` : ""}`);
4794
4945
  const base = s.repository ?? (s.cli.version ? s.cli : null);
4795
4946
  const baseName = s.repository ? "repository" : "this CLI";
4796
4947
  const against = (i2) => {
4797
- if (!fs2.existsSync(i2.root))
4948
+ if (!fs3.existsSync(i2.root))
4798
4949
  return { note: "The install directory is gone. Skill paths are invalid too", update: true };
4799
4950
  if (!base?.version || !i2.version)
4800
4951
  return {};
@@ -4806,7 +4957,7 @@ ${indent}${caution(note)}` : ""}`);
4806
4957
  note: s.repository ? `newer than the repository (${base.version}); the repository checkout is old` : `newer than this CLI (${base.version}). Match the CLI with \`npm i -g sphica@${i2.version}\``
4807
4958
  };
4808
4959
  }
4809
- if (path2.resolve(i2.root) === path2.resolve(base.root))
4960
+ if (path3.resolve(i2.root) === path3.resolve(base.root))
4810
4961
  return {};
4811
4962
  const diff = differingFiles(base.root, i2.root, { tracked: Boolean(s.repository) });
4812
4963
  if (!diff.length)
@@ -4867,7 +5018,7 @@ ${indent}${caution(note)}` : ""}`);
4867
5018
  }
4868
5019
  const x = s.codex.length === 1 ? s.codex[0] : undefined;
4869
5020
  if (!base && s.claude && !unknown(s.claude) && x && s.claude.version === x.version) {
4870
- if (fs2.existsSync(s.claude.root) && differingFiles(s.claude.root, x.root).length) {
5021
+ if (fs3.existsSync(s.claude.root) && differingFiles(s.claude.root, x.root).length) {
4871
5022
  say("warn", "Claude Code and Codex", "same version, different contents");
4872
5023
  }
4873
5024
  }
@@ -4912,15 +5063,15 @@ ${indent}${caution(note)}` : ""}`);
4912
5063
  // server/src/sqlite.ts
4913
5064
  var SCHEMA_GENERATION = 2;
4914
5065
  var SCHEMA_REVISION = 12;
4915
- var sphicaHome = () => process.env.SPHICA_HOME || path3.join(os2.homedir(), ".sphica");
4916
- var dbFile = () => process.env.SPHICA_DB || path3.join(sphicaHome(), "sphica.db");
5066
+ var sphicaHome = () => process.env.SPHICA_HOME || path4.join(os3.homedir(), ".sphica");
5067
+ var dbFile = () => process.env.SPHICA_DB || path4.join(sphicaHome(), "sphica.db");
4917
5068
  function requireRuntime() {
4918
5069
  const proto = DatabaseSync.prototype;
4919
5070
  if (typeof proto.setAuthorizer !== "function" || typeof proto.enableDefensive !== "function")
4920
5071
  throw new Error(`Sphica needs Node 24.15 or later (this is ${process.version}). Upgrade Node.`);
4921
5072
  }
4922
5073
  function requireFile(file) {
4923
- if (!fs3.existsSync(file))
5074
+ if (!fs4.existsSync(file))
4924
5075
  throw new Error(`No database at ${file}. Create it with \`sphica init\`.`);
4925
5076
  }
4926
5077
  function prepare(raw, check, busyMs = 5000) {
@@ -4999,22 +5150,22 @@ function connectReader(file = dbFile()) {
4999
5150
  }
5000
5151
 
5001
5152
  // server/src/backups.ts
5002
- var backupDir = (file = dbFile()) => path4.join(path4.dirname(file), "backups");
5003
- var stem = (file) => path4.basename(file).replace(/\.db$/, "");
5153
+ var backupDir = (file = dbFile()) => path5.join(path5.dirname(file), "backups");
5154
+ var stem = (file) => path5.basename(file).replace(/\.db$/, "");
5004
5155
  var pattern = (file) => new RegExp(`^${stem(file).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.rev\\d+\\.(\\d{8}T\\d{9}Z)\\.\\d+\\.db$`);
5005
- var backupPath = (file, from) => path4.join(backupDir(file), `${stem(file)}.rev${from}.${new Date().toISOString().replace(/[-:.]/g, "")}.${process.pid}.db`);
5156
+ var backupPath = (file, from) => path5.join(backupDir(file), `${stem(file)}.rev${from}.${new Date().toISOString().replace(/[-:.]/g, "")}.${process.pid}.db`);
5006
5157
  function backups(file = dbFile()) {
5007
5158
  const dir = backupDir(file);
5008
- if (!fs4.existsSync(dir))
5159
+ if (!fs5.existsSync(dir))
5009
5160
  return [];
5010
5161
  const named = pattern(file);
5011
- return fs4.readdirSync(dir).filter((f) => named.test(f)).sort((a2, b) => (named.exec(b)?.[1] ?? "").localeCompare(named.exec(a2)?.[1] ?? "") || b.localeCompare(a2)).map((f) => path4.join(dir, f));
5162
+ return fs5.readdirSync(dir).filter((f) => named.test(f)).sort((a2, b) => (named.exec(b)?.[1] ?? "").localeCompare(named.exec(a2)?.[1] ?? "") || b.localeCompare(a2)).map((f) => path5.join(dir, f));
5012
5163
  }
5013
5164
 
5014
5165
  // server/src/capture.ts
5015
- import { spawn } from "node:child_process";
5016
- import fs8 from "node:fs";
5017
- import path8 from "node:path";
5166
+ import { spawn as spawn2 } from "node:child_process";
5167
+ import fs9 from "node:fs";
5168
+ import path9 from "node:path";
5018
5169
 
5019
5170
  // server/node_modules/kysely/dist/util/object-utils.js
5020
5171
  function isUndefined(obj) {
@@ -6043,16 +6194,16 @@ function parseReferentialBinaryOperation(left, operator, right) {
6043
6194
  function parseFilterObject(obj, combinator) {
6044
6195
  return parseFilterList(Object.entries(obj).filter(([, v]) => !isUndefined(v)).map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? "is" : "=", v)), combinator);
6045
6196
  }
6046
- function parseFilterList(list, combinator, withParens = true) {
6197
+ function parseFilterList(list2, combinator, withParens = true) {
6047
6198
  const combine = combinator === "and" ? AndNode.create : OrNode.create;
6048
- if (list.length === 0) {
6199
+ if (list2.length === 0) {
6049
6200
  return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0));
6050
6201
  }
6051
- let node = toOperationNode(list[0]);
6052
- for (let i2 = 1;i2 < list.length; ++i2) {
6053
- node = combine(node, toOperationNode(list[i2]));
6202
+ let node = toOperationNode(list2[0]);
6203
+ for (let i2 = 1;i2 < list2.length; ++i2) {
6204
+ node = combine(node, toOperationNode(list2[i2]));
6054
6205
  }
6055
- if (list.length > 1 && withParens) {
6206
+ if (list2.length > 1 && withParens) {
6056
6207
  return ParensNode.create(node);
6057
6208
  }
6058
6209
  return node;
@@ -6789,8 +6940,8 @@ var DefaultInsertValueNode = freeze({
6789
6940
  // server/node_modules/kysely/dist/parser/insert-values-parser.js
6790
6941
  function parseInsertExpression(arg) {
6791
6942
  const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg;
6792
- const list = isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]);
6793
- return parseInsertColumnsAndValues(list);
6943
+ const list2 = isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]);
6944
+ return parseInsertColumnsAndValues(list2);
6794
6945
  }
6795
6946
  function parseInsertColumnsAndValues(rows) {
6796
6947
  const columns = parseColumnNamesAndIndexes(rows);
@@ -8093,11 +8244,11 @@ class OperationNodeTransformer {
8093
8244
  transformNodeImpl(node, queryId) {
8094
8245
  return this.#transformers[node.kind](node, queryId);
8095
8246
  }
8096
- transformNodeList(list, queryId) {
8097
- if (!list) {
8098
- return list;
8247
+ transformNodeList(list2, queryId) {
8248
+ if (!list2) {
8249
+ return list2;
8099
8250
  }
8100
- return freeze(list.map((node) => this.transformNode(node, queryId)));
8251
+ return freeze(list2.map((node) => this.transformNode(node, queryId)));
8101
8252
  }
8102
8253
  transformSelectQuery(node, queryId) {
8103
8254
  return {
@@ -16088,7 +16239,7 @@ function connectWriter(role, file = dbFile(), create = false, busyMs) {
16088
16239
  const raw = new DatabaseSync2(file);
16089
16240
  try {
16090
16241
  prepare(raw, create ? "none" : role === "ingest" || role === "forget" ? "revision" : "generation", busyMs);
16091
- raw.function("sphica_terms", { deterministic: true }, (text) => terms(String(text ?? "")).join(" "));
16242
+ raw.function("sphica_terms", { deterministic: true }, (text2) => terms(String(text2 ?? "")).join(" "));
16092
16243
  } catch (e) {
16093
16244
  raw.close();
16094
16245
  throw e;
@@ -16123,17 +16274,16 @@ function openWriter(role, file = dbFile(), busyMs) {
16123
16274
  var sessionId = (projectId, host, externalId) => uuidFrom(String(projectId), host, externalId);
16124
16275
 
16125
16276
  // server/src/project.ts
16126
- import { execFileSync as execFileSync2 } from "node:child_process";
16127
- import fs6 from "node:fs";
16128
- import path6 from "node:path";
16277
+ import fs7 from "node:fs";
16278
+ import path7 from "node:path";
16129
16279
 
16130
16280
  // server/src/anchors.ts
16131
- import path5 from "node:path";
16281
+ import path6 from "node:path";
16132
16282
  var MAX_BYTES = 2 * 1024 * 1024;
16133
- var leaves = (rel) => rel === ".." || rel.startsWith(`..${path5.sep}`) || path5.isAbsolute(rel);
16283
+ var leaves = (rel) => rel === ".." || rel.startsWith(`..${path6.sep}`) || path6.isAbsolute(rel);
16134
16284
 
16135
16285
  // server/src/file-lock.ts
16136
- import fs5 from "node:fs";
16286
+ import fs6 from "node:fs";
16137
16287
  var WAIT_MS = 5000;
16138
16288
  var POLL_MS = 40;
16139
16289
  var TRIES = 5;
@@ -16156,7 +16306,7 @@ function retryBusy(op) {
16156
16306
  function heldBy(lock) {
16157
16307
  let holder = 0;
16158
16308
  try {
16159
- holder = Number(fs5.readFileSync(lock, "utf8").trim()) || 0;
16309
+ holder = Number(fs6.readFileSync(lock, "utf8").trim()) || 0;
16160
16310
  } catch {}
16161
16311
  if (holder <= 0)
16162
16312
  return `${lock} is held by another process. Run this again when it finishes.`;
@@ -16175,7 +16325,7 @@ function withFileLock(lock, fn, waitMs = WAIT_MS) {
16175
16325
  let fd = null;
16176
16326
  let refused = null;
16177
16327
  try {
16178
- fd = fs5.openSync(lock, "wx");
16328
+ fd = fs6.openSync(lock, "wx");
16179
16329
  } catch (e) {
16180
16330
  const code = e.code;
16181
16331
  if (code === "EPERM" || code === "EACCES" || code === "EBUSY")
@@ -16186,13 +16336,13 @@ function withFileLock(lock, fn, waitMs = WAIT_MS) {
16186
16336
  if (fd !== null) {
16187
16337
  try {
16188
16338
  try {
16189
- fs5.writeFileSync(fd, mine);
16339
+ fs6.writeFileSync(fd, mine);
16190
16340
  } finally {
16191
- fs5.closeSync(fd);
16341
+ fs6.closeSync(fd);
16192
16342
  }
16193
16343
  } catch (e) {
16194
16344
  try {
16195
- retryBusy(() => fs5.rmSync(lock, { force: true }));
16345
+ retryBusy(() => fs6.rmSync(lock, { force: true }));
16196
16346
  } catch {}
16197
16347
  throw e;
16198
16348
  }
@@ -16219,7 +16369,7 @@ function release(lock, mine) {
16219
16369
  let held = "";
16220
16370
  try {
16221
16371
  retryBusy(() => {
16222
- held = fs5.readFileSync(lock, "utf8");
16372
+ held = fs6.readFileSync(lock, "utf8");
16223
16373
  });
16224
16374
  } catch (e) {
16225
16375
  if (e.code === "ENOENT")
@@ -16229,32 +16379,32 @@ function release(lock, mine) {
16229
16379
  if (held !== mine)
16230
16380
  return;
16231
16381
  try {
16232
- retryBusy(() => fs5.rmSync(lock, { force: true }));
16382
+ retryBusy(() => fs6.rmSync(lock, { force: true }));
16233
16383
  } catch (e) {
16234
16384
  throw cannot(e);
16235
16385
  }
16236
16386
  }
16237
- function replaceFile(file, text) {
16387
+ function replaceFile(file, text2) {
16238
16388
  const tmp = `${file}.${process.pid}.tmp`;
16239
16389
  try {
16240
- const fd = fs5.openSync(tmp, "w");
16390
+ const fd = fs6.openSync(tmp, "w");
16241
16391
  try {
16242
- fs5.writeFileSync(fd, text);
16243
- fs5.fsyncSync(fd);
16392
+ fs6.writeFileSync(fd, text2);
16393
+ fs6.fsyncSync(fd);
16244
16394
  } finally {
16245
- fs5.closeSync(fd);
16395
+ fs6.closeSync(fd);
16246
16396
  }
16247
- retryBusy(() => fs5.renameSync(tmp, file));
16397
+ retryBusy(() => fs6.renameSync(tmp, file));
16248
16398
  } catch (e) {
16249
16399
  try {
16250
- retryBusy(() => fs5.rmSync(tmp, { force: true }));
16400
+ retryBusy(() => fs6.rmSync(tmp, { force: true }));
16251
16401
  } catch {}
16252
16402
  throw e;
16253
16403
  }
16254
16404
  }
16255
16405
 
16256
16406
  // server/src/project.ts
16257
- var localFile = () => path6.join(sphicaHome(), "projects.json");
16407
+ var localFile = () => path7.join(sphicaHome(), "projects.json");
16258
16408
  var LOCAL_KEY = /^[a-z0-9][a-z0-9._-]*$/;
16259
16409
  function legacyRemote(url) {
16260
16410
  const raw = String(url ?? "").trim();
@@ -16282,21 +16432,18 @@ function normalizeKey(key) {
16282
16432
  const host = fold(cut < 0 ? rest : rest.slice(0, cut));
16283
16433
  return host === "github.com" ? fold(key) : `git:${host}${cut < 0 ? "" : rest.slice(cut)}`;
16284
16434
  }
16285
- var git = (dir, ...args) => {
16435
+ var ask = (fn) => {
16286
16436
  try {
16287
- return execFileSync2("git", ["-C", dir, ...args], {
16288
- encoding: "utf8",
16289
- stdio: ["ignore", "pipe", "ignore"],
16290
- timeout: 5000
16291
- }).trim();
16437
+ return fn() || null;
16292
16438
  } catch {
16293
16439
  return null;
16294
16440
  }
16295
16441
  };
16442
+ var top = (dir) => ask(() => topLevel(dir, { timeout: 5000 }));
16296
16443
  function localMap() {
16297
16444
  let raw;
16298
16445
  try {
16299
- raw = fs6.readFileSync(localFile(), "utf8");
16446
+ raw = fs7.readFileSync(localFile(), "utf8");
16300
16447
  } catch (e) {
16301
16448
  if (e.code === "ENOENT")
16302
16449
  return {};
@@ -16308,27 +16455,27 @@ function localMap() {
16308
16455
  } catch {
16309
16456
  m = null;
16310
16457
  }
16311
- if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path6.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
16458
+ if (!m || typeof m !== "object" || Array.isArray(m) || Object.entries(m).some(([root, name]) => !path7.isAbsolute(root) || typeof name !== "string" || !LOCAL_KEY.test(name)))
16312
16459
  throw new Error(`${localFile()} is not a valid JSON project table. Fix or delete it, then name the project again.`);
16313
16460
  return m;
16314
16461
  }
16315
- var rootOf = (dir) => git(path6.resolve(dir), "rev-parse", "--show-toplevel") || path6.resolve(dir);
16462
+ var rootOf = (dir) => top(path7.resolve(dir)) || path7.resolve(dir);
16316
16463
  function identify(dir) {
16317
- const given = path6.resolve(dir);
16318
- const top = git(given, "rev-parse", "--show-toplevel");
16319
- const root = top || given;
16320
- const legacy = top ? legacyRemote(git(root, "remote", "get-url", "origin")) : null;
16464
+ const given = path7.resolve(dir);
16465
+ const found = top(given);
16466
+ const root = found || given;
16467
+ const legacy = found ? legacyRemote(ask(() => originUrl(root, { timeout: 5000 }))) : null;
16321
16468
  if (legacy) {
16322
16469
  const key = normalizeKey(`git:${legacy}`);
16323
16470
  const remote = key.slice(4);
16324
16471
  return { key, legacyKey: `git:${legacy}`, root, name: remote.split("/").slice(1).join("/") || remote };
16325
16472
  }
16326
16473
  const map = localMap();
16327
- for (let d = root;; d = path6.dirname(d)) {
16474
+ for (let d = root;; d = path7.dirname(d)) {
16328
16475
  const local = map[d];
16329
16476
  if (local && LOCAL_KEY.test(local))
16330
16477
  return { key: `local:${local}`, legacyKey: `local:${local}`, root: d, name: local };
16331
- if (top || path6.dirname(d) === d)
16478
+ if (found || path7.dirname(d) === d)
16332
16479
  return null;
16333
16480
  }
16334
16481
  }
@@ -16336,14 +16483,14 @@ function checkLocalName(name) {
16336
16483
  if (!LOCAL_KEY.test(name))
16337
16484
  throw new Error(`Use only lowercase letters, digits, and . _ - in the name: ${name}`);
16338
16485
  }
16339
- var repositoryRoot = (dir) => git(path6.resolve(dir), "rev-parse", "--show-toplevel") || null;
16486
+ var repositoryRoot = (dir) => top(path7.resolve(dir));
16340
16487
  function nameLocal(dir, name) {
16341
16488
  checkLocalName(name);
16342
16489
  const place = identify(dir);
16343
16490
  if (place?.key.startsWith("git:"))
16344
16491
  throw new Error(`${place.root} has a git remote, so its key is ${place.key}. Add it without --name.`);
16345
16492
  const root = rootOf(dir);
16346
- fs6.mkdirSync(path6.dirname(localFile()), { recursive: true, mode: 448 });
16493
+ fs7.mkdirSync(path7.dirname(localFile()), { recursive: true, mode: 448 });
16347
16494
  withFileLock(`${localFile()}.lock`, () => {
16348
16495
  const m = localMap();
16349
16496
  m[root] = name;
@@ -16353,11 +16500,11 @@ function nameLocal(dir, name) {
16353
16500
  return { key: `local:${name}`, root, name };
16354
16501
  }
16355
16502
  function relativeTo(root, file, cwd = root) {
16356
- const abs = path6.resolve(cwd, file);
16357
- const rel = path6.relative(root, abs);
16503
+ const abs = path7.resolve(cwd, file);
16504
+ const rel = path7.relative(root, abs);
16358
16505
  if (!rel || leaves(rel) || /\p{Cc}/u.test(rel))
16359
16506
  return null;
16360
- return rel.split(path6.sep).join("/");
16507
+ return rel.split(path7.sep).join("/");
16361
16508
  }
16362
16509
  function patchPaths(patch) {
16363
16510
  const out = [];
@@ -16371,25 +16518,15 @@ function patchPaths(patch) {
16371
16518
  }
16372
16519
 
16373
16520
  // server/src/worktree.ts
16374
- import { execFileSync as execFileSync3 } from "node:child_process";
16375
- import fs7 from "node:fs";
16376
- import path7 from "node:path";
16521
+ import fs8 from "node:fs";
16522
+ import path8 from "node:path";
16377
16523
  var MAX_PATHS = 200;
16378
- var git2 = (root, args) => {
16379
- try {
16380
- return execFileSync3("git", ["-C", root, ...args], {
16381
- encoding: "utf8",
16382
- stdio: ["ignore", "pipe", "ignore"],
16383
- timeout: 5000,
16384
- maxBuffer: 16 * 1024 * 1024
16385
- });
16386
- } catch {
16387
- return null;
16388
- }
16389
- };
16524
+ var LIMITS = { timeout: 5000, max: 16 * 1024 * 1024 };
16525
+ var STATUS_DEADLINE = 5000;
16390
16526
  var usable = (p) => p !== "" && !p.includes("\\") && !/\p{Cc}/u.test(p);
16391
- function snapshot(root) {
16392
- const out = git2(root, ["status", "--porcelain=v2", "-z", "--untracked-files=all"]);
16527
+ async function snapshot(root) {
16528
+ const until = Date.now() + STATUS_DEADLINE;
16529
+ const out = await worktreeStatus(root, STATUS_DEADLINE);
16393
16530
  if (out === null)
16394
16531
  return null;
16395
16532
  const fields = out.split("\x00");
@@ -16407,13 +16544,18 @@ function snapshot(root) {
16407
16544
  continue;
16408
16545
  let st;
16409
16546
  try {
16410
- st = fs7.lstatSync(path7.join(root, p), { throwIfNoEntry: false });
16547
+ st = fs8.lstatSync(path8.join(root, p), { throwIfNoEntry: false });
16411
16548
  } catch {
16412
16549
  st = undefined;
16413
16550
  }
16414
16551
  entries[p] = `${parts.slice(0, skip).join(" ")} ${st ? `${st.size}:${st.mtimeMs}` : "gone"}`;
16415
16552
  }
16416
- const head2 = git2(root, ["rev-parse", "--verify", "-q", "HEAD"])?.trim() || null;
16553
+ let head2 = null;
16554
+ try {
16555
+ const left = until - Date.now();
16556
+ if (left > 0)
16557
+ head2 = commitOf(root, "HEAD", { ...LIMITS, timeout: left }) || null;
16558
+ } catch {}
16417
16559
  return { head: head2, entries };
16418
16560
  }
16419
16561
  function changed(root, before, after) {
@@ -16421,8 +16563,12 @@ function changed(root, before, after) {
16421
16563
  for (const p of new Set([...Object.keys(before.entries), ...Object.keys(after.entries)]))
16422
16564
  if (before.entries[p] !== after.entries[p])
16423
16565
  paths.add(p);
16424
- if (before.head && after.head && before.head !== after.head && git2(root, ["merge-base", "--is-ancestor", before.head, after.head]) !== null) {
16425
- for (const p of (git2(root, ["diff", "--name-only", "-z", before.head, after.head]) ?? "").split("\x00"))
16566
+ if (before.head && after.head && before.head !== after.head && isAncestor(root, before.head, after.head, LIMITS)) {
16567
+ let between = [];
16568
+ try {
16569
+ between = commitDiffNames(root, before.head, after.head, LIMITS);
16570
+ } catch {}
16571
+ for (const p of between)
16426
16572
  if (usable(p))
16427
16573
  paths.add(p);
16428
16574
  }
@@ -16430,15 +16576,15 @@ function changed(root, before, after) {
16430
16576
  }
16431
16577
 
16432
16578
  // server/src/capture.ts
16433
- var spoolDir = () => path8.join(sphicaHome(), "spool");
16434
- var stateFile = () => path8.join(sphicaHome(), "capture.json");
16435
- var rejectedDir = () => path8.join(spoolDir(), "rejected");
16436
- var unregisteredDir = () => path8.join(spoolDir(), "unregistered");
16437
- var callsDir = () => path8.join(spoolDir(), "calls");
16438
- var callsRejectedDir = () => path8.join(callsDir(), "rejected");
16579
+ var spoolDir = () => path9.join(sphicaHome(), "spool");
16580
+ var stateFile = () => path9.join(sphicaHome(), "capture.json");
16581
+ var rejectedDir = () => path9.join(spoolDir(), "rejected");
16582
+ var unregisteredDir = () => path9.join(spoolDir(), "unregistered");
16583
+ var callsDir = () => path9.join(spoolDir(), "calls");
16584
+ var callsRejectedDir = () => path9.join(callsDir(), "rejected");
16439
16585
  var HOLD_DAYS = 30;
16440
16586
  var HOLD_MAX = 1000;
16441
- var baselineDir = () => path8.join(sphicaHome(), "worktree");
16587
+ var baselineDir = () => path9.join(sphicaHome(), "worktree");
16442
16588
  function current(raw) {
16443
16589
  const r2 = raw;
16444
16590
  if (typeof r2.project !== "string")
@@ -16487,7 +16633,7 @@ ${z}`,
16487
16633
  function prune(held, removed = () => {}) {
16488
16634
  let files;
16489
16635
  try {
16490
- files = fs8.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
16636
+ files = fs9.readdirSync(held).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort();
16491
16637
  } catch {
16492
16638
  return;
16493
16639
  }
@@ -16495,26 +16641,26 @@ function prune(held, removed = () => {}) {
16495
16641
  const stale = files.filter((f) => Number(f.split("-")[0]) < cutoff);
16496
16642
  const over = files.slice(0, Math.max(0, files.length - HOLD_MAX));
16497
16643
  for (const f of new Set([...stale, ...over])) {
16498
- fs8.rmSync(path8.join(held, f), { force: true });
16644
+ fs9.rmSync(path9.join(held, f), { force: true });
16499
16645
  removed();
16500
16646
  }
16501
16647
  }
16502
16648
  function put(dir, record) {
16503
- fs8.mkdirSync(dir, { recursive: true, mode: 448 });
16649
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
16504
16650
  const name = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 10)}.json`;
16505
- const tmp = path8.join(dir, `.${name}`);
16506
- fs8.writeFileSync(tmp, JSON.stringify(record), { mode: 384 });
16507
- fs8.renameSync(tmp, path8.join(dir, name));
16508
- return path8.join(dir, name);
16651
+ const tmp = path9.join(dir, `.${name}`);
16652
+ fs9.writeFileSync(tmp, JSON.stringify(record), { mode: 384 });
16653
+ fs9.renameSync(tmp, path9.join(dir, name));
16654
+ return path9.join(dir, name);
16509
16655
  }
16510
16656
  function spool(record) {
16511
16657
  put(spoolDir(), record);
16512
16658
  }
16513
16659
  var branchOf = (root) => {
16514
16660
  try {
16515
- const dotgit = path8.join(root, ".git");
16516
- const gitdir = fs8.statSync(dotgit).isFile() ? path8.resolve(root, fs8.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
16517
- const h2 = fs8.readFileSync(path8.join(gitdir, "HEAD"), "utf8").trim();
16661
+ const dotgit = path9.join(root, ".git");
16662
+ const gitdir = fs9.statSync(dotgit).isFile() ? path9.resolve(root, fs9.readFileSync(dotgit, "utf8").match(/^gitdir: (.+)$/m)?.[1]?.trim() ?? "") : dotgit;
16663
+ const h2 = fs9.readFileSync(path9.join(gitdir, "HEAD"), "utf8").trim();
16518
16664
  return h2.startsWith("ref: refs/heads/") ? h2.slice("ref: refs/heads/".length) : null;
16519
16665
  } catch {
16520
16666
  return null;
@@ -16560,7 +16706,7 @@ Notes: ${notes.trim()}` : "";
16560
16706
  };
16561
16707
  }
16562
16708
  function captureNotice(file = dbFile()) {
16563
- if (!fs8.existsSync(file))
16709
+ if (!fs9.existsSync(file))
16564
16710
  return panel("sphica: no database, so conversations are not recorded", [file], "Create it with sphica init");
16565
16711
  const s = readState();
16566
16712
  if (s.unreadable)
@@ -16571,15 +16717,15 @@ function captureNotice(file = dbFile()) {
16571
16717
  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");
16572
16718
  return null;
16573
16719
  }
16574
- var turnDir = (host, session) => path8.join(baselineDir(), digest(`${host}\x00${session}`));
16575
- var startFile = (dir, turn) => path8.join(dir, `${digest(turn)}.json`);
16720
+ var turnDir = (host, session) => path9.join(baselineDir(), digest(`${host}\x00${session}`));
16721
+ var startFile = (dir, turn) => path9.join(dir, `${digest(turn)}.json`);
16576
16722
  var isStart = (v) => {
16577
16723
  const s = v;
16578
16724
  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");
16579
16725
  };
16580
16726
  function readStart(file) {
16581
16727
  try {
16582
- const s = JSON.parse(fs8.readFileSync(file, "utf8"));
16728
+ const s = JSON.parse(fs9.readFileSync(file, "utf8"));
16583
16729
  return isStart(s) ? s : null;
16584
16730
  } catch {
16585
16731
  return null;
@@ -16588,7 +16734,7 @@ function readStart(file) {
16588
16734
  function readStarts(dir) {
16589
16735
  let names;
16590
16736
  try {
16591
- names = fs8.readdirSync(dir);
16737
+ names = fs9.readdirSync(dir);
16592
16738
  } catch (e) {
16593
16739
  return e.code === "ENOENT" ? [] : null;
16594
16740
  }
@@ -16596,7 +16742,7 @@ function readStarts(dir) {
16596
16742
  for (const name of names) {
16597
16743
  if (name.startsWith("."))
16598
16744
  continue;
16599
- const s = readStart(path8.join(dir, name));
16745
+ const s = readStart(path9.join(dir, name));
16600
16746
  if (!s)
16601
16747
  return null;
16602
16748
  starts.push(s);
@@ -16606,30 +16752,30 @@ function readStarts(dir) {
16606
16752
  function newestTurn(starts) {
16607
16753
  if (!starts?.length || starts.some((s) => s.seq === null))
16608
16754
  return null;
16609
- const top = Math.max(...starts.map((s) => s.seq));
16610
- const at = starts.filter((s) => s.seq === top);
16755
+ const top2 = Math.max(...starts.map((s) => s.seq));
16756
+ const at = starts.filter((s) => s.seq === top2);
16611
16757
  return at.length === 1 ? at[0]?.turn ?? null : null;
16612
16758
  }
16613
16759
  function writeStart(dir, s, file = startFile(dir, s.turn)) {
16614
- fs8.mkdirSync(dir, { recursive: true, mode: 448 });
16615
- const tmp = path8.join(dir, `.${path8.basename(file)}.${process.pid}.tmp`);
16616
- fs8.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
16617
- fs8.renameSync(tmp, file);
16760
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
16761
+ const tmp = path9.join(dir, `.${path9.basename(file)}.${process.pid}.tmp`);
16762
+ fs9.writeFileSync(tmp, JSON.stringify(s), { mode: 384 });
16763
+ fs9.renameSync(tmp, file);
16618
16764
  }
16619
- function openTurn(dir, turn, root) {
16765
+ async function openTurn(dir, turn, root) {
16620
16766
  if (readStart(startFile(dir, turn))?.running)
16621
16767
  return null;
16622
16768
  const starts = readStarts(dir);
16623
16769
  const seq = starts && !starts.some((s) => s.seq === null) ? Math.max(0, ...starts.map((s) => s.seq)) + 1 : null;
16624
- const now = snapshot(root);
16770
+ const now = await snapshot(root);
16625
16771
  return () => writeStart(dir, { head: now?.head ?? null, entries: now?.entries ?? null, running: true, turn, seq });
16626
16772
  }
16627
- function closeTurn(dir, turn, root) {
16773
+ async function closeTurn(dir, turn, root) {
16628
16774
  const own = readStart(startFile(dir, turn));
16629
16775
  if (!own?.entries)
16630
16776
  return null;
16631
16777
  const before = { head: own.head, entries: own.entries };
16632
- const now = snapshot(root);
16778
+ const now = await snapshot(root);
16633
16779
  return () => {
16634
16780
  if (newestTurn(readStarts(dir)) !== turn || JSON.stringify(readStart(startFile(dir, turn))) !== JSON.stringify(own))
16635
16781
  return [];
@@ -16644,22 +16790,22 @@ function stopTurn(dir, turn) {
16644
16790
  }
16645
16791
  function pruneBaselines() {
16646
16792
  const cutoff = Date.now() - HOLD_DAYS * 24 * 60 * 60 * 1000;
16647
- const fresh = (file) => (fs8.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
16793
+ const fresh = (file) => (fs9.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) >= cutoff;
16648
16794
  let names;
16649
16795
  try {
16650
- names = fs8.readdirSync(baselineDir());
16796
+ names = fs9.readdirSync(baselineDir());
16651
16797
  } catch {
16652
16798
  return;
16653
16799
  }
16654
16800
  for (const name of names) {
16655
- const at = path8.join(baselineDir(), name);
16656
- if (!fs8.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
16801
+ const at = path9.join(baselineDir(), name);
16802
+ if (!fs9.statSync(at, { throwIfNoEntry: false })?.isDirectory()) {
16657
16803
  if (!fresh(at))
16658
- fs8.rmSync(at, { force: true });
16804
+ fs9.rmSync(at, { force: true });
16659
16805
  } else {
16660
- const files = fs8.readdirSync(at);
16661
- if (files.length && !files.some((f) => fresh(path8.join(at, f))))
16662
- fs8.rmSync(at, { recursive: true, force: true });
16806
+ const files = fs9.readdirSync(at);
16807
+ if (files.length && !files.some((f) => fresh(path9.join(at, f))))
16808
+ fs9.rmSync(at, { recursive: true, force: true });
16663
16809
  }
16664
16810
  }
16665
16811
  }
@@ -16670,7 +16816,14 @@ function attempt(fn) {
16670
16816
  return;
16671
16817
  }
16672
16818
  }
16673
- function onHook(host, input) {
16819
+ async function attemptAsync(fn) {
16820
+ try {
16821
+ return await fn();
16822
+ } catch {
16823
+ return;
16824
+ }
16825
+ }
16826
+ async function onHook(host, input) {
16674
16827
  const event = input.hook_event_name;
16675
16828
  const owner = () => isOwnerTurn(input, undefined, undefined, host === "codex" ? process.env.CODEX_THREAD_ID : undefined);
16676
16829
  if (event === "SessionStart") {
@@ -16678,7 +16831,7 @@ function onHook(host, input) {
16678
16831
  return { flush: false };
16679
16832
  const file = process.env.CLAUDE_ENV_FILE;
16680
16833
  if (file && input.session_id && /^[A-Za-z0-9_-]+$/.test(input.session_id)) {
16681
- fs8.appendFileSync(file, `export SPHICA_PARENT_SESSION=${input.session_id}
16834
+ fs9.appendFileSync(file, `export SPHICA_PARENT_SESSION=${input.session_id}
16682
16835
  `);
16683
16836
  }
16684
16837
  attempt(pruneBaselines);
@@ -16722,12 +16875,12 @@ function onHook(host, input) {
16722
16875
  say(`${turn}:owner`, "owner", prompt);
16723
16876
  }
16724
16877
  if (event === "UserPromptSubmit")
16725
- attempt(() => openTurn(dir, turn, place.root)?.());
16878
+ await attemptAsync(async () => (await openTurn(dir, turn, place.root))?.());
16726
16879
  if (event === "Stop") {
16727
16880
  if (input.last_assistant_message)
16728
16881
  say(`${turn}:assistant`, "assistant", input.last_assistant_message);
16729
- const paths = attempt(() => {
16730
- const finish = closeTurn(dir, turn, place.root);
16882
+ const paths = await attemptAsync(async () => {
16883
+ const finish = await closeTurn(dir, turn, place.root);
16731
16884
  if (finish)
16732
16885
  return finish();
16733
16886
  stopTurn(dir, turn);
@@ -16761,7 +16914,7 @@ function onHook(host, input) {
16761
16914
  function readStateFile() {
16762
16915
  let raw = {};
16763
16916
  try {
16764
- const parsed = JSON.parse(fs8.readFileSync(stateFile(), "utf8"));
16917
+ const parsed = JSON.parse(fs9.readFileSync(stateFile(), "utf8"));
16765
16918
  if (parsed && typeof parsed === "object")
16766
16919
  raw = parsed;
16767
16920
  } catch {}
@@ -16775,7 +16928,7 @@ function readStateFile() {
16775
16928
  }
16776
16929
  function writeState(s) {
16777
16930
  try {
16778
- fs8.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
16931
+ fs9.writeFileSync(stateFile(), JSON.stringify({ ...s, pruned: s.pruned ?? readStateFile().pruned }));
16779
16932
  } catch {}
16780
16933
  }
16781
16934
  function readState() {
@@ -16791,7 +16944,7 @@ function readState() {
16791
16944
  }
16792
16945
  function listQueue(dir) {
16793
16946
  try {
16794
- const names = fs8.readdirSync(dir);
16947
+ const names = fs9.readdirSync(dir);
16795
16948
  return {
16796
16949
  files: names.filter((f) => f.endsWith(".json") && !f.startsWith(".")),
16797
16950
  temp: names.filter((f) => f.endsWith(".json") && f.startsWith(".")),
@@ -16817,7 +16970,7 @@ function queueReport(now = Date.now()) {
16817
16970
  const temp = { count: 0, oldestMs: 0, bytes: 0 };
16818
16971
  for (const name of listed[k].temp)
16819
16972
  try {
16820
- const st = fs8.statSync(path8.join(dirs[k], name));
16973
+ const st = fs9.statSync(path9.join(dirs[k], name));
16821
16974
  const age = now - st.mtimeMs;
16822
16975
  if (age < TEMP_AGE_MS)
16823
16976
  continue;
@@ -16832,9 +16985,9 @@ function queueReport(now = Date.now()) {
16832
16985
  for (const name of listed[k].files ?? []) {
16833
16986
  let why = "unknown";
16834
16987
  try {
16835
- const text = fs8.readFileSync(path8.join(dirs[k], `${name}.reason`), "utf8");
16836
- if (REASON.test(text))
16837
- why = text;
16988
+ const text2 = fs9.readFileSync(path9.join(dirs[k], `${name}.reason`), "utf8");
16989
+ if (REASON.test(text2))
16990
+ why = text2;
16838
16991
  } catch {}
16839
16992
  out[why] = (out[why] ?? 0) + 1;
16840
16993
  }
@@ -16842,7 +16995,7 @@ function queueReport(now = Date.now()) {
16842
16995
  };
16843
16996
  const read = (dir, name) => {
16844
16997
  try {
16845
- return JSON.parse(fs8.readFileSync(path8.join(dir, name), "utf8"));
16998
+ return JSON.parse(fs9.readFileSync(path9.join(dir, name), "utf8"));
16846
16999
  } catch {
16847
17000
  return null;
16848
17001
  }
@@ -16871,25 +17024,25 @@ function queueReport(now = Date.now()) {
16871
17024
  };
16872
17025
  }
16873
17026
  function lock() {
16874
- const file = path8.join(spoolDir(), ".lock");
16875
- fs8.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
17027
+ const file = path9.join(spoolDir(), ".lock");
17028
+ fs9.mkdirSync(spoolDir(), { recursive: true, mode: 448 });
16876
17029
  for (let attempt2 = 0;attempt2 < 2; attempt2++) {
16877
17030
  try {
16878
- fs8.writeFileSync(file, String(process.pid), { flag: "wx", mode: 384 });
17031
+ fs9.writeFileSync(file, String(process.pid), { flag: "wx", mode: 384 });
16879
17032
  return () => {
16880
17033
  try {
16881
- if (fs8.readFileSync(file, "utf8") === String(process.pid))
16882
- fs8.rmSync(file, { force: true });
17034
+ if (fs9.readFileSync(file, "utf8") === String(process.pid))
17035
+ fs9.rmSync(file, { force: true });
16883
17036
  } catch {}
16884
17037
  };
16885
17038
  } catch (e) {
16886
17039
  if (e.code !== "EEXIST")
16887
17040
  throw e;
16888
17041
  }
16889
- const st = fs8.statSync(file, { throwIfNoEntry: false });
17042
+ const st = fs9.statSync(file, { throwIfNoEntry: false });
16890
17043
  if (!st)
16891
17044
  continue;
16892
- const holder = Number(fs8.readFileSync(file, "utf8") || 0);
17045
+ const holder = Number(fs9.readFileSync(file, "utf8") || 0);
16893
17046
  const fresh = Date.now() - st.mtimeMs < 5 * 60000;
16894
17047
  const alive = (() => {
16895
17048
  if (holder <= 0)
@@ -16902,7 +17055,7 @@ function lock() {
16902
17055
  })();
16903
17056
  if (alive && fresh)
16904
17057
  return null;
16905
- fs8.rmSync(file, { force: true });
17058
+ fs9.rmSync(file, { force: true });
16906
17059
  }
16907
17060
  return null;
16908
17061
  }
@@ -17001,23 +17154,23 @@ var REJECTED = new Set([18, 19, 20, 25]);
17001
17154
  var rejected = (e) => REJECTED.has(sqliteCode(e) ?? -1);
17002
17155
  var queued = (from) => {
17003
17156
  try {
17004
- return fs8.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
17157
+ return fs9.readdirSync(from).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().map((name) => ({ name, from }));
17005
17158
  } catch {
17006
17159
  return [];
17007
17160
  }
17008
17161
  };
17009
17162
  var CODE_NAMES = { 18: "TOOBIG", 19: "CONSTRAINT", 20: "MISMATCH", 25: "RANGE" };
17010
17163
  function setAside(from, name, dir, reason2) {
17011
- fs8.mkdirSync(dir, { recursive: true, mode: 448 });
17164
+ fs9.mkdirSync(dir, { recursive: true, mode: 448 });
17012
17165
  try {
17013
- fs8.renameSync(path8.join(from, name), path8.join(dir, name));
17166
+ fs9.renameSync(path9.join(from, name), path9.join(dir, name));
17014
17167
  } catch (e) {
17015
17168
  if (e.code === "ENOENT")
17016
17169
  return;
17017
17170
  throw e;
17018
17171
  }
17019
17172
  try {
17020
- fs8.writeFileSync(path8.join(dir, `${name}.reason`), reason2, { mode: 384 });
17173
+ fs9.writeFileSync(path9.join(dir, `${name}.reason`), reason2, { mode: 384 });
17021
17174
  } catch {}
17022
17175
  }
17023
17176
  async function sendBatch(db, names) {
@@ -17027,7 +17180,7 @@ async function sendBatch(db, names) {
17027
17180
  let raw;
17028
17181
  let r2;
17029
17182
  try {
17030
- raw = JSON.parse(fs8.readFileSync(path8.join(from, name), "utf8"));
17183
+ raw = JSON.parse(fs9.readFileSync(path9.join(from, name), "utf8"));
17031
17184
  } catch {
17032
17185
  setAside(from, name, rejectedDir(), "unreadable");
17033
17186
  continue;
@@ -17041,7 +17194,7 @@ async function sendBatch(db, names) {
17041
17194
  if (r2)
17042
17195
  records.push({ name, from, r: r2 });
17043
17196
  else
17044
- fs8.rmSync(path8.join(from, name), { force: true });
17197
+ fs9.rmSync(path9.join(from, name), { force: true });
17045
17198
  }
17046
17199
  let sent = 0;
17047
17200
  let strayed = [];
@@ -17069,12 +17222,12 @@ async function sendBatch(db, names) {
17069
17222
  for (const x of bad)
17070
17223
  setAside(x.from, x.name, rejectedDir(), x.why);
17071
17224
  if (strayed.length) {
17072
- fs8.mkdirSync(held, { recursive: true, mode: 448 });
17225
+ fs9.mkdirSync(held, { recursive: true, mode: 448 });
17073
17226
  for (const x of strayed) {
17074
17227
  if (x.from === held)
17075
17228
  continue;
17076
17229
  try {
17077
- fs8.renameSync(path8.join(x.from, x.name), path8.join(held, x.name));
17230
+ fs9.renameSync(path9.join(x.from, x.name), path9.join(held, x.name));
17078
17231
  } catch (e) {
17079
17232
  if (e.code !== "ENOENT")
17080
17233
  throw e;
@@ -17084,7 +17237,7 @@ async function sendBatch(db, names) {
17084
17237
  const moved = new Set([...bad, ...strayed].map((x) => x.name));
17085
17238
  for (const x of records)
17086
17239
  if (!moved.has(x.name))
17087
- fs8.rmSync(path8.join(x.from, x.name), { force: true });
17240
+ fs9.rmSync(path9.join(x.from, x.name), { force: true });
17088
17241
  return { sent, rejected: bad.length };
17089
17242
  }
17090
17243
  async function sendObservations(db, names) {
@@ -17095,16 +17248,16 @@ async function sendObservations(db, names) {
17095
17248
  };
17096
17249
  const rows = [];
17097
17250
  for (const { name, from } of names) {
17098
- let text;
17251
+ let text2;
17099
17252
  try {
17100
- text = fs8.readFileSync(path8.join(from, name), "utf8");
17253
+ text2 = fs9.readFileSync(path9.join(from, name), "utf8");
17101
17254
  } catch {
17102
17255
  continue;
17103
17256
  }
17104
17257
  let o = null;
17105
17258
  let why = "unreadable";
17106
17259
  try {
17107
- o = observation(JSON.parse(text));
17260
+ o = observation(JSON.parse(text2));
17108
17261
  why = "shape";
17109
17262
  } catch {}
17110
17263
  if (o)
@@ -17136,7 +17289,7 @@ async function sendObservations(db, names) {
17136
17289
  aside(x.name, why);
17137
17290
  else
17138
17291
  try {
17139
- fs8.rmSync(path8.join(callsDir(), x.name), { force: true });
17292
+ fs9.rmSync(path9.join(callsDir(), x.name), { force: true });
17140
17293
  } catch {}
17141
17294
  }
17142
17295
  return true;
@@ -17279,7 +17432,7 @@ async function observeRecordCall(file, input, owner, waitMs = OBSERVE_WAIT_MS) {
17279
17432
  }
17280
17433
  if (kept)
17281
17434
  try {
17282
- fs8.rmSync(kept, { force: true });
17435
+ fs9.rmSync(kept, { force: true });
17283
17436
  } catch {}
17284
17437
  }
17285
17438
  async function main() {
@@ -17295,11 +17448,11 @@ async function main() {
17295
17448
  }
17296
17449
  if (host === "codex" && input.hook_event_name === "Stop")
17297
17450
  process.stdout.write("{}");
17298
- const { flush: send, notice } = onHook(host, input);
17451
+ const { flush: send, notice } = await onHook(host, input);
17299
17452
  if (notice)
17300
17453
  process.stdout.write(JSON.stringify({ systemMessage: notice }));
17301
17454
  if (send)
17302
- spawn(process.execPath, [process.argv[1] ?? "", "--flush"], {
17455
+ spawn2(process.execPath, [process.argv[1] ?? "", "--flush"], {
17303
17456
  detached: true,
17304
17457
  stdio: "ignore",
17305
17458
  windowsHide: true
@@ -17315,23 +17468,23 @@ import { styleText as styleText3 } from "node:util";
17315
17468
  var colored2 = () => Boolean(process.stdout.isTTY && process.stderr.isTTY) && !process.env.NO_COLOR;
17316
17469
  var columns = () => process.stdout.isTTY ? Math.max(10, process.stdout.columns || 100) : 1e4;
17317
17470
  function capture(draw) {
17318
- let text = "";
17471
+ let text2 = "";
17319
17472
  const output = new Writable({
17320
17473
  write(chunk, _encoding, done) {
17321
- text += String(chunk);
17474
+ text2 += String(chunk);
17322
17475
  done();
17323
17476
  }
17324
17477
  });
17325
17478
  Object.assign(output, { columns: columns(), isTTY: true });
17326
17479
  draw(output);
17327
- return text.replace(/\n$/, "");
17480
+ return text2.replace(/\n$/, "");
17328
17481
  }
17329
17482
  var SGR = /(\u001b\[[0-9;]*m)/;
17330
- var clean2 = (text) => text.split(SGR).map((piece, i2) => i2 % 2 ? piece : plain(piece)).join("");
17331
- var oneLine = (text) => clean2(text).replace(/[\n\t]+/g, " ");
17332
- var bold = (text) => styleText3("bold", text);
17333
- var dim = (text) => styleText3("dim", text);
17334
- var plainLine = (text) => wrapAnsi(oneLine(text), columns() - 2, { hard: true, trim: true }).split(`
17483
+ var clean2 = (text2) => text2.split(SGR).map((piece, i2) => i2 % 2 ? piece : plain(piece)).join("");
17484
+ var oneLine = (text2) => clean2(text2).replace(/[\n\t]+/g, " ");
17485
+ var bold = (text2) => styleText3("bold", text2);
17486
+ var dim = (text2) => styleText3("dim", text2);
17487
+ var plainLine = (text2) => wrapAnsi(oneLine(text2), columns() - 2, { hard: true, trim: true }).split(`
17335
17488
  `).join(`
17336
17489
  `);
17337
17490
  var GUIDE = 3;
@@ -17344,8 +17497,8 @@ function wrapLine(line, room) {
17344
17497
  const cells = MARKED.test(body) ? /^(.*\S\s{2,})(\S.*)$/.exec(body) : null;
17345
17498
  const label = cells?.[1] ?? "";
17346
17499
  const hang = lead + dist_default2(label);
17347
- const [head2, text, at] = cells?.[2] && room - hang >= 10 ? [label, cells[2], hang] : ["", body, lead];
17348
- return wrapAnsi(text, Math.max(1, room - at), { hard: true, trim: true }).split(`
17500
+ const [head2, text2, at] = cells?.[2] && room - hang >= 10 ? [label, cells[2], hang] : ["", body, lead];
17501
+ return wrapAnsi(text2, Math.max(1, room - at), { hard: true, trim: true }).split(`
17349
17502
  `).map((part, i2) => i2 === 0 ? `${" ".repeat(lead)}${head2}${part}` : `${" ".repeat(at)}${part}`);
17350
17503
  }
17351
17504
  function content(lines, spacing = 0) {
@@ -17359,29 +17512,29 @@ function content(lines, spacing = 0) {
17359
17512
  const wrapped = cleaned.flatMap((l) => wrapLine(l, columns() - GUIDE));
17360
17513
  return capture((output) => log.message(wrapped, { output, spacing }));
17361
17514
  }
17362
- function title2(text, meta) {
17515
+ function title2(text2, meta) {
17363
17516
  if (!colored2())
17364
- return plainLine(text);
17365
- const t2 = cut(oneLine(text), columns() - GUIDE - 2);
17517
+ return plainLine(text2);
17518
+ const t2 = cut(oneLine(text2), columns() - GUIDE - 2);
17366
17519
  const room = columns() - GUIDE - dist_default2(t2) - 2;
17367
17520
  const extra = meta && room > 8 ? ` ${cut(oneLine(meta), room - 2)}` : "";
17368
17521
  return capture((output) => intro(`${styleText3(["inverse", "bold"], ` ${t2} `)}${extra ? dim(extra) : ""}`, { output }));
17369
17522
  }
17370
- function section(text, gap = false) {
17371
- const t2 = oneLine(text);
17523
+ function section(text2, gap = false) {
17524
+ const t2 = oneLine(text2);
17372
17525
  if (!colored2())
17373
17526
  return `${gap ? `
17374
17527
  ` : ""} ${t2}`;
17375
17528
  return capture((output) => log.step(bold(t2), { output }));
17376
17529
  }
17377
- function indent(text) {
17378
- return content(text.split(`
17530
+ function indent(text2) {
17531
+ return content(text2.split(`
17379
17532
  `));
17380
17533
  }
17381
- function closing(text) {
17534
+ function closing(text2) {
17382
17535
  if (!colored2())
17383
- return plainLine(text);
17384
- const t2 = oneLine(text);
17536
+ return plainLine(text2);
17537
+ const t2 = oneLine(text2);
17385
17538
  const lines = wrapAnsi(t2, columns() - GUIDE, { hard: true, trim: true }).split(`
17386
17539
  `);
17387
17540
  return capture((output) => outro(bold(lines.join(`
@@ -17405,7 +17558,7 @@ function stopped(reason2) {
17405
17558
  cancel("Stopped", { output });
17406
17559
  }).replace(/\n+$/, "");
17407
17560
  }
17408
- var cut = (text, room) => dist_default2(text) <= room ? text : `${wrapAnsi(text, Math.max(1, room - 1), { hard: true }).split(`
17561
+ var cut = (text2, room) => dist_default2(text2) <= room ? text2 : `${wrapAnsi(text2, Math.max(1, room - 1), { hard: true }).split(`
17409
17562
  `)[0]}…`;
17410
17563
  function steps(heading, items, note) {
17411
17564
  const room = columns() - 11;
@@ -17444,11 +17597,11 @@ function judge(s) {
17444
17597
  contenders.set(i2.to, [...contenders.get(i2.to) ?? [], i2]);
17445
17598
  }
17446
17599
  const holders = new Map;
17447
- for (const [to, list] of contenders) {
17600
+ for (const [to, list2] of contenders) {
17448
17601
  const kept = openInto.get(to);
17449
- const holder = list.some((i2) => i2.from === kept) ? kept : list[0].from;
17602
+ const holder = list2.some((i2) => i2.from === kept) ? kept : list2[0].from;
17450
17603
  holders.set(to, holder);
17451
- for (const i2 of list)
17604
+ for (const i2 of list2)
17452
17605
  if (i2.from !== holder)
17453
17606
  waits.set(i2.from, { why: "place held", holder });
17454
17607
  }
@@ -17609,7 +17762,7 @@ var OPEN_SQL = `select r.from_unit, r.to_unit from unit_replacement r join unit
17609
17762
  where r.ended_at is null and u.project_id = ?`;
17610
17763
  function settleForMigration(io, runs, at) {
17611
17764
  const notes = [];
17612
- for (const [project, run2] of runs) {
17765
+ for (const [project, run3] of runs) {
17613
17766
  const rowsNow = () => {
17614
17767
  const units = io.all(UNITS_SQL, project).filter((u3) => Number(u3.stated) === 1);
17615
17768
  const ids = new Set(units.map((u3) => u3.id));
@@ -17623,16 +17776,16 @@ function settleForMigration(io, runs, at) {
17623
17776
  const key = (id) => planned.loaded.keys.get(id) ?? `u${id}`;
17624
17777
  for (const w of planned.writes) {
17625
17778
  if (w.op === "close") {
17626
- io.run("update unit_replacement set ended_at = max(?, started_at), end_reason = ?, end_run_id = ? where from_unit = ? and to_unit = ? and ended_at is null", at, w.reason, run2, w.from, w.to);
17779
+ io.run("update unit_replacement set ended_at = max(?, started_at), end_reason = ?, end_run_id = ? where from_unit = ? and to_unit = ? and ended_at is null", at, w.reason, run3, w.from, w.to);
17627
17780
  notes.push([`${key(w.from)} → ${key(w.to)}`, `replacement ended: ${w.reason}`]);
17628
17781
  } else if (w.op === "open") {
17629
- io.run("insert into unit_replacement (from_unit, to_unit, run_id, started_at) values (?, ?, ?, ?)", w.from, w.to, run2, at);
17782
+ io.run("insert into unit_replacement (from_unit, to_unit, run_id, started_at) values (?, ?, ?, ?)", w.from, w.to, run3, at);
17630
17783
  notes.push([
17631
17784
  `${key(w.from)} → ${key(w.to)}`,
17632
17785
  "in effect from this update (earlier history not recorded)"
17633
17786
  ]);
17634
17787
  } else {
17635
- io.run("insert into unit_state (unit_id, from_state, to_state, at, reason, source_id, run_id) values (?, ?, ?, max(?, (select created_at from unit where id = ?)), ?, ?, ?)", w.unit, w.from, w.to, at, w.unit, `revision 10: ${w.reason}`, w.source, run2);
17788
+ io.run("insert into unit_state (unit_id, from_state, to_state, at, reason, source_id, run_id) values (?, ?, ?, max(?, (select created_at from unit where id = ?)), ?, ?, ?)", w.unit, w.from, w.to, at, w.unit, `revision 10: ${w.reason}`, w.source, run3);
17636
17789
  notes.push([key(w.unit), `${w.from ?? "no state"} → ${w.to}: ${w.reason}`]);
17637
17790
  }
17638
17791
  }
@@ -17642,16 +17795,16 @@ function settleForMigration(io, runs, at) {
17642
17795
  }
17643
17796
 
17644
17797
  // server/src/admin.ts
17645
- var say = (text) => console.log(indent(text));
17646
- var SCHEMA = () => path9.join(dbDir(), "schema.sql");
17647
- var MIGRATIONS = () => path9.join(dbDir(), "migrations");
17648
- var MIGRATION = (dir, revision) => path9.join(dir, `${String(revision).padStart(4, "0")}.sql`);
17649
- var CHECK = (dir, revision) => path9.join(dir, `${String(revision).padStart(4, "0")}.check.sql`);
17798
+ var say = (text2) => console.log(indent(text2));
17799
+ var SCHEMA = () => path10.join(dbDir(), "schema.sql");
17800
+ var MIGRATIONS = () => path10.join(dbDir(), "migrations");
17801
+ var MIGRATION = (dir, revision2) => path10.join(dir, `${String(revision2).padStart(4, "0")}.sql`);
17802
+ var CHECK = (dir, revision2) => path10.join(dir, `${String(revision2).padStart(4, "0")}.check.sql`);
17650
17803
  var STOP2 = "sphica_migration_stop";
17651
17804
  var NOTE = "sphica_migration_note";
17652
17805
  var KEEP2 = 3;
17653
17806
  function backUp(raw, file, from) {
17654
- fs9.mkdirSync(backupDir(file), { recursive: true, mode: 448 });
17807
+ fs10.mkdirSync(backupDir(file), { recursive: true, mode: 448 });
17655
17808
  const done = backupPath(file, from);
17656
17809
  const partial = `${done}.partial`;
17657
17810
  try {
@@ -17667,10 +17820,10 @@ function backUp(raw, file, from) {
17667
17820
  } finally {
17668
17821
  look.close();
17669
17822
  }
17670
- fs9.renameSync(partial, done);
17823
+ fs10.renameSync(partial, done);
17671
17824
  } catch (e) {
17672
17825
  for (const f of [partial, `${partial}-wal`, `${partial}-shm`])
17673
- fs9.rmSync(f, { force: true });
17826
+ fs10.rmSync(f, { force: true });
17674
17827
  throw new Error(`Could not back up ${file} before migrating it, so nothing was migrated (${e.message}). Check free space in ${backupDir(file)}.`);
17675
17828
  }
17676
17829
  return done;
@@ -17684,7 +17837,7 @@ function prune2(file, kept) {
17684
17837
  }
17685
17838
  for (const old of all.filter((b) => b !== kept).slice(KEEP2 - 1))
17686
17839
  try {
17687
- fs9.rmSync(old, { force: true });
17840
+ fs10.rmSync(old, { force: true });
17688
17841
  } catch {}
17689
17842
  }
17690
17843
  var versionOf = (raw) => raw.prepare("pragma user_version").get().user_version;
@@ -17712,15 +17865,15 @@ function listed(rows) {
17712
17865
  `);
17713
17866
  }
17714
17867
  var STOP_ADVICE = {
17715
- "projects with records whose keys become one once normalized": (revision, rows) => `Revision ${revision} was not applied: ${plural(rows.length, "project")} with records have keys that become one once normalized (listed below), and this Sphica cannot merge them. Search, read, and the record tools stay unavailable until a Sphica that can merge them migrates this database. Meanwhile capture keeps recording a session whose remote is written as one of the listed keys; a session whose remote is written otherwise is held, and held records are dropped after ${HOLD_DAYS} days or past ${HOLD_MAX} of them. Report the list below at https://github.com/iroha924/sphica/issues. Forgetting sources does not resolve it`
17868
+ "projects with records whose keys become one once normalized": (revision2, rows) => `Revision ${revision2} was not applied: ${plural(rows.length, "project")} with records have keys that become one once normalized (listed below), and this Sphica cannot merge them. Search, read, and the record tools stay unavailable until a Sphica that can merge them migrates this database. Meanwhile capture keeps recording a session whose remote is written as one of the listed keys; a session whose remote is written otherwise is held, and held records are dropped after ${HOLD_DAYS} days or past ${HOLD_MAX} of them. Report the list below at https://github.com/iroha924/sphica/issues. Forgetting sources does not resolve it`
17716
17869
  };
17717
17870
 
17718
17871
  class Stop extends Error {
17719
17872
  list;
17720
- constructor(revision, rows) {
17873
+ constructor(revision2, rows) {
17721
17874
  const rules = new Set(rows.map((r2) => r2.rule));
17722
17875
  const advice = rules.size === 1 ? STOP_ADVICE[String(rows[0]?.rule)] : undefined;
17723
- super(advice ? advice(revision, rows) : `The database has ${plural(rows.length, "row")} that revision ${revision} cannot take, and Sphica writes no such row (listed below). Fix the rows, or forget a listed source with /sphica:forget on the Sphica version that still opens this database, then run \`sphica init\` again`);
17876
+ super(advice ? advice(revision2, rows) : `The database has ${plural(rows.length, "row")} that revision ${revision2} cannot take, and Sphica writes no such row (listed below). Fix the rows, or forget a listed source with /sphica:forget on the Sphica version that still opens this database, then run \`sphica init\` again`);
17724
17877
  this.list = listed(rows);
17725
17878
  }
17726
17879
  }
@@ -17776,27 +17929,27 @@ function migrate(file = dbFile(), dir = MIGRATIONS()) {
17776
17929
  try {
17777
17930
  for (let r2 = from + 1;r2 <= SCHEMA_REVISION; r2++) {
17778
17931
  const script = MIGRATION(dir, r2);
17779
- if (!fs9.existsSync(script))
17932
+ if (!fs10.existsSync(script))
17780
17933
  throw new Error(`This Sphica has no migration script for revision ${r2} (${script} is missing). Reinstall sphica (\`npm i -g sphica@${packageVersionAt(ROOT) ?? "latest"}\`), then run \`sphica init\` again.`);
17781
17934
  raw.exec("pragma foreign_keys = off");
17782
17935
  try {
17783
17936
  const notes = immediate(raw, () => {
17784
17937
  if (versionOf(raw) !== r2 - 1)
17785
17938
  return [];
17786
- if (fs9.existsSync(CHECK(dir, r2))) {
17787
- raw.exec(fs9.readFileSync(CHECK(dir, r2), "utf8"));
17939
+ if (fs10.existsSync(CHECK(dir, r2))) {
17940
+ raw.exec(fs10.readFileSync(CHECK(dir, r2), "utf8"));
17788
17941
  const stops = taken(raw, STOP2);
17789
17942
  if (stops.length)
17790
17943
  throw new Stop(r2, stops);
17791
17944
  }
17792
- raw.exec(fs9.readFileSync(script, "utf8"));
17945
+ raw.exec(fs10.readFileSync(script, "utf8"));
17793
17946
  if (r2 === 10)
17794
17947
  judgeEveryRecord(raw);
17795
17948
  const broken = raw.prepare("pragma foreign_key_check").all().length;
17796
17949
  if (broken)
17797
17950
  throw new Error(`Migration to revision ${r2} left ${plural(broken, "broken reference")}; nothing was changed`);
17798
17951
  if (versionOf(raw) !== r2)
17799
- throw new Error(`${path9.basename(script)} did not set revision ${r2}`);
17952
+ throw new Error(`${path10.basename(script)} did not set revision ${r2}`);
17800
17953
  return taken(raw, NOTE);
17801
17954
  });
17802
17955
  if (notes.length)
@@ -17808,22 +17961,22 @@ ${listed(notes)}`);
17808
17961
  }
17809
17962
  } catch (e) {
17810
17963
  const said = e.message.replace(/\.$/, "");
17811
- const list = e instanceof Stop ? `
17964
+ const list2 = e instanceof Stop ? `
17812
17965
  ${e.list}` : "";
17813
17966
  const now = committed(raw);
17814
17967
  if (now === from) {
17815
17968
  let left = "the backup made for this run was removed";
17816
17969
  try {
17817
- fs9.rmSync(backup, { force: true });
17970
+ fs10.rmSync(backup, { force: true });
17818
17971
  } catch {
17819
17972
  left = `the backup made for this run is still at ${backup}; delete it yourself`;
17820
17973
  }
17821
17974
  const retry = sqliteCode(e) === SQLITE_BUSY ? " Another process is writing to the database. Run `sphica init` again when it has finished." : "";
17822
- throw new Error(`${said}. No migration step was committed: the database is still at revision ${from}, and there is no need to replace it with a backup (${left}).${retry}${list}`);
17975
+ throw new Error(`${said}. No migration step was committed: the database is still at revision ${from}, and there is no need to replace it with a backup (${left}).${retry}${list2}`);
17823
17976
  }
17824
- const base = path9.basename(file);
17977
+ const base = path10.basename(file);
17825
17978
  const state = now === null ? "The committed revision could not be confirmed after the failure" : `The database is now at revision ${now} (this run, or another \`sphica init\` running at the same time, migrated it that far)`;
17826
- throw new Error(`${said}. ${state}. The database before migrating is at ${backup} (anything recorded after it was made is not in it). To go back to it, close every session using Sphica, move ${base}, ${base}-wal, and ${base}-shm in ${path9.dirname(file)} aside, then copy the backup to ${file}.${list}`);
17979
+ throw new Error(`${said}. ${state}. The database before migrating is at ${backup} (anything recorded after it was made is not in it). To go back to it, close every session using Sphica, move ${base}, ${base}-wal, and ${base}-shm in ${path10.dirname(file)} aside, then copy the backup to ${file}.${list2}`);
17827
17980
  }
17828
17981
  optimize(raw);
17829
17982
  prune2(file, backup);
@@ -17831,7 +17984,7 @@ ${e.list}` : "";
17831
17984
  });
17832
17985
  }
17833
17986
  function dbInit(file = dbFile()) {
17834
- if (fs9.existsSync(file)) {
17987
+ if (fs10.existsSync(file)) {
17835
17988
  const look = new DatabaseSync3(file, { readOnly: true });
17836
17989
  let generation;
17837
17990
  try {
@@ -17852,40 +18005,40 @@ function dbInit(file = dbFile()) {
17852
18005
  }
17853
18006
  return;
17854
18007
  }
17855
- fs9.mkdirSync(path9.dirname(file), { recursive: true, mode: 448 });
18008
+ fs10.mkdirSync(path10.dirname(file), { recursive: true, mode: 448 });
17856
18009
  const tmp = `${file}.${process.pid}.tmp`;
17857
- fs9.rmSync(tmp, { force: true });
18010
+ fs10.rmSync(tmp, { force: true });
17858
18011
  try {
17859
18012
  withOwner(tmp, (raw) => {
17860
18013
  raw.exec("pragma journal_mode = wal");
17861
- raw.exec(fs9.readFileSync(SCHEMA(), "utf8"));
18014
+ raw.exec(fs10.readFileSync(SCHEMA(), "utf8"));
17862
18015
  if (versionOf(raw) !== SCHEMA_REVISION)
17863
18016
  throw new Error(`db/schema.sql has user_version ${versionOf(raw)}, but the code expects ${SCHEMA_REVISION}`);
17864
18017
  optimize(raw);
17865
18018
  }, true);
17866
18019
  const taken2 = () => new Error(`${file} already exists (another sphica init created it first). Run this again to check it.`);
17867
18020
  withFileLock(`${file}.init.lock`, () => {
17868
- if (fs9.existsSync(file))
18021
+ if (fs10.existsSync(file))
17869
18022
  throw taken2();
17870
18023
  try {
17871
- fs9.linkSync(tmp, file);
18024
+ fs10.linkSync(tmp, file);
17872
18025
  } catch (e) {
17873
18026
  if (e.code === "EEXIST")
17874
18027
  throw taken2();
17875
- fs9.renameSync(tmp, file);
18028
+ fs10.renameSync(tmp, file);
17876
18029
  }
17877
18030
  });
17878
18031
  } finally {
17879
18032
  for (const f of [tmp, `${tmp}-wal`, `${tmp}-shm`])
17880
- fs9.rmSync(f, { force: true });
18033
+ fs10.rmSync(f, { force: true });
17881
18034
  }
17882
18035
  say(`Created: ${file} (revision ${SCHEMA_REVISION})`);
17883
18036
  }
17884
18037
  function bindOwner(user, file = dbFile()) {
17885
18038
  return withOwner(file, (raw) => immediate(raw, () => {
17886
- const revision = versionOf(raw);
17887
- if (revision !== SCHEMA_REVISION)
17888
- return { kind: "skipped", revision };
18039
+ const revision2 = versionOf(raw);
18040
+ if (revision2 !== SCHEMA_REVISION)
18041
+ return { kind: "skipped", revision: revision2 };
17889
18042
  const bound = raw.prepare("select external_id, login from owner_identity where provider = 'github' order by external_id = ? desc, bound_at, external_id limit 1").get(String(user.id));
17890
18043
  if (!bound) {
17891
18044
  raw.prepare("insert into owner_identity (provider, external_id, login, bound_at) values ('github', ?, ?, ?)").run(String(user.id), user.login, iso(Date.now()));
@@ -17913,7 +18066,7 @@ function reindex(file = dbFile()) {
17913
18066
  say(`Rebuilt the index: ${plural(counts.units, "unit")}, ${plural(counts.sources, "source")}`);
17914
18067
  }
17915
18068
  function inspect(file = dbFile()) {
17916
- const size = (f) => fs9.existsSync(f) ? fs9.statSync(f).size : 0;
18069
+ const size = (f) => fs10.existsSync(f) ? fs10.statSync(f).size : 0;
17917
18070
  return withOwner(file, (raw) => {
17918
18071
  const check = (table) => {
17919
18072
  try {
@@ -17947,7 +18100,11 @@ import { promisify } from "node:util";
17947
18100
  var exec2 = promisify(execFile);
17948
18101
  var MAX_RESPONSE = 16 * 1024 * 1024;
17949
18102
  var HOST = ["--hostname", "github.com"];
17950
- var plainEnv = () => ({ ...process.env, CLICOLOR_FORCE: "0" });
18103
+ var plainEnv = () => ({
18104
+ ...Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^GIT_/i.test(k))),
18105
+ CLICOLOR_FORCE: "0"
18106
+ });
18107
+ var ghCwd = startDir;
17951
18108
  var LOGIN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,38}$/;
17952
18109
  async function ghUser(timeout = 15000) {
17953
18110
  let stdout2;
@@ -17957,7 +18114,8 @@ async function ghUser(timeout = 15000) {
17957
18114
  maxBuffer: 1024 * 1024,
17958
18115
  timeout,
17959
18116
  killSignal: "SIGKILL",
17960
- env: plainEnv()
18117
+ env: plainEnv(),
18118
+ cwd: ghCwd()
17961
18119
  }));
17962
18120
  } catch (e) {
17963
18121
  const code = e.code;
@@ -18632,11 +18790,11 @@ async function adoptionStops(db, waiting, say2) {
18632
18790
  continue;
18633
18791
  const from = new Date(first.called_at).toLocaleString("sv-SE");
18634
18792
  const n2 = group2.length;
18635
- const text = first.host === "claude-code" ? (() => {
18793
+ const text2 = first.host === "claude-code" ? (() => {
18636
18794
  const resend = group2.filter((c) => c.tool_use_id && waiting.has(c.tool_use_id)).length;
18637
18795
  return `Claude Code replies from ${from} on are not adopted as AI decisions: ${plural(n2, "record tool call")} without a hook observation (${resend} waiting to be resent, ${n2 - resend} that cannot be)`;
18638
18796
  })() : first.host === "codex" ? `Codex replies from ${from} on are not adopted as AI decisions: ${plural(n2, "record tool call")} that named no session` : `replies of every host from ${from} on are not adopted as AI decisions: ${plural(n2, "record tool call")} that named no host`;
18639
- say2("warn", "AI adoption", `${named(first)}: ${text}`);
18797
+ say2("warn", "AI adoption", `${named(first)}: ${text2}`);
18640
18798
  }
18641
18799
  for (const t2 of turnless)
18642
18800
  say2("warn", "AI adoption", `${named(t2)}: Claude Code replies in ${plural(Number(t2.sessions), "session")} from ${new Date(t2.first ?? "").toLocaleString("sv-SE")} on are not adopted as AI decisions: a record tool's hook did not know the turn`);
@@ -18649,9 +18807,9 @@ async function doctor(cwd) {
18649
18807
  if (m === "fail")
18650
18808
  process.exitCode = 1;
18651
18809
  };
18652
- const say2 = (m, label, text) => {
18810
+ const say2 = (m, label, text2) => {
18653
18811
  count(m, label);
18654
- console.log(indent(` ${mark(m)} ${pad(label, 26)}${text}`));
18812
+ console.log(indent(` ${mark(m)} ${pad(label, 26)}${text2}`));
18655
18813
  };
18656
18814
  console.log(title2("sphica doctor"));
18657
18815
  const plugin = report(observe(identify(cwd)?.root ?? cwd));
@@ -18677,7 +18835,7 @@ async function doctor(cwd) {
18677
18835
  let usable2 = false;
18678
18836
  if (!runtime)
18679
18837
  say2("none", "DB", "cannot check until Node is upgraded");
18680
- else if (!fs10.existsSync(file))
18838
+ else if (!fs11.existsSync(file))
18681
18839
  say2("fail", "DB", `missing (${file}). Create it with sphica init`);
18682
18840
  else {
18683
18841
  try {
@@ -18765,7 +18923,7 @@ var GH_WHY = {
18765
18923
  };
18766
18924
  async function bindGitHub() {
18767
18925
  const user = await ghUser();
18768
- const line = (m, text) => console.log(indent(`${mark(m)} ${text}`));
18926
+ const line = (m, text2) => console.log(indent(`${mark(m)} ${text2}`));
18769
18927
  if (!user.ok) {
18770
18928
  line("warn", `GitHub account not bound: ${GH_WHY[user.reason]}`);
18771
18929
  return;
@@ -18783,7 +18941,7 @@ async function bindGitHub() {
18783
18941
  }
18784
18942
  async function init(flags) {
18785
18943
  const cwd = flags.cwd ?? process.cwd();
18786
- if (!fs10.statSync(cwd, { throwIfNoEntry: false })?.isDirectory())
18944
+ if (!fs11.statSync(cwd, { throwIfNoEntry: false })?.isDirectory())
18787
18945
  throw new Error(`${cwd} is not a directory`);
18788
18946
  const found = identify(cwd);
18789
18947
  if (flags.name !== undefined) {
@@ -18812,7 +18970,7 @@ async function init(flags) {
18812
18970
  async function uninstall(yes) {
18813
18971
  const home = sphicaHome();
18814
18972
  const inHome = (p) => {
18815
- const rel = path10.relative(home, path10.resolve(p));
18973
+ const rel = path11.relative(home, path11.resolve(p));
18816
18974
  return rel === "" || !leaves(rel);
18817
18975
  };
18818
18976
  const where = [
@@ -18822,7 +18980,7 @@ async function uninstall(yes) {
18822
18980
  await boxed("sphica uninstall", async () => {
18823
18981
  if (process.env.SPHICA_HOME)
18824
18982
  throw new Error("SPHICA_HOME is set; uninstall deletes only ~/.sphica. Unset SPHICA_HOME and run it again");
18825
- if (!fs10.existsSync(home))
18983
+ if (!fs11.existsSync(home))
18826
18984
  console.log(indent(`${mark("none")} ${home} does not exist`));
18827
18985
  else {
18828
18986
  if (!yes) {
@@ -18834,7 +18992,7 @@ async function uninstall(yes) {
18834
18992
  if (isCancel(answer) || !answer)
18835
18993
  return "cancelled";
18836
18994
  }
18837
- fs10.rmSync(home, { recursive: true, force: true });
18995
+ fs11.rmSync(home, { recursive: true, force: true });
18838
18996
  console.log(indent(`${mark("ok")} deleted ${home}`));
18839
18997
  }
18840
18998
  if (where.length > 1)