sphica 0.6.47 → 0.6.49

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.47",
4
+ "version": "0.6.49",
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.47",
3
+ "version": "0.6.49",
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
@@ -31,7 +31,7 @@ The database is a single SQLite file on your machine.
31
31
  - **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
32
  - **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
33
  - **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.
34
- - **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.
34
+ - **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. One file holds about 29 KB, what a single reply to the agent carries whole; more decisions go into several files.
35
35
  - **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.
36
36
  - **Reviews check past decisions.** `/sphica:review` runs a reviewer per focus (correctness, security, written conventions, and past decisions by default; redundancy with `full`), and checks the diff against the records it touches.
37
37
 
@@ -200,6 +200,7 @@ Run `sphica doctor` first. It shows which part is out of date or not working. Co
200
200
  - **The MCP servers report an older version.** Restart the session, or run `/reload-plugins` in Claude Code.
201
201
  - **A search finds nothing.** Search matches words. Try other words, the other language, an identifier, or fewer words. Ask the agent to check `status`: sessions not traced yet are searchable only as captured text.
202
202
  - **`doctor` says the full-text index is broken.** Run `sphica doctor --reindex`.
203
+ - **A review says Sphica's git worker would not start, or `doctor` shows it under `Git worker`.** Sphica reads your working tree with git in a folder of its own, `.sphica/git` under your home directory, and refuses to when that folder overlaps the temp directory or the working tree itself (an agent in a sandbox can write there), or is a link. `sphica doctor`, run inside the repository, says which. Until it is fixed, the check before a review cannot read your local change.
203
204
 
204
205
  ## Commands
205
206
 
@@ -207,6 +208,7 @@ Run `sphica doctor` first. It shows which part is out of date or not working. Co
207
208
  |---|---|
208
209
  | `sphica init` | Create the database, bind the GitHub account `gh` is signed in to, and register the current repository |
209
210
  | `sphica doctor` | Check versions, the database, recording, and each registered project |
211
+ | `sphica doctor --audit-quotes` | List saved adoptions and reasons that rest on quoted words. It only reads: nothing is changed |
210
212
  | `sphica uninstall` | Delete `~/.sphica` and show how to remove the plugin and the CLI |
211
213
 
212
214
  Everything else runs inside Claude Code and Codex, through the `/sphica:*` commands and Sphica's MCP tools.
package/dist/capture.js CHANGED
@@ -11159,7 +11159,7 @@ var commitDiffNames = (root, a, b, limits) => list(text(root, ["diff", ...DIFF_O
11159
11159
  var originUrl = (root, limits) => text(root, ["remote", "get-url", "origin"], limits).trim();
11160
11160
  async function worktreeStatus(root, deadline) {
11161
11161
  const out = await inIsolation(root, [{ kind: "status" }], { deadline, max: 16 * 1024 * 1024 });
11162
- return out?.[0] ?? null;
11162
+ return Array.isArray(out) ? out[0] ?? null : null;
11163
11163
  }
11164
11164
  function workerFile() {
11165
11165
  const js = path.join(import.meta.dirname, "git-worker.js");
@@ -11176,7 +11176,7 @@ function inIsolation(root, ops, { deadline, max }) {
11176
11176
  detached: process.platform !== "win32"
11177
11177
  });
11178
11178
  } catch {
11179
- resolve(null);
11179
+ resolve({ unread: "failed" });
11180
11180
  return;
11181
11181
  }
11182
11182
  const chunks = [];
@@ -11187,7 +11187,7 @@ function inIsolation(root, ops, { deadline, max }) {
11187
11187
  return;
11188
11188
  done = true;
11189
11189
  clearTimeout(timer);
11190
- if (out === null) {
11190
+ if (!Array.isArray(out)) {
11191
11191
  try {
11192
11192
  if (process.platform !== "win32" && child.pid)
11193
11193
  process.kill(-child.pid, "SIGKILL");
@@ -11202,25 +11202,30 @@ function inIsolation(root, ops, { deadline, max }) {
11202
11202
  }
11203
11203
  resolve(out);
11204
11204
  };
11205
- const timer = setTimeout(() => finish(null), deadline);
11205
+ const timer = setTimeout(() => finish({ unread: "timeout" }), deadline);
11206
11206
  const cap = 6 * max * Math.max(1, ops.length * 2) + 64 * 1024;
11207
11207
  child.stdout?.on("data", (c) => {
11208
11208
  size += c.length;
11209
11209
  if (size > cap)
11210
- finish(null);
11210
+ finish({ unread: "too_large" });
11211
11211
  else
11212
11212
  chunks.push(c);
11213
11213
  });
11214
- child.on("error", () => finish(null));
11214
+ child.on("error", () => finish({ unread: "failed" }));
11215
11215
  child.on("close", () => {
11216
11216
  try {
11217
11217
  const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
11218
- finish(result.ok ? result.out : null);
11218
+ if (result.ok)
11219
+ finish(result.out);
11220
+ else if ("refused" in result)
11221
+ finish({ unread: "refused", code: result.refused });
11222
+ else
11223
+ finish({ unread: result.failed });
11219
11224
  } catch {
11220
- finish(null);
11225
+ finish({ unread: "failed" });
11221
11226
  }
11222
11227
  });
11223
- child.stdin?.on("error", () => finish(null));
11228
+ child.stdin?.on("error", () => finish({ unread: "failed" }));
11224
11229
  child.stdin?.end(JSON.stringify({
11225
11230
  root,
11226
11231
  ops,
package/dist/cli.js CHANGED
@@ -93,6 +93,7 @@ var require_src = __commonJS(function(exports, module) {
93
93
 
94
94
  // server/src/cli.ts
95
95
  import fs11 from "node:fs";
96
+ import os4 from "node:os";
96
97
  import path11 from "node:path";
97
98
 
98
99
  // server/node_modules/@clack/core/dist/index.mjs
@@ -4193,12 +4194,26 @@ function listFiles(root, kind, { pathspecs = [], ...limits } = {}) {
4193
4194
  var originUrl = (root, limits) => text(root, ["remote", "get-url", "origin"], limits).trim();
4194
4195
  async function worktreeStatus(root, deadline) {
4195
4196
  const out = await inIsolation(root, [{ kind: "status" }], { deadline, max: 16 * 1024 * 1024 });
4196
- return out?.[0] ?? null;
4197
+ return Array.isArray(out) ? out[0] ?? null : null;
4197
4198
  }
4198
4199
  function workerFile() {
4199
4200
  const js = path2.join(import.meta.dirname, "git-worker.js");
4200
4201
  return fs2.existsSync(js) ? js : path2.join(import.meta.dirname, "git-worker.ts");
4201
4202
  }
4203
+ function refusalText(code) {
4204
+ const folder = "Sphica's git folder (.sphica/git under your home directory)";
4205
+ return {
4206
+ hooks_not_empty: `the hooks folder inside ${folder}, which Sphica keeps empty, holds files`,
4207
+ not_plain_dir: "one of Sphica's folders under your home directory (.sphica, .sphica/git, or .sphica/git/hooks) is a link or not a directory",
4208
+ outside_home: `${folder} leads out of your home directory`,
4209
+ overlaps_worktree: `${folder} overlaps this work tree, which an agent can write`,
4210
+ overlaps_tmp: `${folder} overlaps the temp directory, which an agent can write`
4211
+ }[code];
4212
+ }
4213
+ async function workerPlace(root, deadline = 5000) {
4214
+ const out = await inIsolation(root, [{ kind: "place" }], { deadline, max: 1024 });
4215
+ return Array.isArray(out) ? "ready" : out;
4216
+ }
4202
4217
  function inIsolation(root, ops, { deadline, max }) {
4203
4218
  return new Promise((resolve) => {
4204
4219
  let child;
@@ -4210,7 +4225,7 @@ function inIsolation(root, ops, { deadline, max }) {
4210
4225
  detached: process.platform !== "win32"
4211
4226
  });
4212
4227
  } catch {
4213
- resolve(null);
4228
+ resolve({ unread: "failed" });
4214
4229
  return;
4215
4230
  }
4216
4231
  const chunks = [];
@@ -4221,7 +4236,7 @@ function inIsolation(root, ops, { deadline, max }) {
4221
4236
  return;
4222
4237
  done = true;
4223
4238
  clearTimeout(timer);
4224
- if (out === null) {
4239
+ if (!Array.isArray(out)) {
4225
4240
  try {
4226
4241
  if (process.platform !== "win32" && child.pid)
4227
4242
  process.kill(-child.pid, "SIGKILL");
@@ -4236,25 +4251,30 @@ function inIsolation(root, ops, { deadline, max }) {
4236
4251
  }
4237
4252
  resolve(out);
4238
4253
  };
4239
- const timer = setTimeout(() => finish(null), deadline);
4254
+ const timer = setTimeout(() => finish({ unread: "timeout" }), deadline);
4240
4255
  const cap = 6 * max * Math.max(1, ops.length * 2) + 64 * 1024;
4241
4256
  child.stdout?.on("data", (c) => {
4242
4257
  size += c.length;
4243
4258
  if (size > cap)
4244
- finish(null);
4259
+ finish({ unread: "too_large" });
4245
4260
  else
4246
4261
  chunks.push(c);
4247
4262
  });
4248
- child.on("error", () => finish(null));
4263
+ child.on("error", () => finish({ unread: "failed" }));
4249
4264
  child.on("close", () => {
4250
4265
  try {
4251
4266
  const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
4252
- finish(result.ok ? result.out : null);
4267
+ if (result.ok)
4268
+ finish(result.out);
4269
+ else if ("refused" in result)
4270
+ finish({ unread: "refused", code: result.refused });
4271
+ else
4272
+ finish({ unread: result.failed });
4253
4273
  } catch {
4254
- finish(null);
4274
+ finish({ unread: "failed" });
4255
4275
  }
4256
4276
  });
4257
- child.stdin?.on("error", () => finish(null));
4277
+ child.stdin?.on("error", () => finish({ unread: "failed" }));
4258
4278
  child.stdin?.end(JSON.stringify({
4259
4279
  root,
4260
4280
  ops,
@@ -17540,6 +17560,10 @@ function closing(text2) {
17540
17560
  return capture((output) => outro(bold(lines.join(`
17541
17561
  ${" ".repeat(GUIDE)}`)), { output }));
17542
17562
  }
17563
+ function document(head2, meta, blocks, end) {
17564
+ return [title2(head2, meta), ...blocks.map(drawBlock), closing(end)].filter((x) => x !== "").join(`
17565
+ `);
17566
+ }
17543
17567
  function failure(head2, reason2) {
17544
17568
  return [title2(head2), stopped(reason2)].join(`
17545
17569
  `);
@@ -17558,8 +17582,70 @@ function stopped(reason2) {
17558
17582
  cancel("Stopped", { output });
17559
17583
  }).replace(/\n+$/, "");
17560
17584
  }
17585
+ var cell = (text2) => oneLine(text2).trim();
17561
17586
  var cut = (text2, room) => dist_default2(text2) <= room ? text2 : `${wrapAnsi(text2, Math.max(1, room - 1), { hard: true }).split(`
17562
17587
  `)[0]}…`;
17588
+ var padTo = (text2, to) => text2 + " ".repeat(Math.max(0, to - dist_default2(text2)));
17589
+ function drawBlock(b) {
17590
+ const fancy = colored2();
17591
+ const space = fancy ? 1 : 0;
17592
+ switch (b.kind) {
17593
+ case "lines":
17594
+ return content(b.lines, space);
17595
+ case "table": {
17596
+ const rows = [b.head, ...b.rows].map((r2) => r2.map(cell));
17597
+ if (!fancy)
17598
+ return content(rows.map((r2) => r2.join(" ")));
17599
+ const widths = b.head.map((_, i2) => Math.min(40, Math.max(...rows.map((r2) => dist_default2(r2[i2] ?? "")))));
17600
+ const room = columns() - GUIDE;
17601
+ const line = (r2, head2) => {
17602
+ const before = r2.slice(0, -1).map((c, i2) => padTo(cut(c, widths[i2] ?? 0), (widths[i2] ?? 0) + 3));
17603
+ const used = before.reduce((w, c) => w + dist_default2(c), 0);
17604
+ const text2 = before.join("") + cut(r2.at(-1) ?? "", Math.max(1, room - used));
17605
+ return head2 ? dim(text2) : text2;
17606
+ };
17607
+ return capture((output) => log.message(rows.flatMap((r2, i2) => wrapAnsi(line(r2, i2 === 0), room, { hard: true, trim: false }).split(`
17608
+ `)), { output, spacing: space }));
17609
+ }
17610
+ case "cards": {
17611
+ const items = b.items.map((c) => {
17612
+ const badge = c.badge ? fancy ? `${styleText3("inverse", ` ${cell(c.badge)} `)} ` : `[${cell(c.badge)}] ` : "";
17613
+ return [
17614
+ fancy ? `${badge}${bold(cell(c.title))}` : `${badge}${cell(c.title)}`,
17615
+ ...c.body ? clean2(c.body).split(`
17616
+ `).map((l) => ` ${l}`) : [],
17617
+ ...(c.meta ?? []).map((m) => ` ${fancy ? dim(cell(m)) : cell(m)}`)
17618
+ ];
17619
+ });
17620
+ if (!fancy)
17621
+ return content(items.flat());
17622
+ return items.map((lines, i2) => content(lines, i2 === 0 ? space : 1)).join(`
17623
+ `);
17624
+ }
17625
+ case "fields": {
17626
+ const w = Math.max(...b.rows.map(([k]) => dist_default2(cell(k))));
17627
+ return content(b.rows.map(([k, v]) => fancy ? `${dim(padTo(cell(k), w + 3))}${bold(cell(v))}` : `${cell(k)} ${cell(v)}`), space);
17628
+ }
17629
+ case "meter": {
17630
+ if (!fancy)
17631
+ return content([`${cell(b.label)} ${cell(b.text)}`]);
17632
+ const bar = Math.max(8, Math.min(30, columns() - GUIDE - dist_default2(cell(b.label)) - dist_default2(cell(b.text)) - 4));
17633
+ const filled = Math.round(Math.max(0, Math.min(1, b.ratio)) * bar);
17634
+ return content([
17635
+ `${dim(cell(b.label))} ${"█".repeat(filled)}${dim("░".repeat(bar - filled))} ${bold(cell(b.text))}`
17636
+ ], space);
17637
+ }
17638
+ case "note": {
17639
+ if (!fancy)
17640
+ return content([cell(b.text)]);
17641
+ const text2 = wrapAnsi(cell(b.text), columns() - GUIDE, { hard: true, trim: true });
17642
+ return capture((output) => {
17643
+ const say = { info: log.info, warning: log.warn, error: log.error, success: log.success }[b.tone];
17644
+ say(text2, { output });
17645
+ });
17646
+ }
17647
+ }
17648
+ }
17563
17649
  function steps(heading, items, note) {
17564
17650
  const room = columns() - 11;
17565
17651
  if (!colored2() || items.some((x) => dist_default2(x.command) > room))
@@ -18084,6 +18170,304 @@ function inspect(file = dbFile()) {
18084
18170
  });
18085
18171
  }
18086
18172
 
18173
+ // server/src/own-words.ts
18174
+ var MAINTAINERS = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
18175
+ var PAIRS = { '"': '"', "“": "”", "‘": "’", "「": "」", "『": "』" };
18176
+ var WORD2 = /[\p{Script=Latin}\p{N}]/u;
18177
+ var charAt = (line, at) => at < line.length ? String.fromCodePoint(line.codePointAt(at)) : "";
18178
+ function endsWord(line, end) {
18179
+ for (let i2 = end;i2 > 0; ) {
18180
+ const low = line.charCodeAt(i2 - 1);
18181
+ const from = low >= 56320 && low <= 57343 && i2 > 1 ? i2 - 2 : i2 - 1;
18182
+ const c = charAt(line, from);
18183
+ if (!/\p{M}/u.test(c))
18184
+ return WORD2.test(c);
18185
+ i2 = from;
18186
+ }
18187
+ return false;
18188
+ }
18189
+ var startsWord = (line, at) => WORD2.test(charAt(line, at + 1));
18190
+ function inlineRanges(line) {
18191
+ const found = [];
18192
+ const closing2 = new Map;
18193
+ const last = new Map;
18194
+ for (let end = line.length;end > 0; ) {
18195
+ if (line[end - 1] !== "`") {
18196
+ end--;
18197
+ continue;
18198
+ }
18199
+ let from = end - 1;
18200
+ while (from > 0 && line[from - 1] === "`")
18201
+ from--;
18202
+ const partner = last.get(end - from);
18203
+ if (partner !== undefined)
18204
+ closing2.set(from, partner);
18205
+ last.set(end - from, from);
18206
+ end = from;
18207
+ }
18208
+ const unpaired = new Set;
18209
+ for (let i2 = 0;i2 < line.length; ) {
18210
+ const c = line[i2];
18211
+ let close = -1;
18212
+ let width2 = 1;
18213
+ if (c === "`")
18214
+ while (line[i2 + width2] === "`")
18215
+ width2++;
18216
+ const mark2 = c === "`" ? c.repeat(width2) : c;
18217
+ if (unpaired.has(mark2)) {
18218
+ i2 += width2;
18219
+ continue;
18220
+ }
18221
+ if (c === "`")
18222
+ close = closing2.get(i2) ?? -1;
18223
+ else if (c === "'") {
18224
+ if (endsWord(line, i2)) {
18225
+ i2++;
18226
+ continue;
18227
+ }
18228
+ for (let j = i2 + 1;j < line.length; j++)
18229
+ if (line[j] === "'" && !startsWord(line, j)) {
18230
+ close = j;
18231
+ break;
18232
+ }
18233
+ } else if (PAIRS[c]) {
18234
+ close = line.indexOf(PAIRS[c], i2 + 1);
18235
+ while (c === "‘" && close >= 0 && startsWord(line, close))
18236
+ close = line.indexOf(PAIRS[c], close + 1);
18237
+ } else {
18238
+ i2++;
18239
+ continue;
18240
+ }
18241
+ if (close < 0) {
18242
+ unpaired.add(mark2);
18243
+ i2 += width2;
18244
+ continue;
18245
+ }
18246
+ found.push([i2, close + width2]);
18247
+ i2 = close + width2;
18248
+ }
18249
+ return found;
18250
+ }
18251
+ var OPENS = /["“'‘`「『]/;
18252
+ var CLOSES = /["”'’`」』]/;
18253
+ function notOwnWords(body, start, end) {
18254
+ const bytes2 = Buffer.from(body, "utf8");
18255
+ let fence = null;
18256
+ let own = "";
18257
+ let quoting = false;
18258
+ let before = "";
18259
+ let after = "";
18260
+ for (let at = 0;at <= bytes2.length; ) {
18261
+ const nl = bytes2.indexOf(10, at);
18262
+ const stop = nl < 0 ? bytes2.length : nl;
18263
+ const raw = bytes2.subarray(at, stop).toString("utf8").replace(/\r$/, "");
18264
+ const line = raw.trimStart();
18265
+ let block2 = fence !== null || line.startsWith(">");
18266
+ if (fence) {
18267
+ const closing2 = /^(`+|~+)\s*$/.exec(line)?.[1];
18268
+ if (closing2 && closing2[0] === fence.mark && closing2.length >= fence.length)
18269
+ fence = null;
18270
+ } else {
18271
+ const opening = /^(`{3,}|~{3,})(.*)$/.exec(line);
18272
+ if (opening && !(opening[1]?.startsWith("`") && opening[2]?.includes("`"))) {
18273
+ fence = { mark: opening[1][0], length: opening[1].length };
18274
+ block2 = true;
18275
+ }
18276
+ }
18277
+ if (at < end && stop > start) {
18278
+ if (block2)
18279
+ return "block";
18280
+ const from = Buffer.from(raw, "utf8").subarray(0, Math.max(start - at, 0)).toString("utf8").length;
18281
+ const to = Buffer.from(raw, "utf8").subarray(0, Math.min(end, stop) - at).toString("utf8").length;
18282
+ if (start >= at)
18283
+ before = raw.slice(0, from).trimEnd().slice(-1);
18284
+ if (end <= stop)
18285
+ after = raw.slice(to).trimStart().slice(0, 1);
18286
+ let cursor3 = from;
18287
+ for (const [a2, b] of inlineRanges(raw)) {
18288
+ if (b <= cursor3 || a2 >= to)
18289
+ continue;
18290
+ quoting = true;
18291
+ own += raw.slice(cursor3, Math.max(a2, cursor3));
18292
+ cursor3 = Math.max(cursor3, b);
18293
+ }
18294
+ own += `${raw.slice(cursor3, Math.max(to, cursor3))}
18295
+ `;
18296
+ }
18297
+ if (nl < 0)
18298
+ break;
18299
+ at = nl + 1;
18300
+ }
18301
+ if (OPENS.test(before) && CLOSES.test(after))
18302
+ return "inline";
18303
+ const span = bytes2.subarray(start, end).toString("utf8").trim();
18304
+ const opens = span.slice(0, 1);
18305
+ const closes = PAIRS[opens] ?? (opens === "'" || opens === "`" ? opens : "");
18306
+ if (closes && span.length > 1 && span.endsWith(closes) && !span.slice(1, -1).includes(closes))
18307
+ return "inline";
18308
+ return !quoting || /\p{L}/u.test(own) ? null : "inline";
18309
+ }
18310
+
18311
+ // server/src/audit-quotes.ts
18312
+ var KINDS = [
18313
+ "adoption",
18314
+ "retraction reason",
18315
+ "reconsider condition",
18316
+ "anchor reason",
18317
+ "field definition"
18318
+ ];
18319
+ var REPAIR = {
18320
+ adoption: "if it is not your decision, retract it with glean's retract_adoption, giving your own words as the reason. The adoption stays in the history",
18321
+ "retraction reason": "a retraction cannot be undone, and the same words cannot be added again: add evidence or adoption from other words, or save a successor",
18322
+ "reconsider condition": "retract the condition's quote with glean's retract_evidence, or save a successor with the condition you stated. The retraction takes every piece of the record's evidence that cites the same words: when the record's own evidence does, save a successor instead",
18323
+ "anchor reason": "put the record back where it belongs with glean's anchor or replace_anchor. The retired anchor's row stays",
18324
+ "field definition": "a definition cannot be changed or withdrawn: define the field again under another name, or forget the message, which removes the message and everything that quotes it"
18325
+ };
18326
+ function uncheckedLines(unchecked) {
18327
+ const count = (n2, one, many) => `${n2} ${n2 === 1 ? one : many}`;
18328
+ return [
18329
+ unchecked.links ? `${count(unchecked.links, "link", "links")} from harvest or glean: the words a supersedes or conflicts link rested on are not kept. Read the record's evidence and adoption to judge it` : "",
18330
+ unchecked.withdrawals ? `${count(unchecked.withdrawals, "withdrawal", "withdrawals")}: the reason's message is kept, not its span. A withdrawal cannot be undone: if one was wrong, save the record again under a new key` : "",
18331
+ unchecked.resolutions ? `${count(unchecked.resolutions, "resolved conflict", "resolved conflicts")}: the reason's message is kept, not its span. A resolved conflict cannot be reopened: save a successor of one side that names the other in conflicts` : ""
18332
+ ].filter(Boolean);
18333
+ }
18334
+ function auditSections(audit) {
18335
+ const sections = [];
18336
+ for (const kind of KINDS) {
18337
+ const found = audit.findings.filter((f) => f.kind === kind);
18338
+ if (!found.length)
18339
+ continue;
18340
+ sections.push([
18341
+ `${kind}: ${found.length}`,
18342
+ ...found.map((f) => ` ${inline(f.project)} ${inline(f.what)} (${f.row}): s${f.source} bytes ${f.start}-${f.end} ${f.why === "block" ? "touch a block quote or fenced code" : "sit inside quotation marks"}; ${f.live ? "in effect" : "retracted, kept as history"}`),
18343
+ ` What you can do: ${REPAIR[kind]}`
18344
+ ]);
18345
+ }
18346
+ const unchecked = uncheckedLines(audit.unchecked);
18347
+ sections.push(unchecked.length ? ["Not checked, since their words are not kept:", ...unchecked.map((l) => ` ${l}`)] : [
18348
+ "Not checked, since their words are not kept: no such rows (links from harvest or glean, withdrawals, resolved conflicts)"
18349
+ ]);
18350
+ return sections;
18351
+ }
18352
+ var auditClosing = (audit) => `${audit.findings.length} of ${audit.read} ${audit.read === 1 ? "row" : "rows"} rest on words the quotation rule refuses. Nothing was changed. The rule reads markup, not meaning: a row it passes may still be wrong, and one it lists may be right`;
18353
+ async function auditQuotes(db) {
18354
+ const findings = [];
18355
+ let read = 0;
18356
+ const judge2 = (kind, r2) => {
18357
+ read++;
18358
+ const why = notOwnWords(r2.text, r2.start, r2.end);
18359
+ if (why)
18360
+ findings.push({
18361
+ project: r2.project,
18362
+ what: r2.what,
18363
+ kind,
18364
+ row: r2.row,
18365
+ source: r2.source,
18366
+ start: r2.start,
18367
+ end: r2.end,
18368
+ why,
18369
+ live: r2.live
18370
+ });
18371
+ };
18372
+ for (const a2 of await db.selectFrom("unit_adoption as a").innerJoin("unit as u", "u.id", "a.unit_id").innerJoin("project as p", "p.id", "u.project_id").innerJoin("source as s", "s.id", "a.source_id").select([
18373
+ "a.id",
18374
+ "u.key",
18375
+ "p.name",
18376
+ "a.source_id",
18377
+ "a.span_start",
18378
+ "a.span_end",
18379
+ "s.text",
18380
+ "a.retracted_at"
18381
+ ]).orderBy("a.id").execute())
18382
+ judge2("adoption", {
18383
+ project: a2.name,
18384
+ what: a2.key,
18385
+ row: `unit_adoption ${a2.id}`,
18386
+ source: a2.source_id,
18387
+ start: a2.span_start,
18388
+ end: a2.span_end,
18389
+ text: a2.text,
18390
+ live: a2.retracted_at === null
18391
+ });
18392
+ const reason2 = (table, r2) => judge2("retraction reason", {
18393
+ project: r2.name,
18394
+ what: r2.key,
18395
+ row: `${table} ${r2.id}`,
18396
+ source: r2.source,
18397
+ start: r2.retraction_span_start ?? 0,
18398
+ end: r2.retraction_span_end ?? 0,
18399
+ text: r2.text,
18400
+ live: true
18401
+ });
18402
+ for (const r2 of await db.selectFrom("unit_adoption as r").innerJoin("unit as u", "u.id", "r.unit_id").innerJoin("project as p", "p.id", "u.project_id").innerJoin("source as s", "s.id", "r.retraction_source_id").select([
18403
+ "r.id",
18404
+ "u.key",
18405
+ "p.name",
18406
+ "s.id as source",
18407
+ "r.retraction_span_start",
18408
+ "r.retraction_span_end",
18409
+ "s.text"
18410
+ ]).where("r.retraction_span_end", "is not", null).orderBy("r.id").execute())
18411
+ reason2("unit_adoption", r2);
18412
+ for (const r2 of await db.selectFrom("unit_evidence as r").innerJoin("unit as u", "u.id", "r.unit_id").innerJoin("project as p", "p.id", "u.project_id").innerJoin("source as s", "s.id", "r.retraction_source_id").select([
18413
+ "r.id",
18414
+ "u.key",
18415
+ "p.name",
18416
+ "s.id as source",
18417
+ "r.retraction_span_start",
18418
+ "r.retraction_span_end",
18419
+ "s.text"
18420
+ ]).where("r.retraction_span_end", "is not", null).orderBy("r.id").execute())
18421
+ reason2("unit_evidence", r2);
18422
+ for (const e of await db.selectFrom("unit_evidence as e").innerJoin("unit as u", "u.id", "e.unit_id").innerJoin("project as p", "p.id", "u.project_id").innerJoin("source as s", "s.id", "e.source_id").select([
18423
+ "e.id",
18424
+ "u.key",
18425
+ "p.name",
18426
+ "e.source_id",
18427
+ "e.span_start",
18428
+ "e.span_end",
18429
+ "s.text",
18430
+ "e.retracted_at"
18431
+ ]).where("e.role", "=", "reconsiders").orderBy("e.id").execute())
18432
+ judge2("reconsider condition", {
18433
+ project: e.name,
18434
+ what: e.key,
18435
+ row: `unit_evidence ${e.id}`,
18436
+ source: e.source_id,
18437
+ start: e.span_start,
18438
+ end: e.span_end,
18439
+ text: e.text,
18440
+ live: e.retracted_at === null
18441
+ });
18442
+ for (const r2 of await db.selectFrom("unit_anchor_retirement as r").innerJoin("unit_anchor as an", "an.id", "r.anchor_id").innerJoin("unit as u", "u.id", "an.unit_id").innerJoin("project as p", "p.id", "u.project_id").innerJoin("source as s", "s.id", "r.source_id").select(["r.anchor_id", "u.key", "p.name", "r.source_id", "r.span_start", "r.span_end", "s.text"]).orderBy("r.anchor_id").execute())
18443
+ judge2("anchor reason", {
18444
+ project: r2.name,
18445
+ what: r2.key,
18446
+ row: `unit_anchor_retirement ${r2.anchor_id}`,
18447
+ source: r2.source_id,
18448
+ start: r2.span_start,
18449
+ end: r2.span_end,
18450
+ text: r2.text,
18451
+ live: true
18452
+ });
18453
+ for (const f of await db.selectFrom("field_def as f").innerJoin("project as p", "p.id", "f.project_id").innerJoin("source as s", "s.id", "f.source_id").select(["f.id", "f.name as field", "p.name", "f.source_id", "f.span_start", "f.span_end", "s.text"]).orderBy("f.id").execute())
18454
+ judge2("field definition", {
18455
+ project: f.name,
18456
+ what: f.field,
18457
+ row: `field_def ${f.id}`,
18458
+ source: f.source_id,
18459
+ start: f.span_start,
18460
+ end: f.span_end,
18461
+ text: f.text,
18462
+ live: true
18463
+ });
18464
+ const count = async (q) => Number((await q.executeTakeFirstOrThrow()).n);
18465
+ const links = await count(db.selectFrom("unit_link as l").innerJoin("extraction_run as r", "r.id", "l.run_id").select((eb) => eb.fn.countAll().as("n")).where("r.origin", "in", ["harvest", "glean"]));
18466
+ const withdrawals = await count(db.selectFrom("unit_state").select((eb) => eb.fn.countAll().as("n")).where("to_state", "=", "withdrawn").where("run_id", "is not", null));
18467
+ const resolutions = await count(db.selectFrom("unit_link").select((eb) => eb.fn.countAll().as("n")).where("kind", "=", "conflicts").where("resolved_at", "is not", null));
18468
+ return { findings, read, unchecked: { links, withdrawals, resolutions } };
18469
+ }
18470
+
18087
18471
  // server/src/cli/common.ts
18088
18472
  async function withDb(role, fn) {
18089
18473
  const db = role === "reader" ? openReader() : openWriter(role);
@@ -18831,6 +19215,16 @@ async function doctor(cwd) {
18831
19215
  runtime = false;
18832
19216
  say2("fail", "Node", plain(reason(e)));
18833
19217
  }
19218
+ const tree = fs11.lstatSync(path11.join(os4.homedir(), ".sphica"), { throwIfNoEntry: false }) ? repositoryRoot(cwd) : null;
19219
+ if (tree) {
19220
+ const place = await workerPlace(tree);
19221
+ if (place === "ready")
19222
+ say2("ok", "Git worker", "ready");
19223
+ else if (place.unread === "refused")
19224
+ say2("warn", "Git worker", `would not start: ${refusalText(place.code)}. Reviews cannot read this work tree until that changes`);
19225
+ else
19226
+ say2("warn", "Git worker", place.unread === "timeout" ? "did not answer in time" : "could not be started");
19227
+ }
18834
19228
  const file = dbFile();
18835
19229
  let usable2 = false;
18836
19230
  if (!runtime)
@@ -19012,6 +19406,18 @@ async function uninstall(yes) {
19012
19406
  ], "Sphica does not run these for you"));
19013
19407
  });
19014
19408
  }
19409
+ async function auditReport() {
19410
+ const head2 = "sphica doctor --audit-quotes";
19411
+ let audit;
19412
+ try {
19413
+ audit = await withDb("reader", (db) => auditQuotes(db));
19414
+ } catch (e) {
19415
+ console.log(failure(head2, plain(reason(e))));
19416
+ process.exitCode = 1;
19417
+ return;
19418
+ }
19419
+ console.log(document(head2, undefined, auditSections(audit).map((lines) => ({ kind: "lines", lines })), `${mark(audit.findings.length ? "warn" : "ok")} ${auditClosing(audit)}`));
19420
+ }
19015
19421
  async function boxed(head2, fn) {
19016
19422
  console.log(title2(head2));
19017
19423
  let outcome;
@@ -19063,10 +19469,25 @@ var root = buildRouteMap({
19063
19469
  kind: "boolean",
19064
19470
  brief: "Rebuild the full-text index when doctor reports it broken",
19065
19471
  optional: true
19472
+ },
19473
+ "audit-quotes": {
19474
+ kind: "boolean",
19475
+ brief: "List saved adoptions and reasons that rest on quoted words, without changing anything",
19476
+ optional: true,
19477
+ withNegated: false
19066
19478
  }
19067
19479
  }
19068
19480
  },
19069
- func: (flags) => flags.reindex ? boxed("sphica doctor --reindex", () => reindex()) : doctor(process.cwd())
19481
+ func: (flags) => {
19482
+ if (flags.reindex && flags["audit-quotes"]) {
19483
+ console.log(failed("--audit-quotes only reads, so it cannot go with --reindex. Run them one at a time"));
19484
+ process.exitCode = 1;
19485
+ return;
19486
+ }
19487
+ if (flags["audit-quotes"])
19488
+ return auditReport();
19489
+ return flags.reindex ? boxed("sphica doctor --reindex", () => reindex()) : doctor(process.cwd());
19490
+ }
19070
19491
  }),
19071
19492
  uninstall: buildCommand({
19072
19493
  docs: { brief: "Delete this machine's Sphica data (~/.sphica) and show how to remove the rest" },