@north-light/crouter 0.3.320 → 0.3.321
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.
- package/dist/api/client.d.ts +2 -1
- package/dist/api/client.js +1 -1
- package/dist/api/dto/broker-ops.d.ts +0 -1
- package/dist/api/dto/node-outcomes.d.ts +6 -0
- package/dist/api/dto/nodes.d.ts +4 -3
- package/dist/api/dto/review-comments.d.ts +8 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/viewer.js +582 -582
- package/dist/clients/inbox/review/comments-client.d.ts +8 -1
- package/dist/clients/inbox/review/comments-client.js +1 -1
- package/dist/clients/inbox/review/companion-pane.d.ts +17 -0
- package/dist/clients/inbox/review/companion-pane.js +1 -1
- package/dist/clients/inbox/review/document-surface.d.ts +10 -0
- package/dist/clients/inbox/review/document-surface.js +2 -2
- package/dist/clients/inbox/review/frame.js +1 -1
- package/dist/clients/inbox/review/keys.d.ts +2 -0
- package/dist/clients/inbox/review/keys.js +1 -1
- package/dist/commands/human/prompts.js +1 -1
- package/dist/core/canvas/browse/app.js +3 -3
- package/dist/core/canvas/canvas.d.ts +3 -3
- package/dist/core/canvas/canvas.js +17 -14
- package/dist/core/canvas/migrations.js +34 -27
- package/dist/core/canvas/node-sql-migration.d.ts +1 -0
- package/dist/core/canvas/node-sql-migration.js +28 -2
- package/dist/core/canvas/paths.d.ts +4 -0
- package/dist/core/canvas/paths.js +1 -1
- package/dist/core/canvas/recovery.d.ts +1 -0
- package/dist/core/canvas/recovery.js +1 -1
- package/dist/core/canvas/worktrees.d.ts +1 -0
- package/dist/core/canvas/worktrees.js +1 -1
- package/dist/core/human/requests.d.ts +1 -0
- package/dist/core/human/requests.js +17 -13
- package/dist/core/review/fork.d.ts +8 -0
- package/dist/core/review/fork.js +5 -0
- package/dist/core/runtime/broker/extension-abort.d.ts +3 -0
- package/dist/core/runtime/broker/extension-abort.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/spawn.d.ts +5 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/runtime/stop-guard.d.ts +1 -3
- package/dist/core/runtime/stop-guard.js +2 -2
- package/dist/core/runtime/stop-signals.d.ts +0 -1
- package/dist/core/runtime/stop-signals.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/health.js +14 -1
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/review-comments.js +1 -1
- package/dist/daemon/api/map.d.ts +4 -2
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/companion-retire.d.ts +3 -1
- package/dist/daemon/companion-retire.js +1 -1
- package/dist/daemon/crtrd.js +7 -7
- package/dist/daemon/human/finish.d.ts +4 -1
- package/dist/daemon/human/finish.js +7 -7
- package/dist/daemon/human/settle.d.ts +8 -6
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/package.json +1 -1
- package/runtime.lock.json +5 -5
|
@@ -1,26 +1,29 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var o=(e,n)=>k(e,"name",{value:n,configurable:!0});import{envNodeId as O}from"../../shared/env.js";import{existsSync as F,realpathSync as H,rmSync as R,statSync as j}from"node:fs";import{join as I,resolve as U}from"node:path";import{openDb as s,withCanvasWrite as p}from"./db.js";import{activateArmedExternalActionDelivery as M,armExternalActionDelivery as P}from"./deliveries.js";import{findNodeBySessionFileSql as C}from"./sessions.js";import{hydrateFault as $}from"./recovery.js";import{hasUnreconciledWorktree as B,openWorktree as z,readWorktree as J,worktreeFromRow as Y}from"./worktrees.js";import{isPidAlive as h,recordedPidLiveness as q}from"./pid.js";import{ensureHome as V,ensureNodeDirs as G,jobDir as K,nodeDir as S}from"./paths.js";function f(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}o(f,"jsonValue");function y(e,n,t){P(e,{destinationId:t.actionName,adapter:{adapter:"subprocess",argv:t.argv,cwd:t.cwd,config_origin:t.configOrigin,payload:t.payload??null},idempotencyKey:`node-outcome:${n}`})}o(y,"insertArmedOutcomeDelivery");function Q(e,n){n.prepare('INSERT INTO nodes (node_id, name, description, title, icon, cycles, kind, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, status, intent, waiting_for, final_report, finalized_at, deadline_at, "window", tmux_session, pane) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(e.node_id,e.name,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.kind,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,f(e.persona_ack,"persona_ack"),f(e.review_binding,"review_binding"),f(e.launch,"launch"),e.status??"active",e.intent??null,e.waiting_for??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null)}o(Q,"seedRow");function X(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,r])=>[t==="fault_id"?t:t.slice(6),r]);return $(Object.fromEntries(n))}o(X,"faultFrom");function _(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:e.waiting_for??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=n.pi_pid===null?!1:h(n.pi_pid),r=X(e);return n.fault=r?.link==="pi\u2192provider"&&r.retry.by==="daemon"&&r.retry.disposition==="auto"&&!t?null:r,n.streaming=e.turn_open_at!==null&&e.turn_closed_at===null&&t,n}o(_,"rowFrom");function T(e,n=J(e.node_id)){return{..._(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}o(T,"metaFrom");function Ee(e,n={}){return V(),p(t=>{Q(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&z(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&y(t,e.node_id,n.outcomeDelivery)}),G(e.node_id),E(e.node_id)}o(Ee,"createNode");function E(e){const n=s().prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:T(n)}o(E,"getNode");function me(e){const n=U(e);return F(n)?H(n):n}o(me,"canonicalSessionFile");function we(e){const n=C(e);return n===null?null:E(n)}o(we,"findNodeBySessionFile");function Ne(e){const n=s().prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?_(n):null}o(Ne,"getRow");function Re(e){const n=s().prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?_(n):null}o(Re,"getRowByPane");function Se(e){return s().prepare(`SELECT * FROM node_rows
|
|
2
2
|
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL
|
|
3
3
|
AND deadline_at <= ? AND status IN ('active','idle') AND kind != 'human'
|
|
4
|
-
ORDER BY deadline_at, created, node_id`).all(e).map(_)}o(
|
|
5
|
-
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),i=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let d=0;for(const a of r){const u=Date.parse(a.deadline_at);Number.isNaN(u)||(d+=Number(i.run(new Date(u+n).toISOString(),a.node_id,a.deadline_at).changes))}return d})}o(
|
|
4
|
+
ORDER BY deadline_at, created, node_id`).all(e).map(_)}o(Se,"dueNodeDeadlines");function ge(e,n){return Number(s().prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e).changes)===1}o(ge,"setNodeDeadline");function Oe(e,n){return!Number.isFinite(n)||n<=0?0:p(t=>{const r=t.prepare(`SELECT node_id, deadline_at FROM nodes
|
|
5
|
+
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),i=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let d=0;for(const a of r){const u=Date.parse(a.deadline_at);Number.isNaN(u)||(d+=Number(i.run(new Date(u+n).toISOString(),a.node_id,a.deadline_at).changes))}return d})}o(Oe,"shiftProfileNodeDeadlines");function Z(e,n){if(e==null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="bigint"||e instanceof Uint8Array)return e;throw new TypeError(`${n} must be a SQLite scalar`)}o(Z,"sqlInput");function he(e,n){const t=[],r=o((d,a=d)=>{Object.prototype.hasOwnProperty.call(n,d)&&t.push([a,Z(n[d],d)])},"add");if(r("name"),r("description"),r("title"),r("icon"),r("cycles"),r("kind"),r("mode"),r("lifecycle"),r("cwd"),r("host_kind"),r("profile_id"),r("parent"),r("spawned_by"),r("creator"),r("fork_from"),r("fork_source_file"),r("model_override"),Object.prototype.hasOwnProperty.call(n,"passive_default")&&t.push(["passive_default",n.passive_default===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"cycle_pending")&&t.push(["cycle_pending",n.cycle_pending===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"persona_ack")&&t.push(["persona_ack_json",f(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",f(n.review_binding,"review_binding")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",f(n.launch,"launch")]),t.length===0){const d=E(e);if(d===null)throw new Error(`unknown node: ${e}`);return d}if(s().prepare(`UPDATE nodes SET ${t.map(([d])=>`${d} = ?`).join(", ")} WHERE node_id = ?`).run(...t.map(([,d])=>d),e).changes!==1)throw new Error(`unknown node: ${e}`);return E(e)}o(he,"updateNode");function ye(e,n){s().prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}o(ye,"setStatus");function Te(e,n){s().prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}o(Te,"setIntent");function De(e,n,t={}){if(t.outcome===void 0){const i=[],d=[];Object.prototype.hasOwnProperty.call(n,"status")&&(i.push("status = ?"),d.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(i.push("intent = ?"),d.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(i.push("terminal_reason = ?"),d.push(n.terminal_reason??null));const a=["node_id = ?"];d.push(e),t.fromStatuses!==void 0&&(a.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),d.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&a.push("final_report IS NULL");const u=s().prepare(`UPDATE nodes SET ${i.join(", ")} WHERE ${a.join(" AND ")}`).run(...d);return Number(u.changes)}const r=t.outcome;return p(i=>{const d=[],a=[];Object.prototype.hasOwnProperty.call(n,"status")&&(d.push("status = ?"),a.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(d.push("intent = ?"),a.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(d.push("terminal_reason = ?"),a.push(n.terminal_reason??null));const u=o((re,W)=>r.supersede===!0?"?":`CASE WHEN outcome_at IS NULL THEN ? ELSE ${W} END`,"outcomeValue");d.push(`outcome_kind = ${u(r.kind,"outcome_kind")}`,`outcome_reason = ${u(r.reason,"outcome_reason")}`,`outcome_detail_json = ${u(r.detailJson,"outcome_detail_json")}`,`outcome_revision = ${r.supersede===!0?"outcome_revision + 1":"CASE WHEN outcome_at IS NULL THEN outcome_revision + 1 ELSE outcome_revision END"}`,`outcome_at = ${u(r.at,"outcome_at")}`),a.push(r.kind,r.reason,r.detailJson,r.at);const c=["node_id = ?"];a.push(e),t.fromStatuses!==void 0&&(c.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),a.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&c.push("final_report IS NULL");const l=i.prepare(`UPDATE nodes SET ${d.join(", ")} WHERE ${c.join(" AND ")}`).run(...a);if(Number(l.changes)===0)return 0;const N=i.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(r.supersede===!0||N.outcome_at===r.at)&&r.documentJson!==null&&r.documentJson!==void 0&&M(i,{idempotencyKey:`node-outcome:${e}`,label:e,bodyJson:r.documentJson,supersede:r.supersede===!0}),Number(l.changes)})}o(De,"transitionStatusIntent");function Le(e){return s().prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e)?.final_report??null}o(Le,"getFinalReport");function Ae(e,n){return s().prepare("UPDATE nodes SET final_report = NULL, finalized_at = NULL WHERE node_id = ? AND final_report = ?").run(e,n).changes>0}o(Ae,"clearFinalReportIfMatches");function be(e,n){s().prepare('UPDATE nodes SET tmux_session = ?, "window" = ?, pane = ? WHERE node_id = ?').run(n.tmux_session??null,n.window??null,n.pane??null,e)}o(be,"setPresence");function ve(e,n){s().prepare("UPDATE nodes SET launched_at = ?, frozen_at = NULL, respawn_not_before = NULL WHERE node_id = ?").run(n,e)}o(ve,"recordLaunch");function xe(e,n){s().prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}o(xe,"recordSettledTurn");function We(e,n){s().prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}o(We,"setFrozen");function ke(e){s().prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}o(ke,"clearFrozen");function Fe(e,n){s().prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}o(Fe,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",D=["state","cleanup_state","path","branch","repo_root","base_ref","base_sha","created_at","closed_at","next_attempt_at","attempts","quarantined","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json","abandoned_json","land_intent_json","disposal_json"];function ee(e){return e.worktree_state===null?null:Y(Object.fromEntries(D.map(n=>[n,e[`worktree_${n}`]])))}o(ee,"worktreeFromProjection");function He(e){const n=D.map(r=>`w.${r} AS worktree_${r}`).join(", ");return s().prepare(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.profile_id = ? ORDER BY n.created`).all(e).map(r=>T(r,ee(r)))}o(He,"listNodesByProfile");function je(){return s().prepare("SELECT node_id, cwd, profile_id FROM nodes ORDER BY created").all().map(e=>{const n=e;return{nodeId:n.node_id,cwd:n.cwd,profileId:n.profile_id}})}o(je,"listNodeMemoryTargets");function ne(e){const n=[m],t=[];if(e?.status!==void 0){const i=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${i.map(()=>"?").join(",")})`),t.push(...i)}return e?.withRecordedPid===!0&&n.push("pi_pid IS NOT NULL"),e?.withRecordedPidOrFrozen===!0&&n.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),s().prepare(`SELECT * FROM node_rows WHERE ${n.join(" AND ")} ORDER BY created`).all(...t).map(_)}o(ne,"listNodes");function Ie(){return s().prepare(`SELECT * FROM node_rows
|
|
6
|
+
WHERE ${m} AND kind != 'human'
|
|
7
|
+
AND (status IN ('active', 'idle') OR (status IN ('done', 'canceled', 'dead') AND (pi_pid IS NOT NULL OR frozen_at IS NOT NULL)))
|
|
8
|
+
ORDER BY created`).all().map(_)}o(Ie,"listNodesForSupervision");function Ue(){return s().prepare(`SELECT node_id, name, created FROM nodes WHERE ${m} ORDER BY created`).all()}o(Ue,"listNodeIdentities");function Me(e,n){p(t=>{t.prepare("INSERT OR REPLACE INTO warm_pool (node_id, recipe_key, created) VALUES (?, ?, ?)").run(e,n,new Date().toISOString())})}o(Me,"registerWarmSpare");function Pe(e){return p(n=>n.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e).changes>0)}o(Pe,"unregisterWarmSpare");function g(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
|
|
6
9
|
n.status AS status, n.pi_pid AS pi_pid, n.pi_pid_identity AS pi_pid_identity
|
|
7
|
-
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?e.prepare(t).all():e.prepare(t).all(n)).map(i=>({node_id:i.node_id,recipe_key:i.recipe_key,created:i.created,status:i.status,pi_pid:i.pi_pid??null,pi_pid_identity:i.pi_pid_identity??null}))}o(
|
|
8
|
-
FROM nodes WHERE ${m} ORDER BY created`).all().map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created}))}o(
|
|
10
|
+
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?e.prepare(t).all():e.prepare(t).all(n)).map(i=>({node_id:i.node_id,recipe_key:i.recipe_key,created:i.created,status:i.status,pi_pid:i.pi_pid??null,pi_pid_identity:i.pi_pid_identity??null}))}o(g,"warmSpareRowsFor");function Ce(){return g(s())}o(Ce,"listWarmSpares");function $e(e){return s().prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}o($e,"isWarmSpare");function L(e){return e.status!=="active"&&e.status!=="idle"?!1:q(e.pi_pid,e.pi_pid_identity)==="alive"}o(L,"spareIsClaimable");function Be(e,n,t={}){return p(r=>{const i=g(r,e).find(L);return i===void 0||r.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(i.node_id).changes===0?null:(r.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,i.node_id),t.outcomeDelivery!==void 0&&y(r,i.node_id,t.outcomeDelivery),i.node_id)})}o(Be,"claimWarmSpare");function ze(e){return g(s(),e).filter(L).length}o(ze,"warmSpareCount");function Je(e){return s().prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e).map(n=>n.node_id)}o(Je,"childrenOf");function Ye(){return s().prepare(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created
|
|
11
|
+
FROM nodes WHERE ${m} ORDER BY created`).all().map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created}))}o(Ye,"rosterNodes");function qe(){return s().prepare("SELECT from_id, to_id, active, created FROM edges WHERE type = 'subscribes_to' ORDER BY created").all().map(e=>({from_id:e.from_id,to_id:e.to_id,active:e.active===1,created:e.created}))}o(qe,"rosterEdges");function Ve(e){return s().prepare(`SELECT * FROM node_rows
|
|
9
12
|
WHERE parent IS NULL AND kind != 'human'
|
|
10
13
|
AND status IN ('active','idle') AND cwd = ?
|
|
11
14
|
AND ${m}
|
|
12
|
-
ORDER BY created DESC`).all(e).map(_)}o(
|
|
15
|
+
ORDER BY created DESC`).all(e).map(_)}o(Ve,"listResumableRoots");function A(e,n,t,r){s().prepare(`INSERT INTO edges (type, from_id, to_id, active, created)
|
|
13
16
|
VALUES (?, ?, ?, ?, ?)
|
|
14
|
-
ON CONFLICT(type, from_id, to_id) DO UPDATE SET active=excluded.active`).run(e,n,t,r?1:0,new Date().toISOString())}o(
|
|
15
|
-
WHERE type = 'subscribes_to' AND to_id = ? ORDER BY created`).all(e).map(n=>({node_id:n.node_id,active:n.active===1,created:n.created}))}o(
|
|
16
|
-
WHERE type = 'subscribes_to' AND from_id = ? ORDER BY created`).all(e).map(n=>({node_id:n.node_id,active:n.active===1,created:n.created}))}o(
|
|
17
|
+
ON CONFLICT(type, from_id, to_id) DO UPDATE SET active=excluded.active`).run(e,n,t,r?1:0,new Date().toISOString())}o(A,"addEdge");function Ge(e,n,t=!0){A("subscribes_to",e,n,t)}o(Ge,"subscribe");function Ke(e,n){s().prepare("DELETE FROM edges WHERE type = ? AND from_id = ? AND to_id = ?").run("subscribes_to",e,n)}o(Ke,"unsubscribe");function Qe(e,n,t){s().prepare("UPDATE edges SET active = ? WHERE type = ? AND from_id = ? AND to_id = ?").run(t?1:0,"subscribes_to",e,n)}o(Qe,"setSubscriptionActive");function Xe(e,n){A("spawned_by",e,n,!0)}o(Xe,"recordSpawn");function Ze(e){return s().prepare(`SELECT from_id AS node_id, active, created FROM edges
|
|
18
|
+
WHERE type = 'subscribes_to' AND to_id = ? ORDER BY created`).all(e).map(n=>({node_id:n.node_id,active:n.active===1,created:n.created}))}o(Ze,"subscribersOf");function b(e){return s().prepare(`SELECT to_id AS node_id, active, created FROM edges
|
|
19
|
+
WHERE type = 'subscribes_to' AND from_id = ? ORDER BY created`).all(e).map(n=>({node_id:n.node_id,active:n.active===1,created:n.created}))}o(b,"subscriptionsOf");function en(e){const n=new Set([e]),t=[],r=b(e).map(i=>i.node_id);for(;r.length>0;){const i=r.shift();if(!n.has(i)){n.add(i),t.push(i);for(const d of b(i))n.has(d.node_id)||r.push(d.node_id)}}return t}o(en,"view");function nn(e){return s().prepare(`SELECT 1 FROM edges e JOIN nodes n ON n.node_id = e.to_id
|
|
17
20
|
WHERE e.type = 'subscribes_to' AND e.from_id = ? AND e.active = 1
|
|
18
|
-
AND n.status IN ('active', 'idle') LIMIT 1`).get(e)!==void 0}o(
|
|
21
|
+
AND n.status IN ('active', 'idle') LIMIT 1`).get(e)!==void 0}o(nn,"hasActiveLiveSubscription");function tn(e){return s().prepare(`SELECT 1 FROM edges e JOIN nodes n ON n.node_id = e.from_id
|
|
19
22
|
WHERE e.type = 'subscribes_to' AND e.to_id = ? AND e.active = 1
|
|
20
|
-
AND n.status IN ('active', 'idle') LIMIT 1`).get(e)!==void 0}o(
|
|
23
|
+
AND n.status IN ('active', 'idle') LIMIT 1`).get(e)!==void 0}o(tn,"hasLiveSubscriber");function rn(e){const n=E(e)?.waiting_for;if(n==null)return!1;const t=E(n);return t!==null&&(t.status==="active"||t.status==="idle")}o(rn,"hasLiveMessageWait");function on(e,n){s().prepare("UPDATE nodes SET waiting_for = ?, waiting_for_generation = waiting_for_generation + 1 WHERE node_id = ?").run(n,e)}o(on,"setMessageWait");function dn(e,n,t){return p(r=>{const i=r.prepare("SELECT waiting_for_generation FROM nodes WHERE node_id = ? AND waiting_for = ?").get(e,n),d=t();return n!==null&&i!==void 0&&r.prepare("UPDATE nodes SET waiting_for = NULL WHERE node_id = ? AND waiting_for = ? AND waiting_for_generation = ?").run(e,n,i.waiting_for_generation),d})}o(dn,"deliverAndSettleMessageWait");function sn(e,n,t){return p(r=>{const i=r.prepare(`SELECT waiter.waiting_for, waiter.waiting_for_generation, target.status AS controller_status
|
|
21
24
|
FROM nodes AS waiter LEFT JOIN nodes AS target ON target.node_id = waiter.waiting_for
|
|
22
|
-
WHERE waiter.node_id = ?`).get(e),d=i?.controller_status==="active"||i?.controller_status==="idle";if(i?.waiting_for!==n||d)return null;const a=t();return r.prepare("UPDATE nodes SET waiting_for = NULL WHERE node_id = ? AND waiting_for = ? AND waiting_for_generation = ?").run(e,n,i.waiting_for_generation),a})}o(
|
|
25
|
+
WHERE waiter.node_id = ?`).get(e),d=i?.controller_status==="active"||i?.controller_status==="idle";if(i?.waiting_for!==n||d)return null;const a=t();return r.prepare("UPDATE nodes SET waiting_for = NULL WHERE node_id = ? AND waiting_for = ? AND waiting_for_generation = ?").run(e,n,i.waiting_for_generation),a})}o(sn,"settleDeadMessageWait");function an(e,n,t){return p(r=>{const i=r.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ?").get(e);return i===void 0?{kind:"missing"}:n(i)?{kind:"terminal",status:i.status,final_report:i.final_report}:{kind:"ran",result:t()}})}o(an,"withFreshTerminalGuard");function w(e){return B(e)}o(w,"hasUnreconciledManagedWorktree");function v(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||w(e.node_id)||e.node_id===O()?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}o(v,"isCollectible");function un(e){if(w(e))return{deleted:!1};const n=p(t=>(t.prepare("DELETE FROM nodes WHERE node_id = ?").run(e),{deleted:!0}));return R(S(e),{recursive:!0,force:!0}),n}o(un,"deleteNode");function ln(e){const n=[...new Set(e)];if(n.length===0)return[];const t=n.filter(w);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);const r=n.map(()=>"?").join(","),i=p(d=>{const a=d.prepare(`SELECT node_id FROM nodes WHERE node_id IN (${r}) ORDER BY created`).all(...n).map(({node_id:u})=>u);return d.prepare(`DELETE FROM nodes WHERE node_id IN (${r})`).run(...n),a});for(const d of i)R(S(d),{recursive:!0,force:!0});return i}o(ln,"deleteNodes");function cn(e){const n=e.dryRun??!1,t=e.includeStale??!1,r=new Date(Date.now()-e.ttlDays*864e5).toISOString(),i=O()??"",d=s(),a=d.prepare(`SELECT * FROM node_rows
|
|
23
26
|
WHERE status IN ('dead', 'done', 'canceled') AND created < ?
|
|
24
|
-
ORDER BY created`).all(r).map(_).filter(l=>
|
|
27
|
+
ORDER BY created`).all(r).map(_).filter(l=>v(l,{pastTtl:!0})).map(l=>({node_id:l.node_id,status:l.status,created:l.created})),u=t?d.prepare(`SELECT node_id, status, created, pi_pid FROM node_rows
|
|
25
28
|
WHERE status IN ('active', 'idle') AND created < ?
|
|
26
|
-
ORDER BY created`).all(r).filter(l=>{if(l.node_id===i)return!1;const
|
|
29
|
+
ORDER BY created`).all(r).filter(l=>{if(l.node_id===i)return!1;const N=l.pi_pid;return!h(N)}).map(l=>({node_id:l.node_id,status:l.status,created:l.created})).filter(l=>!w(l.node_id)):[],c=[...a,...u];return n||c.length===0?{pruned:c,dryRun:n}:(x(c),{pruned:c,dryRun:n})}o(cn,"pruneNodes");function x(e){if(e.length!==0){p(n=>{const t=n.prepare("DELETE FROM nodes WHERE node_id = ?");for(const r of e)t.run(r.node_id)});for(const n of e)R(S(n.node_id),{recursive:!0,force:!0})}}o(x,"deletePrunedNodes");function te(e,n){try{const r=j(I(K(e),"telemetry.json"),{throwIfNoEntry:!1});if(r!==void 0)return r.mtimeMs}catch{}const t=Date.parse(n);return Number.isNaN(t)?0:t}o(te,"recencyMs");function pn(e){const n=e.dryRun??!1,r=ne().map(u=>({row:u,recency:te(u.node_id,u.created),retained:!v(u)})).sort((u,c)=>c.recency-u.recency),i=r.filter(u=>u.retained).length,d=Math.max(e.maxNodes,i),a=r.filter((u,c)=>c>=d&&!u.retained).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created}));return n||a.length===0?{pruned:a,dryRun:n}:(x(a),{pruned:a,dryRun:n})}o(pn,"pruneToLimit");export{me as canonicalSessionFile,Je as childrenOf,Be as claimWarmSpare,Ae as clearFinalReportIfMatches,ke as clearFrozen,Ee as createNode,un as deleteNode,ln as deleteNodes,dn as deliverAndSettleMessageWait,Se as dueNodeDeadlines,we as findNodeBySessionFile,Le as getFinalReport,E as getNode,Ne as getRow,Re as getRowByPane,nn as hasActiveLiveSubscription,rn as hasLiveMessageWait,tn as hasLiveSubscriber,v as isCollectible,$e as isWarmSpare,Ue as listNodeIdentities,je as listNodeMemoryTargets,ne as listNodes,He as listNodesByProfile,Ie as listNodesForSupervision,Ve as listResumableRoots,Ce as listWarmSpares,cn as pruneNodes,pn as pruneToLimit,ve as recordLaunch,Fe as recordRespawnAttempt,xe as recordSettledTurn,Xe as recordSpawn,Me as registerWarmSpare,qe as rosterEdges,Ye as rosterNodes,We as setFrozen,Te as setIntent,on as setMessageWait,ge as setNodeDeadline,be as setPresence,ye as setStatus,Qe as setSubscriptionActive,sn as settleDeadMessageWait,Oe as shiftProfileNodeDeadlines,Ge as subscribe,Ze as subscribersOf,b as subscriptionsOf,De as transitionStatusIntent,Pe as unregisterWarmSpare,Ke as unsubscribe,he as updateNode,en as view,ze as warmSpareCount,an as withFreshTerminalGuard};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var J=Object.defineProperty;var i=(e,n)=>J(e,"name",{value:n,configurable:!0});import{importNodeSqlAuthority as Q}from"./node-sql-migration.js";import{migrateRecoveryWitnesses as
|
|
1
|
+
var J=Object.defineProperty;var i=(e,n)=>J(e,"name",{value:n,configurable:!0});import{importNodeSqlAuthority as Q,recreateNodeRowsView as V}from"./node-sql-migration.js";import{migrateRecoveryWitnesses as Z}from"./recovery.js";import{migrateMessagingState as ee}from"./deliveries.js";import{migrateHumanRequestsState as ne}from"../human/requests.js";import{existsSync as A,readFileSync as h,readdirSync as X,realpathSync as te}from"node:fs";import{basename as oe,join as y,resolve as H}from"node:path";import{crtrHome as ie,isSafeNodeId as re,nodesRoot as S,nodeMetaPath as m}from"./paths.js";import{STATE_MIGRATIONS as se}from"../../migrations/registry.js";import{customExtensionPaths as Te}from"./extensions.js";import{readMetaObject as P,updateJsonFileDurably as b,withMetaLock as Ee,writeMetaObjectLocked as ae}from"./meta-file.js";function de(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
|
-
`)}i(
|
|
26
|
+
`)}i(de,"baselineSchema");function w(e,n){return new Set(e.prepare(`PRAGMA table_info(${n})`).all().map(t=>t.name))}i(w,"tableColumns");function Y(e,n,t,o){n.has(t)||(e.exec(o),n.add(t))}i(Y,"addColumnIfMissing");function l(e){return w(e,"nodes")}i(l,"nodeColumns");const a=Y;function _e(e){const n=l(e);a(e,n,"intent","ALTER TABLE nodes ADD COLUMN intent TEXT;"),a(e,n,"pi_pid","ALTER TABLE nodes ADD COLUMN pi_pid INTEGER;"),a(e,n,"window","ALTER TABLE nodes ADD COLUMN window TEXT;"),a(e,n,"tmux_session","ALTER TABLE nodes ADD COLUMN tmux_session TEXT;")}i(_e,"addRuntimeColumns");function ce(e){const n=S();if(!A(n))return;const t=e.prepare('UPDATE nodes SET intent = ?, pi_pid = ?, "window" = ?, tmux_session = ? WHERE node_id = ?');for(const o of X(n)){const s=m(o);if(!A(s))continue;let T;try{T=JSON.parse(h(s,"utf8"))}catch{continue}t.run(T.intent??null,T.pi_pid??null,T.window??null,T.tmux_session??null,o)}}i(ce,"backfillRuntime");function Ne(e){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!==t)throw new Error(`edges FK rebuild lost rows: expected ${t} 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.exec("COMMIT")}catch(o){throw e.exec("ROLLBACK"),o}}finally{e.exec("PRAGMA foreign_keys = ON;")}}i(
|
|
60
|
+
`);const o=e.prepare("SELECT COUNT(*) AS n FROM edges").get().n;if(o!==t)throw new Error(`edges FK rebuild lost rows: expected ${t} 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.exec("COMMIT")}catch(o){throw e.exec("ROLLBACK"),o}}finally{e.exec("PRAGMA foreign_keys = ON;")}}i(Ne,"edgesForeignKeyCascade");function ue(e){const n=l(e);a(e,n,"pane","ALTER TABLE nodes ADD COLUMN pane TEXT;")}i(ue,"addPaneColumn");function le(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
|
-
`)}i(
|
|
67
|
+
`)}i(le,"addFocusesTable");function Le(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
|
-
`)}i(
|
|
83
|
+
`)}i(Le,"appendWakeupsTable");function pe(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
|
-
`)}i(
|
|
134
|
+
`)}i(pe,"migrateWakeupsToTriggers");function Oe(e){const n=l(e);a(e,n,"host_kind","ALTER TABLE nodes ADD COLUMN host_kind TEXT;")}i(Oe,"addHostKindColumn");function Ae(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
|
-
`)}i(
|
|
139
|
+
`)}i(Ae,"addCanvasMetaTable");function fe(e){const n=l(e);a(e,n,"profile_id","ALTER TABLE nodes ADD COLUMN profile_id TEXT;")}i(fe,"addProfileIdColumn");function Ie(e){const n=l(e);a(e,n,"pi_pid_identity","ALTER TABLE nodes ADD COLUMN pi_pid_identity TEXT;")}i(Ie,"addPidIdentityColumn");function Re(e){const n=l(e);a(e,n,"waiting_for","ALTER TABLE nodes ADD COLUMN waiting_for TEXT;")}i(Re,"addMessageWaitColumn");function $(e){const n=l(e);if(n.size===0)return;a(e,n,"final_report","ALTER TABLE nodes ADD COLUMN final_report TEXT;"),a(e,n,"finalized_at","ALTER TABLE nodes ADD COLUMN finalized_at TEXT;");const t=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 t){const T=y(S(),s,"reports");if(!A(T))continue;let r=null;for(const E of X(T))if(E.endsWith(".md"))try{const d=h(y(T,E),"utf8"),_=/^---\nnode: [^\n]+\nkind: final\nts: ([^\n]+)\n---\n/.exec(d);if(_===null||Number.isNaN(Date.parse(_[1])))continue;const c={name:E,ts:_[1]};(r===null||c.ts>r.ts||c.ts===r.ts&&c.name>r.name)&&(r=c)}catch{}r!==null&&o.run(r.name,r.ts,s)}}i($,"addCanonicalFinalColumns");function me(e){const n=S();if(A(n))for(const t of X(n)){const o=m(t);A(o)&&b(o,s=>{const T=s.launch;if(typeof T!="object"||T===null||Array.isArray(T))return!1;const r=T.extensions;if(!Array.isArray(r)||!r.every(d=>typeof d=="string"))return!1;const E=Te(r);return E.length===r.length?!1:(T.extensions=E,!0)})}}i(me,"normalizePersistedLaunchExtensions");function Xe(e){const n=l(e);a(e,n,"waiting_for_generation","ALTER TABLE nodes ADD COLUMN waiting_for_generation INTEGER NOT NULL DEFAULT 0;")}i(Xe,"addMessageWaitGenerationColumn");function Se(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
|
-
`)}i(
|
|
153
|
+
`)}i(Se,"addHumanWorkOutboxTable");function Ue(e){const n=w(e,"consult_outbox"),t=i((o,s)=>Y(e,n,o,s),"add");t("work_kind","ALTER TABLE consult_outbox ADD COLUMN work_kind TEXT NOT NULL DEFAULT 'follow_up';"),t("interaction_id","ALTER TABLE consult_outbox ADD COLUMN interaction_id TEXT;"),t("generation_id","ALTER TABLE consult_outbox ADD COLUMN generation_id TEXT;"),t("interaction_snapshot","ALTER TABLE consult_outbox ADD COLUMN interaction_snapshot TEXT;"),t("handler_command","ALTER TABLE consult_outbox ADD COLUMN handler_command TEXT;"),t("handler_args_json","ALTER TABLE consult_outbox ADD COLUMN handler_args_json TEXT;"),t("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
|
-
`)}i(
|
|
158
|
+
`)}i(Ue,"addHumanWorkColumns");function ge(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
|
-
`)}i(
|
|
161
|
+
`)}i(ge,"addNodeParentCreatedIndexes");function Ce(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,22 +213,22 @@ 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
|
-
`)}i(
|
|
217
|
-
`).includes(o))return o;t++}}i(
|
|
216
|
+
`)}i(Ce,"addCronsTables");function f(e){return`'${e.replace(/'/g,`'"'"'`)}'`}i(f,"shellSingleQuote");function De(e,n){let t=0;for(;;){const o=`${n}_${t}`;if(!e.split(`
|
|
217
|
+
`).includes(o))return o;t++}}i(De,"uniqueHeredocDelimiter");function W(e,n,t){const o=De(n,t);return`${e} <<'${o}'
|
|
218
218
|
${n}
|
|
219
|
-
${o}`}i(W,"heredocCommand");function
|
|
219
|
+
${o}`}i(W,"heredocCommand");function he(e){if(typeof e!="string")return{};try{const n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?{}:n}catch{return{}}}i(he,"migrationPayload");function L(e,n,t){const o=e[n];if(typeof o!="string"||o.trim()==="")throw new Error(`trigger ${t} payload requires non-empty ${n}`);return o}i(L,"requiredString");function U(e,n){const t=e[n];return typeof t=="string"&&t.trim()!==""?t:void 0}i(U,"optionalString");function I(e,n){const t=e[n];return typeof t=="string"&&t.trim()!==""?t:void 0}i(I,"optionalColumn");function K(e,n,t,o){return W(`crtr node message send --to ${f(e)} --tier ${f(n)}`,t,`CRTR_MIGRATED_${o.replace(/[^A-Za-z0-9]/g,"_")}`)}i(K,"migratedMessageCommand");function we(e,n){return`printf '%s\\n' "$CRTR_GATE_STDOUT" | crtr node message send --to ${f(e)} --tier ${f(n)}`}i(we,"migratedGateStdoutMessageCommand");function xe(e,n){const t=[`crtr node new --kind ${f(L(e,"kind",n))}`],o=[["mode","mode"],["cwd","cwd"],["name","name"],["parent","parent"],["worktreeBase","worktree"],["forkFrom","fork-from"],["model","model"],["profile","profile"],["situationalContext","situational-context"]];for(const[T,r]of o){const E=U(e,T);E!==void 0&&t.push(`--${r} ${f(E)}`)}e.root===!0&&t.push("--root");const s=L(e,"prompt",n);return W(t.join(" "),s,`CRTR_MIGRATED_${n.replace(/[^A-Za-z0-9]/g,"_")}`)}i(xe,"migratedSpawnCommand");const q="migration.v22.skipped";function ve(e){const n=e.prepare("SELECT cwd FROM nodes WHERE parent IS NULL ORDER BY created LIMIT 1").get();return(n!==void 0?I(n,"cwd"):void 0)??process.cwd()}i(ve,"ambientMigrationCwd");function Fe(e){let n;try{n=e.prepare("SELECT eval_pid FROM triggers WHERE eval_state = 'running' AND eval_pid IS NOT NULL").all()}catch{return}for(const t of n){const o=t.eval_pid;if(!(typeof o!="number"||!Number.isInteger(o)||o<=1))try{process.kill(-o,"SIGTERM")}catch{}}}i(Fe,"reapRunningPredicateEvaluations");function ye(e){const n=[],t=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'triggers'").get()!==void 0;t&&Fe(e);let o=[];if(t)try{o=e.prepare("SELECT * FROM triggers ORDER BY created, trigger_id").all()}catch(r){n.push({trigger_id:"<unreadable table>",reason:`triggers table could not be read: ${r instanceof Error?r.message:String(r)}`})}const s=ve(e),T=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 r of o){const E=
|
|
224
|
+
) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, NULL, ?, 'profile', ?, 'skip', 'on-failure', '{}', ?, ?, ?)`);for(const r of o){const E=I(r,"trigger_id");if(E===void 0){n.push({trigger_id:"<unidentified row>",reason:"row carries no trigger_id"});continue}try{ke(e,T,r,E,s)}catch(d){n.push({trigger_id:E,reason:d instanceof Error?d.message:String(d)})}}n.length>0&&(e.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(q,JSON.stringify(n)),console.warn(`[canvas migration v22] ${n.length} retired schedule(s) could not be converted to crons and were dropped; see canvas_meta['${q}']: `+n.map(r=>`${r.trigger_id} (${r.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
|
-
`)}i(
|
|
231
|
+
`)}i(ye,"migrateTriggersToCrons");function ke(e,n,t,o,s){const T=L(t,"owner_id",o),r=e.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(T),E=(r===void 0?void 0:I(r,"cwd"))??s,d=r===void 0?null:I(r,"profile_id")??null,_=I(t,"node_id")??null,c=L(t,"action",o),N=L(t,"action_mode",o),u=L(t,"trigger_type",o),R=he(t.payload),M=I(t,"created")??new Date().toISOString(),C=N==="deadline_message"?"urgent":U(R,"tier")??"normal",x=U(R,"label");let p,D,G=!1;if(c==="msg"&&(N==="inbox_message"||N==="deadline_message")){if(_===null)throw new Error("has no message target");const O=U(R,"body");O!==void 0?p=K(_,C,O,o):u==="when"?(G=!0,p=we(_,C)):p=K(_,C,x??"Scheduled message (no body was recorded when this schedule was armed).",o),D=x??(N==="deadline_message"?"deadline":"scheduled message")}else if(c==="msg"&&N==="fresh_revive"){if(_===null)throw new Error("has no revive target");p=`crtr node lifecycle revive ${f(_)} --fresh`,D=x??"scheduled fresh revive"}else if(c==="new"&&N==="node_birth")p=xe(R,o),D=U(R,"name")??`scheduled ${L(R,"kind",o)} node`;else throw new Error(`has unsupported action ${c}/${N}`);let v,F,B=null;if(u==="when"){v=L(t,"next_eval_at",o),F=L(t,"eval_every",o),B=I(t,"timeout_at")??null;const O=L(t,"when_script",o);p=`${G?`if ! CRTR_GATE_STDOUT="$(
|
|
232
232
|
${O}
|
|
233
233
|
)"; then`:`if ! (
|
|
234
234
|
${O}
|
|
@@ -237,14 +237,14 @@ ${O}
|
|
|
237
237
|
fi
|
|
238
238
|
{
|
|
239
239
|
${p}
|
|
240
|
-
} && crtr cron cancel "$CRTR_CRON_ID"`}else if(u==="at"||u==="every"||u==="until")v=L(t,"fire_at",o),F=u==="every"?L(t,"recur",o):null;else throw new Error(`has unknown timing type ${u}`);if(N==="deadline_message"&&_!==null){const O=e.prepare("SELECT cron_id FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1 AND cron_id <> ?").get(_,o);if(O!==void 0)throw new Error(`node ${_} already has a migrated deadline (${String(O.cron_id)}); only one is allowed`)}n.run(o,D,T,p,v,F,B,_,N==="deadline_message"?1:0,E,d,300,C,M,M)}i(
|
|
240
|
+
} && crtr cron cancel "$CRTR_CRON_ID"`}else if(u==="at"||u==="every"||u==="until")v=L(t,"fire_at",o),F=u==="every"?L(t,"recur",o):null;else throw new Error(`has unknown timing type ${u}`);if(N==="deadline_message"&&_!==null){const O=e.prepare("SELECT cron_id FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1 AND cron_id <> ?").get(_,o);if(O!==void 0)throw new Error(`node ${_} already has a migrated deadline (${String(O.cron_id)}); only one is allowed`)}n.run(o,D,T,p,v,F,B,_,N==="deadline_message"?1:0,E,d,300,C,M,M)}i(ke,"convertTriggerRow");function Me(e){const n=w(e,"crons");n.size===0||n.has("run_pid_identity")||e.exec("ALTER TABLE crons ADD COLUMN run_pid_identity TEXT;")}i(Me,"addCronRunPidIdentityColumn");function Ge(e){const n=w(e,"crons");n.size!==0&&(n.has("run_out_of_band")||e.exec("ALTER TABLE crons ADD COLUMN run_out_of_band INTEGER NOT NULL DEFAULT 0;"),n.has("queued")&&e.exec("ALTER TABLE crons DROP COLUMN queued;"))}i(Ge,"addCronOutOfBandColumn");function Be(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
|
-
`)}i(
|
|
247
|
+
`)}i(Be,"addWarmPoolTable");function He(e){const n=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 t=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 n){const T=
|
|
259
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);let o=0;for(const s of n){const T=oe(s.dir);if(!(s.root===H(s.root)&&s.dir===y(s.root,T))||!re(T)){o+=1;continue}t.run(s.node_id,T,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(`
|
|
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
|
-
`)}i(
|
|
268
|
+
`)}i(He,"narrowHumanWorkOutbox");function Pe(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
|
-
`)}i(
|
|
312
|
+
`)}i(Pe,"addReviewsTable");function be(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
|
-
`)}i(
|
|
357
|
+
`)}i(be,"addReviewCommentTables");function Ye(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
|
-
`)}i(
|
|
360
|
+
`)}i(Ye,"addReviewCommentAnchorState");function $e(e){e.exec("DROP TABLE IF EXISTS consult_outbox")}i($e,"dropConsultOutbox");function We(e){e.exec("ALTER TABLE reviews ADD COLUMN submit_requested_at TEXT")}i(We,"addReviewSubmitRequested");function Ke(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
|
-
`)}i(
|
|
363
|
+
`)}i(Ke,"addCronHeldColumns");function qe(e){e.exec(`
|
|
364
364
|
CREATE TABLE human_action_deliveries (
|
|
365
365
|
request_id TEXT PRIMARY KEY,
|
|
366
366
|
state TEXT NOT NULL,
|
|
@@ -378,7 +378,7 @@ 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
|
-
`)}i(
|
|
381
|
+
`)}i(qe,"addHumanActionDeliveries");function je(e){const n=l(e);a(e,n,"pi_session_file","ALTER TABLE nodes ADD COLUMN pi_session_file TEXT;");for(const t of X(S(),{withFileTypes:!0}))if(t.isDirectory())try{const o=JSON.parse(h(m(t.name),"utf8"));typeof o.pi_session_file=="string"&&e.prepare("UPDATE nodes SET pi_session_file = ? WHERE node_id = ?").run(o.pi_session_file,t.name)}catch{}e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}i(je,"addNodeSessionFileIndex");function j(e,n){const t=i(E=>{const d=H(E);return A(d)?te(d):d},"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:E}of s){const d=m(E);if(P(d)===null){o.run(null,E);continue}const _=Ee(d,()=>{const c=P(d);if(c===null)throw new Error(`node ${E} session metadata changed during ownership migration`);if(typeof c.pi_session_file!="string")return null;const N=c.pi_session_file,u=t(N);return u!==N&&(c.pi_session_file=u,ae(d,c)),u});o.run(_,E)}const T=e.prepare(`
|
|
382
382
|
SELECT pi_session_file
|
|
383
383
|
FROM nodes
|
|
384
384
|
WHERE pi_session_file IS NOT NULL
|
|
@@ -389,7 +389,7 @@ SELECT node_id
|
|
|
389
389
|
FROM nodes
|
|
390
390
|
WHERE pi_session_file = ?
|
|
391
391
|
ORDER BY created ASC, node_id ASC
|
|
392
|
-
`).all(E);for(const{node_id:_}of d.slice(1)){if(!b(
|
|
392
|
+
`).all(E);for(const{node_id:_}of d.slice(1)){if(!b(m(_),N=>{const u=N.pi_session_file;if(typeof u!="string"||t(u)!==E)throw new Error(`node ${_} session metadata changed during ownership migration`);return N.pi_session_id=null,N.pi_session_file=null,!0}))throw new Error(`node ${_} session metadata changed during ownership migration`);r.run(_)}}e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}i(j,"reconcileNodeSessionFileOwners");function ze(e){j(e,!0)}i(ze,"makeNodeSessionFileUnique");function Je(e){j(e,!1)}i(Je,"repairNodeSessionFileUniqueIndex");function Qe(e){const n=l(e);a(e,n,"frozen_at","ALTER TABLE nodes ADD COLUMN frozen_at TEXT;"),a(e,n,"respawn_failures","ALTER TABLE nodes ADD COLUMN respawn_failures INTEGER NOT NULL DEFAULT 0;"),a(e,n,"respawn_not_before","ALTER TABLE nodes ADD COLUMN respawn_not_before TEXT;"),a(e,n,"launched_at","ALTER TABLE nodes ADD COLUMN launched_at TEXT;"),a(e,n,"last_settled_at","ALTER TABLE nodes ADD COLUMN last_settled_at TEXT;"),a(e,n,"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
|
-
`)}i(
|
|
401
|
+
`)}i(Qe,"addNodeLifecycleColumns");function Ve(e){const n=l(e);a(e,n,"description","ALTER TABLE nodes ADD COLUMN description TEXT;"),a(e,n,"cycles","ALTER TABLE nodes ADD COLUMN cycles INTEGER;");const t=S();if(!A(t))return;const o=e.prepare("UPDATE nodes SET description = ?, cycles = ? WHERE node_id = ?");for(const s of X(t)){const T=m(s);if(!A(T))continue;let r;try{r=JSON.parse(h(T,"utf8"))}catch{continue}const E=typeof r.description=="string"?r.description:null,d=typeof r.cycles=="number"?r.cycles:null;o.run(E,d,s)}}i(Ve,"addNodeLabelColumns");function Ze(e){const n=l(e);a(e,n,"outcome_kind","ALTER TABLE nodes ADD COLUMN outcome_kind TEXT;"),a(e,n,"outcome_reason","ALTER TABLE nodes ADD COLUMN outcome_reason TEXT;"),a(e,n,"outcome_at","ALTER TABLE nodes ADD COLUMN outcome_at TEXT;"),a(e,n,"outcome_revision","ALTER TABLE nodes ADD COLUMN outcome_revision INTEGER NOT NULL DEFAULT 0;"),a(e,n,"outcome_detail_json","ALTER TABLE nodes ADD COLUMN outcome_detail_json TEXT;"),a(e,n,"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,4 +431,11 @@ 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
|
-
`)}i(
|
|
434
|
+
`)}i(Ze,"addNodeOutcomeAndDeadline");function en(e){e.exec(`
|
|
435
|
+
CREATE INDEX IF NOT EXISTS deliveries_external_due_order
|
|
436
|
+
ON deliveries(state, next_attempt_at, created_at, delivery_id)
|
|
437
|
+
WHERE destination_kind = 'external_action' AND canceled_at IS NULL;
|
|
438
|
+
DROP INDEX IF EXISTS deliveries_external_due;
|
|
439
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_parent_created ON nodes(parent, created);
|
|
440
|
+
CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
441
|
+
`)}i(en,"addRecurringLaneIndexes");const nn=se.filter(e=>e.lane==="journaled").map(e=>n=>e.apply(n,ie()));function tn(e){V(e)}i(tn,"projectLiveNodeState");const g=[de,_e,ce,Ne,ue,le,Le,Oe,pe,Ae,fe,Ie,Re,$,me,$,Xe,Se,Ue,ge,Ce,ye,Me,Ge,Be,He,Pe,be,Ye,$e,We,Ke,qe,je,Qe,ze,Je,Ve,Ze,...nn,e=>{Q(e),Z(e),ee(e),ne(e)},en,tn],on=new Set([3]);function k(e){return e.prepare("PRAGMA user_version").get().user_version}i(k,"currentUserVersion");function z(e,n){g[n](e),e.exec(`PRAGMA user_version = ${n+1}`)}i(z,"applyMigration");function On(e){const n=k(e);if(n>g.length)throw new Error(`unsupported canvas schema version ${n} (latest supported ${g.length})`);if(n===g.length)return;const t=e.prepare("PRAGMA busy_timeout").get().timeout;e.exec("PRAGMA busy_timeout = 60000;");try{rn(e)}finally{e.exec(`PRAGMA busy_timeout = ${t};`)}}i(On,"migrate");function rn(e){for(;;){const n=k(e);if(n>=g.length)return;if(e.isTransaction||on.has(n)){z(e,n);continue}e.exec("BEGIN IMMEDIATE");try{k(e)===n&&z(e,n),e.exec("COMMIT")}catch(t){try{e.exec("ROLLBACK")}catch{}throw t}}}i(rn,"runPendingMigrations");export{g as MIGRATIONS,On as migrate};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
export declare function recreateNodeRowsView(db: DatabaseSync): void;
|
|
2
3
|
/** Imported by the shared appended consolidation transaction. The caller owns the transaction and user_version. */
|
|
3
4
|
export declare function importNodeSqlAuthority(db: DatabaseSync): void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var d=(e,r)=>A(e,"name",{value:r,configurable:!0});import{randomUUID as N}from"node:crypto";import{existsSync as m,readFileSync as h,readdirSync as x,realpathSync as g}from"node:fs";import{join as X,resolve as R}from"node:path";import{nodesRoot as L}from"./paths.js";const C=["node_id","name","created","cwd","kind","mode","lifecycle"];function f(e,r){return new Set(e.prepare(`PRAGMA table_info(${r})`).all().map(({name:i})=>i))}d(f,"columns");function U(e){const r=f(e,"nodes"),i=[["title","TEXT"],["icon","TEXT"],["spawned_by","TEXT"],["creator","TEXT"],["fork_from","TEXT"],["fork_source_file","TEXT"],["passive_default","INTEGER NOT NULL DEFAULT 0 CHECK (passive_default IN (0,1))"],["cycle_pending","INTEGER NOT NULL DEFAULT 0 CHECK (cycle_pending IN (0,1))"],["model_override","TEXT"],["persona_ack_json","TEXT"],["review_binding_json","TEXT"],["launch_config_json","TEXT"]];for(const[n,t]of i)r.has(n)||e.exec(`ALTER TABLE nodes ADD COLUMN ${n} ${t}`);e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_cycle_pending ON nodes(cycle_pending) WHERE cycle_pending = 1")}d(U,"addNodeColumns");function T(e){const r=R(e);return m(r)?g(r):r}d(T,"canonical");function l(e,r,i){if(e===void 0)return null;const n=JSON.stringify(e);if(n===void 0)throw new Error(`cannot serialize ${r} in ${i}`);return n}d(l,"json");function _(e,r,i){const n=e[r];if(typeof n!="string")throw new Error(`cannot import node metadata ${i}: ${r} must be a string`);return n}d(_,"requiredString");function a(e,r,i){const n=e[r];if(n==null)return null;if(typeof n!="string")throw new Error(`cannot import node metadata ${i}: ${r} must be a string or null`);return n}d(a,"optionalString");function O(e,r,i){const n=e[r];if(n==null)return null;if(typeof n!="number"||!Number.isFinite(n))throw new Error(`cannot import node metadata ${i}: ${r} must be a finite number or null`);return n}d(O,"optionalNumber");function y(e,r,i){if(e!=null){if(typeof e!="object"||Array.isArray(e))throw new Error(`cannot import ${r} from ${i}: expected an object`);return e}}d(y,"optionalObject");function k(){if(!m(L()))return[];const e=[];for(const r of x(L(),{withFileTypes:!0})){if(!r.isDirectory())continue;const i=X(L(),r.name,"meta.json");if(!m(i))continue;let n;try{n=JSON.parse(h(i,"utf8"))}catch(t){throw new Error(`cannot import node metadata ${i}: ${t.message}`)}for(const t of C)if(n[t]===void 0||n[t]===null)throw new Error(`cannot import node metadata ${i}: missing required ${t}`);if(typeof n.node_id!="string"||n.node_id!==r.name)throw new Error(`cannot import node metadata ${i}: node_id does not match its directory`);e.push({path:i,meta:n})}return e}d(k,"readMetas");function D(e){return f(e,"nodes").has("pi_session_file")?new Map(e.prepare("SELECT node_id, pi_session_file FROM nodes WHERE pi_session_file IS NOT NULL").all().map(({node_id:i,pi_session_file:n})=>[i,n])):new Map}d(D,"sqlOnlyPaths");function F(e){e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
3
3
|
binding_id TEXT PRIMARY KEY,
|
|
4
4
|
session_id TEXT,
|
|
@@ -51,4 +51,30 @@ CREATE TABLE IF NOT EXISTS worktrees (
|
|
|
51
51
|
disposal_json TEXT
|
|
52
52
|
);
|
|
53
53
|
CREATE INDEX IF NOT EXISTS idx_worktrees_sweep ON worktrees(state, cleanup_state, next_attempt_at);
|
|
54
|
-
`)}
|
|
54
|
+
`)}d(F,"createTables");function b(e,r,i){const n=e.prepare("INSERT INTO nodes (node_id, name, description, cycles, kind, mode, lifecycle, cwd, host_kind, profile_id, parent, created, title, icon, spawned_by, creator, fork_from, fork_source_file, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(node_id) DO UPDATE SET name=excluded.name, description=excluded.description, cycles=excluded.cycles, kind=excluded.kind, mode=excluded.mode, lifecycle=excluded.lifecycle, cwd=excluded.cwd, host_kind=excluded.host_kind, profile_id=excluded.profile_id, parent=excluded.parent, title=excluded.title, icon=excluded.icon, spawned_by=excluded.spawned_by, creator=excluded.creator, fork_from=excluded.fork_from, fork_source_file=excluded.fork_source_file, passive_default=excluded.passive_default, cycle_pending=excluded.cycle_pending, model_override=excluded.model_override, persona_ack_json=excluded.persona_ack_json, review_binding_json=excluded.review_binding_json, launch_config_json=excluded.launch_config_json");for(const{path:t,meta:o}of r){const s=_(o,"node_id",t),c=i.get(s),p=a(o,"pi_session_file",t);if(c!==void 0&&p!==null&&T(c)!==T(p))throw new Error(`cannot import node metadata ${t}: pi_session_file conflicts with indexed path ${c}`);n.run(s,_(o,"name",t),a(o,"description",t),O(o,"cycles",t),_(o,"kind",t),_(o,"mode",t),_(o,"lifecycle",t),_(o,"cwd",t),a(o,"host_kind",t),a(o,"profile_id",t),a(o,"parent",t),_(o,"created",t),a(o,"title",t),a(o,"icon",t),a(o,"spawned_by",t),a(o,"creator",t),a(o,"fork_from",t),a(o,"fork_source_file",t),o.passive_default===!0?1:0,o.cycle_pending===!0?1:0,a(o,"model_override",t),l(o.persona_ack,"persona_ack",t),l(o.review_binding,"review_binding",t),l(o.launch,"launch",t)),p!==null&&i.delete(s)}}d(b,"importMetas");function v(e,r){const i=new Set(e.prepare("SELECT node_id FROM nodes").all().map(({node_id:t})=>t)),n=e.prepare("INSERT INTO edges (type, from_id, to_id, active, created) VALUES ('spawned_by', ?, ?, 1, ?) ON CONFLICT(type, from_id, to_id) DO NOTHING");for(const{meta:t}of r){const o=t.node_id,s=typeof t.spawned_by=="string"?t.spawned_by:typeof t.parent=="string"?t.parent:null;s!==null&&i.has(o)&&i.has(s)&&n.run(o,s,new Date().toISOString())}}d(v,"importEdges");function j(e,r,i){const n=e.prepare("INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, ?, ?, ?, NULL, NULL, ?, ?, NULL)"),t=new Map;for(const{path:o,meta:s}of r){const c=_(s,"node_id",o),p=i.get(c),E=typeof s.pi_session_file=="string"?s.pi_session_file:p,S=typeof s.pi_session_id=="string"?s.pi_session_id:null;if(E===void 0&&S===null)continue;const u=E===void 0?null:T(E);if(u!==null){const I=t.get(u);if(I!==void 0)throw new Error(`cannot import duplicate live transcript ${u}: ${I}, ${c}`);t.set(u,c)}const w=_(s,"created",o);n.run(N(),S,c,u,w,w),p!==void 0&&i.delete(c)}for(const[o,s]of i){const c=T(s),p=t.get(c);if(p!==void 0)throw new Error(`cannot import duplicate live transcript ${c}: ${p}, ${o}`);t.set(c,o);const E=e.prepare("SELECT created FROM nodes WHERE node_id = ?").get(o)?.created;E!==void 0&&n.run(N(),null,o,c,E,E)}}d(j,"importSessions");function $(e,r){const i=e.prepare("INSERT INTO worktrees (node_id, state, cleanup_state, path, branch, repo_root, base_ref, base_sha, created_at, closed_at, next_attempt_at, attempts, quarantined, sweep_reason, sweep_detail, sweep_last_at, sweep_observed_json, abandoned_json, land_intent_json, disposal_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");for(const{path:n,meta:t}of r){const o=y(t.managed_worktree,"managed worktree",n);if(o===void 0)continue;const s=y(o.sweep,"managed_worktree.sweep",n);i.run(_(t,"node_id",n),_(o,"state",n),a(o,"cleanup",n),_(o,"path",n),_(o,"branch",n),_(o,"repo_root",n),_(o,"base_ref",n),_(o,"base_sha",n),_(o,"created",n),a(o,"closed",n),s===void 0?null:a(s,"next_attempt",n),s===void 0?0:O(s,"attempts",n)??0,s?.quarantined===!0?1:0,s===void 0?null:a(s,"reason",n),s===void 0?null:a(s,"detail",n),s===void 0?null:a(s,"last_attempt",n),l(s?.observed,"managed_worktree.sweep.observed",n),l(o.abandoned,"managed_worktree.abandoned",n),l(o.land_intent,"managed_worktree.land_intent",n),l(o.disposal,"managed_worktree.disposal",n))}}d($,"importWorktrees");function H(e){if(!f(e,"nodes").has("pi_pid"))return;const i=e.prepare("SELECT node_id, pi_pid, pi_pid_identity, launched_at, created FROM nodes WHERE pi_pid IS NOT NULL").all(),n=e.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason) VALUES (?, ?, NULL, ?, ?, 'running', ?, NULL, NULL)");for(const t of i)n.run(N(),t.node_id,t.pi_pid,t.pi_pid_identity,t.launched_at??t.created)}d(H,"importExecutions");function M(e,r){if(e.prepare("SELECT COUNT(*) AS count FROM nodes").get().count<r)throw new Error("node import removed an existing SQL row");if(e.prepare("PRAGMA foreign_key_check").all().length>0)throw new Error("node import foreign key check failed")}d(M,"validate");const W=`
|
|
55
|
+
CREATE VIEW node_rows AS
|
|
56
|
+
SELECT n.*,
|
|
57
|
+
CASE WHEN e.state = 'running' THEN e.pid ELSE NULL END AS pi_pid,
|
|
58
|
+
CASE WHEN e.state = 'running' THEN e.process_identity ELSE NULL END AS pi_pid_identity,
|
|
59
|
+
e.turn_open_at,
|
|
60
|
+
e.turn_closed_at,
|
|
61
|
+
s.session_id AS pi_session_id,
|
|
62
|
+
s.transcript_path AS pi_session_file,
|
|
63
|
+
f.fault_id,
|
|
64
|
+
f.link AS fault_link,
|
|
65
|
+
f.op AS fault_op,
|
|
66
|
+
f.kind AS fault_kind,
|
|
67
|
+
f.message AS fault_message,
|
|
68
|
+
f.since AS fault_since,
|
|
69
|
+
f.operation_id AS fault_operation_id,
|
|
70
|
+
f.anchor_entry_id AS fault_anchor_entry_id,
|
|
71
|
+
f.retry_disposition AS fault_retry_disposition,
|
|
72
|
+
f.retry_by AS fault_retry_by,
|
|
73
|
+
f.retry_attempt AS fault_retry_attempt,
|
|
74
|
+
f.retry_max AS fault_retry_max,
|
|
75
|
+
f.retry_next_at AS fault_retry_next_at,
|
|
76
|
+
f.provider_error_json AS fault_provider_error_json
|
|
77
|
+
FROM nodes n
|
|
78
|
+
LEFT JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited'
|
|
79
|
+
LEFT JOIN sessions s ON s.node_id = n.node_id AND s.unbound_at IS NULL
|
|
80
|
+
LEFT JOIN node_faults f ON f.node_id = n.node_id AND f.active = 1`;function K(e){e.exec("DROP VIEW IF EXISTS node_rows"),e.exec(W)}d(K,"recreateNodeRowsView");function P(e){e.exec("DROP INDEX IF EXISTS idx_nodes_pi_session_file");const r=f(e,"nodes");for(const i of["pi_session_file","pi_pid","pi_pid_identity"])r.has(i)&&e.exec(`ALTER TABLE nodes DROP COLUMN ${i}`);K(e)}d(P,"dropLegacyColumnsAndCreateView");function B(e){const r=e.prepare("SELECT COUNT(*) AS count FROM nodes").get().count,i=D(e),n=k();U(e),F(e),b(e,n,i),v(e,n),j(e,n,i),$(e,n),H(e),M(e,r),P(e)}d(B,"importNodeSqlAuthority");export{B as importNodeSqlAuthority,K as recreateNodeRowsView};
|
|
@@ -16,6 +16,10 @@ export declare function nodesRoot(): string;
|
|
|
16
16
|
export declare function reviewsRoot(): string;
|
|
17
17
|
export declare function reviewDir(reviewId: string): string;
|
|
18
18
|
export declare function reviewBranchPath(reviewId: string): string;
|
|
19
|
+
/** The immutable session branch a single comment's fork is born from. Each
|
|
20
|
+
* comment gets its own branch file so concurrent forks never share a source. */
|
|
21
|
+
export declare function reviewForkBranchPath(reviewId: string, commentId: string): string;
|
|
22
|
+
export declare function ensureReviewForkDir(reviewId: string): void;
|
|
19
23
|
export declare function reviewResultPath(reviewId: string): string;
|
|
20
24
|
export declare function ensureReviewDir(reviewId: string): void;
|
|
21
25
|
/** Absolute path to crtrd's API listener unix socket, a sibling of
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var f=Object.defineProperty;var r=(t,
|
|
1
|
+
var f=Object.defineProperty;var r=(t,o)=>f(t,"name",{value:o,configurable:!0});import{homedir as x}from"node:os";import{join as e}from"node:path";import{mkdirSync as u}from"node:fs";import{CRTR_DIR_NAME as h}from"../../types.js";function i(){const t=process.env.CRTR_HOME;return t!==void 0&&t!==""?t:e(x(),h,"canvas")}r(i,"crtrHome");function b(){return e(i(),"canvas.db")}r(b,"canvasDbPath");function g(){return e(i(),"on-disk-migration.lock")}r(g,"onDiskMigrationLockPath");function T(){return e(i(),"on-disk-migrations.json")}r(T,"onDiskMigrationMarkerPath");function N(t){return c(t),e(n(t),"view.sock")}r(N,"viewSocketPath");function a(){return e(i(),"nodes")}r(a,"nodesRoot");function m(){return e(i(),"reviews")}r(m,"reviewsRoot");function s(t){return c(t),e(m(),t)}r(s,"reviewDir");function C(t){return e(s(t),"branch-point.jsonl")}r(C,"reviewBranchPath");function E(t,o){return c(o),e(s(t),"forks",`${o}.jsonl`)}r(E,"reviewForkBranchPath");function M(t){u(e(s(t),"forks"),{recursive:!0,mode:448})}r(M,"ensureReviewForkDir");function d(t){return e(s(t),"result.json")}r(d,"reviewResultPath");function y(t){u(s(t),{recursive:!0,mode:448})}r(y,"ensureReviewDir");function S(){return e(i(),"crtrd.sock")}r(S,"apiSocketPath");function A(){return e(i(),"session-list-cache.json")}r(A,"sessionListCachePath");const v=128;function D(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=v}r(D,"isSafeNodeId");function c(t){if(!D(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}r(c,"assertSafeNodeId");function n(t){return c(t),e(a(),t)}r(n,"nodeDir");function p(t){return e(n(t),"context")}r(p,"contextDir");function B(t,o){return t.replaceAll("$CRTR_CONTEXT_DIR",p(o)).replaceAll("$CRTR_NODE_ID",o)}r(B,"interpolateNodePaths");function l(t){return e(n(t),"job")}r(l,"jobDir");function P(t){return e(n(t),"reports")}r(P,"reportsDir");function O(t){return e(n(t),"messages")}r(O,"messagesDir");function F(t){return e(n(t),"meta.json")}r(F,"nodeMetaPath");function H(t){return e(n(t),"inbox.jsonl")}r(H,"inboxPath");function L(t){return e(n(t),"situational-context.md")}r(L,"situationalContextPath");function $(t){return e(n(t),"passive.jsonl")}r($,"passivePath");function X(t){return e(n(t),"transcript.jsonl")}r(X,"transcriptPath");function U(t){return e(n(t),"session.ptr")}r(U,"sessionPtrPath");function Y(t){return e(n(t),"injected-docs.json")}r(Y,"injectedDocsPath");function q(t){for(const o of[p(t),l(t),P(t)])u(o,{recursive:!0})}r(q,"ensureNodeDirs");function z(){u(a(),{recursive:!0})}r(z,"ensureHome");export{S as apiSocketPath,b as canvasDbPath,p as contextDir,i as crtrHome,z as ensureHome,q as ensureNodeDirs,y as ensureReviewDir,M as ensureReviewForkDir,H as inboxPath,Y as injectedDocsPath,B as interpolateNodePaths,D as isSafeNodeId,l as jobDir,O as messagesDir,n as nodeDir,F as nodeMetaPath,a as nodesRoot,g as onDiskMigrationLockPath,T as onDiskMigrationMarkerPath,$ as passivePath,P as reportsDir,C as reviewBranchPath,s as reviewDir,E as reviewForkBranchPath,d as reviewResultPath,m as reviewsRoot,A as sessionListCachePath,U as sessionPtrPath,L as situationalContextPath,X as transcriptPath,N as viewSocketPath};
|
|
@@ -29,6 +29,7 @@ export interface BootFaultAttempt {
|
|
|
29
29
|
explanation(): string | null;
|
|
30
30
|
}
|
|
31
31
|
export declare function parseProviderError(value: unknown): FaultProviderError | undefined;
|
|
32
|
+
export declare function hydrateFault(row: Record<string, unknown>): StoredFault;
|
|
32
33
|
export declare function openTurn(executionId: string, _opts: {
|
|
33
34
|
reason: 'agent-start' | 'prompt-unsettled';
|
|
34
35
|
}): boolean;
|