@north-light/cli 0.3.605 → 0.3.606
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.
- package/dist/clients/attach/viewer.js +504 -504
- package/dist/core/import/load/copy.js +4 -4
- package/dist/core/import/load/rewrite.d.ts +9 -1
- package/dist/core/import/load/rewrite.js +13 -12
- package/dist/core/import/load/run.js +2 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(
|
|
3
|
-
ORDER BY ${
|
|
1
|
+
var M=Object.defineProperty;var c=(a,r)=>M(a,"name",{value:r,configurable:!0});import{zstdCompressSync as U,zstdDecompressSync as k}from"node:zlib";import{BODIES_TABLE as C,COPIED_TABLES as F,KEY_MAPPED_TABLES as w}from"../bundle/layout.js";import{q as s,rowKey as H,topologicalOrder as x}from"./catalog.js";import{fillEnvironments as v}from"./prepare.js";import{ImportLaneError as L}from"./stage.js";const b=c((a,r)=>`${s(a)}.${s(r)}`,"sq"),j=c(a=>U(Buffer.from(JSON.stringify(a))),"encodeKeys"),Y=c(a=>JSON.parse(k(a).toString("utf8")),"decodeKeys"),q=c(a=>x(a,F),"copyOrder");async function J(a){const{db:r,runId:S,schema:I,target:g,catalog:T,source:f}=a,o=c(e=>b(I,e),"S"),E=c(e=>b(g,e),"T"),d={inserted:{},mapped:{}},N=c(async(e,n)=>{d.inserted[e]=n.length,await r.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(S,e,j(n))},"manifest");for(const[e,n]of Object.entries(w)){const i=T.tables.get(e).columns.filter(p=>p!==n).map(s).join(", "),m=[],_=await r.prepareUncached(`SELECT ${s(n)}::text AS key FROM ${o(e)} ORDER BY ${s(n)}::bigint`).all();for(const{key:p}of _){const l=await r.prepareUncached(`INSERT INTO ${E(e)} (${i}) SELECT ${i} FROM ${o(e)} WHERE ${s(n)}::text = ? RETURNING ${s(n)}::text AS key`).get(p);await r.prepare("INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) VALUES (?, ?, ?, ?)").run(f.installId,e,p,l.key),m.push([l.key])}await N(e,m)}await r.prepareUncached(`UPDATE ${o("review_comments")} c SET created_seq = m.target_key::bigint FROM import_key_map m
|
|
2
|
+
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(f.installId);const h=q(T);for(const e of h){if(e in w)continue;if(e==="profiles"){if(h.indexOf("identities")>h.indexOf("profiles"))throw new L("copy","bundle_invalid","identities must be copied before profiles");await v(r,I,g,f,a.person)}const n=T.tables.get(e),O=Number((await r.prepareUncached(`SELECT count(*) AS n FROM ${o(e)}`).get()).n);if(O===0){d.inserted[e]=0;continue}const i=H(n),m=n.columns.filter(t=>!n.identity.includes(t)),_=n.identity.length>0?n.identity.map(t=>`s.${s(t)}`).join(", "):i.map(t=>`s.${s(t)}`).join(", ");let p=m.map(t=>`s.${s(t)}`),l="";if(e==="messages"){const t=`NOT EXISTS (SELECT 1 FROM ${E("messages")} t WHERE t.message_id = s.message_id)`,u=Number((await r.prepareUncached(`SELECT count(*) AS n FROM ${o("messages")} s WHERE ${t}`).get()).n);if(l=` WHERE ${t}`,u===0){d.inserted[e]=0,await N(e,[]);continue}const D=Number((await r.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(u)).seq);p=m.map(y=>y==="seq"?`${D-u} + row_number() OVER (ORDER BY s.seq)`:`s.${s(y)}`)}const A=i.map(t=>`${s(t)}::text`).join(", "),$=n.primaryKey.length===0;$&&(l=` WHERE NOT EXISTS (SELECT 1 FROM ${E(e)} t WHERE ${i.map(t=>`t.${s(t)} IS NOT DISTINCT FROM s.${s(t)}`).join(" AND ")})`);const R=await r.prepareUncached(`INSERT INTO ${E(e)} (${m.map(s).join(", ")}) SELECT ${p.join(", ")} FROM ${o(e)} s${l}
|
|
3
|
+
ORDER BY ${_}${$?"":` ON CONFLICT (${i.map(s).join(", ")}) DO NOTHING`} RETURNING ${A}`).all();if(e===C){const t=await r.prepareUncached(`SELECT s.hash FROM ${o(e)} s JOIN ${E(e)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();if(t.length>0)throw new L("copy","unique_conflict",`the target holds other text under body ${t[0].hash}; its boot repair has not rekeyed that row`,{table:e,hashes:t.map(u=>u.hash)})}e===C?d.inserted[e]=R.length:await N(e,R.map(t=>Object.values(t))),d.mapped[e]=O-R.length}await r.prepareUncached(`DELETE FROM ${E("charge_totals")} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${o("charges")})`).run(),await r.prepareUncached(`INSERT INTO ${E("charge_totals")} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
4
4
|
SELECT month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, ''), COALESCE(SUM(usd), 0), COALESCE(SUM(billed_usd), 0)
|
|
5
5
|
FROM ${E("charges")} WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${o("charges")})
|
|
6
|
-
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,
|
|
6
|
+
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,n]of[["object",a.idMap.object],["grant",a.idMap.grant],["kind",a.idMap.kind]])for(const[O,i]of n)await r.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(S,e,O,i);for(const e of a.pathMap)await r.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, 'path', ?, ?) ON CONFLICT DO NOTHING").run(S,e.from,e.to);return await r.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(),S),d}c(J,"copyRows");export{q as copyOrder,J as copyRows,Y as decodeKeys,j as encodeKeys};
|
|
@@ -33,7 +33,15 @@ export declare function findFleetGrant(db: CanvasDb, target: string, fleetRuntim
|
|
|
33
33
|
/** The `grant_missing` failure, for the grantees the target holds no grant for. */
|
|
34
34
|
export declare function grantMissing(grantees: readonly string[]): ImportLaneError;
|
|
35
35
|
/** Rewrite 2 (id map): build the map, drop the staged rows of mapped objects, rewrite every id column through it. */
|
|
36
|
-
export declare function rewriteIds(input: RewriteInput): Promise<IdMap>;
|
|
36
|
+
export declare function rewriteIds(input: RewriteInput, profileIds: ReadonlyMap<string, string>): Promise<IdMap>;
|
|
37
|
+
/** Rewrite 2 for the `profiles` table: `profiles.id` is a global primary key, and every install's root profile has the same id (`ROOT_PROFILE_ID`), so the id is
|
|
38
|
+
* matched within the importing person, never taken as it is. Returns source id → target id for the ids that change; a staged row that is the person's profile in the
|
|
39
|
+
* target already is dropped. Runs before the name-clash rename, so the person's root is never renamed into a second one.
|
|
40
|
+
* - The root (`ROOT_PROFILE_ID`) is the person's `root` profile in the target, whatever its id (a cloud role's root has a generated one). With none, it gets a
|
|
41
|
+
* new id derived from the person, so `root-00000000` never reaches a control plane that serves other people.
|
|
42
|
+
* - Any other id the target holds for the person is that profile; one it holds for someone else gets a new id derived from (person, id).
|
|
43
|
+
* The derived id is the same on a second load, which then finds the person's own profile (a root by name, any other by id). The staged profile object's identity (and the handle that is the id) follows. */
|
|
44
|
+
export declare function mapProfileIds(input: RewriteInput): Promise<Map<string, string>>;
|
|
37
45
|
/** The drop step: federation stubs' objects and every staged row that points at a dropped row, then the assertion that no staged foreign
|
|
38
46
|
* key points at a row that is neither staged nor in the target. Returns rows dropped per table. */
|
|
39
47
|
export declare function dropStubRows(input: RewriteInput): Promise<Record<string, number>>;
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
var
|
|
2
|
-
JOIN ${
|
|
3
|
-
JOIN ${
|
|
4
|
-
JOIN ${
|
|
5
|
-
WHERE ${
|
|
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(
|
|
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"]],w={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((i,d)=>{a.has(i)||a.set(i,new Set),a.get(i).add(d)},"add");for(const i of n.foreignKeys)i.parent==="objects"&&i.columns.length===1&&o(i.table,i.columns[0]);for(const[i,d]of I)o(i,d);return a}l(C,"objectIdColumns");const f=l((n,a)=>`${T(n)}.${T(a)}`,"sq"),E=l(async(n,a,...o)=>Number((await n.prepareUncached(a).run(...o)).changes),"run"),$=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,i,d){return o===null?void 0:(await n.prepareUncached(`SELECT id FROM ${f(a,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,i,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:i,target:d}=n,t=l(e=>f(i,e),"S"),m=l(e=>f(d,e),"T"),u={object:new Map,grant:new Map,kind:new Map};for(const[e,p]of a)u.object.set(e,p);const c=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,`SELECT i.object AS src, t.object AS dst FROM ${t("identities")} i
|
|
2
|
+
JOIN ${t("objects")} so ON so.id = i.object AND so.type = ?
|
|
3
|
+
JOIN ${m("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id
|
|
4
|
+
JOIN ${m("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
|
|
5
|
+
WHERE ${p}`,e,e==="person"?n.targetPerson:c);for(const{src:O,dst:L}of R)O!==L&&u.object.set(O,L)}const r=await $(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(u.object.get(e.owner)??e.owner,e.name);if(p!==void 0){u.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 O=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
|
-
UNION ALL SELECT o.id FROM ${
|
|
9
|
-
WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(n.targetPerson,n.targetPerson);if(
|
|
10
|
-
VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,
|
|
11
|
-
FROM ${
|
|
12
|
-
WHERE c.${a}
|
|
13
|
-
|
|
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(O===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 = ?`,O.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,c,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,`SELECT id, sub, grantee FROM ${t("grants")} ORDER BY id`),N=[];for(const e of s){const p=await W(o,d,n.fleetRuntime,e.sub,e.grantee);p===void 0?N.push(e.grantee):u.grant.set(e.id,p)}if(N.length>0)throw F(N);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",u.object],["grant",u.grant]])for(const[R,O]of p)await E(o,`INSERT INTO ${t("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,R,O);const b=`(SELECT source FROM ${t("_idmap")} WHERE kind = 'object')`;for(const[e,p]of Object.entries(w))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 S(o,t(e),R,"object",t("_idmap"));for(const[e,p]of M)await S(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}`);for(const{name:e}of await $(o,`SELECT k.name FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`))u.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)`),u}l(Y,"rewriteIds");async function B(n){const{db:a,schema:o,target:i,targetPerson:d}=n,t=new Map,m=l(async(c,...r)=>await a.prepareUncached(c).get(...r),"row"),u=l(c=>E(a,`DELETE FROM ${f(o,"profiles")} WHERE id = ?`,c),"dropStaged");for(const{id:c}of await $(a,`SELECT id FROM ${f(o,"profiles")} ORDER BY id`)){let r=c===j?await m(`SELECT id, person FROM ${f(i,"profiles")} WHERE person = ? AND name = 'root'`,d):await m(`SELECT id, person FROM ${f(i,"profiles")} WHERE id = ? AND person = ?`,c,d);if(r===void 0){if(await m(`SELECT id, person FROM ${f(i,"profiles")} WHERE id = ?`,c)===void 0&&c!==j)continue;const b=`${c.replace(/-[0-9a-f]{8}$/,"")}-${g("sha256").update(`${d}\0${c}`).digest("hex").slice(0,8)}`,e=await m(`SELECT id, person FROM ${f(i,"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 ${f(o,"profiles")} SET id = ? WHERE id = ?`,b,c):await u(c)}else await u(c);const s=r.id;await E(a,`UPDATE ${f(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${f(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
|
|
12
|
+
AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${f(i,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,s,c,s,c),await E(a,`UPDATE ${f(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${f(o,"objects")} WHERE type = 'profile')`,s,c),s!==c&&t.set(c,s)}return t}l(B,"mapProfileIds");async function S(n,a,o,i,d){await E(n,`UPDATE ${a} t SET ${T(o)} = m.target FROM ${d} m WHERE m.kind = ? AND t.${T(o)} = m.source`,i)}l(S,"remap");async function X(n){const{db:a,schema:o,target:i,catalog:d}=n,t=l(r=>f(o,r),"S"),m={},u=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 c=`(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(w))u(r,await E(a,`DELETE FROM ${t(r)} WHERE ${s} IN ${c}`));for(u("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 N=d.tables.get(s.table),b=T(s.columns[0]),e=N.primaryKey.length===1?T(N.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);u(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]),N=T(r.parentColumns[0]),b=await $(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.${N} = c.${s})
|
|
14
|
+
AND NOT EXISTS (SELECT 1 FROM ${f(i,r.parent)} p WHERE p.${N} = 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};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
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(`
|
|
2
2
|
`)+`
|
|
3
|
-
`))}u(
|
|
3
|
+
`))}u(Fe,"manifestFile");export{L as GRANT_WAIT_MS,pt as processRun};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.606",
|
|
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.
|
|
148
|
+
"@north-light/identity": "0.3.606",
|
|
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",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.606",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.606",
|
|
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.
|
|
31
|
+
"@north-light/identity": "0.3.606",
|
|
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.
|
|
11959
|
+
"version": "0.3.606",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.606",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.606",
|
|
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.
|
|
11977
|
+
"version": "0.3.606",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.606",
|
|
11981
|
+
"@north-light/identity": "0.3.606"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.606",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.606",
|
|
11990
|
+
"@north-light/identity": "0.3.606",
|
|
11991
|
+
"@north-light/plugin": "0.3.606",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|