sphica 0.6.58 → 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.58",
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.58",
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() {
@@ -11802,6 +11802,7 @@ var INGEST_INSERTS = new Set([
11802
11802
  "unit_replacement",
11803
11803
  "unit_anchor",
11804
11804
  "unit_anchor_retirement",
11805
+ "unit_command",
11805
11806
  "unit_alias",
11806
11807
  "field_def",
11807
11808
  "unit_field",
@@ -11849,14 +11850,22 @@ var INGEST_TRIGGER_WRITES = {
11849
11850
  "field_i",
11850
11851
  "field_d",
11851
11852
  "retirement_i",
11852
- "retirement_d"
11853
+ "retirement_d",
11854
+ "command_i"
11853
11855
  ].map((t) => [`unit_rev_${t}`, ["update unit"]])),
11854
11856
  unit_fts_ai: ["insert unit_fts"],
11855
11857
  unit_fts_ad: ["delete unit_fts"],
11856
- ...Object.fromEntries(["option_i", "anchor_i", "anchor_u", "anchor_d", "alias_i", "alias_d", "field_i", "field_d"].map((t) => [
11857
- `unit_fts_${t}`,
11858
- ["delete unit_fts", "insert unit_fts"]
11859
- ]))
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"]]))
11860
11869
  };
11861
11870
  var opOf = (action) => action === C2.SQLITE_INSERT ? "insert" : action === C2.SQLITE_UPDATE ? "update" : action === C2.SQLITE_DELETE ? "delete" : undefined;
11862
11871
  function ingestAuthorizer(action, p1, p2, trigger) {
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() {
@@ -16182,6 +16182,7 @@ var INGEST_INSERTS = new Set([
16182
16182
  "unit_replacement",
16183
16183
  "unit_anchor",
16184
16184
  "unit_anchor_retirement",
16185
+ "unit_command",
16185
16186
  "unit_alias",
16186
16187
  "field_def",
16187
16188
  "unit_field",
@@ -16229,14 +16230,22 @@ var INGEST_TRIGGER_WRITES = {
16229
16230
  "field_i",
16230
16231
  "field_d",
16231
16232
  "retirement_i",
16232
- "retirement_d"
16233
+ "retirement_d",
16234
+ "command_i"
16233
16235
  ].map((t2) => [`unit_rev_${t2}`, ["update unit"]])),
16234
16236
  unit_fts_ai: ["insert unit_fts"],
16235
16237
  unit_fts_ad: ["delete unit_fts"],
16236
- ...Object.fromEntries(["option_i", "anchor_i", "anchor_u", "anchor_d", "alias_i", "alias_d", "field_i", "field_d"].map((t2) => [
16237
- `unit_fts_${t2}`,
16238
- ["delete unit_fts", "insert unit_fts"]
16239
- ]))
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"]]))
16240
16249
  };
16241
16250
  var opOf = (action) => action === C2.SQLITE_INSERT ? "insert" : action === C2.SQLITE_UPDATE ? "update" : action === C2.SQLITE_DELETE ? "delete" : undefined;
16242
16251
  function ingestAuthorizer(action, p1, p2, trigger) {
package/dist/deliver.js CHANGED
@@ -11650,7 +11650,7 @@ var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
11650
11650
 
11651
11651
  // server/src/sqlite.ts
11652
11652
  var SCHEMA_GENERATION = 2;
11653
- var SCHEMA_REVISION = 13;
11653
+ var SCHEMA_REVISION = 14;
11654
11654
  var sphicaHome = () => process.env.SPHICA_HOME || path5.join(os2.homedir(), ".sphica");
11655
11655
  var dbFile = () => process.env.SPHICA_DB || path5.join(sphicaHome(), "sphica.db");
11656
11656
  function requireRuntime() {
@@ -11900,6 +11900,7 @@ var INGEST_INSERTS = new Set([
11900
11900
  "unit_replacement",
11901
11901
  "unit_anchor",
11902
11902
  "unit_anchor_retirement",
11903
+ "unit_command",
11903
11904
  "unit_alias",
11904
11905
  "field_def",
11905
11906
  "unit_field",
@@ -11947,14 +11948,22 @@ var INGEST_TRIGGER_WRITES = {
11947
11948
  "field_i",
11948
11949
  "field_d",
11949
11950
  "retirement_i",
11950
- "retirement_d"
11951
+ "retirement_d",
11952
+ "command_i"
11951
11953
  ].map((t) => [`unit_rev_${t}`, ["update unit"]])),
11952
11954
  unit_fts_ai: ["insert unit_fts"],
11953
11955
  unit_fts_ad: ["delete unit_fts"],
11954
- ...Object.fromEntries(["option_i", "anchor_i", "anchor_u", "anchor_d", "alias_i", "alias_d", "field_i", "field_d"].map((t) => [
11955
- `unit_fts_${t}`,
11956
- ["delete unit_fts", "insert unit_fts"]
11957
- ]))
11956
+ ...Object.fromEntries([
11957
+ "option_i",
11958
+ "anchor_i",
11959
+ "anchor_u",
11960
+ "anchor_d",
11961
+ "command_i",
11962
+ "alias_i",
11963
+ "alias_d",
11964
+ "field_i",
11965
+ "field_d"
11966
+ ].map((t) => [`unit_fts_${t}`, ["delete unit_fts", "insert unit_fts"]]))
11958
11967
  };
11959
11968
  var opOf = (action) => action === C2.SQLITE_INSERT ? "insert" : action === C2.SQLITE_UPDATE ? "update" : action === C2.SQLITE_DELETE ? "delete" : undefined;
11960
11969
  function ingestAuthorizer(action, p1, p2, trigger) {
@@ -13824,7 +13833,7 @@ var RESTARTS = ["compact", "clear"];
13824
13833
  async function sinceRestart(db, session, agent) {
13825
13834
  const restart = await db.selectFrom("delivery as d").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.event", "=", "session_start").where("d.reason", "in", RESTARTS).select((eb) => eb.fn.max("d.id").as("id")).executeTakeFirst();
13826
13835
  const since = restart?.id ?? 0;
13827
- const sent = await db.selectFrom("delivery as d").innerJoin("delivery_unit as x", "x.delivery_id", "d.id").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.outcome", "=", "emitted").select(["x.unit_id", "d.event"]).execute();
13836
+ const sent = await db.selectFrom("delivery as d").innerJoin("delivery_unit as x", "x.delivery_id", "d.id").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.outcome", "=", "emitted").select(["x.unit_id", "d.event", "d.reason"]).execute();
13828
13837
  return { since, sent };
13829
13838
  }
13830
13839
  async function afterShellWrite(db, projectId2, rels, session, agent) {
@@ -13846,9 +13855,12 @@ async function afterShellWrite(db, projectId2, rels, session, agent) {
13846
13855
  reason: SHELL_WRITE
13847
13856
  };
13848
13857
  }
13849
- async function beforeRead(db, projectId2, rels, session, agent, how) {
13858
+ var STOPPED = "command";
13859
+ var COMMAND_CONTEXT = "command_context";
13860
+ var STOPS = 3;
13861
+ async function readRoom(db, session, agent) {
13850
13862
  const { since, sent } = await sinceRestart(db, session, agent);
13851
- const spent = await db.selectFrom("delivery as d").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.event", "=", "pre_read").where("d.outcome", "=", "emitted").where(({ exists, selectFrom }) => exists(selectFrom("delivery_unit as x").select("x.unit_id").whereRef("x.delivery_id", "=", "d.id"))).select(["d.id", "d.at", "d.chars"]).execute();
13863
+ const spent = await db.selectFrom("delivery as d").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", since).where("d.event", "=", "pre_read").where("d.outcome", "=", "emitted").where((eb) => eb.or([eb("d.reason", "is", null), eb("d.reason", "!=", STOPPED)])).where(({ exists, selectFrom }) => exists(selectFrom("delivery_unit as x").select("x.unit_id").whereRef("x.delivery_id", "=", "d.id"))).select(["d.id", "d.at", "d.chars", "d.reason"]).execute();
13852
13864
  const shownBy = spent.length ? await db.selectFrom("delivery_unit").select(["delivery_id", "unit_id"]).where("delivery_id", "in", spent.map((r) => r.id)).execute() : [];
13853
13865
  const marked = new Map;
13854
13866
  for (const r of spent) {
@@ -13857,17 +13869,25 @@ async function beforeRead(db, projectId2, rels, session, agent, how) {
13857
13869
  if (n)
13858
13870
  marked.set(r.id, n);
13859
13871
  }
13860
- const seen = new Set(sent.map((r) => r.unit_id));
13861
- const readUnits = sent.filter((r) => r.event === "pre_read").length;
13862
- const rows = (await anchoredTo(db, projectId2, rels).where("u.kind", "in", ["decision", "constraint"]).execute()).filter((u) => !seen.has(u.id));
13863
- const room = Math.min(LIMITS2.pre_read.units, READ_SESSION.units - readUnits);
13872
+ return {
13873
+ since,
13874
+ seen: new Set(sent.map((r) => r.unit_id)),
13875
+ units: READ_SESSION.units - sent.filter((r) => r.event === "pre_read" && r.reason !== STOPPED).length,
13876
+ chars: READ_SESSION.chars + ASK - spent.reduce((n, r) => {
13877
+ const ai = marked.get(r.id) ?? 0;
13878
+ const ask2 = r.reason === COMMAND_CONTEXT ? RAN.length + 1 : ASK;
13879
+ return n + Math.max(r.chars - ask2 - (ai ? AI_ROOM + ai * AI_MARK.length : 0), 0);
13880
+ }, 0)
13881
+ };
13882
+ }
13883
+ async function beforeRead(db, projectId2, rels, session, agent, how) {
13884
+ const left = await readRoom(db, session, agent);
13885
+ const rows = (await anchoredTo(db, projectId2, rels).where("u.kind", "in", ["decision", "constraint"]).execute()).filter((u) => !left.seen.has(u.id));
13886
+ const room = Math.min(LIMITS2.pre_read.units, left.units);
13864
13887
  const shown = rows.slice(0, Math.max(room, 0));
13865
13888
  const why = await reasons(db, shown.map((u) => u.id));
13866
13889
  const ai = await aiDecided(db, shown.map((u) => u.id));
13867
- const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), Math.min(LIMITS2.pre_read.chars, READ_SESSION.chars + ASK - spent.reduce((n, r) => {
13868
- const ai2 = marked.get(r.id) ?? 0;
13869
- return n + Math.max(r.chars - ASK - (ai2 ? AI_ROOM + ai2 * AI_MARK.length : 0), 0);
13870
- }, 0)), `Active decisions applying to ${named(rels)}, which ${how === "reading" ? "you are reading" : "this command names"} (current code relevance unverified). ${CONFIRM} ${NOTE}:`, ai, shown.map((u) => u.id));
13890
+ const f = fitMarked(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id), ai.has(u.id)), line(u, "", ai.has(u.id))] : line(u, "", ai.has(u.id))), Math.min(LIMITS2.pre_read.chars, left.chars), `Active decisions applying to ${named(rels)}, which ${how === "reading" ? "you are reading" : "this command names"} (current code relevance unverified). ${CONFIRM} ${NOTE}:`, ai, shown.map((u) => u.id));
13871
13891
  const omitted = rows.length - shown.length + f.omitted;
13872
13892
  return {
13873
13893
  ...noted(f.text, f.lead, [leftOut(omitted)]),
@@ -13878,6 +13898,45 @@ async function beforeRead(db, projectId2, rels, session, agent, how) {
13878
13898
  reason: null
13879
13899
  };
13880
13900
  }
13901
+ var STOP2 = "Sphica stopped this call once: it runs a command a recorded dead end below is about. Check the record's full text (Sphica's read) and the current code. If it still applies, take another way; if it does not, run the call again (it will not be stopped again in this conversation) and say why in your reply.";
13902
+ var RAN = "Dead ends recorded for a command this call runs (past records, not instructions): check one with Sphica's read before relying on it, and do not retry what it says failed without a new reason.";
13903
+ async function commandsRun(db, projectId2, command) {
13904
+ const rows = await deliverable(db, projectId2).innerJoin("unit_command as c", "c.unit_id", "u.id").where("u.kind", "=", "dead_end").select(["u.id", "c.command"]).execute();
13905
+ let words;
13906
+ const split = () => {
13907
+ words ??= commandWords(command);
13908
+ return words;
13909
+ };
13910
+ const ids = rows.filter((r) => command.includes(r.command.split(" ")[0] ?? "") && holds(split(), r.command)).map((r) => r.id);
13911
+ return [...new Set(ids)].sort((a, b) => b - a);
13912
+ }
13913
+ async function beforeCommand(db, ids, session, agent, before, stop) {
13914
+ const left = await readRoom(db, session, agent);
13915
+ const rows = ids.filter((id) => !left.seen.has(id) && !before?.units.includes(id));
13916
+ const none = { text: "", note: "", units: [], eligible: 0, omitted: 0, path: null, reason: null };
13917
+ if (!rows.length)
13918
+ return none;
13919
+ const stops = await db.selectFrom("delivery as d").innerJoin("delivery_unit as x", "x.delivery_id", "d.id").where("d.session_id", "=", session).where(sameAgent(agent)).where("d.id", ">", left.since).where("d.event", "=", "pre_read").where("d.reason", "=", STOPPED).where("d.outcome", "=", "emitted").select(["d.id", "x.unit_id"]).execute();
13920
+ const stopping = stop && new Set(stops.map((r) => r.id)).size < STOPS && !stops.some((r) => ids.includes(r.unit_id));
13921
+ const ask2 = stopping ? STOP2 : RAN;
13922
+ const room = stopping ? { units: LIMITS2.pre_read.units, chars: LIMITS2.pre_read.chars - ASK + ask2.length + 1 } : {
13923
+ units: Math.min(LIMITS2.pre_read.units, left.units - (before?.units.length ?? 0)),
13924
+ chars: Math.min(LIMITS2.pre_read.chars, left.chars - Math.max((before ? before.text.length - before.note.length : 0) - ASK, 0)) - ASK + ask2.length + 1
13925
+ };
13926
+ const shown = rows.length ? await db.selectFrom("unit as u").where("u.id", "in", rows.slice(0, Math.max(room.units, 0))).select(["u.id", "u.key", "u.kind", "u.stance", "u.text"]).orderBy("u.id", "desc").execute() : [];
13927
+ const why = await reasons(db, shown.map((u) => u.id));
13928
+ const lead = `${ask2} ${NOTE}:`;
13929
+ const f = fit2(shown.map((u) => why.has(u.id) ? [line(u, why.get(u.id)), line(u)] : line(u)), room.chars, lead);
13930
+ const omitted = rows.length - shown.length + f.omitted;
13931
+ return {
13932
+ ...noted(f.text, lead, [leftOut(omitted)]),
13933
+ units: f.kept.flatMap((i) => shown[i]?.id ?? []),
13934
+ eligible: rows.length,
13935
+ omitted,
13936
+ path: null,
13937
+ reason: stopping && f.text ? STOPPED : COMMAND_CONTEXT
13938
+ };
13939
+ }
13881
13940
  function patchPaths2(patch) {
13882
13941
  const out = new Set;
13883
13942
  for (const l of patch.split(/\r?\n/)) {
@@ -13912,6 +13971,41 @@ async function namedInCommand(db, projectId2, root, cwd, command) {
13912
13971
  };
13913
13972
  return paths.map((r) => r.path).filter((p) => command.includes(p.slice(p.lastIndexOf("/") + 1)) && forms(p).some((t) => command.includes(t) && new RegExp(`(?:^|[${edge}])${esc(t)}(?:$|[${edge}:])`).test(command)));
13914
13973
  }
13974
+ function commandsOf(line2) {
13975
+ const out = [[]];
13976
+ const close = () => {
13977
+ if (out.at(-1)?.length)
13978
+ out.push([]);
13979
+ };
13980
+ for (const token of line2.split(/\s+/).filter(Boolean)) {
13981
+ const lead = /^[;|&]+/.exec(token)?.[0].length ?? 0;
13982
+ const word = token.slice(lead).replace(/[;|&]+$/, "");
13983
+ if (lead)
13984
+ close();
13985
+ if (word)
13986
+ out.at(-1)?.push(word);
13987
+ if (lead + word.length < token.length)
13988
+ close();
13989
+ }
13990
+ return out;
13991
+ }
13992
+ function runsCommand(command, anchor) {
13993
+ return holds(commandWords(command), anchor);
13994
+ }
13995
+ function commandWords(command) {
13996
+ return command.split(/\r\n|\n|\r/).flatMap(commandsOf);
13997
+ }
13998
+ function holds(commands, anchor) {
13999
+ const want = anchor.split(" ").filter(Boolean);
14000
+ if (!want.length)
14001
+ return false;
14002
+ return commands.some((got) => {
14003
+ for (let i = 0;i + want.length <= got.length; i++)
14004
+ if (want.every((w, j) => got[i + j] === w))
14005
+ return true;
14006
+ return false;
14007
+ });
14008
+ }
13915
14009
  function pathNamed(prompt, root, rel) {
13916
14010
  const steps = (p) => p.split(/[\\/]/).map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]");
13917
14011
  return new RegExp(`(?<![A-Za-z0-9_$.\\-/\\\\])(?:(?:\\.[\\\\/])?${steps(rel)}|${steps(path12.join(root, rel))})(?![A-Za-z0-9_$\\-/\\\\]|\\.[A-Za-z0-9_$])`).test(prompt);
@@ -14186,6 +14280,36 @@ async function lockedPlan(file, e, make, keep, logged = () => {}) {
14186
14280
  logged(wrote);
14187
14281
  return plan ?? make();
14188
14282
  }
14283
+ async function beforeShell(file, e, db, rels, shell, session, agent) {
14284
+ const named2 = async () => rels.length ? await beforeRead(db, e.projectId, rels, session, agent, "named") : null;
14285
+ const cap = openWriter("capture", file, LOG_WAIT_MS);
14286
+ let plans = null;
14287
+ try {
14288
+ await inTransaction(cap, async (trx) => {
14289
+ const path14 = await named2();
14290
+ if (path14?.text)
14291
+ await write2(trx, e, path14);
14292
+ const run3 = await beforeCommand(db, await commandsRun(db, e.projectId, shell), session, agent, path14, true);
14293
+ if (run3.text)
14294
+ await write2(trx, e, run3);
14295
+ plans = [path14, run3];
14296
+ });
14297
+ } catch {
14298
+ plans = null;
14299
+ } finally {
14300
+ await cap.destroy().catch(() => {});
14301
+ }
14302
+ const done = plans;
14303
+ if (done?.[1].reason === STOPPED)
14304
+ return { stop: [done[1].text, done[0]?.text].filter(Boolean).join(`
14305
+
14306
+ `) };
14307
+ const path13 = done ? done[0] : await named2();
14308
+ const run2 = done ? done[1] : await beforeCommand(db, await commandsRun(db, e.projectId, shell), session, agent, path13, false);
14309
+ return [run2.text, path13?.text].filter(Boolean).join(`
14310
+
14311
+ `);
14312
+ }
14189
14313
  async function snapshotCall(db, projectId2, place, host, input, who, started) {
14190
14314
  const paths = await deliverablePaths(db, projectId2);
14191
14315
  const cache = loadCache(place.root);
@@ -14253,6 +14377,10 @@ async function afterShell(input, host, agent, file, started) {
14253
14377
  }
14254
14378
  }
14255
14379
  async function deliver(input, host = "claude-code", file = dbFile(), started = Date.now()) {
14380
+ const r = await respond(input, host, file, started);
14381
+ return typeof r === "string" ? r : r.stop;
14382
+ }
14383
+ async function respond(input, host = "claude-code", file = dbFile(), started = Date.now()) {
14256
14384
  const thread = host === "codex" && !agentOf(input) ? codexThread(input) : null;
14257
14385
  const who = agentOf(input) ?? childThread(input, thread);
14258
14386
  if (host !== "codex")
@@ -14266,9 +14394,10 @@ async function deliver(input, host = "claude-code", file = dbFile(), started = D
14266
14394
  place,
14267
14395
  reviewUntil: started + REVIEW_MS
14268
14396
  });
14269
- return [review, rest].filter(Boolean).join(`
14397
+ const text3 = [review, typeof rest === "string" ? rest : rest.stop].filter(Boolean).join(`
14270
14398
 
14271
14399
  `);
14400
+ return typeof rest === "string" ? text3 : { stop: text3 };
14272
14401
  }
14273
14402
  async function deliverOne(input, host, file, started, who, call, known = {}) {
14274
14403
  const name = input.hook_event_name;
@@ -14314,9 +14443,11 @@ async function deliverOne(input, host, file, started, who, call, known = {}) {
14314
14443
  }));
14315
14444
  if (onPath && !shell && !rels.length)
14316
14445
  return "";
14446
+ let ran = [];
14317
14447
  if (shell) {
14318
14448
  rels = await namedInCommand(db, pid, place.root, input.cwd ?? place.root, shell);
14319
- if (!rels.length)
14449
+ ran = await commandsRun(db, pid, shell);
14450
+ if (!rels.length && !ran.length)
14320
14451
  return "";
14321
14452
  }
14322
14453
  if (event === "session_start" && input.source === "resume") {
@@ -14350,6 +14481,8 @@ async function deliverOne(input, host, file, started, who, call, known = {}) {
14350
14481
  branch: branchOf(place.root)
14351
14482
  };
14352
14483
  const keep = (p) => !(onPath && !p.text);
14484
+ if (shell && ran.length)
14485
+ return await beforeShell(file, entry, reader, rels, shell, sessionId(pid, host, session), who);
14353
14486
  if (event === "pre_read" || event === "session_start")
14354
14487
  return (await lockedPlan(file, entry, make, keep)).text;
14355
14488
  const plan = await make();
@@ -14371,10 +14504,18 @@ async function deliverOne(input, host, file, started, who, call, known = {}) {
14371
14504
  async function main2() {
14372
14505
  const input = await readInput(process.stdin);
14373
14506
  const host = process.argv[2] === "codex" ? "codex" : "claude-code";
14374
- const context = await deliver(input, host).catch(() => "");
14375
- if (context)
14507
+ const r = await respond(input, host).catch(() => "");
14508
+ if (typeof r !== "string")
14509
+ process.stdout.write(JSON.stringify({
14510
+ hookSpecificOutput: {
14511
+ hookEventName: input.hook_event_name,
14512
+ permissionDecision: "deny",
14513
+ permissionDecisionReason: r.stop
14514
+ }
14515
+ }));
14516
+ else if (r)
14376
14517
  process.stdout.write(JSON.stringify({
14377
- hookSpecificOutput: { hookEventName: input.hook_event_name, additionalContext: context }
14518
+ hookSpecificOutput: { hookEventName: input.hook_event_name, additionalContext: r }
14378
14519
  }));
14379
14520
  }
14380
14521
  if (process.argv[1] && /deliver\.(ts|js)$/.test(process.argv[1])) {
@@ -14384,6 +14525,8 @@ export {
14384
14525
  AUTO_TRACE,
14385
14526
  CONFIRM,
14386
14527
  CONFIRM_GOLD,
14528
+ RAN,
14529
+ STOP2 as STOP,
14387
14530
  anchoredRules,
14388
14531
  codexInteractive,
14389
14532
  deliver,
@@ -14393,5 +14536,7 @@ export {
14393
14536
  namable,
14394
14537
  namedRecords,
14395
14538
  recordLines,
14539
+ respond,
14540
+ runsCommand,
14396
14541
  traceSkill
14397
14542
  };
@@ -46365,7 +46365,7 @@ var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
46365
46365
 
46366
46366
  // server/src/sqlite.ts
46367
46367
  var SCHEMA_GENERATION = 2;
46368
- var SCHEMA_REVISION = 13;
46368
+ var SCHEMA_REVISION = 14;
46369
46369
  var sphicaHome = () => process.env.SPHICA_HOME || path3.join(os2.homedir(), ".sphica");
46370
46370
  var dbFile = () => process.env.SPHICA_DB || path3.join(sphicaHome(), "sphica.db");
46371
46371
  function requireRuntime() {
@@ -46594,6 +46594,7 @@ var INGEST_INSERTS = new Set([
46594
46594
  "unit_replacement",
46595
46595
  "unit_anchor",
46596
46596
  "unit_anchor_retirement",
46597
+ "unit_command",
46597
46598
  "unit_alias",
46598
46599
  "field_def",
46599
46600
  "unit_field",
@@ -46641,14 +46642,22 @@ var INGEST_TRIGGER_WRITES = {
46641
46642
  "field_i",
46642
46643
  "field_d",
46643
46644
  "retirement_i",
46644
- "retirement_d"
46645
+ "retirement_d",
46646
+ "command_i"
46645
46647
  ].map((t) => [`unit_rev_${t}`, ["update unit"]])),
46646
46648
  unit_fts_ai: ["insert unit_fts"],
46647
46649
  unit_fts_ad: ["delete unit_fts"],
46648
- ...Object.fromEntries(["option_i", "anchor_i", "anchor_u", "anchor_d", "alias_i", "alias_d", "field_i", "field_d"].map((t) => [
46649
- `unit_fts_${t}`,
46650
- ["delete unit_fts", "insert unit_fts"]
46651
- ]))
46650
+ ...Object.fromEntries([
46651
+ "option_i",
46652
+ "anchor_i",
46653
+ "anchor_u",
46654
+ "anchor_d",
46655
+ "command_i",
46656
+ "alias_i",
46657
+ "alias_d",
46658
+ "field_i",
46659
+ "field_d"
46660
+ ].map((t) => [`unit_fts_${t}`, ["delete unit_fts", "insert unit_fts"]]))
46652
46661
  };
46653
46662
  var opOf = (action) => action === C2.SQLITE_INSERT ? "insert" : action === C2.SQLITE_UPDATE ? "update" : action === C2.SQLITE_DELETE ? "delete" : undefined;
46654
46663
  function ingestAuthorizer(action, p1, p2, trigger) {
@@ -49013,6 +49022,7 @@ var Unit = exports_external.object({
49013
49022
  commit: exports_external.string().regex(/^[0-9a-f]{40}$/, "a full 40-character commit sha").optional(),
49014
49023
  lines: exports_external.tuple([exports_external.number().int().positive(), exports_external.number().int().positive()]).optional()
49015
49024
  }).strict()).max(20).default([]),
49025
+ commands: exports_external.array(exports_external.string()).max(5).default([]),
49016
49026
  aliases: exports_external.array(exports_external.string()).max(12).default([]),
49017
49027
  supersedes: exports_external.string().min(1).optional(),
49018
49028
  conflicts: exports_external.array(exports_external.string().min(1)).max(5).default([]),
@@ -49046,6 +49056,25 @@ var Record = exports_external.object({
49046
49056
  work: exports_external.preprocess((w) => w === undefined || Array.isArray(w) ? w : [w], exports_external.array(Work).min(1).max(10).optional())
49047
49057
  }).strict();
49048
49058
  var cited = (body, quote) => quote.trim() ? locate(body, quote) : null;
49059
+ function commandProblem(command) {
49060
+ const words = command.split(" ");
49061
+ if ([...command].length < 3 || [...command].length > 200)
49062
+ return "must be 3 to 200 characters";
49063
+ if (words.length < 2)
49064
+ return "needs the program and at least one more word";
49065
+ if (words[0]?.startsWith("-"))
49066
+ return "must start with the program, not an option";
49067
+ if (/['"`]/.test(command))
49068
+ return "must not contain quotes";
49069
+ if (/[;|&]/.test(command))
49070
+ return "must be one command, with no ; | &";
49071
+ const control = (ch) => ch.charCodeAt(0) <= 31 || ch.charCodeAt(0) >= 127 && ch.charCodeAt(0) <= 159;
49072
+ if (inline(command) !== command || [...command].some(control))
49073
+ return "must not contain control or invisible characters";
49074
+ if (mask(command) !== command || placeholderRanges(command).length)
49075
+ return "holds text Sphica masks as a secret";
49076
+ return null;
49077
+ }
49049
49078
  function anchorProblem(facts, a) {
49050
49079
  if (!facts.root || a.held)
49051
49080
  return null;
@@ -49336,6 +49365,20 @@ async function checkRecord(db, target, raw, facts = prepareRecord(target.root, r
49336
49365
  problems.push(`${key}: the anchor on ${x.path}${x.symbol ? ` ${x.symbol}` : ""} appears twice; left out`);
49337
49366
  anchors.splice(anchors.indexOf(x), 1);
49338
49367
  }
49368
+ const commands = [];
49369
+ if (u.commands.length && u.kind !== "dead_end")
49370
+ problems.push(`${key}: commands go only on a dead end; left out`);
49371
+ else
49372
+ for (const [i2, c] of u.commands.entries()) {
49373
+ const command = c.split(/[^\S\n\v\f\r]+/).filter(Boolean).join(" ");
49374
+ const wrong = commandProblem(command);
49375
+ if (wrong)
49376
+ problems.push(`${key}: command ${i2 + 1} ${wrong}; left out`);
49377
+ else if (commands.includes(command))
49378
+ problems.push(`${key}: command ${i2 + 1} appears twice; left out`);
49379
+ else
49380
+ commands.push(command);
49381
+ }
49339
49382
  const aliases = [...new Set(u.aliases.map((a) => a.trim()))];
49340
49383
  const bad = aliases.filter((a) => !a || [...a].length > 40 || inline(a) !== a);
49341
49384
  if (bad.length)
@@ -49421,6 +49464,7 @@ async function checkRecord(db, target, raw, facts = prepareRecord(target.root, r
49421
49464
  options,
49422
49465
  adoption,
49423
49466
  anchors,
49467
+ commands,
49424
49468
  aliases: aliases.filter((a) => !bad.includes(a)),
49425
49469
  supersedes,
49426
49470
  conflicts,
@@ -49774,6 +49818,8 @@ ${checked.errors.map((e) => ` ${e}`).join(`
49774
49818
  added_at: now
49775
49819
  }).execute();
49776
49820
  }
49821
+ for (const command of p.commands)
49822
+ await trx.insertInto("unit_command").values({ unit_id: id, command, run_id: runId, added_at: now }).execute();
49777
49823
  for (const f of p.fields) {
49778
49824
  const field = fieldIds.get(f.name);
49779
49825
  if (field === undefined)
package/dist/mcp.js CHANGED
@@ -46269,7 +46269,7 @@ var HOST_MARKS = new Set([".orphaned_at", ".in_use"]);
46269
46269
 
46270
46270
  // server/src/sqlite.ts
46271
46271
  var SCHEMA_GENERATION = 2;
46272
- var SCHEMA_REVISION = 13;
46272
+ var SCHEMA_REVISION = 14;
46273
46273
  var sphicaHome = () => process.env.SPHICA_HOME || path3.join(os2.homedir(), ".sphica");
46274
46274
  var dbFile = () => process.env.SPHICA_DB || path3.join(sphicaHome(), "sphica.db");
46275
46275
  function requireRuntime() {
@@ -46674,6 +46674,7 @@ var Unit = exports_external.object({
46674
46674
  commit: exports_external.string().regex(/^[0-9a-f]{40}$/, "a full 40-character commit sha").optional(),
46675
46675
  lines: exports_external.tuple([exports_external.number().int().positive(), exports_external.number().int().positive()]).optional()
46676
46676
  }).strict()).max(20).default([]),
46677
+ commands: exports_external.array(exports_external.string()).max(5).default([]),
46677
46678
  aliases: exports_external.array(exports_external.string()).max(12).default([]),
46678
46679
  supersedes: exports_external.string().min(1).optional(),
46679
46680
  conflicts: exports_external.array(exports_external.string().min(1)).max(5).default([]),
@@ -46943,12 +46944,13 @@ async function pastSuccessor(db, id, asOf) {
46943
46944
  }
46944
46945
  async function judgeUnits(db, rows, wanted, hits, asOf) {
46945
46946
  const ids = rows.map((r) => r.id);
46946
- const [options, anchors, aliases, fields] = ids.length ? await Promise.all([
46947
+ const [options, anchors, aliases, fields, commands] = ids.length ? await Promise.all([
46947
46948
  db.selectFrom("unit_option").select(["unit_id", "text", "outcome", "why", "reconsider_when"]).where("unit_id", "in", ids).orderBy("position").execute(),
46948
46949
  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(),
46949
46950
  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(),
46950
- 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()
46951
- ]) : [[], [], [], []];
46951
+ 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(),
46952
+ db.selectFrom("unit_command").select(["unit_id", "command"]).where("unit_id", "in", ids).execute()
46953
+ ]) : [[], [], [], [], []];
46952
46954
  let weaker = 0;
46953
46955
  for (const r of rows) {
46954
46956
  const opts = options.filter((o) => o.unit_id === r.id);
@@ -46961,6 +46963,7 @@ async function judgeUnits(db, rows, wanted, hits, asOf) {
46961
46963
  r.revisit_when,
46962
46964
  ...opts.flatMap((o) => [o.text, o.why, o.reconsider_when]),
46963
46965
  ...anch.flatMap((a) => [a.path, a.symbol]),
46966
+ ...commands.filter((c) => c.unit_id === r.id).map((c) => c.command),
46964
46967
  ...fields.filter((f) => f.unit_id === r.id).flatMap((f) => [f.name, f.value])
46965
46968
  ].filter(Boolean).join(`
46966
46969
  `)));
@@ -47310,6 +47313,7 @@ var DAY_MS = 24 * 60 * 60 * 1000;
47310
47313
  var MORE_LINE = 120;
47311
47314
  var WHO = ["main", "subagent", "subagent, id unknown"];
47312
47315
  var who = (named, event, reason2) => named ? "subagent" : event === "session_start" && reason2 === "subagent" ? "subagent, id unknown" : "main";
47316
+ var eventName = (event, reason2) => reason2 === "command" ? `${event} (command, stopped)` : reason2 === "command_context" ? `${event} (command, not stopped)` : event;
47313
47317
  var DELIVERY_LIMITS_TEXT = [
47314
47318
  "Counted are the logged delivery rows only: since 0.6.16 a read or edit that showed nothing is not logged (older rows show it as nothing), and a delivery answered while the write lock was busy, or whose log write failed, is not either.",
47315
47319
  "A session's rows are dropped once its last delivery is older than 90 days, so a long period is not a rolling window.",
@@ -47363,7 +47367,7 @@ async function deliveryOverview(db, projectId, days, now = new Date) {
47363
47367
  keyed().select((eb) => ["s.id", "s.host", "s.external_id", "s.branch", eb.fn.max("d.at").as("last")]).groupBy("s.id").orderBy("last", "desc").orderBy("s.id").limit(DELIVERY_LIMITS.sessions).execute(),
47364
47368
  keyed().select((eb) => eb.fn.count("d.session_id").distinct().as("n")).executeTakeFirst()
47365
47369
  ]);
47366
- const via = top.length ? await delivered().where("du.unit_id", "in", top.map((t) => t.id)).select(["du.unit_id", "d.event"]).distinct().orderBy("d.event").execute() : [];
47370
+ const via = top.length ? await delivered().where("du.unit_id", "in", top.map((t) => t.id)).select(["du.unit_id", "d.event", "d.reason"]).distinct().execute() : [];
47367
47371
  const shown2 = await Promise.all(recent.map(async (r) => {
47368
47372
  const rows = keyed().where("d.session_id", "=", r.id);
47369
47373
  const [list2, n] = await Promise.all([
@@ -47413,8 +47417,12 @@ async function deliveryOverview(db, projectId, days, now = new Date) {
47413
47417
  return true;
47414
47418
  };
47415
47419
  const events = new Map;
47416
- for (const v of via)
47417
- events.set(v.unit_id, [...events.get(v.unit_id) ?? [], v.event]);
47420
+ for (const v of via) {
47421
+ const name = eventName(v.event, v.reason);
47422
+ const seen = events.get(v.unit_id) ?? [];
47423
+ if (!seen.includes(name))
47424
+ events.set(v.unit_id, [...seen, name].sort());
47425
+ }
47418
47426
  const topLines = [];
47419
47427
  for (const t of top) {
47420
47428
  const line = `- ${head(inline(t.key), DELIVERY_LIMITS.key)} (u${t.id}, ${t.kind}, ${t.lifecycle} now): ${t.sessions} session${Number(t.sessions) === 1 ? "" : "s"}, ${t.deliveries} deliver${Number(t.deliveries) === 1 ? "y" : "ies"}, via ${(events.get(t.id) ?? []).join(", ")}; named later in ${namedIn.get(t.id) ?? 0} of those sessions`;
@@ -47463,7 +47471,7 @@ async function deliveryOverview(db, projectId, days, now = new Date) {
47463
47471
  function countTable(groups) {
47464
47472
  const rows = new Map;
47465
47473
  for (const g of groups) {
47466
- const id = `${g.event}\x00${g.outcome}`;
47474
+ const id = `${eventName(g.event, g.reason)}\x00${g.outcome}`;
47467
47475
  const row = rows.get(id) ?? { by: new Map, keyless: 0, left: 0 };
47468
47476
  const w = who(Boolean(Number(g.named)), g.event, g.reason);
47469
47477
  const n = Number(g.n);
@@ -47490,7 +47498,7 @@ function deliveryLine(d, units, namedLater) {
47490
47498
  const agent = w === "subagent" && d.agent_id ? ` ${head(inline(d.agent_id), DELIVERY_LIMITS.agent)}` : "";
47491
47499
  const named = units.slice(0, DELIVERY_LIMITS.keys).map((u) => `${head(inline(u.key), DELIVERY_LIMITS.key)} (u${u.id}${namedLater(u.key) ? ", named later" : ""})`).join(", ");
47492
47500
  const more = units.length > DELIVERY_LIMITS.keys ? ` (+${units.length - DELIVERY_LIMITS.keys} more)` : "";
47493
- return `- ${d.at} ${d.event}, ${w}${agent}${d.path ? ` ${head(inline(d.path), DELIVERY_LIMITS.path)}` : ""}: ${named}${more}`;
47501
+ return `- ${d.at} ${eventName(d.event, d.reason)}, ${w}${agent}${d.path ? ` ${head(inline(d.path), DELIVERY_LIMITS.path)}` : ""}: ${named}${more}`;
47494
47502
  }
47495
47503
 
47496
47504
  // server/src/export.ts
@@ -47514,7 +47522,7 @@ async function unitView(db, projectId, ref, root, asOf, renames) {
47514
47522
  }
47515
47523
  var RENAME_LOOKUPS = 5;
47516
47524
  async function describe3(db, u, root, asOf, renames) {
47517
- const [options, evidence, adoption, anchors, links, states, fields] = await Promise.all([
47525
+ const [options, evidence, adoption, anchors, links, states, fields, commands] = await Promise.all([
47518
47526
  db.selectFrom("unit_option").select(["id", "text", "outcome", "why", "reconsider_when"]).where("unit_id", "=", u.id).orderBy("position").execute(),
47519
47527
  db.selectFrom("unit_evidence as e").innerJoin("source as s", "s.id", "e.source_id").where("e.unit_id", "=", u.id).where("e.added_at", "<=", asOf ?? "9999").select([
47520
47528
  "e.option_id",
@@ -47589,7 +47597,8 @@ async function describe3(db, u, root, asOf, renames) {
47589
47597
  "s.author_association",
47590
47598
  "s.created_at",
47591
47599
  "s.text"
47592
- ]).orderBy("f.id").execute()
47600
+ ]).orderBy("f.id").execute(),
47601
+ db.selectFrom("unit_command").select("command").where("unit_id", "=", u.id).where("added_at", "<=", asOf ?? "9999").orderBy("id").execute()
47593
47602
  ]);
47594
47603
  let lifecycle = u.lifecycle;
47595
47604
  let history = states;
@@ -47659,6 +47668,11 @@ async function describe3(db, u, root, asOf, renames) {
47659
47668
  out.push(` - ${where} (${a.role}${a.commit_sha ? `, commit ${a.commit_sha.slice(0, 12)}` : ""}): ${c.state}${c.line ? ` at line ${c.line}` : ""}${c.state === "missing" ? ` — needs review: the code it points at is gone${moved}` : ""}`);
47660
47669
  }
47661
47670
  }
47671
+ if (commands.length) {
47672
+ out.push("Commands (the first call in a conversation that runs one, word for word on one line, is stopped with this dead end as the reason, unless the conversation has already seen it or been stopped 3 times):");
47673
+ for (const c of commands)
47674
+ out.push(` - ${inline(c.command)}`);
47675
+ }
47662
47676
  const retired = anchors.filter((a) => a.retired_at);
47663
47677
  if (retired.length) {
47664
47678
  out.push("Retired anchors (they no longer count for delivery; a live anchor on the same path still does; kept with the words that retired them):");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sphica",
3
- "version": "0.6.58",
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
  "license": "MIT",
6
6
  "type": "module",
@@ -66,7 +66,7 @@ and only by saying so: "we rejected yarn", "let's keep SQLite". check refuses th
66
66
  - Options someone proposed and a maintainer declined, with the reason given: a `decision` whose rejected option carries its `why` and evidence
67
67
  - What the pull request implemented: an `implementation` citing the commit message or the body, with an `evidence` anchor when a path and symbol are named (a `symbol` that is a key or a value Sphica masks is dropped, keeping the path)
68
68
  - The problem the closed issue describes, when it states a rule ("exports must never include private notes"): a `constraint` citing the issue body
69
- - Review findings that led to a change (`finding`), paths tried and abandoned (`dead_end`), questions left open (`question`)
69
+ - Review findings that led to a change (`finding`), paths tried and abandoned (`dead_end`), questions left open (`question`). Write a dead end as the trace Skill says: a lesson with its condition, the cause and the way around it only as the sources state them, and `commands` when it is about a command
70
70
 
71
71
  Do not record the list of changes (git has it), approvals, or thanks. If the pull request decided nothing, save `"units": []` and say so.
72
72
  Write text in the language the owner writes in the pull request's sources (English when they wrote none there), and give every record Japanese and English `aliases`.
@@ -109,11 +109,12 @@ The `"..."` stands for the other language's words: in this example, `"データ
109
109
  | `key` | A short meaningful word (lowercase letters, digits, `. _ -`). Saved as `trace:<session>/<key>`. A key is never reused: records are never rewritten |
110
110
  | `kind` | `decision`, `constraint` (what must hold), `implementation` (what was built), `finding`, `dead_end` (a path tried that failed, and why), `question` |
111
111
  | `stance` | Decisions and constraints only: `do`, `dont`, or `defer`. A deferral may add `revisit_when` |
112
- | `text`, `why`, `scope_note` | In the conversation's language. `text` states the record in one sentence; `why` is the reason given, not one you infer |
112
+ | `text`, `why`, `scope_note` | In the conversation's language. `text` states the record in one sentence; `why` is the reason given, not one you infer. A dead end's `text` is a lesson another task can use: what fails, under which condition (tool, version, environment), and the cause and the way around it only when the conversation says them. Leave the specifics to the quote, the anchors, and `commands` |
113
113
  | `evidence` | Required. `source` is a ref from context, `quote` is copied **exactly** from that message (a phrase is enough). `role`: `states`, `proposes`, `rejects`, `explains`, `implements`, `decides` (the AI's reply deciding it; see below). When the owner reports what someone else said, add `reported_speaker` |
114
114
  | `options` | Options compared, with `outcome` `chosen` / `rejected` / `deferred` / `proposed` and the `why` given. Evidence is optional per option. A rejected option may add `reconsider_when` (when it would be worth looking at again) with `reconsider_quote` (`source`, `quote`): **only a condition the owner stated, quoting the owner's words**. Never infer one, and never take it from the AI's suggestion or from someone else's words the owner passes on (a `>` line, a code block, or words wholly inside quotation marks refuse the save). A `reconsider_quote` not found in the message refuses the save (unlike other quotes, which quarantine the record) |
115
115
  | `adoption` | Decisions and constraints only: the words that settle it. The owner's message adopts it as the owner's decision. The AI's own reply adopts it as an AI's decision only under the rules below. The AI proposing something and the owner not objecting is not adoption; leave it out and the record stays a candidate. Words the owner quoted (`>` lines), pasted in a code block, or put wholly inside quotation marks on a line (straight or curly quotes, Japanese corner brackets, backticks) are someone else's and never adopt, and neither do words that stand right between two such marks or apostrophes: quote more of the owner's own words around them. Check reads where the words sit, not what they mean |
116
116
  | `anchors` | Only where the record has a code location: `path` relative to the repository root, `symbol` when there is one, `role` `applies_to` (where it applies) or `evidence` (code that shows it was done; add `commit` when known). When an adopted decision or constraint governs how one existing code location behaves (keeping it as it is included), give it `applies_to` there, even if this work did not change it: delivery shows it when that file is read or edited. Confirm the path in the repository; do not infer one from a broad topic, and leave it unanchored when several places are plausible. `no_code_surface` may say why there is none. A `symbol` must be a name in the code, never a key or a value Sphica masks: such a symbol is dropped and the anchor keeps only its path (save reports it) |
117
+ | `commands` | Dead ends only, up to 5: a command the dead end is about, as typed, cut to the shortest part that still names the failing use (the program and the flag or option, such as `pnpm test --watch`). The first call in a later conversation that runs it, word for word on one line, is stopped once and shown the dead end. Never a bare program name, a command in quotes, two commands joined with `;`, `\|`, or `&`, or one holding a secret |
117
118
  | `aliases` | 8 to 12 short search words in **both Japanese and English** a later reader might type: synonyms, the other language's words, abbreviations. Search only; never evidence. Not broad words that match everything (`code`, `fix`, `update`) |
118
119
  | `supersedes` | The key of a live record this one replaces (context lists them). The old one is marked superseded, never deleted |
119
120
  | `conflicts` | Keys of live records this one contradicts without replacing them. Until resolved, both are held back from automatic injection, except the owner's decision, which only another record the owner adopted holds back |
@@ -124,7 +125,7 @@ The `"..."` stands for the other language's words: in this example, `"データ
124
125
 
125
126
  A field value that breaks these rules refuses the whole save, like a `reconsider_quote` not found: fix it or leave the field out.
126
127
 
127
- When check or save refuses `answers` as an unknown key, a `work` list as not an object, or a work item whose key is already there for leaving
128
+ When check or save refuses `answers` or `commands` as an unknown key, a `work` list as not an object, or a work item whose key is already there for leaving
128
129
  out a field, the record server is older than this Skill. Do not drop them and save without: ask the owner to reload it (`/reload-plugins` in Claude Code; reopen Codex), then
129
130
  begin again, read context, and save.
130
131