@north-light/cli 0.3.745 → 0.3.746

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.
@@ -39,6 +39,9 @@ export declare function dropExistingWatches(db: CanvasDb, schema: string, target
39
39
  /** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
40
40
  * row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
41
41
  export declare function dropExistingIdempotencyKeys(db: CanvasDb, schema: string, target: string): Promise<number>;
42
+ /** A staged idempotency key at least `IDEMPOTENCY_WINDOW_MS` old is already expired (`findIdempotent` ignores it and the daemon's sweep deletes it within a minute), so it is dropped before
43
+ * the copy: otherwise the sweep removes it between copy and verify and verify reports a difference. Returns the dropped rows. Runs before the pre-check. */
44
+ export declare function dropExpiredIdempotencyKeys(db: CanvasDb, schema: string): Promise<number>;
42
45
  /** The rows `fillEnvironments` created, as manifest keys per table, so rollback removes them and verify (which has no staged row for them) skips them. */
43
46
  export interface FilledRow {
44
47
  table: string;
@@ -1,14 +1,14 @@
1
- var D=Object.defineProperty;var E=(t,s)=>D(t,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as v,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as H}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const d=E((t,s)=>`${l(t)}.${l(s)}`,"sq");async function K(t,s,o){if(o.length===0)return 0;const e=E(c=>d(s,c),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const p=E(async(c,r,n,$=!1)=>{const R=await t.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(c)} WHERE ${n} AND ${l(r)} IS NOT NULL`).all();for(const{value:f}of R){const T=$?g(f,o):S(o,f);T!==f&&(await t.prepareUncached(`UPDATE ${e(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${n}`).run(T,f),a+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),a}E(K,"rewritePaths");async function B(t,s,o,e,i){if(o.length===0)return 0;const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
2
- AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:n}of p){const $=M(i,n),R=await e.get($);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const f=H(R,r,T=>S(o,T));f!==null&&(await e.put($,f),c+=1),await t.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((f??R).length,r)}return c}E(B,"rewriteConversationHeaders");async function J(t,s){const o=d(s,"human_requests"),e=E(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
3
- WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
- WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
5
- ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await t.prepareUncached(`UPDATE ${o} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
6
- request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(J,"rewriteRequestPaths");function g(t,s){const o=E(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(o):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,o(a)])):e,"walk");try{return JSON.stringify(o(JSON.parse(t)))}catch{return S(s,t)}}E(g,"rewriteJsonPaths");async function Y(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let c=0;for(const r of p){const n=await t.prepareUncached(`SELECT o.id FROM ${a("objects")} o JOIN ${a("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
7
- WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=n===void 0?void 0:await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,n.id);if($===void 0&&R===void 0)continue;const f=`${r.name}-${e}`;await t.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(f,r.id),n!==void 0&&await t.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(f,n.id),c+=1}return c}E(Y,"renameClashingProfiles");async function X(t,s,o,e){const i=await t.prepareUncached(`UPDATE ${d(s,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${d(o,"charges")} t
8
- WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}E(X,"renameClashingLegacyCharges");async function G(t,s,o){const e=`FROM ${d(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await t.prepareUncached(`DELETE FROM ${d(s,"watch_subscriptions")} u USING ${d(s,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${e})`).run(),a=await t.prepareUncached(`DELETE FROM ${d(s,"watches")} s WHERE EXISTS (SELECT 1 ${e})`).run();return{watches:Number(a.changes),watch_subscriptions:Number(i.changes)}}E(G,"dropExistingWatches");async function z(t,s,o){const e=await t.prepareUncached(`DELETE FROM ${d(s,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${d(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(e.changes)}E(z,"dropExistingIdempotencyKeys");async function Q(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=[],c=await t.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let n=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"){const $=await t.prepareUncached(`SELECT environment_id FROM ${d(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)n=$.environment_id;else{n=await U(t,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[n]},{table:"environments",key:[n]});for(const R of await t.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(n))p.push({table:"relations",key:[R.resource_type,R.resource_id,R.relation,R.subject_type,R.subject_id,R.subject_relation]})}}if(n===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await t.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(n,r.id)}return p}E(Q,"fillEnvironments");async function V(t,s,o,e){const i=E(c=>d(s,c),"S"),a={},p=E(async(c,r,...n)=>{const $=Number((await t.prepareUncached(r).run(...n)).changes);$>0&&(a[c]=(a[c]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await t.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await t.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[c,r]of Object.entries(v))await p(c,`DELETE FROM ${i(c)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,c);for(const c of o.tables.values())c.columns.includes("claimed_by")&&c.columns.includes("lease_expires_at")&&await t.prepareUncached(`UPDATE ${i(c.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}E(V,"pruneStaged");async function Z(t,s,o){const e=E(p=>d(s,p),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${d(o,"documents")} t WHERE t.object = d.object))`;await t.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
9
- CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await t.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
10
- COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
11
- FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await t.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await t.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(p=>({...p}))}E(Z,"takeRepoSyncedDocuments");const C={edges:["created_at"],relations:["created_at"]},b={charges:["payer","units","usd"]};async function ee(t,s,o,e,i,a,p){const c=E(n=>[...p.get(n)??[],...n==="profiles"?["environment_id"]:[],...C[n]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const n of i){const $=e.tables.get(n);if($===void 0||a.has(n)||$.primaryKey.length===0)continue;const R=$.primaryKey,f=R.some(u=>$.identity.includes(u)),T=R.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),y=f?"TRUE":R.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(n)??[]]);for(const u of e.uniqueKeys.filter(h=>h.table===n&&!h.columns.every(_=>I.has(_)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,_=u.columns.map(m=>`s.${l(m)} = t.${l(m)}`).join(" AND "),O=await t.prepareUncached(`SELECT ${u.columns.map(m=>`s.${l(m)}::text`).join(" || ',' || ")} AS value
12
- FROM (SELECT * FROM ${d(s,n)}${h}) s JOIN (SELECT * FROM ${d(o,n)}${h}) t ON ${_} AND (${y}) LIMIT 10`).all();O.length>0&&r.push({table:n,key:u.name,values:O.map(m=>m.value)});const A=f?"TRUE":R.map(m=>`a.${l(m)} IS DISTINCT FROM b.${l(m)}`).join(" OR "),L=await t.prepareUncached(`SELECT DISTINCT ${u.columns.map(m=>`a.${l(m)}::text`).join(" || ',' || ")} AS value
13
- FROM (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) b ON ${u.columns.map(m=>`a.${l(m)} = b.${l(m)}`).join(" AND ")} AND a.row_id < b.row_id AND (${A}) LIMIT 10`).all();L.length>0&&r.push({table:n,key:u.name,values:L.map(m=>m.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(n).includes(u)&&(b[n]?.includes(u)??!0));if(w.length>0&&!f){const u=w.map(_=>`s.${l(_)} IS DISTINCT FROM t.${l(_)}`).join(" OR "),h=await t.prepareUncached(`SELECT ${R.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
14
- FROM ${d(s,n)} s JOIN ${d(o,n)} t ON ${T} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:n,key:"primary key payload",values:h.map(_=>_.value)})}}if(r.length>0){const n=r[0];throw new N("pre-check","unique_conflict",`${n.table} ${n.key} collides ${n.staged===!0?"within the bundle":"with the target"}: ${n.values.join(", ")}`,{collisions:r})}}E(ee,"precheck");export{z as dropExistingIdempotencyKeys,G as dropExistingWatches,Q as fillEnvironments,ee as precheck,V as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,Z as takeRepoSyncedDocuments};
1
+ var A=Object.defineProperty;var E=(e,a)=>A(e,"name",{value:a,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as M,mapPath as S}from"../bundle/layout.js";import{IDEMPOTENCY_WINDOW_MS as g}from"../../runs/operations.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as H}from"../../conversation-store/row-store.js";import{runBlobKey as v}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const d=E((e,a)=>`${l(e)}.${l(a)}`,"sq");async function J(e,a,o){if(o.length===0)return 0;const t=E(c=>d(a,c),"S"),i=`(SELECT node_id FROM ${t("nodes")} WHERE status IN ('active', 'idle'))`;let s=0;const p=E(async(c,r,n,$=!1)=>{const m=await e.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${t(c)} WHERE ${n} AND ${l(r)} IS NOT NULL`).all();for(const{value:_}of m){const T=$?C(_,o):S(o,_);T!==_&&(await e.prepareUncached(`UPDATE ${t(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${n}`).run(T,_),s+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),s}E(J,"rewritePaths");async function Y(e,a,o,t,i){if(o.length===0)return 0;const s=E(r=>d(a,r),"S"),p=await e.prepareUncached(`SELECT conversation_id, blob_key FROM ${s("conversation_parts")} WHERE seq = 0
2
+ AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${s("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:n}of p){const $=v(i,n),m=await t.get($);if(m===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const _=H(m,r,T=>S(o,T));_!==null&&(await t.put($,_),c+=1),await e.prepareUncached(`UPDATE ${s("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((_??m).length,r)}return c}E(Y,"rewriteConversationHeaders");async function X(e,a){const o=d(a,"human_requests"),t=E(s=>`CASE WHEN ${s} IS NULL OR ${s} NOT LIKE '/%' THEN ${s}
3
+ WHEN rtrim(${s}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
+ WHEN ${s} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${s}, length(rtrim(request_dir, '/')) + 2)
5
+ ELSE 'requests/' || request_id || '/source/' || regexp_replace(${s}, '^.*/', '') END`,"moved"),i=await e.prepareUncached(`UPDATE ${o} SET file = ${t("file")}, presentation_dir = ${t("presentation_dir")},
6
+ request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(X,"rewriteRequestPaths");function C(e,a){const o=E(t=>typeof t=="string"?S(a,t):Array.isArray(t)?t.map(o):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([i,s])=>[i,o(s)])):t,"walk");try{return JSON.stringify(o(JSON.parse(e)))}catch{return S(a,e)}}E(C,"rewriteJsonPaths");async function G(e,a,o,t,i){const s=E(r=>d(a,r),"S"),p=await e.prepareUncached(`SELECT id, name FROM ${s("profiles")} ORDER BY id`).all();let c=0;for(const r of p){const n=await e.prepareUncached(`SELECT o.id FROM ${s("objects")} o JOIN ${s("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
7
+ WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await e.prepareUncached(`SELECT 1 AS found FROM ${d(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),m=n===void 0?void 0:await e.prepareUncached(`SELECT 1 AS found FROM ${d(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,n.id);if($===void 0&&m===void 0)continue;const _=`${r.name}-${t}`;await e.prepareUncached(`UPDATE ${s("profiles")} SET name = ? WHERE id = ?`).run(_,r.id),n!==void 0&&await e.prepareUncached(`UPDATE ${s("objects")} SET name = ? WHERE id = ?`).run(_,n.id),c+=1}return c}E(G,"renameClashingProfiles");async function z(e,a,o,t){const i=await e.prepareUncached(`UPDATE ${d(a,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${d(o,"charges")} t
8
+ WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(t);return Number(i.changes)}E(z,"renameClashingLegacyCharges");async function Q(e,a,o){const t=`FROM ${d(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await e.prepareUncached(`DELETE FROM ${d(a,"watch_subscriptions")} u USING ${d(a,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${t})`).run(),s=await e.prepareUncached(`DELETE FROM ${d(a,"watches")} s WHERE EXISTS (SELECT 1 ${t})`).run();return{watches:Number(s.changes),watch_subscriptions:Number(i.changes)}}E(Q,"dropExistingWatches");async function V(e,a,o){const t=await e.prepareUncached(`DELETE FROM ${d(a,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${d(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(t.changes)}E(V,"dropExistingIdempotencyKeys");async function Z(e,a){const o=await e.prepareUncached(`DELETE FROM ${d(a,"idempotency_keys")} WHERE created_at <= ?`).run(new Date(Date.now()-g).toISOString());return Number(o.changes)}E(Z,"dropExpiredIdempotencyKeys");async function ee(e,a,o,t,i){const s=E(r=>d(a,r),"S"),p=[],c=await e.prepareUncached(`SELECT id, grantee FROM ${s("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let n=t.kind==="machine"?t.environmentObject??null:null;if(t.kind==="hosted"){const $=await e.prepareUncached(`SELECT environment_id FROM ${d(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)n=$.environment_id;else{n=await U(e,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[n]},{table:"environments",key:[n]});for(const m of await e.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(n))p.push({table:"relations",key:[m.resource_type,m.resource_id,m.relation,m.subject_type,m.subject_id,m.subject_relation]})}}if(n===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await e.prepareUncached(`UPDATE ${s("profiles")} SET environment_id = ? WHERE id = ?`).run(n,r.id)}return p}E(ee,"fillEnvironments");async function te(e,a,o,t){const i=E(c=>d(a,c),"S"),s={},p=E(async(c,r,...n)=>{const $=Number((await e.prepareUncached(r).run(...n)).changes);$>0&&(s[c]=(s[c]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),t.kind==="hosted"&&(await e.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await e.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[c,r]of Object.entries(M))await p(c,`DELETE FROM ${i(c)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,t.installId,c);for(const c of o.tables.values())c.columns.includes("claimed_by")&&c.columns.includes("lease_expires_at")&&await e.prepareUncached(`UPDATE ${i(c.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return s}E(te,"pruneStaged");async function ne(e,a,o){const t=E(p=>d(a,p),"S"),i=`(SELECT d.object FROM ${t("documents")} d WHERE EXISTS (SELECT 1 FROM ${d(o,"documents")} t WHERE t.object = d.object))`;await e.exec(`CREATE TABLE ${t("_arr_revisions")} AS SELECT r.* FROM ${t("revisions")} r WHERE r.document IN ${i};
9
+ CREATE TABLE ${t("_arr_parents")} AS SELECT p.* FROM ${t("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${i})`);const s=await e.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
10
+ COALESCE((SELECT array_agg(p.parent) FROM ${t("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
11
+ FROM ${t("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await e.prepareUncached(`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${i})`).run(),await e.prepareUncached(`DELETE FROM ${t("revisions")} WHERE document IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${t("objects")} WHERE id IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${t("documents")} WHERE object IN ${i}`).run(),s.map(p=>({...p}))}E(ne,"takeRepoSyncedDocuments");const W={edges:["created_at"],relations:["created_at"]},b={charges:["payer","units","usd"]};async function re(e,a,o,t,i,s,p){const c=E(n=>[...p.get(n)??[],...n==="profiles"?["environment_id"]:[],...W[n]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const n of i){const $=t.tables.get(n);if($===void 0||s.has(n)||$.primaryKey.length===0)continue;const m=$.primaryKey,_=m.some(u=>$.identity.includes(u)),T=m.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),L=_?"TRUE":m.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(n)??[]]);for(const u of t.uniqueKeys.filter(f=>f.table===n&&!f.columns.every(h=>I.has(h)))){const f=u.predicate===null?"":` WHERE ${u.predicate}`,h=u.columns.map(R=>`s.${l(R)} = t.${l(R)}`).join(" AND "),O=await e.prepareUncached(`SELECT ${u.columns.map(R=>`s.${l(R)}::text`).join(" || ',' || ")} AS value
12
+ FROM (SELECT * FROM ${d(a,n)}${f}) s JOIN (SELECT * FROM ${d(o,n)}${f}) t ON ${h} AND (${L}) LIMIT 10`).all();O.length>0&&r.push({table:n,key:u.name,values:O.map(R=>R.value)});const D=_?"TRUE":m.map(R=>`a.${l(R)} IS DISTINCT FROM b.${l(R)}`).join(" OR "),y=await e.prepareUncached(`SELECT DISTINCT ${u.columns.map(R=>`a.${l(R)}::text`).join(" || ',' || ")} AS value
13
+ FROM (SELECT ctid AS row_id, * FROM ${d(a,n)}${f}) a JOIN (SELECT ctid AS row_id, * FROM ${d(a,n)}${f}) b ON ${u.columns.map(R=>`a.${l(R)} = b.${l(R)}`).join(" AND ")} AND a.row_id < b.row_id AND (${D}) LIMIT 10`).all();y.length>0&&r.push({table:n,key:u.name,values:y.map(R=>R.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(n).includes(u)&&(b[n]?.includes(u)??!0));if(w.length>0&&!_){const u=w.map(h=>`s.${l(h)} IS DISTINCT FROM t.${l(h)}`).join(" OR "),f=await e.prepareUncached(`SELECT ${m.map(h=>`s.${l(h)}::text`).join(" || ',' || ")} AS value
14
+ FROM ${d(a,n)} s JOIN ${d(o,n)} t ON ${T} WHERE ${u} LIMIT 10`).all();f.length>0&&r.push({table:n,key:"primary key payload",values:f.map(h=>h.value)})}}if(r.length>0){const n=r[0];throw new N("pre-check","unique_conflict",`${n.table} ${n.key} collides ${n.staged===!0?"within the bundle":"with the target"}: ${n.values.join(", ")}`,{collisions:r})}}E(re,"precheck");export{V as dropExistingIdempotencyKeys,Q as dropExistingWatches,Z as dropExpiredIdempotencyKeys,ee as fillEnvironments,re as precheck,te as pruneStaged,z as renameClashingLegacyCharges,G as renameClashingProfiles,Y as rewriteConversationHeaders,J as rewritePaths,X as rewriteRequestPaths,ne as takeRepoSyncedDocuments};
@@ -1,3 +1,3 @@
1
- var Q=Object.defineProperty;var m=(e,r)=>Q(e,"name",{value:r,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as A}from"../../canvas/person.js";import{insertImportedRevisions as Z}from"../../graph/documents.js";import{getById as x}from"../../graph/objects.js";import{bundleKeys as B,decodeRows as ee,rowKeys as L,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{appendManifest as N,copyRows as ne,decodeKeys as ie}from"./copy.js";import{pruneStaged as se,precheck as re,dropExistingIdempotencyKeys as oe,dropExistingWatches as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ce,rewriteConversationHeaders as ue,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Se}from"./bind.js";import{deleteBlobs as ve,deleteRunBlobs as Ee,deleteRunPrefix as Re,moveRunBlobs as Ie}from"./blobs.js";import{dropStubRows as Oe,findFleetGrant as Pe,grantMissing as je,mapProfileIds as ke,renameClashingRepos as Te,rewriteIds as Ce,rewritePerson as Me,scopeRepoIdentities as De}from"./rewrite.js";import{dropStaging as W,ImportLaneError as g,stage as Ae,stagingSchema as Be,targetSchema as Le}from"./stage.js";import{verifyRun as Ne}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as Ke}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{openImportGrants as Ge}from"./open-grants.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ye}from"../../events/emit.js";import{ClaimLostError as ze}from"../../../daemon/reconcilers/row-claim.js";const Qe=10*6e4,Ve=30*6e4,R=m(()=>new Date().toISOString(),"now"),K=m(async(e,r)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(r,e)},"setStep");async function Xe(e,r){const i=await e.get(B.source(r));if(i===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(i.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Xe,"readSource");async function Ze(e,r,i,a,n,d,p){const o=[];for(const t of L(i.run_id,"grants",a)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ee(c))}if(o.length===0)return;const w=o.map(t=>({sub:_e(t.sub,a.person,i.person,"grants.sub"),grantee:t.grantee}));await p(i.run_id);const f=[];for(const t of w)await Pe(r,n,d,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw je(f)}m(Ze,"ensureGrants");async function Ot(e,r,i={}){const a=i.blobs??await X(),n=await E(),d=Be(e.run_id);let p="start";const o=m(async t=>{p=t,await r.assertOwned(),await K(e.run_id,t),await i.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Xe(a,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Le(n),I=[...$e],h=await ae(n,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],k=i.fleetRuntime??process.env.CRTR_RUNTIME??null;await ge(n,c,t.person,e.person),await o("open-grants"),await Ze(a,n,e,t,c,k,i.openGrants??Ge),await o("publish-plugins");const H=await Ue(a,e.run_id),S=await A(e.person,()=>qe(H));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Qe)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await r.assertOwned(),await K(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await o("stage");const U=await Ae(n,e.run_id,t.counts,s=>L(e.run_id,s,t),s=>a.get(s));for(const[s,u]of Object.entries(U))l[s]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:n,schema:d,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[s,u]of Object.entries(await he(_)))b(l,s,u);for(const[s,u]of Object.entries(await be(_)))b(l,s,u);await o("rewrite-person"),await Me(_),await De(_),await o("prune");const F=await se(n,d,h,t),v=t.kind==="hosted"?We(t.pathPrefixes??[]):[];await o("rewrite-paths"),await le(n,d,v),await ue(n,d,v,a,e.run_id),await fe(n,d),await Se(_);const J=await ke(_);await ce(n,d,c,t.installId,e.person),await o("rewrite-ids");const T=await Ce(_,J);await o("drop");const G=await me(n,d,c),q=await Oe(_);for(const[s,u]of Object.entries({...F}))b(l,s,u);for(const[s,u]of Object.entries(q))b(l,s,u);for(const[s,u]of Object.entries(await we(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,s,u);await ye(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Te(_),await pe(n,d,c,t.installId);for(const[s,u]of Object.entries(await de(n,d,c)))b(l,s,u);b(l,"idempotency_keys",await oe(n,d,c)),await o("pre-check");const $=new Map([["messages",["seq"]],...te.map(s=>[s,["seq"]])]);await re(n,d,c,h,I,new Set,$),await o("blobs"),await Ie(n,d,c,e.person,a,e.run_id,f),await o("copy"),await A(e.person,()=>D(async s=>{await r.assertOwned({extendLeaseMs:Ve});const u=await ne({db:s,runId:e.run_id,schema:d,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await tt(s,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Ke(s,d,e.run_id,t);const M=await Je({db:s,blobs:a,runId:e.run_id,person:e.person,objectMap:T.object});for(const[Y,z]of Object.entries(M.inserted))u.inserted[Y]=z.length;return P.push(...M.unresolvedPlugins),await s.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...et(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),w=!0,await i.atStep?.("committed")}await o("verify");const y=await Ne(n,e.run_id,d,c,h,t.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=B.manifest(e.run_id);await a.put(O,await at(e.run_id)),await W(n,e.run_id);for(const l of He(e.run_id))await a.delete(l);await Ee(a,e.run_id),await D(async l=>{await Fe(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof ze)throw t;const c=xe(t,p);Ye({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await W(n,e.run_id).catch(()=>{}),w||await ve(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}m(Ot,"processRun");function xe(e,r){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:r,code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}m(xe,"failureOf");function b(e,r,i){(e[r]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=i}m(b,"addDropped");function et(e,r){for(const[i,a]of Object.entries(r.inserted))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[i,a]of Object.entries(r.mapped))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(et,"withInserted");async function tt(e,r,i){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(i.map(p=>p.rev_id)))).map(p=>p.rev_id)),n=i.filter(p=>!a.has(p.rev_id)),d=new Map;for(const p of i)d.set(p.document,[...d.get(p.document)??[],p]);for(const[p,o]of d){const w=await x(e,p);w!==null&&await Z(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await N(e,r,"revisions",n.map(p=>[p.rev_id])),await N(e,r,"revision_parents",n.flatMap(p=>p.parents.map(o=>[p.rev_id,o]))),n.length}m(tt,"arrive");async function at(e){const i=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return V(Buffer.from(i.map(a=>JSON.stringify({table:a.table_name,keys:ie(a.inserted_keys)})).join(`
1
+ var Q=Object.defineProperty;var m=(e,r)=>Q(e,"name",{value:r,configurable:!0});import{zstdCompressSync as x}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as A}from"../../canvas/person.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as B,decodeRows as ee,rowKeys as L,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{appendManifest as N,copyRows as ne,decodeKeys as ie}from"./copy.js";import{pruneStaged as se,precheck as re,dropExistingIdempotencyKeys as oe,dropExpiredIdempotencyKeys as de,dropExistingWatches as pe,renameClashingLegacyCharges as ce,renameClashingProfiles as ue,rewriteConversationHeaders as le,rewritePaths as fe,rewriteRequestPaths as me,takeRepoSyncedDocuments as _e}from"./prepare.js";import{boundSub as we,dropRefusedMessages as ge,checkSourcePerson as be,checkStagedBlobKeys as he,checkStagedPersons as ye,checkStagedReferences as Se,checkStagedRequestKeys as ve}from"./bind.js";import{deleteBlobs as Ee,deleteRunBlobs as Re,deleteRunPrefix as Ie,moveRunBlobs as Oe}from"./blobs.js";import{dropStubRows as Pe,findFleetGrant as je,grantMissing as ke,mapProfileIds as Te,renameClashingRepos as Ce,rewriteIds as Me,rewritePerson as De,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as K,ImportLaneError as g,stage as Be,stagingSchema as Le,targetSchema as Ne}from"./stage.js";import{verifyRun as Ke}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ue,readPluginsStore as Fe,recordImportedActivations as Je,writeStores as Ge}from"./stores.js";import{openImportGrants as qe}from"./open-grants.js";import{publishImportedPlugins as $e}from"./publish-plugins.js";import{COPIED_TABLES as Ye}from"../bundle/layout.js";import{emitEvent as ze}from"../../events/emit.js";import{ClaimLostError as Qe}from"../../../daemon/reconcilers/row-claim.js";const xe=10*6e4,Ve=30*6e4,R=m(()=>new Date().toISOString(),"now"),W=m(async(e,r)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(r,e)},"setStep");async function Xe(e,r){const i=await e.get(B.source(r));if(i===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(i.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}m(Xe,"readSource");async function Ze(e,r,i,n,a,o,p){const d=[];for(const t of L(i.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);d.push(...ee(c))}if(d.length===0)return;const w=d.map(t=>({sub:we(t.sub,n.person,i.person,"grants.sub"),grantee:t.grantee}));await p(i.run_id);const f=[];for(const t of w)await je(r,a,o,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw ke(f)}m(Ze,"ensureGrants");async function Pt(e,r,i={}){const n=i.blobs??await V(),a=await E(),o=Le(e.run_id);let p="start";const d=m(async t=>{p=t,await r.assertOwned(),await W(e.run_id,t),await i.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Xe(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Ne(a),I=[...Ye],h=await ae(a,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],k=i.fleetRuntime??process.env.CRTR_RUNTIME??null;await be(a,c,t.person,e.person),await d("open-grants"),await Ze(n,a,e,t,c,k,i.openGrants??qe),await d("publish-plugins");const H=await Fe(n,e.run_id),S=await A(e.person,()=>$e(H));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=xe)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await r.assertOwned(),await W(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await d("stage");const U=await Be(a,e.run_id,t.counts,s=>L(e.run_id,s,t),s=>n.get(s));for(const[s,u]of Object.entries(U))l[s]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:a,schema:o,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await d("bind-staged");for(const[s,u]of Object.entries(await ye(_)))b(l,s,u);for(const[s,u]of Object.entries(await he(_)))b(l,s,u);await d("rewrite-person"),await De(_),await Ae(_),await d("prune");const F=await se(a,o,h,t),v=t.kind==="hosted"?We(t.pathPrefixes??[]):[];await d("rewrite-paths"),await fe(a,o,v),await le(a,o,v,n,e.run_id),await me(a,o),await ve(_);const J=await Te(_);await ue(a,o,c,t.installId,e.person),await d("rewrite-ids");const T=await Me(_,J);await d("drop");const G=await _e(a,o,c),q=await Pe(_);for(const[s,u]of Object.entries({...F}))b(l,s,u);for(const[s,u]of Object.entries(q))b(l,s,u);for(const[s,u]of Object.entries(await ge(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,s,u);await Se(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Ce(_),await ce(a,o,c,t.installId);for(const[s,u]of Object.entries(await pe(a,o,c)))b(l,s,u);b(l,"idempotency_keys",await oe(a,o,c)),b(l,"idempotency_keys",await de(a,o)),await d("pre-check");const $=new Map([["messages",["seq"]],...te.map(s=>[s,["seq"]])]);await re(a,o,c,h,I,new Set,$),await d("blobs"),await Oe(a,o,c,e.person,n,e.run_id,f),await d("copy"),await A(e.person,()=>D(async s=>{await r.assertOwned({extendLeaseMs:Ve});const u=await ne({db:s,runId:e.run_id,schema:o,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await at(s,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(s,o,e.run_id,t);const M=await Ge({db:s,blobs:n,runId:e.run_id,person:e.person,objectMap:T.object});for(const[Y,z]of Object.entries(M.inserted))u.inserted[Y]=z.length;return P.push(...M.unresolvedPlugins),await s.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...tt(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),w=!0,await i.atStep?.("committed")}await d("verify");const y=await Ke(a,e.run_id,o,c,h,t.installId);if(await a.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await d("manifest");const O=B.manifest(e.run_id);await n.put(O,await nt(e.run_id)),await K(a,e.run_id);for(const l of Ue(e.run_id))await n.delete(l);await Re(n,e.run_id),await D(async l=>{await Je(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof Qe)throw t;const c=et(t,p);ze({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await K(a,e.run_id).catch(()=>{}),w||await Ee(n,f,!0),await a.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Ie(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}m(Pt,"processRun");function et(e,r){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:r,code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}m(et,"failureOf");function b(e,r,i){(e[r]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=i}m(b,"addDropped");function tt(e,r){for(const[i,n]of Object.entries(r.inserted))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[i,n]of Object.entries(r.mapped))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}m(tt,"withInserted");async function at(e,r,i){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(i.map(p=>p.rev_id)))).map(p=>p.rev_id)),a=i.filter(p=>!n.has(p.rev_id)),o=new Map;for(const p of i)o.set(p.document,[...o.get(p.document)??[],p]);for(const[p,d]of o){const w=await Z(e,p);w!==null&&await X(e,w,d.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await N(e,r,"revisions",a.map(p=>[p.rev_id])),await N(e,r,"revision_parents",a.flatMap(p=>p.parents.map(d=>[p.rev_id,d]))),a.length}m(at,"arrive");async function nt(e){const i=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return x(Buffer.from(i.map(n=>JSON.stringify({table:n.table_name,keys:ie(n.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}m(at,"manifestFile");export{Ve as COPY_LEASE_MS,Qe as GRANT_WAIT_MS,Ot as processRun};
3
+ `))}m(nt,"manifestFile");export{Ve as COPY_LEASE_MS,xe as GRANT_WAIT_MS,Pt as processRun};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.745",
3
+ "version": "0.3.746",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.745",
162
- "@north-light/plugin": "0.3.745",
161
+ "@north-light/identity": "0.3.746",
162
+ "@north-light/plugin": "0.3.746",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -2,6 +2,7 @@
2
2
  // repo-synced documents, and the pre-check (design-import, "Import lane"). All SQL names the staging schema explicitly.
3
3
  import { createProfileBlaxelEnvironment } from '../../environments.js';
4
4
  import { KEY_MAPPED_TABLES, mapPath } from '../bundle/layout.js';
5
+ import { IDEMPOTENCY_WINDOW_MS } from '../../runs/operations.js';
5
6
  import { ImportLaneError } from './stage.js';
6
7
  import { withHeaderCwd } from '../../conversation-store/row-store.js';
7
8
  import { runBlobKey } from '../bundle/blob-keys.js';
@@ -126,6 +127,12 @@ export async function dropExistingIdempotencyKeys(db, schema, target) {
126
127
  const done = await db.prepareUncached(`DELETE FROM ${sq(schema, 'idempotency_keys')} s WHERE EXISTS (SELECT 1 FROM ${sq(target, 'idempotency_keys')} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();
127
128
  return Number(done.changes);
128
129
  }
130
+ /** A staged idempotency key at least `IDEMPOTENCY_WINDOW_MS` old is already expired (`findIdempotent` ignores it and the daemon's sweep deletes it within a minute), so it is dropped before
131
+ * the copy: otherwise the sweep removes it between copy and verify and verify reports a difference. Returns the dropped rows. Runs before the pre-check. */
132
+ export async function dropExpiredIdempotencyKeys(db, schema) {
133
+ const done = await db.prepareUncached(`DELETE FROM ${sq(schema, 'idempotency_keys')} WHERE created_at <= ?`).run(new Date(Date.now() - IDEMPOTENCY_WINDOW_MS).toISOString());
134
+ return Number(done.changes);
135
+ }
129
136
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
130
137
  * absent). Runs in the copy transaction: it writes target objects. */
131
138
  export async function fillEnvironments(tx, schema, target, source, person) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.745",
3
+ "version": "0.3.746",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.745",
3
+ "version": "0.3.746",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.745",
3
+ "version": "0.3.746",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.745",
31
- "@north-light/identity": "0.3.745"
30
+ "@north-light/api": "0.3.746",
31
+ "@north-light/identity": "0.3.746"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.745",
3
+ "version": "0.3.746",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.745",
9
+ "version": "0.3.746",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
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.745",
32
- "@north-light/plugin": "0.3.745",
31
+ "@north-light/identity": "0.3.746",
32
+ "@north-light/plugin": "0.3.746",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.745",
11905
+ "version": "0.3.746",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.745",
11910
+ "version": "0.3.746",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.745",
11915
+ "version": "0.3.746",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.745",
11923
+ "version": "0.3.746",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.745",
11927
- "@north-light/identity": "0.3.745"
11926
+ "@north-light/api": "0.3.746",
11927
+ "@north-light/identity": "0.3.746"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.745",
11932
+ "version": "0.3.746",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.745",
11936
- "@north-light/identity": "0.3.745",
11937
- "@north-light/plugin": "0.3.745",
11935
+ "@north-light/api": "0.3.746",
11936
+ "@north-light/identity": "0.3.746",
11937
+ "@north-light/plugin": "0.3.746",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {