sphica 0.6.57 → 0.6.59

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.57",
4
+ "version": "0.6.59",
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.57",
3
+ "version": "0.6.59",
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,12 +31,13 @@ The database is a single SQLite file on your machine.
31
31
  - **Evidence found later.** `/sphica:glean` adds evidence and corrections to existing records. It asks you for the source (an issue URL, the file and line, meeting notes) before saving; a claim without one is kept only as unsourced and never used as fact.
32
32
  - **Forget what should not have been kept.** `/sphica:forget` removes the messages, pull request items, or file excerpts you pick, with their search entries and the bytes left in the database file, after you confirm in a dialog. Records that cited them are judged again and leave active when nothing else supports them; a record's own text stays as it was.
33
33
  - **Shown when it matters.** At session start, the current work; before the agent reads or edits a file, or runs a shell command that names it, the decisions tied to that file; when your prompt names a recorded option or code symbol, that record. An AI's decision is marked as one, with a note that the agent may depart from it for a stated reason.
34
+ - **A command that failed before is stopped once.** When a dead end is recorded with the command it is about (such as `pnpm test --watch`), the first shell call in a conversation that runs that command is stopped, with the dead end as the reason. The agent checks the record and takes another way, or runs the call again, which then goes through.
34
35
  - **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` setting 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. [Settings](https://github.com/iroha924/sphica#settings) says how to turn it on.
35
36
  - **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.
36
37
  - **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.
37
38
  - **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. 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 (oldest first, up to 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.
38
39
  - **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.
39
- - **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.
40
+ - **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 (a shell call a dead end stopped, or was shown on without a stop, counted apart) 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.
40
41
  - **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.
41
42
  - **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.
42
43
  - **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.
@@ -121,9 +122,10 @@ Without being asked, Sphica adds a few past records to what the agent sees, each
121
122
  - On a prompt that names a recorded code symbol, file path, or option.
122
123
  - Before the agent reads or edits a file a decision applies to, and before a shell command that names such a file (naming it is not proof the command reads it). A read shows each record once per session.
123
124
  - After a shell command that changed the content of such a file, when the `shell_write_delivery` setting is on (off by default): the decisions on it the agent has not seen in this conversation.
125
+ - Before a shell command that runs the command a recorded dead end is about: the call is stopped, with the dead end as the reason. A dead end stops a conversation once (once more after a compaction or `/clear`), and a conversation is stopped at most three times. Running the call again goes through. Past three stops, or for a dead end the conversation has already seen, the dead end is shown without stopping, within the read limit.
124
126
  - Before a review. When you run your own review command (any name containing `review`, or a name listed in the review commands [setting](https://github.com/iroha924/sphica#settings)), it gets the decisions your local change touches. `/sphica:review` checks them itself.
125
127
 
126
- In Codex the same happens at session start, on a prompt, before an `apply_patch` edit, before a shell command that names such a file (Codex reads files through shell commands, so this covers reads), and, with the setting on, after a shell command that changed one.
128
+ In Codex the same happens at session start, on a prompt, before an `apply_patch` edit, before a shell command that names such a file (Codex reads files through shell commands, so this covers reads), before a shell command that runs a dead end's command (stopped once, as in Claude Code), and, with the setting on, after a shell command that changed one.
127
129
  Before a review, Codex gets the same decisions in three cases: its built-in review (`/review`, `codex review`), a review skill you name in the prompt (`$my-review`), and a review skill the agent picks itself, when it prints the skill's file with one plain command such as `cat <path>/SKILL.md`. A skill is a review when its name contains `review` or is listed in `SPHICA_REVIEW_COMMANDS`. `$sphica:review` checks them itself.
128
130
 
129
131
  The agent searches with Sphica's `search` and opens full records with `read`. `status` tells it how much of the history has been traced, so an empty search is less likely to be mistaken for "never decided".
@@ -160,6 +162,7 @@ The agent searches with Sphica's `search` and opens full records with `read`. `s
160
162
 
161
163
  - Only what you traced, harvested, or gleaned becomes a structured record. The rest of a conversation is searchable as captured text (`search` with `sources: true`).
162
164
  - For shell commands, Sphica only sees whether a command names a file. It may show decisions for a file the command never reads, and a shell command that edits a file is not treated as an edit (in Codex, a patch passed to `apply_patch` through the shell is treated as an edit).
165
+ - A dead end's command is matched by its words, whole and in a row, within one command of one line. Sphica reads no other shell syntax: a mention outside quotes (`echo pnpm test --watch`) matches, and a command joined to the one before it without a space (`npm ci;pnpm test --watch`) or written another way (`npm.cmd`) does not.
163
166
  - Before a review, Sphica compares your working tree with the default branch, whatever the review itself was given (a commit or a base branch in Codex's built-in review). In Codex, a review skill the agent reads in any other way than one plain command (after `cd`, through a pipe, inside a longer script) gets nothing, and neither does the built-in review of a `codex exec --ephemeral` run.
164
167
  - In Codex, `$sphica:trace`, `$sphica:harvest`, and `$sphica:glean` can write only when Codex tells Sphica which directory the session is in. Current Codex does. When it does not, they write nothing and tell you why.
165
168
  - Showing a record does not make the agent follow it.
@@ -0,0 +1,58 @@
1
+ -- Copyright (c) 2026 iroha924 and contributors
2
+ -- SPDX-License-Identifier: MIT
3
+
4
+ -- Revision 13 → 14 of generation 2: a dead end can be anchored to the command it is about (unit_command), and search finds it by that
5
+ -- command. No record had one before, so the full-text index needs no rebuild. Every statement is the same as in the schema at revision 14.
6
+
7
+ create table unit_command (
8
+ id integer primary key autoincrement not null,
9
+ unit_id integer not null references unit (id) on delete cascade,
10
+ command text not null check (instr(cast(command as blob), x'00') = 0 and length(command) between 3 and 200 and command = trim(command)
11
+ and command glob '* *'
12
+ and command not glob '* *' and command not glob '-*' and command not glob '*[''"`]*' and command not glob '*[;|&]*'
13
+ and command not glob '*[' || char(1) || '-' || char(31) || char(127) || '-' || char(159) || ']*'),
14
+ run_id integer not null references extraction_run (id),
15
+ added_at text not null check (strftime('%Y-%m-%dT%H:%M:%fZ', added_at) is added_at)
16
+ ) strict;
17
+ create unique index unit_command_once on unit_command (unit_id, command);
18
+ create index unit_command_run on unit_command (run_id);
19
+ create trigger unit_command_check before insert on unit_command begin
20
+ select raise(abort, 'only a dead end is anchored to a command')
21
+ where not exists (select 1 from unit where id = new.unit_id and kind = 'dead_end');
22
+ select raise(abort, 'command and unit belong to different projects')
23
+ where (select project_id from unit where id = new.unit_id) is not (select project_id from extraction_run where id = new.run_id);
24
+ end;
25
+ create trigger unit_command_frozen before update on unit_command begin
26
+ select raise(abort, 'a command anchor is never changed');
27
+ end;
28
+ create trigger unit_command_no_delete before delete on unit_command when exists (select 1 from unit where id = old.unit_id) begin
29
+ select raise(abort, 'a command anchor goes only with its record');
30
+ end;
31
+
32
+ create trigger unit_rev_command_i after insert on unit_command begin update unit set revision = revision + 1 where id = new.unit_id; end;
33
+
34
+ drop view unit_search_text;
35
+ create view unit_search_text as
36
+ select u.id,
37
+ sphica_terms(u.text || char(10) || coalesce(u.why, '') || char(10) || coalesce(u.scope_note, '') || char(10)
38
+ || coalesce(u.revisit_when, '') || char(10)
39
+ || coalesce((select group_concat(o.text || ' ' || coalesce(o.why, '') || ' ' || coalesce(o.reconsider_when, ''), char(10))
40
+ from (select text, why, reconsider_when from unit_option where unit_id = u.id order by position) o), '') || char(10)
41
+ || coalesce((select group_concat(f.name || ' ' || f.value, char(10))
42
+ from (select d.name, v.value from unit_field v join field_def d on d.id = v.field_def_id where v.unit_id = u.id order by v.id) f), ''))
43
+ as body,
44
+ sphica_terms(coalesce((select group_concat(a.path || ' ' || coalesce(a.symbol, ''), char(10))
45
+ from (select path, symbol from unit_anchor where unit_id = u.id and retired_at is null order by id) a), '') || char(10)
46
+ || coalesce((select group_concat(c.command, char(10)) from (select command from unit_command where unit_id = u.id order by id) c), ''))
47
+ as ident,
48
+ sphica_terms(coalesce((select group_concat(j.value, ' ')
49
+ from json_each((select terms from unit_alias where unit_id = u.id and content_hash = u.content_hash order by id desc limit 1)) j), ''))
50
+ as alias
51
+ from unit u;
52
+
53
+ create trigger unit_fts_command_i after insert on unit_command begin
54
+ delete from unit_fts where rowid = new.unit_id;
55
+ insert into unit_fts (rowid, body, ident, alias) select id, body, ident, alias from unit_search_text where id = new.unit_id;
56
+ end;
57
+
58
+ pragma user_version = 14;
package/db/schema.sql CHANGED
@@ -766,6 +766,33 @@ when exists (select 1 from unit_anchor where id = old.anchor_id) and exists (sel
766
766
  select raise(abort, 'a retirement reason goes only with its anchor or its source');
767
767
  end;
768
768
 
769
+ -- A command a dead end is about, as typed: delivery stops the first call of a conversation that runs it, matching whole words per line.
770
+ -- Words are split by single spaces, so a command needs a program and at least one more word; quotes would never match a call's words
771
+ create table unit_command (
772
+ id integer primary key autoincrement not null,
773
+ unit_id integer not null references unit (id) on delete cascade,
774
+ command text not null check (instr(cast(command as blob), x'00') = 0 and length(command) between 3 and 200 and command = trim(command)
775
+ and command glob '* *'
776
+ and command not glob '* *' and command not glob '-*' and command not glob '*[''"`]*' and command not glob '*[;|&]*'
777
+ and command not glob '*[' || char(1) || '-' || char(31) || char(127) || '-' || char(159) || ']*'),
778
+ run_id integer not null references extraction_run (id),
779
+ added_at text not null check (strftime('%Y-%m-%dT%H:%M:%fZ', added_at) is added_at)
780
+ ) strict;
781
+ create unique index unit_command_once on unit_command (unit_id, command);
782
+ create index unit_command_run on unit_command (run_id);
783
+ create trigger unit_command_check before insert on unit_command begin
784
+ select raise(abort, 'only a dead end is anchored to a command')
785
+ where not exists (select 1 from unit where id = new.unit_id and kind = 'dead_end');
786
+ select raise(abort, 'command and unit belong to different projects')
787
+ where (select project_id from unit where id = new.unit_id) is not (select project_id from extraction_run where id = new.run_id);
788
+ end;
789
+ create trigger unit_command_frozen before update on unit_command begin
790
+ select raise(abort, 'a command anchor is never changed');
791
+ end;
792
+ create trigger unit_command_no_delete before delete on unit_command when exists (select 1 from unit where id = old.unit_id) begin
793
+ select raise(abort, 'a command anchor goes only with its record');
794
+ end;
795
+
769
796
  -- What an active unit must have, in one place: missing says what it lacks, and is null when it lacks nothing. Activating reads it, and so
770
797
  -- does every change that can take support away (a retraction, retiring an anchor), so the two never disagree.
771
798
  -- Evidence on an option supports the option, never the unit.
@@ -1091,13 +1118,14 @@ end;
1091
1118
  create trigger unit_rev_retirement_d after delete on unit_anchor_retirement begin
1092
1119
  update unit set revision = revision + 1 where id = (select unit_id from unit_anchor where id = old.anchor_id);
1093
1120
  end;
1121
+ create trigger unit_rev_command_i after insert on unit_command begin update unit set revision = revision + 1 where id = new.unit_id; end;
1094
1122
  create trigger unit_rev_alias_i after insert on unit_alias begin update unit set revision = revision + 1 where id = new.unit_id; end;
1095
1123
  create trigger unit_rev_field_i after insert on unit_field begin update unit set revision = revision + 1 where id = new.unit_id; end;
1096
1124
  create trigger unit_rev_field_d after delete on unit_field when exists (select 1 from unit where id = old.unit_id) begin
1097
1125
  update unit set revision = revision + 1 where id = old.unit_id;
1098
1126
  end;
1099
1127
 
1100
- -- Unit search text: body (text, reason, scope, revisit condition, options and their reconsider conditions, field names and values), identifiers (live anchors), and the newest matching alias set.
1128
+ -- Unit search text: body (text, reason, scope, revisit condition, options and their reconsider conditions, field names and values), identifiers (live anchors and command anchors), and the newest matching alias set.
1101
1129
  -- search.ts weighs body and identifiers above aliases. Lifecycle is not indexed; queries filter it.
1102
1130
  create view unit_search_text as
1103
1131
  select u.id,
@@ -1109,7 +1137,9 @@ select u.id,
1109
1137
  from (select d.name, v.value from unit_field v join field_def d on d.id = v.field_def_id where v.unit_id = u.id order by v.id) f), ''))
1110
1138
  as body,
1111
1139
  sphica_terms(coalesce((select group_concat(a.path || ' ' || coalesce(a.symbol, ''), char(10))
1112
- from (select path, symbol from unit_anchor where unit_id = u.id and retired_at is null order by id) a), '')) as ident,
1140
+ from (select path, symbol from unit_anchor where unit_id = u.id and retired_at is null order by id) a), '') || char(10)
1141
+ || coalesce((select group_concat(c.command, char(10)) from (select command from unit_command where unit_id = u.id order by id) c), ''))
1142
+ as ident,
1113
1143
  sphica_terms(coalesce((select group_concat(j.value, ' ')
1114
1144
  from json_each((select terms from unit_alias where unit_id = u.id and content_hash = u.content_hash order by id desc limit 1)) j), ''))
1115
1145
  as alias
@@ -1138,6 +1168,10 @@ create trigger unit_fts_anchor_d after delete on unit_anchor when exists (select
1138
1168
  delete from unit_fts where rowid = old.unit_id;
1139
1169
  insert into unit_fts (rowid, body, ident, alias) select id, body, ident, alias from unit_search_text where id = old.unit_id;
1140
1170
  end;
1171
+ create trigger unit_fts_command_i after insert on unit_command begin
1172
+ delete from unit_fts where rowid = new.unit_id;
1173
+ insert into unit_fts (rowid, body, ident, alias) select id, body, ident, alias from unit_search_text where id = new.unit_id;
1174
+ end;
1141
1175
  create trigger unit_fts_alias_i after insert on unit_alias begin
1142
1176
  delete from unit_fts where rowid = new.unit_id;
1143
1177
  insert into unit_fts (rowid, body, ident, alias) select id, body, ident, alias from unit_search_text where id = new.unit_id;
@@ -1301,4 +1335,4 @@ create trigger capture_delivery_prune_insert instead of insert on capture_delive
1301
1335
  order by d.at, d.id limit 200);
1302
1336
  end;
1303
1337
 
1304
- pragma user_version = 13;
1338
+ pragma user_version = 14;
package/dist/capture.js CHANGED
@@ -11587,7 +11587,7 @@ var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
11587
11587
 
11588
11588
  // server/src/sqlite.ts
11589
11589
  var SCHEMA_GENERATION = 2;
11590
- var SCHEMA_REVISION = 13;
11590
+ var SCHEMA_REVISION = 14;
11591
11591
  var sphicaHome = () => process.env.SPHICA_HOME || path4.join(os2.homedir(), ".sphica");
11592
11592
  var dbFile = () => process.env.SPHICA_DB || path4.join(sphicaHome(), "sphica.db");
11593
11593
  function requireRuntime() {
@@ -11608,6 +11608,9 @@ function prepare(raw, check, busyMs = 5000) {
11608
11608
  checkGeneration(raw);
11609
11609
  if (check === "generation")
11610
11610
  return;
11611
+ requireRevision(raw);
11612
+ }
11613
+ function requireRevision(raw) {
11611
11614
  const got = raw.prepare("pragma user_version").get()?.user_version;
11612
11615
  if (got === SCHEMA_REVISION)
11613
11616
  return;
@@ -11799,6 +11802,7 @@ var INGEST_INSERTS = new Set([
11799
11802
  "unit_replacement",
11800
11803
  "unit_anchor",
11801
11804
  "unit_anchor_retirement",
11805
+ "unit_command",
11802
11806
  "unit_alias",
11803
11807
  "field_def",
11804
11808
  "unit_field",
@@ -11846,14 +11850,22 @@ var INGEST_TRIGGER_WRITES = {
11846
11850
  "field_i",
11847
11851
  "field_d",
11848
11852
  "retirement_i",
11849
- "retirement_d"
11853
+ "retirement_d",
11854
+ "command_i"
11850
11855
  ].map((t) => [`unit_rev_${t}`, ["update unit"]])),
11851
11856
  unit_fts_ai: ["insert unit_fts"],
11852
11857
  unit_fts_ad: ["delete unit_fts"],
11853
- ...Object.fromEntries(["option_i", "anchor_i", "anchor_u", "anchor_d", "alias_i", "alias_d", "field_i", "field_d"].map((t) => [
11854
- `unit_fts_${t}`,
11855
- ["delete unit_fts", "insert unit_fts"]
11856
- ]))
11858
+ ...Object.fromEntries([
11859
+ "option_i",
11860
+ "anchor_i",
11861
+ "anchor_u",
11862
+ "anchor_d",
11863
+ "command_i",
11864
+ "alias_i",
11865
+ "alias_d",
11866
+ "field_i",
11867
+ "field_d"
11868
+ ].map((t) => [`unit_fts_${t}`, ["delete unit_fts", "insert unit_fts"]]))
11857
11869
  };
11858
11870
  var opOf = (action) => action === C2.SQLITE_INSERT ? "insert" : action === C2.SQLITE_UPDATE ? "update" : action === C2.SQLITE_DELETE ? "delete" : undefined;
11859
11871
  function ingestAuthorizer(action, p1, p2, trigger) {
@@ -11915,6 +11927,59 @@ function forgetAuthorizer(action, p1, p2) {
11915
11927
  return C2.SQLITE_OK;
11916
11928
  return C2.SQLITE_DENY;
11917
11929
  }
11930
+ function checkedWrites(raw) {
11931
+ let checked = false;
11932
+ raw.prepare = (text3, ...rest) => {
11933
+ const st = DatabaseSync2.prototype.prepare.call(raw, text3, ...rest);
11934
+ if (text3 !== "begin immediate")
11935
+ return st;
11936
+ const begin = () => {
11937
+ st.run();
11938
+ try {
11939
+ requireRevision(raw);
11940
+ } catch (e) {
11941
+ try {
11942
+ raw.prepare("rollback").run();
11943
+ } catch {}
11944
+ throw e;
11945
+ }
11946
+ checked = true;
11947
+ };
11948
+ return {
11949
+ columns: () => st.columns(),
11950
+ run: () => {
11951
+ begin();
11952
+ return { changes: 0, lastInsertRowid: 0 };
11953
+ },
11954
+ all: () => {
11955
+ begin();
11956
+ return [];
11957
+ },
11958
+ get: () => {
11959
+ begin();
11960
+ return;
11961
+ },
11962
+ iterate: () => {
11963
+ throw new Error("begin immediate runs through run, all, or get");
11964
+ }
11965
+ };
11966
+ };
11967
+ return (action, p1, p2) => {
11968
+ if (action === C2.SQLITE_PRAGMA && p1 === "user_version" && p2 === null)
11969
+ return C2.SQLITE_OK;
11970
+ if (action === C2.SQLITE_TRANSACTION && p1 === "BEGIN")
11971
+ checked = false;
11972
+ if (action === C2.SQLITE_SAVEPOINT && !raw.isTransaction)
11973
+ checked = false;
11974
+ if (writes(action) && !SHADOW.test(p1 ?? "")) {
11975
+ if (!raw.isTransaction)
11976
+ checked = false;
11977
+ if (!checked)
11978
+ return C2.SQLITE_DENY;
11979
+ }
11980
+ return null;
11981
+ };
11982
+ }
11918
11983
  function connectWriter(role, file = dbFile(), create = false, busyMs) {
11919
11984
  requireRuntime();
11920
11985
  if (!create)
@@ -11927,11 +11992,10 @@ function connectWriter(role, file = dbFile(), create = false, busyMs) {
11927
11992
  raw.close();
11928
11993
  throw e;
11929
11994
  }
11930
- if (role === "ingest")
11931
- raw.setAuthorizer((action, p1, p2, _db, trigger) => ingestAuthorizer(action, p1, p2, trigger));
11932
- else if (role === "forget")
11933
- raw.setAuthorizer(forgetAuthorizer);
11934
- else if (role === "capture") {
11995
+ if (role === "ingest" || role === "forget") {
11996
+ const gate = checkedWrites(raw);
11997
+ raw.setAuthorizer((action, p1, p2, _db, trigger) => gate(action, p1, p2) ?? (role === "ingest" ? ingestAuthorizer(action, p1, p2, trigger) : forgetAuthorizer(action, p1, p2)));
11998
+ } else if (role === "capture") {
11935
11999
  let own = false;
11936
12000
  raw.setAuthorizer((action, p1, p2, _db, triggerOrView) => captureAuthorizer(own, action, p1, p2, triggerOrView));
11937
12001
  const prepare2 = raw.prepare.bind(raw);
package/dist/cli.js CHANGED
@@ -5082,7 +5082,7 @@ ${indent}${caution(note)}` : ""}`);
5082
5082
 
5083
5083
  // server/src/sqlite.ts
5084
5084
  var SCHEMA_GENERATION = 2;
5085
- var SCHEMA_REVISION = 13;
5085
+ var SCHEMA_REVISION = 14;
5086
5086
  var sphicaHome = () => process.env.SPHICA_HOME || path4.join(os3.homedir(), ".sphica");
5087
5087
  var dbFile = () => process.env.SPHICA_DB || path4.join(sphicaHome(), "sphica.db");
5088
5088
  function requireRuntime() {
@@ -5103,6 +5103,9 @@ function prepare(raw, check, busyMs = 5000) {
5103
5103
  checkGeneration(raw);
5104
5104
  if (check === "generation")
5105
5105
  return;
5106
+ requireRevision(raw);
5107
+ }
5108
+ function requireRevision(raw) {
5106
5109
  const got = raw.prepare("pragma user_version").get()?.user_version;
5107
5110
  if (got === SCHEMA_REVISION)
5108
5111
  return;
@@ -16179,6 +16182,7 @@ var INGEST_INSERTS = new Set([
16179
16182
  "unit_replacement",
16180
16183
  "unit_anchor",
16181
16184
  "unit_anchor_retirement",
16185
+ "unit_command",
16182
16186
  "unit_alias",
16183
16187
  "field_def",
16184
16188
  "unit_field",
@@ -16226,14 +16230,22 @@ var INGEST_TRIGGER_WRITES = {
16226
16230
  "field_i",
16227
16231
  "field_d",
16228
16232
  "retirement_i",
16229
- "retirement_d"
16233
+ "retirement_d",
16234
+ "command_i"
16230
16235
  ].map((t2) => [`unit_rev_${t2}`, ["update unit"]])),
16231
16236
  unit_fts_ai: ["insert unit_fts"],
16232
16237
  unit_fts_ad: ["delete unit_fts"],
16233
- ...Object.fromEntries(["option_i", "anchor_i", "anchor_u", "anchor_d", "alias_i", "alias_d", "field_i", "field_d"].map((t2) => [
16234
- `unit_fts_${t2}`,
16235
- ["delete unit_fts", "insert unit_fts"]
16236
- ]))
16238
+ ...Object.fromEntries([
16239
+ "option_i",
16240
+ "anchor_i",
16241
+ "anchor_u",
16242
+ "anchor_d",
16243
+ "command_i",
16244
+ "alias_i",
16245
+ "alias_d",
16246
+ "field_i",
16247
+ "field_d"
16248
+ ].map((t2) => [`unit_fts_${t2}`, ["delete unit_fts", "insert unit_fts"]]))
16237
16249
  };
16238
16250
  var opOf = (action) => action === C2.SQLITE_INSERT ? "insert" : action === C2.SQLITE_UPDATE ? "update" : action === C2.SQLITE_DELETE ? "delete" : undefined;
16239
16251
  function ingestAuthorizer(action, p1, p2, trigger) {
@@ -16295,6 +16307,59 @@ function forgetAuthorizer(action, p1, p2) {
16295
16307
  return C2.SQLITE_OK;
16296
16308
  return C2.SQLITE_DENY;
16297
16309
  }
16310
+ function checkedWrites(raw) {
16311
+ let checked = false;
16312
+ raw.prepare = (text3, ...rest) => {
16313
+ const st = DatabaseSync2.prototype.prepare.call(raw, text3, ...rest);
16314
+ if (text3 !== "begin immediate")
16315
+ return st;
16316
+ const begin = () => {
16317
+ st.run();
16318
+ try {
16319
+ requireRevision(raw);
16320
+ } catch (e) {
16321
+ try {
16322
+ raw.prepare("rollback").run();
16323
+ } catch {}
16324
+ throw e;
16325
+ }
16326
+ checked = true;
16327
+ };
16328
+ return {
16329
+ columns: () => st.columns(),
16330
+ run: () => {
16331
+ begin();
16332
+ return { changes: 0, lastInsertRowid: 0 };
16333
+ },
16334
+ all: () => {
16335
+ begin();
16336
+ return [];
16337
+ },
16338
+ get: () => {
16339
+ begin();
16340
+ return;
16341
+ },
16342
+ iterate: () => {
16343
+ throw new Error("begin immediate runs through run, all, or get");
16344
+ }
16345
+ };
16346
+ };
16347
+ return (action, p1, p2) => {
16348
+ if (action === C2.SQLITE_PRAGMA && p1 === "user_version" && p2 === null)
16349
+ return C2.SQLITE_OK;
16350
+ if (action === C2.SQLITE_TRANSACTION && p1 === "BEGIN")
16351
+ checked = false;
16352
+ if (action === C2.SQLITE_SAVEPOINT && !raw.isTransaction)
16353
+ checked = false;
16354
+ if (writes(action) && !SHADOW.test(p1 ?? "")) {
16355
+ if (!raw.isTransaction)
16356
+ checked = false;
16357
+ if (!checked)
16358
+ return C2.SQLITE_DENY;
16359
+ }
16360
+ return null;
16361
+ };
16362
+ }
16298
16363
  function connectWriter(role, file = dbFile(), create = false, busyMs) {
16299
16364
  requireRuntime();
16300
16365
  if (!create)
@@ -16307,11 +16372,10 @@ function connectWriter(role, file = dbFile(), create = false, busyMs) {
16307
16372
  raw.close();
16308
16373
  throw e;
16309
16374
  }
16310
- if (role === "ingest")
16311
- raw.setAuthorizer((action, p1, p2, _db, trigger) => ingestAuthorizer(action, p1, p2, trigger));
16312
- else if (role === "forget")
16313
- raw.setAuthorizer(forgetAuthorizer);
16314
- else if (role === "capture") {
16375
+ if (role === "ingest" || role === "forget") {
16376
+ const gate = checkedWrites(raw);
16377
+ raw.setAuthorizer((action, p1, p2, _db, trigger) => gate(action, p1, p2) ?? (role === "ingest" ? ingestAuthorizer(action, p1, p2, trigger) : forgetAuthorizer(action, p1, p2)));
16378
+ } else if (role === "capture") {
16315
16379
  let own = false;
16316
16380
  raw.setAuthorizer((action, p1, p2, _db, triggerOrView) => captureAuthorizer(own, action, p1, p2, triggerOrView));
16317
16381
  const prepare2 = raw.prepare.bind(raw);
@@ -19436,7 +19500,7 @@ async function init(flags) {
19436
19500
  return;
19437
19501
  }
19438
19502
  await withDb("ingest", async (db) => {
19439
- const added = await db.insertInto("project").values({ key: place.key, name: place.name }).onConflict((oc) => oc.column("key").doNothing()).returning("id").executeTakeFirst();
19503
+ const added = await inTransaction(db, (trx) => trx.insertInto("project").values({ key: place.key, name: place.name }).onConflict((oc) => oc.column("key").doNothing()).returning("id").executeTakeFirst());
19440
19504
  console.log(indent(`${mark(added ? "ok" : "none")} ${inline(place.name)} ${added ? "registered" : "already registered"} (${inline(place.key)}, ${inline(place.root)})`));
19441
19505
  });
19442
19506
  });