@north-light/cli 0.3.610 → 0.3.612

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var g=Object.defineProperty;var y=(i,n)=>g(i,"name",{value:n,configurable:!0});import{randomUUID as O}from"node:crypto";import{closeSync as m,existsSync as k,fsyncSync as S,linkSync as b,lstatSync as U,mkdirSync as B,openSync as E,readFileSync as D,readSync as W,readdirSync as $,realpathSync as M,renameSync as P,rmSync as a,rmdirSync as v,statSync as x,writeSync as F}from"node:fs";import{dirname as w,join as d,resolve as X}from"node:path";import{assertBlobKey as Y}from"./index.js";import{blobFault as j}from"./fault.js";function I(i){const n=E(i,"r");try{S(n)}finally{m(n)}}y(I,"syncDir");function J(i,n,f=b){let t;try{t=M(i)}catch(r){if(r.code==="ENOENT")return;throw r}if(t===X(n))return;const e=new Set,o=y((r,c)=>{let u;try{u=$(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}for(const s of u){if(s.name.endsWith(".tmp"))continue;const l=d(r,s.name),N=d(c,s.name);if(s.isDirectory()){o(l,N);try{v(l)}catch(p){if(!["ENOTEMPTY","ENOENT"].includes(p.code??""))throw p}continue}const h=d(n,N);B(w(h),{recursive:!0,mode:448}),e.add(w(h));try{f(l,h)}catch(p){const T=p.code;if(T==="EEXIST"){K(l,h)&&a(l,{force:!0});continue}if(T==="ENOENT"||!L(l,h))continue}a(l,{force:!0})}},"adopt");o(t,"");for(const r of e)I(r);try{v(t)}catch(r){if(!["ENOTEMPTY","ENOENT"].includes(r.code??""))throw r}U(i,{throwIfNoEntry:!1})?.isSymbolicLink()&&!k(i)&&a(i,{force:!0})}y(J,"adoptBlobDirectory");function K(i,n){try{const f=x(i),t=x(n);return f.ino===t.ino&&f.dev===t.dev}catch{return!1}}y(K,"sameFile");function L(i,n){const f=`${n}.${O()}.tmp`;try{const t=E(f,"wx",384);try{let e;try{e=D(i)}catch(r){if(r.code==="ENOENT")return!1;throw r}let o=0;for(;o<e.length;)o+=F(t,e,o);S(t)}finally{m(t)}try{b(f,n)}catch(e){if(e.code==="EEXIST")return!1;throw e}return!0}finally{a(f,{force:!0})}}y(L,"copyInto");function Q(i){const n=y(t=>(Y(t),d(i,...t.split("/"))),"pathOf");function f(t,e,o){let r;try{r=$(t,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}for(const c of r){if(c.name.endsWith(".tmp"))continue;const u=e===""?c.name:`${e}/${c.name}`;c.isDirectory()?f(d(t,c.name),u,o):o.push(u)}}return y(f,"walk"),{async put(t,e){j("put");const o=n(t);B(w(o),{recursive:!0,mode:448});const r=`${o}.${O()}.tmp`,c=E(r,"wx",384);try{const u=typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e);let s=0;for(;s<u.length;)s+=F(c,u,s);S(c)}catch(u){throw m(c),a(r,{force:!0}),u}m(c),P(r,o),I(w(o))},async get(t,e){try{if(!e)return D(n(t));const o=E(n(t),"r");try{const r=Buffer.allocUnsafe(e.length),c=W(o,r,0,e.length,e.start);return r.subarray(0,c)}finally{m(o)}}catch(o){if(o.code==="ENOENT")return null;throw o}},async list(t){const e=[];return f(i,"",e),e.filter(o=>o.startsWith(t)).sort((o,r)=>Buffer.compare(Buffer.from(o),Buffer.from(r)))},async delete(t){a(n(t),{force:!0})}}}y(Q,"createDirectoryBlobStore");export{J as adoptBlobDirectory,Q as createDirectoryBlobStore};
1
+ var k=Object.defineProperty;var y=(i,n)=>k(i,"name",{value:n,configurable:!0});import{createHash as U,randomUUID as b}from"node:crypto";import{closeSync as d,existsSync as W,fsyncSync as S,linkSync as B,lstatSync as M,mkdirSync as g,openSync as p,readFileSync as w,readSync as P,readdirSync as x,realpathSync as X,renameSync as Y,rmSync as a,rmdirSync as D,statSync as $,writeSync as v}from"node:fs";import{dirname as N,join as m,resolve as j}from"node:path";import{assertBlobKey as z}from"./index.js";import{blobFault as F}from"./fault.js";function I(i){const n=p(i,"r");try{S(n)}finally{d(n)}}y(I,"syncDir");function Q(i,n,u=B){let f;try{f=X(i)}catch(t){if(t.code==="ENOENT")return;throw t}if(f===j(n))return;const r=new Set,e=y((t,c)=>{let o;try{o=x(t,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}for(const s of o){if(s.name.endsWith(".tmp"))continue;const l=m(t,s.name),T=m(c,s.name);if(s.isDirectory()){e(l,T);try{D(l)}catch(E){if(!["ENOTEMPTY","ENOENT"].includes(E.code??""))throw E}continue}const h=m(n,T);g(N(h),{recursive:!0,mode:448}),r.add(N(h));try{u(l,h)}catch(E){const O=E.code;if(O==="EEXIST"){H(l,h)&&a(l,{force:!0});continue}if(O==="ENOENT"||!K(l,h))continue}a(l,{force:!0})}},"adopt");e(f,"");for(const t of r)I(t);try{D(f)}catch(t){if(!["ENOTEMPTY","ENOENT"].includes(t.code??""))throw t}M(i,{throwIfNoEntry:!1})?.isSymbolicLink()&&!W(i)&&a(i,{force:!0})}y(Q,"adoptBlobDirectory");function H(i,n){try{const u=$(i),f=$(n);return u.ino===f.ino&&u.dev===f.dev}catch{return!1}}y(H,"sameFile");function K(i,n){const u=`${n}.${b()}.tmp`;try{const f=p(u,"wx",384);try{let r;try{r=w(i)}catch(t){if(t.code==="ENOENT")return!1;throw t}let e=0;for(;e<r.length;)e+=v(f,r,e);S(f)}finally{d(f)}try{B(u,n)}catch(r){if(r.code==="EEXIST")return!1;throw r}return!0}finally{a(u,{force:!0})}}y(K,"copyInto");function R(i){const n=y(r=>(z(r),m(i,...r.split("/"))),"pathOf");function u(r,e,t){let c;try{c=x(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(const o of c){if(o.name.endsWith(".tmp"))continue;const s=e===""?o.name:`${e}/${o.name}`;o.isDirectory()?u(m(r,o.name),s,t):t.push(s)}}y(u,"walk");function f(r,e){g(N(r),{recursive:!0,mode:448});const t=`${r}.${b()}.tmp`,c=p(t,"wx",384);try{let o=0;for(;o<e.length;)o+=v(c,e,o);S(c)}catch(o){throw d(c),a(t,{force:!0}),o}d(c),Y(t,r),I(N(r))}return y(f,"write"),{async put(r,e){F("put"),f(n(r),typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e))},async head(r){let e;try{e=w(n(r))}catch(t){if(t.code==="ENOENT")return null;throw t}return{size:e.length,etag:U("md5").update(e).digest("hex")}},async copy(r,e){F("copy");const t=n(r),c=n(e);let o;try{o=w(t)}catch(s){if(s.code==="ENOENT")return!1;throw s}return f(c,o),!0},async get(r,e){try{if(!e)return w(n(r));const t=p(n(r),"r");try{const c=Buffer.allocUnsafe(e.length),o=P(t,c,0,e.length,e.start);return c.subarray(0,o)}finally{d(t)}}catch(t){if(t.code==="ENOENT")return null;throw t}},async list(r){const e=[];return u(i,"",e),e.filter(t=>t.startsWith(r)).sort((t,c)=>Buffer.compare(Buffer.from(t),Buffer.from(c)))},async delete(r){a(n(r),{force:!0})}}}y(R,"createDirectoryBlobStore");export{Q as adoptBlobDirectory,R as createDirectoryBlobStore};
@@ -1,3 +1,3 @@
1
- /** Fault switch for the blob store (design-fleet, faulting-store seam): `CRTR_FAULT_BLOB=put_fail` makes every `put`
1
+ /** Fault switch for the blob store (design-fleet, faulting-store seam): `CRTR_FAULT_BLOB=put_fail` makes every `put` and `copy`
2
2
  * throw. Read on each call so a seam test can flip it in the serving process's environment. */
3
- export declare function blobFault(op: 'put'): void;
3
+ export declare function blobFault(op: 'put' | 'copy'): void;
@@ -1 +1 @@
1
- var u=Object.defineProperty;var o=(t,r)=>u(t,"name",{value:r,configurable:!0});function p(t){if(t==="put"&&process.env.CRTR_FAULT_BLOB==="put_fail")throw new Error("blob put refused (CRTR_FAULT_BLOB=put_fail)")}o(p,"blobFault");export{p as blobFault};
1
+ var e=Object.defineProperty;var r=(o,t)=>e(o,"name",{value:t,configurable:!0});function u(o){if(process.env.CRTR_FAULT_BLOB==="put_fail")throw new Error("blob put refused (CRTR_FAULT_BLOB=put_fail)")}r(u,"blobFault");export{u as blobFault};
@@ -11,6 +11,13 @@ export interface BlobStore {
11
11
  }): Promise<Buffer | null>;
12
12
  /** Every key beginning with `prefix`, in ascending byte order. */
13
13
  list(prefix: string): Promise<string[]>;
14
+ /** The object's size and content hash without its bytes, or `null` when no object has this key. `etag` is the hex MD5 of the bytes when the store knows it (an object written in one piece), else `null`: equal sizes and equal non-null etags mean equal bytes. */
15
+ head(key: string): Promise<{
16
+ size: number;
17
+ etag: string | null;
18
+ } | null>;
19
+ /** Write the bytes of the object at `from` to `to`, replacing any object at `to`, without the bytes passing through the caller. False when there is no object at `from` (nothing is written). */
20
+ copy(from: string, to: string): Promise<boolean>;
14
21
  /** Remove the object at `key`; removing an absent key is not an error. */
15
22
  delete(key: string): Promise<void>;
16
23
  }
@@ -1,7 +1,7 @@
1
- var q=Object.defineProperty;var c=(e,a)=>q(e,"name",{value:a,configurable:!0});import{createHash as z,createHmac as R}from"node:crypto";import{assertBlobKey as y}from"./index.js";import{blobFault as I}from"./fault.js";const E=c(e=>z("sha256").update(e).digest("hex"),"sha256"),p=c((e,a)=>R("sha256",e).update(a).digest(),"hmac"),f=c(e=>encodeURIComponent(e).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),"encode");function X(e){const a=new URL(e.endpoint);async function i(t,s,n,r,o){const m=`/${f(e.bucket)}${s===""?"":`/${s.split("/").map(f).join("/")}`}`,l=[...n].sort(([h],[C])=>h<C?-1:1).map(([h,C])=>`${f(h)}=${f(C)}`).join("&"),g=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),w=g.slice(0,8),S=E(r??""),d={host:a.host,"x-amz-content-sha256":S,"x-amz-date":g},$=Object.keys(d).sort(),A=$.map(h=>`${h}:${d[h]}
2
- `).join(""),_=$.join(";"),T=`${w}/auto/s3/aws4_request`,B=[t,m,l,A,_,S].join(`
3
- `),K=["AWS4-HMAC-SHA256",g,T,E(B)].join(`
4
- `),H=p(p(p(p(`AWS4${e.secretAccessKey}`,w),"auto"),"s3"),"aws4_request"),j=R("sha256",H).update(K).digest("hex");d.authorization=`AWS4-HMAC-SHA256 Credential=${e.accessKeyId}/${T}, SignedHeaders=${_}, Signature=${j}`;const{host:U,...x}=d;return o&&(x.range=`bytes=${o.start}-${o.start+o.length-1}`),await fetch(`${a.origin}${m}${l?`?${l}`:""}`,{method:t,headers:x,...r?{body:new Uint8Array(r)}:{}})}c(i,"send");async function u(t,s){if(!t.ok)throw new Error(`R2 ${s} failed (${t.status}): ${(await t.text()).slice(0,300)}`);return t}return c(u,"ok"),{async put(t,s){I("put"),y(t),await u(await i("PUT",t,[],typeof s=="string"?Buffer.from(s,"utf8"):Buffer.from(s)),`put ${t}`)},async get(t,s){y(t);const n=await i("GET",t,[],void 0,s);return n.status===416?(await n.arrayBuffer(),Buffer.alloc(0)):n.status===404?(await n.arrayBuffer(),null):Buffer.from(await(await u(n,`get ${t}`)).arrayBuffer())},async list(t){const s=[];let n;do{const r=[["list-type","2"],["prefix",t],...n?[["continuation-token",n]]:[]],o=await(await u(await i("GET","",r),`list ${t}`)).text();for(const m of o.matchAll(/<Key>([^<]*)<\/Key>/g))s.push(m[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'"));n=/<IsTruncated>true<\/IsTruncated>/.test(o)?/<NextContinuationToken>([^<]*)<\/NextContinuationToken>/.exec(o)?.[1]:void 0}while(n);return s.sort((r,o)=>Buffer.compare(Buffer.from(r),Buffer.from(o)))},async delete(t){y(t);const s=await i("DELETE",t,[]);s.status!==404?await u(s,`delete ${t}`):await s.arrayBuffer()}}}c(X,"createR2BlobStore");function O(){const e=process.env.CRTR_R2_BUCKET;if(!e)return null;const a=c(i=>{const u=process.env[i];if(!u)throw new Error(`${i} is required when CRTR_R2_BUCKET is set`);return u},"need");return{bucket:e,endpoint:a("CRTR_R2_ENDPOINT"),accessKeyId:a("CRTR_R2_ACCESS_KEY_ID"),secretAccessKey:a("CRTR_R2_SECRET_ACCESS_KEY")}}c(O,"r2ConfigFromEnv");function P(e,a,i,u=new Date){y(a);const t=new URL(e.endpoint),s=`/${f(e.bucket)}/${a.split("/").map(f).join("/")}`,n=u.toISOString().replace(/[:-]|\.\d{3}/g,""),r=n.slice(0,8),o=`${r}/auto/s3/aws4_request`,l=[["X-Amz-Algorithm","AWS4-HMAC-SHA256"],["X-Amz-Credential",`${e.accessKeyId}/${o}`],["X-Amz-Date",n],["X-Amz-Expires",String(i)],["X-Amz-SignedHeaders","host"]].sort(([$],[A])=>$<A?-1:1).map(([$,A])=>`${f($)}=${f(A)}`).join("&"),g=["PUT",s,l,`host:${t.host}
1
+ var q=Object.defineProperty;var u=(s,a)=>q(s,"name",{value:a,configurable:!0});import{createHash as D,createHmac as C}from"node:crypto";import{assertBlobKey as g}from"./index.js";import{blobFault as H}from"./fault.js";const R=u(s=>D("sha256").update(s).digest("hex"),"sha256"),m=u((s,a)=>C("sha256",s).update(a).digest(),"hmac"),f=u(s=>encodeURIComponent(s).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),"encode"),I=5,P=200;function v(s){const a=new URL(s.endpoint);async function i(t,e,n,r,c,l={}){for(let d=1;;d++){let o,$;try{o=await A(t,e,n,r,c,l)}catch(h){$=h}if(o&&o.status!==429&&o.status<500)return o;if(d===I){if(o)return o;throw $}await o?.arrayBuffer().catch(()=>{}),await new Promise(h=>setTimeout(h,P*2**(d-1)*(.5+Math.random())))}}u(i,"send");async function A(t,e,n,r,c,l){const d=`/${f(s.bucket)}${e===""?"":`/${e.split("/").map(f).join("/")}`}`,o=[...n].sort(([S],[E])=>S<E?-1:1).map(([S,E])=>`${f(S)}=${f(E)}`).join("&"),$=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),h=$.slice(0,8),y=R(r??""),w={host:a.host,"x-amz-content-sha256":y,"x-amz-date":$,...l},T=Object.keys(w).sort(),K=T.map(S=>`${S}:${w[S]}
2
+ `).join(""),_=T.join(";"),x=`${h}/auto/s3/aws4_request`,z=[t,d,o,K,_,y].join(`
3
+ `),b=["AWS4-HMAC-SHA256",$,x,R(z)].join(`
4
+ `),j=m(m(m(m(`AWS4${s.secretAccessKey}`,h),"auto"),"s3"),"aws4_request"),U=C("sha256",j).update(b).digest("hex");w.authorization=`AWS4-HMAC-SHA256 Credential=${s.accessKeyId}/${x}, SignedHeaders=${_}, Signature=${U}`;const{host:M,...B}=w;return c&&(B.range=`bytes=${c.start}-${c.start+c.length-1}`),await fetch(`${a.origin}${d}${o?`?${o}`:""}`,{method:t,headers:B,...r?{body:new Uint8Array(r)}:{}})}u(A,"sendOnce");async function p(t,e){if(!t.ok)throw new Error(`R2 ${e} failed (${t.status}): ${(await t.text()).slice(0,300)}`);return t}return u(p,"ok"),{async put(t,e){H("put"),g(t),await p(await i("PUT",t,[],typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)),`put ${t}`)},async head(t){g(t);const e=await i("HEAD",t,[]);if(e.status===404)return null;await p(e,`head ${t}`);const n=/^"?([0-9a-f]{32})"?$/.exec(e.headers.get("etag")??"")?.[1]??null;return{size:Number(e.headers.get("content-length")),etag:n}},async copy(t,e){H("copy"),g(t),g(e);const n=await i("PUT",e,[],void 0,void 0,{"x-amz-copy-source":`/${f(s.bucket)}/${t.split("/").map(f).join("/")}`});if(n.status===404)return await n.arrayBuffer(),!1;const r=await(await p(n,`copy ${t} to ${e}`)).text();if(/<Error>/.test(r))throw new Error(`R2 copy ${t} to ${e} failed: ${r.slice(0,300)}`);return!0},async get(t,e){g(t);const n=await i("GET",t,[],void 0,e);return n.status===416?(await n.arrayBuffer(),Buffer.alloc(0)):n.status===404?(await n.arrayBuffer(),null):Buffer.from(await(await p(n,`get ${t}`)).arrayBuffer())},async list(t){const e=[];let n;do{const r=[["list-type","2"],["prefix",t],...n?[["continuation-token",n]]:[]],c=await(await p(await i("GET","",r),`list ${t}`)).text();for(const l of c.matchAll(/<Key>([^<]*)<\/Key>/g))e.push(l[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'"));n=/<IsTruncated>true<\/IsTruncated>/.test(c)?/<NextContinuationToken>([^<]*)<\/NextContinuationToken>/.exec(c)?.[1]:void 0}while(n);return e.sort((r,c)=>Buffer.compare(Buffer.from(r),Buffer.from(c)))},async delete(t){g(t);const e=await i("DELETE",t,[]);e.status!==404?await p(e,`delete ${t}`):await e.arrayBuffer()}}}u(v,"createR2BlobStore");function L(){const s=process.env.CRTR_R2_BUCKET;if(!s)return null;const a=u(i=>{const A=process.env[i];if(!A)throw new Error(`${i} is required when CRTR_R2_BUCKET is set`);return A},"need");return{bucket:s,endpoint:a("CRTR_R2_ENDPOINT"),accessKeyId:a("CRTR_R2_ACCESS_KEY_ID"),secretAccessKey:a("CRTR_R2_SECRET_ACCESS_KEY")}}u(L,"r2ConfigFromEnv");function Y(s,a,i,A=new Date){g(a);const p=new URL(s.endpoint),t=`/${f(s.bucket)}/${a.split("/").map(f).join("/")}`,e=A.toISOString().replace(/[:-]|\.\d{3}/g,""),n=e.slice(0,8),r=`${n}/auto/s3/aws4_request`,l=[["X-Amz-Algorithm","AWS4-HMAC-SHA256"],["X-Amz-Credential",`${s.accessKeyId}/${r}`],["X-Amz-Date",e],["X-Amz-Expires",String(i)],["X-Amz-SignedHeaders","host"]].sort(([y],[w])=>y<w?-1:1).map(([y,w])=>`${f(y)}=${f(w)}`).join("&"),d=["PUT",t,l,`host:${p.host}
5
5
  `,"host","UNSIGNED-PAYLOAD"].join(`
6
- `),w=["AWS4-HMAC-SHA256",n,o,E(g)].join(`
7
- `),S=p(p(p(p(`AWS4${e.secretAccessKey}`,r),"auto"),"s3"),"aws4_request"),d=R("sha256",S).update(w).digest("hex");return`${t.origin}${s}?${l}&X-Amz-Signature=${d}`}c(P,"presignPutUrl");export{X as createR2BlobStore,P as presignPutUrl,O as r2ConfigFromEnv};
6
+ `),o=["AWS4-HMAC-SHA256",e,r,R(d)].join(`
7
+ `),$=m(m(m(m(`AWS4${s.secretAccessKey}`,n),"auto"),"s3"),"aws4_request"),h=C("sha256",$).update(o).digest("hex");return`${p.origin}${t}?${l}&X-Amz-Signature=${h}`}u(Y,"presignPutUrl");export{v as createR2BlobStore,Y as presignPutUrl,L as r2ConfigFromEnv};
@@ -11,9 +11,16 @@ export declare function checkStagedPersons(input: RewriteInput): Promise<Record<
11
11
  * document, the person's own object, an object with an `acts_for` fact for the person, or anything below those that is not directly under an app), and no profile or grant the
12
12
  * rows name belongs to another person. */
13
13
  export declare function checkStagedReferences(input: RewriteInput): Promise<void>;
14
- /** After staging, before rewrite 1: every blob key a staged row names has the shape its row would produce and an owner (node) that is in this bundle.
15
- * A key naming another person's blob is `person_mismatch`; a key of no known shape is `bundle_invalid`. Without this, the importer's own node would read, and
16
- * compaction would delete, a blob of someone else's conversation. (Human requests are checked by `checkStagedRequestKeys`, after their dirs are rewritten to blob keys.) */
17
- export declare function checkStagedBlobKeys(input: RewriteInput): Promise<void>;
14
+ /** After staging, before rewrite 1: every blob key a staged row names has the shape its row would produce and an owner (node) that is in this bundle or is the
15
+ * importing person's own node in the target. A key naming a node of another person is `person_mismatch`; a key of no known shape is `bundle_invalid`. Without this,
16
+ * the importer's own node would read, and compaction would delete, a blob of someone else's conversation. (Human requests are checked by `checkStagedRequestKeys`,
17
+ * after their dirs are rewritten to blob keys.)
18
+ *
19
+ * A row whose owner node is in neither the bundle nor the target, and that no live row of the bundle holds, is what a deleted node left behind (the purge of a node
20
+ * keeps a conversation or attachment row and its blob; a deleted node's job rows stay too). It is dropped, not refused: a conversation no staged `sessions` row binds
21
+ * (its `conversation_parts` and `conversation_entries` rows), an `upload_uses` row whose `run_id` is not a node of the bundle, a `jobs` row whose job object is not
22
+ * owned by a node of the bundle. `moveRunBlobs` leaves the blob of such an owner where it was uploaded. A conversation's owner is the owner of its part keys; a
23
+ * `conversation_entries` row with no part names no owner and is copied as before. Returns rows dropped per table. */
24
+ export declare function checkStagedBlobKeys(input: RewriteInput): Promise<Record<string, number>>;
18
25
  /** After rewrite 4b: a human request's `request_dir`, `presentation_dir` and `file` that are blob keys (`requests/…`) are under the request's own `requests/<its id>`. */
19
26
  export declare function checkStagedRequestKeys(input: RewriteInput): Promise<void>;
@@ -1,15 +1,15 @@
1
- var g=Object.defineProperty;var u=(s,t)=>g(s,"name",{value:t,configurable:!0});import{parseBlobKey as L}from"../bundle/blob-keys.js";import{q as E}from"./catalog.js";import{objectIdColumns as R}from"./rewrite.js";import{ImportLaneError as m}from"./stage.js";const w=/^user:[A-Za-z0-9._-]+$/,S=u(s=>s.replace(/^user:/,""),"bare"),I=u((s,t)=>`${E(s)}.${E(t)}`,"sq"),$=u(async(s,t,...r)=>await s.prepareUncached(t).all(...r),"all");function _(s,t){return new m("bind","person_mismatch",s,t)}u(_,"mismatch");function D(s,t,r,a){if(s===t||s===r)return r;throw _(`${a} names ${s}, which is neither the bundle's person nor the importing person`,{where:a,value:s})}u(D,"boundSub");async function k(s,t,r,a){if(!w.test(r))throw _(`the bundle's person ${JSON.stringify(r)} is not a user:<id> principal`,{where:"source.json person",value:r});if(r===a)return;const i=u(e=>I(t,e),"T"),n=await s.prepareUncached(`SELECT 'identities' AS tbl FROM ${i("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
- UNION ALL SELECT 'grants' FROM ${i("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${i("profiles")} WHERE person = ?
3
- UNION ALL SELECT 'nodes' FROM ${i("nodes")} WHERE sub = ? LIMIT 1`).get(r,r,r,r);if(n!==void 0)throw _(`the bundle's person ${r} is already a person in the target (${n.tbl}), not the importing person ${a}`,{where:`${n.tbl}`,value:r})}u(k,"checkSourcePerson");const v=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"]],C=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function H(s){const{db:t,schema:r,sourcePerson:a,targetPerson:i}=s,n=u(p=>I(r,p),"S"),e=u((p,d)=>{throw _(`${p} names ${d.join(", ")}, who is neither the bundle's person ${a} nor the importing person ${i}`,{where:p,values:d})},"refuse");for(const[p,d]of v){const o=await $(t,`SELECT DISTINCT ${E(d)} AS v FROM ${n(p)} WHERE ${E(d)} IS NOT NULL AND ${E(d)} <> '' AND ${E(d)} NOT IN (?, ?) LIMIT 5`,a,i);o.length>0&&e(`${p}.${d}`,o.map(l=>l.v))}for(const[p,d]of C){const o=await $(t,`SELECT DISTINCT ${E(d)} AS v FROM ${n(p)} WHERE ${E(d)} LIKE 'user:%' AND ${E(d)} NOT IN (?, ?) LIMIT 5`,a,i);o.length>0&&e(`${p}.${d}`,o.map(l=>l.v))}const c=await $(t,`SELECT DISTINCT external_id AS v FROM ${n("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,a,i);c.length>0&&e("identities.external_id",c.map(p=>p.v));const f=await $(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${n("daemon_actions")}
4
- WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,a,i);f.length>0&&e("daemon_actions principal.sub",f.map(p=>p.v));const h=await $(t,`SELECT DISTINCT subject_id AS v FROM ${n("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,S(a),S(i));h.length>0&&e("relations acts_for subject",h.map(p=>p.v));const N=Number((await t.prepareUncached(`DELETE FROM ${n("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return N>0?{relations:N}:{}}u(H,"checkStagedPersons");async function W(s){const{db:t,schema:r,target:a,catalog:i,targetPerson:n}=s,e=u(o=>I(r,o),"S"),c=u(o=>I(a,o),"T"),f=S(n);await t.exec(`CREATE TABLE ${e("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const h=[];for(const[o,l]of R(i))if(!(!i.tables.has(o)||o==="relations"))for(const b of l)!(o==="nodes"&&b==="profile_id")&&!(o==="crons"&&b==="profile")&&h.push([o,b,""]);h.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[o,l,b]of h)await t.prepareUncached(`INSERT INTO ${e("_refs")} SELECT ?, ?, ${E(l)}::text FROM ${e(o)} ${b===""?"WHERE":`${b} AND`} ${E(l)} IS NOT NULL
5
- AND ${E(l)}::text NOT IN (SELECT id FROM ${e("objects")}) AND ${E(l)}::text IN (SELECT id FROM ${c("objects")})`).run(o,l);const N=await $(t,`WITH RECURSIVE chain(start, id) AS (
6
- SELECT DISTINCT value, value FROM ${e("_refs")}
7
- UNION SELECT c.start, o.owner FROM chain c JOIN ${c("objects")} o ON o.id = c.id JOIN ${c("objects")} up ON up.id = o.owner AND up.type <> 'app'),
1
+ var q=Object.defineProperty;var i=(a,t)=>q(a,"name",{value:t,configurable:!0});import{parseBlobKey as L}from"../bundle/blob-keys.js";import{q as _}from"./catalog.js";import{objectIdColumns as J}from"./rewrite.js";import{ImportLaneError as D}from"./stage.js";const P=/^user:[A-Za-z0-9._-]+$/,A=i(a=>a.replace(/^user:/,""),"bare"),g=i((a,t)=>`${_(a)}.${_(t)}`,"sq"),f=i(async(a,t,...c)=>await a.prepareUncached(t).all(...c),"all");function S(a,t){return new D("bind","person_mismatch",a,t)}i(S,"mismatch");function Z(a,t,c,b){if(a===t||a===c)return c;throw S(`${b} names ${a}, which is neither the bundle's person nor the importing person`,{where:b,value:a})}i(Z,"boundSub");async function Q(a,t,c,b){if(!P.test(c))throw S(`the bundle's person ${JSON.stringify(c)} is not a user:<id> principal`,{where:"source.json person",value:c});if(c===b)return;const p=i(r=>g(t,r),"T"),o=await a.prepareUncached(`SELECT 'identities' AS tbl FROM ${p("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
+ UNION ALL SELECT 'grants' FROM ${p("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${p("profiles")} WHERE person = ?
3
+ UNION ALL SELECT 'nodes' FROM ${p("nodes")} WHERE sub = ? LIMIT 1`).get(c,c,c,c);if(o!==void 0)throw S(`the bundle's person ${c} is already a person in the target (${o.tbl}), not the importing person ${b}`,{where:`${o.tbl}`,value:c})}i(Q,"checkSourcePerson");const K=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"]],Y=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function ee(a){const{db:t,schema:c,sourcePerson:b,targetPerson:p}=a,o=i(l=>g(c,l),"S"),r=i((l,u)=>{throw S(`${l} names ${u.join(", ")}, who is neither the bundle's person ${b} nor the importing person ${p}`,{where:l,values:u})},"refuse");for(const[l,u]of K){const n=await f(t,`SELECT DISTINCT ${_(u)} AS v FROM ${o(l)} WHERE ${_(u)} IS NOT NULL AND ${_(u)} <> '' AND ${_(u)} NOT IN (?, ?) LIMIT 5`,b,p);n.length>0&&r(`${l}.${u}`,n.map(d=>d.v))}for(const[l,u]of Y){const n=await f(t,`SELECT DISTINCT ${_(u)} AS v FROM ${o(l)} WHERE ${_(u)} LIKE 'user:%' AND ${_(u)} NOT IN (?, ?) LIMIT 5`,b,p);n.length>0&&r(`${l}.${u}`,n.map(d=>d.v))}const E=await f(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,b,p);E.length>0&&r("identities.external_id",E.map(l=>l.v));const I=await f(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
4
+ WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,b,p);I.length>0&&r("daemon_actions principal.sub",I.map(l=>l.v));const N=await f(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,A(b),A(p));N.length>0&&r("relations acts_for subject",N.map(l=>l.v));const $=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return $>0?{relations:$}:{}}i(ee,"checkStagedPersons");async function te(a){const{db:t,schema:c,target:b,catalog:p,targetPerson:o}=a,r=i(n=>g(c,n),"S"),E=i(n=>g(b,n),"T"),I=A(o);await t.exec(`CREATE TABLE ${r("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const N=[];for(const[n,d]of J(p))if(!(!p.tables.has(n)||n==="relations"))for(const h of d)!(n==="nodes"&&h==="profile_id")&&!(n==="crons"&&h==="profile")&&N.push([n,h,""]);N.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[n,d,h]of N)await t.prepareUncached(`INSERT INTO ${r("_refs")} SELECT ?, ?, ${_(d)}::text FROM ${r(n)} ${h===""?"WHERE":`${h} AND`} ${_(d)} IS NOT NULL
5
+ AND ${_(d)}::text NOT IN (SELECT id FROM ${r("objects")}) AND ${_(d)}::text IN (SELECT id FROM ${E("objects")})`).run(n,d);const $=await f(t,`WITH RECURSIVE chain(start, id) AS (
6
+ SELECT DISTINCT value, value FROM ${r("_refs")}
7
+ UNION SELECT c.start, o.owner FROM chain c JOIN ${E("objects")} o ON o.id = c.id JOIN ${E("objects")} up ON up.id = o.owner AND up.type <> 'app'),
8
8
  ok(id) AS (
9
- SELECT o.id FROM ${c("objects")} o WHERE o.type = 'app'
10
- UNION SELECT d.object FROM ${c("documents")} d WHERE d.source_path IS NOT NULL
11
- UNION SELECT i.object FROM ${c("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
12
- UNION SELECT r.resource_id FROM ${c("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)
13
- SELECT r.tbl, r.col, r.value FROM ${e("_refs")} r
14
- WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,n,f);if(N.length>0)throw _(`the bundle refers to objects that are not ${n}'s: ${N.map(o=>`${o.tbl}.${o.col}=${o.value}`).join(", ")}`,{references:N});const p=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[o,l]of p){const b=await $(t,`SELECT DISTINCT s.${E(l)} AS v FROM ${e(o)} s JOIN ${c("profiles")} p ON p.id = s.${E(l)} WHERE p.person <> ? LIMIT 5`,n);if(b.length>0)throw _(`${o}.${l} names profiles that belong to another person: ${b.map(T=>T.v).join(", ")}`,{where:`${o}.${l}`,values:b.map(T=>T.v)})}for(const[o,l]of[["nodes","grant_id"],["crons","grant_id"]]){const b=await $(t,`SELECT DISTINCT s.${E(l)} AS v FROM ${e(o)} s JOIN ${c("grants")} g ON g.id = s.${E(l)} WHERE g.sub <> ? LIMIT 5`,n);if(b.length>0)throw _(`${o}.${l} names grants that belong to another person: ${b.map(T=>T.v).join(", ")}`,{where:`${o}.${l}`,values:b.map(T=>T.v)})}const d=await $(t,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${e("daemon_actions")} d
15
- JOIN ${c("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,n);if(d.length>0)throw _(`a queued action names grants that belong to another person: ${d.map(o=>o.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:d.map(o=>o.v)})}u(W,"checkStagedReferences");const O=u((s,t)=>new m("bind","bundle_invalid",s,t),"bundleInvalid");async function U(s){const{db:t,schema:r}=s,a=u(e=>I(r,e),"S"),i=new Set((await $(t,`SELECT node_id AS v FROM ${a("nodes")}`)).map(e=>e.v)),n=u((e,c,f,h)=>{const N=L(c);if(N===null||N.kind!==f||h!==void 0&&c!==h)throw O(`${e} holds ${JSON.stringify(c)}, which is not a ${f} blob key${h===void 0?"":` of the shape ${h}`}`,{where:e,value:c});if(!i.has(N.owner))throw _(`${e} holds ${c}, which belongs to node ${N.owner}, who is not in the bundle`,{where:e,value:c})},"check");for(const e of await $(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${a("conversation_parts")}`))if(n("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw O(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of await $(t,`SELECT blob_key FROM ${a("upload_uses")} WHERE blob_key IS NOT NULL`))n("upload_uses.blob_key",e.blob_key,"attachment");for(const e of await $(t,`SELECT object, output_key FROM ${a("jobs")} WHERE output_key IS NOT NULL`)){const c=e.output_key.split("/")[1]??"";n("jobs.output_key",e.output_key,"job",`jobs/${c}/${e.object}/output`)}}u(U,"checkStagedBlobKeys");async function q(s){const{db:t,schema:r}=s;for(const a of await $(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${I(r,"human_requests")}`))for(const i of["request_dir","presentation_dir","file"]){const n=a[i];if(n===null||!n.startsWith("requests/"))continue;const e=L(n.includes("/",9)?n:`${n}/x`);if(e===null||e.kind!=="request")throw O(`human_requests.${i} holds ${JSON.stringify(n)}, which is not a request blob key`,{where:`human_requests.${i}`,value:n});if(e.owner!==a.request_id)throw _(`human_requests.${i} of ${a.request_id} holds ${n}, which belongs to request ${e.owner}`,{where:`human_requests.${i}`,value:n})}}u(q,"checkStagedRequestKeys");export{D as boundSub,k as checkSourcePerson,U as checkStagedBlobKeys,H as checkStagedPersons,W as checkStagedReferences,q as checkStagedRequestKeys};
9
+ SELECT o.id FROM ${E("objects")} o WHERE o.type = 'app'
10
+ UNION SELECT d.object FROM ${E("documents")} d WHERE d.source_path IS NOT NULL
11
+ UNION SELECT i.object FROM ${E("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
12
+ UNION SELECT r.resource_id FROM ${E("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)
13
+ SELECT r.tbl, r.col, r.value FROM ${r("_refs")} r
14
+ WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,o,I);if($.length>0)throw S(`the bundle refers to objects that are not ${o}'s: ${$.map(n=>`${n.tbl}.${n.col}=${n.value}`).join(", ")}`,{references:$});const l=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[n,d]of l){const h=await f(t,`SELECT DISTINCT s.${_(d)} AS v FROM ${r(n)} s JOIN ${E("profiles")} p ON p.id = s.${_(d)} WHERE p.person <> ? LIMIT 5`,o);if(h.length>0)throw S(`${n}.${d} names profiles that belong to another person: ${h.map(T=>T.v).join(", ")}`,{where:`${n}.${d}`,values:h.map(T=>T.v)})}for(const[n,d]of[["nodes","grant_id"],["crons","grant_id"]]){const h=await f(t,`SELECT DISTINCT s.${_(d)} AS v FROM ${r(n)} s JOIN ${E("grants")} g ON g.id = s.${_(d)} WHERE g.sub <> ? LIMIT 5`,o);if(h.length>0)throw S(`${n}.${d} names grants that belong to another person: ${h.map(T=>T.v).join(", ")}`,{where:`${n}.${d}`,values:h.map(T=>T.v)})}const u=await f(t,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${r("daemon_actions")} d
15
+ JOIN ${E("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,o);if(u.length>0)throw S(`a queued action names grants that belong to another person: ${u.map(n=>n.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:u.map(n=>n.v)})}i(te,"checkStagedReferences");const k=i((a,t)=>new D("bind","bundle_invalid",a,t),"bundleInvalid");async function oe(a){const{db:t,schema:c,target:b,targetPerson:p}=a,o=i(e=>g(c,e),"S"),r=new Set((await f(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),E=await f(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),I=await f(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),N=await f(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),$=i(e=>e.split("/")[1]??"","jobOwner"),l=i((e,s,w,O)=>{const F=L(s);if(F===null||F.kind!==w||O!==void 0&&s!==O)throw k(`${e} holds ${JSON.stringify(s)}, which is not a ${w} blob key${O===void 0?"":` of the shape ${O}`}`,{where:e,value:s})},"shaped");for(const e of E)if(l("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of I)l("upload_uses.blob_key",e.blob_key,"attachment");for(const e of N)l("jobs.output_key",e.output_key,"job",`jobs/${$(e.output_key)}/${e.object}/output`);const u=new Set;for(const{blob_key:e}of E){const s=L(e);s!==null&&s.kind==="conversation"&&!r.has(s.owner)&&u.add(s.owner)}for(const{blob_key:e}of I){const s=L(e);s!==null&&s.kind==="attachment"&&!r.has(s.owner)&&u.add(s.owner)}for(const{output_key:e}of N)r.has($(e))||u.add($(e));const n=new Map((u.size===0?[]:await f(t,`SELECT node_id, sub FROM ${g(b,"nodes")} WHERE node_id = ANY(?::text[])`,[...u])).map(e=>[e.node_id,e.sub])),d=i(e=>r.has(e)||n.get(e)===p,"held"),h=i(e=>!r.has(e)&&!n.has(e),"gone"),T={},m=i((e,s)=>{s>0&&(T[e]=(T[e]??0)+s)},"count"),R=i(async(e,...s)=>Number((await t.prepareUncached(e).run(...s)).changes),"drop"),H=new Set((await f(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),v=new Map;for(const{conversation_id:e,blob_key:s}of E){const w=L(s),O=v.get(e);O!==null&&(w===null||w.kind!=="conversation"?v.set(e,null):v.set(e,[...O??[],w.owner]))}const y=[...v].filter(([e,s])=>s!==null&&!H.has(e)&&s.every(h)).map(([e])=>e);y.length>0&&(m("conversation_parts",await R(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,y)),m("conversation_entries",await R(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,y)));const W=new Set(y),j=i((e,s)=>{const w=L(s).owner;if(!d(w))throw S(`${e} holds ${s}, which belongs to node ${w}, who is not in the bundle`,{where:e,value:s})},"owned");for(const e of E)W.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const M=I.filter(e=>{const s=L(e.blob_key);return s!==null&&s.kind==="attachment"&&h(s.owner)&&!r.has(e.run_id)});M.length>0&&m("upload_uses",await R(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,M.map(e=>e.run_id),M.map(e=>e.path)));const U=new Set(M);for(const e of I)U.has(e)||j("upload_uses.blob_key",e.blob_key);const C=N.filter(e=>e.output_key===`jobs/${$(e.output_key)}/${e.object}/output`&&h($(e.output_key)));C.length>0&&m("jobs",await R(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,C.map(e=>e.object)));const x=new Set(C);for(const e of N)x.has(e)||j("jobs.output_key",e.output_key);return T}i(oe,"checkStagedBlobKeys");async function ne(a){const{db:t,schema:c}=a;for(const b of await f(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(c,"human_requests")}`))for(const p of["request_dir","presentation_dir","file"]){const o=b[p];if(o===null||!o.startsWith("requests/"))continue;const r=L(o.includes("/",9)?o:`${o}/x`);if(r===null||r.kind!=="request")throw k(`human_requests.${p} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${p}`,value:o});if(r.owner!==b.request_id)throw S(`human_requests.${p} of ${b.request_id} holds ${o}, which belongs to request ${r.owner}`,{where:`human_requests.${p}`,value:o})}}i(ne,"checkStagedRequestKeys");export{Z as boundSub,Q as checkSourcePerson,oe as checkStagedBlobKeys,ee as checkStagedPersons,te as checkStagedReferences,ne as checkStagedRequestKeys};
@@ -5,6 +5,8 @@ export interface MovedBlobs {
5
5
  left: number;
6
6
  }
7
7
  /** `created` collects the keys this call wrote, so the caller can delete them if the run fails before its copy commits. */
8
- export declare function moveRunBlobs(db: CanvasDb, schema: string, blobs: BlobStore, runId: string, created: string[]): Promise<MovedBlobs>;
8
+ export declare function moveRunBlobs(db: CanvasDb, schema: string, target: string, person: string, blobs: BlobStore, runId: string, created: string[]): Promise<MovedBlobs>;
9
+ /** Delete the keys, concurrently. With `bestEffort`, a key that cannot be deleted is skipped and the rest still go; otherwise the first failure is thrown. */
10
+ export declare function deleteBlobs(blobs: BlobStore, keys: readonly string[], bestEffort?: boolean): Promise<void>;
9
11
  /** Delete the run's uploaded copies (after the run is done). */
10
12
  export declare function deleteRunBlobs(blobs: BlobStore, runId: string): Promise<void>;
@@ -1 +1 @@
1
- var S=Object.defineProperty;var r=(e,n)=>S(e,"name",{value:n,configurable:!0});import{parseBlobKey as q,runBlobPrefix as f}from"../bundle/blob-keys.js";import{q as m}from"./catalog.js";import{ImportLaneError as h}from"./stage.js";const E=8;async function k(e,n,o,g,y){const v={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${m(n)}.nodes`).all()).map(t=>t.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${m(n)}.human_requests`).all()).map(t=>t.v))},w=f(g),s=await o.list(w),i={moved:0,left:0};let p=0;const x=r(async()=>{for(let t=p++;t<s.length;t=p++){const l=s[t],a=l.slice(w.length),c=q(a);if(c===null||!v[c.ownerTable].has(c.owner)){i.left+=1;continue}const u=await o.get(l);if(u===null)throw new h("blobs","bundle_invalid",`${l} was listed and is gone`);const d=await o.get(a);if(d===null)await o.put(a,u),y.push(a);else if(!d.equals(u))throw new h("blobs","unique_conflict",`${a} already exists with other contents; the import does not replace it`,{key:a});i.moved+=1}},"worker");return await Promise.all(Array.from({length:Math.min(E,s.length)},x)),i}r(k,"moveRunBlobs");async function A(e,n){for(const o of await e.list(f(n)))await e.delete(o)}r(A,"deleteRunBlobs");export{A as deleteRunBlobs,k as moveRunBlobs};
1
+ var O=Object.defineProperty;var o=(e,t)=>O(e,"name",{value:t,configurable:!0});import{parseBlobKey as S,runBlobPrefix as E}from"../bundle/blob-keys.js";import{q as h}from"./catalog.js";import{ImportLaneError as y}from"./stage.js";const v=256;function B(){const e=process.env.CRTR_IMPORT_BLOB_WORKERS;if(e===void 0||e==="")return v;const t=Number(e);if(!Number.isInteger(t)||t<1||t>1024)throw new Error(`CRTR_IMPORT_BLOB_WORKERS must be an integer from 1 to 1024, got ${JSON.stringify(e)}`);return t}o(B,"workerLimit");async function p(e,t){if(e.length===0)return;let s=0,n;const i=o(async()=>{for(;n===void 0&&s<e.length;)try{await t(e[s++])}catch(l){n??={error:l}}},"worker");if(await Promise.all(Array.from({length:Math.min(B(),e.length)},i)),n!==void 0)throw n.error}o(p,"forEachBounded");async function N(e,t,s,n,i,l,f){const u={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${h(t)}.nodes UNION SELECT node_id FROM ${h(s)}.nodes WHERE sub = ?`).all(n)).map(a=>a.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${h(t)}.human_requests`).all()).map(a=>a.v))},c=E(l),w={moved:0,left:0},d=[];for(const a of await i.list(c)){const r=S(a.slice(c.length));r===null||!u[r.ownerTable].has(r.owner)?w.left+=1:d.push(a)}const g=new Set,R=new Set(d.map(a=>a.slice(c.length)));return await p([...new Set([...R].map(x))],async a=>{for(const r of await i.list(a))R.has(r)&&g.add(r)}),await p(d,async a=>{const r=a.slice(c.length);if(g.has(r)){if(!await T(i,a,r))throw new y("blobs","unique_conflict",`${r} already exists with other contents; the import does not replace it`,{key:r})}else if(f.push(r),!await i.copy(a,r))throw m(a);w.moved+=1}),w}o(N,"moveRunBlobs");const x=o(e=>e.split("/").slice(0,2).join("/")+"/","ownerPrefix"),m=o(e=>new y("blobs","bundle_invalid",`${e} was listed and is gone`),"gone");async function T(e,t,s){const[n,i]=await Promise.all([e.head(t),e.head(s)]);if(n===null)throw m(t);if(i===null||n.size!==i.size)return!1;if(n.etag!==null&&i.etag!==null)return n.etag===i.etag;for(let l=0;l<n.size;l+=_){const f={start:l,length:Math.min(_,n.size-l)},[u,c]=await Promise.all([e.get(t,f),e.get(s,f)]);if(u===null)throw m(t);if(c===null||!u.equals(c))return!1}return!0}o(T,"sameObject");const _=256*1024;async function L(e,t,s=!1){await p(t,s?n=>e.delete(n).catch(()=>{}):n=>e.delete(n))}o(L,"deleteBlobs");async function $(e,t){await L(e,await e.list(E(t)))}o($,"deleteRunBlobs");export{L as deleteBlobs,$ as deleteRunBlobs,N as moveRunBlobs};
@@ -1,14 +1,14 @@
1
- var h=Object.defineProperty;var l=(n,a)=>h(n,"name",{value:a,configurable:!0});import{createHash as g}from"node:crypto";import{ROOT_PROFILE_ID as j}from"../../profiles/manifest.js";import{substitutePerson as D}from"../../canvas/person.js";import{withCanvasWrite as A}from"../../canvas/db.js";import{ImportLaneError as _}from"./stage.js";import{q as T}from"./catalog.js";const I=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"]],M=[["nodes","grant_id"],["crons","grant_id"]],S={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},H=["app","person","profile","repo"];function C(n){const a=new Map,o=l((c,d)=>{a.has(c)||a.set(c,new Set),a.get(c).add(d)},"add");for(const c of n.foreignKeys)c.parent==="objects"&&c.columns.length===1&&o(c.table,c.columns[0]);for(const[c,d]of I)o(c,d);return a}l(C,"objectIdColumns");const N=l((n,a)=>`${T(n)}.${T(a)}`,"sq"),E=l(async(n,a,...o)=>Number((await n.prepareUncached(a).run(...o)).changes),"run"),O=l(async(n,a,...o)=>await n.prepareUncached(a).all(...o),"rows");async function K(n){n.sourcePerson!==n.targetPerson&&await A(async a=>{await a.exec(`SET LOCAL search_path TO ${T(n.schema)}`),await D(a,n.sourcePerson,n.targetPerson)})}l(K,"rewritePerson");async function W(n,a,o,c,d){return o===null?void 0:(await n.prepareUncached(`SELECT id FROM ${N(a,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,c,d))?.id}l(W,"findFleetGrant");function F(n){return new _("id_map","grant_missing",`no grant in the target for: ${n.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...n]})}l(F,"grantMissing");async function Y(n,a){const{db:o,schema:c,target:d}=n,t=l(e=>N(c,e),"S"),m=l(e=>N(d,e),"T"),f={object:new Map,grant:new Map,kind:new Map};for(const[e,p]of a)f.object.set(e,p);const i=n.targetPerson.replace(/^user:/,"");for(const e of H){const p=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${m("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,R=await O(o,`SELECT i.object AS src, t.object AS dst FROM ${t("identities")} i
1
+ var h=Object.defineProperty;var l=(n,s)=>h(n,"name",{value:s,configurable:!0});import{createHash as D}from"node:crypto";import{ROOT_PROFILE_ID as L}from"../../profiles/manifest.js";import{substitutePerson as A}from"../../canvas/person.js";import{withCanvasWrite as I}from"../../canvas/db.js";import{ImportLaneError as j}from"./stage.js";import{q as T}from"./catalog.js";const M=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"],["waits","target_id"]],H=[["nodes","grant_id"],["crons","grant_id"]],w={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},C=["app","person","profile","repo"];function S(n){const s=new Map,o=l((E,d)=>{s.has(E)||s.set(E,new Set),s.get(E).add(d)},"add");for(const E of n.foreignKeys)E.parent==="objects"&&E.columns.length===1&&o(E.table,E.columns[0]);for(const[E,d]of M)o(E,d);return s}l(S,"objectIdColumns");const N=l((n,s)=>`${T(n)}.${T(s)}`,"sq"),p=l(async(n,s,...o)=>Number((await n.prepareUncached(s).run(...o)).changes),"run"),O=l(async(n,s,...o)=>await n.prepareUncached(s).all(...o),"rows");async function K(n){n.sourcePerson!==n.targetPerson&&await I(async s=>{await s.exec(`SET LOCAL search_path TO ${T(n.schema)}`),await A(s,n.sourcePerson,n.targetPerson)})}l(K,"rewritePerson");async function W(n,s,o,E,d){return o===null?void 0:(await n.prepareUncached(`SELECT id FROM ${N(s,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,E,d))?.id}l(W,"findFleetGrant");function F(n){return new j("id_map","grant_missing",`no grant in the target for: ${n.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...n]})}l(F,"grantMissing");async function Y(n,s){const{db:o,schema:E,target:d}=n,t=l(e=>N(E,e),"S"),m=l(e=>N(d,e),"T"),b={object:new Map,grant:new Map,kind:new Map};for(const[e,r]of s)b.object.set(e,r);const i=n.targetPerson.replace(/^user:/,"");for(const e of C){const r=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${m("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,f=await O(o,`SELECT i.object AS src, t.object AS dst FROM ${t("identities")} i
2
2
  JOIN ${t("objects")} so ON so.id = i.object AND so.type = ?
3
3
  JOIN ${m("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id
4
4
  JOIN ${m("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
5
- WHERE ${p}`,e,e==="person"?n.targetPerson:i);for(const{src:$,dst:L}of R)$!==L&&f.object.set($,L)}const r=await O(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${t("objects")} o JOIN ${t("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL`);for(const e of r){const p=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("documents")} d ON d.object = o.id
6
- WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(f.object.get(e.owner)??e.owner,e.name);if(p!==void 0){f.object.set(e.id,p.id);continue}const R=n.shippedBodies[e.id];if(R===void 0)throw new _("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const $=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("identities")} i ON i.object = o.id
5
+ WHERE ${r}`,e,e==="person"?n.targetPerson:i);for(const{src:R,dst:_}of f)R!==_&&b.object.set(R,_)}const u=await O(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${t("objects")} o JOIN ${t("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL`);for(const e of u){const r=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("documents")} d ON d.object = o.id
6
+ WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(b.object.get(e.owner)??e.owner,e.name);if(r!==void 0){b.object.set(e.id,r.id);continue}const f=n.shippedBodies[e.id];if(f===void 0)throw new j("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const R=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("identities")} i ON i.object = o.id
7
7
  WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ?
8
8
  UNION ALL SELECT o.id FROM ${t("objects")} o JOIN ${t("identities")} i ON i.object = o.id
9
- WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(n.targetPerson,n.targetPerson);if($===void 0)throw new _("id_map","bundle_invalid",`no person object for ${n.targetPerson}; cannot import shipped document ${e.name}`);await E(o,`UPDATE ${t("objects")} SET owner = ? WHERE id = ?`,$.id,e.id),await E(o,`DELETE FROM ${t("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await E(o,`INSERT INTO ${t("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
10
- VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,i,e.created_at),await E(o,`UPDATE ${t("documents")} SET source_path = NULL WHERE object = ?`,e.id),await E(o,`UPDATE ${t("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${t("revision_parents")} p WHERE p.parent = r.rev_id)`,R,e.id)}const s=await O(o,`SELECT id, sub, grantee FROM ${t("grants")} ORDER BY id`),u=[];for(const e of s){const p=await W(o,d,n.fleetRuntime,e.sub,e.grantee);p===void 0?u.push(e.grantee):f.grant.set(e.id,p)}if(u.length>0)throw F(u);await o.exec(`CREATE TABLE ${t("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,p]of[["object",f.object],["grant",f.grant]])for(const[R,$]of p)await E(o,`INSERT INTO ${t("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,R,$);const b=`(SELECT source FROM ${t("_idmap")} WHERE kind = 'object')`;for(const[e,p]of Object.entries(S))await E(o,`DELETE FROM ${t(e)} WHERE ${p} IN ${b}`);await E(o,`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${b})`),await E(o,`DELETE FROM ${t("revisions")} WHERE document IN ${b}`);for(const[e,p]of C(n.catalog))if(n.catalog.tables.has(e))for(const R of p)await w(o,t(e),R,"object",t("_idmap"));for(const[e,p]of M)await w(o,t(e),p,"grant",t("_idmap"));await E(o,`UPDATE ${t("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
11
- FROM ${t("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await E(o,`DELETE FROM ${t("objects")} WHERE id IN ${b}`),await E(o,`UPDATE ${t("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${t("identities")} WHERE scheme = 'user' AND external_id = ?)`,i,i,n.targetPerson);for(const{name:e}of await O(o,`SELECT k.name FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`))f.kind.set(e,e);return await E(o,`DELETE FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`),f}l(Y,"rewriteIds");async function B(n){const{db:a,schema:o,target:c,targetPerson:d}=n,t=new Map,m=l(async(i,...r)=>await a.prepareUncached(i).get(...r),"row"),f=l(i=>E(a,`DELETE FROM ${N(o,"profiles")} WHERE id = ?`,i),"dropStaged");for(const{id:i}of await O(a,`SELECT id FROM ${N(o,"profiles")} ORDER BY id`)){let r=i===j?await m(`SELECT id, person FROM ${N(c,"profiles")} WHERE person = ? AND name = 'root'`,d):await m(`SELECT id, person FROM ${N(c,"profiles")} WHERE id = ? AND person = ?`,i,d);if(r===void 0){if(await m(`SELECT id, person FROM ${N(c,"profiles")} WHERE id = ?`,i)===void 0&&i!==j)continue;const b=`${i.replace(/-[0-9a-f]{8}$/,"")}-${g("sha256").update(`${d}\0${i}`).digest("hex").slice(0,8)}`,e=await m(`SELECT id, person FROM ${N(c,"profiles")} WHERE id = ?`,b);if(e!==void 0&&e.person!==d)throw new _("id_map","unique_conflict",`profiles ${b} is held by another person in the target`,{table:"profiles",values:[b]});r=e??{id:b,person:d},e===void 0?await E(a,`UPDATE ${N(o,"profiles")} SET id = ? WHERE id = ?`,b,i):await f(i)}else await f(i);const s=r.id;await E(a,`UPDATE ${N(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${N(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
12
- AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${N(c,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,s,i,s,i),await E(a,`UPDATE ${N(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${N(o,"objects")} WHERE type = 'profile')`,s,i),s!==i&&t.set(i,s)}return t}l(B,"mapProfileIds");async function w(n,a,o,c,d){await E(n,`UPDATE ${a} t SET ${T(o)} = m.target FROM ${d} m WHERE m.kind = ? AND t.${T(o)} = m.source`,c)}l(w,"remap");async function X(n){const{db:a,schema:o,target:c,catalog:d}=n,t=l(r=>N(o,r),"S"),m={},f=l((r,s)=>{s>0&&(m[r]=(m[r]??0)+s)},"count");await a.exec(`CREATE TABLE ${t("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const i=`(SELECT id FROM ${t("objects")} WHERE home_machine IS NOT NULL)`;await E(a,`INSERT INTO ${t("_dropped")} SELECT 'objects', id FROM ${t("objects")} WHERE home_machine IS NOT NULL`);for(const[r,s]of Object.entries(S))f(r,await E(a,`DELETE FROM ${t(r)} WHERE ${s} IN ${i}`));for(f("objects",await E(a,`DELETE FROM ${t("objects")} WHERE home_machine IS NOT NULL`));;){let r=0;for(const s of d.foreignKeys){if(s.columns.length!==1||s.parentColumns.length!==1||!n.catalog.tables.has(s.table))continue;const u=d.tables.get(s.table),b=T(s.columns[0]),e=u.primaryKey.length===1?T(u.primaryKey[0]):null;e!==null&&await E(a,`INSERT INTO ${t("_dropped")} SELECT ?, ${e}::text FROM ${t(s.table)} WHERE ${b} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?) ON CONFLICT DO NOTHING`,s.table,s.parent);const p=await E(a,`DELETE FROM ${t(s.table)} WHERE ${b} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?)`,s.parent);f(s.table,p),r+=p}if(r===0)break}for(const r of d.foreignKeys){if(r.columns.length!==1||!d.tables.has(r.table))continue;const s=T(r.columns[0]),u=T(r.parentColumns[0]),b=await O(a,`SELECT DISTINCT c.${s}::text AS value FROM ${t(r.table)} c
13
- WHERE c.${s} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${t(r.parent)} p WHERE p.${u} = c.${s})
14
- AND NOT EXISTS (SELECT 1 FROM ${N(c,r.parent)} p WHERE p.${u} = c.${s}) LIMIT 10`);if(b.length>0)throw new _("drop","bundle_invalid",`${r.table}.${r.columns[0]} names rows that exist nowhere: ${b.map(e=>e.value).join(", ")}`,{table:r.table,column:r.columns[0],values:b.map(e=>e.value)})}return m}l(X,"dropStubRows");export{I as OBJECT_ID_COLUMNS,X as dropStubRows,W as findFleetGrant,F as grantMissing,B as mapProfileIds,C as objectIdColumns,Y as rewriteIds,K as rewritePerson};
9
+ WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(n.targetPerson,n.targetPerson);if(R===void 0)throw new j("id_map","bundle_invalid",`no person object for ${n.targetPerson}; cannot import shipped document ${e.name}`);await p(o,`UPDATE ${t("objects")} SET owner = ? WHERE id = ?`,R.id,e.id),await p(o,`DELETE FROM ${t("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await p(o,`INSERT INTO ${t("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
10
+ VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,i,e.created_at),await p(o,`UPDATE ${t("documents")} SET source_path = NULL WHERE object = ?`,e.id),await p(o,`UPDATE ${t("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${t("revision_parents")} p WHERE p.parent = r.rev_id)`,f,e.id)}const $=await O(o,`SELECT id, sub, grantee FROM ${t("grants")} ORDER BY id`),a=[];for(const e of $){const r=await W(o,d,n.fleetRuntime,e.sub,e.grantee);r===void 0?a.push(e.grantee):b.grant.set(e.id,r)}if(a.length>0)throw F(a);await o.exec(`CREATE TABLE ${t("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,r]of[["object",b.object],["grant",b.grant]])for(const[f,R]of r)await p(o,`INSERT INTO ${t("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,f,R);const c=`(SELECT source FROM ${t("_idmap")} WHERE kind = 'object')`;for(const[e,r]of Object.entries(w))await p(o,`DELETE FROM ${t(e)} WHERE ${r} IN ${c}`);await p(o,`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${c})`),await p(o,`DELETE FROM ${t("revisions")} WHERE document IN ${c}`);for(const[e,r]of S(n.catalog))if(n.catalog.tables.has(e))for(const f of r)await g(o,t(e),f,"object",t("_idmap"));for(const[e,r]of H)await g(o,t(e),r,"grant",t("_idmap"));await p(o,`UPDATE ${t("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
11
+ FROM ${t("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(o,`DELETE FROM ${t("objects")} WHERE id IN ${c}`),await p(o,`UPDATE ${t("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${t("identities")} WHERE scheme = 'user' AND external_id = ?)`,i,i,n.targetPerson);for(const{name:e}of await O(o,`SELECT k.name FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`))b.kind.set(e,e);return await p(o,`DELETE FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`),b}l(Y,"rewriteIds");async function B(n){const{db:s,schema:o,target:E,targetPerson:d}=n,t=new Map,m=l(async(i,...u)=>await s.prepareUncached(i).get(...u),"row"),b=l(i=>p(s,`DELETE FROM ${N(o,"profiles")} WHERE id = ?`,i),"dropStaged");for(const{id:i}of await O(s,`SELECT id FROM ${N(o,"profiles")} ORDER BY id`)){let u=i===L?await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE person = ? AND name = 'root'`,d):await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ? AND person = ?`,i,d);if(u===void 0){if(await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ?`,i)===void 0&&i!==L)continue;const c=`${i.replace(/-[0-9a-f]{8}$/,"")}-${D("sha256").update(`${d}\0${i}`).digest("hex").slice(0,8)}`,e=await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ?`,c);if(e!==void 0&&e.person!==d)throw new j("id_map","unique_conflict",`profiles ${c} is held by another person in the target`,{table:"profiles",values:[c]});u=e??{id:c,person:d},e===void 0?await p(s,`UPDATE ${N(o,"profiles")} SET id = ? WHERE id = ?`,c,i):await b(i)}else await b(i);const $=u.id;await p(s,`UPDATE ${N(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${N(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
12
+ AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${N(E,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,$,i,$,i),await p(s,`UPDATE ${N(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${N(o,"objects")} WHERE type = 'profile')`,$,i),$!==i&&t.set(i,$)}return t}l(B,"mapProfileIds");async function g(n,s,o,E,d){await p(n,`UPDATE ${s} t SET ${T(o)} = m.target FROM ${d} m WHERE m.kind = ? AND t.${T(o)} = m.source`,E)}l(g,"remap");async function X(n){const{db:s,schema:o,target:E,catalog:d}=n,t=l(a=>N(o,a),"S"),m={},b=l((a,c)=>{c>0&&(m[a]=(m[a]??0)+c)},"count");await s.exec(`CREATE TABLE ${t("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const i=`(SELECT id FROM ${t("objects")} WHERE home_machine IS NOT NULL)`;await p(s,`INSERT INTO ${t("_dropped")} SELECT 'objects', id FROM ${t("objects")} WHERE home_machine IS NOT NULL`);for(const[a,c]of Object.entries(w))b(a,await p(s,`DELETE FROM ${t(a)} WHERE ${c} IN ${i}`));b("objects",await p(s,`DELETE FROM ${t("objects")} WHERE home_machine IS NOT NULL`));const u=new Map;for(const[a,c]of S(d))d.tables.has(a)&&a!=="messages"&&u.set(a,[...c]);const $=`(SELECT key FROM ${t("_dropped")} WHERE tbl = 'objects')`;for(;;){let a=0;const c=l(async(e,r,...f)=>{const R=d.tables.get(e).primaryKey.length===1?T(d.tables.get(e).primaryKey[0]):null;R!==null&&await p(s,`INSERT INTO ${t("_dropped")} SELECT ?, ${R}::text FROM ${t(e)} WHERE ${r} ON CONFLICT DO NOTHING`,e,...f);const _=await p(s,`DELETE FROM ${t(e)} WHERE ${r}`,...f);b(e,_),a+=_},"drop");for(const e of d.foreignKeys)e.columns.length!==1||e.parentColumns.length!==1||!n.catalog.tables.has(e.table)||await c(e.table,`${T(e.columns[0])} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?)`,e.parent);for(const[e,r]of u)await c(e,r.map(f=>`${T(f)} IN ${$}`).join(" OR "));if(a===0)break}for(const a of d.foreignKeys){if(a.columns.length!==1||!d.tables.has(a.table))continue;const c=T(a.columns[0]),e=T(a.parentColumns[0]),r=await O(s,`SELECT DISTINCT c.${c}::text AS value FROM ${t(a.table)} c
13
+ WHERE c.${c} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${t(a.parent)} p WHERE p.${e} = c.${c})
14
+ AND NOT EXISTS (SELECT 1 FROM ${N(E,a.parent)} p WHERE p.${e} = c.${c}) LIMIT 10`);if(r.length>0)throw new j("drop","bundle_invalid",`${a.table}.${a.columns[0]} names rows that exist nowhere: ${r.map(f=>f.value).join(", ")}`,{table:a.table,column:a.columns[0],values:r.map(f=>f.value)})}return m}l(X,"dropStubRows");export{M as OBJECT_ID_COLUMNS,X as dropStubRows,W as findFleetGrant,F as grantMissing,B as mapProfileIds,S as objectIdColumns,Y as rewriteIds,K as rewritePerson};
@@ -1,3 +1,3 @@
1
- var Q=Object.defineProperty;var u=(e,i)=>Q(e,"name",{value:i,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as Y}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as N}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as S,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as C,encodeKeys as W}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewritePaths as oe,rewriteRequestPaths as de,takeRepoSyncedDocuments as pe}from"./prepare.js";import{boundSub as ce,checkSourcePerson as ue,checkStagedBlobKeys as fe,checkStagedPersons as le,checkStagedReferences as me,checkStagedRequestKeys as _e}from"./bind.js";import{deleteRunBlobs as we,moveRunBlobs as ge}from"./blobs.js";import{dropStubRows as be,findFleetGrant as he,grantMissing as ye,mapProfileIds as Ee,rewriteIds as Se,rewritePerson as ve}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as Re,stagingSchema as Oe,targetSchema as Te}from"./stage.js";import{verifyRun as Pe}from"./verify.js";import{sandboxPathMap as ke,writeNodeFiles as Ie}from"./path-map.js";import{allStoreKeys as je,readPluginsStore as De,recordImportedActivations as Ae,writeStores as Me}from"./stores.js";import{publishImportedPlugins as Ne}from"./publish-plugins.js";import{COPIED_TABLES as Ce}from"../bundle/layout.js";import{ClaimLostError as We}from"../../../daemon/reconcilers/row-claim.js";const L=10*6e4,v=u(()=>new Date().toISOString(),"now"),R=u(async(e,i)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Be(e,i){const n=await e.get(S.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}u(Be,"readSource");async function Le(e,i,n,r,s,d){const t=await e.get(S.rows(n.run_id,"grants")),l=t===null?[]:x(t),m=[];for(const a of l){const p=ce(a.sub,r,n.person,"grants.sub");await he(i,s,d,p,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=L)throw ye(m);return!1}u(Le,"grantsReady");async function pt(e,i,n={}){const r=n.blobs??await Y(),s=await E(),d=Oe(e.run_id),t=u(async a=>{await i.assertOwned(),await R(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const m=[];try{const a=await Be(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const p=await Te(s),b=[...Ce],g=await ae(s,p,[...b,"grants"]);if(!l){const f={},P=[],k=[],I=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ue(s,p,a.person,e.person),!await Le(r,s,e,a.person,p,I)){await i.assertOwned(),await R(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const y=await Ne(await De(r,e.run_id));if(y.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=L)throw new w("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 i.assertOwned(),await R(e.run_id,"waiting_for_directory");return}k.push(...y.refused),await t("stage");const K=await Re(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,c]of Object.entries(K))f[o]={staged:c,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:p,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:I,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,c]of Object.entries(await le(_)))O(f,o,c);await fe(_),await t("rewrite-person"),await ve(_),await t("prune");const U=await ie(s,d,g,a),j=a.kind==="hosted"?ke(a.pathPrefixes??[]):[];await t("rewrite-paths"),await oe(s,d,j),await de(s,d),await _e(_);const F=await Ee(_);await re(s,d,p,a.installId,e.person),await t("rewrite-ids");const D=await Se(_,F);await t("drop");const J=await pe(s,d,p),q=await be(_);for(const[o,c]of Object.entries({...U}))O(f,o,c);for(const[o,c]of Object.entries(q))O(f,o,c);await me(_),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,p,g,b,new Set,$),await t("blobs"),await ge(s,d,r,e.run_id,m),await t("copy"),await N(async o=>{await i.assertOwned();const c=await ne({db:o,runId:e.run_id,schema:d,target:p,catalog:g,source:a,person:e.person,idMap:D,pathMap:j}),A=await Ue(o,e.run_id,J);A>0&&(c.inserted.revisions=(c.inserted.revisions??0)+A),await Ie(o,d,e.run_id,a);const M=await Me({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,z]of Object.entries(M.inserted))c.inserted[G]=z.length;return P.push(...M.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ke(f,c),unresolved_plugins:P,refused_plugins:k}),v(),e.run_id),c}),l=!0,await n.atStep?.("committed")}await t("verify");const h=await Pe(s,e.run_id,d,p,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(h),e.run_id),!h.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:h.differences,invariants:h.invariants});await t("manifest");const T=S.manifest(e.run_id);await r.put(T,await Fe(e.run_id)),await B(s,e.run_id);for(const f of je(e.run_id))await r.delete(f);await we(r,e.run_id),await N(async f=>{await Ae(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(T,v(),e.run_id)})}catch(a){if(a instanceof We)throw a;const p=He(a);if(await B(s,e.run_id).catch(()=>{}),!l)for(const b of m)await r.delete(b).catch(()=>{});await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(p),v(),e.run_id)}}u(pt,"processRun");function He(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}u(He,"failureOf");function O(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(O,"addDropped");function Ke(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}u(Ke,"withInserted");async function Ue(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,l]of d){const m=await Z(e,t);m!==null&&await X(e,m,l.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await H(e,i,"revisions",s.map(t=>[t.rev_id])),await H(e,i,"revision_parents",s.flatMap(t=>t.parents.map(l=>[t.rev_id,l]))),s.length}u(Ue,"arrive");async function H(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,W(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...C(s.inserted_keys),...r]),i,n)}u(H,"appendManifest");async function Fe(e){const n=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(n.map(r=>JSON.stringify({table:r.table_name,keys:C(r.inserted_keys)})).join(`
1
+ var Q=Object.defineProperty;var u=(e,i)=>Q(e,"name",{value:i,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as Y}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as N}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as S,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as C,encodeKeys as B}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewritePaths as oe,rewriteRequestPaths as de,takeRepoSyncedDocuments as pe}from"./prepare.js";import{boundSub as ce,checkSourcePerson as ue,checkStagedBlobKeys as fe,checkStagedPersons as le,checkStagedReferences as me,checkStagedRequestKeys as _e}from"./bind.js";import{deleteBlobs as we,deleteRunBlobs as ge,moveRunBlobs as be}from"./blobs.js";import{dropStubRows as he,findFleetGrant as ye,grantMissing as Ee,mapProfileIds as Se,rewriteIds as ve,rewritePerson as Re}from"./rewrite.js";import{dropStaging as W,ImportLaneError as w,stage as Oe,stagingSchema as Te,targetSchema as Pe}from"./stage.js";import{verifyRun as ke}from"./verify.js";import{sandboxPathMap as je,writeNodeFiles as Ie}from"./path-map.js";import{allStoreKeys as De,readPluginsStore as Ae,recordImportedActivations as Me,writeStores as Ne}from"./stores.js";import{publishImportedPlugins as Ce}from"./publish-plugins.js";import{COPIED_TABLES as Be}from"../bundle/layout.js";import{ClaimLostError as We}from"../../../daemon/reconcilers/row-claim.js";const L=10*6e4,v=u(()=>new Date().toISOString(),"now"),R=u(async(e,i)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Le(e,i){const n=await e.get(S.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}u(Le,"readSource");async function He(e,i,n,r,s,d){const t=await e.get(S.rows(n.run_id,"grants")),l=t===null?[]:x(t),m=[];for(const a of l){const c=ce(a.sub,r,n.person,"grants.sub");await ye(i,s,d,c,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=L)throw Ee(m);return!1}u(He,"grantsReady");async function ct(e,i,n={}){const r=n.blobs??await Y(),s=await E(),d=Te(e.run_id),t=u(async a=>{await i.assertOwned(),await R(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const m=[];try{const a=await Le(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const c=await Pe(s),O=[...Be],g=await ae(s,c,[...O,"grants"]);if(!l){const f={},P=[],k=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ue(s,c,a.person,e.person),!await He(r,s,e,a.person,c,j)){await i.assertOwned(),await R(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await Ce(await Ae(r,e.run_id));if(h.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=L)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${h.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:h.unavailable});await i.assertOwned(),await R(e.run_id,"waiting_for_directory");return}k.push(...h.refused),await t("stage");const K=await Oe(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:c,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await le(_)))y(f,o,p);for(const[o,p]of Object.entries(await fe(_)))y(f,o,p);await t("rewrite-person"),await Re(_),await t("prune");const U=await ie(s,d,g,a),I=a.kind==="hosted"?je(a.pathPrefixes??[]):[];await t("rewrite-paths"),await oe(s,d,I),await de(s,d),await _e(_);const F=await Se(_);await re(s,d,c,a.installId,e.person),await t("rewrite-ids");const D=await ve(_,F);await t("drop");const J=await pe(s,d,c),q=await he(_);for(const[o,p]of Object.entries({...U}))y(f,o,p);for(const[o,p]of Object.entries(q))y(f,o,p);await me(_),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,c,g,O,new Set,$),await t("blobs"),await be(s,d,c,e.person,r,e.run_id,m),await t("copy"),await N(async o=>{await i.assertOwned();const p=await ne({db:o,runId:e.run_id,schema:d,target:c,catalog:g,source:a,person:e.person,idMap:D,pathMap:I}),A=await Fe(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Ie(o,d,e.run_id,a);const M=await Ne({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,z]of Object.entries(M.inserted))p.inserted[G]=z.length;return P.push(...M.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ue(f,p),unresolved_plugins:P,refused_plugins:k}),v(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const b=await ke(s,e.run_id,d,c,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const T=S.manifest(e.run_id);await r.put(T,await Je(e.run_id)),await W(s,e.run_id);for(const f of De(e.run_id))await r.delete(f);await ge(r,e.run_id),await N(async f=>{await Me(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(T,v(),e.run_id)})}catch(a){if(a instanceof We)throw a;const c=Ke(a);await W(s,e.run_id).catch(()=>{}),l||await we(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),v(),e.run_id)}}u(ct,"processRun");function Ke(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}u(Ke,"failureOf");function y(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(y,"addDropped");function Ue(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}u(Ue,"withInserted");async function Fe(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,l]of d){const m=await Z(e,t);m!==null&&await X(e,m,l.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await H(e,i,"revisions",s.map(t=>[t.rev_id])),await H(e,i,"revision_parents",s.flatMap(t=>t.parents.map(l=>[t.rev_id,l]))),s.length}u(Fe,"arrive");async function H(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,B(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...C(s.inserted_keys),...r]),i,n)}u(H,"appendManifest");async function Je(e){const n=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(n.map(r=>JSON.stringify({table:r.table_name,keys:C(r.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}u(Fe,"manifestFile");export{L as GRANT_WAIT_MS,pt as processRun};
3
+ `))}u(Je,"manifestFile");export{L as GRANT_WAIT_MS,ct as processRun};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.610",
3
+ "version": "0.3.612",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.610",
148
+ "@north-light/identity": "0.3.612",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.610",
3
+ "version": "0.3.612",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.610",
3
+ "version": "0.3.612",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.610",
9
+ "version": "0.3.612",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.610",
31
+ "@north-light/identity": "0.3.612",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.610",
11959
+ "version": "0.3.612",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.610",
11964
+ "version": "0.3.612",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.610",
11969
+ "version": "0.3.612",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.610",
11977
+ "version": "0.3.612",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.610",
11981
- "@north-light/identity": "0.3.610"
11980
+ "@north-light/api": "0.3.612",
11981
+ "@north-light/identity": "0.3.612"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.610",
11986
+ "version": "0.3.612",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.610",
11990
- "@north-light/identity": "0.3.610",
11991
- "@north-light/plugin": "0.3.610",
11989
+ "@north-light/api": "0.3.612",
11990
+ "@north-light/identity": "0.3.612",
11991
+ "@north-light/plugin": "0.3.612",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {