sphica 0.6.38 → 0.6.40

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://anthropic.com/claude-code/plugin.schema.json",
3
3
  "name": "sphica",
4
- "version": "0.6.38",
4
+ "version": "0.6.40",
5
5
  "description": "Records Claude Code and Codex sessions on your machine and keeps past implementation and decisions, with their sources, for your agent to find.",
6
6
  "author": {
7
7
  "name": "iroha924",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sphica",
3
- "version": "0.6.38",
3
+ "version": "0.6.40",
4
4
  "description": "Records Claude Code and Codex sessions on your machine and keeps past implementation and decisions, with their sources, for your agent to find.",
5
5
  "author": {
6
6
  "name": "iroha924",
package/README.md CHANGED
@@ -28,6 +28,7 @@ The database is a single SQLite file on your machine.
28
28
  - **Search in Japanese and English.** Records are made with search words in both languages, so a question in either language is more likely to find them.
29
29
  - **Find what you asked before.** Ask the agent whether you asked something like this before: `search` with `asked: true` shows your earlier messages in other sessions, the records that quote them (with what replaced them), and says "no recorded decision" when none was recorded, including a matter you raised in several sessions.
30
30
  - **See what is live, and what needs a look.** Ask for the overview: `view: "live"` lists every active decision and constraint by the directory it applies to; `view: "look"` lists records whose file is gone or whose symbol is not found, conditions you said would bring a rejected option back, and lines in your instruction files whose record was replaced. Nothing is expired or changed on its own.
31
+ - **See what Sphica showed your agent.** Ask what Sphica has been showing: `view: "delivery"` (with `days`, 1 to 90, 7 by default) counts the deliveries the hooks logged by event and by main agent or subagent, lists the records shown most, and gives recent sessions with each record's key, so you can judge whether each helped. It says what the log leaves out, and marks a record "named later" only when a later reply wrote its key.
31
32
  - **Track your own fields on records (trial).** Say in a session which extra field to keep on records (the affected tenant, a p95 figure); trace then saves a value only when the conversation writes it, with the quote. `/sphica:fields` shows each field and how many records carry a value.
32
33
  - **Share decisions as a file.** `/sphica:export` writes the live decisions you pick, with the words quoted for them and the older decisions they replaced, to a Markdown file in your repository for people who do not run Sphica. You see the whole file before it is written, and it is never committed for you.
33
34
  - **Rule text from records.** `/sphica:rules` drafts lines for CLAUDE.md, AGENTS.md, or `.claude/rules` from the constraints and decisions you pick, each marked with its record key so the overview flags it once the record changes. It never edits the file.
package/dist/deliver.js CHANGED
@@ -11552,6 +11552,17 @@ function sqliteCode(e) {
11552
11552
  const x = e;
11553
11553
  return x?.code === "ERR_SQLITE_ERROR" && typeof x.errcode === "number" ? x.errcode & 255 : null;
11554
11554
  }
11555
+ function byUnit(rows) {
11556
+ const out = new Map;
11557
+ for (const r of rows) {
11558
+ const list = out.get(r.unit_id);
11559
+ if (list)
11560
+ list.push(r);
11561
+ else
11562
+ out.set(r.unit_id, [r]);
11563
+ }
11564
+ return out;
11565
+ }
11555
11566
 
11556
11567
  // server/src/db-write.ts
11557
11568
  import { constants as C2, DatabaseSync as DatabaseSync2 } from "node:sqlite";
@@ -12901,12 +12912,15 @@ async function selectForReview(db, projectId2, files) {
12901
12912
  because: `anchored to ${a.path}${a.symbol ? ` ${a.symbol}` : ""}`
12902
12913
  });
12903
12914
  const added = files.flatMap((f) => f.added.map((l) => ({ path: f.path, text: l.normalize("NFKC").toLowerCase() })));
12904
- const free = await live.where("u.stance", "in", ["dont", "defer"]).where(({ not, exists, selectFrom }) => not(exists(selectFrom("unit_anchor as a").select("a.id").whereRef("a.unit_id", "=", "u.id").where("a.retired_at", "is", null)))).select(["u.id", "u.revision", "u.key", "u.kind", "u.stance", "u.text"]).execute();
12905
- const options = free.length ? await db.selectFrom("unit_option").select(["unit_id", "text"]).where("unit_id", "in", free.map((u) => u.id)).execute() : [];
12915
+ const locationFree = live.where("u.stance", "in", ["dont", "defer"]).where(({ not, exists, selectFrom }) => not(exists(selectFrom("unit_anchor as a").select("a.id").whereRef("a.unit_id", "=", "u.id").where("a.retired_at", "is", null))));
12916
+ const [free, options] = await Promise.all([
12917
+ locationFree.select(["u.id", "u.revision", "u.key", "u.kind", "u.stance", "u.text"]).execute(),
12918
+ db.selectFrom("unit_option").select(["unit_id", "text"]).where("unit_id", "in", locationFree.select("u.id")).orderBy("id").execute().then(byUnit)
12919
+ ]);
12906
12920
  for (const u of free) {
12907
12921
  if (out.has(u.id))
12908
12922
  continue;
12909
- for (const o of options.filter((x) => x.unit_id === u.id && x.text.trim().length >= 3)) {
12923
+ for (const o of (options.get(u.id) ?? []).filter((x) => x.text.trim().length >= 3)) {
12910
12924
  const name = o.text.normalize("NFKC").toLowerCase();
12911
12925
  const hit = added.find((l) => l.text.includes(name));
12912
12926
  if (hit) {
@@ -13260,27 +13274,38 @@ async function namedInCommand(db, projectId2, root, cwd, command) {
13260
13274
  }
13261
13275
  return [...out];
13262
13276
  };
13263
- return paths.map((r) => r.path).filter((p) => forms(p).some((t) => new RegExp(`(?:^|[${edge}])${esc(t)}(?:$|[${edge}:])`).test(command)));
13277
+ 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)));
13264
13278
  }
13265
13279
  function pathNamed(prompt, root, rel) {
13266
13280
  const steps = (p) => p.split(/[\\/]/).map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]");
13267
13281
  return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(path8.join(root, rel))})(?![A-Za-z0-9_$\\-/\\\\]|\\.[A-Za-z0-9_$])`).test(prompt);
13268
13282
  }
13283
+ function once(f) {
13284
+ const seen = new Map;
13285
+ return (k) => {
13286
+ if (!seen.has(k))
13287
+ seen.set(k, f(k));
13288
+ return seen.get(k);
13289
+ };
13290
+ }
13269
13291
  async function onPrompt(db, projectId2, root, prompt) {
13270
13292
  const text = prompt.normalize("NFKC");
13271
13293
  const lower = text.toLowerCase();
13272
- const word = (w, s) => new RegExp(`(?<![\\p{L}\\p{N}_$])${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}_$])`, "u").test(s);
13273
- const named2 = (symbol) => symbol.length >= 3 && (/[^a-z]/.test(symbol) ? word(symbol, text) : text.includes(`${symbol}(`) || text.includes(`\`${symbol}\``));
13274
- const units = await deliverable(db, projectId2).select(["u.id", "u.key", "u.kind", "u.stance", "u.text"]).execute();
13275
- const ids = units.map((u) => u.id);
13276
- const [anchors, options] = ids.length ? await Promise.all([
13277
- db.selectFrom("unit_anchor").select(["unit_id", "path", "symbol"]).where("unit_id", "in", ids).where("retired_at", "is", null).execute(),
13278
- db.selectFrom("unit_option").select(["unit_id", "text", "outcome"]).where("unit_id", "in", ids).execute()
13279
- ]) : [[], []];
13294
+ const word = (w, s) => s.includes(w) && new RegExp(`(?<![\\p{L}\\p{N}_$])${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}_$])`, "u").test(s);
13295
+ const named2 = once((symbol) => symbol.length >= 3 && (/[^a-z]/.test(symbol) ? word(symbol, text) : text.includes(`${symbol}(`) || text.includes(`\`${symbol}\``)));
13296
+ const slashed = prompt.replaceAll("\\", "/");
13297
+ const pathIn = once((rel) => slashed.includes(rel) && pathNamed(prompt, root, rel));
13298
+ const optionIn = once((option) => option.length >= 3 && word(option.normalize("NFKC").toLowerCase(), lower));
13299
+ const units = await deliverable(db, projectId2).select(["u.id", "u.key", "u.kind", "u.stance", "u.text"]).orderBy("u.kind").orderBy("u.id").execute();
13300
+ const ids = deliverable(db, projectId2).select("u.id");
13301
+ const [anchors, options] = await Promise.all([
13302
+ db.selectFrom("unit_anchor").select(["unit_id", "path", "symbol"]).where("unit_id", "in", ids).where("retired_at", "is", null).orderBy("id").execute().then(byUnit),
13303
+ db.selectFrom("unit_option").select(["unit_id", "text", "outcome"]).where("unit_id", "in", ids).orderBy("id").execute().then(byUnit)
13304
+ ]);
13280
13305
  const hits = [];
13281
13306
  for (const u of units) {
13282
- const a = anchors.find((x) => x.unit_id === u.id && (x.symbol && named2(x.symbol) || pathNamed(prompt, root, x.path)));
13283
- const o = options.find((x) => x.unit_id === u.id && x.text.length >= 3 && word(x.text.normalize("NFKC").toLowerCase(), lower));
13307
+ const a = anchors.get(u.id)?.find((x) => x.symbol && named2(x.symbol) || pathIn(x.path));
13308
+ const o = options.get(u.id)?.find((x) => optionIn(x.text));
13284
13309
  if (a)
13285
13310
  hits.push({ u, why: ` [names ${a.symbol && named2(a.symbol) ? a.symbol : a.path}]` });
13286
13311
  else if (o)
@@ -13387,12 +13412,12 @@ async function beforeReview(db, projectId2, root, call) {
13387
13412
  const base = inline(change.base);
13388
13413
  if (!n)
13389
13414
  return said(`Sphica: no local change against ${base} to check against past decisions.`, "no change");
13390
- const once = `${change.base}\x00${change.digest}`;
13415
+ const once2 = `${change.base}\x00${change.digest}`;
13391
13416
  const live = new Set((await deliverable(db, projectId2).select("u.id").execute()).map((r) => r.id));
13392
13417
  const rows = (await selectForReview(db, projectId2, change.files)).filter((a) => live.has(a.id));
13393
13418
  const checked = `checked ${n} changed path${n === 1 ? "" : "s"} against ${base}`;
13394
13419
  if (!rows.length)
13395
- return { ...said(`Sphica ${checked}: no active recorded decision applies.`, null), once };
13420
+ return { ...said(`Sphica ${checked}: no active recorded decision applies.`, null), once: once2 };
13396
13421
  const shown = rows.slice(0, LIMITS.review.units);
13397
13422
  const ai = await aiDecided(db, shown.map((u) => u.id));
13398
13423
  const f = fitMarked(shown.map((u) => line(u, ` [${inline(u.because)}]`, ai.has(u.id))), LIMITS.review.chars, `Sphica: past decisions that apply to this change (${checked}). ${NOTE}; compare the change against each:`, ai, shown.map((u) => u.id));
@@ -13404,7 +13429,7 @@ async function beforeReview(db, projectId2, root, call) {
13404
13429
  omitted,
13405
13430
  path: null,
13406
13431
  reason: null,
13407
- once
13432
+ once: once2
13408
13433
  };
13409
13434
  }
13410
13435
  function toldBefore(session, key) {
package/dist/mcp.js CHANGED
@@ -46105,6 +46105,23 @@ function kyselyOn(connect) {
46105
46105
  function openReader(file2 = dbFile()) {
46106
46106
  return kyselyOn(() => connectReader(file2));
46107
46107
  }
46108
+ var iso = (d) => {
46109
+ const t = new Date(d);
46110
+ if (Number.isNaN(t.getTime()))
46111
+ throw new RangeError(`Not a readable time: ${String(d)}`);
46112
+ return t.toISOString();
46113
+ };
46114
+ function byUnit(rows) {
46115
+ const out = new Map;
46116
+ for (const r of rows) {
46117
+ const list = out.get(r.unit_id);
46118
+ if (list)
46119
+ list.push(r);
46120
+ else
46121
+ out.set(r.unit_id, [r]);
46122
+ }
46123
+ return out;
46124
+ }
46108
46125
 
46109
46126
  // server/src/knowledge.ts
46110
46127
  var UNIT_KINDS = [
@@ -46817,10 +46834,6 @@ function askedText(r, known = true) {
46817
46834
  `);
46818
46835
  }
46819
46836
 
46820
- // server/src/export.ts
46821
- import fs5 from "node:fs";
46822
- import path5 from "node:path";
46823
-
46824
46837
  // server/src/frame.ts
46825
46838
  import crypto2 from "node:crypto";
46826
46839
  function framed(body) {
@@ -47159,7 +47172,208 @@ async function readRefs(db, projectId, refs, root) {
47159
47172
  `)}${tail(next)}`);
47160
47173
  }
47161
47174
 
47175
+ // server/src/delivery-view.ts
47176
+ var DELIVERY_DAYS = { min: 1, max: 90, default: 7 };
47177
+ var DELIVERY_LIMITS = {
47178
+ records: 20,
47179
+ sessions: 5,
47180
+ deliveries: 15,
47181
+ keys: 8,
47182
+ key: 200,
47183
+ path: 200,
47184
+ agent: 40,
47185
+ session: 80
47186
+ };
47187
+ var DAY_MS = 24 * 60 * 60 * 1000;
47188
+ var MORE_LINE = 120;
47189
+ var WHO = ["main", "subagent", "subagent, id unknown"];
47190
+ var who = (named, event, reason2) => named ? "subagent" : event === "session_start" && reason2 === "subagent" ? "subagent, id unknown" : "main";
47191
+ var DELIVERY_LIMITS_TEXT = [
47192
+ "Counted are the logged delivery rows only: since 0.6.16 a read or edit that showed nothing is not logged (older rows show it as nothing), and a delivery answered while the write lock was busy, or whose log write failed, is not either.",
47193
+ "A session's rows are dropped once its last delivery is older than 90 days, so a long period is not a rolling window.",
47194
+ "The text delivered then is not kept, only the record ids: a record shown now may have changed since.",
47195
+ "Outcomes suppressed and unavailable are not written today, so only emitted and nothing appear.",
47196
+ "Rows without an agent id count as main, as the host reported them, except a subagent start logged without one: subagent, id unknown.",
47197
+ "named later: a captured reply of the same session, after the delivery, writes the key whole (questions asked with AskUserQuestion are not counted). An agent may use a record without naming it, naming it does not mean it helped, a reply may be missing, cut, or redacted in capture, and it may come from any agent of the session."
47198
+ ];
47199
+ var CLOSING = "Read a record by its key or u<id> before relying on it. Change a record only through /sphica:trace, with the owner's words.";
47200
+ var BEFORE_KEY = /[A-Za-z0-9_./:-]/;
47201
+ var AFTER_KEY = /[A-Za-z0-9_/-]/;
47202
+ var KEY_AFTER_DOT = /[A-Za-z0-9_./-]/;
47203
+ var QUESTION2 = /:ask:.*:q:/s;
47204
+ function namesKey(text2, key) {
47205
+ for (let i = text2.indexOf(key);i !== -1 && key; i = text2.indexOf(key, i + 1)) {
47206
+ const before = text2[i - 1];
47207
+ const after = text2[i + key.length];
47208
+ const next = text2[i + key.length + 1];
47209
+ const goesOn = after !== undefined && (AFTER_KEY.test(after) || after === "." && next !== undefined && KEY_AFTER_DOT.test(next));
47210
+ if ((before === undefined || !BEFORE_KEY.test(before)) && !goesOn)
47211
+ return true;
47212
+ }
47213
+ return false;
47214
+ }
47215
+ async function deliveryOverview(db, projectId, days, now = new Date) {
47216
+ const to = iso(now);
47217
+ const from = iso(now.getTime() - days * DAY_MS);
47218
+ const logged = () => db.selectFrom("delivery as d").innerJoin("session as s", "s.id", "d.session_id").where("s.project_id", "=", projectId).where("d.at", ">=", from).where("d.at", "<", to);
47219
+ const keyed = () => logged().where((eb) => eb.exists(eb.selectFrom("delivery_unit as k").whereRef("k.delivery_id", "=", "d.id").select("k.unit_id")));
47220
+ const delivered = () => db.selectFrom("delivery_unit as du").innerJoin("delivery as d", "d.id", "du.delivery_id").innerJoin("session as s", "s.id", "d.session_id").where("s.project_id", "=", projectId).where("d.at", ">=", from).where("d.at", "<", to);
47221
+ const [oldest, groups, top, units, recent, sessions] = await Promise.all([
47222
+ db.selectFrom("delivery as d").innerJoin("session as s", "s.id", "d.session_id").where("s.project_id", "=", projectId).select((eb) => eb.fn.min("d.at").as("at")).executeTakeFirst(),
47223
+ logged().select((eb) => [
47224
+ "d.event",
47225
+ "d.outcome",
47226
+ "d.reason",
47227
+ "d.omitted",
47228
+ eb("d.agent_id", "is not", null).as("named"),
47229
+ eb.exists(eb.selectFrom("delivery_unit as k").whereRef("k.delivery_id", "=", "d.id").select("k.unit_id")).as("keyed"),
47230
+ eb.fn.countAll().as("n")
47231
+ ]).groupBy(["d.event", "d.outcome", "d.reason", "d.omitted", "named", "keyed"]).execute(),
47232
+ delivered().innerJoin("unit as u", "u.id", "du.unit_id").select((eb) => [
47233
+ "u.id",
47234
+ "u.key",
47235
+ "u.kind",
47236
+ "u.lifecycle",
47237
+ eb.fn.count("d.session_id").distinct().as("sessions"),
47238
+ eb.fn.countAll().as("deliveries")
47239
+ ]).groupBy("u.id").orderBy("sessions", "desc").orderBy("deliveries", "desc").orderBy("u.id").limit(DELIVERY_LIMITS.records).execute(),
47240
+ delivered().select((eb) => eb.fn.count("du.unit_id").distinct().as("n")).executeTakeFirst(),
47241
+ keyed().select((eb) => ["s.id", "s.host", "s.external_id", "s.branch", eb.fn.max("d.at").as("last")]).groupBy("s.id").orderBy("last", "desc").orderBy("s.id").limit(DELIVERY_LIMITS.sessions).execute(),
47242
+ keyed().select((eb) => eb.fn.count("d.session_id").distinct().as("n")).executeTakeFirst()
47243
+ ]);
47244
+ const via = top.length ? await delivered().where("du.unit_id", "in", top.map((t) => t.id)).select(["du.unit_id", "d.event"]).distinct().orderBy("d.event").execute() : [];
47245
+ const shown = await Promise.all(recent.map(async (r) => {
47246
+ const rows = keyed().where("d.session_id", "=", r.id);
47247
+ const [list, n] = await Promise.all([
47248
+ rows.select(["d.id", "d.at", "d.event", "d.agent_id", "d.reason", "d.path"]).orderBy("d.at").orderBy("d.id").limit(DELIVERY_LIMITS.deliveries).execute(),
47249
+ rows.select((eb) => eb.fn.countAll().as("n")).executeTakeFirst()
47250
+ ]);
47251
+ return { session: r, list, total: Number(n?.n ?? 0) };
47252
+ }));
47253
+ const ids = shown.flatMap((s) => s.list.map((d) => d.id));
47254
+ const keys = ids.length ? await db.selectFrom("delivery_unit as du").innerJoin("unit as u", "u.id", "du.unit_id").where("du.delivery_id", "in", ids).select(["du.delivery_id", "u.id", "u.key"]).orderBy("du.delivery_id").orderBy("u.id").execute() : [];
47255
+ const byDelivery = new Map;
47256
+ for (const k of keys)
47257
+ byDelivery.set(k.delivery_id, [...byDelivery.get(k.delivery_id) ?? [], k]);
47258
+ const replies = () => db.selectFrom("source as m").where("m.kind", "=", "session_message").where("m.author_kind", "=", "assistant").where("m.created_at", "<", to);
47259
+ const holding = (keys2) => (eb) => eb.or(keys2.map((k) => eb(eb.fn("instr", ["m.text", eb.val(k)]), ">", 0)));
47260
+ const reply = (r) => !QUESTION2.test(r.external_id);
47261
+ const namedIn = new Map;
47262
+ for (const t of top) {
47263
+ const found = await replies().innerJoin(delivered().where("du.unit_id", "=", t.id).select((f) => ["d.session_id", f.fn.min("d.at").as("first")]).groupBy("d.session_id").as("f"), (j) => j.onRef("f.session_id", "=", "m.session_id")).whereRef("m.created_at", ">", "f.first").where(holding([t.key])).select(["m.session_id", "m.external_id", "m.text"]).execute();
47264
+ namedIn.set(t.id, new Set(found.filter((r) => reply(r) && namesKey(r.text, t.key)).map((r) => r.session_id)).size);
47265
+ }
47266
+ const later = new Map;
47267
+ for (const s of shown) {
47268
+ const wanted = [...new Set(s.list.flatMap((d) => (byDelivery.get(d.id) ?? []).map((k) => k.key)))];
47269
+ const since = s.list[0]?.at;
47270
+ if (since && wanted.length)
47271
+ later.set(s.session.id, (await replies().where("m.session_id", "=", s.session.id).where("m.created_at", ">", since).where(holding(wanted)).select(["m.external_id", "m.created_at", "m.text"]).execute()).filter(reply));
47272
+ }
47273
+ const counts = countTable(groups);
47274
+ const fixedTop = [
47275
+ `# Delivery log of the last ${days} day${days === 1 ? "" : "s"}`,
47276
+ `Period: from ${from} up to ${to} (UTC). Oldest delivery still logged for this project: ${oldest?.at ?? "none"}.`,
47277
+ "",
47278
+ "## Logged delivery rows",
47279
+ ...counts,
47280
+ ""
47281
+ ];
47282
+ const fixedEnd = ["", "## Limits", ...DELIVERY_LIMITS_TEXT.map((l) => `- ${l}`), "", CLOSING];
47283
+ let room = READ_BUDGET - bytes(framed("")) - bytes(fixedTop.join(`
47284
+ `)) - bytes(fixedEnd.join(`
47285
+ `)) - MORE_LINE * (2 + shown.length) - 512;
47286
+ const fit = (lines) => {
47287
+ const b = lines.reduce((sum, l) => sum + bytes(l) + 1, 0);
47288
+ if (b > room)
47289
+ return false;
47290
+ room -= b;
47291
+ return true;
47292
+ };
47293
+ const events = new Map;
47294
+ for (const v of via)
47295
+ events.set(v.unit_id, [...events.get(v.unit_id) ?? [], v.event]);
47296
+ const topLines = [];
47297
+ for (const t of top) {
47298
+ const line = `- ${head(inline(t.key), DELIVERY_LIMITS.key)} (u${t.id}, ${t.kind}, ${t.lifecycle} now): ${t.sessions} session${Number(t.sessions) === 1 ? "" : "s"}, ${t.deliveries} deliver${Number(t.deliveries) === 1 ? "y" : "ies"}, via ${(events.get(t.id) ?? []).join(", ")}; named later in ${namedIn.get(t.id) ?? 0} of those sessions`;
47299
+ if (!fit([line]))
47300
+ break;
47301
+ topLines.push(line);
47302
+ }
47303
+ const recordsLeft = Number(units?.n ?? 0) - topLines.length;
47304
+ const sessionParts = [];
47305
+ let sessionsShown = 0;
47306
+ for (const s of shown) {
47307
+ const heading = `### ${inline(s.session.host)} session ${head(inline(s.session.external_id), DELIVERY_LIMITS.session)}${s.session.branch ? ` (branch ${head(inline(s.session.branch), DELIVERY_LIMITS.path)})` : ""}, last delivery with a record ${s.session.last}`;
47308
+ const replies2 = later.get(s.session.id) ?? [];
47309
+ const lines = s.list.map((d) => deliveryLine(d, byDelivery.get(d.id) ?? [], (key) => replies2.some((r) => r.created_at > d.at && namesKey(r.text, key))));
47310
+ if (!lines.length || !fit([heading, lines[0] ?? ""]))
47311
+ break;
47312
+ const part = [heading, lines[0] ?? ""];
47313
+ let n = 1;
47314
+ for (const l of lines.slice(1)) {
47315
+ if (!fit([l]))
47316
+ break;
47317
+ part.push(l);
47318
+ n++;
47319
+ }
47320
+ if (s.total > n)
47321
+ part.push(`(${s.total - n} more deliver${s.total - n === 1 ? "y" : "ies"} with records in this session not shown.)`);
47322
+ sessionParts.push(...part);
47323
+ sessionsShown++;
47324
+ }
47325
+ const sessionsLeft = Number(sessions?.n ?? 0) - sessionsShown;
47326
+ return [
47327
+ ...fixedTop,
47328
+ "## Records delivered most",
47329
+ ...topLines.length ? topLines : ["No record was delivered in this period."],
47330
+ ...recordsLeft > 0 ? [`(${recordsLeft} more delivered record${recordsLeft === 1 ? "" : "s"} not shown.)`] : [],
47331
+ "",
47332
+ "## Example sessions, the most recent first",
47333
+ ...sessionParts.length ? sessionParts : ["No session was delivered a record in this period."],
47334
+ ...sessionsLeft > 0 ? [
47335
+ `(${sessionsLeft} more session${sessionsLeft === 1 ? "" : "s"} delivered records in this period, not shown.)`
47336
+ ] : [],
47337
+ ...fixedEnd
47338
+ ].join(`
47339
+ `);
47340
+ }
47341
+ function countTable(groups) {
47342
+ const rows = new Map;
47343
+ for (const g of groups) {
47344
+ const id = `${g.event}\x00${g.outcome}`;
47345
+ const row = rows.get(id) ?? { by: new Map, keyless: 0, left: 0 };
47346
+ const w = who(Boolean(Number(g.named)), g.event, g.reason);
47347
+ const n = Number(g.n);
47348
+ row.by.set(w, (row.by.get(w) ?? 0) + n);
47349
+ if (g.outcome === "emitted" && !Number(g.keyed))
47350
+ row.keyless += n;
47351
+ row.left += Number(g.omitted) * n;
47352
+ rows.set(id, row);
47353
+ }
47354
+ if (!rows.size)
47355
+ return ["No delivery was logged for this project in this period."];
47356
+ return [
47357
+ `| event | outcome | ${WHO.join(" | ")} | emitted rows with no logged record key | left out |`,
47358
+ `|${" --- |".repeat(WHO.length + 4)}`,
47359
+ ...[...rows.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([id, r]) => {
47360
+ const [event, outcome] = id.split("\x00");
47361
+ return `| ${event} | ${outcome} | ${WHO.map((w) => r.by.get(w) ?? 0).join(" | ")} | ${outcome === "emitted" ? r.keyless : "-"} | ${r.left} |`;
47362
+ }),
47363
+ "left out: the sum of the counts each row logged of what applied but was not shown; a session start also counts work items."
47364
+ ];
47365
+ }
47366
+ function deliveryLine(d, units, namedLater) {
47367
+ const w = who(d.agent_id !== null, d.event, d.reason);
47368
+ const agent = w === "subagent" && d.agent_id ? ` ${head(inline(d.agent_id), DELIVERY_LIMITS.agent)}` : "";
47369
+ const named = units.slice(0, DELIVERY_LIMITS.keys).map((u) => `${head(inline(u.key), DELIVERY_LIMITS.key)} (u${u.id}${namedLater(u.key) ? ", named later" : ""})`).join(", ");
47370
+ const more = units.length > DELIVERY_LIMITS.keys ? ` (+${units.length - DELIVERY_LIMITS.keys} more)` : "";
47371
+ return `- ${d.at} ${d.event}, ${w}${agent}${d.path ? ` ${head(inline(d.path), DELIVERY_LIMITS.path)}` : ""}: ${named}${more}`;
47372
+ }
47373
+
47162
47374
  // server/src/export.ts
47375
+ import fs5 from "node:fs";
47376
+ import path5 from "node:path";
47163
47377
  var EXPORT_LIMITS = { records: 50, depth: 20, bytes: 60 * 1024 };
47164
47378
  async function chosen(db, projectId, ref) {
47165
47379
  const byId = /^u([1-9][0-9]{0,15})$/.exec(ref);
@@ -47924,12 +48138,15 @@ async function selectForReview(db, projectId2, files) {
47924
48138
  because: `anchored to ${a.path}${a.symbol ? ` ${a.symbol}` : ""}`
47925
48139
  });
47926
48140
  const added = files.flatMap((f) => f.added.map((l) => ({ path: f.path, text: l.normalize("NFKC").toLowerCase() })));
47927
- const free = await live.where("u.stance", "in", ["dont", "defer"]).where(({ not, exists, selectFrom }) => not(exists(selectFrom("unit_anchor as a").select("a.id").whereRef("a.unit_id", "=", "u.id").where("a.retired_at", "is", null)))).select(["u.id", "u.revision", "u.key", "u.kind", "u.stance", "u.text"]).execute();
47928
- const options = free.length ? await db.selectFrom("unit_option").select(["unit_id", "text"]).where("unit_id", "in", free.map((u) => u.id)).execute() : [];
48141
+ const locationFree = live.where("u.stance", "in", ["dont", "defer"]).where(({ not, exists, selectFrom }) => not(exists(selectFrom("unit_anchor as a").select("a.id").whereRef("a.unit_id", "=", "u.id").where("a.retired_at", "is", null))));
48142
+ const [free, options] = await Promise.all([
48143
+ locationFree.select(["u.id", "u.revision", "u.key", "u.kind", "u.stance", "u.text"]).execute(),
48144
+ db.selectFrom("unit_option").select(["unit_id", "text"]).where("unit_id", "in", locationFree.select("u.id")).orderBy("id").execute().then(byUnit)
48145
+ ]);
47929
48146
  for (const u of free) {
47930
48147
  if (out.has(u.id))
47931
48148
  continue;
47932
- for (const o of options.filter((x) => x.unit_id === u.id && x.text.trim().length >= 3)) {
48149
+ for (const o of (options.get(u.id) ?? []).filter((x) => x.text.trim().length >= 3)) {
47933
48150
  const name = o.text.normalize("NFKC").toLowerCase();
47934
48151
  const hit = added.find((l) => l.text.includes(name));
47935
48152
  if (hit) {
@@ -48325,15 +48542,20 @@ server.registerTool("fields", {
48325
48542
  var DIFF = exports_external.string().min(1).max(2000000).describe("The change under review as a unified diff (git diff output)");
48326
48543
  var notChecked = (e) => text2(`Decision lane: not checked. Sphica unavailable: ${head(reason(e), 300)}. Report the decision check as not run, not as passed.`, true);
48327
48544
  server.registerTool("overview", {
48328
- title: "Live decisions, and records that need a look",
48329
- description: "On request, not before every change. view live lists every active decision and constraint of the project, grouped by the directory it " + "applies to, a page at a time (pass after from the previous page). view look lists live records whose code file is gone or whose symbol " + "is not found, written conditions for reconsidering an option (for you to judge, never applied), and lines in CLAUDE.md, AGENTS.md, or " + ".claude/rules marked <!-- sphica: key --> whose record was replaced or withdrawn, a page at a time until one says Complete (pass the after it gives). " + "Read a record by its key before relying on it.",
48545
+ title: "Live decisions, records that need a look, and what Sphica showed",
48546
+ description: "On request, not before every change. view live lists every active decision and constraint of the project, grouped by the directory it " + "applies to, a page at a time (pass after from the previous page). view look lists live records whose code file is gone or whose symbol " + "is not found, written conditions for reconsidering an option (for you to judge, never applied), and lines in CLAUDE.md, AGENTS.md, or " + ".claude/rules marked <!-- sphica: key --> whose record was replaced or withdrawn, a page at a time until one says Complete (pass the after it gives). " + "view delivery shows what Sphica's hooks showed the agent over the last days (default 7): logged rows by event, the records delivered most, " + "and example sessions; use it when the user asks what Sphica has been showing. " + "Read a record by its key before relying on it.",
48330
48547
  inputSchema: exports_external.object({
48331
- view: exports_external.enum(["live", "look"]).describe("live: every active decision and constraint; look: records that need a look"),
48548
+ view: exports_external.enum(["live", "look", "delivery"]).describe("live: every active decision and constraint; look: records that need a look; delivery: what the hooks showed the agent"),
48332
48549
  after: exports_external.union([exports_external.number().int().min(0), exports_external.string().min(1).max(8192)]).optional().describe("With live: the id the previous page said to continue after. With look: the cursor the previous page gave, as it is"),
48550
+ days: exports_external.number().int().min(DELIVERY_DAYS.min).max(DELIVERY_DAYS.max).optional().describe(`With delivery: how many days back to look, ending now (default ${DELIVERY_DAYS.default})`),
48333
48551
  cwd: CWD
48334
48552
  }).strict(),
48335
48553
  annotations: READ_ONLY
48336
48554
  }, async (a, extra) => {
48555
+ if (a.view !== "delivery" && a.days !== undefined)
48556
+ return text2("days: only with view delivery", true);
48557
+ if (a.view === "delivery" && a.after !== undefined)
48558
+ return text2("after: not with view delivery, which is one page", true);
48337
48559
  if (a.view === "live" && typeof a.after === "string")
48338
48560
  return text2("after: with view live, pass the id the previous page gave", true);
48339
48561
  if (a.view === "look" && typeof a.after === "number")
@@ -48344,7 +48566,7 @@ server.registerTool("overview", {
48344
48566
  const p = await projectOf(a.cwd, extra._meta);
48345
48567
  if (typeof p === "string")
48346
48568
  return text2(p);
48347
- return text2(framed(typeof a.after === "string" || a.view === "look" ? await lookOverview(db, p.id, p.root, typeof a.after === "string" ? a.after : undefined) : await liveOverview(db, p.id, a.after ?? null)));
48569
+ return text2(framed(a.view === "delivery" ? await deliveryOverview(db, p.id, a.days ?? DELIVERY_DAYS.default) : typeof a.after === "string" || a.view === "look" ? await lookOverview(db, p.id, p.root, typeof a.after === "string" ? a.after : undefined) : await liveOverview(db, p.id, a.after ?? null)));
48348
48570
  } catch (e) {
48349
48571
  return text2(`Sphica unavailable: ${head(reason(e), 300)}`, true);
48350
48572
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sphica",
3
- "version": "0.6.38",
3
+ "version": "0.6.40",
4
4
  "description": "Records Claude Code and Codex sessions on your machine and keeps past implementation and decisions, with their sources, for your agent to find.",
5
5
  "license": "MIT",
6
6
  "type": "module",