@north-light/cli 0.3.639 → 0.3.641

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,8 +1,8 @@
1
- var Y=Object.defineProperty;var l=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{mkdtempSync as q,readFileSync as U,readdirSync as R,rmSync as K}from"node:fs";import{tmpdir as X}from"node:os";import{join as p}from"node:path";import{CrtrError as s,general as Q}from"../../../core/errors.js";import{ExitCode as h}from"../../../types.js";import{cliClient as T}from"../../api-client.js";import{ImportCloud as x,STORE_FILE as Z,STORE_ORDER as tt}from"../../../core/import/export/cloud.js";import{Uploader as et,localObjects as F,reviewSourceObject as rt}from"../../../core/import/export/files.js";import{bundleKeys as $}from"../../../core/import/bundle/layout.js";import{crtrVersion as nt}from"../../../shared/crtr-version.js";import{nodeArchive as ot}from"../../../core/import/export/archive.js";import{buildSourceJson as it}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as at,runDaemonImportDump as st,runDaemonInstallId as ct,spawnDaemon as dt,stopAllDaemons as lt}from"../../../daemon/manage.js";import{deleteMoveRecord as N,moveUnfinishedError as ut,readMachineConfig as ft,readMoveRecord as A,writeMachineConfig as mt,writeMachineCredential as wt,writeMoveRecord as M}from"../../../daemon/machine-link/config.js";import{notifyMoveFinished as pt}from"../../../daemon/machine-link/move-notify.js";import{controlPlaneUrl as ht,forgetSignIn as gt,personAccount as G,personBearer as D,readPersonCredential as yt,signIn as _t,signOut as Et}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as vt}from"../../../core/directory/issuer.js";import{isPidAlive as L}from"../../../core/canvas/pid.js";const g=l(e=>new Promise(t=>setTimeout(t,e)),"sleep");function Kt(){return ft()?.directoryUrl??yt()?.directoryUrl??vt}l(Kt,"defaultDirectoryUrl");async function B(e){let t="the daemon still reports a drain";for(let r=1;r<=3;r++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}r<3&&await g(1e3)}throw new s("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,h.GENERAL,{next:"Run `crtr sys import resume`."})}l(B,"endDrainConfirmed");async function $t(e,t){e||await B(t)}l($t,"settleDrainAtEnd");const St=3e4;async function bt(e,t,r){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(c){const u=c instanceof s?c.details?.status:void 0;if(c instanceof s&&(c.code==="not_signed_in"||typeof u=="number"&&u<500&&u!==408&&u!==429))throw new s("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${c.message}`,h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${c instanceof Error?c.message:String(c)}
2
- `),await g(n),n=Math.min(n*2,St);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw Q(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&r!==void 0)throw r;await g(2e3)}}l(bt,"awaitRunOutcome");async function Ut(e,t,r,n,i=()=>{},c=()=>{}){let u=Date.now();const o=l((m,f)=>{const w=Date.now(),v=`${m}=${((w-u)/1e3).toFixed(1)}s`;n.timings.push(v),process.stderr.write(`${m} ${((w-u)/1e3).toFixed(1)}s
3
- `),u=w,n.name=f},"next"),d=q(p(X(),"crtr-import-")),S=T({local:!0});let y=!1,I=!1,_=!1,E;try{n.name="start";const{installId:m}=await ct(),f=r===void 0?await t.start({source_install_id:m,source_kind:e,release:nt()}):{run_id:r};i(f.run_id),n.name="blobs";const w=new et(t,f.run_id,a=>process.stderr.write(`${a}
4
- `));await w.upload(F()),await at(d);for(const a of R(p(d,"rows","bodies")))await w.uploadBytes($.bodyRows(f.run_id,a.replace(/\.jsonl\.zst$/,"")),U(p(d,"rows","bodies",a)));o("blobs","drain"),y=!0,await S.drainDaemon({settle_limit_ms:6e5}),o("drain","dump"),await w.upload(F());const v=await st(d,e),k=[];for(const a of v.requests){const b=rt(a.id,a.dir,a.file);b!==null&&k.push(b)}await w.upload(k),o("dump","upload");for(const a of R(p(d,"rows"),{withFileTypes:!0}))a.isFile()&&await w.uploadBytes($.rows(f.run_id,a.name.replace(/\.jsonl\.zst$/,"")),U(p(d,"rows",a.name)));const V=new Set(R(p(d,"rows","bodies")).filter(a=>a.startsWith("pre-")));for(const a of R(p(d,"rows","bodies")))V.has(a)||await w.uploadBytes($.bodyRows(f.run_id,a.replace(/\.jsonl\.zst$/,"")),U(p(d,"rows","bodies",a)));const O=[];if(e==="hosted")for(const a of v.runningNodes){const{data:b,prefixes:W}=await ot(a);O.push(...W),await w.uploadBytes($.nodeFiles(f.run_id,a.node),b)}await w.uploadBytes($.source(f.run_id),Buffer.from(JSON.stringify(it(v.source,O))));const H=JSON.parse(U(p(d,Z),"utf8"));for(const a of tt)await t.putStore(f.run_id,a,H[a]);o("upload","load"),_=!0;let C;try{await t.load(f.run_id)}catch(a){C=a}try{await bt(t,f.run_id,C)}catch(a){throw a instanceof s&&a.code==="move_outcome_unknown"||(_=!1),a}return _=!1,I=!0,o("load","restart"),f.run_id}catch(m){throw E=m,m}finally{if(K(d,{recursive:!0,force:!0}),!I&&!_&&c(),y&&!_)try{await $t(I,S)}catch(m){if(E===void 0)throw m;const f=m instanceof s?m.code:"drain_not_ended";throw new s(f,`${E instanceof Error?E.message:String(E)} (and ${m instanceof Error?m.message:String(m)})`,h.GENERAL,{next:"Run `crtr sys import resume`."})}}}l(Ut,"exportRun");async function Rt(e){await pt(e);const t=new x(e.apiUrl,()=>D(e.directoryUrl));let r;try{r=await t.machineCredential(e.runId)}catch(n){if(!(n instanceof s)||n.details?.code!=="credential_exists")throw n;r=await t.machineCredential(e.runId,!0)}wt(r.credential),mt({apiUrl:e.apiUrl,environmentId:r.environment_id,runId:e.runId,directoryUrl:e.directoryUrl,account:e.account}),await lt(),await dt(),N()}l(Rt,"finishMove");const P=3,Nt=3e4;async function Xt(e){const t={name:"sign-in",timings:[]};let r,n="",i;try{const o=await G(e.directoryUrl),d=e.apiUrl??await ht(e.directoryUrl),S=new x(d,()=>D(e.directoryUrl));i={apiUrl:d,directoryUrl:e.directoryUrl,account:o,notify:e.notify,notified:!1,pid:process.pid},await Ut("machine",S,void 0,t,y=>{n=y,M({...i,runId:y,state:"running"})},N)}catch(o){throw o instanceof s&&o.code==="move_outcome_unknown"?o:await j(t.name,o,e.notify)}r={...i,runId:n,state:"committed"},M(r);let c;const u=Date.now();for(let o=1;o<=P;o++)try{return await Rt(r),t.timings.push(`restart=${((Date.now()-u)/1e3).toFixed(1)}s`),process.stderr.write(`restart ${((Date.now()-u)/1e3).toFixed(1)}s
5
- `),{runId:r.runId,account:r.account.display,timings:t.timings.join(" ")}}catch(d){c=d,process.stderr.write(`switch-over attempt ${o} failed: ${d instanceof Error?d.message:String(d)}
6
- `),o<P&&await g(Nt),r=A()??r}throw ut(c instanceof Error?c.message:String(c))}l(Xt,"runMove");async function j(e,t,r){const n=t instanceof Error?t.message:String(t),i=t instanceof s&&t.code==="drain_not_ended"?"crtr is still local, but its pause could not be ended: run `crtr sys import resume`":"crtr is still local and working as before",c=`The move to Northlight failed at ${e}: ${n}. ${i}.`,u=await J(c,r),o=t instanceof s&&t.code!=="error"?t.code:t instanceof s&&typeof t.details?.code=="string"?t.details.code:"move_failed";return new s(o,`the move to Northlight failed at ${e}: ${n}. ${i}, and ${z(u)}`,h.GENERAL)}l(j,"undoMove");const z=l(e=>e===void 0?"this computer is signed out.":`this computer's sign-in was removed here but could not be revoked at Northlight (${e}); revoke it on your Northlight account page.`,"signedOutText");async function J(e,t){N();let r;try{await Et()}catch(n){gt(),r=n instanceof Error?n.message:String(n),process.stderr.write(`could not revoke the sign-in at Northlight: ${r}
7
- `)}if(t===null)return r;try{await T({local:!0}).sendMessage(t,{from:null,body:`${e} Tell the person the move failed.${r===void 0?"":` ${z(r)}`}`})}catch(n){process.stderr.write(`could not message ${t}: ${n instanceof Error?n.message:String(n)}
8
- `)}return r}l(J,"dropMove");async function It(e){const t=A();if(t===void 0||t.state==="activated")return;const r=l(async()=>{await _t(t.directoryUrl,e,{accept:l(async o=>o.account.id===t.account.id?void 0:new s("signin_other_account",`This computer's move belongs to the Northlight account ${t.account.display}. Sign in to that account.`,h.USAGE),"accept")})},"signBackIn");if(t.state==="committed"){if(e!==void 0)try{await G(t.directoryUrl)}catch(o){if(!(o instanceof s&&o.code==="not_signed_in"))throw o;await r()}return t}if(t.pid>0&&L(t.pid))throw new s("move_running",`a move to Northlight is already running (process ${t.pid}).`,h.USAGE,{next:"Wait for it to finish; the node that asked is messaged when it does."});const n=l(()=>new x(t.apiUrl,()=>D(t.directoryUrl)).get(t.runId),"ask");let i;try{i=await n()}catch(o){if(!(o instanceof s&&o.code==="not_signed_in")||e===void 0)throw o;await r(),i=await n()}if(i.state==="done"){const o={...t,state:"committed"};return M(o),o}if(i.state==="loading"||i.state==="committed")throw new s("move_running","Northlight is still loading this computer's records from an earlier move.",h.USAGE,{next:"Retry in a minute."});if(i.state!=="failed"&&i.state!=="rolled_back"&&i.state!=="uploading")throw new s("move_outcome_unknown","Northlight did not report a settled outcome for this move.",h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});const c=i.failure?.step??"an earlier step",u=i.failure==null?"the process that was moving this computer stopped before Northlight had the records":i.failure.message;N();try{await B(T({local:!0}))}catch(o){throw await j(c,new s("drain_not_ended",`${u} (and ${o instanceof Error?o.message:String(o)})`,h.GENERAL),t.notify)}await J(`The move to Northlight failed at ${c}: ${u}. crtr is still local and working as before.`,t.notify)}l(It,"settleEarlierMove");const Tt=6e4,xt=5e3;async function Qt(e,t){for(await g(xt);!e();){const r=A();if(r===void 0||r.state!=="running"||r.pid>0&&L(r.pid))return;try{await It();return}catch(n){if(t(n),n instanceof s&&n.code==="not_signed_in")return}await g(Tt)}}l(Qt,"settleMoveAtDaemonStart");export{Kt as defaultDirectoryUrl,B as endDrainConfirmed,Ut as exportRun,Rt as finishMove,Xt as runMove,$t as settleDrainAtEnd,It as settleEarlierMove,Qt as settleMoveAtDaemonStart};
1
+ var W=Object.defineProperty;var d=(e,t)=>W(e,"name",{value:t,configurable:!0});import{mkdtempSync as X,readFileSync as L,readdirSync as A,rmSync as Q}from"node:fs";import{tmpdir as Z}from"node:os";import{join as g}from"node:path";import{CrtrError as s,general as tt}from"../../../core/errors.js";import{ExitCode as h}from"../../../types.js";import{cliClient as R}from"../../api-client.js";import{ImportCloud as T,STORE_FILE as et,STORE_ORDER as rt}from"../../../core/import/export/cloud.js";import{Uploader as nt,localObjects as F,reviewSourceObject as ot}from"../../../core/import/export/files.js";import{BODIES_TABLE as P,bundleKeys as x}from"../../../core/import/bundle/layout.js";import{crtrVersion as it}from"../../../shared/crtr-version.js";import{nodeArchive as at}from"../../../core/import/export/archive.js";import{buildSourceJson as st}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as ct,runDaemonImportDump as dt,runDaemonInstallId as lt,spawnDaemon as ut,stopAllDaemons as ft}from"../../../daemon/manage.js";import{deleteMoveRecord as U,moveUnfinishedError as mt,readMachineConfig as wt,readMoveRecord as D,writeMachineConfig as pt,writeMachineCredential as ht,writeMoveRecord as M}from"../../../daemon/machine-link/config.js";import{notifyMoveFinished as gt}from"../../../daemon/machine-link/move-notify.js";import{controlPlaneUrl as _t,forgetSignIn as yt,personAccount as B,personBearer as b,readPersonCredential as Et,signIn as $t,signOut as vt}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as St}from"../../../core/directory/issuer.js";import{isPidAlive as j}from"../../../core/canvas/pid.js";const _=d(e=>new Promise(t=>setTimeout(t,e)),"sleep");function Qt(){return wt()?.directoryUrl??Et()?.directoryUrl??St}d(Qt,"defaultDirectoryUrl");async function J(e){let t="the daemon still reports a drain";for(let r=1;r<=3;r++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}r<3&&await _(1e3)}throw new s("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,h.GENERAL,{next:"Run `crtr sys import resume`."})}d(J,"endDrainConfirmed");async function Ut(e,t){e||await J(t)}d(Ut,"settleDrainAtEnd");const It=3e4;async function Nt(e,t,r){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(c){const l=c instanceof s?c.details?.status:void 0;if(c instanceof s&&(c.code==="not_signed_in"||typeof l=="number"&&l<500&&l!==408&&l!==429))throw new s("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${c.message}`,h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${c instanceof Error?c.message:String(c)}
2
+ `),await _(n),n=Math.min(n*2,It);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw tt(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&r!==void 0)throw r;await _(2e3)}}d(Nt,"awaitRunOutcome");async function At(e,t,r,n,i=()=>{},c=()=>{}){let l=Date.now();const o=d((f,m)=>{const p=Date.now(),S=`${f}=${((p-l)/1e3).toFixed(1)}s`;n.timings.push(S),process.stderr.write(`${f} ${((p-l)/1e3).toFixed(1)}s
3
+ `),l=p,n.name=m},"next"),u=X(g(Z(),"crtr-import-")),v=R({local:!0});let y=!1,I=!1,E=!1,$;try{n.name="start";const{installId:f}=await lt(),m=r===void 0?await t.start({source_install_id:f,source_kind:e,release:it()}):{run_id:r};i(m.run_id),n.name="blobs";const p=new nt(t,m.run_id,a=>process.stderr.write(`${a}
4
+ `));await p.upload(F()),await ct(u);const S=new Set,O=d(async(a,w)=>{await p.uploadBytes(x.rowPart(m.run_id,a,w.replace(/\.jsonl\.zst$/,"")),L(g(u,"rows",a,w))),S.add(`${a}/${w}`)},"uploadPart");for(const a of A(g(u,"rows",P)))await O(P,a);o("blobs","drain"),y=!0,await v.drainDaemon({settle_limit_ms:6e5}),o("drain","dump"),await p.upload(F());const N=await dt(u,e),k=[];for(const a of N.requests){const w=ot(a.id,a.dir,a.file);w!==null&&k.push(w)}await p.upload(k),o("dump","upload");for(const a of A(g(u,"rows")))for(const w of A(g(u,"rows",a)))S.has(`${a}/${w}`)||await O(a,w);const C=[];if(e==="hosted")for(const a of N.runningNodes){const{data:w,prefixes:K}=await at(a);C.push(...K),await p.uploadBytes(x.nodeFiles(m.run_id,a.node),w)}await p.uploadBytes(x.source(m.run_id),Buffer.from(JSON.stringify(st(N.source,C))));const z=JSON.parse(L(g(u,et),"utf8"));for(const a of rt)await t.putStore(m.run_id,a,z[a]);o("upload","load"),E=!0;let G;try{await t.load(m.run_id)}catch(a){G=a}try{await Nt(t,m.run_id,G)}catch(a){throw a instanceof s&&a.code==="move_outcome_unknown"||(E=!1),a}return E=!1,I=!0,o("load","restart"),m.run_id}catch(f){throw $=f,f}finally{if(Q(u,{recursive:!0,force:!0}),!I&&!E&&c(),y&&!E)try{await Ut(I,v)}catch(f){if($===void 0)throw f;const m=f instanceof s?f.code:"drain_not_ended";throw new s(m,`${$ instanceof Error?$.message:String($)} (and ${f instanceof Error?f.message:String(f)})`,h.GENERAL,{next:"Run `crtr sys import resume`."})}}}d(At,"exportRun");async function Rt(e){await gt(e);const t=new T(e.apiUrl,()=>b(e.directoryUrl));let r;try{r=await t.machineCredential(e.runId)}catch(n){if(!(n instanceof s)||n.details?.code!=="credential_exists")throw n;r=await t.machineCredential(e.runId,!0)}ht(r.credential),pt({apiUrl:e.apiUrl,environmentId:r.environment_id,runId:e.runId,directoryUrl:e.directoryUrl,account:e.account}),await ft(),await ut(),U()}d(Rt,"finishMove");const V=3,Tt=3e4;async function Zt(e){const t={name:"sign-in",timings:[]};let r,n="",i;try{const o=await B(e.directoryUrl),u=e.apiUrl??await _t(e.directoryUrl),v=new T(u,()=>b(e.directoryUrl));i={apiUrl:u,directoryUrl:e.directoryUrl,account:o,notify:e.notify,notified:!1,pid:process.pid},await At("machine",v,void 0,t,y=>{n=y,M({...i,runId:y,state:"running"})},U)}catch(o){throw o instanceof s&&o.code==="move_outcome_unknown"?o:await H(t.name,o,e.notify)}r={...i,runId:n,state:"committed"},M(r);let c;const l=Date.now();for(let o=1;o<=V;o++)try{return await Rt(r),t.timings.push(`restart=${((Date.now()-l)/1e3).toFixed(1)}s`),process.stderr.write(`restart ${((Date.now()-l)/1e3).toFixed(1)}s
5
+ `),{runId:r.runId,account:r.account.display,timings:t.timings.join(" ")}}catch(u){c=u,process.stderr.write(`switch-over attempt ${o} failed: ${u instanceof Error?u.message:String(u)}
6
+ `),o<V&&await _(Tt),r=D()??r}throw mt(c instanceof Error?c.message:String(c))}d(Zt,"runMove");async function H(e,t,r){const n=t instanceof Error?t.message:String(t),i=t instanceof s&&t.code==="drain_not_ended"?"crtr is still local, but its pause could not be ended: run `crtr sys import resume`":"crtr is still local and working as before",c=`The move to Northlight failed at ${e}: ${n}. ${i}.`,l=await q(c,r),o=t instanceof s&&t.code!=="error"?t.code:t instanceof s&&typeof t.details?.code=="string"?t.details.code:"move_failed";return new s(o,`the move to Northlight failed at ${e}: ${n}. ${i}, and ${Y(l)}`,h.GENERAL)}d(H,"undoMove");const Y=d(e=>e===void 0?"this computer is signed out.":`this computer's sign-in was removed here but could not be revoked at Northlight (${e}); revoke it on your Northlight account page.`,"signedOutText");async function q(e,t){U();let r;try{await vt()}catch(n){yt(),r=n instanceof Error?n.message:String(n),process.stderr.write(`could not revoke the sign-in at Northlight: ${r}
7
+ `)}if(t===null)return r;try{await R({local:!0}).sendMessage(t,{from:null,body:`${e} Tell the person the move failed.${r===void 0?"":` ${Y(r)}`}`})}catch(n){process.stderr.write(`could not message ${t}: ${n instanceof Error?n.message:String(n)}
8
+ `)}return r}d(q,"dropMove");async function xt(e){const t=D();if(t===void 0||t.state==="activated")return;const r=d(async()=>{await $t(t.directoryUrl,e,{accept:d(async o=>o.account.id===t.account.id?void 0:new s("signin_other_account",`This computer's move belongs to the Northlight account ${t.account.display}. Sign in to that account.`,h.USAGE),"accept")})},"signBackIn");if(t.state==="committed"){if(e!==void 0)try{await B(t.directoryUrl)}catch(o){if(!(o instanceof s&&o.code==="not_signed_in"))throw o;await r()}return t}if(t.pid>0&&j(t.pid))throw new s("move_running",`a move to Northlight is already running (process ${t.pid}).`,h.USAGE,{next:"Wait for it to finish; the node that asked is messaged when it does."});const n=d(()=>new T(t.apiUrl,()=>b(t.directoryUrl)).get(t.runId),"ask");let i;try{i=await n()}catch(o){if(!(o instanceof s&&o.code==="not_signed_in")||e===void 0)throw o;await r(),i=await n()}if(i.state==="done"){const o={...t,state:"committed"};return M(o),o}if(i.state==="loading"||i.state==="committed")throw new s("move_running","Northlight is still loading this computer's records from an earlier move.",h.USAGE,{next:"Retry in a minute."});if(i.state!=="failed"&&i.state!=="rolled_back"&&i.state!=="uploading")throw new s("move_outcome_unknown","Northlight did not report a settled outcome for this move.",h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});const c=i.failure?.step??"an earlier step",l=i.failure==null?"the process that was moving this computer stopped before Northlight had the records":i.failure.message;U();try{await J(R({local:!0}))}catch(o){throw await H(c,new s("drain_not_ended",`${l} (and ${o instanceof Error?o.message:String(o)})`,h.GENERAL),t.notify)}await q(`The move to Northlight failed at ${c}: ${l}. crtr is still local and working as before.`,t.notify)}d(xt,"settleEarlierMove");const Dt=6e4,Mt=5e3;async function te(e,t){for(await _(Mt);!e();){const r=D();if(r===void 0||r.state!=="running"||r.pid>0&&j(r.pid))return;try{await xt();return}catch(n){if(t(n),n instanceof s&&n.code==="not_signed_in")return}await _(Dt)}}d(te,"settleMoveAtDaemonStart");export{Qt as defaultDirectoryUrl,J as endDrainConfirmed,At as exportRun,Rt as finishMove,Zt as runMove,Ut as settleDrainAtEnd,xt as settleEarlierMove,te as settleMoveAtDaemonStart};
@@ -1,9 +1,8 @@
1
- /** `bodies` (revision text, design-fleet D106) is copied like any table but dumped apart: its 667 MB do not fit one row file (a whole table as one string exceeds V8's string limit), so its rows
2
- * travel as the part files named in `source.bodyParts` (see `rowKeys`), each written and read a line at a time (`RowFileWriter`, `rowLines`).
1
+ /** `bodies` (revision text, design-fleet D106) is copied like any table; it is dumped apart only because its rows come from the database in hash batches, and every row must be canonical.
3
2
  * Every row is canonical: `hash` is the sha256 of `text`, which holds no NUL. The exporter dumps only such rows and the lane refuses a bundle with any other (`stage`). */
4
3
  export declare const BODIES_TABLE = "bodies";
5
4
  /** Tables whose rows are dumped, staged and (after rewrites) copied, in no particular order: the lane computes the copy
6
- * order from the target's foreign-key catalog. Each row file holds the table's rows in primary-key order (identity-ordered
5
+ * order from the target's foreign-key catalog. A table's part files, read in order, hold its rows in primary-key order (identity-ordered
7
6
  * tables in source `seq` order). */
8
7
  export declare const COPIED_TABLES: readonly ["objects", "documents", "revisions", "revision_parents", "identities", "jobs", "custom_objects", "context_sessions", "environments", "object_kinds", "edges", "watches", "watch_subscriptions", "exposures", "rules", "unresolved_links", "nodes", "sessions", "worktrees", "node_faults", "waits", "structured_requests", "memory_reads", "deleted_isolated_nodes", "node_outcome_deliveries", "run_events", "messages", "message_causes", "deliveries", "crons", "cron_runs", "daemon_actions", "human_requests", "human_action_deliveries", "review_comments", "review_comment_events", "audit_rows", "idempotency_keys", "uploads", "upload_uses", "shares", "provider_approvals", "relations", "charges", "limits", "conversation_parts", "conversation_entries", "profiles", "bodies"];
9
8
  /** Dumped and staged so rewrite 2 can map them, never inserted into the target (`grants`: the directory writes them). */
@@ -20,15 +19,15 @@ export declare const KEY_MAPPED_TABLES: {
20
19
  export declare const SEQ_TABLES: readonly ["objects", "revisions", "watches", "watch_subscriptions", "sessions", "waits", "structured_requests", "deliveries", "run_events"];
21
20
  export declare const bundleKeys: {
22
21
  readonly prefix: (run: string) => string;
23
- readonly rows: (run: string, table: string) => string;
22
+ /** One part file of a table's rows (`source.rowParts[table]` names the parts). */
23
+ readonly rowPart: (run: string, table: string, part: string) => string;
24
24
  readonly source: (run: string) => string;
25
25
  readonly manifest: (run: string) => string;
26
26
  readonly nodeFiles: (run: string, node: string) => string;
27
- readonly bodyRows: (run: string, part: string) => string;
28
27
  readonly request: (requestId: string, relative: string) => string;
29
28
  };
30
- /** The blob keys of a table's row files: one file, or for `bodies` its parts. */
31
- export declare function rowKeys(run: string, table: string, source: Pick<SourceJson, 'bodyParts'>): string[];
29
+ /** The blob keys of a table's row part files, in order. A table with no rows has none. */
30
+ export declare function rowKeys(run: string, table: string, source: Pick<SourceJson, 'rowParts'>): string[];
32
31
  /** `imports/<run>/source.json`. */
33
32
  export interface SourceJson {
34
33
  installId: string;
@@ -37,15 +36,16 @@ export interface SourceJson {
37
36
  person: string;
38
37
  release: string;
39
38
  schemaVersion: number;
40
- /** Rows per dumped table. The lane refuses a row file whose line count differs. */
39
+ /** Rows per dumped table. The lane refuses a table whose part files' line count differs. */
41
40
  counts: Record<string, number>;
41
+ /** The part files of each dumped table's rows (`imports/<run>/rows/<table>/<part>.jsonl.zst`), in row order; each holds about 16 MiB of JSON before compression, so no upload is large.
42
+ * `bodies` lists the pre-pause dump's parts, then the pause dump's. `counts[table]` is the total of a table's parts. */
43
+ rowParts: Record<string, string[]>;
42
44
  /** The source's machine environment object id, when it has one (`environments.object`). */
43
45
  environmentObject?: string;
44
46
  /** Hosted sources: every directory the exporter archived for a running node (`nodeFiles` holds its entries as `<from minus leading slash>/<relative path>`).
45
47
  * The lane picks the sandbox directory each one lands in (`sandboxPathMap`); the exporter does not. */
46
48
  pathPrefixes?: PathPrefix[];
47
- /** The part files of the `bodies` rows (`imports/<run>/rows/bodies/<part>.jsonl.zst`): the pre-pause dump's parts, then the pause dump's. `counts.bodies` is their total. */
48
- bodyParts?: string[];
49
49
  /** Shipped documents (`documents.source_path` set): document object id → hash of the body text the exporter read from its file; that text is a `bodies` row in the bundle.
50
50
  * The lane uses it for a shipped document the target has no copy of, which becomes an ordinary document (I23). */
51
51
  shippedBodies?: Record<string, string>;
@@ -1,4 +1,4 @@
1
- var a=Object.defineProperty;var o=(s,e)=>a(s,"name",{value:e,configurable:!0});import{once as d}from"node:events";import{createWriteStream as u}from"node:fs";import{pipeline as f}from"node:stream/promises";import{createZstdCompress as m,createZstdDecompress as l,zstdDecompressSync as p}from"node:zlib";const _="bodies",h=["objects","documents","revisions","revision_parents","identities","jobs","custom_objects","context_sessions","environments","object_kinds","edges","watches","watch_subscriptions","exposures","rules","unresolved_links","nodes","sessions","worktrees","node_faults","waits","structured_requests","memory_reads","deleted_isolated_nodes","node_outcome_deliveries","run_events","messages","message_causes","deliveries","crons","cron_runs","daemon_actions","human_requests","human_action_deliveries","review_comments","review_comment_events","audit_rows","idempotency_keys","uploads","upload_uses","shares","provider_approvals","relations","charges","limits","conversation_parts","conversation_entries","profiles","bodies"],w=["grants"],E=[...h,...w],S={audit_rows:"id",review_comment_events:"seq"},z=["objects","revisions","watches","watch_subscriptions","sessions","waits","structured_requests","deliveries","run_events"],c={prefix:o(s=>`imports/${s}/`,"prefix"),rows:o((s,e)=>`imports/${s}/rows/${e}.jsonl.zst`,"rows"),source:o(s=>`imports/${s}/source.json`,"source"),manifest:o(s=>`imports/${s}/manifest.jsonl.zst`,"manifest"),nodeFiles:o((s,e)=>`imports/${s}/node-files/${e}.tar.zst`,"nodeFiles"),bodyRows:o((s,e)=>`imports/${s}/rows/bodies/${e}.jsonl.zst`,"bodyRows"),request:o((s,e)=>`requests/${s}/${e}`,"request")};function $(s,e,t){return e===_?(t.bodyParts??[]).map(r=>c.bodyRows(s,r)):[c.rows(s,e)]}o($,"rowKeys");function L(s,e){let t;for(const r of s)(e===r.from||e.startsWith(r.from.endsWith("/")?r.from:`${r.from}/`))&&(t===void 0||r.from.length>t.from.length)&&(t=r);return t===void 0?e:t.to+e.slice(t.from.length)}o(L,"mapPath");function j(s){const e=p(s).toString("utf8");if(e==="")return[];if(!e.endsWith(`
1
+ var c=Object.defineProperty;var n=(t,e)=>c(t,"name",{value:e,configurable:!0});import{once as a}from"node:events";import{createWriteStream as d}from"node:fs";import{pipeline as u}from"node:stream/promises";import{createZstdCompress as f,createZstdDecompress as m,zstdDecompressSync as l}from"node:zlib";const E="bodies",p=["objects","documents","revisions","revision_parents","identities","jobs","custom_objects","context_sessions","environments","object_kinds","edges","watches","watch_subscriptions","exposures","rules","unresolved_links","nodes","sessions","worktrees","node_faults","waits","structured_requests","memory_reads","deleted_isolated_nodes","node_outcome_deliveries","run_events","messages","message_causes","deliveries","crons","cron_runs","daemon_actions","human_requests","human_action_deliveries","review_comments","review_comment_events","audit_rows","idempotency_keys","uploads","upload_uses","shares","provider_approvals","relations","charges","limits","conversation_parts","conversation_entries","profiles","bodies"],_=["grants"],S=[...p,..._],b={audit_rows:"id",review_comment_events:"seq"},z=["objects","revisions","watches","watch_subscriptions","sessions","waits","structured_requests","deliveries","run_events"],h={prefix:n(t=>`imports/${t}/`,"prefix"),rowPart:n((t,e,s)=>`imports/${t}/rows/${e}/${s}.jsonl.zst`,"rowPart"),source:n(t=>`imports/${t}/source.json`,"source"),manifest:n(t=>`imports/${t}/manifest.jsonl.zst`,"manifest"),nodeFiles:n((t,e)=>`imports/${t}/node-files/${e}.tar.zst`,"nodeFiles"),request:n((t,e)=>`requests/${t}/${e}`,"request")};function $(t,e,s){return(s.rowParts[e]??[]).map(r=>h.rowPart(t,e,r))}n($,"rowKeys");function L(t,e){let s;for(const r of t)(e===r.from||e.startsWith(r.from.endsWith("/")?r.from:`${r.from}/`))&&(s===void 0||r.from.length>s.from.length)&&(s=r);return s===void 0?e:s.to+e.slice(s.from.length)}n(L,"mapPath");function B(t){const e=l(t).toString("utf8");if(e==="")return[];if(!e.endsWith(`
2
2
  `))throw new Error("row file is truncated: the last line is not newline-terminated");return e.slice(0,-1).split(`
3
- `).map(t=>JSON.parse(t))}o(j,"decodeRows");function B(s){return`${JSON.stringify(s)}
4
- `}o(B,"rowLine");class A{static{o(this,"RowFileWriter")}zst=m();finished;written=0;constructor(e){this.finished=f(this.zst,u(e)),this.finished.catch(()=>{})}get bytes(){return this.written}async write(e,t=Buffer.byteLength(e,"utf8")){this.written+=t,this.zst.write(e,"utf8")||await Promise.race([d(this.zst,"drain"),this.finished])}async close(){this.zst.end(),await this.finished}destroy(){this.zst.destroy()}}async function*D(s){const e=l({chunkSize:1048576});e.end(s);let t=[];for await(const r of e){let n=0;for(let i=r.indexOf(10,n);i!==-1;i=r.indexOf(10,n))t.push(r.subarray(n,i)),yield(t.length===1?t[0]:Buffer.concat(t)).toString("utf8"),t=[],n=i+1;n<r.length&&t.push(r.subarray(n))}if(t.length>0)throw new Error("row file is truncated: the last line is not newline-terminated")}o(D,"rowLines");export{_ as BODIES_TABLE,h as COPIED_TABLES,E as DUMPED_TABLES,S as KEY_MAPPED_TABLES,A as RowFileWriter,z as SEQ_TABLES,w as STAGED_ONLY_TABLES,c as bundleKeys,j as decodeRows,L as mapPath,$ as rowKeys,B as rowLine,D as rowLines};
3
+ `).map(s=>JSON.parse(s))}n(B,"decodeRows");function P(t){return`${JSON.stringify(t)}
4
+ `}n(P,"rowLine");class j{static{n(this,"RowFileWriter")}zst=f();finished;written=0;constructor(e){this.finished=u(this.zst,d(e)),this.finished.catch(()=>{})}get bytes(){return this.written}async write(e,s=Buffer.byteLength(e,"utf8")){this.written+=s,this.zst.write(e,"utf8")||await Promise.race([a(this.zst,"drain"),this.finished])}async close(){this.zst.end(),await this.finished}destroy(){this.zst.destroy()}}async function*A(t){const e=m({chunkSize:1048576});e.end(t);let s=[];for await(const r of e){let o=0;for(let i=r.indexOf(10,o);i!==-1;i=r.indexOf(10,o))s.push(r.subarray(o,i)),yield(s.length===1?s[0]:Buffer.concat(s)).toString("utf8"),s=[],o=i+1;o<r.length&&s.push(r.subarray(o))}if(s.length>0)throw new Error("row file is truncated: the last line is not newline-terminated")}n(A,"rowLines");export{E as BODIES_TABLE,p as COPIED_TABLES,S as DUMPED_TABLES,b as KEY_MAPPED_TABLES,j as RowFileWriter,z as SEQ_TABLES,_ as STAGED_ONLY_TABLES,h as bundleKeys,B as decodeRows,L as mapPath,$ as rowKeys,P as rowLine,A as rowLines};
@@ -20,7 +20,7 @@ export interface DumpResult {
20
20
  bodiesMissing: number;
21
21
  bodiesInlined: number;
22
22
  }
23
- /** A `bodies` part file holds about this much JSON (the encoded lines, before compression); a row that alone exceeds it is a part of its own. */
23
+ /** A row part file holds about this much JSON (the encoded lines, before compression); a row that alone exceeds it is a part of its own. */
24
24
  export declare const PART_JSON_BYTES: number;
25
25
  /** A body longer than this many UTF-8 bytes fails the export. The largest body on Silas's Mac is 5.2 MB. JSON escapes one character into at most six (`\u0001`), so a body at
26
26
  * the ceiling is a line of at most 192 MiB, well inside V8's ~512 MiB string limit. */
@@ -1,4 +1,4 @@
1
- var K=Object.defineProperty;var o=(e,r)=>K(e,"name",{value:r,configurable:!0});import{mkdirSync as M,readFileSync as $,writeFileSync as Q}from"node:fs";import{join as m}from"node:path";import{openDb as Z,withCanvasWrite as ee}from"../../canvas/db.js";import{hashOf as te}from"../../graph/bodies.js";import{personIdAsync as re}from"../../canvas/person.js";import{CANVAS_SCHEMA_VERSION as ne}from"../../canvas/schema-version.js";import{crtrVersion as ae}from"../../../shared/crtr-version.js";import{BODIES_TABLE as T,DUMPED_TABLES as k,RowFileWriter as v,SEQ_TABLES as oe,bundleKeys as se,rowLine as Y}from"../bundle/layout.js";import{inlineMessageBody as ie}from"./inline.js";const ce=16*1024*1024,le=8*1024*1024,j=32*1024*1024,he=500,W=5e3,N="bodies-pre.json",L=o(e=>`"${e.replace(/"/g,'""')}"`,"q");function de(e){try{const r=$(e,"utf8");return r.trim()===""?null:r}catch(r){if(r.code==="ENOENT")return null;throw r}}o(de,"readText");function pe(e,r){return new Error(`revision text ${e} is ${r} bytes; the import carries at most ${j} bytes of text per body`)}o(pe,"tooLarge");function ue(e){const r=te(e.text);if(r!==e.hash)throw new Error(`body ${e.hash} does not hash to its key (its text hashes to ${r}); upgrade and restart the daemon so its boot repair rekeys the row, then export again`)}o(ue,"assertCanonical");async function H(e,r,s,h){const n=m(r,"rows",T);M(n,{recursive:!0});const f=[];let i=null;const y=o(async()=>{const a=i;i=null,a!==null&&await a.close()},"close"),g=o(async a=>{ue(a);const E=Y(a),c=Buffer.byteLength(E,"utf8");if(i!==null&&i.bytes>0&&i.bytes+c>ce&&await y(),i===null){const d=`${s}-${f.length}`;i=new v(m(n,`${d}.jsonl.zst`)),f.push(d)}await i.write(E,c)},"add");try{for(let a=0;a<h.length;){const E=await e.prepare("SELECT hash, octet_length(text) AS n FROM bodies WHERE hash = ANY(?::text[]) ORDER BY hash").all(h.slice(a,a+W));let c=[],d=0;const R=o(async()=>{if(c.length===0)return;const u=await e.prepare("SELECT hash, text FROM bodies WHERE hash = ANY(?::text[]) ORDER BY hash").all(c);for(const w of u)await g(w);c=[],d=0},"fetchPage");for(const{hash:u,n:w}of E){const p=Number(w);if(p>j)throw pe(u,p);c.length>0&&d+p>le&&await R(),c.push(u),d+=p}await R(),a+=W}await y()}catch(a){throw i?.destroy(),a}return f}o(H,"writeBodyParts");const P=o(async e=>(await e.prepare("SELECT hash FROM bodies ORDER BY hash").all()).map(r=>r.hash),"allHashes");async function Ne(e){const r=await Z(),s=await P(r),h=await H(r,e,"pre",s),n={hashes:s,parts:h,count:s.length,canonical:!0};return Q(m(e,N),JSON.stringify(n)),{parts:h,count:s.length}}o(Ne,"dumpBodiesPre");function Ee(e){try{return JSON.parse($(m(e,N),"utf8"))}catch(r){if(r.code==="ENOENT")return{hashes:[],parts:[],count:0};throw r}}o(Ee,"readPre");function we(e,r){if(e.count===0&&e.parts.length===0)return;if(e.canonical!==!0)throw new Error(`${N} was written before bodies were checked against their keys; discard the export directory and run the pre-pause dump again`);const s=e.hashes.filter(h=>!r.has(h));if(s.length>0)throw new Error(`the pre-pause dump holds ${s.length} body row(s) the database no longer has (first: ${s[0]}); the boot repair ran after it. Discard the export directory and run the pre-pause dump again`)}o(we,"assertPreCurrent");async function Le(e,r,s=he){const h=await re();return M(m(e,"rows"),{recursive:!0}),ee(async n=>{await n.exec("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");const f=new Set((await n.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema()").all()).map(t=>t.table_name)),i=k.filter(t=>!f.has(t));if(i.length>0)throw new Error(`the canvas database lacks tables the bundle needs: ${i.join(", ")}`);const y=await n.prepareUncached(`SELECT c.conrelid::regclass::text AS tbl, (SELECT array_agg(a.attname::text ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY k(attnum, ord)
2
- JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum) AS cols FROM pg_constraint c WHERE c.contype = 'p' AND c.connamespace = current_schema()::regnamespace`).all(),g=new Map(y.map(t=>[t.tbl.replace(/"/g,"").replace(/^.*\./,""),t.cols])),a=await n.prepareUncached("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = current_schema() ORDER BY table_name, ordinal_position").all(),E=new Set(oe),c={};let d=0,R=0;for(const t of k.filter(_=>_!==T)){const _=E.has(t)?["seq"]:g.get(t),D=_!==void 0&&_.length>0?_.map(l=>`t.${L(l)}`):a.filter(l=>l.table_name===t).map(l=>`t.${L(l.column_name)}::text`);if(D.length===0)throw new Error(`table ${t} has no columns to order its dump by`);const b=new v(m(e,se.rows("",t).replace(/^imports\/\//,"")));let x=0;try{for(await n.exec(`DECLARE dump_cursor NO SCROLL CURSOR FOR SELECT row_to_json(t)::text AS j FROM ${L(t)} t ORDER BY ${D.join(", ")}`);;){const l=await n.prepareUncached(`FETCH FORWARD ${s} FROM dump_cursor`).all();for(const G of l){let O=JSON.parse(G.j);if(t==="messages"){const F=O.body_ref,I=ie(O,de);typeof F=="string"&&F.startsWith("/")&&(I===O?R+=1:d+=1),O=I}await b.write(Y(O))}if(x+=l.length,l.length<s)break}await n.exec("CLOSE dump_cursor"),await b.close()}catch(l){throw b.destroy(),l}c[t]=x}const u=(await n.prepare("SELECT value FROM canvas_meta WHERE key = 'install_id'").get())?.value;if(u===void 0)throw new Error("this canvas database has no install id");const w=await n.prepare("SELECT object FROM environments WHERE kind = 'machine' ORDER BY object LIMIT 1").get(),p={installId:u,kind:r,person:h,release:ae(),schemaVersion:ne,counts:c,...w===void 0?{}:{environmentObject:w.object}},q=await n.prepare("SELECT request_id, request_dir, file FROM human_requests ORDER BY request_id").all(),J=await n.prepare(`SELECT d.object, r.body_hash FROM documents d JOIN revisions r ON r.document = d.object
3
- WHERE d.source_path IS NOT NULL AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY d.object, r.number DESC, r.rev_id`).all(),A={};for(const t of J)A[t.object]??=t.body_hash;const S=Ee(e),U=new Set(S.hashes),C=await P(n);we(S,new Set(C));const B=C.filter(t=>!U.has(t)),V=await H(n,e,"pause",B),z=S.count+B.length;c[T]=z,p.bodyParts=[...S.parts,...V];const X=await n.prepare(`SELECT n.node_id, r.grantee, n.cwd, w.path AS worktree FROM nodes n JOIN node_rows r ON r.node_id = n.node_id LEFT JOIN worktrees w ON w.node_id = n.node_id AND w.state = 'open'
4
- WHERE n.status IN ('active', 'idle') ORDER BY n.node_id`).all();return p.shippedBodies=A,{source:p,requests:q.map(t=>({id:t.request_id,dir:t.request_dir,file:t.file})),runningNodes:X.map(t=>({node:t.node_id,app:t.grantee,cwd:t.cwd,worktree:t.worktree})),bodiesInlined:d,bodiesMissing:R}})}o(Le,"dumpRows");export{j as BODY_MAX_BYTES,ce as PART_JSON_BYTES,Ne as dumpBodiesPre,Le as dumpRows};
1
+ var Q=Object.defineProperty;var s=(t,e)=>Q(t,"name",{value:e,configurable:!0});import{mkdirSync as Z,readFileSync as $,writeFileSync as K}from"node:fs";import{join as w}from"node:path";import{openDb as ee,withCanvasWrite as te}from"../../canvas/db.js";import{hashOf as re}from"../../graph/bodies.js";import{personIdAsync as ne}from"../../canvas/person.js";import{CANVAS_SCHEMA_VERSION as ae}from"../../canvas/schema-version.js";import{crtrVersion as se}from"../../../shared/crtr-version.js";import{BODIES_TABLE as O,DUMPED_TABLES as k,RowFileWriter as oe,SEQ_TABLES as ie,rowLine as W}from"../bundle/layout.js";import{inlineMessageBody as ce}from"./inline.js";const le=16*1024*1024,he=8*1024*1024,Y=32*1024*1024,de=500,j=5e3,g="bodies-pre.json";class v{static{s(this,"PartWriter")}dir;prefix;parts=[];file=null;constructor(e,a){this.dir=e,this.prefix=a,Z(e,{recursive:!0})}async add(e){const a=Buffer.byteLength(e,"utf8");if(this.file!==null&&this.file.bytes>0&&this.file.bytes+a>le&&await this.close(),this.file===null){const o=`${this.prefix}${this.parts.length}`;this.file=new oe(w(this.dir,`${o}.jsonl.zst`)),this.parts.push(o)}await this.file.write(e,a)}async close(){const e=this.file;this.file=null,e!==null&&await e.close()}destroy(){this.file?.destroy(),this.file=null}}const b=s(t=>`"${t.replace(/"/g,'""')}"`,"q");function pe(t){try{const e=$(t,"utf8");return e.trim()===""?null:e}catch(e){if(e.code==="ENOENT")return null;throw e}}s(pe,"readText");function ue(t,e){return new Error(`revision text ${t} is ${e} bytes; the import carries at most ${Y} bytes of text per body`)}s(ue,"tooLarge");function Ee(t){const e=re(t.text);if(e!==t.hash)throw new Error(`body ${t.hash} does not hash to its key (its text hashes to ${e}); upgrade and restart the daemon so its boot repair rekeys the row, then export again`)}s(Ee,"assertCanonical");async function H(t,e,a,o){const n=new v(w(e,"rows",O),`${a}-`),y=s(async i=>{Ee(i),await n.add(W(i))},"add");try{for(let i=0;i<o.length;){const S=await t.prepare("SELECT hash, octet_length(text) AS n FROM bodies WHERE hash = ANY(?::text[]) ORDER BY hash").all(o.slice(i,i+j));let h=[],u=0;const m=s(async()=>{if(h.length===0)return;const l=await t.prepare("SELECT hash, text FROM bodies WHERE hash = ANY(?::text[]) ORDER BY hash").all(h);for(const d of l)await y(d);h=[],u=0},"fetchPage");for(const{hash:l,n:d}of S){const p=Number(d);if(p>Y)throw ue(l,p);h.length>0&&u+p>he&&await m(),h.push(l),u+=p}await m(),i+=j}await n.close()}catch(i){throw n.destroy(),i}return n.parts}s(H,"writeBodyParts");const P=s(async t=>(await t.prepare("SELECT hash FROM bodies ORDER BY hash").all()).map(e=>e.hash),"allHashes");async function Le(t){const e=await ee(),a=await P(e),o=await H(e,t,"pre",a),n={hashes:a,parts:o,count:a.length,canonical:!0};return K(w(t,g),JSON.stringify(n)),{parts:o,count:a.length}}s(Le,"dumpBodiesPre");function fe(t){try{return JSON.parse($(w(t,g),"utf8"))}catch(e){if(e.code==="ENOENT")return{hashes:[],parts:[],count:0};throw e}}s(fe,"readPre");function we(t,e){if(t.count===0&&t.parts.length===0)return;if(t.canonical!==!0)throw new Error(`${g} was written before bodies were checked against their keys; discard the export directory and run the pre-pause dump again`);const a=t.hashes.filter(o=>!e.has(o));if(a.length>0)throw new Error(`the pre-pause dump holds ${a.length} body row(s) the database no longer has (first: ${a[0]}); the boot repair ran after it. Discard the export directory and run the pre-pause dump again`)}s(we,"assertPreCurrent");async function Ae(t,e,a=de){const o=await ne();return te(async n=>{await n.exec("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");const y=new Set((await n.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema()").all()).map(r=>r.table_name)),i=k.filter(r=>!y.has(r));if(i.length>0)throw new Error(`the canvas database lacks tables the bundle needs: ${i.join(", ")}`);const S=await n.prepareUncached(`SELECT c.conrelid::regclass::text AS tbl, (SELECT array_agg(a.attname::text ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY k(attnum, ord)
2
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum) AS cols FROM pg_constraint c WHERE c.contype = 'p' AND c.connamespace = current_schema()::regnamespace`).all(),h=new Map(S.map(r=>[r.tbl.replace(/"/g,"").replace(/^.*\./,""),r.cols])),u=await n.prepareUncached("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = current_schema() ORDER BY table_name, ordinal_position").all(),m=new Set(ie),l={},d={};let p=0,T=0;for(const r of k.filter(E=>E!==O)){const E=m.has(r)?["seq"]:h.get(r),D=E!==void 0&&E.length>0?E.map(c=>`t.${b(c)}`):u.filter(c=>c.table_name===r).map(c=>`t.${b(c.column_name)}::text`);if(D.length===0)throw new Error(`table ${r} has no columns to order its dump by`);const _=new v(w(t,"rows",r),"");let F=0;try{for(await n.exec(`DECLARE dump_cursor NO SCROLL CURSOR FOR SELECT row_to_json(t)::text AS j FROM ${b(r)} t ORDER BY ${D.join(", ")}`);;){const c=await n.prepareUncached(`FETCH FORWARD ${a} FROM dump_cursor`).all();for(const G of c){let f=JSON.parse(G.j);if(r==="messages"){const I=f.body_ref,M=ce(f,pe);typeof I=="string"&&I.startsWith("/")&&(M===f?T+=1:p+=1),f=M}await _.add(W(f))}if(F+=c.length,c.length<a)break}await n.exec("CLOSE dump_cursor"),await _.close()}catch(c){throw _.destroy(),c}l[r]=F,d[r]=_.parts}const N=(await n.prepare("SELECT value FROM canvas_meta WHERE key = 'install_id'").get())?.value;if(N===void 0)throw new Error("this canvas database has no install id");const L=await n.prepare("SELECT object FROM environments WHERE kind = 'machine' ORDER BY object LIMIT 1").get(),A={installId:N,kind:e,person:o,release:se(),schemaVersion:ae,counts:l,rowParts:d,...L===void 0?{}:{environmentObject:L.object}},q=await n.prepare("SELECT request_id, request_dir, file FROM human_requests ORDER BY request_id").all(),J=await n.prepare(`SELECT d.object, r.body_hash FROM documents d JOIN revisions r ON r.document = d.object
3
+ WHERE d.source_path IS NOT NULL AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY d.object, r.number DESC, r.rev_id`).all(),C={};for(const r of J)C[r.object]??=r.body_hash;const R=fe(t),U=new Set(R.hashes),x=await P(n);we(R,new Set(x));const B=x.filter(r=>!U.has(r)),V=await H(n,t,"pause",B),z=R.count+B.length;l[O]=z,d[O]=[...R.parts,...V];const X=await n.prepare(`SELECT n.node_id, r.grantee, n.cwd, w.path AS worktree FROM nodes n JOIN node_rows r ON r.node_id = n.node_id LEFT JOIN worktrees w ON w.node_id = n.node_id AND w.state = 'open'
4
+ WHERE n.status IN ('active', 'idle') ORDER BY n.node_id`).all();return A.shippedBodies=C,{source:A,requests:q.map(r=>({id:r.request_id,dir:r.request_dir,file:r.file})),runningNodes:X.map(r=>({node:r.node_id,app:r.grantee,cwd:r.cwd,worktree:r.worktree})),bodiesInlined:p,bodiesMissing:T}})}s(Ae,"dumpRows");export{Y as BODY_MAX_BYTES,le as PART_JSON_BYTES,Le as dumpBodiesPre,Ae as dumpRows};
@@ -1,12 +1,12 @@
1
- var A=Object.defineProperty;var d=(n,s)=>A(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as H,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as p}from"./catalog.js";const f=d((n,s)=>`${p(n)}.${p(s)}`,"sq");async function P(n,s,c){if(c.length===0)return 0;const e=d(o=>f(s,o),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=d(async(o,t,r,u=!1)=>{const R=await n.prepareUncached(`SELECT ${p(t)}::text AS value FROM ${e(o)} WHERE ${r} AND ${p(t)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?D(m,c):S(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(o)} SET ${p(t)} = ? WHERE ${p(t)}::text = ? AND ${r}`).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(P,"rewritePaths");async function B(n,s,c,e,i){if(c.length===0)return 0;const a=d(t=>f(s,t),"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 o=0;for(const{conversation_id:t,blob_key:r}of E){const u=M(i,r),R=await e.get(u);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${t} cannot be rewritten`);const m=C(R,t,h=>S(c,h));m!==null&&(await e.put(u,m),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ? WHERE conversation_id = ? AND seq = 0`).run((m??R).length,t)}return o}d(B,"rewriteConversationHeaders");async function K(n,s){const c=f(s,"human_requests"),e=d(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
1
+ var A=Object.defineProperty;var p=(n,s)=>A(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as H,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const f=p((n,s)=>`${l(n)}.${l(s)}`,"sq");async function B(n,s,c){if(c.length===0)return 0;const e=p(o=>f(s,o),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=p(async(o,t,r,u=!1)=>{const R=await n.prepareUncached(`SELECT ${l(t)}::text AS value FROM ${e(o)} WHERE ${r} AND ${l(t)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?D(m,c):S(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(o)} SET ${l(t)} = ? WHERE ${l(t)}::text = ? AND ${r}`).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}p(B,"rewritePaths");async function K(n,s,c,e,i){if(c.length===0)return 0;const a=p(t=>f(s,t),"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 o=0;for(const{conversation_id:t,blob_key:r}of E){const u=M(i,r),R=await e.get(u);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${t} cannot be rewritten`);const m=C(R,t,h=>S(c,h));m!==null&&(await e.put(u,m),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ? WHERE conversation_id = ? AND seq = 0`).run((m??R).length,t)}return o}p(K,"rewriteConversationHeaders");async function J(n,s){const c=f(s,"human_requests"),e=p(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
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(K,"rewriteRequestPaths");function D(n,s){const c=d(e=>typeof e=="string"?S(s,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 S(s,n)}}d(D,"rewriteJsonPaths");async function J(n,s,c,e,i){const a=d(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let o=0;for(const t of E)await n.prepareUncached(`SELECT 1 AS found FROM ${f(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,t.name,t.id)!==void 0&&(await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(`${t.name}-${e}`,t.id),o+=1);return o}d(J,"renameClashingProfiles");async function Y(n,s,c,e,i){const a=d(t=>f(s,t),"S");let E=0;const o=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const t of o){let r=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(r=(await n.prepareUncached(`SELECT environment_id FROM ${f(c,"profiles")} WHERE id = ?`).get(t.id))?.environment_id??await U(n,{profileId:t.id,grantee:t.grantee??"app:terminal",person:i})),r===null)throw new N("fill","bundle_invalid",`profile ${t.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(r,t.id),E+=1}return E}d(Y,"fillEnvironments");async function X(n,s,c,e){const i=d(o=>f(s,o),"S"),a={},E=d(async(o,t,...r)=>{const u=Number((await n.prepareUncached(t).run(...r)).changes);u>0&&(a[o]=(a[o]??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[o,t]of Object.entries(H))await E(o,`DELETE FROM ${i(o)} WHERE ${p(t)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,o);for(const o of c.tables.values())o.columns.includes("claimed_by")&&o.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(o.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(X,"pruneStaged");async function z(n,s,c){const e=d(E=>f(s,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${f(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};
6
+ request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}p(J,"rewriteRequestPaths");function D(n,s){const c=p(e=>typeof e=="string"?S(s,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 S(s,n)}}p(D,"rewriteJsonPaths");async function Y(n,s,c,e,i){const a=p(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let o=0;for(const t of E)await n.prepareUncached(`SELECT 1 AS found FROM ${f(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,t.name,t.id)!==void 0&&(await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(`${t.name}-${e}`,t.id),o+=1);return o}p(Y,"renameClashingProfiles");async function X(n,s,c,e,i){const a=p(t=>f(s,t),"S");let E=0;const o=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const t of o){let r=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(r=(await n.prepareUncached(`SELECT environment_id FROM ${f(c,"profiles")} WHERE id = ?`).get(t.id))?.environment_id??await U(n,{profileId:t.id,grantee:t.grantee??"app:terminal",person:i})),r===null)throw new N("fill","bundle_invalid",`profile ${t.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(r,t.id),E+=1}return E}p(X,"fillEnvironments");async function z(n,s,c,e){const i=p(o=>f(s,o),"S"),a={},E=p(async(o,t,...r)=>{const u=Number((await n.prepareUncached(t).run(...r)).changes);u>0&&(a[o]=(a[o]??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[o,t]of Object.entries(H))await E(o,`DELETE FROM ${i(o)} WHERE ${l(t)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,o);for(const o of c.tables.values())o.columns.includes("claimed_by")&&o.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(o.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}p(z,"pruneStaged");async function G(n,s,c){const e=p(E=>f(s,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${f(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};
7
7
  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,
8
8
  COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
9
- 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(z,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]};async function G(n,s,c,e,i,a,E){const o=d(r=>[...E.get(r)??[],...r==="profiles"?["environment_id"]:[],...g[r]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const r of i){const u=e.tables.get(r);if(u===void 0||a.has(r)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(l=>u.identity.includes(l)),h=R.map(l=>`s.${p(l)} = t.${p(l)}`).join(" AND "),I=m?"TRUE":R.map(l=>`s.${p(l)} IS DISTINCT FROM t.${p(l)}`).join(" OR "),v=new Set([...u.identity,...E.get(r)??[]]);for(const l of e.uniqueKeys.filter(_=>_.table===r&&!_.columns.every(T=>v.has(T)))){const _=l.predicate===null?"":` WHERE ${l.predicate}`,T=l.columns.map($=>`s.${p($)} = t.${p($)}`).join(" AND "),L=await n.prepareUncached(`SELECT ${l.columns.map($=>`s.${p($)}::text`).join(" || ',' || ")} AS value
10
- FROM (SELECT * FROM ${f(s,r)}${_}) s JOIN (SELECT * FROM ${f(c,r)}${_}) t ON ${T} AND (${I}) LIMIT 10`).all();L.length>0&&t.push({table:r,key:l.name,values:L.map($=>$.value)});const y=m?"TRUE":R.map($=>`a.${p($)} IS DISTINCT FROM b.${p($)}`).join(" OR "),O=await n.prepareUncached(`SELECT DISTINCT ${l.columns.map($=>`a.${p($)}::text`).join(" || ',' || ")} AS value
11
- FROM (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) a JOIN (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) b ON ${l.columns.map($=>`a.${p($)} = b.${p($)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();O.length>0&&t.push({table:r,key:l.name,values:O.map($=>$.value),staged:!0})}const w=u.columns.filter(l=>!u.identity.includes(l)&&!o(r).includes(l));if(w.length>0&&!m){const l=w.map(T=>`s.${p(T)} IS DISTINCT FROM t.${p(T)}`).join(" OR "),_=await n.prepareUncached(`SELECT ${R.map(T=>`s.${p(T)}::text`).join(" || ',' || ")} AS value
12
- FROM ${f(s,r)} s JOIN ${f(c,r)} t ON ${h} WHERE ${l} LIMIT 10`).all();_.length>0&&t.push({table:r,key:"primary key payload",values:_.map(T=>T.value)})}}if(t.length>0){const r=t[0];throw new N("pre-check","unique_conflict",`${r.table} ${r.key} collides ${r.staged===!0?"within the bundle":"with the target"}: ${r.values.join(", ")}`,{collisions:t})}}d(G,"precheck");export{Y as fillEnvironments,G as precheck,X as pruneStaged,J as renameClashingProfiles,B as rewriteConversationHeaders,P as rewritePaths,K as rewriteRequestPaths,z as takeRepoSyncedDocuments};
9
+ 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}))}p(G,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},W={charges:["payer","units","usd"]};async function Q(n,s,c,e,i,a,E){const o=p(r=>[...E.get(r)??[],...r==="profiles"?["environment_id"]:[],...g[r]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const r of i){const u=e.tables.get(r);if(u===void 0||a.has(r)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(d=>u.identity.includes(d)),h=R.map(d=>`s.${l(d)} = t.${l(d)}`).join(" AND "),I=m?"TRUE":R.map(d=>`s.${l(d)} IS DISTINCT FROM t.${l(d)}`).join(" OR "),v=new Set([...u.identity,...E.get(r)??[]]);for(const d of e.uniqueKeys.filter(_=>_.table===r&&!_.columns.every(T=>v.has(T)))){const _=d.predicate===null?"":` WHERE ${d.predicate}`,T=d.columns.map($=>`s.${l($)} = t.${l($)}`).join(" AND "),O=await n.prepareUncached(`SELECT ${d.columns.map($=>`s.${l($)}::text`).join(" || ',' || ")} AS value
10
+ FROM (SELECT * FROM ${f(s,r)}${_}) s JOIN (SELECT * FROM ${f(c,r)}${_}) t ON ${T} AND (${I}) LIMIT 10`).all();O.length>0&&t.push({table:r,key:d.name,values:O.map($=>$.value)});const y=m?"TRUE":R.map($=>`a.${l($)} IS DISTINCT FROM b.${l($)}`).join(" OR "),L=await n.prepareUncached(`SELECT DISTINCT ${d.columns.map($=>`a.${l($)}::text`).join(" || ',' || ")} AS value
11
+ FROM (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) a JOIN (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) b ON ${d.columns.map($=>`a.${l($)} = b.${l($)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();L.length>0&&t.push({table:r,key:d.name,values:L.map($=>$.value),staged:!0})}const w=u.columns.filter(d=>!u.identity.includes(d)&&!o(r).includes(d)&&(W[r]?.includes(d)??!0));if(w.length>0&&!m){const d=w.map(T=>`s.${l(T)} IS DISTINCT FROM t.${l(T)}`).join(" OR "),_=await n.prepareUncached(`SELECT ${R.map(T=>`s.${l(T)}::text`).join(" || ',' || ")} AS value
12
+ FROM ${f(s,r)} s JOIN ${f(c,r)} t ON ${h} WHERE ${d} LIMIT 10`).all();_.length>0&&t.push({table:r,key:"primary key payload",values:_.map(T=>T.value)})}}if(t.length>0){const r=t[0];throw new N("pre-check","unique_conflict",`${r.table} ${r.key} collides ${r.staged===!0?"within the bundle":"with the target"}: ${r.values.join(", ")}`,{collisions:t})}}p(Q,"precheck");export{X as fillEnvironments,Q as precheck,z as pruneStaged,Y as renameClashingProfiles,K as rewriteConversationHeaders,B as rewritePaths,J as rewriteRequestPaths,G as takeRepoSyncedDocuments};
@@ -1,3 +1,3 @@
1
- var z=Object.defineProperty;var c=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as M}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,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 N,encodeKeys as L}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ue}from"./prepare.js";import{boundSub as ce,checkSourcePerson as le,checkStagedBlobKeys as fe,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,deleteRunPrefix as he,moveRunBlobs as Ee}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Se,grantMissing as ve,mapProfileIds as Re,renameClashingRepos as Oe,rewriteIds as Pe,rewritePerson as Ie,scopeRepoIdentities as Te}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as ke,stagingSchema as je,targetSchema as De}from"./stage.js";import{verifyRun as Ae}from"./verify.js";import{sandboxPathMap as Ce,writeNodeFiles as Me}from"./path-map.js";import{allStoreKeys as Ne,readPluginsStore as Le,recordImportedActivations as Be,writeStores as We}from"./stores.js";import{publishImportedPlugins as He}from"./publish-plugins.js";import{COPIED_TABLES as Ke}from"../bundle/layout.js";import{ClaimLostError as Ue}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,Fe=30*6e4,R=c(()=>new Date().toISOString(),"now"),O=c(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Je(e,i){const n=await e.get(v.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}c(Je,"readSource");async function qe(e,i,n,r,s,d){const a=await e.get(v.rows(n.run_id,"grants")),f=a===null?[]:x(a),m=[];for(const t of f){const u=ce(t.sub,r,n.person,"grants.sub");await Se(i,s,d,u,t.grantee)===void 0&&m.push(t.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)>=W)throw ve(m);return!1}c(qe,"grantsReady");async function mt(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=je(e.run_id),a=c(async t=>{await i.assertOwned(),await O(e.run_id,t),await n.atStep?.(t)},"at");let f=e.state==="committed";const m=[];try{const t=await Je(r,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new w("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 De(s),P=[...Ke],g=await ae(s,u,[...P,"grants"]);if(!f){const l={},T=[],k=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await le(s,u,t.person,e.person),!await qe(r,s,e,t.person,u,j)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await a("publish-plugins");const h=await He(await Le(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)>=W)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 O(e.run_id,"waiting_for_directory");return}k.push(...h.refused),await a("stage");const K=await ke(s,e.run_id,t.counts,o=>ee(e.run_id,o,t),o=>r.get(o));for(const[o,p]of Object.entries(K))l[o]={staged:p,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:u,catalog:g,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:t.shippedBodies??{}};await a("bind-staged");for(const[o,p]of Object.entries(await _e(_)))E(l,o,p);for(const[o,p]of Object.entries(await fe(_)))E(l,o,p);await a("rewrite-person"),await Ie(_),await Te(_),await a("prune");const U=await ie(s,d,g,t),y=t.kind==="hosted"?Ce(t.pathPrefixes??[]):[];await a("rewrite-paths"),await de(s,d,y),await oe(s,d,y,r,e.run_id),await pe(s,d),await we(_);const F=await Re(_);await re(s,d,u,t.installId,e.person),await a("rewrite-ids");const D=await Pe(_,F);await a("drop");const J=await ue(s,d,u),q=await ye(_);for(const[o,p]of Object.entries({...U}))E(l,o,p);for(const[o,p]of Object.entries(q))E(l,o,p);await me(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Oe(_),await a("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,u,g,P,new Set,$),await a("blobs"),await Ee(s,d,u,e.person,r,e.run_id,m),await a("copy"),await M(async o=>{await i.assertOwned({extendLeaseMs:Fe});const p=await ne({db:o,runId:e.run_id,schema:d,target:u,catalog:g,source:t,person:e.person,idMap:D,pathMap:y}),A=await Ye(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Me(o,d,e.run_id,t);const C=await We({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,Y]of Object.entries(C.inserted))p.inserted[G]=Y.length;return T.push(...C.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ge(l,p),unresolved_plugins:T,refused_plugins:k}),R(),e.run_id),p}),f=!0,await n.atStep?.("committed")}await a("verify");const b=await Ae(s,e.run_id,d,u,g,t.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 a("manifest");const I=v.manifest(e.run_id);await r.put(I,await ze(e.run_id)),await B(s,e.run_id);for(const l of Ne(e.run_id))await r.delete(l);await be(r,e.run_id),await M(async l=>{await Be(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(I,R(),e.run_id)})}catch(t){if(t instanceof Ue)throw t;const u=$e(t);await B(s,e.run_id).catch(()=>{}),f||await ge(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await he(r,e.run_id,{keepNodeFiles:f,bestEffort:!0})}}c(mt,"processRun");function $e(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)}}c($e,"failureOf");function E(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}c(E,"addDropped");function Ge(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}c(Ge,"withInserted");async function Ye(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(a=>a.rev_id)))).map(a=>a.rev_id)),s=n.filter(a=>!r.has(a.rev_id)),d=new Map;for(const a of n)d.set(a.document,[...d.get(a.document)??[],a]);for(const[a,f]of d){const m=await Z(e,a);m!==null&&await X(e,m,f.map(t=>({rev_id:t.rev_id,parents:t.parents,body_hash:t.body_hash,rationale:t.rationale,created_at:t.created_at})))}return await H(e,i,"revisions",s.map(a=>[a.rev_id])),await H(e,i,"revision_parents",s.flatMap(a=>a.parents.map(f=>[a.rev_id,f]))),s.length}c(Ye,"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,L(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(L([...N(s.inserted_keys),...r]),i,n)}c(H,"appendManifest");async function ze(e){const n=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Q(Buffer.from(n.map(r=>JSON.stringify({table:r.table_name,keys:N(r.inserted_keys)})).join(`
1
+ var Q=Object.defineProperty;var u=(e,s)=>Q(e,"name",{value:s,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as X}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as C}from"../../canvas/db.js";import{insertImportedRevisions as Z}from"../../graph/documents.js";import{getById as x}from"../../graph/objects.js";import{bundleKeys as M,decodeRows as ee,rowKeys as N,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as L,encodeKeys as B}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ue}from"./prepare.js";import{boundSub as ce,checkSourcePerson as le,checkStagedBlobKeys as fe,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,deleteRunPrefix as he,moveRunBlobs as ye}from"./blobs.js";import{dropStubRows as Ee,findFleetGrant as Se,grantMissing as ve,mapProfileIds as Re,renameClashingRepos as Oe,rewriteIds as Pe,rewritePerson as Ie,scopeRepoIdentities as Te}from"./rewrite.js";import{dropStaging as W,ImportLaneError as w,stage as ke,stagingSchema as je,targetSchema as De}from"./stage.js";import{verifyRun as Ae}from"./verify.js";import{sandboxPathMap as Ce,writeNodeFiles as Me}from"./path-map.js";import{allStoreKeys as Ne,readPluginsStore as Le,recordImportedActivations as Be,writeStores as We}from"./stores.js";import{publishImportedPlugins as He}from"./publish-plugins.js";import{COPIED_TABLES as Ke}from"../bundle/layout.js";import{ClaimLostError as Ue}from"../../../daemon/reconcilers/row-claim.js";const H=10*6e4,Fe=30*6e4,v=u(()=>new Date().toISOString(),"now"),R=u(async(e,s)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Je(e,s){const i=await e.get(M.source(s));if(i===null)throw new w("stage","bundle_invalid","source.json is missing");const n=JSON.parse(i.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new w("stage","bundle_invalid","source.json names no row parts");return n}u(Je,"readSource");async function qe(e,s,i,n,r,d){const a=[];for(const l of N(i.run_id,"grants",n)){const t=await e.get(l);if(t===null)throw new w("stage","bundle_invalid",`row file ${l} is missing`);a.push(...ee(t))}const c=[];for(const l of a){const t=ce(l.sub,n.person,i.person,"grants.sub");await Se(s,r,d,t,l.grantee)===void 0&&c.push(l.grantee)}if(c.length===0)return!0;if(i.loaded_at===void 0||i.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(i.loaded_at)>=H)throw ve(c);return!1}u(qe,"grantsReady");async function mt(e,s,i={}){const n=i.blobs??await X(),r=await S(),d=je(e.run_id),a=u(async t=>{await s.assertOwned(),await R(e.run_id,t),await i.atStep?.(t)},"at");let c=e.state==="committed";const l=[];try{const t=await Je(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const f=await De(r),O=[...Ke],g=await ae(r,f,[...O,"grants"]);if(!c){const _={},I=[],T=[],k=i.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await le(r,f,t.person,e.person),!await qe(n,r,e,t,f,k)){await s.assertOwned(),await R(e.run_id,"waiting_for_grants");return}await a("publish-plugins");const h=await He(await Le(n,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)>=H)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 s.assertOwned(),await R(e.run_id,"waiting_for_directory");return}T.push(...h.refused),await a("stage");const U=await ke(r,e.run_id,t.counts,o=>N(e.run_id,o,t),o=>n.get(o));for(const[o,p]of Object.entries(U))_[o]={staged:p,inserted:0,mapped:0,dropped:0};const m={db:r,schema:d,target:f,catalog:g,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await a("bind-staged");for(const[o,p]of Object.entries(await _e(m)))y(_,o,p);for(const[o,p]of Object.entries(await fe(m)))y(_,o,p);await a("rewrite-person"),await Ie(m),await Te(m),await a("prune");const F=await ie(r,d,g,t),E=t.kind==="hosted"?Ce(t.pathPrefixes??[]):[];await a("rewrite-paths"),await de(r,d,E),await oe(r,d,E,n,e.run_id),await pe(r,d),await we(m);const J=await Re(m);await re(r,d,f,t.installId,e.person),await a("rewrite-ids");const j=await Pe(m,J);await a("drop");const q=await ue(r,d,f),$=await Ee(m);for(const[o,p]of Object.entries({...F}))y(_,o,p);for(const[o,p]of Object.entries($))y(_,o,p);await me(m,{installId:t.installId,person:e.person,runId:e.run_id}),await Oe(m),await a("pre-check");const G=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(r,d,f,g,O,new Set,G),await a("blobs"),await ye(r,d,f,e.person,n,e.run_id,l),await a("copy"),await C(async o=>{await s.assertOwned({extendLeaseMs:Fe});const p=await ne({db:o,runId:e.run_id,schema:d,target:f,catalog:g,source:t,person:e.person,idMap:j,pathMap:E}),D=await Ye(o,e.run_id,q);D>0&&(p.inserted.revisions=(p.inserted.revisions??0)+D),await Me(o,d,e.run_id,t);const A=await We({db:o,blobs:n,runId:e.run_id,person:e.person,objectMap:j.object});for(const[Y,z]of Object.entries(A.inserted))p.inserted[Y]=z.length;return I.push(...A.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ge(_,p),unresolved_plugins:I,refused_plugins:T}),v(),e.run_id),p}),c=!0,await i.atStep?.("committed")}await a("verify");const b=await Ae(r,e.run_id,d,f,g,t.installId);if(await r.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 a("manifest");const P=M.manifest(e.run_id);await n.put(P,await ze(e.run_id)),await W(r,e.run_id);for(const _ of Ne(e.run_id))await n.delete(_);await be(n,e.run_id),await C(async _=>{await Be(_,e.run_id,e.person),await _.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(P,v(),e.run_id)})}catch(t){if(t instanceof Ue)throw t;const f=$e(t);await W(r,e.run_id).catch(()=>{}),c||await ge(n,l,!0),await r.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(f),v(),e.run_id),await he(n,e.run_id,{keepNodeFiles:c,bestEffort:!0})}}u(mt,"processRun");function $e(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const s=e.code;return{step:"unknown",code:typeof s=="string"?s:"import_failed",message:e instanceof Error?e.message:String(e)}}u($e,"failureOf");function y(e,s,i){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=i}u(y,"addDropped");function Ge(e,s){for(const[i,n]of Object.entries(s.inserted))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[i,n]of Object.entries(s.mapped))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}u(Ge,"withInserted");async function Ye(e,s,i){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(i.map(a=>a.rev_id)))).map(a=>a.rev_id)),r=i.filter(a=>!n.has(a.rev_id)),d=new Map;for(const a of i)d.set(a.document,[...d.get(a.document)??[],a]);for(const[a,c]of d){const l=await x(e,a);l!==null&&await Z(e,l,c.map(t=>({rev_id:t.rev_id,parents:t.parents,body_hash:t.body_hash,rationale:t.rationale,created_at:t.created_at})))}return await K(e,s,"revisions",r.map(a=>[a.rev_id])),await K(e,s,"revision_parents",r.flatMap(a=>a.parents.map(c=>[a.rev_id,c]))),r.length}u(Ye,"arrive");async function K(e,s,i,n){if(n.length===0)return;const r=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,i);r===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,i,B(n)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...L(r.inserted_keys),...n]),s,i)}u(K,"appendManifest");async function ze(e){const i=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return V(Buffer.from(i.map(n=>JSON.stringify({table:n.table_name,keys:L(n.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}c(ze,"manifestFile");export{Fe as COPY_LEASE_MS,W as GRANT_WAIT_MS,mt as processRun};
3
+ `))}u(ze,"manifestFile");export{Fe as COPY_LEASE_MS,H as GRANT_WAIT_MS,mt as processRun};
@@ -5,7 +5,7 @@ export declare const stagingSchema: (run: string) => string;
5
5
  /** The target schema's name (the transaction's current schema). */
6
6
  export declare function targetSchema(db: CanvasDb): Promise<string>;
7
7
  export declare function dropStaging(db: CanvasDb, run: string): Promise<void>;
8
- /** Create the staging schema and load every row file. `rowKeys(table)` names the table's row files (one file, or the parts of `bodies`) and `get` reads one from R2. */
8
+ /** Create the staging schema and load every row file. `rowKeys(table)` names the table's row part files, in order, and `get` reads one from R2. */
9
9
  export declare function stage(db: CanvasDb, run: string, counts: Record<string, number>, rowKeys: (table: string) => string[], get: (key: string) => Promise<Buffer | null>): Promise<Record<string, number>>;
10
10
  export declare class ImportLaneError extends Error {
11
11
  readonly step: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.639",
3
+ "version": "0.3.641",
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.639",
148
+ "@north-light/identity": "0.3.641",
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.639",
3
+ "version": "0.3.641",
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.639",
3
+ "version": "0.3.641",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.639",
9
+ "version": "0.3.641",
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.639",
31
+ "@north-light/identity": "0.3.641",
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.639",
11959
+ "version": "0.3.641",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.639",
11964
+ "version": "0.3.641",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.639",
11969
+ "version": "0.3.641",
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.639",
11977
+ "version": "0.3.641",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.639",
11981
- "@north-light/identity": "0.3.639"
11980
+ "@north-light/api": "0.3.641",
11981
+ "@north-light/identity": "0.3.641"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.639",
11986
+ "version": "0.3.641",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.639",
11990
- "@north-light/identity": "0.3.639",
11991
- "@north-light/plugin": "0.3.639",
11989
+ "@north-light/api": "0.3.641",
11990
+ "@north-light/identity": "0.3.641",
11991
+ "@north-light/plugin": "0.3.641",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {