@north-light/cli 0.3.739 → 0.3.741

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.
@@ -30,6 +30,12 @@ export declare function renameClashingProfiles(db: CanvasDb, schema: string, tar
30
30
  * different amounts. A staged one whose id the target holds with a different payer, units or usd is renamed `<id>:install-<install id>`; one the target holds unchanged keeps its
31
31
  * id and is skipped by the copy. A second load of the same bundle derives the same id. Runs before the pre-check. */
32
32
  export declare function renameClashingLegacyCharges(db: CanvasDb, schema: string, target: string, installId: string): Promise<number>;
33
+ /** A staged watch whose (watcher, object) the target already holds is already imported (a hosted person's nodes watching shared objects): it and its subscriptions are
34
+ * dropped, the target's rows stand. Only this key is skipped; any other unique conflict still fails the pre-check. Returns the dropped watches and subscriptions. Runs before the pre-check. */
35
+ export declare function dropExistingWatches(db: CanvasDb, schema: string, target: string): Promise<{
36
+ watches: number;
37
+ watch_subscriptions: number;
38
+ }>;
33
39
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
34
40
  * absent). Runs in the copy transaction: it writes target objects. */
35
41
  export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<number>;
@@ -1,14 +1,14 @@
1
- var D=Object.defineProperty;var d=(n,o)=>D(n,"name",{value:o,configurable:!0});import{createProfileBlaxelEnvironment as v}from"../../environments.js";import{KEY_MAPPED_TABLES as U,mapPath as N}from"../bundle/layout.js";import{ImportLaneError as S}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as H}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const $=d((n,o)=>`${l(n)}.${l(o)}`,"sq");async function K(n,o,c){if(c.length===0)return 0;const e=d(s=>$(o,s),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=d(async(s,r,t,u=!1)=>{const R=await n.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(s)} WHERE ${t} AND ${l(r)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?M(m,c):N(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(s)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${t}`).run(h,m),a+=1)}},"apply");return await E("nodes","cwd",`node_id IN ${i}`),await E("worktrees","path",`node_id IN ${i}`),await E("worktrees","repo_root",`node_id IN ${i}`),await E("crons","cwd",`anchor_node IN ${i}`),await E("provider_approvals","prepared_files","TRUE",!0),await E("upload_uses","path",`run_id IN ${i}`),a}d(K,"rewritePaths");async function B(n,o,c,e,i){if(c.length===0)return 0;const a=d(r=>$(o,r),"S"),E=await n.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 s=0;for(const{conversation_id:r,blob_key:t}of E){const u=H(i,t),R=await e.get(u);if(R===null)throw new S("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${r} cannot be rewritten`);const m=C(R,r,h=>N(c,h));m!==null&&(await e.put(u,m),s+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((m??R).length,r)}return s}d(B,"rewriteConversationHeaders");async function J(n,o){const c=$(o,"human_requests"),e=d(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
1
+ var D=Object.defineProperty;var E=(n,s)=>D(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as v,mapPath as N}from"../bundle/layout.js";import{ImportLaneError as _}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as H}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const p=E((n,s)=>`${l(n)}.${l(s)}`,"sq");async function K(n,s,o){if(o.length===0)return 0;const e=E(c=>p(s,c),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const d=E(async(c,r,t,$=!1)=>{const m=await n.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(c)} WHERE ${t} AND ${l(r)} IS NOT NULL`).all();for(const{value:f}of m){const S=$?M(f,o):N(o,f);S!==f&&(await n.prepareUncached(`UPDATE ${e(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${t}`).run(S,f),a+=1)}},"apply");return await d("nodes","cwd",`node_id IN ${i}`),await d("worktrees","path",`node_id IN ${i}`),await d("worktrees","repo_root",`node_id IN ${i}`),await d("crons","cwd",`anchor_node IN ${i}`),await d("provider_approvals","prepared_files","TRUE",!0),await d("upload_uses","path",`run_id IN ${i}`),a}E(K,"rewritePaths");async function B(n,s,o,e,i){if(o.length===0)return 0;const a=E(r=>p(s,r),"S"),d=await n.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:t}of d){const $=H(i,t),m=await e.get($);if(m===null)throw new _("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const f=C(m,r,S=>N(o,S));f!==null&&(await e.put($,f),c+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((f??m).length,r)}return c}E(B,"rewriteConversationHeaders");async function J(n,s){const o=p(s,"human_requests"),e=E(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
3
3
  WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
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 n.prepareUncached(`UPDATE ${c} 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)}d(J,"rewriteRequestPaths");function M(n,o){const c=d(e=>typeof e=="string"?N(o,e):Array.isArray(e)?e.map(c):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,c(a)])):e,"walk");try{return JSON.stringify(c(JSON.parse(n)))}catch{return N(o,n)}}d(M,"rewriteJsonPaths");async function Y(n,o,c,e,i){const a=d(r=>$(o,r),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let s=0;for(const r of E){const t=await n.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),u=await n.prepareUncached(`SELECT 1 AS found FROM ${$(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=t===void 0?void 0:await n.prepareUncached(`SELECT 1 AS found FROM ${$(c,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,t.id);if(u===void 0&&R===void 0)continue;const m=`${r.name}-${e}`;await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(m,r.id),t!==void 0&&await n.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(m,t.id),s+=1}return s}d(Y,"renameClashingProfiles");async function X(n,o,c,e){const i=await n.prepareUncached(`UPDATE ${$(o,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${$(c,"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)}d(X,"renameClashingLegacyCharges");async function z(n,o,c,e,i){const a=d(r=>$(o,r),"S");let E=0;const s=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of s){let t=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(t=(await n.prepareUncached(`SELECT environment_id FROM ${$(c,"profiles")} WHERE id = ?`).get(r.id))?.environment_id??await v(n,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i})),t===null)throw new S("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(t,r.id),E+=1}return E}d(z,"fillEnvironments");async function G(n,o,c,e){const i=d(s=>$(o,s),"S"),a={},E=d(async(s,r,...t)=>{const u=Number((await n.prepareUncached(r).run(...t)).changes);u>0&&(a[s]=(a[s]??0)+u)},"del");await E("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[s,r]of Object.entries(U))await E(s,`DELETE FROM ${i(s)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,s);for(const s of c.tables.values())s.columns.includes("claimed_by")&&s.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(s.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}d(G,"pruneStaged");async function Q(n,o,c){const e=d(E=>$(o,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${$(c,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
5
+ ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await n.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 M(n,s){const o=E(e=>typeof e=="string"?N(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(n)))}catch{return N(s,n)}}E(M,"rewriteJsonPaths");async function Y(n,s,o,e,i){const a=E(r=>p(s,r),"S"),d=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let c=0;for(const r of d){const t=await n.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 n.prepareUncached(`SELECT 1 AS found FROM ${p(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),m=t===void 0?void 0:await n.prepareUncached(`SELECT 1 AS found FROM ${p(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,t.id);if($===void 0&&m===void 0)continue;const f=`${r.name}-${e}`;await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(f,r.id),t!==void 0&&await n.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(f,t.id),c+=1}return c}E(Y,"renameClashingProfiles");async function X(n,s,o,e){const i=await n.prepareUncached(`UPDATE ${p(s,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${p(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(n,s,o){const e=`FROM ${p(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await n.prepareUncached(`DELETE FROM ${p(s,"watch_subscriptions")} u USING ${p(s,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${e})`).run(),a=await n.prepareUncached(`DELETE FROM ${p(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(n,s,o,e,i){const a=E(r=>p(s,r),"S");let d=0;const c=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let t=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(t=(await n.prepareUncached(`SELECT environment_id FROM ${p(o,"profiles")} WHERE id = ?`).get(r.id))?.environment_id??await U(n,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i})),t===null)throw new _("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(t,r.id),d+=1}return d}E(z,"fillEnvironments");async function Q(n,s,o,e){const i=E(c=>p(s,c),"S"),a={},d=E(async(c,r,...t)=>{const $=Number((await n.prepareUncached(r).run(...t)).changes);$>0&&(a[c]=(a[c]??0)+$)},"del");await d("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.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 d(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 n.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(Q,"pruneStaged");async function V(n,s,o){const e=E(d=>p(s,d),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${p(o,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
9
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 n.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
10
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 n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(E=>({...E}))}d(Q,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},F={charges:["payer","units","usd"]};async function V(n,o,c,e,i,a,E){const s=d(t=>[...E.get(t)??[],...t==="profiles"?["environment_id"]:[],...g[t]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const t of i){const u=e.tables.get(t);if(u===void 0||a.has(t)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(p=>u.identity.includes(p)),h=R.map(p=>`s.${l(p)} = t.${l(p)}`).join(" AND "),I=m?"TRUE":R.map(p=>`s.${l(p)} IS DISTINCT FROM t.${l(p)}`).join(" OR "),y=new Set([...u.identity,...E.get(t)??[]]);for(const p of e.uniqueKeys.filter(T=>T.table===t&&!T.columns.every(_=>y.has(_)))){const T=p.predicate===null?"":` WHERE ${p.predicate}`,_=p.columns.map(f=>`s.${l(f)} = t.${l(f)}`).join(" AND "),w=await n.prepareUncached(`SELECT ${p.columns.map(f=>`s.${l(f)}::text`).join(" || ',' || ")} AS value
12
- FROM (SELECT * FROM ${$(o,t)}${T}) s JOIN (SELECT * FROM ${$(c,t)}${T}) t ON ${_} AND (${I}) LIMIT 10`).all();w.length>0&&r.push({table:t,key:p.name,values:w.map(f=>f.value)});const A=m?"TRUE":R.map(f=>`a.${l(f)} IS DISTINCT FROM b.${l(f)}`).join(" OR "),L=await n.prepareUncached(`SELECT DISTINCT ${p.columns.map(f=>`a.${l(f)}::text`).join(" || ',' || ")} AS value
13
- FROM (SELECT ctid AS row_id, * FROM ${$(o,t)}${T}) a JOIN (SELECT ctid AS row_id, * FROM ${$(o,t)}${T}) b ON ${p.columns.map(f=>`a.${l(f)} = b.${l(f)}`).join(" AND ")} AND a.row_id < b.row_id AND (${A}) LIMIT 10`).all();L.length>0&&r.push({table:t,key:p.name,values:L.map(f=>f.value),staged:!0})}const O=u.columns.filter(p=>!u.identity.includes(p)&&!s(t).includes(p)&&(F[t]?.includes(p)??!0));if(O.length>0&&!m){const p=O.map(_=>`s.${l(_)} IS DISTINCT FROM t.${l(_)}`).join(" OR "),T=await n.prepareUncached(`SELECT ${R.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
14
- FROM ${$(o,t)} s JOIN ${$(c,t)} t ON ${h} WHERE ${p} LIMIT 10`).all();T.length>0&&r.push({table:t,key:"primary key payload",values:T.map(_=>_.value)})}}if(r.length>0){const t=r[0];throw new S("pre-check","unique_conflict",`${t.table} ${t.key} collides ${t.staged===!0?"within the bundle":"with the target"}: ${t.values.join(", ")}`,{collisions:r})}}d(V,"precheck");export{z as fillEnvironments,V as precheck,G as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,Q as takeRepoSyncedDocuments};
11
+ FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(d=>({...d}))}E(V,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},F={charges:["payer","units","usd"]};async function Z(n,s,o,e,i,a,d){const c=E(t=>[...d.get(t)??[],...t==="profiles"?["environment_id"]:[],...g[t]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const t of i){const $=e.tables.get(t);if($===void 0||a.has(t)||$.primaryKey.length===0)continue;const m=$.primaryKey,f=m.some(u=>$.identity.includes(u)),S=m.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),I=f?"TRUE":m.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),A=new Set([...$.identity,...d.get(t)??[]]);for(const u of e.uniqueKeys.filter(h=>h.table===t&&!h.columns.every(T=>A.has(T)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,T=u.columns.map(R=>`s.${l(R)} = t.${l(R)}`).join(" AND "),O=await n.prepareUncached(`SELECT ${u.columns.map(R=>`s.${l(R)}::text`).join(" || ',' || ")} AS value
12
+ FROM (SELECT * FROM ${p(s,t)}${h}) s JOIN (SELECT * FROM ${p(o,t)}${h}) t ON ${T} AND (${I}) LIMIT 10`).all();O.length>0&&r.push({table:t,key:u.name,values:O.map(R=>R.value)});const y=f?"TRUE":m.map(R=>`a.${l(R)} IS DISTINCT FROM b.${l(R)}`).join(" OR "),L=await n.prepareUncached(`SELECT DISTINCT ${u.columns.map(R=>`a.${l(R)}::text`).join(" || ',' || ")} AS value
13
+ FROM (SELECT ctid AS row_id, * FROM ${p(s,t)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${p(s,t)}${h}) b ON ${u.columns.map(R=>`a.${l(R)} = b.${l(R)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();L.length>0&&r.push({table:t,key:u.name,values:L.map(R=>R.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(t).includes(u)&&(F[t]?.includes(u)??!0));if(w.length>0&&!f){const u=w.map(T=>`s.${l(T)} IS DISTINCT FROM t.${l(T)}`).join(" OR "),h=await n.prepareUncached(`SELECT ${m.map(T=>`s.${l(T)}::text`).join(" || ',' || ")} AS value
14
+ FROM ${p(s,t)} s JOIN ${p(o,t)} t ON ${S} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:t,key:"primary key payload",values:h.map(T=>T.value)})}}if(r.length>0){const t=r[0];throw new _("pre-check","unique_conflict",`${t.table} ${t.key} collides ${t.staged===!0?"within the bundle":"with the target"}: ${t.values.join(", ")}`,{collisions:r})}}E(Z,"precheck");export{G as dropExistingWatches,z as fillEnvironments,Z as precheck,Q as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,V as takeRepoSyncedDocuments};
@@ -1,3 +1,3 @@
1
- var X=Object.defineProperty;var l=(e,s)=>X(e,"name",{value:s,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as M}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ae}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{copyRows as se,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as re,precheck as oe,renameClashingLegacyCharges as de,renameClashingProfiles as pe,rewriteConversationHeaders as ue,rewritePaths as ce,rewriteRequestPaths as le,takeRepoSyncedDocuments as fe}from"./prepare.js";import{boundSub as me,dropRefusedMessages as _e,checkSourcePerson as we,checkStagedBlobKeys as ge,checkStagedPersons as be,checkStagedReferences as he,checkStagedRequestKeys as ye}from"./bind.js";import{deleteBlobs as Ee,deleteRunBlobs as Se,deleteRunPrefix as ve,moveRunBlobs as Re}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Oe,grantMissing as Pe,mapProfileIds as Te,renameClashingRepos as je,rewriteIds as ke,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as De,stagingSchema as Me,targetSchema as Ne}from"./stage.js";import{verifyRun as Le}from"./verify.js";import{sandboxPathMap as Be,writeNodeFiles as We}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ke,recordImportedActivations as Ue,writeStores as Fe}from"./stores.js";import{openImportGrants as Je}from"./open-grants.js";import{publishImportedPlugins as Ge}from"./publish-plugins.js";import{COPIED_TABLES as qe}from"../bundle/layout.js";import{emitEvent as $e}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const ze=10*6e4,Qe=30*6e4,R=l(()=>new Date().toISOString(),"now"),K=l(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Ve(e,s){const a=await e.get(N.source(s));if(a===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(a.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}l(Ve,"readSource");async function Xe(e,s,a,n,i,p,d){const o=[];for(const t of L(a.run_id,"grants",n)){const u=await e.get(t);if(u===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ne(u))}if(o.length===0)return;const w=o.map(t=>({sub:me(t.sub,n.person,a.person,"grants.sub"),grantee:t.grantee}));await d(a.run_id);const f=[];for(const t of w)await Oe(s,i,p,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Pe(f)}l(Xe,"ensureGrants");async function It(e,s,a={}){const n=a.blobs??await x(),i=await v(),p=Me(e.run_id);let d="start";const o=l(async t=>{d=t,await s.assertOwned(),await K(e.run_id,t),await a.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Ve(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 u=await Ne(i),I=[...qe],b=await ie(i,u,[...I,"grants"]);if(!w){const m={},P=[],T=[],j=a.fleetRuntime??process.env.CRTR_RUNTIME??null;await we(i,u,t.person,e.person),await o("open-grants"),await Xe(n,i,e,t,u,j,a.openGrants??Je),await o("publish-plugins");const F=await Ke(n,e.run_id),E=await M(e.person,()=>Ge(F));if(E.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)>=ze)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await K(e.run_id,"waiting_for_directory");return}T.push(...E.refused),await o("stage");const J=await De(i,e.run_id,t.counts,r=>L(e.run_id,r,t),r=>n.get(r));for(const[r,c]of Object.entries(J))m[r]={staged:c,inserted:0,mapped:0,dropped:0};const _={db:i,schema:p,target:u,catalog:b,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[r,c]of Object.entries(await be(_)))h(m,r,c);for(const[r,c]of Object.entries(await ge(_)))h(m,r,c);await o("rewrite-person"),await Ce(_),await Ae(_),await o("prune");const G=await re(i,p,b,t),S=t.kind==="hosted"?Be(t.pathPrefixes??[]):[];await o("rewrite-paths"),await ce(i,p,S),await ue(i,p,S,n,e.run_id),await le(i,p),await ye(_);const q=await Te(_);await pe(i,p,u,t.installId,e.person),await o("rewrite-ids");const k=await ke(_,q);await o("drop");const $=await fe(i,p,u),Y=await Ie(_);for(const[r,c]of Object.entries({...G}))h(m,r,c);for(const[r,c]of Object.entries(Y))h(m,r,c);for(const[r,c]of Object.entries(await _e(_,{installId:t.installId,person:e.person,runId:e.run_id})))h(m,r,c);await he(_,{installId:t.installId,person:e.person,runId:e.run_id}),await je(_),await de(i,p,u,t.installId),await o("pre-check");const z=new Map([["messages",["seq"]],...ae.map(r=>[r,["seq"]])]);await oe(i,p,u,b,I,new Set,z),await o("blobs"),await Re(i,p,u,e.person,n,e.run_id,f),await o("copy"),await M(e.person,()=>D(async r=>{await s.assertOwned({extendLeaseMs:Qe});const c=await se({db:r,runId:e.run_id,schema:p,target:u,catalog:b,source:t,person:e.person,idMap:k,pathMap:S}),C=await et(r,e.run_id,$);C>0&&(c.inserted.revisions=(c.inserted.revisions??0)+C),await We(r,p,e.run_id,t);const A=await Fe({db:r,blobs:n,runId:e.run_id,person:e.person,objectMap:k.object});for(const[Q,V]of Object.entries(A.inserted))c.inserted[Q]=V.length;return P.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...xe(m,c),unresolved_plugins:P,refused_plugins:T}),R(),e.run_id),c})),w=!0,await a.atStep?.("committed")}await o("verify");const y=await Le(i,e.run_id,p,u,b,t.installId);if(await i.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=N.manifest(e.run_id);await n.put(O,await tt(e.run_id)),await H(i,e.run_id);for(const m of He(e.run_id))await n.delete(m);await Se(n,e.run_id),await D(async m=>{await Ue(m,e.run_id,e.person),await m.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 Ye)throw t;const u=Ze(t,d);$e({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:u.step,code:u.code}}),await H(i,e.run_id).catch(()=>{}),w||await Ee(n,f,!0),await i.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await ve(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}l(It,"processRun");function Ze(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const a=e.code;return{step:s,code:typeof a=="string"?a:"import_failed",message:e instanceof Error?e.message:String(e)}}l(Ze,"failureOf");function h(e,s,a){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=a}l(h,"addDropped");function xe(e,s){for(const[a,n]of Object.entries(s.inserted))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[a,n]of Object.entries(s.mapped))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}l(xe,"withInserted");async function et(e,s,a){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(a.map(d=>d.rev_id)))).map(d=>d.rev_id)),i=a.filter(d=>!n.has(d.rev_id)),p=new Map;for(const d of a)p.set(d.document,[...p.get(d.document)??[],d]);for(const[d,o]of p){const w=await te(e,d);w!==null&&await ee(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 U(e,s,"revisions",i.map(d=>[d.rev_id])),await U(e,s,"revision_parents",i.flatMap(d=>d.parents.map(o=>[d.rev_id,o]))),i.length}l(et,"arrive");async function U(e,s,a,n){if(n.length===0)return;const i=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,a);i===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,a,W(n)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(i.inserted_keys),...n]),s,a)}l(U,"appendManifest");async function tt(e){const a=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(a.map(n=>JSON.stringify({table:n.table_name,keys:B(n.inserted_keys)})).join(`
1
+ var X=Object.defineProperty;var f=(e,s)=>X(e,"name",{value:s,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as M}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ae}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{copyRows as se,decodeKeys as W,encodeKeys as B}from"./copy.js";import{pruneStaged as re,precheck 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 Ee,checkStagedRequestKeys as ye}from"./bind.js";import{deleteBlobs as Se,deleteRunBlobs as ve,deleteRunPrefix as Re,moveRunBlobs as Ie}from"./blobs.js";import{dropStubRows as Oe,findFleetGrant as Pe,grantMissing as je,mapProfileIds as Te,renameClashingRepos as ke,rewriteIds as Ce,rewritePerson as Ae,scopeRepoIdentities as De}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as Me,stagingSchema as Ne,targetSchema as Le}from"./stage.js";import{verifyRun as We}from"./verify.js";import{sandboxPathMap as Be,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ke,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=f(()=>new Date().toISOString(),"now"),K=f(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Xe(e,s){const a=await e.get(N.source(s));if(a===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(a.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}f(Xe,"readSource");async function Ze(e,s,a,n,i,p,d){const o=[];for(const t of L(a.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ne(c))}if(o.length===0)return;const w=o.map(t=>({sub:_e(t.sub,n.person,a.person,"grants.sub"),grantee:t.grantee}));await d(a.run_id);const m=[];for(const t of w)await Pe(s,i,p,t.sub,t.grantee)===void 0&&m.push(t.grantee);if(m.length>0)throw je(m)}f(Ze,"ensureGrants");async function Ot(e,s,a={}){const n=a.blobs??await x(),i=await v(),p=Ne(e.run_id);let d="start";const o=f(async t=>{d=t,await s.assertOwned(),await K(e.run_id,t),await a.atStep?.(t)},"at");let w=e.state==="committed";const m=[];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 Le(i),I=[...$e],h=await ie(i,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],T=a.fleetRuntime??process.env.CRTR_RUNTIME??null;await ge(i,c,t.person,e.person),await o("open-grants"),await Ze(n,i,e,t,c,T,a.openGrants??Ge),await o("publish-plugins");const F=await Ue(n,e.run_id),y=await M(e.person,()=>qe(F));if(y.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: ${y.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:y.unavailable});await s.assertOwned(),await K(e.run_id,"waiting_for_directory");return}j.push(...y.refused),await o("stage");const J=await Me(i,e.run_id,t.counts,r=>L(e.run_id,r,t),r=>n.get(r));for(const[r,u]of Object.entries(J))l[r]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:i,schema:p,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:T,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[r,u]of Object.entries(await he(_)))b(l,r,u);for(const[r,u]of Object.entries(await be(_)))b(l,r,u);await o("rewrite-person"),await Ae(_),await De(_),await o("prune");const G=await re(i,p,h,t),S=t.kind==="hosted"?Be(t.pathPrefixes??[]):[];await o("rewrite-paths"),await le(i,p,S),await ue(i,p,S,n,e.run_id),await fe(i,p),await ye(_);const q=await Te(_);await ce(i,p,c,t.installId,e.person),await o("rewrite-ids");const k=await Ce(_,q);await o("drop");const $=await me(i,p,c),Y=await Oe(_);for(const[r,u]of Object.entries({...G}))b(l,r,u);for(const[r,u]of Object.entries(Y))b(l,r,u);for(const[r,u]of Object.entries(await we(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,r,u);await Ee(_,{installId:t.installId,person:e.person,runId:e.run_id}),await ke(_),await pe(i,p,c,t.installId);for(const[r,u]of Object.entries(await de(i,p,c)))b(l,r,u);await o("pre-check");const z=new Map([["messages",["seq"]],...ae.map(r=>[r,["seq"]])]);await oe(i,p,c,h,I,new Set,z),await o("blobs"),await Ie(i,p,c,e.person,n,e.run_id,m),await o("copy"),await M(e.person,()=>D(async r=>{await s.assertOwned({extendLeaseMs:Ve});const u=await se({db:r,runId:e.run_id,schema:p,target:c,catalog:h,source:t,person:e.person,idMap:k,pathMap:S}),C=await tt(r,e.run_id,$);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(r,p,e.run_id,t);const A=await Je({db:r,blobs:n,runId:e.run_id,person:e.person,objectMap:k.object});for(const[Q,V]of Object.entries(A.inserted))u.inserted[Q]=V.length;return P.push(...A.unresolvedPlugins),await r.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 a.atStep?.("committed")}await o("verify");const E=await We(i,e.run_id,p,c,h,t.installId);if(await i.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(E),e.run_id),!E.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:E.differences,invariants:E.invariants});await o("manifest");const O=N.manifest(e.run_id);await n.put(O,await nt(e.run_id)),await H(i,e.run_id);for(const l of Ke(e.run_id))await n.delete(l);await ve(n,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,d);Ye({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await H(i,e.run_id).catch(()=>{}),w||await Se(n,m,!0),await i.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}f(Ot,"processRun");function xe(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const a=e.code;return{step:s,code:typeof a=="string"?a:"import_failed",message:e instanceof Error?e.message:String(e)}}f(xe,"failureOf");function b(e,s,a){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=a}f(b,"addDropped");function et(e,s){for(const[a,n]of Object.entries(s.inserted))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[a,n]of Object.entries(s.mapped))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}f(et,"withInserted");async function tt(e,s,a){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(a.map(d=>d.rev_id)))).map(d=>d.rev_id)),i=a.filter(d=>!n.has(d.rev_id)),p=new Map;for(const d of a)p.set(d.document,[...p.get(d.document)??[],d]);for(const[d,o]of p){const w=await te(e,d);w!==null&&await ee(e,w,o.map(m=>({rev_id:m.rev_id,parents:m.parents,body_hash:m.body_hash,rationale:m.rationale,created_at:m.created_at})))}return await U(e,s,"revisions",i.map(d=>[d.rev_id])),await U(e,s,"revision_parents",i.flatMap(d=>d.parents.map(o=>[d.rev_id,o]))),i.length}f(tt,"arrive");async function U(e,s,a,n){if(n.length===0)return;const i=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,a);i===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,a,B(n)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...W(i.inserted_keys),...n]),s,a)}f(U,"appendManifest");async function nt(e){const a=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(a.map(n=>JSON.stringify({table:n.table_name,keys:W(n.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}l(tt,"manifestFile");export{Qe as COPY_LEASE_MS,ze as GRANT_WAIT_MS,It as processRun};
3
+ `))}f(nt,"manifestFile");export{Ve as COPY_LEASE_MS,Qe as GRANT_WAIT_MS,Ot as processRun};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.739",
3
+ "version": "0.3.741",
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.739",
162
- "@north-light/plugin": "0.3.739",
161
+ "@north-light/identity": "0.3.741",
162
+ "@north-light/plugin": "0.3.741",
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",
@@ -112,6 +112,14 @@ export async function renameClashingLegacyCharges(db, schema, target, installId)
112
112
  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(installId);
113
113
  return Number(done.changes);
114
114
  }
115
+ /** A staged watch whose (watcher, object) the target already holds is already imported (a hosted person's nodes watching shared objects): it and its subscriptions are
116
+ * dropped, the target's rows stand. Only this key is skipped; any other unique conflict still fails the pre-check. Returns the dropped watches and subscriptions. Runs before the pre-check. */
117
+ export async function dropExistingWatches(db, schema, target) {
118
+ const same = `FROM ${sq(target, 'watches')} t WHERE t.watcher = s.watcher AND t.object = s.object`;
119
+ const subs = await db.prepareUncached(`DELETE FROM ${sq(schema, 'watch_subscriptions')} u USING ${sq(schema, 'watches')} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${same})`).run();
120
+ const watches = await db.prepareUncached(`DELETE FROM ${sq(schema, 'watches')} s WHERE EXISTS (SELECT 1 ${same})`).run();
121
+ return { watches: Number(watches.changes), watch_subscriptions: Number(subs.changes) };
122
+ }
115
123
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
116
124
  * absent). Runs in the copy transaction: it writes target objects. */
117
125
  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.739",
3
+ "version": "0.3.741",
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.739",
3
+ "version": "0.3.741",
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.739",
3
+ "version": "0.3.741",
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.739",
31
- "@north-light/identity": "0.3.739"
30
+ "@north-light/api": "0.3.741",
31
+ "@north-light/identity": "0.3.741"
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.739",
3
+ "version": "0.3.741",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.739",
9
+ "version": "0.3.741",
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.739",
32
- "@north-light/plugin": "0.3.739",
31
+ "@north-light/identity": "0.3.741",
32
+ "@north-light/plugin": "0.3.741",
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.739",
11905
+ "version": "0.3.741",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.739",
11910
+ "version": "0.3.741",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.739",
11915
+ "version": "0.3.741",
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.739",
11923
+ "version": "0.3.741",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.739",
11927
- "@north-light/identity": "0.3.739"
11926
+ "@north-light/api": "0.3.741",
11927
+ "@north-light/identity": "0.3.741"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.739",
11932
+ "version": "0.3.741",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.739",
11936
- "@north-light/identity": "0.3.739",
11937
- "@north-light/plugin": "0.3.739",
11935
+ "@north-light/api": "0.3.741",
11936
+ "@north-light/identity": "0.3.741",
11937
+ "@north-light/plugin": "0.3.741",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {