@north-light/cli 0.3.627 → 0.3.628

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,11 @@
1
1
  import type { ObjectRow, Reader } from './types.js';
2
2
  import { type CanvasDb } from '../canvas/db.js';
3
+ /** An import rollback holds this advisory lock exclusively for its whole transaction. Anything that deletes or soft-deletes node rows takes it shared
4
+ * (the deletion paths wait, the physical purges skip their pass with `tryShareNodeDeletes`), so none of them takes row locks on the rows the rollback is
5
+ * deleting in an order of its own, which deadlocked the rollback against the node purge. */
6
+ export declare const IMPORT_ROLLBACK_LOCK = "import-rollback";
7
+ /** Take the shared lock without waiting; false while an import rollback is running. Held until the transaction ends. */
8
+ export declare function tryShareNodeDeletes(db: CanvasDb): Promise<boolean>;
3
9
  /** Mark the node and everything it owns deleted except kept documents, which stay owned by the
4
10
  * deleted node; drop the node's watches (both ends) and its `nodes` row. One savepoint, so it runs as one
5
11
  * transaction or inside the caller's. Refuses a node whose managed worktree is unreconciled. */
@@ -1,7 +1,7 @@
1
- var u=Object.defineProperty;var r=(e,t)=>u(e,"name",{value:t,configurable:!0});import{hasUnreconciledWorktree as f}from"../canvas/worktrees.js";import{usage as m}from"../errors.js";import{deleteDocument as O,undeleteDocument as R}from"./documents.js";import{publish as c}from"./events.js";import{getById as E}from"./objects.js";import{writeActsFor as N}from"../permissions/facts.js";import{rememberDeletedIsolated as D}from"../permissions/ceiling.js";import{withCanvasWrite as w}from"../canvas/db.js";async function j(e,t){if(t.type!=="node")throw new Error(`deleteNodeWithOwned: ${t.id} is a ${t.type}, not a node`);if(await f(t.id))throw new Error(`refusing to delete node ${t.id}: its managed worktree is not reconciled`);await w(async()=>await T(e,t),{savepoint:!0})}r(j,"deleteNodeWithOwned");async function _(e,t){const i=await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
- WHERE i.scheme = 'profile' AND i.external_id = ? AND o.type = 'profile' AND o.deleted_at IS NULL`).get(t);return i?(await w(async()=>{const o=await e.prepare(`UPDATE objects o SET owner = n.app FROM nodes n WHERE n.node_id = o.id AND o.owner = ? AND n.app IS NOT NULL
3
- RETURNING o.id, n.sub`).all(i.id);for(const{id:s,sub:n}of o)n&&await N(e,s,n);await p(e,i),await e.prepare("UPDATE objects SET deleted_at = ?, name = ? WHERE id = ?").run(new Date().toISOString(),`${i.name}.deleted-${i.id}`,i.id),await c(e,{event:"deleted",object:await E(e,i.id),actor:null,attrs:{}}),await e.prepare("DELETE FROM watches WHERE object = ? OR watcher = ?").run(i.id,i.id)},{savepoint:!0}),!0):!1}r(_,"deleteProfileWithOwned");async function F(e,t,i){if(i.type!=="document")throw m(`${i.type} ${i.name} cannot be undeleted; only documents can`,{id:i.id});return await R(e,t,i)}r(F,"undeleteObject");async function T(e,t){const i=await p(e,t);await e.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(i,t.id),await c(e,{event:"deleted",object:await E(e,t.id),actor:null,attrs:{}}),await e.prepare("DELETE FROM watches WHERE object = ? OR watcher = ?").run(t.id,t.id),await D(t.id,e),await e.prepare("UPDATE nodes SET run_id = NULL WHERE run_id = ? AND node_id != ? AND isolated = 0").run(t.id,t.id),await e.prepare("DELETE FROM nodes WHERE node_id = ?").run(t.id)}r(T,"deleteInside");async function p(e,t){const i=await e.prepare(`WITH RECURSIVE sub(id) AS (
1
+ var f=Object.defineProperty;var r=(e,t)=>f(e,"name",{value:t,configurable:!0});import{hasUnreconciledWorktree as m}from"../canvas/worktrees.js";import{usage as O}from"../errors.js";import{deleteDocument as R,undeleteDocument as N}from"./documents.js";import{publish as c}from"./events.js";import{getById as E}from"./objects.js";import{writeActsFor as h}from"../permissions/facts.js";import{rememberDeletedIsolated as S}from"../permissions/ceiling.js";import{withCanvasWrite as p}from"../canvas/db.js";const l="import-rollback";async function U(e){return(await e.prepare("SELECT pg_try_advisory_xact_lock_shared(hashtext(?)) AS ok").get(l)).ok}r(U,"tryShareNodeDeletes");async function j(e,t){if(t.type!=="node")throw new Error(`deleteNodeWithOwned: ${t.id} is a ${t.type}, not a node`);if(await m(t.id))throw new Error(`refusing to delete node ${t.id}: its managed worktree is not reconciled`);await p(async()=>{await e.prepare("SELECT pg_advisory_xact_lock_shared(hashtext(?))").get(l),await T(e,t)},{savepoint:!0})}r(j,"deleteNodeWithOwned");async function C(e,t){const a=await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
+ WHERE i.scheme = 'profile' AND i.external_id = ? AND o.type = 'profile' AND o.deleted_at IS NULL`).get(t);return a?(await p(async()=>{const o=await e.prepare(`UPDATE objects o SET owner = n.app FROM nodes n WHERE n.node_id = o.id AND o.owner = ? AND n.app IS NOT NULL
3
+ RETURNING o.id, n.sub`).all(a.id);for(const{id:s,sub:n}of o)n&&await h(e,s,n);await w(e,a),await e.prepare("UPDATE objects SET deleted_at = ?, name = ? WHERE id = ?").run(new Date().toISOString(),`${a.name}.deleted-${a.id}`,a.id),await c(e,{event:"deleted",object:await E(e,a.id),actor:null,attrs:{}}),await e.prepare("DELETE FROM watches WHERE object = ? OR watcher = ?").run(a.id,a.id)},{savepoint:!0}),!0):!1}r(C,"deleteProfileWithOwned");async function F(e,t,a){if(a.type!=="document")throw O(`${a.type} ${a.name} cannot be undeleted; only documents can`,{id:a.id});return await N(e,t,a)}r(F,"undeleteObject");async function T(e,t){const a=await w(e,t);await e.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(a,t.id),await c(e,{event:"deleted",object:await E(e,t.id),actor:null,attrs:{}}),await e.prepare("DELETE FROM watches WHERE object = ? OR watcher = ?").run(t.id,t.id),await S(t.id,e),await e.prepare("UPDATE nodes SET run_id = NULL WHERE run_id = ? AND node_id != ? AND isolated = 0").run(t.id,t.id),await e.prepare("DELETE FROM nodes WHERE node_id = ?").run(t.id)}r(T,"deleteInside");async function w(e,t){const a=await e.prepare(`WITH RECURSIVE sub(id) AS (
4
4
  SELECT id FROM objects WHERE owner = ?
5
5
  UNION SELECT o.id FROM objects o JOIN sub ON o.owner = sub.id)
6
- SELECT o.* FROM objects o JOIN sub ON sub.id = o.id WHERE o.deleted_at IS NULL`).all(t.id),o=new Set(i.map(a=>a.id)),s=e.prepare(`SELECT e.src FROM edges e JOIN objects s ON s.id = e.src
7
- WHERE e.type = 'links-to' AND e.dst = ? AND s.deleted_at IS NULL`);for(let a=!0;a;){a=!1;for(const d of i)d.type!=="document"||!o.has(d.id)||(await s.all(d.id)).some(({src:l})=>!o.has(l))&&(o.delete(d.id),a=!0)}const n=new Date().toISOString();for(const a of i)if(o.has(a.id)){if(a.type==="document"){await O(e,null,a);continue}await e.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(n,a.id),await c(e,{event:"deleted",object:await E(e,a.id),actor:null,attrs:{}}),await e.prepare("DELETE FROM watches WHERE object = ? OR watcher = ?").run(a.id,a.id)}return n}r(p,"deleteOwned");export{j as deleteNodeWithOwned,_ as deleteProfileWithOwned,F as undeleteObject};
6
+ SELECT o.* FROM objects o JOIN sub ON sub.id = o.id WHERE o.deleted_at IS NULL`).all(t.id),o=new Set(a.map(i=>i.id)),s=e.prepare(`SELECT e.src FROM edges e JOIN objects s ON s.id = e.src
7
+ WHERE e.type = 'links-to' AND e.dst = ? AND s.deleted_at IS NULL`);for(let i=!0;i;){i=!1;for(const d of a)d.type!=="document"||!o.has(d.id)||(await s.all(d.id)).some(({src:u})=>!o.has(u))&&(o.delete(d.id),i=!0)}const n=new Date().toISOString();for(const i of a)if(o.has(i.id)){if(i.type==="document"){await R(e,null,i);continue}await e.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(n,i.id),await c(e,{event:"deleted",object:await E(e,i.id),actor:null,attrs:{}}),await e.prepare("DELETE FROM watches WHERE object = ? OR watcher = ?").run(i.id,i.id)}return n}r(w,"deleteOwned");export{l as IMPORT_ROLLBACK_LOCK,j as deleteNodeWithOwned,C as deleteProfileWithOwned,U as tryShareNodeDeletes,F as undeleteObject};
@@ -1,6 +1,6 @@
1
- var C=Object.defineProperty;var u=(n,d)=>C(n,"name",{value:d,configurable:!0});import{openDb as D,withCanvasWrite as h}from"../../canvas/db.js";import{bundleKeys as M}from"../bundle/layout.js";import{keyMatch as m,q as a,readCatalog as y,rowKey as S,topologicalOrder as F}from"./catalog.js";import{deleteOwnedBlobs as W}from"./blobs.js";import{decodeKeys as $}from"./copy.js";import{OBJECT_ID_COLUMNS as H}from"./rewrite.js";import{targetSchema as g}from"./stage.js";class N extends Error{static{u(this,"Refused")}}async function Y(n,d){const _=await D(),c=await _.prepare("SELECT source_install_id, source_kind, state, created_at FROM import_runs WHERE run_id = ?").get(n);if(c===void 0)throw new Error(`no import run ${n}`);if(c.state!=="done"&&c.state!=="committed"&&c.state!=="failed")throw new Error(`import run ${n} is ${c.state}, not rollbackable`);const L=(await _.prepare("SELECT blob_key FROM import_node_files WHERE blob_key LIKE ?").all(`imports/${n}/node-files/%`)).map(t=>t.blob_key),E={run_id:n,rolled_back:!1,dependents:{},deleted:{}},R={nodes:[],human_requests:[]};try{await h(async t=>{const i=await g(t),k=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(i)).map(e=>e.table_name),l=await y(t,i,k);l.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const T=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(n);for(const{table_name:e,inserted_keys:o}of T){const r=$(o);(e==="nodes"||e==="human_requests")&&R[e].push(...r.map(s=>s[0]));for(let s=0;s<r.length;s+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(r.slice(s,s+5e3)))}const b=new Set(T.map(e=>e.table_name));await t.exec("ANALYZE _rb");for(const e of l.foreignKeys){const o=l.tables.get(e.parent),r=l.tables.get(e.table);if(e.table==="import_node_files"||!b.has(e.parent)||o===void 0||r===void 0||e.parentColumns.join()!==o.primaryKey.join())continue;const s=b.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${m(r,S(r),"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e.table)} c WHERE ${e.columns.map(A=>`c.${a(A)} IS NOT NULL`).join(" AND ")}
2
- AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${m(r,e.columns,"c","p.k")}) ${s}`).get()).n);p>0&&(E.dependents[e.table]=(E.dependents[e.table]??0)+p)}for(const[e,o]of H){const r=l.tables.get(e);if(r===void 0||!r.columns.includes(o)||r.primaryKey.length===0)continue;const s=b.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${m(r,r.primaryKey,"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e)} c WHERE c.${a(o)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${s}`).get()).n);p>0&&(E.dependents[`${e}.${o}`]=p)}const f=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(c.source_install_id,n,c.created_at)).n);f>0&&(E.dependents.import_runs=f);const O=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(n)).n);if(O>0&&(E.dependents.import_id_map=O),Object.keys(E.dependents).length>0)throw new N;const w=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${a(i)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
3
- AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of F(l,[...b]).reverse()){const o=l.tables.get(e);if(o===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${a(i)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${m(o,S(o),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const r=await t.prepareUncached(`DELETE FROM ${a(i)}.${a(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${m(o,S(o),"t","k.k")})`).run();E.deleted[e]=r.changes}for(const e of w)await t.prepareUncached(`UPDATE ${a(i)}.documents d SET
1
+ var A=Object.defineProperty;var u=(n,d)=>A(n,"name",{value:d,configurable:!0});import{openDb as h,withCanvasWrite as D}from"../../canvas/db.js";import{bundleKeys as M}from"../bundle/layout.js";import{keyMatch as m,q as a,readCatalog as y,rowKey as S,topologicalOrder as F}from"./catalog.js";import{deleteOwnedBlobs as W}from"./blobs.js";import{decodeKeys as $}from"./copy.js";import{IMPORT_ROLLBACK_LOCK as g}from"../../graph/deletion.js";import{OBJECT_ID_COLUMNS as H}from"./rewrite.js";import{targetSchema as v}from"./stage.js";class L extends Error{static{u(this,"Refused")}}async function Z(n,d){const l=await h(),c=await l.prepare("SELECT source_install_id, source_kind, state, created_at FROM import_runs WHERE run_id = ?").get(n);if(c===void 0)throw new Error(`no import run ${n}`);if(c.state!=="done"&&c.state!=="committed"&&c.state!=="failed")throw new Error(`import run ${n} is ${c.state}, not rollbackable`);const N=(await l.prepare("SELECT blob_key FROM import_node_files WHERE blob_key LIKE ?").all(`imports/${n}/node-files/%`)).map(t=>t.blob_key),E={run_id:n,rolled_back:!1,dependents:{},deleted:{}},R={nodes:[],human_requests:[]};try{await D(async t=>{await t.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(g);const i=await v(t),k=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(i)).map(e=>e.table_name),_=await y(t,i,k);_.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const T=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(n);for(const{table_name:e,inserted_keys:o}of T){const r=$(o);(e==="nodes"||e==="human_requests")&&R[e].push(...r.map(s=>s[0]));for(let s=0;s<r.length;s+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(r.slice(s,s+5e3)))}const b=new Set(T.map(e=>e.table_name));await t.exec("ANALYZE _rb");for(const e of _.foreignKeys){const o=_.tables.get(e.parent),r=_.tables.get(e.table);if(e.table==="import_node_files"||!b.has(e.parent)||o===void 0||r===void 0||e.parentColumns.join()!==o.primaryKey.join())continue;const s=b.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${m(r,S(r),"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e.table)} c WHERE ${e.columns.map(C=>`c.${a(C)} IS NOT NULL`).join(" AND ")}
2
+ AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${m(r,e.columns,"c","p.k")}) ${s}`).get()).n);p>0&&(E.dependents[e.table]=(E.dependents[e.table]??0)+p)}for(const[e,o]of H){const r=_.tables.get(e);if(r===void 0||!r.columns.includes(o)||r.primaryKey.length===0)continue;const s=b.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${m(r,r.primaryKey,"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e)} c WHERE c.${a(o)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${s}`).get()).n);p>0&&(E.dependents[`${e}.${o}`]=p)}const f=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(c.source_install_id,n,c.created_at)).n);f>0&&(E.dependents.import_runs=f);const O=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(n)).n);if(O>0&&(E.dependents.import_id_map=O),Object.keys(E.dependents).length>0)throw new L;const w=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${a(i)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
3
+ AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of F(_,[...b]).reverse()){const o=_.tables.get(e);if(o===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${a(i)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${m(o,S(o),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const r=await t.prepareUncached(`DELETE FROM ${a(i)}.${a(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${m(o,S(o),"t","k.k")})`).run();E.deleted[e]=r.changes}for(const e of w)await t.prepareUncached(`UPDATE ${a(i)}.documents d SET
4
4
  heads_key = COALESCE((SELECT string_agg(r.rev_id, ',' ORDER BY r.rev_id) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), ''),
5
5
  revision = COALESCE((SELECT max(r.number) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), 0)
6
- WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(c.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await v(t,c)})}catch(t){if(t instanceof N)return E;throw t}await d.delete(M.manifest(n));for(const t of L)await d.delete(t);return await W(d,R.nodes,R.human_requests),E.rolled_back=!0,E}u(Y,"rollbackRun");async function v(n,d){if(d.source_kind!=="machine")return;const _=await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(d.source_install_id);_!==void 0&&await n.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),_.object)}u(v,"revokeFor");export{Y as rollbackRun};
6
+ WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(c.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await U(t,c)})}catch(t){if(t instanceof L)return E;throw t}await d.delete(M.manifest(n));for(const t of N)await d.delete(t);return await W(d,R.nodes,R.human_requests),E.rolled_back=!0,E}u(Z,"rollbackRun");async function U(n,d){if(d.source_kind!=="machine")return;const l=await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(d.source_install_id);l!==void 0&&await n.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),l.object)}u(U,"revokeFor");export{Z as rollbackRun};
@@ -1,4 +1,4 @@
1
- var c=Object.defineProperty;var a=(o,r)=>c(o,"name",{value:r,configurable:!0});import{withCanvasWrite as d}from"../canvas/db.js";const s=720*60*6e4,R=`o.deleted_at IS NOT NULL AND o.deleted_at < ? AND o.type <> 'node'
1
+ var s=Object.defineProperty;var n=(o,r)=>s(o,"name",{value:r,configurable:!0});import{withCanvasWrite as c}from"../canvas/db.js";import{tryShareNodeDeletes as d}from"../graph/deletion.js";const R=720*60*6e4,S=`o.deleted_at IS NOT NULL AND o.deleted_at < ? AND o.type <> 'node'
2
2
  AND NOT EXISTS (SELECT 1 FROM objects x WHERE x.owner = o.id)
3
3
  AND NOT EXISTS (SELECT 1 FROM revisions r WHERE r.author = o.id)
4
- AND NOT EXISTS (SELECT 1 FROM object_kinds k WHERE k.owner = o.id AND EXISTS (SELECT 1 FROM objects t WHERE t.type = k.name))`;async function S(o,r){const E=new Date(o-s).toISOString();try{return await d(async e=>{const t=(await e.prepare(`SELECT o.id FROM objects o WHERE ${R} ORDER BY o.deleted_at, o.id LIMIT ?`).all(E,r)).map(i=>i.id);return t.length===0?0:(await e.prepare("DELETE FROM object_kinds WHERE owner = ANY(?::text[])").run(t),(await e.prepare("DELETE FROM objects WHERE id = ANY(?::text[]) AND deleted_at < ?").run(t,E)).changes)},{savepoint:!0})}catch(e){if(e.code==="23503")return 0;throw e}}a(S,"purgeFreeRows");async function N(o,r,E=async()=>!0,e=100){let t=0;for(;t<r&&await E();){const n=await S(o,Math.min(e,r-t));if(n===0)break;t+=n}return t}a(N,"purgeSoftDeleted");export{s as PURGE_RETENTION_MS,S as purgeFreeRows,N as purgeSoftDeleted};
4
+ AND NOT EXISTS (SELECT 1 FROM object_kinds k WHERE k.owner = o.id AND EXISTS (SELECT 1 FROM objects t WHERE t.type = k.name))`;async function p(o,r){const E=new Date(o-R).toISOString();try{return await c(async e=>{if(!await d(e))return 0;const t=(await e.prepare(`SELECT o.id FROM objects o WHERE ${S} ORDER BY o.deleted_at, o.id LIMIT ?`).all(E,r)).map(i=>i.id);return t.length===0?0:(await e.prepare("DELETE FROM object_kinds WHERE owner = ANY(?::text[])").run(t),(await e.prepare("DELETE FROM objects WHERE id = ANY(?::text[]) AND deleted_at < ?").run(t,E)).changes)},{savepoint:!0})}catch(e){if(e.code==="23503")return 0;throw e}}n(p,"purgeFreeRows");async function w(o,r,E=async()=>!0,e=100){let t=0;for(;t<r&&await E();){const a=await p(o,Math.min(e,r-t));if(a===0)break;t+=a}return t}n(w,"purgeSoftDeleted");export{R as PURGE_RETENTION_MS,p as purgeFreeRows,w as purgeSoftDeleted};
@@ -1,3 +1,3 @@
1
- var m=Object.defineProperty;var f=(c,e)=>m(c,"name",{value:e,configurable:!0});import{blobStore as O}from"../../core/blobs/index.js";import{openDb as R,withCanvasWrite as g}from"../../core/canvas/db.js";import{emitEvent as u}from"../../core/events/emit.js";import{operationIdContext as w}from"../../core/events/operation-id.js";import{RunError as b}from"../../core/runs/operations.js";import{storageClient as v,storageConfig as T}from"../../core/storage/client.js";import{deleteUploadRow as N,expireShares as y,markShareObjectDeleted as k,markUploadsDeletePending as L,pendingUploadDeletes as U,sharesOwingObjectDelete as A,staleUnusedUploads as I}from"../../core/storage/tables.js";import{runThrottledLane as x}from"./throttled-lane.js";const W=6e4,j=1440*6e4,S=200,M=5*6e4,D=25,F=["conversations","events","jobs","attachments"],C=3,G=f(c=>c instanceof b&&c.code==="storage_unavailable","unavailable");class q{static{f(this,"StorageDueWorkReconciler")}deps;constructor(e={config:T,client:v}){this.deps=e}run(e,r){if(!r.lifecycle.acceptsDetachedWork())return;const t=w.fresh(()=>x("storage-due-work","",e,W,M,async s=>{await this.pass(e,s)})).then(()=>{}).catch(s=>{w.fresh(()=>u({level:"error",event:"storage.due_work.failed",error:s}))});r.lifecycle.registerDetached(t)}async pass(e,r){const t={marked_uploads:0,expired_shares:0,deleted_uploads:0,deleted_share_objects:0,purged_nodes:0,failed:0};return t.purged_nodes=await this.purgeDeletedNodes(r),this.deps.config()&&await this.settleFileTransfers(e,t),(t.purged_nodes||t.marked_uploads||t.expired_shares||t.deleted_uploads||t.deleted_share_objects)&&u({level:"info",event:"storage.due_work.settled",outcome:"succeeded",fields:{...t}}),t}async purgeDeletedNodes(e){const r=await R(),t=e?.state?JSON.parse(e.state):null,s=await r.prepare(`SELECT id, deleted_at FROM objects WHERE type = 'node' AND deleted_at IS NOT NULL
1
+ var D=Object.defineProperty;var u=(c,e)=>D(c,"name",{value:e,configurable:!0});import{blobStore as O}from"../../core/blobs/index.js";import{openDb as R,withCanvasWrite as w}from"../../core/canvas/db.js";import{tryShareNodeDeletes as b}from"../../core/graph/deletion.js";import{emitEvent as h}from"../../core/events/emit.js";import{operationIdContext as g}from"../../core/events/operation-id.js";import{RunError as v}from"../../core/runs/operations.js";import{storageClient as T,storageConfig as N}from"../../core/storage/client.js";import{deleteUploadRow as y,expireShares as k,markShareObjectDeleted as L,markUploadsDeletePending as U,pendingUploadDeletes as A,sharesOwingObjectDelete as I,staleUnusedUploads as W}from"../../core/storage/tables.js";import{runThrottledLane as j}from"./throttled-lane.js";const x=6e4,M=1440*6e4,S=200,F=5*6e4,m=25,C=["conversations","events","jobs","attachments"],G=3,B=u(c=>c instanceof v&&c.code==="storage_unavailable","unavailable");class Q{static{u(this,"StorageDueWorkReconciler")}deps;constructor(e={config:N,client:T}){this.deps=e}run(e,r){if(!r.lifecycle.acceptsDetachedWork())return;const t=g.fresh(()=>j("storage-due-work","",e,x,F,async s=>{await this.pass(e,s)})).then(()=>{}).catch(s=>{g.fresh(()=>h({level:"error",event:"storage.due_work.failed",error:s}))});r.lifecycle.registerDetached(t)}async pass(e,r){const t={marked_uploads:0,expired_shares:0,deleted_uploads:0,deleted_share_objects:0,purged_nodes:0,failed:0};return t.purged_nodes=await this.purgeDeletedNodes(r),this.deps.config()&&await this.settleFileTransfers(e,t),(t.purged_nodes||t.marked_uploads||t.expired_shares||t.deleted_uploads||t.deleted_share_objects)&&h({level:"info",event:"storage.due_work.settled",outcome:"succeeded",fields:{...t}}),t}async purgeDeletedNodes(e){const r=await R(),t=e?.state?JSON.parse(e.state):null,s=await r.prepare(`SELECT id, deleted_at FROM objects WHERE type = 'node' AND deleted_at IS NOT NULL
2
2
  AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.run_id = objects.id)
3
- AND (deleted_at, id) > (?, ?) ORDER BY deleted_at, id LIMIT ?`).all(t?.deleted_at??"",t?.id??"",D);if(s.length===0)return t&&await e?.save(null),0;const _=await(this.deps.blobs??O)();let p=0,i=-1;for(const[a,{id:d}]of s.entries())try{for(const o of F)for(const l of await _.list(`${o}/${d}/`))o==="conversations"&&await r.prepare("SELECT 1 FROM conversation_parts WHERE blob_key = ? LIMIT 1").get(l)!==void 0||await _.delete(l);await g(async o=>{await o.prepare("DELETE FROM objects WHERE id = ? AND type = 'node' AND deleted_at IS NOT NULL").run(d)},{savepoint:!0}),p++}catch(o){o.code!=="23503"&&(i<0&&(i=a),u({level:"warn",event:"storage.due_work.node_purge_failed",error:o,fields:{node_id:d}}))}if(i>=0){const a=s[i-1];await e?.save(a?JSON.stringify({deleted_at:a.deleted_at,id:a.id}):e.state)}else{const a=s[s.length-1];await e?.save(s.length<D?null:JSON.stringify({deleted_at:a.deleted_at,id:a.id}))}return p}async settleFileTransfers(e,r){const t=new Date(e).toISOString(),{marked:s,expired:_}=await g(async a=>{const d=await I(new Date(e-j).toISOString(),a);return await L(d,a,t),{marked:d.length,expired:(await y(t,a)).length}});r.marked_uploads=s,r.expired_shares=_;const p=(await U()).slice(0,S),i=(await A()).slice(0,S);if(p.length||i.length){const a=this.deps.client();let d,o=0,l=!1;const h=f(async n=>{if(l)return!1;try{return await n(),o=0,!0}catch(E){return r.failed++,d??=E,o=G(E)?o+1:0,o>=C&&(l=!0),!1}},"attempt");for(const n of p)await h(()=>a.deleteUpload(n.upload_id))&&(await N(n.upload_id),r.deleted_uploads++);for(const n of i)await h(()=>a.deleteShare(n.share_id))&&(await k(n.share_id),r.deleted_share_objects++);d!==void 0&&u({level:"warn",event:"storage.due_work.deletes_failed",error:d,fields:{failed:r.failed,storage_unavailable:l}})}}}export{D as NODE_PURGE_BUDGET,C as STORAGE_DOWN_AFTER,S as STORAGE_DUE_WORK_BUDGET,W as STORAGE_DUE_WORK_INTERVAL_MS,q as StorageDueWorkReconciler,j as UNUSED_UPLOAD_TTL_MS};
3
+ AND (deleted_at, id) > (?, ?) ORDER BY deleted_at, id LIMIT ?`).all(t?.deleted_at??"",t?.id??"",m);if(s.length===0)return t&&await e?.save(null),0;const _=await(this.deps.blobs??O)();let f=0,n=-1;for(const[a,{id:o}]of s.entries())try{for(const d of C)for(const p of await _.list(`${d}/${o}/`))d==="conversations"&&await r.prepare("SELECT 1 FROM conversation_parts WHERE blob_key = ? LIMIT 1").get(p)!==void 0||await _.delete(p);await w(async d=>await b(d)?(await d.prepare("DELETE FROM objects WHERE id = ? AND type = 'node' AND deleted_at IS NOT NULL").run(o),!0):!1,{savepoint:!0})&&f++}catch(i){i.code!=="23503"&&(n<0&&(n=a),h({level:"warn",event:"storage.due_work.node_purge_failed",error:i,fields:{node_id:o}}))}if(n>=0){const a=s[n-1];await e?.save(a?JSON.stringify({deleted_at:a.deleted_at,id:a.id}):e.state)}else{const a=s[s.length-1];await e?.save(s.length<m?null:JSON.stringify({deleted_at:a.deleted_at,id:a.id}))}return f}async settleFileTransfers(e,r){const t=new Date(e).toISOString(),{marked:s,expired:_}=await w(async a=>{const o=await W(new Date(e-M).toISOString(),a);return await U(o,a,t),{marked:o.length,expired:(await k(t,a)).length}});r.marked_uploads=s,r.expired_shares=_;const f=(await A()).slice(0,S),n=(await I()).slice(0,S);if(f.length||n.length){const a=this.deps.client();let o,i=0,d=!1;const p=u(async l=>{if(d)return!1;try{return await l(),i=0,!0}catch(E){return r.failed++,o??=E,i=B(E)?i+1:0,i>=G&&(d=!0),!1}},"attempt");for(const l of f)await p(()=>a.deleteUpload(l.upload_id))&&(await y(l.upload_id),r.deleted_uploads++);for(const l of n)await p(()=>a.deleteShare(l.share_id))&&(await L(l.share_id),r.deleted_share_objects++);o!==void 0&&h({level:"warn",event:"storage.due_work.deletes_failed",error:o,fields:{failed:r.failed,storage_unavailable:d}})}}}export{m as NODE_PURGE_BUDGET,G as STORAGE_DOWN_AFTER,S as STORAGE_DUE_WORK_BUDGET,x as STORAGE_DUE_WORK_INTERVAL_MS,Q as StorageDueWorkReconciler,M as UNUSED_UPLOAD_TTL_MS};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.627",
3
+ "version": "0.3.628",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.627",
148
+ "@north-light/identity": "0.3.628",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.627",
3
+ "version": "0.3.628",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.627",
3
+ "version": "0.3.628",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.627",
9
+ "version": "0.3.628",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.627",
31
+ "@north-light/identity": "0.3.628",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.627",
11959
+ "version": "0.3.628",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.627",
11964
+ "version": "0.3.628",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.627",
11969
+ "version": "0.3.628",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.627",
11977
+ "version": "0.3.628",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.627",
11981
- "@north-light/identity": "0.3.627"
11980
+ "@north-light/api": "0.3.628",
11981
+ "@north-light/identity": "0.3.628"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.627",
11986
+ "version": "0.3.628",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.627",
11990
- "@north-light/identity": "0.3.627",
11991
- "@north-light/plugin": "0.3.627",
11989
+ "@north-light/api": "0.3.628",
11990
+ "@north-light/identity": "0.3.628",
11991
+ "@north-light/plugin": "0.3.628",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {