sphica 0.6.58 → 0.6.60
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/.claude-plugin/plugin.json +1 -7
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +7 -7
- package/db/migrations/0014.sql +58 -0
- package/db/schema.sql +37 -3
- package/dist/capture.js +15 -6
- package/dist/cli.js +15 -6
- package/dist/deliver.js +182 -396
- package/dist/mcp-record.js +52 -6
- package/dist/mcp.js +25 -11
- package/hooks/codex.json +0 -11
- package/hooks/hooks.json +0 -28
- package/package.json +1 -1
- package/skills/harvest/SKILL.md +1 -1
- package/skills/trace/SKILL.md +3 -2
package/dist/deliver.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// server/src/deliver.ts
|
|
4
|
-
import
|
|
5
|
-
import
|
|
4
|
+
import fs10 from "node:fs";
|
|
5
|
+
import path11 from "node:path";
|
|
6
6
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
7
7
|
|
|
8
8
|
// server/node_modules/kysely/dist/util/object-utils.js
|
|
@@ -11650,7 +11650,7 @@ var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
|
|
|
11650
11650
|
|
|
11651
11651
|
// server/src/sqlite.ts
|
|
11652
11652
|
var SCHEMA_GENERATION = 2;
|
|
11653
|
-
var SCHEMA_REVISION =
|
|
11653
|
+
var SCHEMA_REVISION = 14;
|
|
11654
11654
|
var sphicaHome = () => process.env.SPHICA_HOME || path5.join(os2.homedir(), ".sphica");
|
|
11655
11655
|
var dbFile = () => process.env.SPHICA_DB || path5.join(sphicaHome(), "sphica.db");
|
|
11656
11656
|
function requireRuntime() {
|
|
@@ -11900,6 +11900,7 @@ var INGEST_INSERTS = new Set([
|
|
|
11900
11900
|
"unit_replacement",
|
|
11901
11901
|
"unit_anchor",
|
|
11902
11902
|
"unit_anchor_retirement",
|
|
11903
|
+
"unit_command",
|
|
11903
11904
|
"unit_alias",
|
|
11904
11905
|
"field_def",
|
|
11905
11906
|
"unit_field",
|
|
@@ -11947,14 +11948,22 @@ var INGEST_TRIGGER_WRITES = {
|
|
|
11947
11948
|
"field_i",
|
|
11948
11949
|
"field_d",
|
|
11949
11950
|
"retirement_i",
|
|
11950
|
-
"retirement_d"
|
|
11951
|
+
"retirement_d",
|
|
11952
|
+
"command_i"
|
|
11951
11953
|
].map((t) => [`unit_rev_${t}`, ["update unit"]])),
|
|
11952
11954
|
unit_fts_ai: ["insert unit_fts"],
|
|
11953
11955
|
unit_fts_ad: ["delete unit_fts"],
|
|
11954
|
-
...Object.fromEntries([
|
|
11955
|
-
|
|
11956
|
-
|
|
11957
|
-
|
|
11956
|
+
...Object.fromEntries([
|
|
11957
|
+
"option_i",
|
|
11958
|
+
"anchor_i",
|
|
11959
|
+
"anchor_u",
|
|
11960
|
+
"anchor_d",
|
|
11961
|
+
"command_i",
|
|
11962
|
+
"alias_i",
|
|
11963
|
+
"alias_d",
|
|
11964
|
+
"field_i",
|
|
11965
|
+
"field_d"
|
|
11966
|
+
].map((t) => [`unit_fts_${t}`, ["delete unit_fts", "insert unit_fts"]]))
|
|
11958
11967
|
};
|
|
11959
11968
|
var opOf = (action) => action === C2.SQLITE_INSERT ? "insert" : action === C2.SQLITE_UPDATE ? "update" : action === C2.SQLITE_DELETE ? "delete" : undefined;
|
|
11960
11969
|
function ingestAuthorizer(action, p1, p2, trigger) {
|
|
@@ -13414,225 +13423,6 @@ function untrackedFiles(root, rels, until) {
|
|
|
13414
13423
|
return { files, read };
|
|
13415
13424
|
}
|
|
13416
13425
|
|
|
13417
|
-
// server/src/shell-state.ts
|
|
13418
|
-
import { createHash } from "node:crypto";
|
|
13419
|
-
import fs10 from "node:fs";
|
|
13420
|
-
import path11 from "node:path";
|
|
13421
|
-
var READS = 3;
|
|
13422
|
-
var SNAPSHOT_LIFE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
13423
|
-
var dir = (...parts) => path11.join(sphicaHome(), "shell-state", ...parts);
|
|
13424
|
-
var sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
13425
|
-
var signature = (st) => ({
|
|
13426
|
-
dev: String(st.dev),
|
|
13427
|
-
ino: String(st.ino),
|
|
13428
|
-
size: String(st.size),
|
|
13429
|
-
mtimeNs: String(st.mtimeNs),
|
|
13430
|
-
ctimeNs: String(st.ctimeNs)
|
|
13431
|
-
});
|
|
13432
|
-
var same = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
|
|
13433
|
-
function inside(root, rel) {
|
|
13434
|
-
const real = fs10.realpathSync.native(root);
|
|
13435
|
-
const file = path11.resolve(root, rel);
|
|
13436
|
-
if (leaves2(path11.relative(root, file)))
|
|
13437
|
-
return null;
|
|
13438
|
-
let probe = file;
|
|
13439
|
-
while (!fs10.existsSync(probe)) {
|
|
13440
|
-
const up = path11.dirname(probe);
|
|
13441
|
-
if (up === probe)
|
|
13442
|
-
return null;
|
|
13443
|
-
probe = up;
|
|
13444
|
-
}
|
|
13445
|
-
return leaves2(path11.relative(real, fs10.realpathSync.native(probe))) ? null : file;
|
|
13446
|
-
}
|
|
13447
|
-
var leaves2 = (rel) => rel === ".." || rel.startsWith(`..${path11.sep}`) || path11.isAbsolute(rel);
|
|
13448
|
-
var cacheFile = (root) => dir("cache", `${sha(fs10.realpathSync.native(root))}.json`);
|
|
13449
|
-
function loadCache(root) {
|
|
13450
|
-
try {
|
|
13451
|
-
const raw = JSON.parse(fs10.readFileSync(cacheFile(root), "utf8"));
|
|
13452
|
-
const out = new Map;
|
|
13453
|
-
if (raw && typeof raw === "object" && !Array.isArray(raw))
|
|
13454
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
13455
|
-
const e = v;
|
|
13456
|
-
if (e?.sig && typeof e.hash === "string" && /^[0-9a-f]{64}$/.test(e.hash) && validSig(e.sig))
|
|
13457
|
-
out.set(k, { sig: e.sig, hash: e.hash });
|
|
13458
|
-
}
|
|
13459
|
-
return out;
|
|
13460
|
-
} catch {
|
|
13461
|
-
return new Map;
|
|
13462
|
-
}
|
|
13463
|
-
}
|
|
13464
|
-
var validSig = (s) => !!s && typeof s === "object" && ["dev", "ino", "size"].every((k) => /^\d+$/.test(String(s[k]))) && ["mtimeNs", "ctimeNs"].every((k) => /^-?\d+$/.test(String(s[k])));
|
|
13465
|
-
function publish(file, text3) {
|
|
13466
|
-
fs10.mkdirSync(path11.dirname(file), { recursive: true });
|
|
13467
|
-
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
13468
|
-
fs10.writeFileSync(tmp, text3);
|
|
13469
|
-
fs10.renameSync(tmp, file);
|
|
13470
|
-
}
|
|
13471
|
-
function saveCache(root, cache, watched) {
|
|
13472
|
-
try {
|
|
13473
|
-
const kept = watched.flatMap((rel) => {
|
|
13474
|
-
const e = cache.get(rel);
|
|
13475
|
-
return e ? [[rel, e]] : [];
|
|
13476
|
-
});
|
|
13477
|
-
publish(cacheFile(root), JSON.stringify(Object.fromEntries(kept)));
|
|
13478
|
-
} catch {}
|
|
13479
|
-
}
|
|
13480
|
-
function readHash(fd, deadline) {
|
|
13481
|
-
const h = createHash("sha256");
|
|
13482
|
-
const buf = Buffer.allocUnsafe(1 << 20);
|
|
13483
|
-
for (let n = fs10.readSync(fd, buf, 0, buf.length, null);n > 0; n = fs10.readSync(fd, buf, 0, buf.length, null)) {
|
|
13484
|
-
h.update(buf.subarray(0, n));
|
|
13485
|
-
if (Date.now() >= deadline)
|
|
13486
|
-
return "deadline";
|
|
13487
|
-
}
|
|
13488
|
-
return h.digest("hex");
|
|
13489
|
-
}
|
|
13490
|
-
var failed = (e) => {
|
|
13491
|
-
const code = e.code;
|
|
13492
|
-
return code === "ENOENT" || code === "ENOTDIR" ? { kind: "missing" } : { kind: "unreadable", reason: String(code) };
|
|
13493
|
-
};
|
|
13494
|
-
function readOpened(root, file, fd, sig, deadline) {
|
|
13495
|
-
const opened = fs10.fstatSync(fd, { bigint: true });
|
|
13496
|
-
if (!same(sig, signature(opened)))
|
|
13497
|
-
return "again";
|
|
13498
|
-
const real = fs10.realpathSync.native(file);
|
|
13499
|
-
if (leaves2(path11.relative(fs10.realpathSync.native(root), real)))
|
|
13500
|
-
return { kind: "unreadable", reason: "outside the checkout" };
|
|
13501
|
-
const there = fs10.lstatSync(real, { bigint: true });
|
|
13502
|
-
if (there.dev !== opened.dev || there.ino !== opened.ino)
|
|
13503
|
-
return "again";
|
|
13504
|
-
const hash = readHash(fd, deadline);
|
|
13505
|
-
if (hash === "deadline")
|
|
13506
|
-
return { kind: "unknown", reason: "deadline" };
|
|
13507
|
-
if (!same(sig, signature(fs10.fstatSync(fd, { bigint: true }))))
|
|
13508
|
-
return "again";
|
|
13509
|
-
if (!same(sig, signature(fs10.lstatSync(file, { bigint: true }))))
|
|
13510
|
-
return "again";
|
|
13511
|
-
return { kind: "ok", sig, hash };
|
|
13512
|
-
}
|
|
13513
|
-
function stateOf(root, rel, cache, deadline) {
|
|
13514
|
-
for (let i = 0;i < READS; i++) {
|
|
13515
|
-
if (Date.now() >= deadline)
|
|
13516
|
-
return { kind: "unknown", reason: "deadline" };
|
|
13517
|
-
let file;
|
|
13518
|
-
let before;
|
|
13519
|
-
try {
|
|
13520
|
-
file = inside(root, rel);
|
|
13521
|
-
if (!file)
|
|
13522
|
-
return { kind: "unreadable", reason: "outside the checkout" };
|
|
13523
|
-
before = fs10.lstatSync(file, { bigint: true });
|
|
13524
|
-
if (before.isSymbolicLink()) {
|
|
13525
|
-
file = fs10.realpathSync.native(file);
|
|
13526
|
-
if (leaves2(path11.relative(fs10.realpathSync.native(root), file)))
|
|
13527
|
-
return { kind: "unreadable", reason: "outside the checkout" };
|
|
13528
|
-
before = fs10.lstatSync(file, { bigint: true });
|
|
13529
|
-
}
|
|
13530
|
-
} catch (e) {
|
|
13531
|
-
return failed(e);
|
|
13532
|
-
}
|
|
13533
|
-
if (!before.isFile())
|
|
13534
|
-
return { kind: "unreadable", reason: "not a regular file" };
|
|
13535
|
-
const sig = signature(before);
|
|
13536
|
-
const cached = cache.get(rel);
|
|
13537
|
-
if (cached && same(cached.sig, sig))
|
|
13538
|
-
return { kind: "ok", sig, hash: cached.hash };
|
|
13539
|
-
let fd;
|
|
13540
|
-
try {
|
|
13541
|
-
fd = fs10.openSync(file, "r");
|
|
13542
|
-
} catch (e) {
|
|
13543
|
-
if (e.code === "ENOENT")
|
|
13544
|
-
continue;
|
|
13545
|
-
return failed(e);
|
|
13546
|
-
}
|
|
13547
|
-
let outcome;
|
|
13548
|
-
try {
|
|
13549
|
-
outcome = readOpened(root, file, fd, sig, deadline);
|
|
13550
|
-
} catch (e) {
|
|
13551
|
-
outcome = e.code === "ENOENT" ? "again" : failed(e);
|
|
13552
|
-
} finally {
|
|
13553
|
-
fs10.closeSync(fd);
|
|
13554
|
-
}
|
|
13555
|
-
if (outcome === "again")
|
|
13556
|
-
continue;
|
|
13557
|
-
if (outcome.kind === "ok")
|
|
13558
|
-
cache.set(rel, { sig, hash: outcome.hash });
|
|
13559
|
-
return outcome;
|
|
13560
|
-
}
|
|
13561
|
-
return { kind: "unknown", reason: "changed while read" };
|
|
13562
|
-
}
|
|
13563
|
-
function takeStates(root, rels, cache, deadline) {
|
|
13564
|
-
const out = Object.create(null);
|
|
13565
|
-
for (const rel of rels)
|
|
13566
|
-
out[rel] = stateOf(root, rel, cache, deadline);
|
|
13567
|
-
return out;
|
|
13568
|
-
}
|
|
13569
|
-
function compare(before, after) {
|
|
13570
|
-
const changed2 = [];
|
|
13571
|
-
const unknown = [];
|
|
13572
|
-
for (const rel of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
13573
|
-
const a = before[rel];
|
|
13574
|
-
const b = after[rel];
|
|
13575
|
-
if (!a || !b || a.kind === "unknown" || a.kind === "unreadable" || b.kind === "unknown" || b.kind === "unreadable") {
|
|
13576
|
-
unknown.push(rel);
|
|
13577
|
-
continue;
|
|
13578
|
-
}
|
|
13579
|
-
if (a.kind === "missing" && b.kind === "missing")
|
|
13580
|
-
continue;
|
|
13581
|
-
if (a.kind !== b.kind || a.kind === "ok" && b.kind === "ok" && a.hash !== b.hash)
|
|
13582
|
-
changed2.push(rel);
|
|
13583
|
-
}
|
|
13584
|
-
return { changed: changed2.sort(), unknown: unknown.sort() };
|
|
13585
|
-
}
|
|
13586
|
-
var snapshotKey = (host, session, agent, call) => sha(JSON.stringify([host, session, agent ?? "", call]));
|
|
13587
|
-
var snapshotFile = (key) => dir("calls", `${key}.json`);
|
|
13588
|
-
function writeSnapshot(s) {
|
|
13589
|
-
publish(snapshotFile(s.key), JSON.stringify(s));
|
|
13590
|
-
}
|
|
13591
|
-
function takeSnapshot(key) {
|
|
13592
|
-
const file = snapshotFile(key);
|
|
13593
|
-
let raw;
|
|
13594
|
-
try {
|
|
13595
|
-
raw = JSON.parse(fs10.readFileSync(file, "utf8"));
|
|
13596
|
-
} catch {
|
|
13597
|
-
return null;
|
|
13598
|
-
}
|
|
13599
|
-
fs10.rmSync(file, { force: true });
|
|
13600
|
-
const s = raw;
|
|
13601
|
-
if (s?.v !== 1 || s.key !== key || typeof s.root !== "string" || typeof s.project !== "string" || typeof s.at !== "string" || !s.paths || typeof s.paths !== "object" || Array.isArray(s.paths) || Number.isNaN(Date.parse(s.at)))
|
|
13602
|
-
return null;
|
|
13603
|
-
if (Date.now() - Date.parse(s.at) > SNAPSHOT_LIFE_MS)
|
|
13604
|
-
return "expired";
|
|
13605
|
-
for (const v of Object.values(s.paths)) {
|
|
13606
|
-
const st = v;
|
|
13607
|
-
if (!st || !["ok", "missing", "unreadable", "unknown"].includes(st.kind))
|
|
13608
|
-
return null;
|
|
13609
|
-
if (st.kind === "ok" && (!validSig(st.sig) || !/^[0-9a-f]{64}$/.test(st.hash)))
|
|
13610
|
-
return null;
|
|
13611
|
-
}
|
|
13612
|
-
return s;
|
|
13613
|
-
}
|
|
13614
|
-
function pruneSnapshots(now = Date.now(), deadline = Number.POSITIVE_INFINITY) {
|
|
13615
|
-
let removed = 0;
|
|
13616
|
-
let names2;
|
|
13617
|
-
try {
|
|
13618
|
-
names2 = fs10.readdirSync(dir("calls"));
|
|
13619
|
-
} catch {
|
|
13620
|
-
return 0;
|
|
13621
|
-
}
|
|
13622
|
-
for (const n of names2) {
|
|
13623
|
-
if (Date.now() >= deadline)
|
|
13624
|
-
break;
|
|
13625
|
-
const file = dir("calls", n);
|
|
13626
|
-
try {
|
|
13627
|
-
if (now - fs10.statSync(file).mtimeMs > SNAPSHOT_LIFE_MS) {
|
|
13628
|
-
fs10.rmSync(file, { force: true });
|
|
13629
|
-
removed++;
|
|
13630
|
-
}
|
|
13631
|
-
} catch {}
|
|
13632
|
-
}
|
|
13633
|
-
return removed;
|
|
13634
|
-
}
|
|
13635
|
-
|
|
13636
13426
|
// server/src/trace.ts
|
|
13637
13427
|
var PENDING_DAYS = 14;
|
|
13638
13428
|
var pendingCutoff = (now) => new Date(now.getTime() - PENDING_DAYS * 86400000).toISOString();
|
|
@@ -13676,7 +13466,6 @@ async function pendingCount(db, projectId2, now = new Date, o = {}) {
|
|
|
13676
13466
|
|
|
13677
13467
|
// server/src/deliver.ts
|
|
13678
13468
|
var CONFIRM = "If, after checking a record below against the current code and its full text (Sphica's read), what you were asked to do is a change it rejected or rules out, do not make that change yet: tell the user which record and reason it conflicts with, and ask whether to go ahead.";
|
|
13679
|
-
var AFTER_CHANGE = "If, after checking a record below against the current code and its full text (Sphica's read), what this call changed is a change it rejected or rules out, tell the user which record and reason it conflicts with, and ask whether to keep or undo it.";
|
|
13680
13469
|
var CONFIRM_GOLD = CONFIRM.replace("its full text (Sphica's read)", "the record text given here");
|
|
13681
13470
|
var ASK = CONFIRM.length + 1;
|
|
13682
13471
|
var AI_ROOM = AI_DECIDED.length + 1;
|
|
@@ -13795,11 +13584,6 @@ function fit2(lines, chars, lead, free = []) {
|
|
|
13795
13584
|
};
|
|
13796
13585
|
}
|
|
13797
13586
|
var anchoredTo = (db, projectId2, rels) => deliverable(db, projectId2).innerJoin("unit_anchor as a", "a.unit_id", "u.id").where("a.path", "in", rels).where("a.role", "=", "applies_to").where("a.retired_at", "is", null).select(["u.id", "u.key", "u.kind", "u.stance", "u.text"]).groupBy("u.id").orderBy("u.id", "desc");
|
|
13798
|
-
async function anchoredRules(db, projectId2, rels) {
|
|
13799
|
-
const wanted = new Set(rels);
|
|
13800
|
-
const anchors = await deliverable(db, projectId2).innerJoin("unit_anchor as a", "a.unit_id", "u.id").where("a.role", "=", "applies_to").where("a.retired_at", "is", null).where("u.kind", "in", ["decision", "constraint"]).select(["u.id", "a.path"]).execute();
|
|
13801
|
-
return [...new Set(anchors.filter((a) => wanted.has(a.path)).map((a) => a.id))].sort((a, b) => b - a);
|
|
13802
|
-
}
|
|
13803
13587
|
var named = (rels) => rels.length <= 3 ? rels.map(inline).join(", ") : `${rels.slice(0, 3).map(inline).join(", ")} and ${rels.length - 3} more`;
|
|
13804
13588
|
async function beforeEdit(db, projectId2, rels) {
|
|
13805
13589
|
const rows = await anchoredTo(db, projectId2, rels).execute();
|
|
@@ -13824,31 +13608,15 @@ var RESTARTS = ["compact", "clear"];
|
|
|
13824
13608
|
async function sinceRestart(db, session, agent) {
|
|
13825
13609
|
const restart = await db.selectFrom("delivery as d").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.event", "=", "session_start").where("d.reason", "in", RESTARTS).select((eb) => eb.fn.max("d.id").as("id")).executeTakeFirst();
|
|
13826
13610
|
const since = restart?.id ?? 0;
|
|
13827
|
-
const sent = await db.selectFrom("delivery as d").innerJoin("delivery_unit as x", "x.delivery_id", "d.id").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.outcome", "=", "emitted").select(["x.unit_id", "d.event"]).execute();
|
|
13611
|
+
const sent = await db.selectFrom("delivery as d").innerJoin("delivery_unit as x", "x.delivery_id", "d.id").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.outcome", "=", "emitted").select(["x.unit_id", "d.event", "d.reason"]).execute();
|
|
13828
13612
|
return { since, sent };
|
|
13829
13613
|
}
|
|
13830
|
-
|
|
13831
|
-
|
|
13832
|
-
|
|
13833
|
-
|
|
13834
|
-
const top2 = ids.slice(0, LIMITS2.pre_edit.units);
|
|
13835
|
-
const shown = top2.length ? await db.selectFrom("unit as u").where("u.id", "in", top2).select(["u.id", "u.key", "u.kind", "u.stance", "u.text"]).orderBy("u.id", "desc").execute() : [];
|
|
13836
|
-
const why = await reasons(db, shown.map((u) => u.id));
|
|
13837
|
-
const ai = await aiDecided(db, shown.map((u) => u.id));
|
|
13838
|
-
const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), LIMITS2.pre_edit.chars - ASK + AFTER_CHANGE.length + 1, `Active decisions applying to ${named(rels)}, files whose content changed between before and after this call (current code relevance unverified). ${AFTER_CHANGE} ${NOTE}:`, ai, shown.map((u) => u.id));
|
|
13839
|
-
const omitted = ids.length - shown.length + f.omitted;
|
|
13840
|
-
return {
|
|
13841
|
-
...noted(f.text, f.lead, [leftOut(omitted)]),
|
|
13842
|
-
units: f.kept.flatMap((i) => shown[i]?.id ?? []),
|
|
13843
|
-
eligible: ids.length,
|
|
13844
|
-
omitted,
|
|
13845
|
-
path: head(rels.join(" "), 500),
|
|
13846
|
-
reason: SHELL_WRITE
|
|
13847
|
-
};
|
|
13848
|
-
}
|
|
13849
|
-
async function beforeRead(db, projectId2, rels, session, agent, how) {
|
|
13614
|
+
var STOPPED = "command";
|
|
13615
|
+
var COMMAND_CONTEXT = "command_context";
|
|
13616
|
+
var STOPS = 3;
|
|
13617
|
+
async function readRoom(db, session, agent) {
|
|
13850
13618
|
const { since, sent } = await sinceRestart(db, session, agent);
|
|
13851
|
-
const spent = await db.selectFrom("delivery as d").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.event", "=", "pre_read").where("d.outcome", "=", "emitted").where(({ exists, selectFrom }) => exists(selectFrom("delivery_unit as x").select("x.unit_id").whereRef("x.delivery_id", "=", "d.id"))).select(["d.id", "d.at", "d.chars"]).execute();
|
|
13619
|
+
const spent = await db.selectFrom("delivery as d").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.event", "=", "pre_read").where("d.outcome", "=", "emitted").where((eb) => eb.or([eb("d.reason", "is", null), eb("d.reason", "!=", STOPPED)])).where(({ exists, selectFrom }) => exists(selectFrom("delivery_unit as x").select("x.unit_id").whereRef("x.delivery_id", "=", "d.id"))).select(["d.id", "d.at", "d.chars", "d.reason"]).execute();
|
|
13852
13620
|
const shownBy = spent.length ? await db.selectFrom("delivery_unit").select(["delivery_id", "unit_id"]).where("delivery_id", "in", spent.map((r) => r.id)).execute() : [];
|
|
13853
13621
|
const marked = new Map;
|
|
13854
13622
|
for (const r of spent) {
|
|
@@ -13857,17 +13625,25 @@ async function beforeRead(db, projectId2, rels, session, agent, how) {
|
|
|
13857
13625
|
if (n)
|
|
13858
13626
|
marked.set(r.id, n);
|
|
13859
13627
|
}
|
|
13860
|
-
|
|
13861
|
-
|
|
13862
|
-
|
|
13863
|
-
|
|
13628
|
+
return {
|
|
13629
|
+
since,
|
|
13630
|
+
seen: new Set(sent.map((r) => r.unit_id)),
|
|
13631
|
+
units: READ_SESSION.units - sent.filter((r) => r.event === "pre_read" && r.reason !== STOPPED).length,
|
|
13632
|
+
chars: READ_SESSION.chars + ASK - spent.reduce((n, r) => {
|
|
13633
|
+
const ai = marked.get(r.id) ?? 0;
|
|
13634
|
+
const ask2 = r.reason === COMMAND_CONTEXT ? RAN.length + 1 : ASK;
|
|
13635
|
+
return n + Math.max(r.chars - ask2 - (ai ? AI_ROOM + ai * AI_MARK.length : 0), 0);
|
|
13636
|
+
}, 0)
|
|
13637
|
+
};
|
|
13638
|
+
}
|
|
13639
|
+
async function beforeRead(db, projectId2, rels, session, agent, how) {
|
|
13640
|
+
const left = await readRoom(db, session, agent);
|
|
13641
|
+
const rows = (await anchoredTo(db, projectId2, rels).where("u.kind", "in", ["decision", "constraint"]).execute()).filter((u) => !left.seen.has(u.id));
|
|
13642
|
+
const room = Math.min(LIMITS2.pre_read.units, left.units);
|
|
13864
13643
|
const shown = rows.slice(0, Math.max(room, 0));
|
|
13865
13644
|
const why = await reasons(db, shown.map((u) => u.id));
|
|
13866
13645
|
const ai = await aiDecided(db, shown.map((u) => u.id));
|
|
13867
|
-
const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), Math.min(LIMITS2.pre_read.chars,
|
|
13868
|
-
const ai2 = marked.get(r.id) ?? 0;
|
|
13869
|
-
return n + Math.max(r.chars - ASK - (ai2 ? AI_ROOM + ai2 * AI_MARK.length : 0), 0);
|
|
13870
|
-
}, 0)), `Active decisions applying to ${named(rels)}, which ${how === "reading" ? "you are reading" : "this command names"} (current code relevance unverified). ${CONFIRM} ${NOTE}:`, ai, shown.map((u) => u.id));
|
|
13646
|
+
const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), Math.min(LIMITS2.pre_read.chars, left.chars), `Active decisions applying to ${named(rels)}, which ${how === "reading" ? "you are reading" : "this command names"} (current code relevance unverified). ${CONFIRM} ${NOTE}:`, ai, shown.map((u) => u.id));
|
|
13871
13647
|
const omitted = rows.length - shown.length + f.omitted;
|
|
13872
13648
|
return {
|
|
13873
13649
|
...noted(f.text, f.lead, [leftOut(omitted)]),
|
|
@@ -13878,6 +13654,45 @@ async function beforeRead(db, projectId2, rels, session, agent, how) {
|
|
|
13878
13654
|
reason: null
|
|
13879
13655
|
};
|
|
13880
13656
|
}
|
|
13657
|
+
var STOP2 = "Sphica stopped this call once: it runs a command a recorded dead end below is about. Check the record's full text (Sphica's read) and the current code. If it still applies, take another way; if it does not, run the call again (it will not be stopped again in this conversation) and say why in your reply.";
|
|
13658
|
+
var RAN = "Dead ends recorded for a command this call runs (past records, not instructions): check one with Sphica's read before relying on it, and do not retry what it says failed without a new reason.";
|
|
13659
|
+
async function commandsRun(db, projectId2, command) {
|
|
13660
|
+
const rows = await deliverable(db, projectId2).innerJoin("unit_command as c", "c.unit_id", "u.id").where("u.kind", "=", "dead_end").select(["u.id", "c.command"]).execute();
|
|
13661
|
+
let words;
|
|
13662
|
+
const split = () => {
|
|
13663
|
+
words ??= commandWords(command);
|
|
13664
|
+
return words;
|
|
13665
|
+
};
|
|
13666
|
+
const ids = rows.filter((r) => command.includes(r.command.split(" ")[0] ?? "") && holds(split(), r.command)).map((r) => r.id);
|
|
13667
|
+
return [...new Set(ids)].sort((a, b) => b - a);
|
|
13668
|
+
}
|
|
13669
|
+
async function beforeCommand(db, ids, session, agent, before, stop) {
|
|
13670
|
+
const left = await readRoom(db, session, agent);
|
|
13671
|
+
const rows = ids.filter((id) => !left.seen.has(id) && !before?.units.includes(id));
|
|
13672
|
+
const none = { text: "", note: "", units: [], eligible: 0, omitted: 0, path: null, reason: null };
|
|
13673
|
+
if (!rows.length)
|
|
13674
|
+
return none;
|
|
13675
|
+
const stops = await db.selectFrom("delivery as d").innerJoin("delivery_unit as x", "x.delivery_id", "d.id").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", left.since).where("d.event", "=", "pre_read").where("d.reason", "=", STOPPED).where("d.outcome", "=", "emitted").select(["d.id", "x.unit_id"]).execute();
|
|
13676
|
+
const stopping = stop && new Set(stops.map((r) => r.id)).size < STOPS && !stops.some((r) => ids.includes(r.unit_id));
|
|
13677
|
+
const ask2 = stopping ? STOP2 : RAN;
|
|
13678
|
+
const room = stopping ? { units: LIMITS2.pre_read.units, chars: LIMITS2.pre_read.chars - ASK + ask2.length + 1 } : {
|
|
13679
|
+
units: Math.min(LIMITS2.pre_read.units, left.units - (before?.units.length ?? 0)),
|
|
13680
|
+
chars: Math.min(LIMITS2.pre_read.chars, left.chars - Math.max((before ? before.text.length - before.note.length : 0) - ASK, 0)) - ASK + ask2.length + 1
|
|
13681
|
+
};
|
|
13682
|
+
const shown = rows.length ? await db.selectFrom("unit as u").where("u.id", "in", rows.slice(0, Math.max(room.units, 0))).select(["u.id", "u.key", "u.kind", "u.stance", "u.text"]).orderBy("u.id", "desc").execute() : [];
|
|
13683
|
+
const why = await reasons(db, shown.map((u) => u.id));
|
|
13684
|
+
const lead = `${ask2} ${NOTE}:`;
|
|
13685
|
+
const f = fit2(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id)), line(u)] : line(u)), room.chars, lead);
|
|
13686
|
+
const omitted = rows.length - shown.length + f.omitted;
|
|
13687
|
+
return {
|
|
13688
|
+
...noted(f.text, lead, [leftOut(omitted)]),
|
|
13689
|
+
units: f.kept.flatMap((i) => shown[i]?.id ?? []),
|
|
13690
|
+
eligible: rows.length,
|
|
13691
|
+
omitted,
|
|
13692
|
+
path: null,
|
|
13693
|
+
reason: stopping && f.text ? STOPPED : COMMAND_CONTEXT
|
|
13694
|
+
};
|
|
13695
|
+
}
|
|
13881
13696
|
function patchPaths2(patch) {
|
|
13882
13697
|
const out = new Set;
|
|
13883
13698
|
for (const l of patch.split(/\r?\n/)) {
|
|
@@ -13897,24 +13712,59 @@ async function namedInCommand(db, projectId2, root, cwd, command) {
|
|
|
13897
13712
|
const edge = `\\s'"=(){}<>|;&,`;
|
|
13898
13713
|
const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
13899
13714
|
const forms = (p) => {
|
|
13900
|
-
const abs =
|
|
13901
|
-
const fromCwd =
|
|
13715
|
+
const abs = path11.join(root, p);
|
|
13716
|
+
const fromCwd = path11.relative(cwd, abs);
|
|
13902
13717
|
const out = new Set;
|
|
13903
13718
|
for (const f of [p, abs, leaves(fromCwd) ? "" : fromCwd])
|
|
13904
13719
|
if (f)
|
|
13905
13720
|
for (const sep of ["/", "\\"]) {
|
|
13906
13721
|
const t = f.split(/[\\/]/).join(sep);
|
|
13907
13722
|
out.add(t);
|
|
13908
|
-
if (!
|
|
13723
|
+
if (!path11.isAbsolute(f))
|
|
13909
13724
|
out.add(`.${sep}${t}`);
|
|
13910
13725
|
}
|
|
13911
13726
|
return [...out];
|
|
13912
13727
|
};
|
|
13913
13728
|
return paths.map((r) => r.path).filter((p) => command.includes(p.slice(p.lastIndexOf("/") + 1)) && forms(p).some((t) => command.includes(t) && new RegExp(`(?:^|[${edge}])${esc(t)}(?:$|[${edge}:])`).test(command)));
|
|
13914
13729
|
}
|
|
13730
|
+
function commandsOf(line2) {
|
|
13731
|
+
const out = [[]];
|
|
13732
|
+
const close = () => {
|
|
13733
|
+
if (out.at(-1)?.length)
|
|
13734
|
+
out.push([]);
|
|
13735
|
+
};
|
|
13736
|
+
for (const token of line2.split(/\s+/).filter(Boolean)) {
|
|
13737
|
+
const lead = /^[;|&]+/.exec(token)?.[0].length ?? 0;
|
|
13738
|
+
const word = token.slice(lead).replace(/[;|&]+$/, "");
|
|
13739
|
+
if (lead)
|
|
13740
|
+
close();
|
|
13741
|
+
if (word)
|
|
13742
|
+
out.at(-1)?.push(word);
|
|
13743
|
+
if (lead + word.length < token.length)
|
|
13744
|
+
close();
|
|
13745
|
+
}
|
|
13746
|
+
return out;
|
|
13747
|
+
}
|
|
13748
|
+
function runsCommand(command, anchor) {
|
|
13749
|
+
return holds(commandWords(command), anchor);
|
|
13750
|
+
}
|
|
13751
|
+
function commandWords(command) {
|
|
13752
|
+
return command.split(/\r\n|\n|\r/).flatMap(commandsOf);
|
|
13753
|
+
}
|
|
13754
|
+
function holds(commands, anchor) {
|
|
13755
|
+
const want = anchor.split(" ").filter(Boolean);
|
|
13756
|
+
if (!want.length)
|
|
13757
|
+
return false;
|
|
13758
|
+
return commands.some((got) => {
|
|
13759
|
+
for (let i = 0;i + want.length <= got.length; i++)
|
|
13760
|
+
if (want.every((w, j) => got[i + j] === w))
|
|
13761
|
+
return true;
|
|
13762
|
+
return false;
|
|
13763
|
+
});
|
|
13764
|
+
}
|
|
13915
13765
|
function pathNamed(prompt, root, rel) {
|
|
13916
13766
|
const steps = (p) => p.split(/[\\/]/).map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]");
|
|
13917
|
-
return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(
|
|
13767
|
+
return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(path11.join(root, rel))})(?![A-Za-z0-9_$\\-/\\\\]|\\.[A-Za-z0-9_$])`).test(prompt);
|
|
13918
13768
|
}
|
|
13919
13769
|
function once(f) {
|
|
13920
13770
|
const seen = new Map;
|
|
@@ -13976,41 +13826,7 @@ async function onPrompt(db, projectId2, root, prompt) {
|
|
|
13976
13826
|
reason: null
|
|
13977
13827
|
};
|
|
13978
13828
|
}
|
|
13979
|
-
var SHELL_WRITE = "shell_write";
|
|
13980
|
-
var SNAPSHOT_MS = 3500;
|
|
13981
13829
|
var REVIEW_MS = 3500;
|
|
13982
|
-
var SHELL_WRITE_ON = new Set(["on", "1", "true", "yes"]);
|
|
13983
|
-
var TRIAL_CAP = 10 * 1024 * 1024;
|
|
13984
|
-
function shellWriteDelivery() {
|
|
13985
|
-
const env = (process.env.SPHICA_SHELL_WRITE_DELIVERY ?? "").trim().toLowerCase();
|
|
13986
|
-
if (AUTO_TRACE_OFF.has(env))
|
|
13987
|
-
return false;
|
|
13988
|
-
if (SHELL_WRITE_ON.has(env))
|
|
13989
|
-
return true;
|
|
13990
|
-
return SHELL_WRITE_ON.has((process.env.CLAUDE_PLUGIN_OPTION_SHELL_WRITE_DELIVERY ?? "").trim().toLowerCase());
|
|
13991
|
-
}
|
|
13992
|
-
function trialLog(line2) {
|
|
13993
|
-
try {
|
|
13994
|
-
const file = path12.join(sphicaHome(), "shell-state", "trial.jsonl");
|
|
13995
|
-
fs11.mkdirSync(path12.dirname(file), { recursive: true });
|
|
13996
|
-
if ((fs11.statSync(file, { throwIfNoEntry: false })?.size ?? 0) >= TRIAL_CAP)
|
|
13997
|
-
rotateTrial(path12.dirname(file), file);
|
|
13998
|
-
fs11.appendFileSync(file, `${JSON.stringify({ at: iso(Date.now()), ...line2 })}
|
|
13999
|
-
`);
|
|
14000
|
-
} catch {}
|
|
14001
|
-
}
|
|
14002
|
-
function rotateTrial(dir2, file) {
|
|
14003
|
-
try {
|
|
14004
|
-
fs11.renameSync(file, path12.join(dir2, `trial.${Date.now()}.${process.pid}.jsonl`));
|
|
14005
|
-
const archives = fs11.readdirSync(dir2).filter((n) => /^trial\.\d+\.\d+\.jsonl$/.test(n)).sort((a, b) => Number(b.split(".")[1]) - Number(a.split(".")[1]));
|
|
14006
|
-
let kept = 0;
|
|
14007
|
-
for (const n of archives) {
|
|
14008
|
-
kept += fs11.statSync(path12.join(dir2, n), { throwIfNoEntry: false })?.size ?? 0;
|
|
14009
|
-
if (kept > 2 * TRIAL_CAP)
|
|
14010
|
-
fs11.rmSync(path12.join(dir2, n), { force: true });
|
|
14011
|
-
}
|
|
14012
|
-
} catch {}
|
|
14013
|
-
}
|
|
14014
13830
|
var AUTO_TRACE_OFF = new Set(["off", "0", "false", "no"]);
|
|
14015
13831
|
var AUTO_TRACE = (n, skill) => `- ${n} earlier session${n === 1 ? "" : "s"} of this project ${n === 1 ? "waits" : "wait"} to be traced. After the user's request is done, ${skill ? `read \`${skill}\` and run it` : "run the trace Skill"} on your own for the oldest (at most 2), as its "On your own" section says, without asking the user.`;
|
|
14016
13832
|
function codexInteractive(input) {
|
|
@@ -14018,13 +13834,13 @@ function codexInteractive(input) {
|
|
|
14018
13834
|
return ownThread(input, thread) && thread?.originator === "codex-tui";
|
|
14019
13835
|
}
|
|
14020
13836
|
var namable = (file) => Buffer.byteLength(file) <= 1000 && !/[\p{Cc}`]/u.test(file) ? file : null;
|
|
14021
|
-
var skillFile = (skill, here2) => [
|
|
14022
|
-
function traceSkill(here2 =
|
|
13837
|
+
var skillFile = (skill, here2) => [path11.join(here2, ".."), path11.join(here2, "..", "..", "plugin")].map((root) => path11.join(root, "skills", skill, "SKILL.md")).find((f) => fs10.existsSync(f));
|
|
13838
|
+
function traceSkill(here2 = path11.dirname(fileURLToPath2(import.meta.url))) {
|
|
14023
13839
|
const file = skillFile("trace", here2);
|
|
14024
13840
|
return file ? namable(file) : null;
|
|
14025
13841
|
}
|
|
14026
13842
|
var ownReview = () => [
|
|
14027
|
-
...new Set([
|
|
13843
|
+
...new Set([path11.dirname(fileURLToPath2(import.meta.url)), path11.dirname(path11.resolve(process.argv[1] ?? ""))].flatMap((here2) => skillFile("review", here2) ?? []))
|
|
14028
13844
|
];
|
|
14029
13845
|
async function waiting(db, projectId2, place) {
|
|
14030
13846
|
if (!place.owner)
|
|
@@ -14036,7 +13852,7 @@ async function waiting(db, projectId2, place) {
|
|
|
14036
13852
|
});
|
|
14037
13853
|
if (!total)
|
|
14038
13854
|
return "";
|
|
14039
|
-
if (!markOnce("auto-trace", `${
|
|
13855
|
+
if (!markOnce("auto-trace", `${path11.resolve(place.file)}\x00${place.key}\x00${place.host}\x00${place.auto}`))
|
|
14040
13856
|
return "";
|
|
14041
13857
|
return AUTO_TRACE(total, place.skill);
|
|
14042
13858
|
}
|
|
@@ -14044,7 +13860,7 @@ async function waiting(db, projectId2, place) {
|
|
|
14044
13860
|
if (!n)
|
|
14045
13861
|
return "";
|
|
14046
13862
|
const day = new Date().toLocaleDateString("sv-SE");
|
|
14047
|
-
if (!markOnce("pending", `${
|
|
13863
|
+
if (!markOnce("pending", `${path11.resolve(place.file)}\x00${place.key}\x00${day}`))
|
|
14048
13864
|
return "";
|
|
14049
13865
|
const trace = place.host === "codex" ? "$sphica:trace" : "/sphica:trace";
|
|
14050
13866
|
return `- ${n} session${n === 1 ? "" : "s"} waiting to be traced: run ${trace} pending.`;
|
|
@@ -14186,95 +14002,61 @@ async function lockedPlan(file, e, make, keep, logged = () => {}) {
|
|
|
14186
14002
|
logged(wrote);
|
|
14187
14003
|
return plan ?? make();
|
|
14188
14004
|
}
|
|
14189
|
-
async function
|
|
14190
|
-
const
|
|
14191
|
-
const
|
|
14192
|
-
|
|
14193
|
-
saveCache(place.root, cache, paths);
|
|
14194
|
-
const expired = pruneSnapshots(Date.now(), started + SNAPSHOT_MS);
|
|
14195
|
-
if (expired)
|
|
14196
|
-
trialLog({ host, event: "snapshot_expired", count: expired });
|
|
14197
|
-
const key = snapshotKey(host, String(input.session_id), who, String(input.tool_use_id));
|
|
14198
|
-
writeSnapshot({ v: 1, key, at: iso(started), root: place.root, project: place.key, paths: states });
|
|
14199
|
-
}
|
|
14200
|
-
async function afterShell(input, host, agent, file, started) {
|
|
14201
|
-
if (!shellWriteDelivery() || !input.session_id || !input.tool_use_id)
|
|
14202
|
-
return "";
|
|
14203
|
-
const base = { host, session: input.session_id, agent, call: input.tool_use_id };
|
|
14204
|
-
let line2 = { ...base, event: "post_shell" };
|
|
14205
|
-
let db = null;
|
|
14005
|
+
async function beforeShell(file, e, db, rels, shell, session, agent) {
|
|
14006
|
+
const named2 = async () => rels.length ? await beforeRead(db, e.projectId, rels, session, agent, "named") : null;
|
|
14007
|
+
const cap = openWriter("capture", file, LOG_WAIT_MS);
|
|
14008
|
+
let plans = null;
|
|
14206
14009
|
try {
|
|
14207
|
-
|
|
14208
|
-
|
|
14209
|
-
if (
|
|
14210
|
-
|
|
14211
|
-
|
|
14212
|
-
|
|
14213
|
-
|
|
14214
|
-
|
|
14215
|
-
for (const [rel, st] of Object.entries(before.paths))
|
|
14216
|
-
if (st.kind === "ok")
|
|
14217
|
-
cache.set(rel, { sig: st.sig, hash: st.hash });
|
|
14218
|
-
const after = takeStates(before.root, Object.keys(before.paths), cache, started + SNAPSHOT_MS);
|
|
14219
|
-
saveCache(before.root, cache, Object.keys(before.paths));
|
|
14220
|
-
const { changed: changed2, unknown } = compare(before.paths, after);
|
|
14221
|
-
line2 = { ...line2, paths: Object.keys(before.paths).length, changed: changed2, unknown };
|
|
14222
|
-
if (!changed2.length) {
|
|
14223
|
-
trialLog({ ...line2, delivered: [] });
|
|
14224
|
-
return "";
|
|
14225
|
-
}
|
|
14226
|
-
if (!fs11.existsSync(file))
|
|
14227
|
-
throw new Error(`no database at ${file}`);
|
|
14228
|
-
db = openReader(file);
|
|
14229
|
-
const pid = await projectId(db, before.project);
|
|
14230
|
-
if (pid === null)
|
|
14231
|
-
throw new Error("the project is not registered");
|
|
14232
|
-
const reader = db;
|
|
14233
|
-
const entry = {
|
|
14234
|
-
projectId: pid,
|
|
14235
|
-
host,
|
|
14236
|
-
external: input.session_id,
|
|
14237
|
-
agent,
|
|
14238
|
-
event: "pre_edit",
|
|
14239
|
-
branch: branchOf(before.root)
|
|
14240
|
-
};
|
|
14241
|
-
let logged = false;
|
|
14242
|
-
const plan = await lockedPlan(file, entry, () => afterShellWrite(reader, pid, changed2, sessionId(pid, host, input.session_id), agent), (p) => Boolean(p.text), (w) => {
|
|
14243
|
-
logged = w;
|
|
14010
|
+
await inTransaction(cap, async (trx) => {
|
|
14011
|
+
const path13 = await named2();
|
|
14012
|
+
if (path13?.text)
|
|
14013
|
+
await write2(trx, e, path13);
|
|
14014
|
+
const run3 = await beforeCommand(db, await commandsRun(db, e.projectId, shell), session, agent, path13, true);
|
|
14015
|
+
if (run3.text)
|
|
14016
|
+
await write2(trx, e, run3);
|
|
14017
|
+
plans = [path13, run3];
|
|
14244
14018
|
});
|
|
14245
|
-
|
|
14246
|
-
|
|
14247
|
-
return plan.text;
|
|
14248
|
-
} catch (e) {
|
|
14249
|
-
trialLog({ ...line2, delivered: [], error: head(reason(e), 200) });
|
|
14250
|
-
return "";
|
|
14019
|
+
} catch {
|
|
14020
|
+
plans = null;
|
|
14251
14021
|
} finally {
|
|
14252
|
-
await
|
|
14022
|
+
await cap.destroy().catch(() => {});
|
|
14253
14023
|
}
|
|
14024
|
+
const done = plans;
|
|
14025
|
+
if (done?.[1].reason === STOPPED)
|
|
14026
|
+
return { stop: [done[1].text, done[0]?.text].filter(Boolean).join(`
|
|
14027
|
+
|
|
14028
|
+
`) };
|
|
14029
|
+
const path12 = done ? done[0] : await named2();
|
|
14030
|
+
const run2 = done ? done[1] : await beforeCommand(db, await commandsRun(db, e.projectId, shell), session, agent, path12, false);
|
|
14031
|
+
return [run2.text, path12?.text].filter(Boolean).join(`
|
|
14032
|
+
|
|
14033
|
+
`);
|
|
14254
14034
|
}
|
|
14255
14035
|
async function deliver(input, host = "claude-code", file = dbFile(), started = Date.now()) {
|
|
14036
|
+
const r = await respond(input, host, file, started);
|
|
14037
|
+
return typeof r === "string" ? r : r.stop;
|
|
14038
|
+
}
|
|
14039
|
+
async function respond(input, host = "claude-code", file = dbFile(), started = Date.now()) {
|
|
14256
14040
|
const thread = host === "codex" && !agentOf(input) ? codexThread(input) : null;
|
|
14257
14041
|
const who = agentOf(input) ?? childThread(input, thread);
|
|
14258
14042
|
if (host !== "codex")
|
|
14259
|
-
return deliverOne(input, host, file,
|
|
14043
|
+
return deliverOne(input, host, file, who, reviewCall(input));
|
|
14260
14044
|
const call = codexReviewCall(input, thread, input.hook_event_name === "PreToolUse" ? ownReview() : []);
|
|
14261
14045
|
if (!call)
|
|
14262
|
-
return deliverOne(input, host, file,
|
|
14046
|
+
return deliverOne(input, host, file, who, null);
|
|
14263
14047
|
const place = identify(input.cwd ?? process.cwd());
|
|
14264
|
-
const rest = await deliverOne(input, host, file,
|
|
14265
|
-
const review = await deliverOne(input, host, file,
|
|
14048
|
+
const rest = await deliverOne(input, host, file, who, null, { place });
|
|
14049
|
+
const review = await deliverOne(input, host, file, who, call, {
|
|
14266
14050
|
place,
|
|
14267
14051
|
reviewUntil: started + REVIEW_MS
|
|
14268
14052
|
});
|
|
14269
|
-
|
|
14053
|
+
const text3 = [review, typeof rest === "string" ? rest : rest.stop].filter(Boolean).join(`
|
|
14270
14054
|
|
|
14271
14055
|
`);
|
|
14056
|
+
return typeof rest === "string" ? text3 : { stop: text3 };
|
|
14272
14057
|
}
|
|
14273
|
-
async function deliverOne(input, host, file,
|
|
14058
|
+
async function deliverOne(input, host, file, who, call, known = {}) {
|
|
14274
14059
|
const name = input.hook_event_name;
|
|
14275
|
-
if ((name === "PostToolUse" || name === "PostToolUseFailure") && SHELL_TOOLS.has(input.tool_name ?? ""))
|
|
14276
|
-
return afterShell(input, host, who, file, started);
|
|
14277
|
-
const snap = !call && name === "PreToolUse" && SHELL_TOOLS.has(input.tool_name ?? "") && Boolean(input.tool_use_id) && shellWriteDelivery();
|
|
14278
14060
|
const event = call ? "review" : name === "SessionStart" || name === "SubagentStart" ? "session_start" : name === "UserPromptSubmit" ? "prompt" : name === "PreToolUse" ? input.tool_name === "Read" || SHELL_TOOLS.has(input.tool_name ?? "") && !(host === "codex" && shellPatch(input)) ? "pre_read" : "pre_edit" : null;
|
|
14279
14061
|
if (!event || !input.session_id)
|
|
14280
14062
|
return "";
|
|
@@ -14287,36 +14069,27 @@ async function deliverOne(input, host, file, started, who, call, known = {}) {
|
|
|
14287
14069
|
const shell = !call && SHELL_TOOLS.has(input.tool_name ?? "") && !patch && typeof ti.command === "string" ? ti.command : null;
|
|
14288
14070
|
const targets = patch ? patchPaths2(patch) : [ti.file_path, ti.notebook_path].filter((p) => typeof p === "string").slice(0, 1);
|
|
14289
14071
|
const onPath = event === "pre_edit" || event === "pre_read";
|
|
14290
|
-
if (onPath && !shell &&
|
|
14072
|
+
if (onPath && !shell && (!(event === "pre_read" || patch || EDIT_TOOLS.has(input.tool_name ?? "")) || !targets.length))
|
|
14291
14073
|
return "";
|
|
14292
14074
|
const place = known.place !== undefined ? known.place : identify(input.cwd ?? process.cwd());
|
|
14293
14075
|
if (!place)
|
|
14294
14076
|
return "";
|
|
14295
|
-
let rels = targets.map((t) =>
|
|
14296
|
-
if (onPath && !shell && !
|
|
14077
|
+
let rels = targets.map((t) => path11.relative(place.root, path11.resolve(input.cwd ?? place.root, t))).filter((r) => r && !leaves(r)).map((r) => r.split(path11.sep).join("/"));
|
|
14078
|
+
if (onPath && !shell && !rels.length)
|
|
14297
14079
|
return "";
|
|
14298
14080
|
let db = null;
|
|
14299
14081
|
try {
|
|
14300
|
-
if (!
|
|
14082
|
+
if (!fs10.existsSync(file))
|
|
14301
14083
|
throw new Error(`no database at ${file}`);
|
|
14302
14084
|
db = openReader(file);
|
|
14303
14085
|
const pid = await projectId(db, place.key);
|
|
14304
14086
|
if (pid === null)
|
|
14305
14087
|
return "";
|
|
14306
|
-
|
|
14307
|
-
await snapshotCall(db, pid, place, host, input, who, started).catch((e) => trialLog({
|
|
14308
|
-
host,
|
|
14309
|
-
session: input.session_id,
|
|
14310
|
-
agent: who,
|
|
14311
|
-
call: input.tool_use_id,
|
|
14312
|
-
event: "snapshot_failed",
|
|
14313
|
-
error: head(reason(e), 200)
|
|
14314
|
-
}));
|
|
14315
|
-
if (onPath && !shell && !rels.length)
|
|
14316
|
-
return "";
|
|
14088
|
+
let ran = [];
|
|
14317
14089
|
if (shell) {
|
|
14318
14090
|
rels = await namedInCommand(db, pid, place.root, input.cwd ?? place.root, shell);
|
|
14319
|
-
|
|
14091
|
+
ran = await commandsRun(db, pid, shell);
|
|
14092
|
+
if (!rels.length && !ran.length)
|
|
14320
14093
|
return "";
|
|
14321
14094
|
}
|
|
14322
14095
|
if (event === "session_start" && input.source === "resume") {
|
|
@@ -14350,6 +14123,8 @@ async function deliverOne(input, host, file, started, who, call, known = {}) {
|
|
|
14350
14123
|
branch: branchOf(place.root)
|
|
14351
14124
|
};
|
|
14352
14125
|
const keep = (p) => !(onPath && !p.text);
|
|
14126
|
+
if (shell && ran.length)
|
|
14127
|
+
return await beforeShell(file, entry, reader, rels, shell, sessionId(pid, host, session), who);
|
|
14353
14128
|
if (event === "pre_read" || event === "session_start")
|
|
14354
14129
|
return (await lockedPlan(file, entry, make, keep)).text;
|
|
14355
14130
|
const plan = await make();
|
|
@@ -14371,10 +14146,18 @@ async function deliverOne(input, host, file, started, who, call, known = {}) {
|
|
|
14371
14146
|
async function main2() {
|
|
14372
14147
|
const input = await readInput(process.stdin);
|
|
14373
14148
|
const host = process.argv[2] === "codex" ? "codex" : "claude-code";
|
|
14374
|
-
const
|
|
14375
|
-
if (
|
|
14149
|
+
const r = await respond(input, host).catch(() => "");
|
|
14150
|
+
if (typeof r !== "string")
|
|
14151
|
+
process.stdout.write(JSON.stringify({
|
|
14152
|
+
hookSpecificOutput: {
|
|
14153
|
+
hookEventName: input.hook_event_name,
|
|
14154
|
+
permissionDecision: "deny",
|
|
14155
|
+
permissionDecisionReason: r.stop
|
|
14156
|
+
}
|
|
14157
|
+
}));
|
|
14158
|
+
else if (r)
|
|
14376
14159
|
process.stdout.write(JSON.stringify({
|
|
14377
|
-
hookSpecificOutput: { hookEventName: input.hook_event_name, additionalContext:
|
|
14160
|
+
hookSpecificOutput: { hookEventName: input.hook_event_name, additionalContext: r }
|
|
14378
14161
|
}));
|
|
14379
14162
|
}
|
|
14380
14163
|
if (process.argv[1] && /deliver\.(ts|js)$/.test(process.argv[1])) {
|
|
@@ -14384,7 +14167,8 @@ export {
|
|
|
14384
14167
|
AUTO_TRACE,
|
|
14385
14168
|
CONFIRM,
|
|
14386
14169
|
CONFIRM_GOLD,
|
|
14387
|
-
|
|
14170
|
+
RAN,
|
|
14171
|
+
STOP2 as STOP,
|
|
14388
14172
|
codexInteractive,
|
|
14389
14173
|
deliver,
|
|
14390
14174
|
deliverableIds,
|
|
@@ -14393,5 +14177,7 @@ export {
|
|
|
14393
14177
|
namable,
|
|
14394
14178
|
namedRecords,
|
|
14395
14179
|
recordLines,
|
|
14180
|
+
respond,
|
|
14181
|
+
runsCommand,
|
|
14396
14182
|
traceSkill
|
|
14397
14183
|
};
|