@north-light/cli 0.3.618 → 0.3.619

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,11 +1,11 @@
1
- var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as f,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as j}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as h}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new f;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await h(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=j();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object already holds ${r}; merging two person objects is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
1
+ var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as N,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new N;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await j(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=s(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
2
2
  WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
3
3
  AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of Q)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+s(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const a=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=s(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
4
4
  AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
5
5
  AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(a,p))+s(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,a)),t["relations.written_by"]=s(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=s(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of ne)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of ee){const d=s(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+s(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));d!==0&&(t[`${o}.person`]=d)}const u=s(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await re(n,e))&&(await z(n,e,r),t["charge_totals.rebuilt"]=1),t}c(U,"substitutePerson");async function te(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
6
6
  WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?s(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await G(n,"app:terminal")).id)):0)+s(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+s(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(te,"rewriteLegacyGrantees");async function ae(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),a=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=s(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t)),p["node_tokens.grant"]=s(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${a})`).run(r,...t)),p["crons.grant_id"]=s(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=s(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
7
7
  WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
8
- AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await h(async e=>{const r={},t=c((w,T="")=>{for(const[N,R]of Object.entries(w))R!==0&&(r[T+N]=(r[T+N]??0)+R)},"add");let a=await m(e,l);if(a===null)throw new f;let p=null;const u=j();u!==null&&u!==a&&(t(await U(e,a,u),"join."),await _(e,l,u),p=a,a=u);const o=M()??S("user").runtime?.issuer,i=await m(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const d=await m(e,O)!==a;if(d){t({legacy_grantees:await te(e)}),t(await U(e,E,a));const w=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
8
+ AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await j(async e=>{const r={},t=c((w,T="")=>{for(const[R,f]of Object.entries(w))f!==0&&(r[T+R]=(r[T+R]??0)+f)},"add");let a=await m(e,l);if(a===null)throw new N;let p=null;const u=h();u!==null&&u!==a&&(t(await U(e,a,u),"join."),await _(e,l,u),p=a,a=u);const o=M()??S("user").runtime?.issuer,i=await m(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const d=await m(e,O)!==a;if(d){t({legacy_grantees:await te(e)}),t(await U(e,E,a));const w=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
9
9
  WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${w} LIMIT 1`).get()!==void 0){const T=await J(e,"person","user",a,"user");t({repaired_stubs:s(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${w})`).run(T.id))})}t({"nodes.sub_null_terminal":s(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
10
10
  SELECT n.node_id FROM nodes n JOIN identities i ON i.object = n.app
11
- WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,f as PersonUnresolvedError,D as isCloudRole,v as markCloudRole,$ as personId,me as personIdAsync,V as resolvePerson,Z as resolvePersonId,ge as retireLocalPerson,b as runAsPerson,y as setPersonId,U as substitutePerson};
11
+ WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,N as PersonUnresolvedError,D as isCloudRole,v as markCloudRole,$ as personId,me as personIdAsync,V as resolvePerson,Z as resolvePersonId,ge as retireLocalPerson,b as runAsPerson,y as setPersonId,U as substitutePerson};
@@ -0,0 +1,35 @@
1
+ -- 014-identities-person.sql — a repo identity belongs to a person. One transaction. `identities.person` is the owning account's
2
+ -- principal (`user:…`) for a repo object and '' for every other identity (app, person, profile, user), so those stay unique across
3
+ -- the whole graph while two people may each hold a repo with the same git remote or local path. The unique key becomes
4
+ -- (person, scheme, external_id); the raw remote or path stays in `external_id`, which repo-sync compares.
5
+ --
6
+ -- Dropping `identities_scheme_external_id_key` is a removal. No writer names that key in an ON CONFLICT clause, but the previous build
7
+ -- (version 11) looks a repo up by (scheme, external_id) alone and inserts repo identities without a person, so on this schema it would
8
+ -- find another person's repo or create a second one under person ''; `schema_min_reader` rises to 14 in the last statement.
9
+ ALTER TABLE identities ADD COLUMN person text NOT NULL DEFAULT '';
10
+
11
+ -- Backfill: each repo identity takes the person of its single `acts_for @ user` fact. None or several is a database this change
12
+ -- must not guess about, so it stops here instead of handing the repo to whichever account imports next. A soft-deleted repo with no
13
+ -- fact (boot's seed skipped it) keeps person '': nothing looks it up, and its identity stays unique.
14
+ DO $$
15
+ DECLARE bad record;
16
+ BEGIN
17
+ FOR bad IN
18
+ SELECT i.object, count(DISTINCT r.subject_id) AS n
19
+ FROM identities i JOIN objects o ON o.id = i.object AND o.type = 'repo'
20
+ LEFT JOIN relations r ON r.resource_type = 'crtr/object' AND r.resource_id = i.object
21
+ AND r.relation = 'acts_for' AND r.subject_type = 'user'
22
+ GROUP BY i.object, o.deleted_at
23
+ HAVING count(DISTINCT r.subject_id) <> 1 AND NOT (count(DISTINCT r.subject_id) = 0 AND o.deleted_at IS NOT NULL)
24
+ LOOP
25
+ RAISE EXCEPTION 'repo % has % acts_for facts; each repo must have exactly one before its identity can belong to a person', bad.object, bad.n;
26
+ END LOOP;
27
+ END $$;
28
+ UPDATE identities i SET person = 'user:' || r.subject_id
29
+ FROM objects o, relations r
30
+ WHERE o.id = i.object AND o.type = 'repo'
31
+ AND r.resource_type = 'crtr/object' AND r.resource_id = i.object AND r.relation = 'acts_for' AND r.subject_type = 'user';
32
+
33
+ ALTER TABLE identities DROP CONSTRAINT identities_scheme_external_id_key;
34
+ ALTER TABLE identities ADD CONSTRAINT identities_person_scheme_external_id_key UNIQUE (person, scheme, external_id);
35
+ INSERT INTO canvas_meta (key, value) VALUES ('schema_min_reader', '14') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 13;
4
+ export declare const CANVAS_SCHEMA_VERSION = 14;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=13;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=14;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -16,9 +16,10 @@ export declare function createObject(db: CanvasDb, spec: {
16
16
  schema_type?: string;
17
17
  }): Promise<ObjectRow>;
18
18
  /** The advisory lock key `ensureOwner` takes for a first sighting of an identity. */
19
- export declare const ownerLockKey: (scheme: string, externalId: string) => string;
19
+ export declare const ownerLockKey: (scheme: string, externalId: string, person?: string) => string;
20
20
  /** The owner object for an identity, created on first sight. Idempotent on
21
- * (scheme, externalId). Handles are unique per owner type: a handle already held
21
+ * (scheme, externalId); a repo identity is also scoped to the person the request runs as, so two people
22
+ * holding the same remote or path each get their own repo. Handles are unique per owner type: a handle already held
22
23
  * by a different identity of the same type throws `conflict` naming both; it is
23
24
  * never renamed silently. */
24
25
  export declare function ensureOwner(db: CanvasDb, type: OwnerType, scheme: string, externalId: string, handle: string, owner?: ObjectRow): Promise<ObjectRow>;
@@ -1,17 +1,17 @@
1
- var W=Object.defineProperty;var s=(e,t)=>W(e,"name",{value:t,configurable:!0});import{CrtrError as D,notFound as T}from"../errors.js";import{ExitCode as x}from"../../types.js";import{newNodeId as v}from"../runtime/nodes.js";import{kindOf as k}from"./kinds/registry.js";import{findMany as J}from"./bodies.js";import{isCloudRole as O,personId as P,personIdAsync as Y}from"../canvas/person.js";import{check as B,permits as A,resolveReader as $}from"../permissions/evaluator.js";import{userSubject as C,writeActsFor as g}from"../permissions/facts.js";const K=new Set(["person","app","repo","profile"]);function U(e){return e||null}s(U,"rowFrom");async function X(e,t){return U(await e.prepare("SELECT * FROM objects WHERE id = ?").get(t))}s(X,"getById");async function z(e,t){return await k(e,t.type),await e.prepare(`INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at, home_machine, schema_type)
2
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(t.id??await v(),t.type,t.kind,t.owner,t.privacy,t.name,t.preview,new Date().toISOString(),t.home_machine??null,t.schema_type??null)}s(z,"createObject");const G=s((e,t)=>`owner:${e}:${t}`,"ownerLockKey");async function F(e,t,o,i,n,d){if(!K.has(t))throw new Error(`ensureOwner: ${t} is not an owner type`);const p=s(async()=>await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE i.scheme = ? AND i.external_id = ?`).get(o,i),"find"),u=await p();if(u)return u;await e.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(G(o,i));const f=await p();if(f)return f;const E=await e.prepare(`SELECT o.id, o.type, i.scheme, i.external_id FROM objects o
1
+ var v=Object.defineProperty;var s=(e,t)=>v(e,"name",{value:t,configurable:!0});import{CrtrError as x,notFound as $}from"../errors.js";import{ExitCode as C}from"../../types.js";import{newNodeId as k}from"../runtime/nodes.js";import{kindOf as J}from"./kinds/registry.js";import{findMany as P}from"./bodies.js";import{isCloudRole as A,personId as Y,personIdAsync as g}from"../canvas/person.js";import{check as B,permits as _,resolveReader as U}from"../permissions/evaluator.js";import{userSubject as R,writeActsFor as y}from"../permissions/facts.js";const K=new Set(["person","app","repo","profile"]);function F(e){return e||null}s(F,"rowFrom");async function X(e,t){return F(await e.prepare("SELECT * FROM objects WHERE id = ?").get(t))}s(X,"getById");async function z(e,t){return await J(e,t.type),await e.prepare(`INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at, home_machine, schema_type)
2
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`).get(t.id??await k(),t.type,t.kind,t.owner,t.privacy,t.name,t.preview,new Date().toISOString(),t.home_machine??null,t.schema_type??null)}s(z,"createObject");const G=s((e,t,o="")=>`owner:${o}:${e}:${t}`,"ownerLockKey");async function M(e,t,o,i,n,d){if(!K.has(t))throw new Error(`ensureOwner: ${t} is not an owner type`);const p=t==="repo"?await g():"",u=s(async()=>await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(p,o,i),"find"),w=await u();if(w)return w;await e.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(G(o,i,p));const S=await u();if(S)return S;const E=await e.prepare(`SELECT o.id, o.type, i.scheme, i.external_id FROM objects o
4
4
  LEFT JOIN identities i ON i.object = o.id
5
- WHERE o.name = ? AND o.type = ? AND o.home_machine IS NULL`).get(n,t);if(E)throw new D("conflict",`handle "${n}" is held by ${E.type} ${E.id} (${E.scheme}:${E.external_id}); cannot give it to ${t} ${o}:${i}`,x.GENERAL,{handle:n,holder:E.id});const h=await z(e,{type:t,kind:null,owner:t==="profile"?d?.id??null:null,privacy:"public",name:n,preview:""});return await e.prepare("INSERT INTO identities (object, scheme, external_id) VALUES (?, ?, ?)").run(h.id,o,i),t==="person"&&o==="user"?await g(e,h.id,C(i).id):(t==="profile"||t==="repo")&&await g(e,h.id,C(await Y()).id),h}s(F,"ensureOwner");async function ae(e,t,o){if(O())return!1;const i=await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
5
+ WHERE o.name = ? AND o.type = ? AND o.home_machine IS NULL`).get(n,t);if(E)throw new x("conflict",`handle "${n}" is held by ${E.type} ${E.id} (${E.scheme}:${E.external_id}); cannot give it to ${t} ${o}:${i}`,C.GENERAL,{handle:n,holder:E.id});const m=await z(e,{type:t,kind:null,owner:t==="profile"?d?.id??null:null,privacy:"public",name:n,preview:""});return await e.prepare("INSERT INTO identities (object, scheme, external_id, person) VALUES (?, ?, ?, ?)").run(m.id,o,i,p),t==="person"&&o==="user"?await y(e,m.id,R(i).id):t==="repo"?await y(e,m.id,R(p).id):t==="profile"&&await y(e,m.id,R(await g()).id),m}s(M,"ensureOwner");async function ae(e,t,o){if(A())return!1;const i=await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
6
6
  WHERE i.scheme = 'profile' AND i.external_id = ? AND o.type = 'profile' AND o.deleted_at IS NULL`).get(t),n=await e.prepare(`SELECT o.id FROM objects o
7
- WHERE o.name = ? AND o.type = 'profile' AND o.deleted_at IS NULL AND o.home_machine IS NULL AND o.id <> ?`).get(o,i?i.id:"");if(n)throw new D("conflict",`handle "${o}" is already held by profile object ${n.id}; cannot rename profile ${t} to it`,x.GENERAL,{handle:o,holder:n.id});if(!i)return!1;const d=i;return d.name===o?!1:(await V(e,d,o),!0)}s(ae,"renameProfileObject");function ce(e,t){return O()?e:t}s(ce,"profileHandle");async function de(e,t){if(/^app:[a-z0-9][a-z0-9._-]*$/.test(t))return await F(e,"app","app",t,t.slice(4));if(/^user:[a-z0-9][a-z0-9._-]*$/.test(t))return await F(e,"person","user",t,!O()&&t===P()?"user":t.slice(5));throw new Error(`principal ${JSON.stringify(t)} is neither app:<name> nor user:<id>`)}s(de,"ownerForGrantee");async function pe(e,t,o){return U(await e.prepare("SELECT * FROM objects WHERE (type = 'document' OR strpos(type, '.') > 0) AND owner = ? AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(t,o))}s(pe,"liveDocumentNamed");async function ue(e,t){const o=await X(e,t);if(!o||o.type!=="node")throw T(`no node object ${t}`);return o}s(ue,"nodeObject");async function V(e,t,o){await e.prepare("UPDATE objects SET name = ? WHERE id = ?").run(o,t.id)}s(V,"setObjectName");async function Ee(e,t,o){await e.prepare("UPDATE objects SET kind = ? WHERE id = ?").run(o,t.id)}s(Ee,"setObjectKind");function _(e,t){const o=[];return e.type!==void 0&&(o.push("o.type = ?"),t.push(e.type)),e.kind!==void 0&&(o.push("o.kind = ?"),t.push(e.kind)),e.owner!==void 0&&(o.push("o.owner = ?"),t.push(e.owner.id)),e.namePrefix!==void 0&&(o.push("o.name LIKE ? ESCAPE '\\'"),t.push(`${e.namePrefix.replace(/[\\%_]/g,i=>`\\${i}`)}%`)),e.schemaType!==void 0&&(o.push("o.schema_type = ?"),t.push(e.schemaType)),e.extensions!==void 0&&(o.push("EXISTS (SELECT 1 FROM documents x WHERE x.object = o.id AND x.extensions_json::jsonb @> ?::jsonb)"),t.push(JSON.stringify(e.extensions))),o}s(_,"narrowing");function Q(e,t){const o="WITH RECURSIVE sa(id, owner, depth) AS (SELECT o.id, o.owner, 0 UNION ALL SELECT p.id, p.owner, sa.depth + 1 FROM sa JOIN objects p ON p.id = sa.owner WHERE sa.depth < 12)";t.push(e.subjects.userIds,e.subjects.groupIds);const i=["o.schema_type IS NULL",`EXISTS (${o} SELECT 1 FROM sa JOIN relations r ON r.resource_type = 'crtr/object' AND r.resource_id = sa.id
7
+ WHERE o.name = ? AND o.type = 'profile' AND o.deleted_at IS NULL AND o.home_machine IS NULL AND o.id <> ?`).get(o,i?i.id:"");if(n)throw new x("conflict",`handle "${o}" is already held by profile object ${n.id}; cannot rename profile ${t} to it`,C.GENERAL,{handle:o,holder:n.id});if(!i)return!1;const d=i;return d.name===o?!1:(await V(e,d,o),!0)}s(ae,"renameProfileObject");function ce(e,t){return A()?e:t}s(ce,"profileHandle");async function de(e,t){if(/^app:[a-z0-9][a-z0-9._-]*$/.test(t))return await M(e,"app","app",t,t.slice(4));if(/^user:[a-z0-9][a-z0-9._-]*$/.test(t))return await M(e,"person","user",t,!A()&&t===Y()?"user":t.slice(5));throw new Error(`principal ${JSON.stringify(t)} is neither app:<name> nor user:<id>`)}s(de,"ownerForGrantee");async function pe(e,t,o){return F(await e.prepare("SELECT * FROM objects WHERE (type = 'document' OR strpos(type, '.') > 0) AND owner = ? AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(t,o))}s(pe,"liveDocumentNamed");async function ue(e,t){const o=await X(e,t);if(!o||o.type!=="node")throw $(`no node object ${t}`);return o}s(ue,"nodeObject");async function V(e,t,o){await e.prepare("UPDATE objects SET name = ? WHERE id = ?").run(o,t.id)}s(V,"setObjectName");async function Ee(e,t,o){await e.prepare("UPDATE objects SET kind = ? WHERE id = ?").run(o,t.id)}s(Ee,"setObjectKind");function j(e,t){const o=[];return e.type!==void 0&&(o.push("o.type = ?"),t.push(e.type)),e.kind!==void 0&&(o.push("o.kind = ?"),t.push(e.kind)),e.owner!==void 0&&(o.push("o.owner = ?"),t.push(e.owner.id)),e.namePrefix!==void 0&&(o.push("o.name LIKE ? ESCAPE '\\'"),t.push(`${e.namePrefix.replace(/[\\%_]/g,i=>`\\${i}`)}%`)),e.schemaType!==void 0&&(o.push("o.schema_type = ?"),t.push(e.schemaType)),e.extensions!==void 0&&(o.push("EXISTS (SELECT 1 FROM documents x WHERE x.object = o.id AND x.extensions_json::jsonb @> ?::jsonb)"),t.push(JSON.stringify(e.extensions))),o}s(j,"narrowing");function Q(e,t){const o="WITH RECURSIVE sa(id, owner, depth) AS (SELECT o.id, o.owner, 0 UNION ALL SELECT p.id, p.owner, sa.depth + 1 FROM sa JOIN objects p ON p.id = sa.owner WHERE sa.depth < 12)";t.push(e.subjects.userIds,e.subjects.groupIds);const i=["o.schema_type IS NULL",`EXISTS (${o} SELECT 1 FROM sa JOIN relations r ON r.resource_type = 'crtr/object' AND r.resource_id = sa.id
8
8
  AND r.relation IN ('reader', 'editor', 'messenger', 'user_of') AND r.written_by <> 'package'
9
9
  AND ((r.subject_type = 'user' AND r.subject_id = ANY(?::text[])) OR (r.subject_type = 'crtr/group' AND r.subject_relation = 'member' AND r.subject_id = ANY(?::text[]))))`];return e.userId===null?i:(t.push(e.userId),[...i,`NOT EXISTS (${o} SELECT 1 FROM sa JOIN relations r ON r.resource_type = 'crtr/object' AND r.resource_id = sa.id
10
- AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`])}s(Q,"sharedOnly");async function me(e,t,o,i={}){const n=["o.seq > ?"],d=[i.after_seq??0];o.privacy!==void 0&&(n.push("o.privacy = ?"),d.push(o.privacy)),o.name!==void 0&&(n.push("o.name = ?"),d.push(o.name)),n.push("o.home_machine IS NULL"),n.push(o.deleted?"o.deleted_at IS NOT NULL":"o.deleted_at IS NULL"),n.push(..._(o,d));const p=await $(e,t);o.shared&&n.push(...Q(p,d));const u=await A(e,p,"read","o"),f=Math.min(i.limit??100,100);return await e.prepareUncached(`SELECT o.* FROM objects o WHERE ${n.join(" AND ")} AND (${u.sql}) ORDER BY o.seq LIMIT ${f}`).all(...d,...u.params)}s(me,"listObjects");async function fe(e,t,o){const n=[],d=`%${o.text.replace(/[\\%_]/g,r=>`\\${r}`)}%`,p=await $(e,t);if(!o.grep){const r=[d],m=_(o,r).map(l=>` AND ${l}`).join(""),c=await A(e,p,"read","o"),a=await e.prepareUncached(`SELECT o.*, (SELECT d.summary FROM documents d WHERE d.object = o.id) AS _summary FROM objects o
10
+ AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`])}s(Q,"sharedOnly");async function me(e,t,o,i={}){const n=["o.seq > ?"],d=[i.after_seq??0];o.privacy!==void 0&&(n.push("o.privacy = ?"),d.push(o.privacy)),o.name!==void 0&&(n.push("o.name = ?"),d.push(o.name)),n.push("o.home_machine IS NULL"),n.push(o.deleted?"o.deleted_at IS NOT NULL":"o.deleted_at IS NULL"),n.push(...j(o,d));const p=await U(e,t);o.shared&&n.push(...Q(p,d));const u=await _(e,p,"read","o"),w=Math.min(i.limit??100,100);return await e.prepareUncached(`SELECT o.* FROM objects o WHERE ${n.join(" AND ")} AND (${u.sql}) ORDER BY o.seq LIMIT ${w}`).all(...d,...u.params)}s(me,"listObjects");async function fe(e,t,o){const n=[],d=`%${o.text.replace(/[\\%_]/g,r=>`\\${r}`)}%`,p=await U(e,t);if(!o.grep){const r=[d],f=j(o,r).map(l=>` AND ${l}`).join(""),c=await _(e,p,"read","o"),a=await e.prepareUncached(`SELECT o.*, (SELECT d.summary FROM documents d WHERE d.object = o.id) AS _summary FROM objects o
11
11
  WHERE o.deleted_at IS NULL AND o.home_machine IS NULL AND (o.name ILIKE ?1 ESCAPE '\\' OR o.preview ILIKE ?1 ESCAPE '\\'
12
- OR EXISTS (SELECT 1 FROM documents d WHERE d.object = o.id AND d.summary ILIKE ?1 ESCAPE '\\'))${m}
13
- AND (${c.sql}) ORDER BY o.seq LIMIT 100`).all(...r,...c.params),N=o.text.toLowerCase();for(const l of a){const{_summary:S,...H}=l,L=H,b=L.name.toLowerCase().includes(N)?"name":L.preview.toLowerCase().includes(N)?"preview":"summary";n.push({object:L,field:b,...b==="summary"?{text:String(S)}:{}})}if(n.length>=100)return n}if(!o.body&&!o.grep)return n;const u=new Set(n.map(r=>r.object.id)),f=o.grep?(r=>m=>r.test(m))(new RegExp(o.text)):r=>r.includes(o.text),E=[],h=_(o,E).map(r=>` AND ${r}`).join(""),R=await e.prepareUncached(`SELECT o.id, r.body_hash AS body_hash FROM objects o
12
+ OR EXISTS (SELECT 1 FROM documents d WHERE d.object = o.id AND d.summary ILIKE ?1 ESCAPE '\\'))${f}
13
+ AND (${c.sql}) ORDER BY o.seq LIMIT 100`).all(...r,...c.params),N=o.text.toLowerCase();for(const l of a){const{_summary:L,...W}=l,O=W,T=O.name.toLowerCase().includes(N)?"name":O.preview.toLowerCase().includes(N)?"preview":"summary";n.push({object:O,field:T,...T==="summary"?{text:String(L)}:{}})}if(n.length>=100)return n}if(!o.body&&!o.grep)return n;const u=new Set(n.map(r=>r.object.id)),w=o.grep?(r=>f=>r.test(f))(new RegExp(o.text)):r=>r.includes(o.text),S=[],E=j(o,S).map(r=>` AND ${r}`).join(""),m=await e.prepareUncached(`SELECT o.id, r.body_hash AS body_hash FROM objects o
14
14
  JOIN documents d ON d.object = o.id JOIN revisions r ON r.document = o.id
15
- WHERE o.type = 'document' AND o.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id)${h}
16
- ORDER BY o.seq, r.number`).all(...E),y=await A(e,p,"read","o"),M=200;let w=[];const j=s(async()=>{if(w.length===0)return!1;const r=await e.prepareUncached(`SELECT o.* FROM objects o WHERE o.id = ANY(?::text[]) AND (${y.sql})`).all(w.map(c=>c.id),...y.params),m=new Map(r.map(c=>[c.id,c]));for(const c of w){const a=m.get(c.id);if(a!==void 0&&(n.push({object:a,field:"body",line:c.line,text:c.text}),n.length>=100))return!0}return w=[],!1},"flush"),I=100;for(let r=0;r<R.length;r+=I){const m=R.slice(r,r+I).filter(a=>!u.has(a.id)),c=await J(e,m.map(a=>a.body_hash));for(const a of m){if(u.has(a.id))continue;const N=c.get(a.body_hash);if(N===void 0){if(await B(e,p,"read",a.id))throw T(`no body ${a.body_hash}`);continue}if(!o.grep&&!N.includes(o.text))continue;const l=N.split(`
17
- `),S=l.findIndex(f);if(!(S<0)&&(u.add(a.id),w.push({id:a.id,line:S+1,text:l[S]}),w.length>=M&&await j()))return n}}return await j(),n}s(fe,"searchObjects");export{z as createObject,F as ensureOwner,X as getById,me as listObjects,pe as liveDocumentNamed,ue as nodeObject,de as ownerForGrantee,G as ownerLockKey,ce as profileHandle,ae as renameProfileObject,fe as searchObjects,Ee as setObjectKind,V as setObjectName};
15
+ WHERE o.type = 'document' AND o.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id)${E}
16
+ ORDER BY o.seq, r.number`).all(...S),I=await _(e,p,"read","o"),H=200;let h=[];const D=s(async()=>{if(h.length===0)return!1;const r=await e.prepareUncached(`SELECT o.* FROM objects o WHERE o.id = ANY(?::text[]) AND (${I.sql})`).all(h.map(c=>c.id),...I.params),f=new Map(r.map(c=>[c.id,c]));for(const c of h){const a=f.get(c.id);if(a!==void 0&&(n.push({object:a,field:"body",line:c.line,text:c.text}),n.length>=100))return!0}return h=[],!1},"flush"),b=100;for(let r=0;r<m.length;r+=b){const f=m.slice(r,r+b).filter(a=>!u.has(a.id)),c=await P(e,f.map(a=>a.body_hash));for(const a of f){if(u.has(a.id))continue;const N=c.get(a.body_hash);if(N===void 0){if(await B(e,p,"read",a.id))throw $(`no body ${a.body_hash}`);continue}if(!o.grep&&!N.includes(o.text))continue;const l=N.split(`
17
+ `),L=l.findIndex(w);if(!(L<0)&&(u.add(a.id),h.push({id:a.id,line:L+1,text:l[L]}),h.length>=H&&await D()))return n}}return await D(),n}s(fe,"searchObjects");export{z as createObject,M as ensureOwner,X as getById,me as listObjects,pe as liveDocumentNamed,ue as nodeObject,de as ownerForGrantee,G as ownerLockKey,ce as profileHandle,ae as renameProfileObject,fe as searchObjects,Ee as setObjectKind,V as setObjectName};
@@ -7,7 +7,7 @@ export interface RepoIdentity {
7
7
  externalId: string;
8
8
  handleHint: string;
9
9
  }
10
- /** The repo object for an identity, created on first sight. A handle already
10
+ /** The repo object of the person this request runs as for an identity, created on first sight. A handle already
11
11
  * held by another repo gets `-2`, `-3`, … appended. */
12
12
  export declare function ensureRepo(db: CanvasDb, id: RepoIdentity, handle?: string): Promise<ObjectRow>;
13
13
  /** Repos enclosing `cwd`, nearest first: every enclosing git checkout (created
@@ -1,3 +1,3 @@
1
- var l=Object.defineProperty;var a=(t,o)=>l(t,"name",{value:o,configurable:!0});import{resolve as c,sep as f}from"node:path";import{CrtrError as u}from"../../errors.js";import{realpathOrSelf as h}from"../../fs-utils.js";import{ExitCode as m}from"../../../types.js";import{ensureOwner as w}from"../objects.js";import{checkoutChain as d,handleHint as E}from"./identity.js";async function x(t,o,r){return await t.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
- WHERE o.type = 'repo' AND i.scheme = ? AND i.external_id = ?`).get(o,r)??null}a(x,"existingRepo");async function N(t,o,r){const n=await x(t,o.scheme,o.externalId);if(n)return n;const s=r??o.handleHint,p=t.prepare("SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL");let e=s;for(let i=2;await p.get(e);i++)e=`${s}-${i}`;return await w(t,"repo",o.scheme,o.externalId,e)}a(N,"ensureRepo");async function I(t,o){return(await y(t,o)).map(r=>r.repo)}a(I,"reposForCwd");async function L(t){await d(h(c(t)))}a(L,"warmCheckoutIdentities");async function y(t,o){const r=h(c(o)),n=[];for(const e of await d(r)){if(!e.ok)throw new u("git-lookup-failed",`cannot identify the repo at ${e.dir}: ${e.reason}`,m.GENERAL,{dir:e.dir});n.push({root:e.root,repo:await N(t,e)})}const s=await t.prepare(`SELECT o.*, i.external_id AS path FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(const{path:e,...i}of s)(r===e||r.startsWith(e.endsWith(f)?e:e+f))&&n.push({root:e,repo:i});n.sort((e,i)=>i.root.length-e.root.length);const p=new Set;return n.filter(({repo:e})=>!p.has(e.id)&&(p.add(e.id),!0))}a(y,"checkoutsForCwd");export{y as checkoutsForCwd,N as ensureRepo,E as handleHint,I as reposForCwd,L as warmCheckoutIdentities};
1
+ var E=Object.defineProperty;var i=(t,o)=>E(t,"name",{value:o,configurable:!0});import{resolve as h,sep as l}from"node:path";import{CrtrError as x}from"../../errors.js";import{realpathOrSelf as d}from"../../fs-utils.js";import{ExitCode as N}from"../../../types.js";import{personIdAsync as m}from"../../canvas/person.js";import{ensureOwner as y}from"../objects.js";import{checkoutChain as w,handleHint as g}from"./identity.js";async function A(t,o,r,n){return await t.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
+ WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(o,r,n)??null}i(A,"existingRepo");async function C(t,o,r){const n=await A(t,await m(),o.scheme,o.externalId);if(n)return n;const a=r??o.handleHint;await t.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`repo-handle:${a}`);const c=t.prepare("SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL");let s=a;for(let p=2;await c.get(s);p++)s=`${a}-${p}`;return await y(t,"repo",o.scheme,o.externalId,s)}i(C,"ensureRepo");async function F(t,o){return(await O(t,o)).map(r=>r.repo)}i(F,"reposForCwd");async function H(t){await w(d(h(t)))}i(H,"warmCheckoutIdentities");async function O(t,o){const r=d(h(o)),n=[];for(const e of await w(r)){if(!e.ok)throw new x("git-lookup-failed",`cannot identify the repo at ${e.dir}: ${e.reason}`,N.GENERAL,{dir:e.dir});n.push({root:e.root,repo:await C(t,e)})}const c=(await t.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all()).filter(({path:e})=>r===e||r.startsWith(e.endsWith(l)?e:e+l)),s=c.length>0?await m():"";for(const{path:e,person:f,...u}of c)f===s&&n.push({root:e,repo:u});n.sort((e,f)=>f.root.length-e.root.length);const p=new Set;return n.filter(({repo:e})=>!p.has(e.id)&&(p.add(e.id),!0))}i(O,"checkoutsForCwd");export{O as checkoutsForCwd,C as ensureRepo,g as handleHint,F as reposForCwd,H as warmCheckoutIdentities};
@@ -5,16 +5,16 @@ export declare const BODIES_TABLE = "bodies";
5
5
  /** Tables whose rows are dumped, staged and (after rewrites) copied, in no particular order: the lane computes the copy
6
6
  * order from the target's foreign-key catalog. Each row file holds the table's rows in primary-key order (identity-ordered
7
7
  * tables in source `seq` order). */
8
- 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", "app_users", "idempotency_keys", "uploads", "upload_uses", "shares", "provider_approvals", "relations", "charges", "limits", "conversation_parts", "conversation_entries", "profiles", "bodies"];
8
+ 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
9
  /** Dumped and staged so rewrite 2 can map them, never inserted into the target (`grants`: the directory writes them). */
10
10
  export declare const STAGED_ONLY_TABLES: readonly ["grants"];
11
11
  /** Every table the exporter dumps. */
12
12
  export declare const DUMPED_TABLES: readonly string[];
13
- /** Tables with an identity primary key, tracked in `import_key_map` (source key → target key). */
13
+ /** Tables with an identity primary key, tracked in `import_key_map` (source key → target key). `app_users` is not among them: it records the Linux users
14
+ * of the source host, which mean nothing on the target, and a host allows one active row per app. */
14
15
  export declare const KEY_MAPPED_TABLES: {
15
16
  readonly audit_rows: "id";
16
17
  readonly review_comment_events: "seq";
17
- readonly app_users: "uid";
18
18
  };
19
19
  /** Tables the target numbers by `seq`/identity in source order (the staged `seq` is not carried over). */
20
20
  export declare const SEQ_TABLES: readonly ["objects", "revisions", "watches", "watch_subscriptions", "sessions", "waits", "structured_requests", "deliveries", "run_events"];
@@ -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 p,zstdDecompressSync as l}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","app_users","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",app_users:"uid"},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=l(s).toString("utf8");if(e==="")return[];if(!e.endsWith(`
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(`
2
2
  `))throw new Error("row file is truncated: the last line is not newline-terminated");return e.slice(0,-1).split(`
3
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=p({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};
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};
@@ -36,7 +36,8 @@ export declare function takeRepoSyncedDocuments(db: CanvasDb, schema: string, ta
36
36
  export interface Collision {
37
37
  table: string;
38
38
  key: string;
39
- values: string[];
39
+ values: string[]; /** Two staged rows collide with each other, not with the target. */
40
+ staged?: true;
40
41
  }
41
- /** Pre-check (I9): every non-primary unique key and every text primary key the target already holds. Throws `unique_conflict` naming the first 10 values. */
42
+ /** Pre-check (I9): every non-primary unique key and every text primary key the target already holds, and every unique key two staged rows share. Throws `unique_conflict` naming the first 10 values. */
42
43
  export declare function precheck(db: CanvasDb, schema: string, target: string, catalog: Catalog, tables: readonly string[], skip: ReadonlySet<string>, seqLike: ReadonlyMap<string, string[]>): Promise<void>;
@@ -1,11 +1,12 @@
1
- var y=Object.defineProperty;var d=(n,s)=>y(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as I}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 U}from"../../conversation-store/row-store.js";import{runBlobKey as A}from"../bundle/blob-keys.js";import{q as u}from"./catalog.js";const $=d((n,s)=>`${u(n)}.${u(s)}`,"sq");async function j(n,s,c){if(c.length===0)return 0;const e=d(o=>$(s,o),"S"),r=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=d(async(o,t,i,l=!1)=>{const m=await n.prepareUncached(`SELECT ${u(t)}::text AS value FROM ${e(o)} WHERE ${i} AND ${u(t)} IS NOT NULL`).all();for(const{value:f}of m){const h=l?W(f,c):S(c,f);h!==f&&(await n.prepareUncached(`UPDATE ${e(o)} SET ${u(t)} = ? WHERE ${u(t)}::text = ? AND ${i}`).run(h,f),a+=1)}},"apply");return await E("nodes","cwd",`node_id IN ${r}`),await E("worktrees","path",`node_id IN ${r}`),await E("worktrees","repo_root",`node_id IN ${r}`),await E("crons","cwd",`anchor_node IN ${r}`),await E("provider_approvals","prepared_files","TRUE",!0),await E("upload_uses","path",`run_id IN ${r}`),a}d(j,"rewritePaths");async function k(n,s,c,e,r){if(c.length===0)return 0;const a=d(t=>$(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:i}of E){const l=A(r,i),m=await e.get(l);if(m===null)throw new N("rewrite-paths","bundle_invalid",`${l} is missing: the header of conversation ${t} cannot be rewritten`);const f=U(m,t,h=>S(c,h));f!==null&&(await e.put(l,f),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ? WHERE conversation_id = ? AND seq = 0`).run((f??m).length,t)}return o}d(k,"rewriteConversationHeaders");async function P(n,s){const c=$(s,"human_requests"),e=d(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
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}
3
3
  WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
4
  WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
5
- ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),r=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(r.changes)}d(P,"rewriteRequestPaths");function W(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(([r,a])=>[r,c(a)])):e,"walk");try{return JSON.stringify(c(JSON.parse(n)))}catch{return S(s,n)}}d(W,"rewriteJsonPaths");async function B(n,s,c,e,r){const a=d(t=>$(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 ${$(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(r,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(B,"renameClashingProfiles");async function K(n,s,c,e,r){const a=d(t=>$(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 i=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(i=(await n.prepareUncached(`SELECT environment_id FROM ${$(c,"profiles")} WHERE id = ?`).get(t.id))?.environment_id??await I(n,{profileId:t.id,grantee:t.grantee??"app:terminal",person:r})),i===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(i,t.id),E+=1}return E}d(K,"fillEnvironments");async function J(n,s,c,e){const r=d(o=>$(s,o),"S"),a={},E=d(async(o,t,...i)=>{const l=Number((await n.prepareUncached(t).run(...i)).changes);l>0&&(a[o]=(a[o]??0)+l)},"del");await E("limits",`DELETE FROM ${r("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${r("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${r("environments")})`).run(),await n.prepareUncached(`UPDATE ${r("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${r("environments")})`).run());for(const[o,t]of Object.entries(H))await E(o,`DELETE FROM ${r(o)} WHERE ${u(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 ${r(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(J,"pruneStaged");async function Y(n,s,c){const e=d(E=>$(s,E),"S"),r=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${$(c,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${r};
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 ${r})`);const a=await n.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
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};
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 ${r} 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 ${r})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${r}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${r}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${r}`).run(),a.map(E=>({...E}))}d(Y,"takeRepoSyncedDocuments");const C={edges:["created_at"],relations:["created_at"]};async function X(n,s,c,e,r,a,E){const o=d(i=>[...E.get(i)??[],...i==="profiles"?["environment_id"]:[],...C[i]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const i of r){const l=e.tables.get(i);if(l===void 0||a.has(i)||l.primaryKey.length===0)continue;const m=l.primaryKey,f=m.some(p=>l.identity.includes(p)),h=m.map(p=>`s.${u(p)} = t.${u(p)}`).join(" AND "),O=f?"TRUE":m.map(p=>`s.${u(p)} IS DISTINCT FROM t.${u(p)}`).join(" OR "),v=new Set([...l.identity,...E.get(i)??[]]);for(const p of e.uniqueKeys.filter(R=>R.table===i&&!R.columns.every(_=>v.has(_)))){const R=p.predicate===null?"":` WHERE ${p.predicate}`,_=p.columns.map(T=>`s.${u(T)} = t.${u(T)}`).join(" AND "),L=await n.prepareUncached(`SELECT ${p.columns.map(T=>`s.${u(T)}::text`).join(" || ',' || ")} AS value
10
- FROM (SELECT * FROM ${$(s,i)}${R}) s JOIN (SELECT * FROM ${$(c,i)}${R}) t ON ${_} AND (${O}) LIMIT 10`).all();L.length>0&&t.push({table:i,key:p.name,values:L.map(T=>T.value)})}const w=l.columns.filter(p=>!l.identity.includes(p)&&!o(i).includes(p));if(w.length>0&&!f){const p=w.map(_=>`s.${u(_)} IS DISTINCT FROM t.${u(_)}`).join(" OR "),R=await n.prepareUncached(`SELECT ${m.map(_=>`s.${u(_)}::text`).join(" || ',' || ")} AS value
11
- FROM ${$(s,i)} s JOIN ${$(c,i)} t ON ${h} WHERE ${p} LIMIT 10`).all();R.length>0&&t.push({table:i,key:"primary key payload",values:R.map(_=>_.value)})}}if(t.length>0){const i=t[0];throw new N("pre-check","unique_conflict",`${i.table} ${i.key} collides with the target: ${i.values.join(", ")}`,{collisions:t})}}d(X,"precheck");export{K as fillEnvironments,X as precheck,J as pruneStaged,B as renameClashingProfiles,k as rewriteConversationHeaders,j as rewritePaths,P as rewriteRequestPaths,Y 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}))}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};
@@ -27,6 +27,13 @@ export declare const OBJECT_ID_COLUMNS: ReadonlyArray<[string, string]>;
27
27
  export declare function objectIdColumns(catalog: Catalog): Map<string, Set<string>>;
28
28
  /** Rewrite 1: `substitutePerson` against the staging schema (every table it touches is staged, the ones the bundle does not dump empty). */
29
29
  export declare function rewritePerson(input: RewriteInput): Promise<void>;
30
+ /** The staged repo identities belong to the run's person (`identities.person`, delta 014). Runs after `rewritePerson` and whether or not it changed anything: a bundle's
31
+ * repo identities carry the source person, or none at all when exported before the column existed, and the person of this run is the one that owns them here. */
32
+ export declare function scopeRepoIdentities(input: RewriteInput): Promise<number>;
33
+ /** A staged repo whose handle another repo holds is renamed `<handle>-<its object id>`. Handles are unique per type across the whole fleet (`objects_handle`, soft-deleted
34
+ * objects included), so a second person's repo named like the first's cannot keep its name, and it is never the other person's repo that moves. The new handle is a function of
35
+ * the object alone, so a second load of the bundle derives the same one. A repo the target already holds under its own id is not a clash with itself. Runs after the id map. */
36
+ export declare function renameClashingRepos(input: RewriteInput): Promise<number>;
30
37
  /** The target's grant for (fleet runtime, sub, grantee), the key the directory writes an importing person's grants under. The lane's wait for those
31
38
  * grants (`run.ts`) and rewrite 2 both look a grant up here. A null fleet runtime (`CRTR_RUNTIME` unset) holds none. */
32
39
  export declare function findFleetGrant(db: CanvasDb, target: string, fleetRuntime: string | null, sub: string, grantee: string): Promise<string | undefined>;
@@ -1,14 +1,15 @@
1
- var h=Object.defineProperty;var l=(n,s)=>h(n,"name",{value:s,configurable:!0});import{createHash as D}from"node:crypto";import{ROOT_PROFILE_ID as L}from"../../profiles/manifest.js";import{substitutePerson as A}from"../../canvas/person.js";import{withCanvasWrite as I}from"../../canvas/db.js";import{ImportLaneError as j}from"./stage.js";import{q as T}from"./catalog.js";const M=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"],["waits","target_id"]],H=[["nodes","grant_id"],["crons","grant_id"]],w={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},C=["app","person","profile","repo"];function S(n){const s=new Map,o=l((E,d)=>{s.has(E)||s.set(E,new Set),s.get(E).add(d)},"add");for(const E of n.foreignKeys)E.parent==="objects"&&E.columns.length===1&&o(E.table,E.columns[0]);for(const[E,d]of M)o(E,d);return s}l(S,"objectIdColumns");const N=l((n,s)=>`${T(n)}.${T(s)}`,"sq"),p=l(async(n,s,...o)=>Number((await n.prepareUncached(s).run(...o)).changes),"run"),O=l(async(n,s,...o)=>await n.prepareUncached(s).all(...o),"rows");async function K(n){n.sourcePerson!==n.targetPerson&&await I(async s=>{await s.exec(`SET LOCAL search_path TO ${T(n.schema)}`),await A(s,n.sourcePerson,n.targetPerson)})}l(K,"rewritePerson");async function W(n,s,o,E,d){return o===null?void 0:(await n.prepareUncached(`SELECT id FROM ${N(s,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,E,d))?.id}l(W,"findFleetGrant");function F(n){return new j("id_map","grant_missing",`no grant in the target for: ${n.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...n]})}l(F,"grantMissing");async function Y(n,s){const{db:o,schema:E,target:d}=n,t=l(e=>N(E,e),"S"),m=l(e=>N(d,e),"T"),b={object:new Map,grant:new Map,kind:new Map};for(const[e,r]of s)b.object.set(e,r);const i=n.targetPerson.replace(/^user:/,"");for(const e of C){const r=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${m("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,f=await O(o,`SELECT i.object AS src, t.object AS dst FROM ${t("identities")} i
2
- 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 ${r}`,e,e==="person"?n.targetPerson:i);for(const{src:R,dst:_}of f)R!==_&&b.object.set(R,_)}const u=await O(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${t("objects")} o JOIN ${t("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL`);for(const e of u){const r=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("documents")} d ON d.object = o.id
6
- WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(b.object.get(e.owner)??e.owner,e.name);if(r!==void 0){b.object.set(e.id,r.id);continue}const f=n.shippedBodies[e.id];if(f===void 0)throw new j("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const R=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("identities")} i ON i.object = o.id
1
+ var I=Object.defineProperty;var d=(t,a)=>I(t,"name",{value:a,configurable:!0});import{createHash as M}from"node:crypto";import{ROOT_PROFILE_ID as h}from"../../profiles/manifest.js";import{substitutePerson as H}from"../../canvas/person.js";import{withCanvasWrite as W}from"../../canvas/db.js";import{ImportLaneError as j}from"./stage.js";import{q as $}from"./catalog.js";const C=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"],["waits","target_id"]],F=[["nodes","grant_id"],["crons","grant_id"]],g={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},y=["app","person","profile","repo"];function D(t){const a=new Map,o=d((c,s)=>{a.has(c)||a.set(c,new Set),a.get(c).add(s)},"add");for(const c of t.foreignKeys)c.parent==="objects"&&c.columns.length===1&&o(c.table,c.columns[0]);for(const[c,s]of C)o(c,s);return a}d(D,"objectIdColumns");const f=d((t,a)=>`${$(t)}.${$(a)}`,"sq"),p=d(async(t,a,...o)=>Number((await t.prepareUncached(a).run(...o)).changes),"run"),_=d(async(t,a,...o)=>await t.prepareUncached(a).all(...o),"rows");async function q(t){t.sourcePerson!==t.targetPerson&&await W(async a=>{await a.exec(`SET LOCAL search_path TO ${$(t.schema)}`),await H(a,t.sourcePerson,t.targetPerson)})}d(q,"rewritePerson");async function G(t){const a=d(o=>f(t.schema,o),"S");return await p(t.db,`UPDATE ${a("identities")} SET person = '' WHERE person IS NULL`),await p(t.db,`UPDATE ${a("identities")} SET person = ? WHERE object IN (SELECT id FROM ${a("objects")} WHERE type = 'repo')`,t.targetPerson)}d(G,"scopeRepoIdentities");async function V(t){const a=d(s=>f(t.schema,s),"S"),o=d(s=>f(t.target,s),"T");let c=0;for(const s of await _(t.db,`SELECT id, name FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL ORDER BY id`))await t.db.prepareUncached(`SELECT 1 AS found FROM ${o("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id <> ?
2
+ UNION ALL SELECT 1 FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id < ? LIMIT 1`).get(s.name,s.id,s.name,s.id)!==void 0&&(await p(t.db,`UPDATE ${a("objects")} SET name = ? WHERE id = ?`,`${s.name}-${s.id}`,s.id),c+=1);return c}d(V,"renameClashingRepos");async function U(t,a,o,c,s){return o===null?void 0:(await t.prepareUncached(`SELECT id FROM ${f(a,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,c,s))?.id}d(U,"findFleetGrant");function x(t){return new j("id_map","grant_missing",`no grant in the target for: ${t.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...t]})}d(x,"grantMissing");async function P(t,a,o,c,s,n,l,N){const E=a.uniqueKeys.find(r=>r.table==="objects"&&r.name==="objects_named");if(E===void 0||E.predicate===null)throw new j("id_map","import_failed","the target has no objects_named unique index with a predicate");const T=d(r=>`(SELECT * FROM ${r} WHERE ${E.predicate}) o`,"live"),u="o.id <> ? AND o.name = ?";return await t.prepareUncached(`SELECT 1 FROM ${T(o)} WHERE o.owner IN (${s.map(()=>"?").join(", ")}) AND ${u} LIMIT 1`).get(...s,l,N)!==void 0?!0:await t.prepareUncached(`SELECT 1 FROM ${T(c)} WHERE o.owner = ? AND ${u} LIMIT 1`).get(n,l,N)!==void 0}d(P,"usesName");async function z(t,a){const{db:o,schema:c,target:s}=t,n=d(e=>f(c,e),"S"),l=d(e=>f(s,e),"T"),N={object:new Map,grant:new Map,kind:new Map};for(const[e,m]of a)N.object.set(e,m);const E=t.targetPerson.replace(/^user:/,"");for(const e of y){const m=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${l("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 = ?)`,b=await _(o,`SELECT i.object AS src, t.object AS dst FROM ${n("identities")} i
3
+ JOIN ${n("objects")} so ON so.id = i.object AND so.type = ?
4
+ JOIN ${l("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id${e==="repo"?" AND t.person = ? AND t.scheme = 'git'":""}
5
+ JOIN ${l("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
6
+ WHERE ${m}`,e,...e==="repo"?[t.targetPerson]:[],e==="person"?t.targetPerson:E);for(const{src:R,dst:O}of b)R!==O&&N.object.set(R,O)}const T=await _(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${n("objects")} o JOIN ${n("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL ORDER BY o.id`);for(const e of T){const m=await o.prepareUncached(`SELECT o.id FROM ${l("objects")} o JOIN ${l("documents")} d ON d.object = o.id
7
+ WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(N.object.get(e.owner)??e.owner,e.name);if(m!==void 0){N.object.set(e.id,m.id);continue}const b=t.shippedBodies[e.id];if(b===void 0)throw new j("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const R=await o.prepareUncached(`SELECT o.id FROM ${l("objects")} o JOIN ${l("identities")} i ON i.object = o.id
7
8
  WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ?
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(R===void 0)throw new j("id_map","bundle_invalid",`no person object for ${n.targetPerson}; cannot import shipped document ${e.name}`);await p(o,`UPDATE ${t("objects")} SET owner = ? WHERE id = ?`,R.id,e.id),await p(o,`DELETE FROM ${t("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await p(o,`INSERT INTO ${t("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
10
- VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,i,e.created_at),await p(o,`UPDATE ${t("documents")} SET source_path = NULL WHERE object = ?`,e.id),await p(o,`UPDATE ${t("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${t("revision_parents")} p WHERE p.parent = r.rev_id)`,f,e.id)}const $=await O(o,`SELECT id, sub, grantee FROM ${t("grants")} ORDER BY id`),a=[];for(const e of $){const r=await W(o,d,n.fleetRuntime,e.sub,e.grantee);r===void 0?a.push(e.grantee):b.grant.set(e.id,r)}if(a.length>0)throw F(a);await o.exec(`CREATE TABLE ${t("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,r]of[["object",b.object],["grant",b.grant]])for(const[f,R]of r)await p(o,`INSERT INTO ${t("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,f,R);const c=`(SELECT source FROM ${t("_idmap")} WHERE kind = 'object')`;for(const[e,r]of Object.entries(w))await p(o,`DELETE FROM ${t(e)} WHERE ${r} IN ${c}`);await p(o,`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${c})`),await p(o,`DELETE FROM ${t("revisions")} WHERE document IN ${c}`);for(const[e,r]of S(n.catalog))if(n.catalog.tables.has(e))for(const f of r)await g(o,t(e),f,"object",t("_idmap"));for(const[e,r]of H)await g(o,t(e),r,"grant",t("_idmap"));await p(o,`UPDATE ${t("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
11
- FROM ${t("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(o,`DELETE FROM ${t("objects")} WHERE id IN ${c}`),await p(o,`UPDATE ${t("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${t("identities")} WHERE scheme = 'user' AND external_id = ?)`,i,i,n.targetPerson);for(const{name:e}of await O(o,`SELECT k.name FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`))b.kind.set(e,e);return await p(o,`DELETE FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`),b}l(Y,"rewriteIds");async function B(n){const{db:s,schema:o,target:E,targetPerson:d}=n,t=new Map,m=l(async(i,...u)=>await s.prepareUncached(i).get(...u),"row"),b=l(i=>p(s,`DELETE FROM ${N(o,"profiles")} WHERE id = ?`,i),"dropStaged");for(const{id:i}of await O(s,`SELECT id FROM ${N(o,"profiles")} ORDER BY id`)){let u=i===L?await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE person = ? AND name = 'root'`,d):await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ? AND person = ?`,i,d);if(u===void 0){if(await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ?`,i)===void 0&&i!==L)continue;const c=`${i.replace(/-[0-9a-f]{8}$/,"")}-${D("sha256").update(`${d}\0${i}`).digest("hex").slice(0,8)}`,e=await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ?`,c);if(e!==void 0&&e.person!==d)throw new j("id_map","unique_conflict",`profiles ${c} is held by another person in the target`,{table:"profiles",values:[c]});u=e??{id:c,person:d},e===void 0?await p(s,`UPDATE ${N(o,"profiles")} SET id = ? WHERE id = ?`,c,i):await b(i)}else await b(i);const $=u.id;await p(s,`UPDATE ${N(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${N(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
12
- AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${N(E,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,$,i,$,i),await p(s,`UPDATE ${N(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${N(o,"objects")} WHERE type = 'profile')`,$,i),$!==i&&t.set(i,$)}return t}l(B,"mapProfileIds");async function g(n,s,o,E,d){await p(n,`UPDATE ${s} t SET ${T(o)} = m.target FROM ${d} m WHERE m.kind = ? AND t.${T(o)} = m.source`,E)}l(g,"remap");async function X(n){const{db:s,schema:o,target:E,catalog:d}=n,t=l(a=>N(o,a),"S"),m={},b=l((a,c)=>{c>0&&(m[a]=(m[a]??0)+c)},"count");await s.exec(`CREATE TABLE ${t("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const i=`(SELECT id FROM ${t("objects")} WHERE home_machine IS NOT NULL)`;await p(s,`INSERT INTO ${t("_dropped")} SELECT 'objects', id FROM ${t("objects")} WHERE home_machine IS NOT NULL`);for(const[a,c]of Object.entries(w))b(a,await p(s,`DELETE FROM ${t(a)} WHERE ${c} IN ${i}`));b("objects",await p(s,`DELETE FROM ${t("objects")} WHERE home_machine IS NOT NULL`));const u=new Map;for(const[a,c]of S(d))d.tables.has(a)&&a!=="messages"&&u.set(a,[...c]);const $=`(SELECT key FROM ${t("_dropped")} WHERE tbl = 'objects')`;for(;;){let a=0;const c=l(async(e,r,...f)=>{const R=d.tables.get(e).primaryKey.length===1?T(d.tables.get(e).primaryKey[0]):null;R!==null&&await p(s,`INSERT INTO ${t("_dropped")} SELECT ?, ${R}::text FROM ${t(e)} WHERE ${r} ON CONFLICT DO NOTHING`,e,...f);const _=await p(s,`DELETE FROM ${t(e)} WHERE ${r}`,...f);b(e,_),a+=_},"drop");for(const e of d.foreignKeys)e.columns.length!==1||e.parentColumns.length!==1||!n.catalog.tables.has(e.table)||await c(e.table,`${T(e.columns[0])} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?)`,e.parent);for(const[e,r]of u)await c(e,r.map(f=>`${T(f)} IN ${$}`).join(" OR "));if(a===0)break}for(const a of d.foreignKeys){if(a.columns.length!==1||!d.tables.has(a.table))continue;const c=T(a.columns[0]),e=T(a.parentColumns[0]),r=await O(s,`SELECT DISTINCT c.${c}::text AS value FROM ${t(a.table)} c
13
- WHERE c.${c} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${t(a.parent)} p WHERE p.${e} = c.${c})
14
- AND NOT EXISTS (SELECT 1 FROM ${N(E,a.parent)} p WHERE p.${e} = c.${c}) LIMIT 10`);if(r.length>0)throw new j("drop","bundle_invalid",`${a.table}.${a.columns[0]} names rows that exist nowhere: ${r.map(f=>f.value).join(", ")}`,{table:a.table,column:a.columns[0],values:r.map(f=>f.value)})}return m}l(X,"dropStubRows");export{M as OBJECT_ID_COLUMNS,X as dropStubRows,W as findFleetGrant,F as grantMissing,B as mapProfileIds,S as objectIdColumns,Y as rewriteIds,K as rewritePerson};
9
+ UNION ALL SELECT o.id FROM ${n("objects")} o JOIN ${n("identities")} i ON i.object = o.id
10
+ WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(t.targetPerson,t.targetPerson);if(R===void 0)throw new j("id_map","bundle_invalid",`no person object for ${t.targetPerson}; cannot import shipped document ${e.name}`);const O=[R.id,...[...N.object].filter(([,L])=>L===R.id).map(([L])=>L)],w=d(L=>P(o,t.catalog,n("objects"),l("objects"),O,R.id,e.id,L),"named");let S=e.name;if(await w(S)){const L=await o.prepareUncached(`SELECT name FROM ${n("objects")} WHERE id = ?`).get(e.owner);S=`${e.name}-${L?.name??e.id}`,await w(S)&&(S=`${e.name}-${e.id}`)}await p(o,`UPDATE ${n("objects")} SET owner = ?, name = ? WHERE id = ?`,R.id,S,e.id),await p(o,`UPDATE ${n("rules")} SET owner = ? WHERE object = ?`,R.id,e.id),await p(o,`DELETE FROM ${n("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await p(o,`INSERT INTO ${n("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
11
+ VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,E,e.created_at),await p(o,`UPDATE ${n("documents")} SET source_path = NULL WHERE object = ?`,e.id),await p(o,`UPDATE ${n("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${n("revision_parents")} p WHERE p.parent = r.rev_id)`,b,e.id)}const u=await _(o,`SELECT id, sub, grantee FROM ${n("grants")} ORDER BY id`),i=[];for(const e of u){const m=await U(o,s,t.fleetRuntime,e.sub,e.grantee);m===void 0?i.push(e.grantee):N.grant.set(e.id,m)}if(i.length>0)throw x(i);await o.exec(`CREATE TABLE ${n("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,m]of[["object",N.object],["grant",N.grant]])for(const[b,R]of m)await p(o,`INSERT INTO ${n("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,b,R);const r=`(SELECT source FROM ${n("_idmap")} WHERE kind = 'object')`;for(const[e,m]of Object.entries(g))await p(o,`DELETE FROM ${n(e)} WHERE ${m} IN ${r}`);await p(o,`DELETE FROM ${n("revision_parents")} WHERE child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${r})`),await p(o,`DELETE FROM ${n("revisions")} WHERE document IN ${r}`);for(const[e,m]of D(t.catalog))if(t.catalog.tables.has(e))for(const b of m)await A(o,n(e),b,"object",n("_idmap"));for(const[e,m]of F)await A(o,n(e),m,"grant",n("_idmap"));await p(o,`UPDATE ${n("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
12
+ FROM ${n("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(o,`DELETE FROM ${n("objects")} WHERE id IN ${r}`),await p(o,`UPDATE ${n("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${n("identities")} WHERE scheme = 'user' AND external_id = ?)`,E,E,t.targetPerson);for(const{name:e}of await _(o,`SELECT k.name FROM ${n("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${l("object_kinds")} t WHERE t.name = k.name)`))N.kind.set(e,e);return await p(o,`DELETE FROM ${n("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${l("object_kinds")} t WHERE t.name = k.name)`),N}d(z,"rewriteIds");async function Q(t){const{db:a,schema:o,target:c,targetPerson:s}=t,n=new Map,l=d(async(E,...T)=>await a.prepareUncached(E).get(...T),"row"),N=d(E=>p(a,`DELETE FROM ${f(o,"profiles")} WHERE id = ?`,E),"dropStaged");for(const{id:E}of await _(a,`SELECT id FROM ${f(o,"profiles")} ORDER BY id`)){let T=E===h?await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE person = ? AND name = 'root'`,s):await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ? AND person = ?`,E,s);if(T===void 0){if(await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ?`,E)===void 0&&E!==h)continue;const r=`${E.replace(/-[0-9a-f]{8}$/,"")}-${M("sha256").update(`${s}\0${E}`).digest("hex").slice(0,8)}`,e=await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ?`,r);if(e!==void 0&&e.person!==s)throw new j("id_map","unique_conflict",`profiles ${r} is held by another person in the target`,{table:"profiles",values:[r]});T=e??{id:r,person:s},e===void 0?await p(a,`UPDATE ${f(o,"profiles")} SET id = ? WHERE id = ?`,r,E):await N(E)}else await N(E);const u=T.id;await p(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 = ?)
13
+ AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${f(c,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,u,E,u,E),await p(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')`,u,E),u!==E&&n.set(E,u)}return n}d(Q,"mapProfileIds");async function A(t,a,o,c,s){await p(t,`UPDATE ${a} t SET ${$(o)} = m.target FROM ${s} m WHERE m.kind = ? AND t.${$(o)} = m.source`,c)}d(A,"remap");async function Z(t){const{db:a,schema:o,target:c,catalog:s}=t,n=d(i=>f(o,i),"S"),l={},N=d((i,r)=>{r>0&&(l[i]=(l[i]??0)+r)},"count");await a.exec(`CREATE TABLE ${n("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const E=`(SELECT id FROM ${n("objects")} WHERE home_machine IS NOT NULL)`;await p(a,`INSERT INTO ${n("_dropped")} SELECT 'objects', id FROM ${n("objects")} WHERE home_machine IS NOT NULL`);for(const[i,r]of Object.entries(g))N(i,await p(a,`DELETE FROM ${n(i)} WHERE ${r} IN ${E}`));N("objects",await p(a,`DELETE FROM ${n("objects")} WHERE home_machine IS NOT NULL`));const T=new Map;for(const[i,r]of D(s))s.tables.has(i)&&i!=="messages"&&T.set(i,[...r]);const u=`(SELECT key FROM ${n("_dropped")} WHERE tbl = 'objects')`;for(;;){let i=0;const r=d(async(e,m,...b)=>{const R=s.tables.get(e).primaryKey.length===1?$(s.tables.get(e).primaryKey[0]):null;R!==null&&await p(a,`INSERT INTO ${n("_dropped")} SELECT ?, ${R}::text FROM ${n(e)} WHERE ${m} ON CONFLICT DO NOTHING`,e,...b);const O=await p(a,`DELETE FROM ${n(e)} WHERE ${m}`,...b);N(e,O),i+=O},"drop");for(const e of s.foreignKeys)e.columns.length!==1||e.parentColumns.length!==1||!t.catalog.tables.has(e.table)||await r(e.table,`${$(e.columns[0])} IN (SELECT key FROM ${n("_dropped")} WHERE tbl = ?)`,e.parent);for(const[e,m]of T)await r(e,m.map(b=>`${$(b)} IN ${u}`).join(" OR "));if(i===0)break}for(const i of s.foreignKeys){if(i.columns.length!==1||!s.tables.has(i.table))continue;const r=$(i.columns[0]),e=$(i.parentColumns[0]),m=await _(a,`SELECT DISTINCT c.${r}::text AS value FROM ${n(i.table)} c
14
+ WHERE c.${r} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${n(i.parent)} p WHERE p.${e} = c.${r})
15
+ AND NOT EXISTS (SELECT 1 FROM ${f(c,i.parent)} p WHERE p.${e} = c.${r}) LIMIT 10`);if(m.length>0)throw new j("drop","bundle_invalid",`${i.table}.${i.columns[0]} names rows that exist nowhere: ${m.map(b=>b.value).join(", ")}`,{table:i.table,column:i.columns[0],values:m.map(b=>b.value)})}return l}d(Z,"dropStubRows");export{C as OBJECT_ID_COLUMNS,Z as dropStubRows,U as findFleetGrant,x as grantMissing,Q as mapProfileIds,D as objectIdColumns,V as renameClashingRepos,z as rewriteIds,q as rewritePerson,G as scopeRepoIdentities};
@@ -1,3 +1,3 @@
1
- var z=Object.defineProperty;var u=(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 C}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 ce}from"./prepare.js";import{boundSub as ue,checkSourcePerson as fe,checkStagedBlobKeys as le,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,moveRunBlobs as he}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Ee,grantMissing as Se,mapProfileIds as ve,rewriteIds as Re,rewritePerson as Oe}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as Pe,stagingSchema as Te,targetSchema as ke}from"./stage.js";import{verifyRun as je}from"./verify.js";import{sandboxPathMap as Ie,writeNodeFiles as De}from"./path-map.js";import{allStoreKeys as Ae,readPluginsStore as Me,recordImportedActivations as Ce,writeStores as Ne}from"./stores.js";import{publishImportedPlugins as Le}from"./publish-plugins.js";import{COPIED_TABLES as Be}from"../bundle/layout.js";import{ClaimLostError as We}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,He=30*6e4,R=u(()=>new Date().toISOString(),"now"),O=u(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Ke(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"))}u(Ke,"readSource");async function Ue(e,i,n,r,s,d){const t=await e.get(v.rows(n.run_id,"grants")),l=t===null?[]:x(t),_=[];for(const a of l){const c=ue(a.sub,r,n.person,"grants.sub");await Ee(i,s,d,c,a.grantee)===void 0&&_.push(a.grantee)}if(_.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 Se(_);return!1}u(Ue,"grantsReady");async function ft(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=Te(e.run_id),t=u(async a=>{await i.assertOwned(),await O(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const _=[];try{const a=await Ke(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const c=await ke(s),P=[...Be],g=await ae(s,c,[...P,"grants"]);if(!l){const f={},k=[],j=[],I=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await fe(s,c,a.person,e.person),!await Ue(r,s,e,a.person,c,I)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await Le(await Me(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}j.push(...h.refused),await t("stage");const K=await Pe(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const m={db:s,schema:d,target:c,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:I,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await _e(m)))y(f,o,p);for(const[o,p]of Object.entries(await le(m)))y(f,o,p);await t("rewrite-person"),await Oe(m),await t("prune");const U=await ie(s,d,g,a),E=a.kind==="hosted"?Ie(a.pathPrefixes??[]):[];await t("rewrite-paths"),await de(s,d,E),await oe(s,d,E,r,e.run_id),await pe(s,d),await we(m);const F=await ve(m);await re(s,d,c,a.installId,e.person),await t("rewrite-ids");const D=await Re(m,F);await t("drop");const J=await ce(s,d,c),q=await ye(m);for(const[o,p]of Object.entries({...U}))y(f,o,p);for(const[o,p]of Object.entries(q))y(f,o,p);await me(m),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,c,g,P,new Set,$),await t("blobs"),await he(s,d,c,e.person,r,e.run_id,_),await t("copy"),await C(async o=>{await i.assertOwned({extendLeaseMs:He});const p=await ne({db:o,runId:e.run_id,schema:d,target:c,catalog:g,source:a,person:e.person,idMap:D,pathMap:E}),A=await qe(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await De(o,d,e.run_id,a);const M=await Ne({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,Y]of Object.entries(M.inserted))p.inserted[G]=Y.length;return k.push(...M.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Je(f,p),unresolved_plugins:k,refused_plugins:j}),R(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const b=await je(s,e.run_id,d,c,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const T=v.manifest(e.run_id);await r.put(T,await $e(e.run_id)),await B(s,e.run_id);for(const f of Ae(e.run_id))await r.delete(f);await be(r,e.run_id),await C(async f=>{await Ce(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,R(),e.run_id)})}catch(a){if(a instanceof We)throw a;const c=Fe(a);await B(s,e.run_id).catch(()=>{}),l||await ge(r,_,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id)}}u(ft,"processRun");function Fe(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(Fe,"failureOf");function y(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(y,"addDropped");function Je(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(Je,"withInserted");async function qe(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 _=await Z(e,t);_!==null&&await X(e,_,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(qe,"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)}u(H,"appendManifest");async function $e(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 z=Object.defineProperty;var u=(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 ce}from"./prepare.js";import{boundSub as ue,checkSourcePerson as fe,checkStagedBlobKeys as le,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,moveRunBlobs as he}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Ee,grantMissing as Se,mapProfileIds as ve,renameClashingRepos as Re,rewriteIds as Oe,rewritePerson as Pe,scopeRepoIdentities as Te}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as ke,stagingSchema as Ie,targetSchema as je}from"./stage.js";import{verifyRun as De}from"./verify.js";import{sandboxPathMap as Ae,writeNodeFiles as Ce}from"./path-map.js";import{allStoreKeys as Me,readPluginsStore as Ne,recordImportedActivations as Le,writeStores as Be}from"./stores.js";import{publishImportedPlugins as We}from"./publish-plugins.js";import{COPIED_TABLES as He}from"../bundle/layout.js";import{ClaimLostError as Ke}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,Ue=30*6e4,R=u(()=>new Date().toISOString(),"now"),O=u(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Fe(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"))}u(Fe,"readSource");async function Je(e,i,n,r,s,d){const t=await e.get(v.rows(n.run_id,"grants")),_=t===null?[]:x(t),m=[];for(const a of _){const c=ue(a.sub,r,n.person,"grants.sub");await Ee(i,s,d,c,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=W)throw Se(m);return!1}u(Je,"grantsReady");async function _t(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=Ie(e.run_id),t=u(async a=>{await i.assertOwned(),await O(e.run_id,a),await n.atStep?.(a)},"at");let _=e.state==="committed";const m=[];try{const a=await Fe(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const c=await je(s),P=[...He],g=await ae(s,c,[...P,"grants"]);if(!_){const f={},k=[],I=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await fe(s,c,a.person,e.person),!await Je(r,s,e,a.person,c,j)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await We(await Ne(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}I.push(...h.refused),await t("stage");const K=await ke(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const l={db:s,schema:d,target:c,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await _e(l)))y(f,o,p);for(const[o,p]of Object.entries(await le(l)))y(f,o,p);await t("rewrite-person"),await Pe(l),await Te(l),await t("prune");const U=await ie(s,d,g,a),E=a.kind==="hosted"?Ae(a.pathPrefixes??[]):[];await t("rewrite-paths"),await de(s,d,E),await oe(s,d,E,r,e.run_id),await pe(s,d),await we(l);const F=await ve(l);await re(s,d,c,a.installId,e.person),await t("rewrite-ids");const D=await Oe(l,F);await t("drop");const J=await ce(s,d,c),q=await ye(l);for(const[o,p]of Object.entries({...U}))y(f,o,p);for(const[o,p]of Object.entries(q))y(f,o,p);await me(l),await Re(l),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,c,g,P,new Set,$),await t("blobs"),await he(s,d,c,e.person,r,e.run_id,m),await t("copy"),await M(async o=>{await i.assertOwned({extendLeaseMs:Ue});const p=await ne({db:o,runId:e.run_id,schema:d,target:c,catalog:g,source:a,person:e.person,idMap:D,pathMap:E}),A=await Ge(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Ce(o,d,e.run_id,a);const C=await Be({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 k.push(...C.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...$e(f,p),unresolved_plugins:k,refused_plugins:I}),R(),e.run_id),p}),_=!0,await n.atStep?.("committed")}await t("verify");const b=await De(s,e.run_id,d,c,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const T=v.manifest(e.run_id);await r.put(T,await Ye(e.run_id)),await B(s,e.run_id);for(const f of Me(e.run_id))await r.delete(f);await be(r,e.run_id),await M(async f=>{await Le(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,R(),e.run_id)})}catch(a){if(a instanceof Ke)throw a;const c=qe(a);await B(s,e.run_id).catch(()=>{}),_||await ge(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id)}}u(_t,"processRun");function qe(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(qe,"failureOf");function y(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(y,"addDropped");function $e(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($e,"withInserted");async function Ge(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,_]of d){const m=await Z(e,t);m!==null&&await X(e,m,_.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(_=>[t.rev_id,_]))),s.length}u(Ge,"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)}u(H,"appendManifest");async function Ye(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(`
2
2
  `)+`
3
- `))}u($e,"manifestFile");export{He as COPY_LEASE_MS,W as GRANT_WAIT_MS,ft as processRun};
3
+ `))}u(Ye,"manifestFile");export{Ue as COPY_LEASE_MS,W as GRANT_WAIT_MS,_t as processRun};
@@ -1 +1 @@
1
- var m=Object.defineProperty;var a=(t,s)=>m(t,"name",{value:s,configurable:!0});import{BODIES_TABLE as L,DUMPED_TABLES as E,rowLines as x}from"../bundle/layout.js";import{hashOf as T}from"../../graph/bodies.js";const A=["node_tokens","charge_chunks","charge_totals","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints","credential_activations"],y=16*1024*1024,I=2e3,$=a(t=>`import_${t.replace(/[^A-Za-z0-9_]/g,"_")}`,"stagingSchema"),n=a(t=>`"${t.replace(/"/g,'""')}"`,"q");async function C(t){return(await t.prepare("SELECT current_schema() AS s").get()).s}a(C,"targetSchema");async function D(t,s){await t.exec(`DROP SCHEMA IF EXISTS ${n($(s))} CASCADE`)}a(D,"dropStaging");async function U(t,s,e,i,f){const l=$(s),S=await C(t);await D(t,s),await t.exec(`CREATE SCHEMA ${n(l)}`);const g={};for(const o of[...E,...A])await t.exec(`CREATE UNLOGGED TABLE ${n(l)}.${n(o)} (LIKE ${n(S)}.${n(o)} INCLUDING DEFAULTS)`);for(const o of E){let d=0;for(const p of i(o)){const u=await f(p);if(u===null){if((e[o]??0)!==0)throw c(`row file ${p} is missing`);continue}let r=[],_=0;const w=a(async()=>{r.length!==0&&(await t.prepareUncached(`INSERT INTO ${n(l)}.${n(o)} SELECT * FROM json_populate_recordset(NULL::${n(l)}.${n(o)}, ?::json)`).run(`[${r.join(",")}]`),d+=r.length,r=[],_=0)},"insert");for await(const h of x(u)){if(!h.startsWith("{"))throw c(`row file ${p} has a line that is not a JSON object`);o===L&&N(p,h),r.length>0&&(r.length>=I||_+h.length>y)&&await w(),r.push(h),_+=h.length}await w()}if(d!==(e[o]??0))throw c(`row file for ${o} has ${d} rows; source.json says ${e[o]??0}`);g[o]=d}return g}a(U,"stage");function N(t,s){const e=JSON.parse(s);if(typeof e.hash!="string"||typeof e.text!="string")throw c(`row file ${t} has a bodies row without a hash and a text`);if(e.text.includes("\0"))throw c(`body ${e.hash} in ${t} holds a NUL character; export the source again after its daemon has been upgraded and restarted`);const i=T(e.text);if(i!==e.hash)throw c(`body ${e.hash} in ${t} does not hash to its key (its text hashes to ${i}); export the source again after its daemon has been upgraded and restarted`)}a(N,"checkBodyLine");class O extends Error{static{a(this,"ImportLaneError")}step;code;detail;constructor(s,e,i,f){super(i),this.step=s,this.code=e,this.detail=f}}function c(t){return new O("stage","bundle_invalid",t)}a(c,"bundleInvalid");export{A as EMPTY_STAGED_TABLES,O as ImportLaneError,D as dropStaging,U as stage,$ as stagingSchema,C as targetSchema};
1
+ var S=Object.defineProperty;var n=(t,a)=>S(t,"name",{value:a,configurable:!0});import{BODIES_TABLE as m,DUMPED_TABLES as w,rowLines as T}from"../bundle/layout.js";import{hashOf as x}from"../../graph/bodies.js";const A=["node_tokens","charge_chunks","charge_totals","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints","credential_activations"],y=16*1024*1024,C=2e3,$=n(t=>`import_${t.replace(/[^A-Za-z0-9_]/g,"_")}`,"stagingSchema"),s=n(t=>`"${t.replace(/"/g,'""')}"`,"q");async function I(t){return(await t.prepare("SELECT current_schema() AS s").get()).s}n(I,"targetSchema");async function N(t,a){await t.exec(`DROP SCHEMA IF EXISTS ${s($(a))} CASCADE`)}n(N,"dropStaging");async function k(t,a,e,i,f){const h=$(a),L=await I(t);await N(t,a),await t.exec(`CREATE SCHEMA ${s(h)}`);const g={};for(const o of[...w,...A])await t.exec(`CREATE UNLOGGED TABLE ${s(h)}.${s(o)} (LIKE ${s(L)}.${s(o)} INCLUDING DEFAULTS)`);await t.exec(`ALTER TABLE ${s(h)}.identities ALTER COLUMN person DROP NOT NULL`);for(const o of w){let p=0;for(const d of i(o)){const E=await f(d);if(E===null){if((e[o]??0)!==0)throw c(`row file ${d} is missing`);continue}let r=[],_=0;const u=n(async()=>{r.length!==0&&(await t.prepareUncached(`INSERT INTO ${s(h)}.${s(o)} SELECT * FROM json_populate_recordset(NULL::${s(h)}.${s(o)}, ?::json)`).run(`[${r.join(",")}]`),p+=r.length,r=[],_=0)},"insert");for await(const l of T(E)){if(!l.startsWith("{"))throw c(`row file ${d} has a line that is not a JSON object`);o===m&&O(d,l),r.length>0&&(r.length>=C||_+l.length>y)&&await u(),r.push(l),_+=l.length}await u()}if(p!==(e[o]??0))throw c(`row file for ${o} has ${p} rows; source.json says ${e[o]??0}`);g[o]=p}return g}n(k,"stage");function O(t,a){const e=JSON.parse(a);if(typeof e.hash!="string"||typeof e.text!="string")throw c(`row file ${t} has a bodies row without a hash and a text`);if(e.text.includes("\0"))throw c(`body ${e.hash} in ${t} holds a NUL character; export the source again after its daemon has been upgraded and restarted`);const i=x(e.text);if(i!==e.hash)throw c(`body ${e.hash} in ${t} does not hash to its key (its text hashes to ${i}); export the source again after its daemon has been upgraded and restarted`)}n(O,"checkBodyLine");class D extends Error{static{n(this,"ImportLaneError")}step;code;detail;constructor(a,e,i,f){super(i),this.step=a,this.code=e,this.detail=f}}function c(t){return new D("stage","bundle_invalid",t)}n(c,"bundleInvalid");export{A as EMPTY_STAGED_TABLES,D as ImportLaneError,N as dropStaging,k as stage,$ as stagingSchema,I as targetSchema};
@@ -1,8 +1,8 @@
1
- var E=Object.defineProperty;var r=(e,o)=>E(e,"name",{value:o,configurable:!0});import{withCanvasWrite as O}from"../canvas/db.js";import{personIdAsync as u}from"../canvas/person.js";async function b(){return await O(async e=>await I(e,await u()))}r(b,"runPermissionsBoot");async function _(e){return(await e.prepare(`UPDATE nodes n SET app = o.owner FROM objects o JOIN objects a ON a.id = o.owner AND a.type = 'app'
2
- WHERE o.id = n.node_id AND n.app IS NULL`).run()).changes}r(_,"backfillNodeApps");async function I(e,o){const t=new Date().toISOString(),s=o.replace(/^user:/,""),c=await _(e),N=(await e.prepare(`UPDATE objects o SET owner = p.id FROM nodes n
1
+ var E=Object.defineProperty;var r=(e,o)=>E(e,"name",{value:o,configurable:!0});import{withCanvasWrite as O}from"../canvas/db.js";import{personIdAsync as u}from"../canvas/person.js";async function j(){return await O(async e=>await T(e,await u()))}r(j,"runPermissionsBoot");async function _(e){return(await e.prepare(`UPDATE nodes n SET app = o.owner FROM objects o JOIN objects a ON a.id = o.owner AND a.type = 'app'
2
+ WHERE o.id = n.node_id AND n.app IS NULL`).run()).changes}r(_,"backfillNodeApps");async function T(e,o){const t=new Date().toISOString(),s=o.replace(/^user:/,""),c=await _(e),p=(await e.prepare(`UPDATE objects o SET owner = p.id FROM nodes n
3
3
  JOIN identities i ON i.scheme = 'profile' AND i.external_id = n.profile_id
4
4
  JOIN objects p ON p.id = i.object AND p.type = 'profile' AND p.deleted_at IS NULL
5
- WHERE o.id = n.node_id AND o.owner IS DISTINCT FROM p.id`).run()).changes,d=(await e.prepare(`INSERT INTO relations (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
5
+ WHERE o.id = n.node_id AND o.owner IS DISTINCT FROM p.id`).run()).changes,N=(await e.prepare(`INSERT INTO relations (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
6
6
  SELECT 'crtr/object', o.id, 'acts_for', 'user', regexp_replace(i.external_id, '^user:', ''), '', 'boot', ?
7
7
  FROM objects o JOIN identities i ON i.object = o.id AND i.scheme = 'user' WHERE o.type = 'person' ON CONFLICT DO NOTHING`).run(t)).changes;let a=0,i=0;const n=await e.prepare("SELECT value FROM canvas_meta WHERE key = 'permissions_seeded'").get();n===void 0&&(a=(await e.prepare(`INSERT INTO relations (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
8
8
  SELECT 'crtr/object', o.id, 'acts_for', 'user', ?, '', 'boot', ? FROM objects o
@@ -10,9 +10,9 @@ var E=Object.defineProperty;var r=(e,o)=>E(e,"name",{value:o,configurable:!0});i
10
10
  AND NOT EXISTS (SELECT 1 FROM documents d WHERE d.object = o.id AND d.source_path IS NOT NULL)))
11
11
  ON CONFLICT DO NOTHING`).run(s,t)).changes,i=(await e.prepare(`INSERT INTO relations (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
12
12
  SELECT 'crtr/object', o.id, 'reader', 'user', '*', '', 'package', ? FROM objects o JOIN documents d ON d.object = o.id
13
- WHERE o.deleted_at IS NULL AND d.source_path IS NOT NULL ON CONFLICT DO NOTHING`).run(t)).changes,await e.prepare("INSERT INTO canvas_meta (key, value) VALUES ('permissions_seeded', ?) ON CONFLICT (key) DO NOTHING").run(t));const p=(await e.prepare(`INSERT INTO relations (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
13
+ WHERE o.deleted_at IS NULL AND d.source_path IS NOT NULL ON CONFLICT DO NOTHING`).run(t)).changes,await e.prepare("INSERT INTO canvas_meta (key, value) VALUES ('permissions_seeded', ?) ON CONFLICT (key) DO NOTHING").run(t));const d=(await e.prepare(`INSERT INTO relations (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
14
14
  SELECT 'crtr/object', o.id, 'acts_for', 'user', ?, '', 'boot', ? FROM objects o
15
15
  WHERE o.type = 'node' AND o.deleted_at IS NOT NULL AND o.owner IN (SELECT id FROM objects WHERE type = 'app')
16
16
  AND EXISTS (SELECT 1 FROM objects d WHERE d.owner = o.id AND d.deleted_at IS NULL)
17
17
  AND NOT EXISTS (SELECT 1 FROM relations r WHERE r.resource_type = 'crtr/object' AND r.resource_id = o.id AND r.relation = 'acts_for')
18
- ON CONFLICT DO NOTHING`).run(s,t)).changes;return{nodesApp:c,reparented:N,personActsFor:d,actsFor:a,reapedNodes:p,shippedReaders:i,seeded:n===void 0}}r(I,"permissionsBoot");export{_ as backfillNodeApps,I as permissionsBoot,b as runPermissionsBoot};
18
+ ON CONFLICT DO NOTHING`).run(s,t)).changes;return await e.prepare("UPDATE identities i SET person = ? FROM objects o WHERE o.id = i.object AND o.type = 'repo' AND i.person = ''").run(o),{nodesApp:c,reparented:p,personActsFor:N,actsFor:a,reapedNodes:d,shippedReaders:i,seeded:n===void 0}}r(T,"permissionsBoot");export{_ as backfillNodeApps,T as permissionsBoot,j as runPermissionsBoot};
@@ -1,3 +1,3 @@
1
- var p=Object.defineProperty;var d=(e,i)=>p(e,"name",{value:i,configurable:!0});import{dirname as h}from"node:path";import{parseFrontmatterGeneric as w}from"../../frontmatter.js";import{readText as g,realpathOrSelf as R}from"../../fs-utils.js";import{checkoutChain as b}from"../../graph/repo-sync/identity.js";import{minRung as k,rungAtLeast as N,rungRank as m}from"../schema.js";import{ruleConstraintsFit as O,ruleGate as F}from"./match.js";function E(e){return e.doc.ownNode?"knowledge":e.doc.kind}d(E,"bootPartitionOf");async function L(e,i,t,a,n,o={}){const r=await v(e,n,o),c=(n==="document-read"&&o.doc!==void 0?a.filter(u=>u.object.id!==o.doc.object.id):a).map(u=>j(u,i,n,r));return W(n,c),{on:n,subject:i,reader:t,docs:c}}d(L,"planDelivery");async function v(e,i,t){if(i!=="file-read"||t.absoluteFile===void 0)return t;const a=R(t.absoluteFile);return{...t,absoluteFile:a,readFrontmatter:t.readFrontmatter??x(a),repoRoots:await y(e,a)}}d(v,"resolvePayload");function x(e){if(!/\.(md|mdx|markdown)$/i.test(e))return{};try{return w(g(e)).data??{}}catch{return{}}}d(x,"readFileFrontmatter");async function y(e,i){const t=new Map,a=e.prepare(`SELECT o.id FROM identities i JOIN objects o ON o.id = i.object
2
- WHERE o.type = 'repo' AND i.scheme = ? AND i.external_id = ?`);for(const o of await b(h(i))){if(!o.ok)break;const r=await a.get(o.scheme,o.externalId);r!==void 0&&!t.has(r.id)&&t.set(r.id,o.root)}const n=await e.prepare(`SELECT o.id, i.external_id AS path FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(const{id:o,path:r}of n)!t.has(o)&&i.startsWith(r.endsWith("/")?r:`${r}/`)&&t.set(o,r);return t}d(y,"repoRootsOf");function j(e,i,t,a){const n=e.rules.filter(s=>s.on===t).map(s=>{const f=F(s,i);return{rule:s,gate:f,matched:f.pass&&O(s,e,t,a)}});let o=null;for(const{rule:s,matched:f}of n)f&&(o===null||m(s.deliver)>m(o.deliver))&&(o=s);const r=o?.deliver??"none",l=(t==="boot"||t==="workspace-open")&&!e.ownNode?e.limit:null,c=l===null?r:k(r,l),u=t==="boot"&&e.ownNode&&n.length===0?"name":c;return{doc:e,authoredRules:n,matchedRule:o,authoredRung:r,limit:l,cappedRung:c,ruleGate:n.length===0?null:o!==null?{pass:!0}:n.find(s=>!s.gate.pass)?.gate??{pass:!0},finalRung:u,winner:!1,shadowedBy:null}}d(j,"decide");function A(e,i){if(i==="boot"){const t=e.authoredRules.length>0&&e.authoredRules.every(a=>!a.gate.pass);return e.limit!=="none"&&!t}return N(e.finalRung,"name")}d(A,"holdsName");function W(e,i){const t=e==="boot"||e==="workspace-open",a=new Map;for(const n of i){if(!A(n,e))continue;if(!t){n.winner=!0;continue}const o=e==="boot"?`${E(n)}:${n.doc.name}`:n.doc.name,r=a.get(o);r===void 0?(a.set(o,n),n.winner=!0):n.shadowedBy=r.doc}}d(W,"resolveWinners");export{E as bootPartitionOf,L as planDelivery};
1
+ var m=Object.defineProperty;var u=(e,o)=>m(e,"name",{value:o,configurable:!0});import{dirname as h}from"node:path";import{parseFrontmatterGeneric as w}from"../../frontmatter.js";import{readText as g,realpathOrSelf as R}from"../../fs-utils.js";import{checkoutChain as b}from"../../graph/repo-sync/identity.js";import{minRung as N,rungAtLeast as k,rungRank as p}from"../schema.js";import{ruleConstraintsFit as O,ruleGate as F}from"./match.js";import{personIdAsync as y}from"../../canvas/person.js";function A(e){return e.doc.ownNode?"knowledge":e.doc.kind}u(A,"bootPartitionOf");async function B(e,o,t,r,n,i={}){const c=await E(e,n,i),a=(n==="document-read"&&i.doc!==void 0?r.filter(l=>l.object.id!==i.doc.object.id):r).map(l=>j(l,o,n,c));return S(n,a),{on:n,subject:o,reader:t,docs:a}}u(B,"planDelivery");async function E(e,o,t){if(o!=="file-read"||t.absoluteFile===void 0)return t;const r=R(t.absoluteFile);return{...t,absoluteFile:r,readFrontmatter:t.readFrontmatter??v(r),repoRoots:await x(e,r)}}u(E,"resolvePayload");function v(e){if(!/\.(md|mdx|markdown)$/i.test(e))return{};try{return w(g(e)).data??{}}catch{return{}}}u(v,"readFileFrontmatter");async function x(e,o){const t=new Map;let r;const n=u(async()=>r??=await y(),"personOf"),i=e.prepare(`SELECT o.id FROM identities i JOIN objects o ON o.id = i.object
2
+ WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`);for(const s of await b(h(o))){if(!s.ok)break;const a=await i.get(await n(),s.scheme,s.externalId);a!==void 0&&!t.has(a.id)&&t.set(a.id,s.root)}const c=await e.prepare(`SELECT o.id, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(const{id:s,path:a,person:l}of c)!t.has(s)&&o.startsWith(a.endsWith("/")?a:`${a}/`)&&l===await n()&&t.set(s,a);return t}u(x,"repoRootsOf");function j(e,o,t,r){const n=e.rules.filter(d=>d.on===t).map(d=>{const f=F(d,o);return{rule:d,gate:f,matched:f.pass&&O(d,e,t,r)}});let i=null;for(const{rule:d,matched:f}of n)f&&(i===null||p(d.deliver)>p(i.deliver))&&(i=d);const c=i?.deliver??"none",s=(t==="boot"||t==="workspace-open")&&!e.ownNode?e.limit:null,a=s===null?c:N(c,s),l=t==="boot"&&e.ownNode&&n.length===0?"name":a;return{doc:e,authoredRules:n,matchedRule:i,authoredRung:c,limit:s,cappedRung:a,ruleGate:n.length===0?null:i!==null?{pass:!0}:n.find(d=>!d.gate.pass)?.gate??{pass:!0},finalRung:l,winner:!1,shadowedBy:null}}u(j,"decide");function D(e,o){if(o==="boot"){const t=e.authoredRules.length>0&&e.authoredRules.every(r=>!r.gate.pass);return e.limit!=="none"&&!t}return k(e.finalRung,"name")}u(D,"holdsName");function S(e,o){const t=e==="boot"||e==="workspace-open",r=new Map;for(const n of o){if(!D(n,e))continue;if(!t){n.winner=!0;continue}const i=e==="boot"?`${A(n)}:${n.doc.name}`:n.doc.name,c=r.get(i);c===void 0?(r.set(i,n),n.winner=!0):n.shadowedBy=c.doc}}u(S,"resolveWinners");export{A as bootPartitionOf,B as planDelivery};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.618",
3
+ "version": "0.3.619",
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.618",
148
+ "@north-light/identity": "0.3.619",
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.618",
3
+ "version": "0.3.619",
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.618",
3
+ "version": "0.3.619",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.618",
9
+ "version": "0.3.619",
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.618",
31
+ "@north-light/identity": "0.3.619",
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.618",
11959
+ "version": "0.3.619",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.618",
11964
+ "version": "0.3.619",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.618",
11969
+ "version": "0.3.619",
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.618",
11977
+ "version": "0.3.619",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.618",
11981
- "@north-light/identity": "0.3.618"
11980
+ "@north-light/api": "0.3.619",
11981
+ "@north-light/identity": "0.3.619"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.618",
11986
+ "version": "0.3.619",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.618",
11990
- "@north-light/identity": "0.3.618",
11991
- "@north-light/plugin": "0.3.618",
11989
+ "@north-light/api": "0.3.619",
11990
+ "@north-light/identity": "0.3.619",
11991
+ "@north-light/plugin": "0.3.619",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {