@north-light/cli 0.3.414 → 0.3.415

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.
Files changed (88) hide show
  1. package/dist/api/client.d.ts +20 -0
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/dto/common.d.ts +1 -1
  4. package/dist/api/dto/crons.d.ts +7 -1
  5. package/dist/api/dto/human-requests.d.ts +1 -1
  6. package/dist/api/dto/run-events.d.ts +1 -1
  7. package/dist/api/dto/usage.d.ts +27 -0
  8. package/dist/api/dto/usage.js +0 -0
  9. package/dist/api/errors.js +1 -1
  10. package/dist/api/index.d.ts +3 -2
  11. package/dist/api/index.js +1 -1
  12. package/dist/builtin-memory/crouter-sdk/README.md +22 -4
  13. package/dist/builtin-memory/crouter-sdk/client.md +32 -1
  14. package/dist/builtin-memory/crouter-sdk/errors.md +3 -0
  15. package/dist/builtin-memory/crouter-sdk/getting-started.md +26 -4
  16. package/dist/builtin-memory/crouter-sdk/release-notes.md +23 -0
  17. package/dist/builtin-memory/crouter-sdk/testing.md +9 -3
  18. package/dist/builtin-memory/internal/nodes-and-canvas.md +4 -0
  19. package/dist/clients/attach/viewer.js +606 -606
  20. package/dist/commands/cron.js +1 -1
  21. package/dist/commands/node/create.js +1 -1
  22. package/dist/core/canvas/crons.d.ts +15 -1
  23. package/dist/core/canvas/crons.js +13 -13
  24. package/dist/core/canvas/delivery-contract.d.ts +1 -1
  25. package/dist/core/canvas/migrations.js +73 -66
  26. package/dist/core/canvas/types.d.ts +1 -1
  27. package/dist/core/command.d.ts +7 -0
  28. package/dist/core/command.js +9 -9
  29. package/dist/core/grants/mirror.d.ts +4 -0
  30. package/dist/core/grants/mirror.js +2 -2
  31. package/dist/core/layout.d.ts +2 -0
  32. package/dist/core/layout.js +2 -2
  33. package/dist/core/llm/run.d.ts +5 -1
  34. package/dist/core/llm/run.js +3 -3
  35. package/dist/core/providers/call.d.ts +2 -0
  36. package/dist/core/providers/call.js +1 -1
  37. package/dist/core/providers/errors.js +1 -1
  38. package/dist/core/providers/receipts.d.ts +2 -0
  39. package/dist/core/providers/receipts.js +2 -3
  40. package/dist/core/runs/operations.d.ts +2 -0
  41. package/dist/core/runs/operations.js +4 -4
  42. package/dist/core/runtime/broker/model-adapter.js +2 -2
  43. package/dist/core/runtime/run-command.d.ts +6 -0
  44. package/dist/core/runtime/run-command.js +1 -1
  45. package/dist/core/spaces/mounts.d.ts +2 -0
  46. package/dist/core/spaces/mounts.js +1 -1
  47. package/dist/core/spaces/process.d.ts +14 -2
  48. package/dist/core/spaces/process.js +1 -1
  49. package/dist/core/usage/ledger.d.ts +49 -0
  50. package/dist/core/usage/ledger.js +10 -0
  51. package/dist/daemon/api/app-listener.js +12 -12
  52. package/dist/daemon/api/handlers/crons.js +1 -1
  53. package/dist/daemon/api/handlers/llm.d.ts +8 -0
  54. package/dist/daemon/api/handlers/llm.js +3 -3
  55. package/dist/daemon/api/map.d.ts +1 -1
  56. package/dist/daemon/api/map.js +1 -1
  57. package/dist/daemon/api/operations.js +1 -1
  58. package/dist/daemon/cron/armed-context.d.ts +21 -4
  59. package/dist/daemon/cron/armed-context.js +1 -1
  60. package/dist/daemon/cron/authority.d.ts +27 -0
  61. package/dist/daemon/cron/authority.js +1 -0
  62. package/dist/daemon/cron/disposition.d.ts +2 -0
  63. package/dist/daemon/cron/disposition.js +1 -1
  64. package/dist/daemon/cron/escalation.js +3 -3
  65. package/dist/daemon/cron/folders.d.ts +5 -0
  66. package/dist/daemon/cron/folders.js +1 -0
  67. package/dist/daemon/cron/lease-recovery.js +1 -1
  68. package/dist/daemon/cron/settle.d.ts +10 -0
  69. package/dist/daemon/cron/settle.js +1 -1
  70. package/dist/daemon/cron/sinks.d.ts +2 -1
  71. package/dist/daemon/cron/sinks.js +2 -2
  72. package/dist/daemon/cron-run.js +1 -1
  73. package/dist/daemon/reconcilers/action-lane.js +1 -1
  74. package/dist/daemon/reconcilers/broker-supervision.d.ts +10 -0
  75. package/dist/daemon/reconcilers/broker-supervision.js +4 -4
  76. package/dist/daemon/reconcilers/cron-lane.d.ts +1 -0
  77. package/dist/daemon/reconcilers/cron-lane.js +1 -1
  78. package/docs/sdk/README.md +22 -4
  79. package/docs/sdk/client.md +32 -1
  80. package/docs/sdk/errors.md +3 -0
  81. package/docs/sdk/getting-started.md +26 -4
  82. package/docs/sdk/release-notes.md +23 -0
  83. package/docs/sdk/testing.md +9 -3
  84. package/package.json +2 -2
  85. package/packages/crouter-identity/dist/index.d.ts +29 -2
  86. package/packages/crouter-identity/dist/index.js +81 -12
  87. package/packages/crouter-identity/package.json +1 -1
  88. package/runtime.lock.json +12 -12
@@ -1,4 +1,4 @@
1
- var re=Object.defineProperty;var E=(e,t)=>re(e,"name",{value:t,configurable:!0});import{randomBytes as P}from"node:crypto";import{parseScope as ae}from"@north-light/identity";import{importNodeSqlAuthority as de,recreateNodeRowsView as _e}from"./node-sql-migration.js";import{migrateRecoveryWitnesses as Ne}from"./recovery.js";import{migrateMessagingState as ce}from"./deliveries.js";import{migrateHumanRequestsState as Le}from"../human/requests.js";import{existsSync as I,readFileSync as k,readdirSync as M,realpathSync as le,statSync as ue}from"node:fs";import{basename as pe,join as H,resolve as Y}from"node:path";import{isSafeNodeId as Re,nodesRoot as y,nodeMetaPath as v}from"./paths.js";import{convertLegacyEdges as Ae}from"../../migrations/004-canvas-documents/legacy-edges.js";import{customExtensionPaths as Oe}from"./extensions.js";import{readMetaObject as K,updateJsonFileDurably as q,withMetaLock as Ie,writeMetaObjectLocked as me}from"./meta-file.js";function Xe(e){e.exec(`
1
+ var ae=Object.defineProperty;var o=(e,t)=>ae(e,"name",{value:t,configurable:!0});import{randomBytes as P}from"node:crypto";import{parseScope as Te}from"@north-light/identity";import{importNodeSqlAuthority as de,recreateNodeRowsView as _e}from"./node-sql-migration.js";import{migrateRecoveryWitnesses as ce}from"./recovery.js";import{migrateMessagingState as Ne}from"./deliveries.js";import{migrateHumanRequestsState as Le}from"../human/requests.js";import{existsSync as U,readFileSync as M,readdirSync as k,realpathSync as le,statSync as ue}from"node:fs";import{basename as pe,join as j,resolve as Y}from"node:path";import{appSpace as Re}from"../layout.js";import{emitEvent as Ae}from"../events/emit.js";import{isSafeNodeId as Oe,nodesRoot as h,nodeMetaPath as x}from"./paths.js";import{convertLegacyEdges as me}from"../../migrations/004-canvas-documents/legacy-edges.js";import{customExtensionPaths as Ie}from"./extensions.js";import{readMetaObject as K,updateJsonFileDurably as q,withMetaLock as fe,writeMetaObjectLocked as Xe}from"./meta-file.js";function Ue(e){e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS nodes (
3
3
  node_id TEXT PRIMARY KEY,
4
4
  name TEXT NOT NULL,
@@ -23,7 +23,7 @@ CREATE TABLE IF NOT EXISTS edges (
23
23
  CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(type, to_id);
24
24
  CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(type, from_id);
25
25
  CREATE INDEX IF NOT EXISTS idx_nodes_status ON nodes(status);
26
- `)}E(Xe,"baselineSchema");function B(e,t){return new Set(e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name))}E(B,"tableColumns");function $(e,t,n,o){t.has(n)||(e.exec(o),t.add(n))}E($,"addColumnIfMissing");function u(e){return B(e,"nodes")}E(u,"nodeColumns");const a=$;function fe(e){const t=u(e);a(e,t,"intent","ALTER TABLE nodes ADD COLUMN intent TEXT;"),a(e,t,"pi_pid","ALTER TABLE nodes ADD COLUMN pi_pid INTEGER;"),a(e,t,"window","ALTER TABLE nodes ADD COLUMN window TEXT;"),a(e,t,"tmux_session","ALTER TABLE nodes ADD COLUMN tmux_session TEXT;")}E(fe,"addRuntimeColumns");function Ce(e){const t=y();if(!I(t))return;const n=e.prepare('UPDATE nodes SET intent = ?, pi_pid = ?, "window" = ?, tmux_session = ? WHERE node_id = ?');for(const o of M(t)){const s=v(o);if(!I(s))continue;let i;try{i=JSON.parse(k(s,"utf8"))}catch{continue}n.run(i.intent??null,i.pi_pid??null,i.window??null,i.tmux_session??null,o)}}E(Ce,"backfillRuntime");function Ue(e){b(e,3,()=>{if(!(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'edges'").get()!==void 0)){e.exec(`
26
+ `)}o(Ue,"baselineSchema");function b(e,t){return new Set(e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name))}o(b,"tableColumns");function $(e,t,n,E){t.has(n)||(e.exec(E),t.add(n))}o($,"addColumnIfMissing");function m(e){return b(e,"nodes")}o(m,"nodeColumns");const N=$;function Ce(e){const t=m(e);N(e,t,"intent","ALTER TABLE nodes ADD COLUMN intent TEXT;"),N(e,t,"pi_pid","ALTER TABLE nodes ADD COLUMN pi_pid INTEGER;"),N(e,t,"window","ALTER TABLE nodes ADD COLUMN window TEXT;"),N(e,t,"tmux_session","ALTER TABLE nodes ADD COLUMN tmux_session TEXT;")}o(Ce,"addRuntimeColumns");function Se(e){const t=h();if(!U(t))return;const n=e.prepare('UPDATE nodes SET intent = ?, pi_pid = ?, "window" = ?, tmux_session = ? WHERE node_id = ?');for(const E of k(t)){const a=x(E);if(!U(a))continue;let i;try{i=JSON.parse(M(a,"utf8"))}catch{continue}n.run(i.intent??null,i.pi_pid??null,i.window??null,i.tmux_session??null,E)}}o(Se,"backfillRuntime");function ge(e){B(e,3,()=>{if(!(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'edges'").get()!==void 0)){e.exec(`
27
27
  CREATE TABLE edges (
28
28
  type TEXT NOT NULL,
29
29
  from_id TEXT NOT NULL,
@@ -57,14 +57,14 @@ DROP TABLE edges;
57
57
  ALTER TABLE edges_new RENAME TO edges;
58
58
  CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(type, to_id);
59
59
  CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(type, from_id);
60
- `);const o=e.prepare("SELECT COUNT(*) AS n FROM edges").get().n;if(o!==n)throw new Error(`edges FK rebuild lost rows: expected ${n} non-orphan edge(s), got ${o}`);const s=e.prepare("PRAGMA foreign_key_check").all();if(s.length>0)throw new Error(`edges FK rebuild left ${s.length} foreign-key violation(s)`)})}E(Ue,"edgesForeignKeyCascade");function Se(e){const t=u(e);a(e,t,"pane","ALTER TABLE nodes ADD COLUMN pane TEXT;")}E(Se,"addPaneColumn");function De(e){e.exec(`
60
+ `);const E=e.prepare("SELECT COUNT(*) AS n FROM edges").get().n;if(E!==n)throw new Error(`edges FK rebuild lost rows: expected ${n} non-orphan edge(s), got ${E}`);const a=e.prepare("PRAGMA foreign_key_check").all();if(a.length>0)throw new Error(`edges FK rebuild left ${a.length} foreign-key violation(s)`)})}o(ge,"edgesForeignKeyCascade");function De(e){const t=m(e);N(e,t,"pane","ALTER TABLE nodes ADD COLUMN pane TEXT;")}o(De,"addPaneColumn");function ve(e){e.exec(`
61
61
  CREATE TABLE IF NOT EXISTS focuses (
62
62
  focus_id TEXT PRIMARY KEY, -- stable internal id for the viewport
63
63
  pane TEXT, -- the durable %pane_id realizing the focus
64
64
  session TEXT, -- derived cache of the user session (reconciled from pane)
65
65
  node_id TEXT NOT NULL UNIQUE -- the node shown; UNIQUE \u2192 a node occupies <=1 focus
66
66
  );
67
- `)}E(De,"addFocusesTable");function ge(e){e.exec(`
67
+ `)}o(ve,"addFocusesTable");function we(e){e.exec(`
68
68
  CREATE TABLE IF NOT EXISTS wakeups (
69
69
  wakeup_id TEXT PRIMARY KEY,
70
70
  node_id TEXT, -- TARGET + node-anchored cancel anchor; NULL = canvas-detached
@@ -80,7 +80,7 @@ CREATE INDEX IF NOT EXISTS idx_wakeups_fire ON wakeups(fire_at);
80
80
  CREATE INDEX IF NOT EXISTS idx_wakeups_node ON wakeups(node_id); -- by-node cancel / list
81
81
  CREATE INDEX IF NOT EXISTS idx_wakeups_owner ON wakeups(owner_id); -- by-owner reap (ruling A)
82
82
  CREATE UNIQUE INDEX IF NOT EXISTS idx_wakeups_deadline ON wakeups(node_id) WHERE kind = 'deadline';
83
- `)}E(ge,"appendWakeupsTable");function we(e){e.exec(`
83
+ `)}o(we,"appendWakeupsTable");function ye(e){e.exec(`
84
84
  CREATE TABLE IF NOT EXISTS triggers (
85
85
  trigger_id TEXT PRIMARY KEY,
86
86
  owner_id TEXT NOT NULL,
@@ -131,12 +131,12 @@ SELECT
131
131
  FROM wakeups;
132
132
 
133
133
  DROP TABLE wakeups;
134
- `)}E(we,"migrateWakeupsToTriggers");function ye(e){const t=u(e);a(e,t,"host_kind","ALTER TABLE nodes ADD COLUMN host_kind TEXT;")}E(ye,"addHostKindColumn");function ve(e){e.exec(`
134
+ `)}o(ye,"migrateWakeupsToTriggers");function he(e){const t=m(e);N(e,t,"host_kind","ALTER TABLE nodes ADD COLUMN host_kind TEXT;")}o(he,"addHostKindColumn");function xe(e){e.exec(`
135
135
  CREATE TABLE IF NOT EXISTS canvas_meta (
136
136
  key TEXT PRIMARY KEY,
137
137
  value TEXT NOT NULL
138
138
  );
139
- `)}E(ve,"addCanvasMetaTable");function he(e){const t=u(e);a(e,t,"profile_id","ALTER TABLE nodes ADD COLUMN profile_id TEXT;")}E(he,"addProfileIdColumn");function xe(e){const t=u(e);a(e,t,"pi_pid_identity","ALTER TABLE nodes ADD COLUMN pi_pid_identity TEXT;")}E(xe,"addPidIdentityColumn");function Fe(e){const t=u(e);a(e,t,"waiting_for","ALTER TABLE nodes ADD COLUMN waiting_for TEXT;")}E(Fe,"addMessageWaitColumn");function J(e){const t=u(e);if(t.size===0)return;a(e,t,"final_report","ALTER TABLE nodes ADD COLUMN final_report TEXT;"),a(e,t,"finalized_at","ALTER TABLE nodes ADD COLUMN finalized_at TEXT;");const n=e.prepare("SELECT node_id FROM nodes WHERE status = 'done' AND final_report IS NULL").all(),o=e.prepare("UPDATE nodes SET final_report = ?, finalized_at = ? WHERE node_id = ? AND final_report IS NULL");for(const{node_id:s}of n){const i=H(y(),s,"reports");if(!I(i))continue;let T=null;for(const d of M(i))if(d.endsWith(".md"))try{const _=k(H(i,d),"utf8"),N=/^---\nnode: [^\n]+\nkind: final\nts: ([^\n]+)\n---\n/.exec(_);if(N===null||Number.isNaN(Date.parse(N[1])))continue;const c={name:d,ts:N[1]};(T===null||c.ts>T.ts||c.ts===T.ts&&c.name>T.name)&&(T=c)}catch{}T!==null&&o.run(T.name,T.ts,s)}}E(J,"addCanonicalFinalColumns");function ke(e){const t=y();if(I(t))for(const n of M(t)){const o=v(n);I(o)&&q(o,s=>{const i=s.launch;if(typeof i!="object"||i===null||Array.isArray(i))return!1;const T=i.extensions;if(!Array.isArray(T)||!T.every(_=>typeof _=="string"))return!1;const d=Oe(T);return d.length===T.length?!1:(i.extensions=d,!0)})}}E(ke,"normalizePersistedLaunchExtensions");function Me(e){const t=u(e);a(e,t,"waiting_for_generation","ALTER TABLE nodes ADD COLUMN waiting_for_generation INTEGER NOT NULL DEFAULT 0;")}E(Me,"addMessageWaitGenerationColumn");function je(e){e.exec(`
139
+ `)}o(xe,"addCanvasMetaTable");function Fe(e){const t=m(e);N(e,t,"profile_id","ALTER TABLE nodes ADD COLUMN profile_id TEXT;")}o(Fe,"addProfileIdColumn");function Me(e){const t=m(e);N(e,t,"pi_pid_identity","ALTER TABLE nodes ADD COLUMN pi_pid_identity TEXT;")}o(Me,"addPidIdentityColumn");function ke(e){const t=m(e);N(e,t,"waiting_for","ALTER TABLE nodes ADD COLUMN waiting_for TEXT;")}o(ke,"addMessageWaitColumn");function J(e){const t=m(e);if(t.size===0)return;N(e,t,"final_report","ALTER TABLE nodes ADD COLUMN final_report TEXT;"),N(e,t,"finalized_at","ALTER TABLE nodes ADD COLUMN finalized_at TEXT;");const n=e.prepare("SELECT node_id FROM nodes WHERE status = 'done' AND final_report IS NULL").all(),E=e.prepare("UPDATE nodes SET final_report = ?, finalized_at = ? WHERE node_id = ? AND final_report IS NULL");for(const{node_id:a}of n){const i=j(h(),a,"reports");if(!U(i))continue;let T=null;for(const c of k(i))if(c.endsWith(".md"))try{const L=M(j(i,c),"utf8"),l=/^---\nnode: [^\n]+\nkind: final\nts: ([^\n]+)\n---\n/.exec(L);if(l===null||Number.isNaN(Date.parse(l[1])))continue;const r={name:c,ts:l[1]};(T===null||r.ts>T.ts||r.ts===T.ts&&r.name>T.name)&&(T=r)}catch{}T!==null&&E.run(T.name,T.ts,a)}}o(J,"addCanonicalFinalColumns");function je(e){const t=h();if(U(t))for(const n of k(t)){const E=x(n);U(E)&&q(E,a=>{const i=a.launch;if(typeof i!="object"||i===null||Array.isArray(i))return!1;const T=i.extensions;if(!Array.isArray(T)||!T.every(L=>typeof L=="string"))return!1;const c=Ie(T);return c.length===T.length?!1:(i.extensions=c,!0)})}}o(je,"normalizePersistedLaunchExtensions");function He(e){const t=m(e);N(e,t,"waiting_for_generation","ALTER TABLE nodes ADD COLUMN waiting_for_generation INTEGER NOT NULL DEFAULT 0;")}o(He,"addMessageWaitGenerationColumn");function Ge(e){e.exec(`
140
140
  CREATE TABLE IF NOT EXISTS consult_outbox (
141
141
  node_id TEXT PRIMARY KEY, -- legacy work node id
142
142
  dir TEXT NOT NULL, -- legacy ticket directory
@@ -150,15 +150,15 @@ CREATE INDEX IF NOT EXISTS idx_consult_outbox_status ON consult_outbox(status);
150
150
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_dir ON consult_outbox(dir);
151
151
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_dir_request_status ON consult_outbox(dir, request_id, status);
152
152
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_dir_status ON consult_outbox(dir, status);
153
- `)}E(je,"addHumanWorkOutboxTable");function Ge(e){const t=B(e,"consult_outbox"),n=E((o,s)=>$(e,t,o,s),"add");n("work_kind","ALTER TABLE consult_outbox ADD COLUMN work_kind TEXT NOT NULL DEFAULT 'follow_up';"),n("interaction_id","ALTER TABLE consult_outbox ADD COLUMN interaction_id TEXT;"),n("generation_id","ALTER TABLE consult_outbox ADD COLUMN generation_id TEXT;"),n("interaction_snapshot","ALTER TABLE consult_outbox ADD COLUMN interaction_snapshot TEXT;"),n("handler_command","ALTER TABLE consult_outbox ADD COLUMN handler_command TEXT;"),n("handler_args_json","ALTER TABLE consult_outbox ADD COLUMN handler_args_json TEXT;"),n("claim_token","ALTER TABLE consult_outbox ADD COLUMN claim_token TEXT;"),e.exec(`
153
+ `)}o(Ge,"addHumanWorkOutboxTable");function be(e){const t=b(e,"consult_outbox"),n=o((E,a)=>$(e,t,E,a),"add");n("work_kind","ALTER TABLE consult_outbox ADD COLUMN work_kind TEXT NOT NULL DEFAULT 'follow_up';"),n("interaction_id","ALTER TABLE consult_outbox ADD COLUMN interaction_id TEXT;"),n("generation_id","ALTER TABLE consult_outbox ADD COLUMN generation_id TEXT;"),n("interaction_snapshot","ALTER TABLE consult_outbox ADD COLUMN interaction_snapshot TEXT;"),n("handler_command","ALTER TABLE consult_outbox ADD COLUMN handler_command TEXT;"),n("handler_args_json","ALTER TABLE consult_outbox ADD COLUMN handler_args_json TEXT;"),n("claim_token","ALTER TABLE consult_outbox ADD COLUMN claim_token TEXT;"),e.exec(`
154
154
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_status ON consult_outbox(work_kind, status);
155
155
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_dir_status ON consult_outbox(dir, work_kind, status);
156
156
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_request_status ON consult_outbox(dir, request_id, work_kind, status);
157
157
  CREATE UNIQUE INDEX IF NOT EXISTS idx_consult_outbox_visual_request ON consult_outbox(dir, request_id, work_kind) WHERE work_kind = 'visual';
158
- `)}E(Ge,"addHumanWorkColumns");function He(e){e.exec(`
158
+ `)}o(be,"addHumanWorkColumns");function Be(e){e.exec(`
159
159
  CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent);
160
160
  CREATE INDEX IF NOT EXISTS idx_nodes_created ON nodes(created);
161
- `)}E(He,"addNodeParentCreatedIndexes");function Be(e){e.exec(`
161
+ `)}o(Be,"addNodeParentCreatedIndexes");function We(e){e.exec(`
162
162
  CREATE TABLE IF NOT EXISTS crons (
163
163
  cron_id TEXT PRIMARY KEY,
164
164
  name TEXT NOT NULL, -- agent-legible label; how it shows in list
@@ -213,38 +213,38 @@ CREATE TABLE IF NOT EXISTS cron_runs ( -- bounded ring, last 20 p
213
213
  FOREIGN KEY (cron_id) REFERENCES crons(cron_id) ON DELETE CASCADE
214
214
  );
215
215
  CREATE INDEX IF NOT EXISTS idx_cron_runs_cron ON cron_runs(cron_id, started);
216
- `)}E(Be,"addCronsTables");function U(e){return`'${e.replace(/'/g,`'"'"'`)}'`}E(U,"shellSingleQuote");function be(e,t){let n=0;for(;;){const o=`${t}_${n}`;if(!e.split(`
217
- `).includes(o))return o;n++}}E(be,"uniqueHeredocDelimiter");function Q(e,t,n){const o=be(t,n);return`${e} <<'${o}'
216
+ `)}o(We,"addCronsTables");function D(e){return`'${e.replace(/'/g,`'"'"'`)}'`}o(D,"shellSingleQuote");function Pe(e,t){let n=0;for(;;){const E=`${t}_${n}`;if(!e.split(`
217
+ `).includes(E))return E;n++}}o(Pe,"uniqueHeredocDelimiter");function Q(e,t,n){const E=Pe(t,n);return`${e} <<'${E}'
218
218
  ${t}
219
- ${o}`}E(Q,"heredocCommand");function We(e){if(typeof e!="string")return{};try{const t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?{}:t}catch{return{}}}E(We,"migrationPayload");function A(e,t,n){const o=e[t];if(typeof o!="string"||o.trim()==="")throw new Error(`trigger ${n} payload requires non-empty ${t}`);return o}E(A,"requiredString");function j(e,t){const n=e[t];return typeof n=="string"&&n.trim()!==""?n:void 0}E(j,"optionalString");function S(e,t){const n=e[t];return typeof n=="string"&&n.trim()!==""?n:void 0}E(S,"optionalColumn");function z(e,t,n,o){return Q(`crtr node message send --to ${U(e)} --tier ${U(t)}`,n,`CRTR_MIGRATED_${o.replace(/[^A-Za-z0-9]/g,"_")}`)}E(z,"migratedMessageCommand");function Pe(e,t){return`printf '%s\\n' "$CRTR_GATE_STDOUT" | crtr node message send --to ${U(e)} --tier ${U(t)}`}E(Pe,"migratedGateStdoutMessageCommand");function Ye(e,t){const n=[`crtr node new --kind ${U(A(e,"kind",t))}`],o=[["mode","mode"],["cwd","cwd"],["name","name"],["parent","parent"],["worktreeBase","worktree"],["forkFrom","fork-from"],["model","model"],["profile","profile"],["situationalContext","situational-context"]];for(const[i,T]of o){const d=j(e,i);d!==void 0&&n.push(`--${T} ${U(d)}`)}e.root===!0&&n.push("--root");const s=A(e,"prompt",t);return Q(n.join(" "),s,`CRTR_MIGRATED_${t.replace(/[^A-Za-z0-9]/g,"_")}`)}E(Ye,"migratedSpawnCommand");const V="migration.v22.skipped";function Ke(e){const t=e.prepare("SELECT cwd FROM nodes WHERE parent IS NULL ORDER BY created LIMIT 1").get();return(t!==void 0?S(t,"cwd"):void 0)??process.cwd()}E(Ke,"ambientMigrationCwd");function qe(e){let t;try{t=e.prepare("SELECT eval_pid FROM triggers WHERE eval_state = 'running' AND eval_pid IS NOT NULL").all()}catch{return}for(const n of t){const o=n.eval_pid;if(!(typeof o!="number"||!Number.isInteger(o)||o<=1))try{process.kill(-o,"SIGTERM")}catch{}}}E(qe,"reapRunningPredicateEvaluations");function $e(e){const t=[],n=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'triggers'").get()!==void 0;n&&qe(e);let o=[];if(n)try{o=e.prepare("SELECT * FROM triggers ORDER BY created, trigger_id").all()}catch(T){t.push({trigger_id:"<unreadable table>",reason:`triggers table could not be read: ${T instanceof Error?T.message:String(T)}`})}const s=Ke(e),i=e.prepare(`
219
+ ${E}`}o(Q,"heredocCommand");function Ye(e){if(typeof e!="string")return{};try{const t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?{}:t}catch{return{}}}o(Ye,"migrationPayload");function X(e,t,n){const E=e[t];if(typeof E!="string"||E.trim()==="")throw new Error(`trigger ${n} payload requires non-empty ${t}`);return E}o(X,"requiredString");function H(e,t){const n=e[t];return typeof n=="string"&&n.trim()!==""?n:void 0}o(H,"optionalString");function v(e,t){const n=e[t];return typeof n=="string"&&n.trim()!==""?n:void 0}o(v,"optionalColumn");function z(e,t,n,E){return Q(`crtr node message send --to ${D(e)} --tier ${D(t)}`,n,`CRTR_MIGRATED_${E.replace(/[^A-Za-z0-9]/g,"_")}`)}o(z,"migratedMessageCommand");function Ke(e,t){return`printf '%s\\n' "$CRTR_GATE_STDOUT" | crtr node message send --to ${D(e)} --tier ${D(t)}`}o(Ke,"migratedGateStdoutMessageCommand");function qe(e,t){const n=[`crtr node new --kind ${D(X(e,"kind",t))}`],E=[["mode","mode"],["cwd","cwd"],["name","name"],["parent","parent"],["worktreeBase","worktree"],["forkFrom","fork-from"],["model","model"],["profile","profile"],["situationalContext","situational-context"]];for(const[i,T]of E){const c=H(e,i);c!==void 0&&n.push(`--${T} ${D(c)}`)}e.root===!0&&n.push("--root");const a=X(e,"prompt",t);return Q(n.join(" "),a,`CRTR_MIGRATED_${t.replace(/[^A-Za-z0-9]/g,"_")}`)}o(qe,"migratedSpawnCommand");const V="migration.v22.skipped";function $e(e){const t=e.prepare("SELECT cwd FROM nodes WHERE parent IS NULL ORDER BY created LIMIT 1").get();return(t!==void 0?v(t,"cwd"):void 0)??process.cwd()}o($e,"ambientMigrationCwd");function Je(e){let t;try{t=e.prepare("SELECT eval_pid FROM triggers WHERE eval_state = 'running' AND eval_pid IS NOT NULL").all()}catch{return}for(const n of t){const E=n.eval_pid;if(!(typeof E!="number"||!Number.isInteger(E)||E<=1))try{process.kill(-E,"SIGTERM")}catch{}}}o(Je,"reapRunningPredicateEvaluations");function Qe(e){const t=[],n=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'triggers'").get()!==void 0;n&&Je(e);let E=[];if(n)try{E=e.prepare("SELECT * FROM triggers ORDER BY created, trigger_id").all()}catch(T){t.push({trigger_id:"<unreadable table>",reason:`triggers table could not be read: ${T instanceof Error?T.message:String(T)}`})}const a=$e(e),i=e.prepare(`
220
220
  INSERT OR REPLACE INTO crons (
221
221
  cron_id, name, created_by, command, fire_at, recur, tz, expires_at,
222
222
  anchor_node, cancel_on_wake, cwd, env_json, profile, scope,
223
223
  run_timeout_s, overlap, on_output, sink, tier, created, updated
224
- ) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, NULL, ?, 'profile', ?, 'skip', 'on-failure', '{}', ?, ?, ?)`);for(const T of o){const d=S(T,"trigger_id");if(d===void 0){t.push({trigger_id:"<unidentified row>",reason:"row carries no trigger_id"});continue}try{Je(e,i,T,d,s)}catch(_){t.push({trigger_id:d,reason:_ instanceof Error?_.message:String(_)})}}t.length>0&&(e.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(V,JSON.stringify(t)),console.warn(`[canvas migration v22] ${t.length} retired schedule(s) could not be converted to crons and were dropped; see canvas_meta['${V}']: `+t.map(T=>`${T.trigger_id} (${T.reason})`).join("; "))),e.exec(`
224
+ ) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, NULL, ?, 'profile', ?, 'skip', 'on-failure', '{}', ?, ?, ?)`);for(const T of E){const c=v(T,"trigger_id");if(c===void 0){t.push({trigger_id:"<unidentified row>",reason:"row carries no trigger_id"});continue}try{ze(e,i,T,c,a)}catch(L){t.push({trigger_id:c,reason:L instanceof Error?L.message:String(L)})}}t.length>0&&(e.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(V,JSON.stringify(t)),console.warn(`[canvas migration v22] ${t.length} retired schedule(s) could not be converted to crons and were dropped; see canvas_meta['${V}']: `+t.map(T=>`${T.trigger_id} (${T.reason})`).join("; "))),e.exec(`
225
225
  DROP INDEX IF EXISTS idx_triggers_fire;
226
226
  DROP INDEX IF EXISTS idx_triggers_node;
227
227
  DROP INDEX IF EXISTS idx_triggers_owner;
228
228
  DROP INDEX IF EXISTS idx_triggers_eval;
229
229
  DROP INDEX IF EXISTS idx_triggers_deadline;
230
230
  DROP TABLE IF EXISTS triggers;
231
- `)}E($e,"migrateTriggersToCrons");function Je(e,t,n,o,s){const i=A(n,"owner_id",o),T=e.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(i),d=(T===void 0?void 0:S(T,"cwd"))??s,_=T===void 0?null:S(T,"profile_id")??null,N=S(n,"node_id")??null,c=A(n,"action",o),L=A(n,"action_mode",o),l=A(n,"trigger_type",o),O=We(n.payload),x=S(n,"created")??new Date().toISOString(),f=L==="deadline_message"?"urgent":j(O,"tier")??"normal",D=j(O,"label");let r,p,F=!1;if(c==="msg"&&(L==="inbox_message"||L==="deadline_message")){if(N===null)throw new Error("has no message target");const R=j(O,"body");R!==void 0?r=z(N,f,R,o):l==="when"?(F=!0,r=Pe(N,f)):r=z(N,f,D??"Scheduled message (no body was recorded when this schedule was armed).",o),p=D??(L==="deadline_message"?"deadline":"scheduled message")}else if(c==="msg"&&L==="fresh_revive"){if(N===null)throw new Error("has no revive target");r=`crtr node lifecycle revive ${U(N)} --fresh`,p=D??"scheduled fresh revive"}else if(c==="new"&&L==="node_birth")r=Ye(O,o),p=j(O,"name")??`scheduled ${A(O,"kind",o)} node`;else throw new Error(`has unsupported action ${c}/${L}`);let C,g,G=null;if(l==="when"){C=A(n,"next_eval_at",o),g=A(n,"eval_every",o),G=S(n,"timeout_at")??null;const R=A(n,"when_script",o);r=`${F?`if ! CRTR_GATE_STDOUT="$(
232
- ${R}
231
+ `)}o(Qe,"migrateTriggersToCrons");function ze(e,t,n,E,a){const i=X(n,"owner_id",E),T=e.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(i),c=(T===void 0?void 0:v(T,"cwd"))??a,L=T===void 0?null:v(T,"profile_id")??null,l=v(n,"node_id")??null,r=X(n,"action",E),_=X(n,"action_mode",E),d=X(n,"trigger_type",E),u=Ye(n.payload),p=v(n,"created")??new Date().toISOString(),O=_==="deadline_message"?"urgent":H(u,"tier")??"normal",R=H(u,"label");let s,A,I=!1;if(r==="msg"&&(_==="inbox_message"||_==="deadline_message")){if(l===null)throw new Error("has no message target");const f=H(u,"body");f!==void 0?s=z(l,O,f,E):d==="when"?(I=!0,s=Ke(l,O)):s=z(l,O,R??"Scheduled message (no body was recorded when this schedule was armed).",E),A=R??(_==="deadline_message"?"deadline":"scheduled message")}else if(r==="msg"&&_==="fresh_revive"){if(l===null)throw new Error("has no revive target");s=`crtr node lifecycle revive ${D(l)} --fresh`,A=R??"scheduled fresh revive"}else if(r==="new"&&_==="node_birth")s=qe(u,E),A=H(u,"name")??`scheduled ${X(u,"kind",E)} node`;else throw new Error(`has unsupported action ${r}/${_}`);let g,w,G=null;if(d==="when"){g=X(n,"next_eval_at",E),w=X(n,"eval_every",E),G=v(n,"timeout_at")??null;const f=X(n,"when_script",E);s=`${I?`if ! CRTR_GATE_STDOUT="$(
232
+ ${f}
233
233
  )"; then`:`if ! (
234
- ${R}
234
+ ${f}
235
235
  ); then`}
236
236
  exit 0
237
237
  fi
238
238
  {
239
- ${r}
240
- } && crtr cron cancel "$CRTR_CRON_ID"`}else if(l==="at"||l==="every"||l==="until")C=A(n,"fire_at",o),g=l==="every"?A(n,"recur",o):null;else throw new Error(`has unknown timing type ${l}`);if(L==="deadline_message"&&N!==null){const R=e.prepare("SELECT cron_id FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1 AND cron_id <> ?").get(N,o);if(R!==void 0)throw new Error(`node ${N} already has a migrated deadline (${String(R.cron_id)}); only one is allowed`)}t.run(o,p,i,r,C,g,G,N,L==="deadline_message"?1:0,d,_,300,f,x,x)}E(Je,"convertTriggerRow");function Qe(e){const t=B(e,"crons");t.size===0||t.has("run_pid_identity")||e.exec("ALTER TABLE crons ADD COLUMN run_pid_identity TEXT;")}E(Qe,"addCronRunPidIdentityColumn");function ze(e){const t=B(e,"crons");t.size!==0&&(t.has("run_out_of_band")||e.exec("ALTER TABLE crons ADD COLUMN run_out_of_band INTEGER NOT NULL DEFAULT 0;"),t.has("queued")&&e.exec("ALTER TABLE crons DROP COLUMN queued;"))}E(ze,"addCronOutOfBandColumn");function Ve(e){e.exec(`
239
+ ${s}
240
+ } && crtr cron cancel "$CRTR_CRON_ID"`}else if(d==="at"||d==="every"||d==="until")g=X(n,"fire_at",E),w=d==="every"?X(n,"recur",E):null;else throw new Error(`has unknown timing type ${d}`);if(_==="deadline_message"&&l!==null){const f=e.prepare("SELECT cron_id FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1 AND cron_id <> ?").get(l,E);if(f!==void 0)throw new Error(`node ${l} already has a migrated deadline (${String(f.cron_id)}); only one is allowed`)}t.run(E,A,i,s,g,w,G,l,_==="deadline_message"?1:0,c,L,300,O,p,p)}o(ze,"convertTriggerRow");function Ve(e){const t=b(e,"crons");t.size===0||t.has("run_pid_identity")||e.exec("ALTER TABLE crons ADD COLUMN run_pid_identity TEXT;")}o(Ve,"addCronRunPidIdentityColumn");function Ze(e){const t=b(e,"crons");t.size!==0&&(t.has("run_out_of_band")||e.exec("ALTER TABLE crons ADD COLUMN run_out_of_band INTEGER NOT NULL DEFAULT 0;"),t.has("queued")&&e.exec("ALTER TABLE crons DROP COLUMN queued;"))}o(Ze,"addCronOutOfBandColumn");function et(e){e.exec(`
241
241
  CREATE TABLE IF NOT EXISTS warm_pool (
242
242
  node_id TEXT PRIMARY KEY REFERENCES nodes(node_id) ON DELETE CASCADE,
243
243
  recipe_key TEXT NOT NULL, -- frozen launch tuple this spare was minted for
244
244
  created TEXT NOT NULL -- ISO 8601, mint time (oldest spare claimed first)
245
245
  );
246
246
  CREATE INDEX IF NOT EXISTS idx_warm_pool_recipe ON warm_pool(recipe_key, created);
247
- `)}E(Ve,"addWarmPoolTable");function Ze(e){const t=e.prepare("SELECT node_id, dir, root, request_id, work_kind, status, final_report, updated_at FROM consult_outbox").all();e.exec(`
247
+ `)}o(et,"addWarmPoolTable");function tt(e){const t=e.prepare("SELECT node_id, dir, root, request_id, work_kind, status, final_report, updated_at FROM consult_outbox").all();e.exec(`
248
248
  CREATE TABLE consult_outbox_new (
249
249
  node_id TEXT PRIMARY KEY,
250
250
  ticket_node_id TEXT NOT NULL,
@@ -256,7 +256,7 @@ CREATE TABLE consult_outbox_new (
256
256
  );
257
257
  `);const n=e.prepare(`
258
258
  INSERT INTO consult_outbox_new (node_id, ticket_node_id, request_id, work_kind, status, final_report, updated_at)
259
- VALUES (?, ?, ?, ?, ?, ?, ?)`);let o=0;for(const s of t){const i=pe(s.dir);if(!(s.root===Y(s.root)&&s.dir===H(s.root,i))||!Re(i)){o+=1;continue}n.run(s.node_id,i,s.request_id,s.work_kind,s.status,s.final_report,s.updated_at)}o>0&&console.warn(`[canvas migration v26] dropped ${o} consult_outbox row(s) whose legacy ticket path cannot safely map to a ticket node id`),e.exec(`
259
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);let E=0;for(const a of t){const i=pe(a.dir);if(!(a.root===Y(a.root)&&a.dir===j(a.root,i))||!Oe(i)){E+=1;continue}n.run(a.node_id,i,a.request_id,a.work_kind,a.status,a.final_report,a.updated_at)}E>0&&console.warn(`[canvas migration v26] dropped ${E} consult_outbox row(s) whose legacy ticket path cannot safely map to a ticket node id`),e.exec(`
260
260
  DROP TABLE consult_outbox;
261
261
  ALTER TABLE consult_outbox_new RENAME TO consult_outbox;
262
262
 
@@ -265,7 +265,7 @@ CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_status ON consult_outbo
265
265
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_ticket_status ON consult_outbox(ticket_node_id, work_kind, status);
266
266
  CREATE INDEX IF NOT EXISTS idx_consult_outbox_ticket_request_status ON consult_outbox(ticket_node_id, request_id, work_kind, status);
267
267
  CREATE UNIQUE INDEX IF NOT EXISTS idx_consult_outbox_visual_request ON consult_outbox(ticket_node_id, request_id, work_kind) WHERE work_kind = 'visual';
268
- `)}E(Ze,"narrowHumanWorkOutbox");function et(e){e.exec(`
268
+ `)}o(tt,"narrowHumanWorkOutbox");function nt(e){e.exec(`
269
269
  CREATE TABLE IF NOT EXISTS reviews (
270
270
  review_id TEXT PRIMARY KEY,
271
271
  idempotency_key TEXT NOT NULL UNIQUE,
@@ -309,7 +309,7 @@ CREATE INDEX IF NOT EXISTS idx_reviews_state ON reviews(state);
309
309
  CREATE INDEX IF NOT EXISTS idx_reviews_origin ON reviews(origin_node_id);
310
310
  CREATE INDEX IF NOT EXISTS idx_reviews_file ON reviews(file);
311
311
  CREATE INDEX IF NOT EXISTS idx_reviews_bridge ON reviews(bridge_node_id);
312
- `)}E(et,"addReviewsTable");function tt(e){e.exec(`
312
+ `)}o(nt,"addReviewsTable");function ot(e){e.exec(`
313
313
  CREATE TABLE IF NOT EXISTS review_comments (
314
314
  comment_id TEXT PRIMARY KEY,
315
315
  review_id TEXT NOT NULL,
@@ -354,13 +354,13 @@ CREATE INDEX IF NOT EXISTS idx_review_comment_events_review_seq
354
354
  ON review_comment_events(review_id, seq);
355
355
  CREATE INDEX IF NOT EXISTS idx_review_comment_events_comment_seq
356
356
  ON review_comment_events(comment_id, seq);
357
- `)}E(tt,"addReviewCommentTables");function nt(e){e.exec(`
357
+ `)}o(ot,"addReviewCommentTables");function Et(e){e.exec(`
358
358
  ALTER TABLE review_comments
359
359
  ADD COLUMN anchor_state TEXT NOT NULL DEFAULT 'live' CHECK (anchor_state IN ('live', 'detached'));
360
- `)}E(nt,"addReviewCommentAnchorState");function Et(e){e.exec("DROP TABLE IF EXISTS consult_outbox")}E(Et,"dropConsultOutbox");function ot(e){e.exec("ALTER TABLE reviews ADD COLUMN submit_requested_at TEXT")}E(ot,"addReviewSubmitRequested");function it(e){e.exec(`
360
+ `)}o(Et,"addReviewCommentAnchorState");function it(e){e.exec("DROP TABLE IF EXISTS consult_outbox")}o(it,"dropConsultOutbox");function st(e){e.exec("ALTER TABLE reviews ADD COLUMN submit_requested_at TEXT")}o(st,"addReviewSubmitRequested");function rt(e){e.exec(`
361
361
  ALTER TABLE crons ADD COLUMN held INTEGER NOT NULL DEFAULT 0;
362
362
  ALTER TABLE crons ADD COLUMN last_poke_at TEXT;
363
- `)}E(it,"addCronHeldColumns");function st(e){e.exec(`
363
+ `)}o(rt,"addCronHeldColumns");function at(e){e.exec(`
364
364
  CREATE TABLE human_action_deliveries (
365
365
  request_id TEXT PRIMARY KEY,
366
366
  state TEXT NOT NULL,
@@ -378,18 +378,18 @@ CREATE TABLE human_action_deliveries (
378
378
  updated_at INTEGER NOT NULL
379
379
  );
380
380
  CREATE INDEX idx_human_action_deliveries_due ON human_action_deliveries(state, next_attempt_at);
381
- `)}E(st,"addHumanActionDeliveries");function Tt(e){const t=u(e);a(e,t,"pi_session_file","ALTER TABLE nodes ADD COLUMN pi_session_file TEXT;");for(const n of M(y(),{withFileTypes:!0}))if(n.isDirectory())try{const o=JSON.parse(k(v(n.name),"utf8"));typeof o.pi_session_file=="string"&&e.prepare("UPDATE nodes SET pi_session_file = ? WHERE node_id = ?").run(o.pi_session_file,n.name)}catch{}e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}E(Tt,"addNodeSessionFileIndex");function Z(e,t){const n=E(d=>{const _=Y(d);return I(_)?le(_):_},"canonical"),o=e.prepare("UPDATE nodes SET pi_session_file = ? WHERE node_id = ?");e.exec("DROP INDEX IF EXISTS idx_nodes_pi_session_file;");const s=e.prepare("SELECT node_id FROM nodes ORDER BY created ASC, node_id ASC").all();for(const{node_id:d}of s){const _=v(d);if(K(_)===null){o.run(null,d);continue}const N=Ie(_,()=>{const c=K(_);if(c===null)throw new Error(`node ${d} session metadata changed during ownership migration`);if(typeof c.pi_session_file!="string")return null;const L=c.pi_session_file,l=n(L);return l!==L&&(c.pi_session_file=l,me(_,c)),l});o.run(N,d)}const i=e.prepare(`
381
+ `)}o(at,"addHumanActionDeliveries");function Tt(e){const t=m(e);N(e,t,"pi_session_file","ALTER TABLE nodes ADD COLUMN pi_session_file TEXT;");for(const n of k(h(),{withFileTypes:!0}))if(n.isDirectory())try{const E=JSON.parse(M(x(n.name),"utf8"));typeof E.pi_session_file=="string"&&e.prepare("UPDATE nodes SET pi_session_file = ? WHERE node_id = ?").run(E.pi_session_file,n.name)}catch{}e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}o(Tt,"addNodeSessionFileIndex");function Z(e,t){const n=o(c=>{const L=Y(c);return U(L)?le(L):L},"canonical"),E=e.prepare("UPDATE nodes SET pi_session_file = ? WHERE node_id = ?");e.exec("DROP INDEX IF EXISTS idx_nodes_pi_session_file;");const a=e.prepare("SELECT node_id FROM nodes ORDER BY created ASC, node_id ASC").all();for(const{node_id:c}of a){const L=x(c);if(K(L)===null){E.run(null,c);continue}const l=fe(L,()=>{const r=K(L);if(r===null)throw new Error(`node ${c} session metadata changed during ownership migration`);if(typeof r.pi_session_file!="string")return null;const _=r.pi_session_file,d=n(_);return d!==_&&(r.pi_session_file=d,Xe(L,r)),d});E.run(l,c)}const i=e.prepare(`
382
382
  SELECT pi_session_file
383
383
  FROM nodes
384
384
  WHERE pi_session_file IS NOT NULL
385
385
  GROUP BY pi_session_file
386
386
  HAVING COUNT(*) > 1
387
- `).all();if(!t&&i.length>0){const d=i.map(({pi_session_file:_})=>_).join(", ");throw new Error(`cannot restore unique Pi session ownership: authoritative metadata has concurrent claimants for ${d}`)}const T=e.prepare("UPDATE nodes SET pi_session_file = NULL WHERE node_id = ?");for(const{pi_session_file:d}of i){const _=e.prepare(`
387
+ `).all();if(!t&&i.length>0){const c=i.map(({pi_session_file:L})=>L).join(", ");throw new Error(`cannot restore unique Pi session ownership: authoritative metadata has concurrent claimants for ${c}`)}const T=e.prepare("UPDATE nodes SET pi_session_file = NULL WHERE node_id = ?");for(const{pi_session_file:c}of i){const L=e.prepare(`
388
388
  SELECT node_id
389
389
  FROM nodes
390
390
  WHERE pi_session_file = ?
391
391
  ORDER BY created ASC, node_id ASC
392
- `).all(d);for(const{node_id:N}of _.slice(1)){if(!q(v(N),L=>{const l=L.pi_session_file;if(typeof l!="string"||n(l)!==d)throw new Error(`node ${N} session metadata changed during ownership migration`);return L.pi_session_id=null,L.pi_session_file=null,!0}))throw new Error(`node ${N} session metadata changed during ownership migration`);T.run(N)}}e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}E(Z,"reconcileNodeSessionFileOwners");function rt(e){Z(e,!0)}E(rt,"makeNodeSessionFileUnique");function at(e){Z(e,!1)}E(at,"repairNodeSessionFileUniqueIndex");function dt(e){const t=u(e);a(e,t,"frozen_at","ALTER TABLE nodes ADD COLUMN frozen_at TEXT;"),a(e,t,"respawn_failures","ALTER TABLE nodes ADD COLUMN respawn_failures INTEGER NOT NULL DEFAULT 0;"),a(e,t,"respawn_not_before","ALTER TABLE nodes ADD COLUMN respawn_not_before TEXT;"),a(e,t,"launched_at","ALTER TABLE nodes ADD COLUMN launched_at TEXT;"),a(e,t,"last_settled_at","ALTER TABLE nodes ADD COLUMN last_settled_at TEXT;"),a(e,t,"terminal_reason","ALTER TABLE nodes ADD COLUMN terminal_reason TEXT;"),e.exec(`
392
+ `).all(c);for(const{node_id:l}of L.slice(1)){if(!q(x(l),_=>{const d=_.pi_session_file;if(typeof d!="string"||n(d)!==c)throw new Error(`node ${l} session metadata changed during ownership migration`);return _.pi_session_id=null,_.pi_session_file=null,!0}))throw new Error(`node ${l} session metadata changed during ownership migration`);T.run(l)}}e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}o(Z,"reconcileNodeSessionFileOwners");function dt(e){Z(e,!0)}o(dt,"makeNodeSessionFileUnique");function _t(e){Z(e,!1)}o(_t,"repairNodeSessionFileUniqueIndex");function ct(e){const t=m(e);N(e,t,"frozen_at","ALTER TABLE nodes ADD COLUMN frozen_at TEXT;"),N(e,t,"respawn_failures","ALTER TABLE nodes ADD COLUMN respawn_failures INTEGER NOT NULL DEFAULT 0;"),N(e,t,"respawn_not_before","ALTER TABLE nodes ADD COLUMN respawn_not_before TEXT;"),N(e,t,"launched_at","ALTER TABLE nodes ADD COLUMN launched_at TEXT;"),N(e,t,"last_settled_at","ALTER TABLE nodes ADD COLUMN last_settled_at TEXT;"),N(e,t,"terminal_reason","ALTER TABLE nodes ADD COLUMN terminal_reason TEXT;"),e.exec(`
393
393
  UPDATE nodes SET terminal_reason = CASE
394
394
  WHEN status = 'done' AND final_report IS NOT NULL THEN 'finalized'
395
395
  WHEN status = 'done' AND intent = 'parked' THEN 'parked'
@@ -398,7 +398,7 @@ UPDATE nodes SET terminal_reason = CASE
398
398
  WHEN status = 'dead' THEN 'crashed'
399
399
  END
400
400
  WHERE status IN ('done','canceled','dead') AND terminal_reason IS NULL;
401
- `)}E(dt,"addNodeLifecycleColumns");function _t(e){const t=u(e);a(e,t,"description","ALTER TABLE nodes ADD COLUMN description TEXT;"),a(e,t,"cycles","ALTER TABLE nodes ADD COLUMN cycles INTEGER;");const n=y();if(!I(n))return;const o=e.prepare("UPDATE nodes SET description = ?, cycles = ? WHERE node_id = ?");for(const s of M(n)){const i=v(s);if(!I(i))continue;let T;try{T=JSON.parse(k(i,"utf8"))}catch{continue}const d=typeof T.description=="string"?T.description:null,_=typeof T.cycles=="number"?T.cycles:null;o.run(d,_,s)}}E(_t,"addNodeLabelColumns");function Nt(e){const t=u(e);a(e,t,"outcome_kind","ALTER TABLE nodes ADD COLUMN outcome_kind TEXT;"),a(e,t,"outcome_reason","ALTER TABLE nodes ADD COLUMN outcome_reason TEXT;"),a(e,t,"outcome_at","ALTER TABLE nodes ADD COLUMN outcome_at TEXT;"),a(e,t,"outcome_revision","ALTER TABLE nodes ADD COLUMN outcome_revision INTEGER NOT NULL DEFAULT 0;"),a(e,t,"outcome_detail_json","ALTER TABLE nodes ADD COLUMN outcome_detail_json TEXT;"),a(e,t,"deadline_at","ALTER TABLE nodes ADD COLUMN deadline_at TEXT;"),e.exec(`
401
+ `)}o(ct,"addNodeLifecycleColumns");function Nt(e){const t=m(e);N(e,t,"description","ALTER TABLE nodes ADD COLUMN description TEXT;"),N(e,t,"cycles","ALTER TABLE nodes ADD COLUMN cycles INTEGER;");const n=h();if(!U(n))return;const E=e.prepare("UPDATE nodes SET description = ?, cycles = ? WHERE node_id = ?");for(const a of k(n)){const i=x(a);if(!U(i))continue;let T;try{T=JSON.parse(M(i,"utf8"))}catch{continue}const c=typeof T.description=="string"?T.description:null,L=typeof T.cycles=="number"?T.cycles:null;E.run(c,L,a)}}o(Nt,"addNodeLabelColumns");function Lt(e){const t=m(e);N(e,t,"outcome_kind","ALTER TABLE nodes ADD COLUMN outcome_kind TEXT;"),N(e,t,"outcome_reason","ALTER TABLE nodes ADD COLUMN outcome_reason TEXT;"),N(e,t,"outcome_at","ALTER TABLE nodes ADD COLUMN outcome_at TEXT;"),N(e,t,"outcome_revision","ALTER TABLE nodes ADD COLUMN outcome_revision INTEGER NOT NULL DEFAULT 0;"),N(e,t,"outcome_detail_json","ALTER TABLE nodes ADD COLUMN outcome_detail_json TEXT;"),N(e,t,"deadline_at","ALTER TABLE nodes ADD COLUMN deadline_at TEXT;"),e.exec(`
402
402
  CREATE TABLE IF NOT EXISTS node_outcome_deliveries (
403
403
  node_id TEXT PRIMARY KEY,
404
404
  state TEXT NOT NULL,
@@ -431,17 +431,17 @@ UPDATE nodes SET outcome_kind='failure',
431
431
  outcome_reason=COALESCE(terminal_reason,'crashed'),
432
432
  outcome_at=COALESCE(finalized_at, created), outcome_revision=1
433
433
  WHERE final_report IS NULL AND status IN ('done','dead','canceled') AND outcome_at IS NULL;
434
- `)}E(Nt,"addNodeOutcomeAndDeadline");function ct(e){const t=u(e);a(e,t,"telemetry_tokens_in","ALTER TABLE nodes ADD COLUMN telemetry_tokens_in INTEGER;"),a(e,t,"telemetry_context_tokens","ALTER TABLE nodes ADD COLUMN telemetry_context_tokens INTEGER;"),a(e,t,"telemetry_last_activity","ALTER TABLE nodes ADD COLUMN telemetry_last_activity TEXT;"),a(e,t,"telemetry_updated_at","ALTER TABLE nodes ADD COLUMN telemetry_updated_at TEXT;");const n=e.prepare(`UPDATE nodes
434
+ `)}o(Lt,"addNodeOutcomeAndDeadline");function lt(e){const t=m(e);N(e,t,"telemetry_tokens_in","ALTER TABLE nodes ADD COLUMN telemetry_tokens_in INTEGER;"),N(e,t,"telemetry_context_tokens","ALTER TABLE nodes ADD COLUMN telemetry_context_tokens INTEGER;"),N(e,t,"telemetry_last_activity","ALTER TABLE nodes ADD COLUMN telemetry_last_activity TEXT;"),N(e,t,"telemetry_updated_at","ALTER TABLE nodes ADD COLUMN telemetry_updated_at TEXT;");const n=e.prepare(`UPDATE nodes
435
435
  SET telemetry_tokens_in = ?, telemetry_context_tokens = ?,
436
436
  telemetry_last_activity = ?, telemetry_updated_at = ?
437
- WHERE node_id = ?`);for(const{node_id:o}of e.prepare("SELECT node_id FROM nodes").all()){const s=H(y(),o,"job","telemetry.json");if(I(s))try{const i=JSON.parse(k(s,"utf8")),T=typeof i.tokens_in=="number"&&Number.isFinite(i.tokens_in)?i.tokens_in:null,d=typeof i.context_tokens=="number"&&Number.isFinite(i.context_tokens)?i.context_tokens:null,_=typeof i.last_activity=="string"?i.last_activity:null,N=ue(s).mtime.toISOString();n.run(T,d,_,N,o)}catch{}}}E(ct,"addNodeTelemetryColumns");function Lt(e){e.exec(`
437
+ WHERE node_id = ?`);for(const{node_id:E}of e.prepare("SELECT node_id FROM nodes").all()){const a=j(h(),E,"job","telemetry.json");if(U(a))try{const i=JSON.parse(M(a,"utf8")),T=typeof i.tokens_in=="number"&&Number.isFinite(i.tokens_in)?i.tokens_in:null,c=typeof i.context_tokens=="number"&&Number.isFinite(i.context_tokens)?i.context_tokens:null,L=typeof i.last_activity=="string"?i.last_activity:null,l=ue(a).mtime.toISOString();n.run(T,c,L,l,E)}catch{}}}o(lt,"addNodeTelemetryColumns");function ut(e){e.exec(`
438
438
  CREATE INDEX IF NOT EXISTS deliveries_external_due_order
439
439
  ON deliveries(state, next_attempt_at, created_at, delivery_id)
440
440
  WHERE destination_kind = 'external_action' AND canceled_at IS NULL;
441
441
  DROP INDEX IF EXISTS deliveries_external_due;
442
442
  CREATE INDEX IF NOT EXISTS idx_nodes_parent_created ON nodes(parent, created);
443
443
  CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
444
- `)}E(Lt,"addRecurringLaneIndexes");function lt(e){_e(e)}E(lt,"projectLiveNodeState");function ut(e){a(e,u(e),"scopes_json","ALTER TABLE nodes ADD COLUMN scopes_json TEXT;")}E(ut,"addNodeScopes");function pt(e){const t=u(e);a(e,t,"grantee","ALTER TABLE nodes ADD COLUMN grantee TEXT NOT NULL DEFAULT 'user:local';"),a(e,t,"sub","ALTER TABLE nodes ADD COLUMN sub TEXT;"),a(e,t,"grant_id","ALTER TABLE nodes ADD COLUMN grant_id TEXT;"),a(e,t,"client_id","ALTER TABLE nodes ADD COLUMN client_id TEXT;"),a(e,t,"metadata_json","ALTER TABLE nodes ADD COLUMN metadata_json TEXT;"),a(e,t,"run_id","ALTER TABLE nodes ADD COLUMN run_id TEXT;"),a(e,t,"event_cursor","ALTER TABLE nodes ADD COLUMN event_cursor INTEGER;"),a(e,t,"usage_json","ALTER TABLE nodes ADD COLUMN usage_json TEXT;"),a(e,t,"deleting_at","ALTER TABLE nodes ADD COLUMN deleting_at TEXT;"),e.exec(`
444
+ `)}o(ut,"addRecurringLaneIndexes");function pt(e){_e(e)}o(pt,"projectLiveNodeState");function Rt(e){N(e,m(e),"scopes_json","ALTER TABLE nodes ADD COLUMN scopes_json TEXT;")}o(Rt,"addNodeScopes");function At(e){const t=m(e);N(e,t,"grantee","ALTER TABLE nodes ADD COLUMN grantee TEXT NOT NULL DEFAULT 'user:local';"),N(e,t,"sub","ALTER TABLE nodes ADD COLUMN sub TEXT;"),N(e,t,"grant_id","ALTER TABLE nodes ADD COLUMN grant_id TEXT;"),N(e,t,"client_id","ALTER TABLE nodes ADD COLUMN client_id TEXT;"),N(e,t,"metadata_json","ALTER TABLE nodes ADD COLUMN metadata_json TEXT;"),N(e,t,"run_id","ALTER TABLE nodes ADD COLUMN run_id TEXT;"),N(e,t,"event_cursor","ALTER TABLE nodes ADD COLUMN event_cursor INTEGER;"),N(e,t,"usage_json","ALTER TABLE nodes ADD COLUMN usage_json TEXT;"),N(e,t,"deleting_at","ALTER TABLE nodes ADD COLUMN deleting_at TEXT;"),e.exec(`
445
445
  ALTER TABLE sessions ADD COLUMN event_offset INTEGER;
446
446
  CREATE INDEX idx_nodes_run_id ON nodes(run_id);
447
447
  -- Child nodes may be pruned while their root run and event history remain.
@@ -466,10 +466,10 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
466
466
  PRIMARY KEY (grantee, key)
467
467
  );
468
468
  CREATE INDEX idx_idempotency_keys_created_at ON idempotency_keys(created_at);
469
- `)}E(pt,"addRunFoundation");function Rt(e){e.exec("ALTER TABLE nodes ADD COLUMN last_activity_at TEXT;"),e.exec(`UPDATE nodes SET last_activity_at = (
469
+ `)}o(At,"addRunFoundation");function Ot(e){e.exec("ALTER TABLE nodes ADD COLUMN last_activity_at TEXT;"),e.exec(`UPDATE nodes SET last_activity_at = (
470
470
  SELECT e.ts FROM run_events e WHERE e.run_id = nodes.node_id
471
471
  ORDER BY e.sequence_number DESC LIMIT 1
472
- ) WHERE run_id = node_id`)}E(Rt,"addRunLastActivity");function At(e){e.exec(`
472
+ ) WHERE run_id = node_id`)}o(Ot,"addRunLastActivity");function mt(e){e.exec(`
473
473
  CREATE TABLE structured_requests (
474
474
  request_id TEXT PRIMARY KEY,
475
475
  node_id TEXT REFERENCES nodes(node_id) ON DELETE CASCADE,
@@ -494,7 +494,7 @@ CREATE TABLE structured_requests (
494
494
  CREATE UNIQUE INDEX idx_structured_requests_one_pending_node ON structured_requests(node_id) WHERE state = 'pending';
495
495
  CREATE INDEX idx_structured_requests_expiry ON structured_requests(state, deadline_at);
496
496
  CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done_at) WHERE effects_done_at IS NULL;
497
- `)}E(At,"addStructuredRequests");function Ot(e){e.exec(`
497
+ `)}o(mt,"addStructuredRequests");function It(e){e.exec(`
498
498
  CREATE TABLE grants (
499
499
  id TEXT PRIMARY KEY, runtime TEXT NOT NULL, sub TEXT NOT NULL, grantee TEXT NOT NULL,
500
500
  rev INTEGER NOT NULL, scopes_json TEXT NOT NULL, resolved_scopes_json TEXT NOT NULL,
@@ -503,13 +503,13 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
503
503
  );
504
504
  CREATE UNIQUE INDEX idx_grants_grantee_sub ON grants(grantee, sub);
505
505
  CREATE TABLE runtime_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);
506
- `)}E(Ot,"addGrantMirror");function It(e){e.exec("UPDATE nodes SET grantee = 'app:terminal' WHERE grantee = 'user:local';")}E(It,"migrateTerminalGrantees");function mt(e){const t={llm:"crtr:llm",act:"crtr:act",schedule:"crtr:schedule","memory:read":"crtr:memory:read:user","memory:write":"crtr:memory:rw:user"},n=e.prepare("SELECT node_id, scopes_json FROM nodes WHERE scopes_json IS NOT NULL").all(),o=e.prepare("UPDATE nodes SET scopes_json = ? WHERE node_id = ?");for(const s of n){const i=JSON.parse(s.scopes_json);if(!Array.isArray(i))throw new Error(`invalid launched scopes for node ${s.node_id}`);const T=[];for(const d of i){if(typeof d!="string")continue;const _=t[d]??d;try{ae(_),T.push(_)}catch(N){if(!(N instanceof TypeError))throw N}}o.run(JSON.stringify([...new Set(T)]),s.node_id)}}E(mt,"migrateLaunchedScopes");function Xt(e){e.exec(`CREATE TABLE node_tokens (
506
+ `)}o(It,"addGrantMirror");function ft(e){e.exec("UPDATE nodes SET grantee = 'app:terminal' WHERE grantee = 'user:local';")}o(ft,"migrateTerminalGrantees");function Xt(e){const t={llm:"crtr:llm",act:"crtr:act",schedule:"crtr:schedule","memory:read":"crtr:memory:read:user","memory:write":"crtr:memory:rw:user"},n=e.prepare("SELECT node_id, scopes_json FROM nodes WHERE scopes_json IS NOT NULL").all(),E=e.prepare("UPDATE nodes SET scopes_json = ? WHERE node_id = ?");for(const a of n){const i=JSON.parse(a.scopes_json);if(!Array.isArray(i))throw new Error(`invalid launched scopes for node ${a.node_id}`);const T=[];for(const c of i){if(typeof c!="string")continue;const L=t[c]??c;try{Te(L),T.push(L)}catch(l){if(!(l instanceof TypeError))throw l}}E.run(JSON.stringify([...new Set(T)]),a.node_id)}}o(Xt,"migrateLaunchedScopes");function Ut(e){e.exec(`CREATE TABLE node_tokens (
507
507
  broker_process_id TEXT PRIMARY KEY REFERENCES executions(execution_id) ON DELETE CASCADE,
508
508
  node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
509
509
  token_hash TEXT NOT NULL UNIQUE, grantee TEXT NOT NULL, uid INTEGER NOT NULL,
510
510
  sub TEXT NOT NULL, grant TEXT, client_id TEXT, scopes_json TEXT,
511
511
  issued_at TEXT NOT NULL, revoked_at TEXT
512
- );`)}E(Xt,"addNodeTokens");function m(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}E(m,"hasTable");function X(e,t,n){return e.prepare(`PRAGMA table_info(${t})`).all().some(o=>o.name===n)}E(X,"hasColumn");function ee(e){m(e,"memory_reads")||e.exec(`CREATE TABLE memory_reads (
512
+ );`)}o(Ut,"addNodeTokens");function C(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}o(C,"hasTable");function S(e,t,n){return e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===n)}o(S,"hasColumn");function ee(e){C(e,"memory_reads")||e.exec(`CREATE TABLE memory_reads (
513
513
  node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
514
514
  name TEXT NOT NULL,
515
515
  scope TEXT NOT NULL,
@@ -518,12 +518,12 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
518
518
  );
519
519
  CREATE INDEX idx_memory_reads_at ON memory_reads(at);
520
520
  CREATE INDEX idx_memory_reads_node ON memory_reads(node_id);
521
- INSERT OR IGNORE INTO canvas_meta(key, value) VALUES ('memory_reads.started_at', strftime('%Y-%m-%dT%H:%M:%fZ','now'));`)}E(ee,"addMemoryReads");function te(e){X(e,"sessions","indexed_entry_id")||e.exec("ALTER TABLE sessions ADD COLUMN indexed_entry_id TEXT; ALTER TABLE sessions ADD COLUMN input_ids_json TEXT NOT NULL DEFAULT '[]';")}E(te,"addConversationIndex");function ne(e){m(e,"app_users")||e.exec(`CREATE TABLE app_users (
521
+ INSERT OR IGNORE INTO canvas_meta(key, value) VALUES ('memory_reads.started_at', strftime('%Y-%m-%dT%H:%M:%fZ','now'));`)}o(ee,"addMemoryReads");function te(e){S(e,"sessions","indexed_entry_id")||e.exec("ALTER TABLE sessions ADD COLUMN indexed_entry_id TEXT; ALTER TABLE sessions ADD COLUMN input_ids_json TEXT NOT NULL DEFAULT '[]';")}o(te,"addConversationIndex");function ne(e){C(e,"app_users")||e.exec(`CREATE TABLE app_users (
522
522
  app TEXT PRIMARY KEY, uid INTEGER NOT NULL UNIQUE,
523
523
  created TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'retired'))
524
- );`)}E(ne,"addAppUsers");function Ee(e){X(e,"crons","grantee")||(e.exec("ALTER TABLE crons ADD COLUMN grantee TEXT NOT NULL DEFAULT 'app:terminal'"),e.exec(`UPDATE crons SET grantee = COALESCE(
524
+ );`)}o(ne,"addAppUsers");function oe(e){S(e,"crons","grantee")||(e.exec("ALTER TABLE crons ADD COLUMN grantee TEXT NOT NULL DEFAULT 'app:terminal'"),e.exec(`UPDATE crons SET grantee = COALESCE(
525
525
  (SELECT COALESCE(nodes.grantee, 'app:terminal') FROM nodes WHERE nodes.node_id = crons.anchor_node),
526
- 'app:terminal') WHERE anchor_node IS NOT NULL`))}E(Ee,"addCronGrantee");function ft(e){ee(e),te(e),ne(e),Ee(e)}E(ft,"convergeSharedVersions");function Ct(e){(e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'app_users'").get()?.sql??"").includes("'removed'")||e.exec(`CREATE TABLE app_users_new (
526
+ 'app:terminal') WHERE anchor_node IS NOT NULL`))}o(oe,"addCronGrantee");function Ct(e){ee(e),te(e),ne(e),oe(e)}o(Ct,"convergeSharedVersions");function St(e){(e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'app_users'").get()?.sql??"").includes("'removed'")||e.exec(`CREATE TABLE app_users_new (
527
527
  uid INTEGER PRIMARY KEY, app TEXT NOT NULL,
528
528
  created TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'removed')),
529
529
  removed_at TEXT
@@ -533,7 +533,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
533
533
  CASE status WHEN 'active' THEN NULL ELSE created END FROM app_users;
534
534
  DROP TABLE app_users;
535
535
  ALTER TABLE app_users_new RENAME TO app_users;
536
- CREATE UNIQUE INDEX idx_app_users_active_app ON app_users(app) WHERE status = 'active';`)}E(Ct,"appUsersRemoved");function oe(e){m(e,"objects")||(e.exec(`
536
+ CREATE UNIQUE INDEX idx_app_users_active_app ON app_users(app) WHERE status = 'active';`)}o(St,"appUsersRemoved");function Ee(e){C(e,"objects")||(e.exec(`
537
537
  CREATE TABLE objects (
538
538
  rowid INTEGER PRIMARY KEY,
539
539
  id TEXT NOT NULL UNIQUE,
@@ -655,11 +655,11 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
655
655
  ALTER TABLE messages ADD COLUMN object_id TEXT;
656
656
  ALTER TABLE messages ADD COLUMN level INTEGER;
657
657
  ALTER TABLE messages ADD COLUMN actor_id TEXT;
658
- `),ie(e),e.exec("ANALYZE"))}E(oe,"canvasObjectsSchema");function ie(e){const t=new Date().toISOString(),n=e.prepare("INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at) VALUES (?, ?, NULL, NULL, 'public', ?, '', ?) RETURNING rowid"),o=e.prepare("INSERT INTO identities (object, scheme, external_id) VALUES (?, ?, ?)"),s=e.prepare(`SELECT DISTINCT n.grantee FROM nodes n
659
- WHERE NOT EXISTS (SELECT 1 FROM identities i WHERE i.external_id = n.grantee AND i.scheme IN ('app', 'local-user'))`).all();for(const{grantee:i}of s){let T;if(i==="user:local")T={type:"person",scheme:"local-user",handle:"user"};else if(/^app:[a-z0-9][a-z0-9._-]*$/.test(i))T={type:"app",scheme:"app",handle:i.slice(4)};else throw new Error(`canvas objects migration: node grantee ${JSON.stringify(i)} is neither app:<name> nor user:local`);const{rowid:d}=n.get(`${Date.now().toString(36)}-${P(4).toString("hex")}`,T.type,T.handle,t);o.run(d,T.scheme,i)}e.exec(`INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at)
658
+ `),ie(e),e.exec("ANALYZE"))}o(Ee,"canvasObjectsSchema");function ie(e){const t=new Date().toISOString(),n=e.prepare("INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at) VALUES (?, ?, NULL, NULL, 'public', ?, '', ?) RETURNING rowid"),E=e.prepare("INSERT INTO identities (object, scheme, external_id) VALUES (?, ?, ?)"),a=e.prepare(`SELECT DISTINCT n.grantee FROM nodes n
659
+ WHERE NOT EXISTS (SELECT 1 FROM identities i WHERE i.external_id = n.grantee AND i.scheme IN ('app', 'local-user'))`).all();for(const{grantee:i}of a){let T;if(i==="user:local")T={type:"person",scheme:"local-user",handle:"user"};else if(/^app:[a-z0-9][a-z0-9._-]*$/.test(i))T={type:"app",scheme:"app",handle:i.slice(4)};else throw new Error(`canvas objects migration: node grantee ${JSON.stringify(i)} is neither app:<name> nor user:local`);const{rowid:c}=n.get(`${Date.now().toString(36)}-${P(4).toString("hex")}`,T.type,T.handle,t);E.run(c,T.scheme,i)}e.exec(`INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at)
660
660
  SELECT n.node_id, 'node', n.kind, i.object, 'public', n.name, '', n.created
661
661
  FROM nodes n JOIN identities i ON i.external_id = n.grantee AND i.scheme IN ('app', 'local-user')
662
- WHERE NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = n.node_id)`)}E(ie,"copyNodesIntoObjects");function Ut(e){if(oe(e),!X(e,"nodes","name"))return;ie(e);const t=e.prepare("SELECT COUNT(*) AS n FROM nodes WHERE node_id NOT IN (SELECT id FROM objects)").get();if(t.n>0)throw new Error(`canvasObjectsCut: ${t.n} node(s) have no objects row`);e.exec(`
662
+ WHERE NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = n.node_id)`)}o(ie,"copyNodesIntoObjects");function gt(e){if(Ee(e),!S(e,"nodes","name"))return;ie(e);const t=e.prepare("SELECT COUNT(*) AS n FROM nodes WHERE node_id NOT IN (SELECT id FROM objects)").get();if(t.n>0)throw new Error(`canvasObjectsCut: ${t.n} node(s) have no objects row`);e.exec(`
663
663
  ALTER TABLE edges RENAME TO legacy_edges;
664
664
  CREATE TABLE edges (
665
665
  type TEXT NOT NULL CHECK (type IN ('acted-on','links-to')),
@@ -707,7 +707,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
707
707
  LEFT JOIN sessions s ON s.node_id = n.node_id AND s.unbound_at IS NULL
708
708
  LEFT JOIN node_faults f ON f.node_id = n.node_id AND f.active = 1;
709
709
  ANALYZE;
710
- `)}E(Ut,"canvasObjectsCut");function St(e){e.exec(`CREATE TABLE IF NOT EXISTS uploads (
710
+ `)}o(gt,"canvasObjectsCut");function Dt(e){e.exec(`CREATE TABLE IF NOT EXISTS uploads (
711
711
  upload_id TEXT PRIMARY KEY, grantee TEXT NOT NULL, name TEXT NOT NULL, media_type TEXT NOT NULL,
712
712
  size INTEGER NOT NULL, created_at TEXT NOT NULL, delete_pending_since TEXT
713
713
  );
@@ -723,7 +723,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
723
723
  url TEXT NOT NULL, created_by TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT,
724
724
  status TEXT NOT NULL CHECK (status IN ('on', 'off')), object_deleted_at TEXT
725
725
  );
726
- CREATE INDEX IF NOT EXISTS idx_shares_created_by ON shares(created_by);`)}E(St,"addFileTransfer");function Dt(e){e.exec(`CREATE TABLE IF NOT EXISTS daemon_actions (
726
+ CREATE INDEX IF NOT EXISTS idx_shares_created_by ON shares(created_by);`)}o(Dt,"addFileTransfer");function vt(e){e.exec(`CREATE TABLE IF NOT EXISTS daemon_actions (
727
727
  action_id TEXT PRIMARY KEY,
728
728
  adapter_json TEXT NOT NULL,
729
729
  body_json TEXT,
@@ -762,7 +762,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
762
762
  DELETE FROM messages
763
763
  WHERE message_id IN (SELECT message_id FROM moved_actions WHERE message_id IS NOT NULL)
764
764
  AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.message_id = messages.message_id);
765
- DROP TABLE moved_actions;`)}E(Dt,"moveDaemonActions");function gt(e){b(e,61,()=>{if(!m(e,"objects"))return;const t=e.prepare("SELECT COUNT(*) AS n FROM objects").get().n,n=e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql LIKE '%objects%'").all();for(const i of n)e.exec(`DROP VIEW "${i.name}"`);e.exec(`
765
+ DROP TABLE moved_actions;`)}o(vt,"moveDaemonActions");function wt(e){B(e,61,()=>{if(!C(e,"objects"))return;const t=e.prepare("SELECT COUNT(*) AS n FROM objects").get().n,n=e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql LIKE '%objects%'").all();for(const i of n)e.exec(`DROP VIEW "${i.name}"`);e.exec(`
766
766
  CREATE TABLE objects_new (
767
767
  rowid INTEGER PRIMARY KEY,
768
768
  id TEXT NOT NULL UNIQUE,
@@ -783,10 +783,10 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
783
783
  CREATE UNIQUE INDEX objects_handle ON objects(type, name) WHERE type IN ('person','app','repo','profile');
784
784
  CREATE INDEX objects_owner_type ON objects(owner, type, kind);
785
785
  CREATE INDEX objects_type_kind ON objects(type, kind);
786
- `);for(const i of n)e.exec(i.sql);const o=e.prepare("SELECT COUNT(*) AS n FROM objects").get().n;if(o!==t)throw new Error(`objects rebuild lost rows: expected ${t}, got ${o}`);const s=e.prepare("PRAGMA foreign_key_check").all();if(s.length>0)throw new Error(`objects rebuild left ${s.length} foreign-key violation(s)`)})}E(gt,"objectsWithoutTypeCheck");function wt(e){m(e,"deliveries")&&e.exec(`
786
+ `);for(const i of n)e.exec(i.sql);const E=e.prepare("SELECT COUNT(*) AS n FROM objects").get().n;if(E!==t)throw new Error(`objects rebuild lost rows: expected ${t}, got ${E}`);const a=e.prepare("PRAGMA foreign_key_check").all();if(a.length>0)throw new Error(`objects rebuild left ${a.length} foreign-key violation(s)`)})}o(wt,"objectsWithoutTypeCheck");function yt(e){C(e,"deliveries")&&e.exec(`
787
787
  CREATE INDEX IF NOT EXISTS deliveries_destination ON deliveries(destination_id, wake, state, created_at);
788
788
  DROP INDEX IF EXISTS deliveries_node_inbox;
789
- `)}E(wt,"addDeliveriesDestinationIndex");function yt(e){e.exec(`
789
+ `)}o(yt,"addDeliveriesDestinationIndex");function ht(e){e.exec(`
790
790
  CREATE TABLE object_kinds (
791
791
  name TEXT PRIMARY KEY, owner INTEGER NOT NULL REFERENCES objects(rowid),
792
792
  description TEXT NOT NULL DEFAULT '', events_json TEXT NOT NULL,
@@ -809,16 +809,16 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
809
809
  DROP INDEX objects_doc_name;
810
810
  CREATE UNIQUE INDEX objects_named ON objects(owner, name)
811
811
  WHERE deleted_at IS NULL AND (type = 'document' OR instr(type, '.') > 0);
812
- `)}E(yt,"customObjectKinds");function vt(e){e.exec("CREATE INDEX IF NOT EXISTS revision_parents_parent ON revision_parents(parent);")}E(vt,"addRevisionParentsParentIndex");function ht(e){m(e,"run_events")&&e.exec(`
812
+ `)}o(ht,"customObjectKinds");function xt(e){e.exec("CREATE INDEX IF NOT EXISTS revision_parents_parent ON revision_parents(parent);")}o(xt,"addRevisionParentsParentIndex");function Ft(e){C(e,"run_events")&&e.exec(`
813
813
  DELETE FROM run_events
814
814
  WHERE type IN ('node.thinking.delta', 'node.output_text.delta')
815
815
  AND EXISTS (SELECT 1 FROM run_events done
816
816
  WHERE done.run_id = run_events.run_id AND done.node_id = run_events.node_id
817
817
  AND done.type IN ('node.thinking.done', 'node.output_text.done', 'usage')
818
818
  AND done.sequence_number > run_events.sequence_number);
819
- `)}E(ht,"dropSpentRunEventDeltas");function xt(e){e.exec("CREATE INDEX IF NOT EXISTS idx_run_events_node_type ON run_events(run_id, node_id, type);")}E(xt,"addRunEventsNodeTypeIndex");function Ft(e){b(e,63,()=>{if(!m(e,"objects")||!m(e,"deliveries"))return;if(X(e,"objects","reception")||e.exec("ALTER TABLE objects ADD COLUMN reception INTEGER NOT NULL DEFAULT 0"),X(e,"objects","listen_json")||e.exec("ALTER TABLE objects ADD COLUMN listen_json TEXT"),e.exec(`UPDATE objects SET reception = CASE WHEN n.status IN ('active','idle') THEN 2 ELSE 1 END
820
- FROM nodes n WHERE n.node_id = objects.id`),X(e,"nodes","listen_default_json")){e.exec(`UPDATE objects SET listen_json = n.listen_default_json FROM nodes n
821
- WHERE n.node_id = objects.id AND n.listen_default_json IS NOT NULL`);const n=e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql LIKE '%nodes%'").all();for(const o of n)e.exec(`DROP VIEW "${o.name}"`);e.exec("ALTER TABLE nodes DROP COLUMN listen_default_json");for(const o of n)e.exec(o.sql)}if(e.exec(`
819
+ `)}o(Ft,"dropSpentRunEventDeltas");function Mt(e){e.exec("CREATE INDEX IF NOT EXISTS idx_run_events_node_type ON run_events(run_id, node_id, type);")}o(Mt,"addRunEventsNodeTypeIndex");function kt(e){B(e,63,()=>{if(!C(e,"objects")||!C(e,"deliveries"))return;if(S(e,"objects","reception")||e.exec("ALTER TABLE objects ADD COLUMN reception INTEGER NOT NULL DEFAULT 0"),S(e,"objects","listen_json")||e.exec("ALTER TABLE objects ADD COLUMN listen_json TEXT"),e.exec(`UPDATE objects SET reception = CASE WHEN n.status IN ('active','idle') THEN 2 ELSE 1 END
820
+ FROM nodes n WHERE n.node_id = objects.id`),S(e,"nodes","listen_default_json")){e.exec(`UPDATE objects SET listen_json = n.listen_default_json FROM nodes n
821
+ WHERE n.node_id = objects.id AND n.listen_default_json IS NOT NULL`);const n=e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql LIKE '%nodes%'").all();for(const E of n)e.exec(`DROP VIEW "${E.name}"`);e.exec("ALTER TABLE nodes DROP COLUMN listen_default_json");for(const E of n)e.exec(E.sql)}if(e.exec(`
822
822
  DROP TRIGGER IF EXISTS nodes_reception_insert;
823
823
  DROP TRIGGER IF EXISTS nodes_reception_status;
824
824
  CREATE TRIGGER nodes_reception_insert AFTER INSERT ON nodes BEGIN
@@ -828,7 +828,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
828
828
  UPDATE objects SET reception = CASE WHEN NEW.status IN ('active','idle') THEN 2 ELSE 1 END WHERE id = NEW.node_id;
829
829
  END;
830
830
  CREATE INDEX IF NOT EXISTS objects_receiving ON objects(rowid) WHERE reception = 2;
831
- `),X(e,"deliveries","destination_kind")){const n=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n;e.exec(`
831
+ `),S(e,"deliveries","destination_kind")){const n=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n;e.exec(`
832
832
  CREATE TABLE deliveries_new (
833
833
  delivery_id TEXT PRIMARY KEY,
834
834
  message_id TEXT REFERENCES messages(message_id),
@@ -862,26 +862,26 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
862
862
  CREATE INDEX deliveries_handed_off ON deliveries(claim_owner) WHERE state = 'handed_off';
863
863
  CREATE INDEX deliveries_message ON deliveries(message_id);
864
864
  CREATE UNIQUE INDEX deliveries_idempotency ON deliveries(idempotency_key) WHERE idempotency_key IS NOT NULL;
865
- `);const o=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n;if(o!==n)throw new Error(`deliveries rebuild lost rows: expected ${n}, got ${o}`)}const t=e.prepare("PRAGMA foreign_key_check").all();if(t.length>0)throw new Error(`v64 left ${t.length} foreign-key violation(s)`)})}E(Ft,"nodesOnObjectInterface");function kt(e){b(e,66,()=>{if(e.exec(`CREATE TABLE IF NOT EXISTS custom_objects (
865
+ `);const E=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n;if(E!==n)throw new Error(`deliveries rebuild lost rows: expected ${n}, got ${E}`)}const t=e.prepare("PRAGMA foreign_key_check").all();if(t.length>0)throw new Error(`v64 left ${t.length} foreign-key violation(s)`)})}o(kt,"nodesOnObjectInterface");function jt(e){B(e,66,()=>{if(e.exec(`CREATE TABLE IF NOT EXISTS custom_objects (
866
866
  object INTEGER PRIMARY KEY REFERENCES objects(rowid) ON DELETE CASCADE,
867
867
  receiver_json TEXT,
868
868
  payload_json TEXT
869
- )`),X(e,"deliveries","adapter_json")){const n=e.prepare(`SELECT d.delivery_id, d.state, d.idempotency_key
869
+ )`),S(e,"deliveries","adapter_json")){const n=e.prepare(`SELECT d.delivery_id, d.state, d.idempotency_key
870
870
  FROM deliveries d
871
871
  WHERE d.adapter_json IS NOT NULL
872
872
  AND NOT EXISTS (SELECT 1 FROM nodes n JOIN objects o ON o.id = n.node_id AND o.type = 'node'
873
- WHERE d.idempotency_key = 'node-outcome:' || n.node_id)`).all(),o=n.filter(r=>r.idempotency_key?.startsWith("node-outcome:")!==!0||r.state!=="acknowledged"&&r.state!=="permanent_failed");if(o.length)throw new Error(`v67 cannot migrate ${o.length} unmappable external-action deliver${o.length===1?"y":"ies"}: ${o.slice(0,5).map(r=>`${r.delivery_id} (${r.state}, ${r.idempotency_key??"no key"})`).join(", ")}; pending work requires a live outcome node`);const s=e.prepare("DELETE FROM deliveries WHERE delivery_id = ?");for(const r of n)s.run(r.delivery_id);const i=e.prepare(`SELECT d.delivery_id, d.message_id, d.destination_id,
873
+ WHERE d.idempotency_key = 'node-outcome:' || n.node_id)`).all(),E=n.filter(s=>s.idempotency_key?.startsWith("node-outcome:")!==!0||s.state!=="acknowledged"&&s.state!=="permanent_failed");if(E.length)throw new Error(`v67 cannot migrate ${E.length} unmappable external-action deliver${E.length===1?"y":"ies"}: ${E.slice(0,5).map(s=>`${s.delivery_id} (${s.state}, ${s.idempotency_key??"no key"})`).join(", ")}; pending work requires a live outcome node`);const a=e.prepare("DELETE FROM deliveries WHERE delivery_id = ?");for(const s of n)a.run(s.delivery_id);const i=e.prepare(`SELECT d.delivery_id, d.message_id, d.destination_id,
874
874
  d.adapter_json, d.state, d.created_at, n.node_id, o.owner, o.privacy
875
875
  FROM deliveries d
876
876
  JOIN nodes n ON d.idempotency_key = 'node-outcome:' || n.node_id
877
877
  JOIN objects o ON o.id = n.node_id AND o.type = 'node'
878
878
  WHERE d.idempotency_key LIKE 'node-outcome:%'`).all(),T=e.prepare(`INSERT INTO objects
879
879
  (id, type, kind, owner, privacy, name, preview, created_at, reception)
880
- VALUES (?, 'action', NULL, ?, ?, ?, '', ?, 2) RETURNING rowid`),d=e.prepare("INSERT INTO custom_objects (object, receiver_json, payload_json) VALUES (?, ?, ?)"),_=e.prepare(`INSERT INTO watches (watcher, object, in_tree, read_heads_key, created_at)
881
- VALUES (?, ?, 1, NULL, ?) RETURNING rowid`),N=e.prepare(`INSERT INTO watch_subscriptions
880
+ VALUES (?, 'action', NULL, ?, ?, ?, '', ?, 2) RETURNING rowid`),c=e.prepare("INSERT INTO custom_objects (object, receiver_json, payload_json) VALUES (?, ?, ?)"),L=e.prepare(`INSERT INTO watches (watcher, object, in_tree, read_heads_key, created_at)
881
+ VALUES (?, ?, 1, NULL, ?) RETURNING rowid`),l=e.prepare(`INSERT INTO watch_subscriptions
882
882
  (watch, pattern, filter_json, config_json, started_by, ends_on, created_at)
883
- VALUES (?, 'outcome', NULL, '{"1":"after-turn"}', 'spawn', NULL, ?)`),c=e.prepare("UPDATE deliveries SET destination_id = ?, idempotency_key = NULL WHERE delivery_id = ?"),L=e.prepare("SELECT body_json FROM messages WHERE message_id = ?"),l=e.prepare(`UPDATE messages SET body_json = ?, event = 'outcome', object_id = ?, level = 1
884
- WHERE message_id = ?`);for(const r of i){if(r.owner===null)throw new Error(`v67 outcome node ${r.node_id} has no owner`);const p=JSON.parse(r.adapter_json);if(p.adapter!=="subprocess"||!Array.isArray(p.argv)||typeof p.cwd!="string"||typeof p.config_origin!="string")throw new Error(`v67 invalid outcome adapter on ${r.delivery_id}`);const F=P(16).toString("hex"),C=new Date(r.created_at).toISOString(),g=T.get(F,r.owner,r.privacy,`outcome/${r.node_id}`,C);d.run(g.rowid,JSON.stringify({argv:p.argv,cwd:p.cwd,config_origin:p.config_origin,name:r.destination_id}),JSON.stringify(p.payload??null));const G=_.get(g.rowid,e.prepare("SELECT rowid FROM objects WHERE id = ?").get(r.node_id).rowid,C);if(N.run(G.rowid,C),r.message_id===null){if(r.state!=="armed")throw new Error(`v67 delivery ${r.delivery_id} has no message but is ${r.state}`);continue}const R=L.get(r.message_id);if(!R||R.body_json===null)throw new Error(`v67 delivery ${r.delivery_id} has no frozen outcome document`);if(e.prepare("SELECT COUNT(*) AS n FROM deliveries WHERE message_id = ?").get(r.message_id).n!==1)throw new Error(`v67 outcome message ${r.message_id} is shared`);const w=JSON.parse(R.body_json);if(w===null||Array.isArray(w)||typeof w!="object")throw new Error(`v67 invalid outcome body on ${r.delivery_id}`);delete w.action,delete w.delivery,l.run(JSON.stringify(w),r.node_id,r.message_id),c.run(F,r.delivery_id)}const O=e.prepare("SELECT COUNT(*) AS n FROM deliveries WHERE state = 'armed'").get();if(O.n!==i.filter(r=>r.state==="armed").length)throw new Error(`v67 found ${O.n} armed deliveries but only ${i.length} mapped outcome rows`);const x=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n-O.n,f=e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql LIKE '%deliveries%'").all();for(const r of f)e.exec(`DROP VIEW "${r.name.replaceAll('"','""')}"`);e.exec(`
883
+ VALUES (?, 'outcome', NULL, '{"1":"after-turn"}', 'spawn', NULL, ?)`),r=e.prepare("UPDATE deliveries SET destination_id = ?, idempotency_key = NULL WHERE delivery_id = ?"),_=e.prepare("SELECT body_json FROM messages WHERE message_id = ?"),d=e.prepare(`UPDATE messages SET body_json = ?, event = 'outcome', object_id = ?, level = 1
884
+ WHERE message_id = ?`);for(const s of i){if(s.owner===null)throw new Error(`v67 outcome node ${s.node_id} has no owner`);const A=JSON.parse(s.adapter_json);if(A.adapter!=="subprocess"||!Array.isArray(A.argv)||typeof A.cwd!="string"||typeof A.config_origin!="string")throw new Error(`v67 invalid outcome adapter on ${s.delivery_id}`);const I=P(16).toString("hex"),g=new Date(s.created_at).toISOString(),w=T.get(I,s.owner,s.privacy,`outcome/${s.node_id}`,g);c.run(w.rowid,JSON.stringify({argv:A.argv,cwd:A.cwd,config_origin:A.config_origin,name:s.destination_id}),JSON.stringify(A.payload??null));const G=L.get(w.rowid,e.prepare("SELECT rowid FROM objects WHERE id = ?").get(s.node_id).rowid,g);if(l.run(G.rowid,g),s.message_id===null){if(s.state!=="armed")throw new Error(`v67 delivery ${s.delivery_id} has no message but is ${s.state}`);continue}const f=_.get(s.message_id);if(!f||f.body_json===null)throw new Error(`v67 delivery ${s.delivery_id} has no frozen outcome document`);if(e.prepare("SELECT COUNT(*) AS n FROM deliveries WHERE message_id = ?").get(s.message_id).n!==1)throw new Error(`v67 outcome message ${s.message_id} is shared`);const y=JSON.parse(f.body_json);if(y===null||Array.isArray(y)||typeof y!="object")throw new Error(`v67 invalid outcome body on ${s.delivery_id}`);delete y.action,delete y.delivery,d.run(JSON.stringify(y),s.node_id,s.message_id),r.run(I,s.delivery_id)}const u=e.prepare("SELECT COUNT(*) AS n FROM deliveries WHERE state = 'armed'").get();if(u.n!==i.filter(s=>s.state==="armed").length)throw new Error(`v67 found ${u.n} armed deliveries but only ${i.length} mapped outcome rows`);const p=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n-u.n,O=e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql LIKE '%deliveries%'").all();for(const s of O)e.exec(`DROP VIEW "${s.name.replaceAll('"','""')}"`);e.exec(`
885
885
  CREATE TABLE deliveries_new (
886
886
  delivery_id TEXT PRIMARY KEY,
887
887
  message_id TEXT NOT NULL REFERENCES messages(message_id),
@@ -916,7 +916,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
916
916
  CREATE INDEX deliveries_handed_off ON deliveries(claim_owner) WHERE state = 'handed_off';
917
917
  CREATE INDEX deliveries_message ON deliveries(message_id);
918
918
  CREATE UNIQUE INDEX deliveries_idempotency ON deliveries(idempotency_key) WHERE idempotency_key IS NOT NULL;
919
- `);for(const r of f)e.exec(r.sql);const D=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n;if(D!==x)throw new Error(`v67 deliveries rebuild lost rows: expected ${x}, got ${D}`)}const t=e.prepare("PRAGMA foreign_key_check").all();if(t.length)throw new Error(`v67 left ${t.length} foreign-key violation(s)`)})}E(kt,"outcomeActionsOnObjects");function Mt(e){e.exec(`
919
+ `);for(const s of O)e.exec(s.sql);const R=e.prepare("SELECT COUNT(*) AS n FROM deliveries").get().n;if(R!==p)throw new Error(`v67 deliveries rebuild lost rows: expected ${p}, got ${R}`)}const t=e.prepare("PRAGMA foreign_key_check").all();if(t.length)throw new Error(`v67 left ${t.length} foreign-key violation(s)`)})}o(jt,"outcomeActionsOnObjects");function Ht(e){e.exec(`
920
920
  CREATE TABLE IF NOT EXISTS create_requests (
921
921
  request_key TEXT PRIMARY KEY,
922
922
  node_id TEXT,
@@ -924,7 +924,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
924
924
  state TEXT NOT NULL DEFAULT 'reserved' CHECK (state IN ('reserved', 'warm_claimed', 'complete'))
925
925
  );
926
926
  CREATE INDEX IF NOT EXISTS idx_create_requests_expires ON create_requests(expires_at);
927
- `)}E(Mt,"addCreateRequests");const h=[Xe,fe,Ce,Ue,Se,De,ge,ye,we,ve,he,xe,Fe,J,ke,J,Me,je,Ge,He,Be,$e,Qe,ze,Ve,Ze,et,tt,nt,Et,ot,it,st,Tt,dt,rt,at,_t,Nt,e=>{de(e),Ne(e),ce(e),Le(e)},Lt,lt,ct,ut,pt,Rt,Ot,Xt,It,mt,ee,te,ne,Ee,ft,Ct,oe,Ut,Ae,St,Dt,gt,wt,Ft,xt,ht,kt,vt,e=>e.exec(`
927
+ `)}o(Ht,"addCreateRequests");function Gt(e){for(const[r,_]of[["sub","TEXT"],["grant_id","TEXT"],["scopes_json","TEXT"],["origin_run_id","TEXT"],["run_execution_id","TEXT"]])S(e,"crons",r)||e.exec(`ALTER TABLE crons ADD COLUMN ${r} ${_}`);const t=[],n=o(r=>e.prepare("SELECT id, sub, resolved_scopes_json FROM grants WHERE grantee = ? ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, rev DESC LIMIT 1").get(r),"grantRow"),E=o(r=>e.prepare("SELECT grantee, sub, resolved_scopes_json FROM grants WHERE id = ?").get(r),"grantById"),a=o(r=>{try{const _=JSON.parse(r);return Array.isArray(_)?_.flatMap(d=>d&&d.mode==="always"&&typeof d.scope=="string"?[d.scope]:[]):[]}catch{return[]}},"snapshot"),i=o((r,_)=>{if(_===null)return null;const d=e.prepare("SELECT grantee, sub, grant_id, scopes_json, run_id FROM node_rows WHERE node_id = ?").get(_);if(d===void 0||d.grantee!==r)return null;const u=r==="app:terminal";let p=null;if(d.scopes_json!==null){let A;try{A=JSON.parse(d.scopes_json)}catch{return{pause:"bad_scopes"}}if(!Array.isArray(A)||!A.every(I=>typeof I=="string"))return{pause:"bad_scopes"};p=A}const O=u?n(r):void 0;let R=d.grant_id??O?.id??null;R===null&&!u&&d.sub!==null&&(R=e.prepare("SELECT id FROM grants WHERE grantee = ? AND sub = ? ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, rev DESC LIMIT 1").get(r,d.sub)?.id??null);const s=R===null?void 0:E(R);return R!==null&&(s===void 0||s.grantee!==r||d.sub!==null&&s.sub!==d.sub)?{pause:"no_grant"}:R===null&&!u?{pause:"no_grant"}:(p===null&&!u&&(p=a(s.resolved_scopes_json)),{principal:{sub:d.sub??s?.sub??O?.sub??"user:local",grant_id:R,scopes:p,origin_run_id:d.run_id}})},"fromCreator"),T=o(r=>{const _=n(r);return r==="app:terminal"?{sub:_?.sub??"user:local",grant_id:_?.id??null,scopes:null,origin_run_id:null}:_===void 0?null:{sub:_.sub,grant_id:_.id,scopes:a(_.resolved_scopes_json),origin_run_id:null}},"fromGrantee"),c=e.prepare("SELECT cron_id, grantee, created_by, isolated, cwd FROM crons WHERE sub IS NULL").all(),L=e.prepare("UPDATE crons SET sub = ?, grant_id = ?, scopes_json = ?, origin_run_id = ? WHERE cron_id = ?"),l=new Map;for(const r of c){const _=i(r.grantee,r.created_by),d=_===null?T(r.grantee):"principal"in _?_.principal:null;if(d===null){const u=_!==null&&"pause"in _?_.pause:"no_grant";L.run("user:local",null,null,null,r.cron_id),e.prepare("UPDATE crons SET state = 'paused' WHERE cron_id = ?").run(r.cron_id),t.push({event:`cron.migrated.${u}`,fields:{cron_id:r.cron_id,grantee:r.grantee}})}else l.set(r.cron_id,d),L.run(d.sub,d.grant_id,d.scopes===null?null:JSON.stringify(d.scopes),d.origin_run_id,r.cron_id);if(r.isolated!==0){const u=j(Re(r.grantee).root,"crons",r.cron_id);e.prepare("UPDATE crons SET cwd = ? WHERE cron_id = ?").run(u,r.cron_id),t.push({event:"cron.migrated.isolated_cwd",fields:{cron_id:r.cron_id,old_cwd:r.cwd,cwd:u}})}}if(C(e,"daemon_actions")){const r=e.prepare("SELECT action_id, adapter_json FROM daemon_actions WHERE state IN ('pending', 'handed_off') AND json_extract(adapter_json, '$.adapter') = 'cron_spawn' AND json_extract(adapter_json, '$.principal') IS NULL").all();for(const _ of r){const d=JSON.parse(_.adapter_json),u=typeof d.cronId=="string"?d.cronId:null,p=u===null?void 0:e.prepare("SELECT grantee, sub, grant_id, scopes_json, origin_run_id, isolated, created_by FROM crons WHERE cron_id = ?").get(u);let O=null;if(p!==void 0&&!(p.grant_id===null&&p.grantee!=="app:terminal"))O={cron_id:u,grantee:p.grantee,sub:p.sub,grant_id:p.grant_id,scopes:p.scopes_json===null?null:JSON.parse(p.scopes_json),origin_run_id:p.origin_run_id,isolated:p.isolated!==0,creator:p.created_by};else if(p===void 0){const R=typeof d.parent=="string"?d.parent:null,s=R===null?void 0:e.prepare("SELECT grantee FROM node_rows WHERE node_id = ?").get(R),A=s===void 0?null:i(s.grantee,R),I=A===null||!("principal"in A)?null:A.principal;s!==void 0&&I!==null&&(O={cron_id:u,grantee:s.grantee,sub:I.sub,grant_id:I.grant_id,scopes:I.scopes,origin_run_id:I.origin_run_id,isolated:d.isolated===!0,creator:R})}if(O!==null)e.prepare("UPDATE daemon_actions SET adapter_json = ? WHERE action_id = ?").run(JSON.stringify({...d,principal:O}),_.action_id);else{const R=Date.now();e.prepare("UPDATE daemon_actions SET state = 'permanent_failed', failed_at = ?, updated_at = ?, claimed_at = NULL, claim_owner = NULL, next_attempt_at = NULL, last_failure_json = ? WHERE action_id = ?").run(R,R,JSON.stringify({kind:"grant_refused",message:"the cron has no derivable principal to authorize this birth"}),_.action_id),t.push({event:"cron.birth.refused",fields:{cron_id:u,action_id:_.action_id,reason:"grant_missing"}})}}}for(const{event:r,fields:_}of t)Ae({level:"warn",event:r,fields:_})}o(Gt,"addCronPrincipal");const F=[Ue,Ce,Se,ge,De,ve,we,he,ye,xe,Fe,Me,ke,J,je,J,He,Ge,be,Be,We,Qe,Ve,Ze,et,tt,nt,ot,Et,it,st,rt,at,Tt,ct,dt,_t,Nt,Lt,e=>{de(e),ce(e),Ne(e),Le(e)},ut,pt,lt,Rt,At,Ot,It,Ut,ft,Xt,ee,te,ne,oe,Ct,St,Ee,gt,me,Dt,vt,wt,yt,kt,Mt,Ft,jt,xt,e=>e.exec(`
928
928
  CREATE TABLE audit_rows (
929
929
  id INTEGER PRIMARY KEY, request_id TEXT NOT NULL, time TEXT NOT NULL, grantee TEXT, sub TEXT,
930
930
  client_id TEXT, class TEXT, operation TEXT NOT NULL, scope_checked TEXT,
@@ -955,7 +955,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
955
955
  ALTER TABLE audit_rows ADD COLUMN question_id TEXT;
956
956
  ALTER TABLE provider_approvals ADD COLUMN call_shape TEXT;
957
957
  ALTER TABLE provider_approvals ADD COLUMN prepared_files TEXT;
958
- `),yt,e=>e.exec(`
958
+ `),ht,e=>e.exec(`
959
959
  CREATE INDEX idx_human_requests_page_source ON human_requests(
960
960
  CASE WHEN json_valid(specification_json) THEN json_extract(specification_json, '$.source.nodeId') END
961
961
  ) WHERE kind = 'page';
@@ -986,4 +986,11 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
986
986
  -- that registered a custom object fixes the run that object reads from.
987
987
  CREATE TABLE deleted_isolated_nodes (node_id TEXT PRIMARY KEY, run_id TEXT NOT NULL);
988
988
  ALTER TABLE custom_objects ADD COLUMN registered_by TEXT;
989
- `),At,Mt,e=>e.exec("ALTER TABLE grants ADD COLUMN dependencies_json TEXT NOT NULL DEFAULT '{}'"),e=>e.exec("ALTER TABLE grants ADD COLUMN run_notice_url TEXT")];function b(e,t,n){const o=e.prepare("PRAGMA foreign_keys").get().foreign_keys;e.exec("PRAGMA foreign_keys = OFF;");try{e.exec("BEGIN IMMEDIATE");try{W(e)===t&&(n(),e.exec(`PRAGMA user_version = ${t+1}`)),e.exec("COMMIT")}catch(s){try{e.exec("ROLLBACK")}catch{}throw s}}finally{e.exec(`PRAGMA foreign_keys = ${o};`)}}E(b,"selfTransactionalMigration");const jt=new Set([3,61,63,66]);function W(e){return e.prepare("PRAGMA user_version").get().user_version}E(W,"currentUserVersion");function se(e,t){h[t](e),e.exec(`PRAGMA user_version = ${t+1}`)}E(se,"applyMigration");function Zt(e){const t=W(e);if(t>h.length)throw new Error(`unsupported canvas schema version ${t} (latest supported ${h.length})`);if(t===h.length)return;const n=e.prepare("PRAGMA busy_timeout").get().timeout;e.exec("PRAGMA busy_timeout = 60000;");try{Gt(e)}finally{e.exec(`PRAGMA busy_timeout = ${n};`)}}E(Zt,"migrate");function Gt(e){for(;;){const t=W(e);if(t>=h.length)return;if(jt.has(t)){if(e.isTransaction)throw new Error(`canvas migration v${t+1} requires autocommit`);h[t](e);continue}if(e.isTransaction){se(e,t);continue}e.exec("BEGIN IMMEDIATE");try{W(e)===t&&se(e,t),e.exec("COMMIT")}catch(n){try{e.exec("ROLLBACK")}catch{}throw n}}}E(Gt,"runPendingMigrations");export{h as MIGRATIONS,Zt as migrate};
989
+ `),mt,Ht,e=>e.exec("ALTER TABLE grants ADD COLUMN dependencies_json TEXT NOT NULL DEFAULT '{}'"),e=>e.exec("ALTER TABLE grants ADD COLUMN run_notice_url TEXT"),e=>e.exec(`
990
+ CREATE TABLE usage (
991
+ grantee TEXT NOT NULL, month TEXT NOT NULL, payer TEXT NOT NULL, source TEXT NOT NULL, served_model TEXT NOT NULL,
992
+ input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0, cached_tokens INTEGER NOT NULL DEFAULT 0,
993
+ usd_equivalent REAL,
994
+ PRIMARY KEY (grantee, month, payer, source, served_model)
995
+ );
996
+ `),Gt];function B(e,t,n){const E=e.prepare("PRAGMA foreign_keys").get().foreign_keys;e.exec("PRAGMA foreign_keys = OFF;");try{e.exec("BEGIN IMMEDIATE");try{W(e)===t&&(n(),e.exec(`PRAGMA user_version = ${t+1}`)),e.exec("COMMIT")}catch(a){try{e.exec("ROLLBACK")}catch{}throw a}}finally{e.exec(`PRAGMA foreign_keys = ${E};`)}}o(B,"selfTransactionalMigration");const bt=new Set([3,61,63,66]);function W(e){return e.prepare("PRAGMA user_version").get().user_version}o(W,"currentUserVersion");function se(e,t){F[t](e),e.exec(`PRAGMA user_version = ${t+1}`)}o(se,"applyMigration");function En(e){const t=W(e);if(t>F.length)throw new Error(`unsupported canvas schema version ${t} (latest supported ${F.length})`);if(t===F.length)return;const n=e.prepare("PRAGMA busy_timeout").get().timeout;e.exec("PRAGMA busy_timeout = 60000;");try{Bt(e)}finally{e.exec(`PRAGMA busy_timeout = ${n};`)}}o(En,"migrate");function Bt(e){for(;;){const t=W(e);if(t>=F.length)return;if(bt.has(t)){if(e.isTransaction)throw new Error(`canvas migration v${t+1} requires autocommit`);F[t](e);continue}if(e.isTransaction){se(e,t);continue}e.exec("BEGIN IMMEDIATE");try{W(e)===t&&se(e,t),e.exec("COMMIT")}catch(n){try{e.exec("ROLLBACK")}catch{}throw n}}}o(Bt,"runPendingMigrations");export{F as MIGRATIONS,En as migrate};