sphica 0.6.53 → 0.6.55

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.53",
4
+ "version": "0.6.55",
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.53",
3
+ "version": "0.6.55",
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
  - **Shown after a shell command changes a file (trial, off by default).** A script or command that rewrites a file without naming it gets past the delivery before the command. With the `shell_write_delivery` option on, Sphica compares the content of the files your decisions apply to before and after each shell command, and right after the command shows the decisions on the files whose content changed and that the agent has not seen in this conversation. Turn it on in `/config` (Claude Code 2.1.269 or later), or set `SPHICA_SHELL_WRITE_DELIVERY` to `on` in the environment the host starts from (either host; `off` turns it off whatever the option says). In Codex, trust the new hook in `/hooks` after updating. It keeps content hashes and one line per command in `~/.sphica/shell-state/`.
29
29
  - **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.
30
30
  - **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.
31
+ - **See how a decision changed, and what held at a past time.** Ask the agent how a decision came to be: `read` with `timeline: true` shows the decisions it replaced or was replaced by, when each change took effect and why, and the findings, dead ends, and questions saved by the same trace or harvest or tied to the same code, oldest first. It is an overview; the quoted words are in the full record. Ask what was decided as of a time: `search` with `as_of` (a time with its offset, such as `2026-10-01T09:00:00+09:00`) searches the records as Sphica held them then, by the states and replacements of that time, and names apart the ones saved later that match now (the first ten, then a count). The time is when Sphica saved a record, not when the words were said, so a session traced late or a pull request harvested late counts from the day it was saved.
31
32
  - **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.
32
33
  - **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.
33
34
  - **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.
package/dist/deliver.js CHANGED
@@ -13116,10 +13116,11 @@ function parseDiff(text3) {
13116
13116
  };
13117
13117
  const rows = text3.split(/\r?\n/);
13118
13118
  for (const [i, raw] of rows.entries()) {
13119
- if (cur && (oldLeft > 0 || newLeft > 0)) {
13119
+ if (oldLeft > 0 || newLeft > 0) {
13120
13120
  if (raw.startsWith("+")) {
13121
- cur.added.push(raw.slice(1));
13122
- cur.lines.push(line++);
13121
+ cur?.added.push(raw.slice(1));
13122
+ cur?.lines.push(line);
13123
+ line++;
13123
13124
  newLeft--;
13124
13125
  } else if (raw.startsWith("-"))
13125
13126
  oldLeft--;
package/dist/mcp.js CHANGED
@@ -46720,6 +46720,20 @@ var SOURCE_PAGE = 50;
46720
46720
  var SOURCE_SCAN_MAX = 600;
46721
46721
  var SOURCE_SCAN_BYTES = 64 * 1024 * 1024;
46722
46722
  var LIFE_ORDER = { active: 0, candidate: 1, superseded: 2, withdrawn: 3 };
46723
+ var EXTRA_MAX = 200;
46724
+ var EXTRA_RANK = Number.MAX_SAFE_INTEGER;
46725
+ var LATER_SHOWN = 10;
46726
+ var indexed = (db, projectId, match) => db.selectFrom(sql`(select unit_fts.rowid as rowid, bm25(unit_fts, 3, 2, 1) as rank from unit_fts cross join unit on unit.id = unit_fts.rowid where unit_fts match ${match} and unit.project_id = ${projectId})`.as("f")).innerJoin("unit as u", "u.id", "f.rowid").where("u.project_id", "=", projectId).where("u.extraction", "=", "supported");
46727
+ function filtered(db, projectId, q, path6, match) {
46728
+ let query = indexed(db, projectId, match);
46729
+ if (q.kinds?.length)
46730
+ query = query.where("u.kind", "in", q.kinds);
46731
+ if (q.lifecycles?.length)
46732
+ query = query.where("u.lifecycle", "in", q.lifecycles);
46733
+ if (path6)
46734
+ query = query.where(({ exists, selectFrom }) => exists(selectFrom("unit_anchor as a").select("a.id").whereRef("a.unit_id", "=", "u.id").where("a.path", "=", path6).where("a.retired_at", "is", null)));
46735
+ return query;
46736
+ }
46723
46737
  var strong = (matched, of) => matched * 2 > of;
46724
46738
  var PATH_REFUSED = "path must be relative to the repository root, such as src/x.ts: absolute paths, .., backslashes, and empty parts are refused";
46725
46739
  async function searchUnits(db, projectId, q) {
@@ -46730,13 +46744,9 @@ async function searchUnits(db, projectId, q) {
46730
46744
  const match = ftsQuery(q.question);
46731
46745
  if (!match)
46732
46746
  return { hits: [], weaker: 0, terms: wanted, stopped: false, read: 0 };
46733
- let query = db.selectFrom(sql`(select unit_fts.rowid as rowid, bm25(unit_fts, 3, 2, 1) as rank from unit_fts cross join unit on unit.id = unit_fts.rowid where unit_fts match ${match} and unit.project_id = ${projectId})`.as("f")).innerJoin("unit as u", "u.id", "f.rowid").where("u.project_id", "=", projectId).where("u.extraction", "=", "supported");
46734
- if (q.kinds?.length)
46735
- query = query.where("u.kind", "in", q.kinds);
46736
- if (q.lifecycles?.length)
46737
- query = query.where("u.lifecycle", "in", q.lifecycles);
46738
- if (path6)
46739
- query = query.where(({ exists, selectFrom }) => exists(selectFrom("unit_anchor as a").select("a.id").whereRef("a.unit_id", "=", "u.id").where("a.path", "=", path6).where("a.retired_at", "is", null)));
46747
+ if (q.asOf !== undefined)
46748
+ return searchAsOf(db, projectId, q, q.asOf, wanted, path6, match);
46749
+ const query = filtered(db, projectId, q, path6, match);
46740
46750
  const ranked = await query.select(["u.id", "f.rank"]).orderBy("f.rank").orderBy("u.id").limit(UNIT_SCAN_MAX + 1).execute();
46741
46751
  const stopped = ranked.length > UNIT_SCAN_MAX;
46742
46752
  let weaker = 0;
@@ -46788,11 +46798,121 @@ async function searchUnits(db, projectId, q) {
46788
46798
  read
46789
46799
  };
46790
46800
  }
46791
- async function liveSuccessors(db, id) {
46801
+ async function searchAsOf(db, projectId, q, asOf, wanted, path6, match) {
46802
+ const life = sql`coalesce((select t.to_state from unit_state as t where t.unit_id = u.id and t.at <= ${asOf} order by t.id desc limit 1), 'candidate')`;
46803
+ const held = sql`u.created_at <= ${asOf}${q.kinds?.length ? sql` and u.kind in (${sql.join(q.kinds)})` : sql``}${q.lifecycles?.length ? sql` and ${life} in (${sql.join(q.lifecycles)})` : sql``}${path6 ? sql` and exists (select 1 from unit_anchor as a where a.unit_id = u.id and a.path = ${path6} and a.added_at <= ${asOf} and (a.retired_at is null or a.retired_at > ${asOf}))` : sql``}`;
46804
+ const lostWords = sql`(exists (select 1 from unit_anchor as a where a.unit_id = u.id and a.added_at <= ${asOf} and a.retired_at > ${asOf})
46805
+ or (exists (select 1 from unit_alias as x where x.unit_id = u.id and x.added_at > ${asOf})
46806
+ and exists (select 1 from unit_alias as x where x.unit_id = u.id and x.added_at <= ${asOf})))`;
46807
+ const units = () => db.selectFrom("unit as u").where("u.project_id", "=", projectId).where("u.extraction", "=", "supported").where(held);
46808
+ const ranked = await indexed(db, projectId, match).where(held).select(["u.id", "f.rank"]).orderBy("f.rank").orderBy("u.id").limit(UNIT_SCAN_MAX + 1).execute();
46809
+ const stopped = ranked.length > UNIT_SCAN_MAX;
46810
+ const taken = ranked.slice(0, UNIT_SCAN_MAX);
46811
+ const known = new Set(taken.map((r) => r.id));
46812
+ const lost = (await units().where(lostWords).select("u.id").orderBy("u.id").limit(EXTRA_MAX + taken.length + 1).execute()).filter((r) => !known.has(r.id));
46813
+ const extra = lost.slice(0, EXTRA_MAX).map((r) => ({ id: r.id, rank: EXTRA_RANK }));
46814
+ let weaker = 0;
46815
+ let read = 0;
46816
+ const hits = [];
46817
+ for (const [list2, counted] of [
46818
+ [taken, true],
46819
+ [extra, false]
46820
+ ])
46821
+ for (let at = 0;at < list2.length; at += UNIT_PAGE) {
46822
+ const part = list2.slice(at, at + UNIT_PAGE);
46823
+ const order = new Map(part.map((r, i) => [r.id, { i, rank: r.rank }]));
46824
+ const rows = (await units().select([
46825
+ "u.id",
46826
+ "u.key",
46827
+ "u.kind",
46828
+ "u.stance",
46829
+ life.as("lifecycle"),
46830
+ "u.lifecycle as now",
46831
+ "u.text",
46832
+ "u.why",
46833
+ "u.scope_note",
46834
+ "u.revisit_when",
46835
+ "u.content_hash"
46836
+ ]).where("u.id", "in", part.map((r) => r.id)).execute()).map((r) => ({ ...r, rank: order.get(r.id)?.rank ?? EXTRA_RANK })).sort((a, b) => (order.get(a.id)?.i ?? 0) - (order.get(b.id)?.i ?? 0));
46837
+ const left = await judgeUnits(db, rows, wanted, hits, asOf);
46838
+ if (counted) {
46839
+ read += rows.length;
46840
+ weaker += left;
46841
+ }
46842
+ }
46843
+ const shown = new Set(hits.map((h) => h.id));
46844
+ for (const h of [...hits].filter((x) => x.lifecycle === "superseded"))
46845
+ for (const n of await liveSuccessors(db, h.id, asOf))
46846
+ if (!shown.has(n.id) && (!q.kinds?.length || q.kinds.includes(n.kind)) && (!q.lifecycles?.length || q.lifecycles.includes(n.lifecycle))) {
46847
+ shown.add(n.id);
46848
+ hits.push({
46849
+ ...n,
46850
+ options: [],
46851
+ anchors: [],
46852
+ matched: [],
46853
+ aliasOnly: false,
46854
+ successorOf: h.key,
46855
+ successorOfId: h.id,
46856
+ rank: h.rank
46857
+ });
46858
+ }
46859
+ hits.sort((a, b) => (LIFE_ORDER[a.lifecycle] ?? 9) - (LIFE_ORDER[b.lifecycle] ?? 9) || b.matched.length - a.matched.length || a.rank - b.rank);
46860
+ const top = hits.slice(0, q.limit);
46861
+ const whose = await authorityOf(db, top.filter((h) => ["decision", "constraint"].includes(h.kind)).map((h) => h.id), asOf);
46862
+ const after = await filtered(db, projectId, q, path6, match).where("u.created_at", ">", asOf).select(["u.id", "u.created_at"]).orderBy("u.created_at").orderBy("u.id").limit(UNIT_SCAN_MAX + 1).execute();
46863
+ const laterHits = [];
46864
+ for (let at = 0;at < Math.min(after.length, UNIT_SCAN_MAX); at += UNIT_PAGE) {
46865
+ const part = after.slice(at, Math.min(at + UNIT_PAGE, UNIT_SCAN_MAX));
46866
+ const order = new Map(part.map((r, i) => [r.id, i]));
46867
+ const rows = (await filtered(db, projectId, q, path6, match).select([
46868
+ "u.id",
46869
+ "u.key",
46870
+ "u.kind",
46871
+ "u.stance",
46872
+ "u.lifecycle",
46873
+ "u.text",
46874
+ "u.why",
46875
+ "u.scope_note",
46876
+ "u.revisit_when",
46877
+ "u.content_hash",
46878
+ "f.rank"
46879
+ ]).where("u.id", "in", part.map((r) => r.id)).execute()).sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
46880
+ await judgeUnits(db, rows, wanted, laterHits);
46881
+ }
46882
+ const savedAt = new Map(after.map((r) => [r.id, r.created_at]));
46883
+ const later = laterHits.map((h) => ({ id: h.id, created_at: savedAt.get(h.id) ?? "" }));
46884
+ return {
46885
+ hits: top.map(({ rank: _rank, ...h }) => ({
46886
+ ...h,
46887
+ authority: whose.get(h.id),
46888
+ ...whose.get(h.id) === "none" ? { noAdoptionKept: true } : {}
46889
+ })),
46890
+ weaker,
46891
+ terms: wanted,
46892
+ stopped,
46893
+ read,
46894
+ asOf: {
46895
+ later: later.slice(0, LATER_SHOWN),
46896
+ laterMore: Math.max(later.length - LATER_SHOWN, 0),
46897
+ laterStopped: after.length > UNIT_SCAN_MAX,
46898
+ extraStopped: lost.length > EXTRA_MAX
46899
+ }
46900
+ };
46901
+ }
46902
+ async function liveSuccessors(db, id, asOf) {
46792
46903
  const seen = new Set([id]);
46793
46904
  let end;
46794
46905
  for (let at = id;; ) {
46795
- const next = await db.selectFrom("unit_replacement as h").innerJoin("unit as n", "n.id", "h.from_unit").where("h.to_unit", "=", at).where("h.ended_at", "is", null).select(["n.id", "n.key", "n.kind", "n.stance", "n.lifecycle", "n.text", "n.why", "n.revisit_when"]).executeTakeFirst();
46906
+ const next = asOf === undefined ? await db.selectFrom("unit_replacement as h").innerJoin("unit as n", "n.id", "h.from_unit").where("h.to_unit", "=", at).where("h.ended_at", "is", null).select([
46907
+ "n.id",
46908
+ "n.key",
46909
+ "n.kind",
46910
+ "n.stance",
46911
+ "n.lifecycle",
46912
+ "n.text",
46913
+ "n.why",
46914
+ "n.revisit_when"
46915
+ ]).executeTakeFirst() : await pastSuccessor(db, at, asOf);
46796
46916
  if (!next || seen.has(next.id))
46797
46917
  break;
46798
46918
  seen.add(next.id);
@@ -46801,12 +46921,29 @@ async function liveSuccessors(db, id) {
46801
46921
  }
46802
46922
  return end ? [end] : [];
46803
46923
  }
46804
- async function judgeUnits(db, rows, wanted, hits) {
46924
+ async function pastSuccessor(db, id, asOf) {
46925
+ const n = await db.selectFrom("unit_replacement as h").innerJoin("unit as n", "n.id", "h.from_unit").where("h.to_unit", "=", id).where("h.started_at", "<=", asOf).where((eb) => eb.or([eb("h.ended_at", "is", null), eb("h.ended_at", ">", asOf)])).select([
46926
+ "n.id",
46927
+ "n.key",
46928
+ "n.kind",
46929
+ "n.stance",
46930
+ sql`coalesce((select t.to_state from unit_state as t where t.unit_id = n.id and t.at <= ${asOf} order by t.id desc limit 1), 'candidate')`.as("lifecycle"),
46931
+ "n.lifecycle as now",
46932
+ "n.text",
46933
+ "n.why",
46934
+ "n.revisit_when"
46935
+ ]).executeTakeFirst();
46936
+ if (!n)
46937
+ return;
46938
+ const { now, ...rest } = n;
46939
+ return now === rest.lifecycle ? rest : { ...rest, now };
46940
+ }
46941
+ async function judgeUnits(db, rows, wanted, hits, asOf) {
46805
46942
  const ids = rows.map((r) => r.id);
46806
46943
  const [options, anchors, aliases, fields] = ids.length ? await Promise.all([
46807
46944
  db.selectFrom("unit_option").select(["unit_id", "text", "outcome", "why", "reconsider_when"]).where("unit_id", "in", ids).orderBy("position").execute(),
46808
- db.selectFrom("unit_anchor").select(["unit_id", "path", "symbol", "role"]).where("unit_id", "in", ids).where("retired_at", "is", null).orderBy("id").execute(),
46809
- db.selectFrom("unit_alias").select(["unit_id", "terms", "content_hash"]).where("unit_id", "in", ids).orderBy("id", "desc").execute(),
46945
+ db.selectFrom("unit_anchor").select(["unit_id", "path", "symbol", "role"]).where("unit_id", "in", ids).$if(asOf === undefined, (a) => a.where("retired_at", "is", null)).$if(asOf !== undefined, (a) => a.where("added_at", "<=", asOf ?? "").where((eb) => eb.or([eb("retired_at", "is", null), eb("retired_at", ">", asOf ?? "")]))).orderBy("id").execute(),
46946
+ db.selectFrom("unit_alias").select(["unit_id", "terms", "content_hash"]).where("unit_id", "in", ids).$if(asOf !== undefined, (a) => a.where("added_at", "<=", asOf ?? "")).orderBy("id", "desc").execute(),
46810
46947
  db.selectFrom("unit_field as f").innerJoin("field_def as d", "d.id", "f.field_def_id").select(["f.unit_id", "d.name", "f.value"]).where("f.unit_id", "in", ids).execute()
46811
46948
  ]) : [[], [], [], []];
46812
46949
  let weaker = 0;
@@ -46844,7 +46981,8 @@ async function judgeUnits(db, rows, wanted, hits) {
46844
46981
  anchors: anch.map((a) => ({ path: a.path, symbol: a.symbol, role: a.role })),
46845
46982
  matched,
46846
46983
  aliasOnly: matched.every((w) => !own2.has(w)),
46847
- rank: r.rank
46984
+ rank: r.rank,
46985
+ ...r.now !== undefined && r.now !== r.lifecycle ? { now: r.now } : {}
46848
46986
  });
46849
46987
  }
46850
46988
  return weaker;
@@ -46932,7 +47070,7 @@ function hitText(h) {
46932
47070
  if (h.anchors.length > SHOWN.anchors)
46933
47071
  anchors.push(more(h.anchors.length - SHOWN.anchors, "anchors"));
46934
47072
  return [
46935
- `## ${key}${key.endsWith("…") && key !== h.key ? " [key cut]" : ""} (u${h.id}): ${h.kind}${h.stance ? ` ${h.stance}` : ""}, ${h.lifecycle}${h.authority ? `, ${AUTHORITY[h.authority]}` : ""}`,
47073
+ `## ${key}${key.endsWith("…") && key !== h.key ? " [key cut]" : ""} (u${h.id}): ${h.kind}${h.stance ? ` ${h.stance}` : ""}, ${h.lifecycle}${h.now ? `, now ${h.now}` : ""}${h.noAdoptionKept ? ", no adoption in effect then is on record" : h.authority ? `, ${AUTHORITY[h.authority]}` : ""}`,
46936
47074
  preview(h.text, SHOWN.text, true),
46937
47075
  ...h.why ? [`Why: ${preview(h.why, SHOWN.why, true)}`] : [],
46938
47076
  ...h.revisit_when ? [`Revisit when: ${preview(h.revisit_when, SHOWN.revisit, true)}`] : [],
@@ -46944,18 +47082,34 @@ function hitText(h) {
46944
47082
  }
46945
47083
  var withNotes = (body, notes) => [framed(body), ...notes.filter(Boolean)].join(`
46946
47084
  `);
46947
- function hitsReply(hits, after) {
47085
+ function asOfLines(at, n) {
47086
+ const more = n?.laterMore ? `, and ${n.laterMore} more${n.laterStopped ? " at least" : ""}` : n?.laterStopped ? ", and possibly more" : "";
47087
+ return {
47088
+ lead: `As of ${at}: which records existed, and their states, anchors, aliases, and replacements, are as Sphica held them then (by when it saved them, not when the words were said); the order follows today's index. read shows each record as it is now, with its dated history.`,
47089
+ notes: [
47090
+ n?.later.length ? `Saved after this time and not counted: ${n.later.map((l) => `u${l.id} (saved ${l.created_at})`).join(", ")}${more}.` : n?.laterStopped ? `Records saved after this time were read up to ${UNIT_SCAN_MAX} from the oldest and none matched; newer ones were not read.` : "",
47091
+ n?.extraStopped ? `Records found only by an anchor or alias they have lost since were looked at up to ${EXTRA_MAX}; more may match.` : ""
47092
+ ].filter(Boolean)
47093
+ };
47094
+ }
47095
+ function hitsReply(hits, after, asOf) {
46948
47096
  const parts = hits.map(hitText);
46949
- const reply = (kept) => withNotes([
46950
- ...parts.slice(0, kept),
46951
- ...hits.slice(0, kept).some((h) => h.authority === "agent") ? [AI_DECIDED] : []
46952
- ].join(`
47097
+ const lines = asOf ? asOfLines(asOf.at, asOf.notes) : undefined;
47098
+ const reply = (kept) => [
47099
+ ...lines ? [lines.lead] : [],
47100
+ withNotes([
47101
+ ...parts.slice(0, kept),
47102
+ ...hits.slice(0, kept).some((h) => h.authority === "agent") ? [AI_DECIDED] : []
47103
+ ].join(`
46953
47104
 
46954
47105
  `), [
46955
- leftOut(hits.slice(kept).map((h) => `u${h.id}`), "hits"),
46956
- after,
46957
- "Read a record by its key before relying on it."
46958
- ]);
47106
+ leftOut(hits.slice(kept).map((h) => `u${h.id}`), "hits"),
47107
+ ...lines?.notes ?? [],
47108
+ after,
47109
+ "Read a record by its key before relying on it."
47110
+ ])
47111
+ ].join(`
47112
+ `);
46959
47113
  return reply(fitCount(parts, READ_BUDGET, reply));
46960
47114
  }
46961
47115
  function sourcesReply(hits, after) {
@@ -47344,10 +47498,13 @@ import path6 from "node:path";
47344
47498
  var UNSUPPORTED = "unsupported: its owner quote was retracted or forgotten, so it is not the owner's condition";
47345
47499
  var cut = (text3, start, end) => Buffer.from(text3, "utf8").subarray(start, end).toString("utf8");
47346
47500
  var speaker = (s) => s.author_kind === "owner" ? "the owner" : s.author_kind === "assistant" ? "the assistant" : `${s.author_login ?? "someone"} (${s.author_association ?? s.author_kind})`;
47347
- async function unitView(db, projectId, ref, root, asOf, renames) {
47501
+ async function unitByRef(db, projectId, ref) {
47348
47502
  const byId = /^u([1-9][0-9]{0,15})$/.exec(ref);
47349
47503
  const u = await db.selectFrom("unit").selectAll().where("project_id", "=", projectId).where(byId ? "id" : "key", "=", byId ? Number(byId[1]) : ref).executeTakeFirst();
47350
- const bare = u ?? (byId ? undefined : await db.selectFrom("unit").selectAll().where("project_id", "=", projectId).where("key", "in", ["trace:", "harvest:", "glean:"].map((o) => o + ref)).execute().then((rows) => rows.length === 1 ? rows[0] : undefined));
47504
+ return u ?? (byId ? undefined : await db.selectFrom("unit").selectAll().where("project_id", "=", projectId).where("key", "in", ["trace:", "harvest:", "glean:"].map((o) => o + ref)).execute().then((rows) => rows.length === 1 ? rows[0] : undefined));
47505
+ }
47506
+ async function unitView(db, projectId, ref, root, asOf, renames) {
47507
+ const bare = await unitByRef(db, projectId, ref);
47351
47508
  if (!bare || asOf && bare.created_at > asOf)
47352
47509
  return null;
47353
47510
  return { id: bare.id, text: await describe3(db, bare, root, asOf, renames) };
@@ -48409,10 +48566,11 @@ function parseDiff(text3) {
48409
48566
  };
48410
48567
  const rows = text3.split(/\r?\n/);
48411
48568
  for (const [i, raw] of rows.entries()) {
48412
- if (cur && (oldLeft > 0 || newLeft > 0)) {
48569
+ if (oldLeft > 0 || newLeft > 0) {
48413
48570
  if (raw.startsWith("+")) {
48414
- cur.added.push(raw.slice(1));
48415
- cur.lines.push(line++);
48571
+ cur?.added.push(raw.slice(1));
48572
+ cur?.lines.push(line);
48573
+ line++;
48416
48574
  newLeft--;
48417
48575
  } else if (raw.startsWith("-"))
48418
48576
  oldLeft--;
@@ -48775,11 +48933,416 @@ function stopOnOverflow(transport) {
48775
48933
  };
48776
48934
  }
48777
48935
 
48936
+ // server/src/timeline.ts
48937
+ var CHAIN_MAX = 20;
48938
+ var EDGE_NAMED = 10;
48939
+ var RELATED_MAX = 30;
48940
+ var RELATED_READ = 200;
48941
+ var PLACES_MAX = 200;
48942
+ var LEFT_NAMED = 20;
48943
+ var SHOWN3 = { text: 200, who: 100, path: 200, symbol: 100, sources: 5 };
48944
+ var LEAD = "Timelines are overviews, oldest first: each line sums up a record or a change to it and is not the quoted words (read the record or s<id> for those). A record marked same run or same place was saved by the same run as one in the chain, or is anchored at the same place; that is not a confirmed cause.";
48945
+ var ORDER = {
48946
+ saved: 0,
48947
+ evidence: 1,
48948
+ adoption: 2,
48949
+ state: 3,
48950
+ replaced: 4,
48951
+ ended: 5,
48952
+ anchor: 6,
48953
+ conflict: 7
48954
+ };
48955
+ var text3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
48956
+ var keys = (a, b) => {
48957
+ for (let i = 0;i < Math.max(a.length, b.length); i++) {
48958
+ const d = (a[i] ?? -1) - (b[i] ?? -1);
48959
+ if (d)
48960
+ return d;
48961
+ }
48962
+ return 0;
48963
+ };
48964
+ var byTime = (a, b) => (a.at === null ? 1 : 0) - (b.at === null ? 1 : 0) || text3(a.at ?? "", b.at ?? "") || a.order - b.order || keys(a.pk, b.pk);
48965
+ async function chainOf(db, entry) {
48966
+ const ids = [entry];
48967
+ const seen = new Set(ids);
48968
+ const edge = new Set;
48969
+ for (let frontier = [entry];frontier.length; ) {
48970
+ const links = await db.selectFrom("unit_link").select(["from_unit", "to_unit"]).where("kind", "=", "supersedes").where((eb) => eb.or([eb("from_unit", "in", frontier), eb("to_unit", "in", frontier)])).orderBy("from_unit").orderBy("to_unit").execute();
48971
+ const next = [];
48972
+ for (const l of links)
48973
+ for (const [near, far] of [
48974
+ [l.from_unit, l.to_unit],
48975
+ [l.to_unit, l.from_unit]
48976
+ ]) {
48977
+ if (!frontier.includes(near) || seen.has(far))
48978
+ continue;
48979
+ if (ids.length >= CHAIN_MAX) {
48980
+ edge.add(near);
48981
+ continue;
48982
+ }
48983
+ seen.add(far);
48984
+ ids.push(far);
48985
+ next.push(far);
48986
+ }
48987
+ frontier = next;
48988
+ }
48989
+ return { ids, edge: [...edge] };
48990
+ }
48991
+ async function linesOf(db, projectId2, entry) {
48992
+ const { ids, edge } = await chainOf(db, entry);
48993
+ const units = await db.selectFrom("unit").select(["id", "key", "kind", "stance", "text", "why", "created_at", "run_id"]).where("project_id", "=", projectId2).where("id", "in", ids).execute();
48994
+ const unit = new Map(units.map((u) => [u.id, u]));
48995
+ const runs = [...new Set(units.map((u) => u.run_id))];
48996
+ const [intents, rows, gaps, states, evidence, adoption, anchors, conflicts, sameRun, outside] = await Promise.all([
48997
+ db.selectFrom("unit_link").select(["from_unit", "to_unit", "added_at"]).where("kind", "=", "supersedes").where("from_unit", "in", ids).where("to_unit", "in", ids).execute(),
48998
+ db.selectFrom("unit_replacement").select(["id", "from_unit", "to_unit", "started_at", "ended_at", "end_reason"]).where("from_unit", "in", ids).where("to_unit", "in", ids).execute(),
48999
+ db.selectFrom("unit_replacement_gap").select(["from_unit", "to_unit"]).where("from_unit", "in", ids).where("to_unit", "in", ids).execute(),
49000
+ db.selectFrom("unit_state").select(["id", "unit_id", "from_state", "to_state", "at", "reason"]).where("unit_id", "in", ids).execute(),
49001
+ db.selectFrom("unit_evidence").select([
49002
+ "id",
49003
+ "unit_id",
49004
+ "source_id",
49005
+ "role",
49006
+ "run_id",
49007
+ "added_at",
49008
+ "retracted_at",
49009
+ "retraction_reason",
49010
+ "retraction_source_id"
49011
+ ]).where("unit_id", "in", ids).orderBy("id").execute(),
49012
+ db.selectFrom("unit_adoption as a").innerJoin("source as s", "s.id", "a.source_id").select([
49013
+ "a.id",
49014
+ "a.unit_id",
49015
+ "a.source_id",
49016
+ "a.route",
49017
+ "a.run_id",
49018
+ "a.added_at",
49019
+ "a.retracted_at",
49020
+ "a.retraction_reason",
49021
+ "a.retraction_source_id",
49022
+ "s.author_kind",
49023
+ "s.author_login",
49024
+ "s.author_association"
49025
+ ]).where("a.unit_id", "in", ids).orderBy("a.id").execute(),
49026
+ db.selectFrom("unit_anchor as a").leftJoin("unit_anchor as to", "to.id", "a.replaced_by").leftJoin("unit_anchor_retirement as r", "r.anchor_id", "a.id").select([
49027
+ "a.id",
49028
+ "a.unit_id",
49029
+ "a.path",
49030
+ "a.symbol",
49031
+ "a.role",
49032
+ "a.run_id",
49033
+ "a.added_at",
49034
+ "a.retired_at",
49035
+ "to.path as to_path",
49036
+ "to.symbol as to_symbol",
49037
+ "r.source_id as said"
49038
+ ]).where("a.unit_id", "in", ids).execute(),
49039
+ db.selectFrom("unit_link as l").innerJoin("unit as a", "a.id", "l.from_unit").innerJoin("unit as b", "b.id", "l.to_unit").select([
49040
+ "l.from_unit",
49041
+ "l.to_unit",
49042
+ "l.added_at",
49043
+ "l.resolved_at",
49044
+ "l.resolution",
49045
+ "a.key as from_key",
49046
+ "b.key as to_key"
49047
+ ]).where("l.kind", "=", "conflicts").where((eb) => eb.or([eb("l.from_unit", "in", ids), eb("l.to_unit", "in", ids)])).execute(),
49048
+ db.selectFrom("unit").select(["id", "key", "kind", "text", "created_at"]).where("project_id", "=", projectId2).where("extraction", "=", "supported").where("kind", "in", ["finding", "dead_end", "question"]).where("run_id", "in", runs).where("id", "not in", ids).orderBy("created_at", "desc").orderBy("id", "desc").limit(RELATED_READ + 1).execute(),
49049
+ db.selectFrom("unit_state as t").innerJoin("unit as o", "o.id", "t.unit_id").select(["t.id", "t.at", "t.to_state", "t.reason", "o.id as unit", "o.key"]).where("o.project_id", "=", projectId2).where("t.run_id", "in", runs).where("o.id", "not in", ids).where((eb) => eb.or([
49050
+ eb("o.run_id", "<>", eb.ref("t.run_id")),
49051
+ eb("t.to_state", "in", ["superseded", "withdrawn"])
49052
+ ])).execute()
49053
+ ]);
49054
+ const everyPlace = [
49055
+ ...new Map(anchors.filter((a) => a.retired_at === null).sort((a, b) => a.id - b.id).map((a) => [JSON.stringify([a.path, a.symbol]), a])).values()
49056
+ ];
49057
+ const places = everyPlace.slice(0, PLACES_MAX);
49058
+ const samePlace = places.length ? await db.selectFrom("unit_anchor as a").crossJoin("unit as f").whereRef("f.id", "=", "a.unit_id").select(["f.id", "f.key", "f.kind", "f.text", "f.created_at"]).distinct().where("f.project_id", "=", projectId2).where("f.extraction", "=", "supported").where("f.kind", "in", ["finding", "dead_end", "question"]).where("f.id", "not in", ids).where("a.retired_at", "is", null).where("a.path", "in", [...new Set(places.map((at) => at.path))]).where((eb) => eb.or(places.map((at) => eb.and([
49059
+ eb("a.path", "=", at.path),
49060
+ at.symbol === null ? eb("a.symbol", "is", null) : eb("a.symbol", "=", at.symbol)
49061
+ ])))).orderBy("f.created_at", "desc").orderBy("f.id", "desc").limit(RELATED_READ + 1).execute() : [];
49062
+ const name = (id, key = unit.get(id)?.key ?? `u${id}`) => `${keyShown(key, id)} (u${id})`;
49063
+ const cut2 = (s) => preview(s ?? "", SHOWN3.text);
49064
+ const lines2 = [];
49065
+ for (const u of units) {
49066
+ const first = (e) => e.run_id === u.run_id;
49067
+ const sources = [
49068
+ ...new Set(evidence.filter((e) => e.unit_id === u.id && first(e)).map((e) => e.source_id))
49069
+ ];
49070
+ const adopted = adoption.filter((a) => a.unit_id === u.id && first(a));
49071
+ lines2.push({
49072
+ at: u.created_at,
49073
+ order: ORDER.saved,
49074
+ pk: [u.id],
49075
+ unit: u.id,
49076
+ must: u.id === entry,
49077
+ text: [
49078
+ `${name(u.id)} saved: ${u.kind}${u.stance ? ` ${u.stance}` : ""}, ${cut2(u.text)}`,
49079
+ ...u.why ? [` Why: ${cut2(u.why)}`] : [],
49080
+ ...sources.length ? [
49081
+ ` Evidence: ${sources.slice(0, SHOWN3.sources).map((s) => `s${s}`).join(", ")}${sources.length > SHOWN3.sources ? `, and ${sources.length - SHOWN3.sources} more` : ""}`
49082
+ ] : [],
49083
+ ...adopted.length ? [
49084
+ ` Adoption: ${adopted.slice(0, SHOWN3.sources).map((a) => `s${a.source_id} (${preview(speaker(a), SHOWN3.who)})`).join(", ")}${adopted.length > SHOWN3.sources ? `, and ${adopted.length - SHOWN3.sources} more` : ""}`
49085
+ ] : []
49086
+ ].join(`
49087
+ `)
49088
+ });
49089
+ }
49090
+ for (const e of evidence) {
49091
+ const u = unit.get(e.unit_id);
49092
+ if (!u)
49093
+ continue;
49094
+ if (e.run_id !== u.run_id)
49095
+ lines2.push({
49096
+ at: e.added_at,
49097
+ order: ORDER.evidence,
49098
+ pk: [e.id, 0],
49099
+ unit: u.id,
49100
+ text: `${name(u.id)} evidence added: s${e.source_id} (${e.role})`
49101
+ });
49102
+ if (e.retracted_at)
49103
+ lines2.push({
49104
+ at: e.retracted_at,
49105
+ order: ORDER.evidence,
49106
+ pk: [e.id, 1],
49107
+ unit: u.id,
49108
+ text: `${name(u.id)} evidence retracted: s${e.source_id} (${e.role}); reason: ${cut2(e.retraction_reason)}${e.retraction_source_id === null ? "" : `, said in s${e.retraction_source_id}`}`
49109
+ });
49110
+ }
49111
+ for (const a of adoption) {
49112
+ const u = unit.get(a.unit_id);
49113
+ if (!u)
49114
+ continue;
49115
+ const who2 = `s${a.source_id} (${preview(speaker(a), SHOWN3.who)}, ${a.route})`;
49116
+ if (a.run_id !== u.run_id)
49117
+ lines2.push({
49118
+ at: a.added_at,
49119
+ order: ORDER.adoption,
49120
+ pk: [a.id, 0],
49121
+ unit: u.id,
49122
+ text: `${name(u.id)} adopted: ${who2}`
49123
+ });
49124
+ if (a.retracted_at)
49125
+ lines2.push({
49126
+ at: a.retracted_at,
49127
+ order: ORDER.adoption,
49128
+ pk: [a.id, 1],
49129
+ unit: u.id,
49130
+ text: `${name(u.id)} adoption retracted: ${who2}; reason: ${cut2(a.retraction_reason)}${a.retraction_source_id === null ? "" : `, said in s${a.retraction_source_id}`}`
49131
+ });
49132
+ }
49133
+ for (const s of states) {
49134
+ if (s.from_state === null || !unit.has(s.unit_id))
49135
+ continue;
49136
+ lines2.push({
49137
+ at: s.at,
49138
+ order: ORDER.state,
49139
+ pk: [s.id],
49140
+ unit: s.unit_id,
49141
+ text: `${name(s.unit_id)} became ${s.to_state}: ${cut2(s.reason)}`
49142
+ });
49143
+ }
49144
+ const newest = (at) => rows.reduce((best, r) => at(r) !== null && (!best || (at(r) ?? "") >= (at(best) ?? "")) ? r : best, undefined)?.id;
49145
+ const lastStart = newest((r) => r.started_at);
49146
+ const lastEnd = newest((r) => r.ended_at);
49147
+ for (const r of rows) {
49148
+ lines2.push({
49149
+ at: r.started_at,
49150
+ order: ORDER.replaced,
49151
+ pk: [r.id],
49152
+ unit: r.from_unit,
49153
+ must: r.id === lastStart,
49154
+ text: `${name(r.from_unit)} replaced ${name(r.to_unit)}`
49155
+ });
49156
+ if (r.ended_at)
49157
+ lines2.push({
49158
+ at: r.ended_at,
49159
+ order: ORDER.ended,
49160
+ pk: [r.id],
49161
+ unit: r.from_unit,
49162
+ must: r.id === lastEnd,
49163
+ text: `${name(r.from_unit)} stopped replacing ${name(r.to_unit)}: ${cut2(r.end_reason)}`
49164
+ });
49165
+ }
49166
+ for (const l of intents) {
49167
+ const same = (x) => x.from_unit === l.from_unit && x.to_unit === l.to_unit;
49168
+ if (gaps.some(same))
49169
+ lines2.push({
49170
+ at: null,
49171
+ order: ORDER.replaced,
49172
+ pk: [l.from_unit, l.to_unit],
49173
+ unit: l.from_unit,
49174
+ text: `${name(l.from_unit)} replaced ${name(l.to_unit)}`
49175
+ });
49176
+ else if (!rows.some(same))
49177
+ lines2.push({
49178
+ at: l.added_at,
49179
+ order: ORDER.replaced,
49180
+ pk: [l.from_unit, l.to_unit],
49181
+ unit: l.from_unit,
49182
+ text: `${name(l.from_unit)} proposed to replace ${name(l.to_unit)}; it has not taken effect`
49183
+ });
49184
+ }
49185
+ for (const a of anchors) {
49186
+ const u = unit.get(a.unit_id);
49187
+ if (!u)
49188
+ continue;
49189
+ const where = (path9, symbol2) => `${preview(path9, SHOWN3.path)}${symbol2 ? ` ${preview(symbol2, SHOWN3.symbol)}` : ""}`;
49190
+ if (a.run_id !== u.run_id)
49191
+ lines2.push({
49192
+ at: a.added_at,
49193
+ order: ORDER.anchor,
49194
+ pk: [a.id, 0],
49195
+ unit: u.id,
49196
+ text: `${name(u.id)} anchor added: ${where(a.path, a.symbol)} (${a.role}); no source recorded for this change`
49197
+ });
49198
+ if (a.retired_at)
49199
+ lines2.push({
49200
+ at: a.retired_at,
49201
+ order: ORDER.anchor,
49202
+ pk: [a.id, 1],
49203
+ unit: u.id,
49204
+ text: `${name(u.id)} anchor retired: ${where(a.path, a.symbol)} (${a.role})${a.to_path ? `, moved to ${where(a.to_path, a.to_symbol)}` : ""}; ${a.said === null ? "the words that retired it are not recorded or no longer kept" : `said in s${a.said}`}`
49205
+ });
49206
+ }
49207
+ for (const c of conflicts) {
49208
+ const mine = unit.has(c.from_unit) ? c.from_unit : c.to_unit;
49209
+ const pair = `${name(c.from_unit, c.from_key)} conflicts with ${name(c.to_unit, c.to_key)}`;
49210
+ lines2.push({
49211
+ at: c.added_at,
49212
+ order: ORDER.conflict,
49213
+ pk: [c.from_unit, c.to_unit, 0],
49214
+ unit: mine,
49215
+ text: pair
49216
+ });
49217
+ if (c.resolved_at)
49218
+ lines2.push({
49219
+ at: c.resolved_at,
49220
+ order: ORDER.conflict,
49221
+ pk: [c.from_unit, c.to_unit, 1],
49222
+ unit: mine,
49223
+ text: `${pair}: resolved, ${cut2(c.resolution)}`
49224
+ });
49225
+ }
49226
+ for (const o of outside)
49227
+ lines2.push({
49228
+ at: o.at,
49229
+ order: ORDER.state,
49230
+ pk: [o.id],
49231
+ unit: o.unit,
49232
+ text: `${name(o.unit, o.key)} became ${o.to_state}: ${cut2(o.reason)}`
49233
+ });
49234
+ const related = new Map;
49235
+ for (const [list2, why] of [
49236
+ [sameRun.slice(0, RELATED_READ), "same run"],
49237
+ [samePlace.slice(0, RELATED_READ), "same place"]
49238
+ ])
49239
+ for (const f of list2) {
49240
+ const seen = related.get(f.id) ?? { ...f, why: new Set };
49241
+ seen.why.add(why);
49242
+ related.set(f.id, seen);
49243
+ }
49244
+ const ordered = [...related.entries()].sort(([a, x], [b, y]) => text3(y.created_at, x.created_at) || b - a);
49245
+ for (const [id, f] of ordered.slice(0, RELATED_MAX))
49246
+ lines2.push({
49247
+ at: f.created_at,
49248
+ order: ORDER.saved,
49249
+ pk: [id],
49250
+ unit: id,
49251
+ related: true,
49252
+ text: `${name(id, f.key)} saved [${[...f.why].join(", ")}]: ${f.kind}, ${cut2(f.text)}`
49253
+ });
49254
+ return {
49255
+ lines: lines2,
49256
+ edge,
49257
+ relatedMore: Math.max(ordered.length - RELATED_MAX, 0),
49258
+ relatedCut: sameRun.length > RELATED_READ || samePlace.length > RELATED_READ,
49259
+ placesCut: everyPlace.length > PLACES_MAX
49260
+ };
49261
+ }
49262
+ var named = (ids, max) => `${ids.slice(0, max).map((id) => `u${id}`).join(", ")}${ids.length > max ? `, and ${ids.length - max} more` : ""}`;
49263
+ async function timelineRefs(db, projectId2, refs) {
49264
+ const sections = [];
49265
+ const notes = [];
49266
+ const tail = (left) => left.length ? `(This reply stops here to stay within ${READ_BUDGET / 1024} KiB. Call read with timeline: true and refs ${JSON.stringify(left)} for the rest.)` : "";
49267
+ const reply = (section, note, left) => [LEAD, framed([...sections, ...section].join(`
49268
+
49269
+ `)), ...notes, ...note, tail(left)].filter(Boolean).join(`
49270
+ `);
49271
+ let next = [];
49272
+ for (const [i, ref] of refs.entries()) {
49273
+ const rest = refs.slice(i + 1);
49274
+ const shown3 = head(inline(ref), 200);
49275
+ const u = /^(s[1-9][0-9]{0,15}(@\d{1,9})?|u[1-9][0-9]{0,15}@\d{1,9}:[0-9a-f]{12})$/.test(ref) ? "other" : await unitByRef(db, projectId2, ref);
49276
+ const fixed = u === "other" ? `${shown3}: a timeline takes a record's key or u<id>` : u ? null : `${shown3}: not found in this project`;
49277
+ if (fixed !== null) {
49278
+ if (bytes(reply([fixed], [], rest)) > READ_BUDGET) {
49279
+ next = refs.slice(i);
49280
+ break;
49281
+ }
49282
+ sections.push(fixed);
49283
+ continue;
49284
+ }
49285
+ if (!u || u === "other")
49286
+ continue;
49287
+ const { lines: lines2, edge, relatedMore, relatedCut, placesCut } = await linesOf(db, projectId2, u.id);
49288
+ const newestFirst = (a, b2) => byTime(b2, a);
49289
+ const wanted = [
49290
+ ...lines2.filter((l) => l.must),
49291
+ ...lines2.filter((l) => !l.must && !l.related).sort(newestFirst),
49292
+ ...lines2.filter((l) => l.related).sort(newestFirst)
49293
+ ];
49294
+ const built = (kept2) => {
49295
+ const left = lines2.filter((l) => !kept2.includes(l));
49296
+ const chain = [...new Set(left.filter((l) => !l.related).map((l) => l.unit))];
49297
+ const others = [...new Set(left.filter((l) => l.related).map((l) => l.unit))];
49298
+ const more = relatedMore + others.length;
49299
+ return {
49300
+ section: [
49301
+ `## Timeline of ${keyShown(u.key, u.id)} (u${u.id})`,
49302
+ ...[...kept2].sort(byTime).map((l) => `${l.at ?? "at some time (not recorded)"} ${l.text}`)
49303
+ ].join(`
49304
+ `),
49305
+ note: [
49306
+ chain.length ? `u${u.id}: ${left.filter((l) => !l.related).length} changes left out to keep this reply within ${READ_BUDGET / 1024} KiB; read ${named(chain, LEFT_NAMED)} for them.` : "",
49307
+ more ? `u${u.id}: ${more}${relatedCut ? " or more" : ""} related records left out${others.length ? `: ${named(others, LEFT_NAMED)}` : ""}.` : "",
49308
+ placesCut ? `u${u.id}: its chain is anchored at more than ${PLACES_MAX} places; records at the same place were looked for at the ${PLACES_MAX} oldest only.` : "",
49309
+ edge.length ? `u${u.id}: its chain was followed for ${CHAIN_MAX} records and stops at ${named(edge, EDGE_NAMED)}; beyond them it was not followed, and how many more there are is not known.` : ""
49310
+ ].filter(Boolean)
49311
+ };
49312
+ };
49313
+ const fits = (kept2) => {
49314
+ const b2 = built(kept2);
49315
+ return bytes(reply([b2.section], b2.note, rest)) <= READ_BUDGET;
49316
+ };
49317
+ const must = wanted.filter((l) => l.must);
49318
+ if (!fits(must)) {
49319
+ next = refs.slice(i);
49320
+ break;
49321
+ }
49322
+ const kept = [...must];
49323
+ let chainFull = false;
49324
+ for (const l of wanted.slice(must.length)) {
49325
+ if (!l.related && chainFull)
49326
+ continue;
49327
+ if (fits([...kept, l]))
49328
+ kept.push(l);
49329
+ else if (l.related)
49330
+ break;
49331
+ else
49332
+ chainFull = true;
49333
+ }
49334
+ const b = built(kept);
49335
+ sections.push(b.section);
49336
+ notes.push(...b.note);
49337
+ }
49338
+ return reply([], [], next);
49339
+ }
49340
+
48778
49341
  // server/src/mcp.ts
48779
49342
  requireRuntime();
48780
49343
  var db = openReader();
48781
49344
  var VERSION = versionAt(ROOT);
48782
- var text3 = (t, isError = false) => ({
49345
+ var text4 = (t, isError = false) => ({
48783
49346
  content: [{ type: "text", text: t }],
48784
49347
  ...isError ? { isError: true } : {}
48785
49348
  });
@@ -48807,6 +49370,17 @@ var server = new McpServer({ name: "sphica", version: VERSION ?? "unknown" }, {
48807
49370
  ].join(`
48808
49371
  `)
48809
49372
  });
49373
+ var STORED_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
49374
+ var AS_OF_FORM = "as_of must be a time with its offset, such as 2026-10-01T09:00:00+09:00 or 2026-10-01T00:00:00Z, from year 0000 to 9999 in UTC; a date alone is not taken";
49375
+ function storedTime(raw) {
49376
+ if (!exports_external.iso.datetime({ offset: true }).safeParse(raw).success)
49377
+ return null;
49378
+ const at = new Date(raw);
49379
+ if (Number.isNaN(at.getTime()))
49380
+ return null;
49381
+ const iso2 = at.toISOString();
49382
+ return STORED_TIME.test(iso2) ? iso2 : null;
49383
+ }
48810
49384
  var READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
48811
49385
  var CWD = exports_external.string().optional().describe("Which project to use. Pass the repository root. " + `Without it, the host's workspace is used if the host names one, else the server's working directory, whose empty result looks like "none"`);
48812
49386
  server.registerTool("status", {
@@ -48818,15 +49392,15 @@ server.registerTool("status", {
48818
49392
  try {
48819
49393
  const p = await projectOf(a.cwd, extra._meta);
48820
49394
  if (typeof p === "string")
48821
- return text3(p);
48822
- return text3(await status(db, p.id, head(inline(p.name), 200)));
49395
+ return text4(p);
49396
+ return text4(await status(db, p.id, head(inline(p.name), 200)));
48823
49397
  } catch (e) {
48824
- return text3(`Sphica unavailable: ${head(reason(e), 300)}`, true);
49398
+ return text4(`Sphica unavailable: ${head(reason(e), 300)}`, true);
48825
49399
  }
48826
49400
  });
48827
49401
  server.registerTool("search", {
48828
49402
  title: "Search past decisions and implementation",
48829
- description: "Finds records (decisions, constraints, implementations, findings, dead ends, questions) whose text holds most of the query's words, " + "active ones first. Use short queries of the subject's words (identifiers, option names, the domain terms). sources: true searches the " + "captured conversation and pull request text instead. asked: true finds the owner's earlier messages like the query in other sessions, " + "with the records that quote each and whether a decision was recorded. An empty result also says how many weaker matches were left out. " + `Each hit is a preview, and a reply stays within ${READ_BUDGET / 1024} KiB: hits that do not fit are named after the results, by u<id> or s<id>, for read.`,
49403
+ description: "Finds records (decisions, constraints, implementations, findings, dead ends, questions) whose text holds most of the query's words, " + "active ones first. Use short queries of the subject's words (identifiers, option names, the domain terms). sources: true searches the " + "captured conversation and pull request text instead. asked: true finds the owner's earlier messages like the query in other sessions, " + "with the records that quote each and whether a decision was recorded. as_of searches the records as Sphica held them at a past time: " + "only those saved by then, by their states, anchors, aliases, and replacements of that time, ranked by today's index; records saved " + "later that match are named apart. An empty result also says how many weaker matches were left out. " + `Each hit is a preview, and a reply stays within ${READ_BUDGET / 1024} KiB: hits that do not fit are named after the results, by u<id> or s<id>, for read.`,
48830
49404
  inputSchema: exports_external.object({
48831
49405
  query: exports_external.string().min(1).max(500).describe("Words for the subject, in Japanese or English"),
48832
49406
  cwd: CWD,
@@ -48836,6 +49410,7 @@ server.registerTool("search", {
48836
49410
  sources: exports_external.boolean().optional().describe("Search captured sources instead of records"),
48837
49411
  asked: exports_external.boolean().optional().describe("Find the owner's earlier messages like the query, what they led to, and repeats with no recorded decision"),
48838
49412
  session: exports_external.string().max(200).optional().describe("With asked: this session's id, so its own messages are left out (in Codex pass CODEX_THREAD_ID from your shell; Codex gives MCP servers none)"),
49413
+ as_of: exports_external.string().min(1).max(64).optional().describe("A past time with its offset, such as 2026-10-01T09:00:00+09:00 or 2026-10-01T00:00:00Z (digits finer than milliseconds are dropped; " + "a date alone is refused). The time is when Sphica saved a record or a change to it, not when the words were said. Not with sources or asked"),
48839
49414
  limit: exports_external.number().int().min(1).max(20).optional()
48840
49415
  }).strict(),
48841
49416
  annotations: READ_ONLY
@@ -48843,11 +49418,16 @@ server.registerTool("search", {
48843
49418
  try {
48844
49419
  const p = await projectOf(a.cwd, extra._meta);
48845
49420
  if (typeof p === "string")
48846
- return text3(p);
49421
+ return text4(p);
48847
49422
  const limit = a.limit ?? 8;
49423
+ if (a.as_of !== undefined && (a.asked || a.sources))
49424
+ return text4("as_of cannot be combined with sources or asked.", true);
49425
+ const asOf = a.as_of === undefined ? undefined : storedTime(a.as_of);
49426
+ if (asOf === null)
49427
+ return text4(`Nothing was searched: ${AS_OF_FORM}.`, true);
48848
49428
  if (a.asked) {
48849
49429
  if (a.sources || a.path !== undefined)
48850
- return text3("asked cannot be combined with sources or path.");
49430
+ return text4("asked cannot be combined with sources or path.");
48851
49431
  const external2 = [a.session, process.env.CLAUDE_CODE_SESSION_ID, process.env.CODEX_THREAD_ID].filter((x) => !!x);
48852
49432
  const r2 = await askedBefore(db, p.id, {
48853
49433
  question: a.query,
@@ -48858,49 +49438,59 @@ server.registerTool("search", {
48858
49438
  });
48859
49439
  const known = external2.length > 0;
48860
49440
  if (!r2.messages.length)
48861
- return text3(`No ${known ? "earlier " : ""}owner message ${r2.stopped ? `among the first ${r2.read} candidates by rank ` : ""}holds most of: ${r2.terms.join(", ") || "(no searchable words)"}. ${r2.weaker} weaker matches left out.${r2.stopped ? " Search with more specific words." : ""}${known ? "" : ` ${UNKNOWN_SESSION}`}`);
48862
- return text3(askedText(r2, known));
49441
+ return text4(`No ${known ? "earlier " : ""}owner message ${r2.stopped ? `among the first ${r2.read} candidates by rank ` : ""}holds most of: ${r2.terms.join(", ") || "(no searchable words)"}. ${r2.weaker} weaker matches left out.${r2.stopped ? " Search with more specific words." : ""}${known ? "" : ` ${UNKNOWN_SESSION}`}`);
49442
+ return text4(askedText(r2, known));
48863
49443
  }
48864
49444
  if (a.sources) {
48865
49445
  if (a.path !== undefined)
48866
- return text3("sources cannot be combined with path.", true);
49446
+ return text4("sources cannot be combined with path.", true);
48867
49447
  const r2 = await searchSources(db, p.id, a.query, limit);
48868
49448
  if (!r2.hits.length)
48869
- return text3(`No source ${among(r2)}holds most of: ${r2.terms.join(", ") || "(no searchable words)"}. ${r2.weaker} weaker matches left out.${r2.stopped ? " Search with more specific words." : ""}`);
48870
- return text3(sourcesReply(r2.hits, stoppedAfter(r2)));
49449
+ return text4(`No source ${among(r2)}holds most of: ${r2.terms.join(", ") || "(no searchable words)"}. ${r2.weaker} weaker matches left out.${r2.stopped ? " Search with more specific words." : ""}`);
49450
+ return text4(sourcesReply(r2.hits, stoppedAfter(r2)));
48871
49451
  }
48872
49452
  const r = await searchUnits(db, p.id, {
48873
49453
  question: a.query,
48874
49454
  kinds: a.kinds,
48875
49455
  lifecycles: a.lifecycles,
48876
49456
  path: a.path,
48877
- limit
49457
+ limit,
49458
+ asOf
48878
49459
  });
48879
49460
  if (r.refused)
48880
- return text3(`Nothing was searched: ${r.refused}`, true);
48881
- if (!r.hits.length)
48882
- return text3(`No record ${among(r)}holds most of: ${r.terms.join(", ") || "(no searchable words)"}. ${r.weaker} weaker matches left out. ` + (r.stopped ? "Search with more specific words. " : "") + "Search again with other words or the other language, or search sources; status says whether sessions are still untraced.");
48883
- return text3(hitsReply(r.hits, stoppedAfter(r)));
49461
+ return text4(`Nothing was searched: ${r.refused}`, true);
49462
+ const past = asOf === undefined ? undefined : { at: asOf, notes: r.asOf };
49463
+ if (!r.hits.length) {
49464
+ const lines2 = past ? asOfLines(past.at, past.notes) : undefined;
49465
+ return text4([
49466
+ ...lines2 ? [lines2.lead] : [],
49467
+ `No record ${past ? `as of ${past.at} ` : ""}${among(r)}holds most of: ${r.terms.join(", ") || "(no searchable words)"}. ${r.weaker} weaker matches left out. ` + (r.stopped ? "Search with more specific words. " : "") + (past ? "Search again with other words or the other language, or without as_of for the records as they are now; status says whether sessions are still untraced." : "Search again with other words or the other language, or search sources; status says whether sessions are still untraced."),
49468
+ ...lines2?.notes ?? []
49469
+ ].join(`
49470
+ `));
49471
+ }
49472
+ return text4(hitsReply(r.hits, stoppedAfter(r), past));
48884
49473
  } catch (e) {
48885
- return text3(`Sphica unavailable: ${head(reason(e), 300)}`, true);
49474
+ return text4(`Sphica unavailable: ${head(reason(e), 300)}`, true);
48886
49475
  }
48887
49476
  });
48888
49477
  server.registerTool("read", {
48889
49478
  title: "Read past records and sources in full",
48890
- description: "The full record: its text, options, the exact words cited as evidence and adoption with who said them, links (supersedes, conflicts), " + "state history, and each code location checked in the working tree now. Pass keys or u<id> from search, or s<id> for a source. " + `A reply stays within ${READ_BUDGET / 1024} KiB: when it stops, it names the refs to read next, the one it cut first.`,
49479
+ description: "The full record: its text, options, the exact words cited as evidence and adoption with who said them, links (supersedes, conflicts), " + "state history, and each code location checked in the working tree now. Pass keys or u<id> from search, or s<id> for a source. " + "It shows a record as it is now, also after a search with as_of. timeline: true gives an overview instead of the full record: the " + "records it replaced or was replaced by, what happened to each and when, with each reason and its sources, and the findings, dead " + "ends, and questions saved by the same runs or anchored at the same places, oldest first. " + `A reply stays within ${READ_BUDGET / 1024} KiB: when it stops, it names the refs to read next, the one it cut first.`,
48891
49480
  inputSchema: exports_external.object({
48892
49481
  refs: exports_external.array(exports_external.string().min(1).max(300)).min(1).max(10).describe("Record keys, u<id>, or s<id>; s<id>@<byte> and u<id>@<byte>:<digest>, as a reply names them, go on from where it stopped"),
48893
- cwd: CWD
49482
+ cwd: CWD,
49483
+ timeline: exports_external.boolean().optional().describe("true: the timeline of each record in refs (keys or u<id> only) instead of its full text. A summary, not the quoted words; " + "what does not fit is named after it by u<id>")
48894
49484
  }).strict(),
48895
49485
  annotations: READ_ONLY
48896
49486
  }, async (a, extra) => {
48897
49487
  try {
48898
49488
  const p = await projectOf(a.cwd, extra._meta);
48899
49489
  if (typeof p === "string")
48900
- return text3(p);
48901
- return text3(await readRefs(db, p.id, a.refs, p.root));
49490
+ return text4(p);
49491
+ return text4(a.timeline ? await timelineRefs(db, p.id, a.refs) : await readRefs(db, p.id, a.refs, p.root));
48902
49492
  } catch (e) {
48903
- return text3(`Sphica unavailable: ${head(reason(e), 300)}`, true);
49493
+ return text4(`Sphica unavailable: ${head(reason(e), 300)}`, true);
48904
49494
  }
48905
49495
  });
48906
49496
  server.registerTool("export", {
@@ -48916,16 +49506,16 @@ server.registerTool("export", {
48916
49506
  try {
48917
49507
  const p = await projectOf(a.cwd, extra._meta);
48918
49508
  if (typeof p === "string")
48919
- return text3(`Nothing was exported: ${p}`, true);
49509
+ return text4(`Nothing was exported: ${p}`, true);
48920
49510
  const where = exportPath(p.root, a.path);
48921
49511
  if ("error" in where)
48922
- return text3(`Nothing was exported: ${where.error}`, true);
49512
+ return text4(`Nothing was exported: ${where.error}`, true);
48923
49513
  const built = await exportDecisions(db, p.id, p.name, a.records);
48924
49514
  if ("error" in built)
48925
- return text3(built.error, true);
48926
- return text3(exportReply(where, built.document));
49515
+ return text4(built.error, true);
49516
+ return text4(exportReply(where, built.document));
48927
49517
  } catch (e) {
48928
- return text3(`Sphica unavailable: ${head(reason(e), 300)}`, true);
49518
+ return text4(`Sphica unavailable: ${head(reason(e), 300)}`, true);
48929
49519
  }
48930
49520
  });
48931
49521
  server.registerTool("fields", {
@@ -48940,14 +49530,14 @@ server.registerTool("fields", {
48940
49530
  try {
48941
49531
  const p = await projectOf(a.cwd, extra._meta);
48942
49532
  if (typeof p === "string")
48943
- return text3(p, true);
48944
- return text3(await fieldsText(db, p.id, a.after));
49533
+ return text4(p, true);
49534
+ return text4(await fieldsText(db, p.id, a.after));
48945
49535
  } catch (e) {
48946
- return text3(`Sphica unavailable: ${head(reason(e), 300)}`, true);
49536
+ return text4(`Sphica unavailable: ${head(reason(e), 300)}`, true);
48947
49537
  }
48948
49538
  });
48949
49539
  var DIFF = exports_external.string().min(1).max(2000000).describe("The change under review as a unified diff (git diff output)");
48950
- var notChecked = (e) => text3(`Decision lane: not checked. Sphica unavailable: ${head(reason(e), 300)}. Report the decision check as not run, not as passed.`, true);
49540
+ var notChecked = (e) => text4(`Decision lane: not checked. Sphica unavailable: ${head(reason(e), 300)}. Report the decision check as not run, not as passed.`, true);
48951
49541
  server.registerTool("overview", {
48952
49542
  title: "Live decisions, records that need a look, and what Sphica showed",
48953
49543
  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.",
@@ -48960,22 +49550,22 @@ server.registerTool("overview", {
48960
49550
  annotations: READ_ONLY
48961
49551
  }, async (a, extra) => {
48962
49552
  if (a.view !== "delivery" && a.days !== undefined)
48963
- return text3("days: only with view delivery", true);
49553
+ return text4("days: only with view delivery", true);
48964
49554
  if (a.view === "delivery" && a.after !== undefined)
48965
- return text3("after: not with view delivery, which is one page", true);
49555
+ return text4("after: not with view delivery, which is one page", true);
48966
49556
  if (a.view === "live" && typeof a.after === "string")
48967
- return text3("after: with view live, pass the id the previous page gave", true);
49557
+ return text4("after: with view live, pass the id the previous page gave", true);
48968
49558
  if (a.view === "look" && typeof a.after === "number")
48969
- return text3("after: with view look, pass the cursor the previous page gave, as it is", true);
49559
+ return text4("after: with view look, pass the cursor the previous page gave, as it is", true);
48970
49560
  if (typeof a.after === "string" && !lookCursor(a.after))
48971
- return text3("after: not a cursor a look page gave; call look without after to start again", true);
49561
+ return text4("after: not a cursor a look page gave; call look without after to start again", true);
48972
49562
  try {
48973
49563
  const p = await projectOf(a.cwd, extra._meta);
48974
49564
  if (typeof p === "string")
48975
- return text3(p);
48976
- return text3(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)));
49565
+ return text4(p);
49566
+ return text4(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)));
48977
49567
  } catch (e) {
48978
- return text3(`Sphica unavailable: ${head(reason(e), 300)}`, true);
49568
+ return text4(`Sphica unavailable: ${head(reason(e), 300)}`, true);
48979
49569
  }
48980
49570
  });
48981
49571
  server.registerTool("review_select", {
@@ -48995,12 +49585,12 @@ server.registerTool("review_select", {
48995
49585
  const files = parseDiff(a.diff);
48996
49586
  const b = await reviewBatch(db, p.id, files, a.after ?? null, a.diff);
48997
49587
  if (!b.all.length)
48998
- return text3(`Decision lane: checked. No active record applies to the ${files.length} changed files.`);
49588
+ return text4(`Decision lane: checked. No active record applies to the ${files.length} changed files.`);
48999
49589
  if (!b.aligned)
49000
- return text3(`Decision lane: not checked. after ${a.after} is not where a batch ended: pass the after a batch gave, or none for the first batch.`, true);
49590
+ return text4(`Decision lane: not checked. after ${a.after} is not where a batch ended: pass the after a batch gave, or none for the first batch.`, true);
49001
49591
  if (!b.records.length)
49002
- return text3(`Decision lane: checked. No record after id ${a.after}: ${b.all.length} records apply in all (selection ${b.selection}).`);
49003
- return text3(await selectReply(db, b, a.after ?? null));
49592
+ return text4(`Decision lane: checked. No record after id ${a.after}: ${b.all.length} records apply in all (selection ${b.selection}).`);
49593
+ return text4(await selectReply(db, b, a.after ?? null));
49004
49594
  } catch (e) {
49005
49595
  return notChecked(e);
49006
49596
  }
@@ -49021,7 +49611,7 @@ server.registerTool("review_check", {
49021
49611
  const p = await projectOf(a.cwd, extra._meta);
49022
49612
  if (typeof p === "string")
49023
49613
  return notChecked(new Error(p));
49024
- return text3(checkedText(await checkFindings(db, p.id, parseDiff(a.diff), a.findings, {
49614
+ return text4(checkedText(await checkFindings(db, p.id, parseDiff(a.diff), a.findings, {
49025
49615
  after: a.after ?? null,
49026
49616
  selection: a.selection,
49027
49617
  diff: a.diff
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sphica",
3
- "version": "0.6.53",
3
+ "version": "0.6.55",
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",