@north-light/cli 0.3.742 → 0.3.744
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/canvas/tree.js +4 -4
- package/dist/core/import/load/copy.d.ts +2 -0
- package/dist/core/import/load/copy.js +9 -9
- package/dist/core/import/load/prepare.d.ts +9 -1
- package/dist/core/import/load/prepare.js +11 -11
- package/dist/core/import/load/rollback.js +7 -6
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/import/load/verify.js +8 -8
- package/package.json +3 -3
- package/packages/crouter-api/dist/core/canvas/tree.js +3 -1
- package/packages/crouter-api/dist/core/import/load/copy.js +18 -1
- package/packages/crouter-api/dist/core/import/load/prepare.js +16 -3
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
package/dist/core/canvas/tree.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var O=Object.defineProperty;var i=(o,t)=>O(o,"name",{value:t,configurable:!0});import{openDb as r,withCanvasWrite as u}from"./db.js";import{getById as N,nodeObject as w}from"../graph/objects.js";import{recordWatch as
|
|
1
|
+
var O=Object.defineProperty;var i=(o,t)=>O(o,"name",{value:t,configurable:!0});import{openDb as r,withCanvasWrite as u}from"./db.js";import{getById as N,nodeObject as w}from"../graph/objects.js";import{recordWatch as I,unwatch as b,configFromJson as E,configToJson as T}from"../graph/watches.js";import{publish as D}from"../graph/events.js";import{DEFAULT_LISTEN as v}from"../graph/types.js";const R=["spawn","job-start","ask"],S="('spawn','job-start','ask')",j=[{threshold:3,delivery:"next-turn"}];function h(o){const t=o.find(n=>n.threshold<=7);return t!==void 0&&t.delivery!=="next-turn"}i(h,"wakesAtSeven");async function d(o,t,...n){const a=await o.prepareUncached(`SELECT wo.id AS from_id, oo.id AS to_id, ws.config_json, ws.created_at,
|
|
2
2
|
wo.listen_json, wn.status AS from_status, onode.status AS to_status
|
|
3
3
|
FROM watches w
|
|
4
4
|
JOIN objects wo ON wo.id = w.watcher AND wo.type = 'node'
|
|
@@ -7,13 +7,13 @@ var O=Object.defineProperty;var i=(o,t)=>O(o,"name",{value:t,configurable:!0});i
|
|
|
7
7
|
JOIN nodes wn ON wn.node_id = wo.id
|
|
8
8
|
JOIN nodes onode ON onode.node_id = oo.id
|
|
9
9
|
WHERE w.in_tree = 1 ${t}
|
|
10
|
-
ORDER BY ws.created_at, ws.seq`).all(...
|
|
10
|
+
ORDER BY ws.created_at, ws.seq`).all(...n),s=new Map;for(const e of a){const c=e.config_json,f=e.listen_json,_=c!=null?E(c):f!=null?E(f):v,p=`${e.from_id}\0${e.to_id}`,l=s.get(p);if(l){l.active||=h(_);continue}s.set(p,{from_id:e.from_id,to_id:e.to_id,active:h(_),created:e.created_at,from_status:e.from_status??null,to_status:e.to_status??null})}return[...s.values()]}i(d,"treeEdges");async function F(o=null){const t=o===null?null:[...o];return(t===null?await d(await r(),""):await d(await r(),"AND wo.id IN (SELECT unnest(?::text[])) AND oo.id IN (SELECT unnest(?::text[]))",t,t)).map(({from_id:a,to_id:s,active:e,created:c})=>({from_id:a,to_id:s,active:e,created:c}))}i(F,"rosterEdges");async function W(o,t,n=!0){await u(async a=>{const s=await w(a,o),e=await w(a,t);await I(a,s,e,"ask"),await x(o,t,n),await D(a,{event:"watched",object:e,actor:s,attrs:{}})})}i(W,"subscribe");async function M(o,t){await u(async n=>{const a=await w(n,o),s=await w(n,t);for(const e of R)await b(n,a,s,{startedBy:e})})}i(M,"unsubscribe");async function x(o,t,n){await u(async a=>{await a.prepareUncached(`UPDATE watch_subscriptions SET config_json = ?
|
|
11
11
|
WHERE started_by IN ${S}
|
|
12
|
-
AND watch IN (SELECT watch_id FROM watches WHERE watcher = ? AND object = ?)`).run(
|
|
12
|
+
AND watch IN (SELECT watch_id FROM watches WHERE watcher = ? AND object = ?)`).run(n?null:T(j),(await w(a,o)).id,(await w(a,t)).id)})}i(x,"setSubscriptionActive");async function $(o){const t=await r(),n=await N(t,o);if(n?.type!=="node")return[];let a=n.id;const s=new Set([a]);for(;;){const c=(await d(t,"AND oo.id = ?",a))[0]?.from_id;if(c===void 0||s.has(c))break;s.add(c),a=c}const e=(await t.prepareUncached(m).all(a,a)).map(c=>c.id);return[a,...e]}i($,"treeContaining");async function B(o){return(await d(await r(),"AND oo.id = ?",o)).map(t=>({node_id:t.from_id,active:t.active,created:t.created}))}i(B,"subscribersOf");async function H(o){return(await d(await r(),"AND wo.id = ?",o)).map(t=>({node_id:t.to_id,active:t.active,created:t.created}))}i(H,"subscriptionsOf");function A(o){return`WITH RECURSIVE walk(id) AS (
|
|
13
13
|
SELECT CAST(? AS text)
|
|
14
14
|
UNION
|
|
15
15
|
SELECT w.object FROM walk
|
|
16
16
|
JOIN watches w ON w.watcher = walk.id AND w.in_tree = 1
|
|
17
17
|
${o?`JOIN objects oo ON oo.id = w.object AND oo.type = 'node' AND oo.kind IS DISTINCT FROM 'human'
|
|
18
18
|
JOIN nodes onode ON onode.node_id = oo.id`:"JOIN nodes onode ON onode.node_id = w.object"}
|
|
19
|
-
) SELECT id FROM walk WHERE id != ?`}i(
|
|
19
|
+
) SELECT id FROM walk WHERE id != ?`}i(A,"subtreeSql");const P=A(!0),m=A(!1);async function Q(o){const t=await r(),n=await N(t,o);return n?.type!=="node"?[]:(await t.prepareUncached(m).all(n.id,n.id)).map(a=>a.id)}i(Q,"view");const y=new Set(["active","idle"]);async function V(o){return(await d(await r(),"AND wo.id = ?",o)).some(t=>t.active&&y.has(t.to_status??""))}i(V,"hasActiveLiveSubscription");async function q(o){return(await d(await r(),"AND oo.id = ?",o)).some(t=>t.active&&y.has(t.from_status??""))}i(q,"hasLiveSubscriber");export{m as SUBTREE_ALL_IDS_SQL,P as SUBTREE_IDS_SQL,V as hasActiveLiveSubscription,q as hasLiveSubscriber,F as rosterEdges,x as setSubscriptionActive,W as subscribe,B as subscribersOf,H as subscriptionsOf,$ as treeContaining,M as unsubscribe,Q as view};
|
|
@@ -25,3 +25,5 @@ export interface CopyInput {
|
|
|
25
25
|
export declare const copyOrder: (catalog: Catalog) => string[];
|
|
26
26
|
/** Must run inside `withCanvasWrite`. */
|
|
27
27
|
export declare function copyRows(input: CopyInput): Promise<CopyResult>;
|
|
28
|
+
/** Adds keys to a table's manifest row, creating it when the copy inserted no row of that table. */
|
|
29
|
+
export declare function appendManifest(tx: CanvasDb, runId: string, table: string, keys: string[][]): Promise<void>;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
SELECT s.${s(
|
|
3
|
-
FROM (SELECT * FROM ${
|
|
4
|
-
ins AS (INSERT INTO ${
|
|
1
|
+
var H=Object.defineProperty;var o=(n,t)=>H(n,"name",{value:t,configurable:!0});import{zstdCompressSync as x,zstdDecompressSync as j}from"node:zlib";import{BODIES_TABLE as C,COPIED_TABLES as W,KEY_MAPPED_TABLES as A}from"../bundle/layout.js";import{q as s,rowKey as v,topologicalOrder as q}from"./catalog.js";import{fillEnvironments as B}from"./prepare.js";import{ImportLaneError as b}from"./stage.js";const k=o((n,t)=>`${s(n)}.${s(t)}`,"sq"),h=o(n=>x(Buffer.from(JSON.stringify(n))),"encodeKeys"),M=o(n=>JSON.parse(j(n).toString("utf8")),"decodeKeys"),D=new Map;async function Z(n){const t=await n.prepare("SELECT run_id FROM import_runs WHERE state = 'committed' OR (state = 'failed' AND committed_at IS NOT NULL)").all(),i=new Set;for(const{run_id:E}of t){let c=D.get(E);if(c===void 0){const l=await n.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = 'nodes'").get(E);if(l===void 0)continue;c=new Set(M(l.inserted_keys).map(T=>T[0])),D.set(E,c)}for(const l of c)i.add(l)}return i}o(Z,"nodesAwaitingVerify");const G=o(n=>q(n,W),"copyOrder");async function Q(n){const{db:t,runId:i,schema:E,target:c,catalog:l,source:T}=n,p=o(e=>k(E,e),"S"),m=o(e=>k(c,e),"T"),f={inserted:{},mapped:{}},R=o(async(e,r)=>{f.inserted[e]=r.length,await t.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,e,h(r))},"manifest");for(const[e,r]of Object.entries(A)){const d=l.tables.get(e).columns.filter(_=>_!==r),S=await t.prepareUncached(`WITH src AS MATERIALIZED (
|
|
2
|
+
SELECT s.${s(r)}::text AS source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${d.map(_=>`s.${s(_)}`).join(", ")}
|
|
3
|
+
FROM (SELECT * FROM ${p(e)} ORDER BY ${s(r)}::bigint) s),
|
|
4
|
+
ins AS (INSERT INTO ${m(e)} (${s(r)}, ${d.map(s).join(", ")}) SELECT target_key, ${d.map(s).join(", ")} FROM src RETURNING 1),
|
|
5
5
|
km AS (INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) SELECT ?, ?, source_key, target_key::text FROM src RETURNING target_key)
|
|
6
|
-
SELECT target_key FROM km ORDER BY target_key::bigint`).all(
|
|
7
|
-
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(
|
|
8
|
-
ORDER BY ${
|
|
6
|
+
SELECT target_key FROM km ORDER BY target_key::bigint`).all(m(e),r,T.installId,e);await R(e,S.map(_=>[_.target_key]))}await t.prepareUncached(`UPDATE ${p("review_comments")} c SET created_seq = m.target_key::bigint FROM import_key_map m
|
|
7
|
+
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(T.installId);const g=G(l);await t.exec(`CREATE TABLE IF NOT EXISTS ${p("_filled")} (tbl text NOT NULL, k jsonb NOT NULL)`);const N=[];for(const e of g){if(e in A)continue;if(e==="profiles"){if(g.indexOf("identities")>g.indexOf("profiles"))throw new b("copy","bundle_invalid","identities must be copied before profiles");N.push(...await B(t,E,c,T,n.person))}const r=l.tables.get(e),u=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${p(e)}`).get()).n);if(u===0){f.inserted[e]=0;continue}const d=v(r),S=r.columns.filter(a=>!r.identity.includes(a)),_=r.identity.length>0?r.identity.map(a=>`s.${s(a)}`).join(", "):d.map(a=>`s.${s(a)}`).join(", ");let L=S.map(a=>`s.${s(a)}`),I="";if(e==="messages"){const a=`NOT EXISTS (SELECT 1 FROM ${m("messages")} t WHERE t.message_id = s.message_id)`,O=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${p("messages")} s WHERE ${a}`).get()).n);if(I=` WHERE ${a}`,O===0){f.inserted[e]=0,await R(e,[]);continue}const F=Number((await t.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(O)).seq);L=S.map(w=>w==="seq"?`${F-O} + row_number() OVER (ORDER BY s.seq)`:`s.${s(w)}`)}const U=d.map(a=>`${s(a)}::text`).join(", "),$=r.primaryKey.length===0;$&&(I=` WHERE NOT EXISTS (SELECT 1 FROM ${m(e)} t WHERE ${d.map(a=>`t.${s(a)} IS NOT DISTINCT FROM s.${s(a)}`).join(" AND ")})`);const y=await t.prepareUncached(`INSERT INTO ${m(e)} (${S.map(s).join(", ")}) SELECT ${L.join(", ")} FROM ${p(e)} s${I}
|
|
8
|
+
ORDER BY ${_}${$?"":` ON CONFLICT (${d.map(s).join(", ")}) DO NOTHING`} RETURNING ${U}`).all();if(e===C){const a=await t.prepareUncached(`SELECT s.hash FROM ${p(e)} s JOIN ${m(e)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();if(a.length>0)throw new b("copy","unique_conflict",`the target holds other text under body ${a[0].hash}; its boot repair has not rekeyed that row`,{table:e,hashes:a.map(O=>O.hash)})}e===C?f.inserted[e]=y.length:await R(e,y.map(a=>Object.values(a))),f.mapped[e]=u-y.length}for(const e of N)await t.prepare(`INSERT INTO ${p("_filled")} VALUES (?, ?::jsonb)`).run(e.table,JSON.stringify(e.key));for(const e of new Set(N.map(r=>r.table)))await P(t,i,e,N.filter(r=>r.table===e).map(r=>r.key));await t.prepareUncached(`DELETE FROM ${m("charge_totals")} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${p("charges")})`).run(),await t.prepareUncached(`INSERT INTO ${m("charge_totals")} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
9
9
|
SELECT month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, ''), COALESCE(SUM(usd), 0), COALESCE(SUM(billed_usd), 0)
|
|
10
|
-
FROM ${
|
|
11
|
-
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,
|
|
10
|
+
FROM ${m("charges")} WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${p("charges")})
|
|
11
|
+
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,r]of[["object",n.idMap.object],["grant",n.idMap.grant],["kind",n.idMap.kind]])for(const[u,d]of r)await t.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(i,e,u,d);for(const e of n.pathMap)await t.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, 'path', ?, ?) ON CONFLICT DO NOTHING").run(i,e.from,e.to);return await t.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(),i),f}o(Q,"copyRows");async function P(n,t,i,E){if(E.length===0)return;const c=await n.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(t,i);c===void 0?await n.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(t,i,h(E)):await n.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(h([...M(c.inserted_keys),...E]),t,i)}o(P,"appendManifest");export{P as appendManifest,G as copyOrder,Q as copyRows,M as decodeKeys,h as encodeKeys,Z as nodesAwaitingVerify};
|
|
@@ -36,9 +36,17 @@ export declare function dropExistingWatches(db: CanvasDb, schema: string, target
|
|
|
36
36
|
watches: number;
|
|
37
37
|
watch_subscriptions: number;
|
|
38
38
|
}>;
|
|
39
|
+
/** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
|
|
40
|
+
* row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
|
|
41
|
+
export declare function dropExistingIdempotencyKeys(db: CanvasDb, schema: string, target: string): Promise<number>;
|
|
42
|
+
/** The rows `fillEnvironments` created, as manifest keys per table, so rollback removes them and verify (which has no staged row for them) skips them. */
|
|
43
|
+
export interface FilledRow {
|
|
44
|
+
table: string;
|
|
45
|
+
key: string[];
|
|
46
|
+
}
|
|
39
47
|
/** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
|
|
40
48
|
* absent). Runs in the copy transaction: it writes target objects. */
|
|
41
|
-
export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<
|
|
49
|
+
export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<FilledRow[]>;
|
|
42
50
|
/** Staged edits that need nothing from the target but its key map: limits the directory or an operator wrote stay out, a hosted source's own
|
|
43
51
|
* machine environment is marked for the drop step, claims of the old runtime's lanes are cleared, and rows of the identity-keyed tables already in
|
|
44
52
|
* `import_key_map` are not staged again. Returns the rows removed per table. */
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var D=Object.defineProperty;var E=(
|
|
2
|
-
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:
|
|
1
|
+
var D=Object.defineProperty;var E=(t,s)=>D(t,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as v,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as H}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const d=E((t,s)=>`${l(t)}.${l(s)}`,"sq");async function K(t,s,o){if(o.length===0)return 0;const e=E(c=>d(s,c),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const p=E(async(c,r,n,$=!1)=>{const R=await t.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(c)} WHERE ${n} AND ${l(r)} IS NOT NULL`).all();for(const{value:f}of R){const T=$?g(f,o):S(o,f);T!==f&&(await t.prepareUncached(`UPDATE ${e(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${n}`).run(T,f),a+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),a}E(K,"rewritePaths");async function B(t,s,o,e,i){if(o.length===0)return 0;const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
|
|
2
|
+
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:n}of p){const $=M(i,n),R=await e.get($);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const f=H(R,r,T=>S(o,T));f!==null&&(await e.put($,f),c+=1),await t.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((f??R).length,r)}return c}E(B,"rewriteConversationHeaders");async function J(t,s){const o=d(s,"human_requests"),e=E(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
|
|
3
3
|
WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
|
|
4
4
|
WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
|
|
5
|
-
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await
|
|
6
|
-
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(J,"rewriteRequestPaths");function
|
|
7
|
-
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await
|
|
8
|
-
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}E(X,"renameClashingLegacyCharges");async function G(
|
|
9
|
-
CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await
|
|
5
|
+
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await t.prepareUncached(`UPDATE ${o} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
|
|
6
|
+
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(J,"rewriteRequestPaths");function g(t,s){const o=E(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(o):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,o(a)])):e,"walk");try{return JSON.stringify(o(JSON.parse(t)))}catch{return S(s,t)}}E(g,"rewriteJsonPaths");async function Y(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let c=0;for(const r of p){const n=await t.prepareUncached(`SELECT o.id FROM ${a("objects")} o JOIN ${a("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
|
|
7
|
+
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=n===void 0?void 0:await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,n.id);if($===void 0&&R===void 0)continue;const f=`${r.name}-${e}`;await t.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(f,r.id),n!==void 0&&await t.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(f,n.id),c+=1}return c}E(Y,"renameClashingProfiles");async function X(t,s,o,e){const i=await t.prepareUncached(`UPDATE ${d(s,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${d(o,"charges")} t
|
|
8
|
+
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}E(X,"renameClashingLegacyCharges");async function G(t,s,o){const e=`FROM ${d(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await t.prepareUncached(`DELETE FROM ${d(s,"watch_subscriptions")} u USING ${d(s,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${e})`).run(),a=await t.prepareUncached(`DELETE FROM ${d(s,"watches")} s WHERE EXISTS (SELECT 1 ${e})`).run();return{watches:Number(a.changes),watch_subscriptions:Number(i.changes)}}E(G,"dropExistingWatches");async function z(t,s,o){const e=await t.prepareUncached(`DELETE FROM ${d(s,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${d(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(e.changes)}E(z,"dropExistingIdempotencyKeys");async function Q(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=[],c=await t.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let n=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"){const $=await t.prepareUncached(`SELECT environment_id FROM ${d(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)n=$.environment_id;else{n=await U(t,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[n]},{table:"environments",key:[n]});for(const R of await t.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(n))p.push({table:"relations",key:[R.resource_type,R.resource_id,R.relation,R.subject_type,R.subject_id,R.subject_relation]})}}if(n===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await t.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(n,r.id)}return p}E(Q,"fillEnvironments");async function V(t,s,o,e){const i=E(c=>d(s,c),"S"),a={},p=E(async(c,r,...n)=>{const $=Number((await t.prepareUncached(r).run(...n)).changes);$>0&&(a[c]=(a[c]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await t.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await t.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[c,r]of Object.entries(v))await p(c,`DELETE FROM ${i(c)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,c);for(const c of o.tables.values())c.columns.includes("claimed_by")&&c.columns.includes("lease_expires_at")&&await t.prepareUncached(`UPDATE ${i(c.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}E(V,"pruneStaged");async function Z(t,s,o){const e=E(p=>d(s,p),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${d(o,"documents")} t WHERE t.object = d.object))`;await t.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
|
|
9
|
+
CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await t.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
|
|
10
10
|
COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
|
|
11
|
-
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await
|
|
12
|
-
FROM (SELECT * FROM ${
|
|
13
|
-
FROM (SELECT ctid AS row_id, * FROM ${
|
|
14
|
-
FROM ${
|
|
11
|
+
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await t.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await t.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(p=>({...p}))}E(Z,"takeRepoSyncedDocuments");const C={edges:["created_at"],relations:["created_at"]},b={charges:["payer","units","usd"]};async function ee(t,s,o,e,i,a,p){const c=E(n=>[...p.get(n)??[],...n==="profiles"?["environment_id"]:[],...C[n]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const n of i){const $=e.tables.get(n);if($===void 0||a.has(n)||$.primaryKey.length===0)continue;const R=$.primaryKey,f=R.some(u=>$.identity.includes(u)),T=R.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),y=f?"TRUE":R.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(n)??[]]);for(const u of e.uniqueKeys.filter(h=>h.table===n&&!h.columns.every(_=>I.has(_)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,_=u.columns.map(m=>`s.${l(m)} = t.${l(m)}`).join(" AND "),O=await t.prepareUncached(`SELECT ${u.columns.map(m=>`s.${l(m)}::text`).join(" || ',' || ")} AS value
|
|
12
|
+
FROM (SELECT * FROM ${d(s,n)}${h}) s JOIN (SELECT * FROM ${d(o,n)}${h}) t ON ${_} AND (${y}) LIMIT 10`).all();O.length>0&&r.push({table:n,key:u.name,values:O.map(m=>m.value)});const A=f?"TRUE":R.map(m=>`a.${l(m)} IS DISTINCT FROM b.${l(m)}`).join(" OR "),L=await t.prepareUncached(`SELECT DISTINCT ${u.columns.map(m=>`a.${l(m)}::text`).join(" || ',' || ")} AS value
|
|
13
|
+
FROM (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) b ON ${u.columns.map(m=>`a.${l(m)} = b.${l(m)}`).join(" AND ")} AND a.row_id < b.row_id AND (${A}) LIMIT 10`).all();L.length>0&&r.push({table:n,key:u.name,values:L.map(m=>m.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(n).includes(u)&&(b[n]?.includes(u)??!0));if(w.length>0&&!f){const u=w.map(_=>`s.${l(_)} IS DISTINCT FROM t.${l(_)}`).join(" OR "),h=await t.prepareUncached(`SELECT ${R.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
|
|
14
|
+
FROM ${d(s,n)} s JOIN ${d(o,n)} t ON ${T} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:n,key:"primary key payload",values:h.map(_=>_.value)})}}if(r.length>0){const n=r[0];throw new N("pre-check","unique_conflict",`${n.table} ${n.key} collides ${n.staged===!0?"within the bundle":"with the target"}: ${n.values.join(", ")}`,{collisions:r})}}E(ee,"precheck");export{z as dropExistingIdempotencyKeys,G as dropExistingWatches,Q as fillEnvironments,ee as precheck,V as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,Z as takeRepoSyncedDocuments};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND EXISTS (SELECT 1 FROM _rb
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
var A=Object.defineProperty;var b=(a,_)=>A(a,"name",{value:_,configurable:!0});import{openDb as k,withCanvasWrite as D}from"../../canvas/db.js";import{keyMatch as m,q as r,readCatalog as M,rowKey as u,topologicalOrder as h}from"./catalog.js";import{deleteOwnedBlobs as F,deleteRunPrefix as W}from"./blobs.js";import{decodeKeys as H}from"./copy.js";import{IMPORT_ROLLBACK_LOCK as $}from"../../graph/deletion.js";import{OBJECT_ID_COLUMNS as y}from"./rewrite.js";import{targetSchema as g}from"./stage.js";class N extends Error{static{b(this,"Refused")}}const v=new Set(["machine_credentials","machine_links"]);async function J(a,_){const E=await(await k()).prepare("SELECT source_install_id, source_kind, state, created_at, committed_at FROM import_runs WHERE run_id = ?").get(a);if(E===void 0)throw new Error(`no import run ${a}`);if(E.state!=="done"&&E.state!=="committed"&&E.state!=="failed")throw new Error(`import run ${a} is ${E.state}, not rollbackable`);const s={run_id:a,rolled_back:!1,dependents:{},deleted:{}},T={nodes:[],human_requests:[]};try{await D(async t=>{await t.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get($);const o=await g(t),f=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(o)).map(e=>e.table_name),d=await M(t,o,f);d.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const L=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(a);for(const{table_name:e,inserted_keys:i}of L){const n=H(i);(e==="nodes"||e==="human_requests")&&T[e].push(...n.map(c=>c[0]));for(let c=0;c<n.length;c+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(n.slice(c,c+5e3)))}E.committed_at!==null&&(await t.prepareUncached(`CREATE TEMP TABLE _fill ON COMMIT DROP AS SELECT o.id FROM ${r(o)}.objects o WHERE o.type = 'environment' AND o.kind = 'blaxel' AND o.created_at >= ? AND o.created_at <= ?
|
|
2
|
+
AND o.owner IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') AND NOT EXISTS (SELECT 1 FROM _rb x WHERE x.tbl = 'objects' AND x.k ->> 0 = o.id)`).run(E.created_at,E.committed_at),await t.exec("INSERT INTO _rb SELECT 'objects', jsonb_build_array(id) FROM _fill"),await t.exec(`INSERT INTO _rb SELECT 'environments', jsonb_build_array(e.object) FROM ${r(o)}.environments e WHERE e.object IN (SELECT id FROM _fill)`),await t.exec(`INSERT INTO _rb SELECT 'relations', jsonb_build_array(r.resource_type, r.resource_id, r.relation, r.subject_type, r.subject_id, r.subject_relation) FROM ${r(o)}.relations r WHERE r.resource_id IN (SELECT id FROM _fill)`));const p=new Set((await t.prepareUncached("SELECT DISTINCT tbl FROM _rb").all()).map(e=>e.tbl));await t.exec("ANALYZE _rb");for(const e of d.foreignKeys){const i=d.tables.get(e.parent),n=d.tables.get(e.table);if(e.table==="import_node_files"||v.has(e.table)||!p.has(e.parent)||i===void 0||n===void 0||e.parentColumns.join()!==i.primaryKey.join())continue;const c=p.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${m(n,u(n),"c","o.k")})`:"",l=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${r(o)}.${r(e.table)} c WHERE ${e.columns.map(w=>`c.${r(w)} IS NOT NULL`).join(" AND ")}
|
|
3
|
+
AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${m(n,e.columns,"c","p.k")}) ${c}`).get()).n);l>0&&(s.dependents[e.table]=(s.dependents[e.table]??0)+l)}for(const[e,i]of y){const n=d.tables.get(e);if(n===void 0||!n.columns.includes(i)||n.primaryKey.length===0)continue;const c=p.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${m(n,n.primaryKey,"c","o.k")})`:"",l=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${r(o)}.${r(e)} c WHERE c.${r(i)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${c}`).get()).n);l>0&&(s.dependents[`${e}.${i}`]=l)}const S=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(E.source_install_id,a,E.created_at)).n);S>0&&(s.dependents.import_runs=S);const O=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(a)).n);if(O>0&&(s.dependents.import_id_map=O),Object.keys(s.dependents).length>0)throw new N;const C=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${r(o)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
|
|
4
|
+
AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of h(d,[...p]).reverse()){const i=d.tables.get(e);if(i===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${r(o)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${m(i,u(i),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const n=await t.prepareUncached(`DELETE FROM ${r(o)}.${r(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${m(i,u(i),"t","k.k")})`).run();s.deleted[e]=n.changes}for(const e of C)await t.prepareUncached(`UPDATE ${r(o)}.documents d SET
|
|
5
|
+
heads_key = COALESCE((SELECT string_agg(r.rev_id, ',' ORDER BY r.rev_id) FROM ${r(o)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${r(o)}.revision_parents p WHERE p.parent = r.rev_id)), ''),
|
|
6
|
+
revision = COALESCE((SELECT max(r.number) FROM ${r(o)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${r(o)}.revision_parents p WHERE p.parent = r.rev_id)), 0)
|
|
7
|
+
WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(E.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(a),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(a),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),a),await I(t,E)})}catch(t){if(t instanceof N)return s;throw t}return await W(_,a),await F(_,T.nodes,T.human_requests),s.rolled_back=!0,s}b(J,"rollbackRun");async function I(a,_){if(_.source_kind!=="machine")return;const R=await a.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(_.source_install_id);R!==void 0&&await a.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),R.object)}b(I,"revokeFor");export{J as rollbackRun};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Q=Object.defineProperty;var m=(e,r)=>Q(e,"name",{value:r,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as A}from"../../canvas/person.js";import{insertImportedRevisions as Z}from"../../graph/documents.js";import{getById as x}from"../../graph/objects.js";import{bundleKeys as B,decodeRows as ee,rowKeys as L,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{appendManifest as N,copyRows as ne,decodeKeys as ie}from"./copy.js";import{pruneStaged as se,precheck as re,dropExistingIdempotencyKeys as oe,dropExistingWatches as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ce,rewriteConversationHeaders as ue,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Se}from"./bind.js";import{deleteBlobs as ve,deleteRunBlobs as Ee,deleteRunPrefix as Re,moveRunBlobs as Ie}from"./blobs.js";import{dropStubRows as Oe,findFleetGrant as Pe,grantMissing as je,mapProfileIds as ke,renameClashingRepos as Te,rewriteIds as Ce,rewritePerson as Me,scopeRepoIdentities as De}from"./rewrite.js";import{dropStaging as W,ImportLaneError as g,stage as Ae,stagingSchema as Be,targetSchema as Le}from"./stage.js";import{verifyRun as Ne}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as Ke}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{openImportGrants as Ge}from"./open-grants.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ye}from"../../events/emit.js";import{ClaimLostError as ze}from"../../../daemon/reconcilers/row-claim.js";const Qe=10*6e4,Ve=30*6e4,R=m(()=>new Date().toISOString(),"now"),K=m(async(e,r)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(r,e)},"setStep");async function Xe(e,r){const i=await e.get(B.source(r));if(i===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(i.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Xe,"readSource");async function Ze(e,r,i,a,n,d,p){const o=[];for(const t of L(i.run_id,"grants",a)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ee(c))}if(o.length===0)return;const w=o.map(t=>({sub:_e(t.sub,a.person,i.person,"grants.sub"),grantee:t.grantee}));await p(i.run_id);const f=[];for(const t of w)await Pe(r,n,d,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw je(f)}m(Ze,"ensureGrants");async function Ot(e,r,i={}){const a=i.blobs??await X(),n=await E(),d=Be(e.run_id);let p="start";const o=m(async t=>{p=t,await r.assertOwned(),await K(e.run_id,t),await i.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Xe(a,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Le(n),I=[...$e],h=await ae(n,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],k=i.fleetRuntime??process.env.CRTR_RUNTIME??null;await ge(n,c,t.person,e.person),await o("open-grants"),await Ze(a,n,e,t,c,k,i.openGrants??Ge),await o("publish-plugins");const H=await Ue(a,e.run_id),S=await A(e.person,()=>qe(H));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Qe)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await r.assertOwned(),await K(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await o("stage");const U=await Ae(n,e.run_id,t.counts,s=>L(e.run_id,s,t),s=>a.get(s));for(const[s,u]of Object.entries(U))l[s]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:n,schema:d,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[s,u]of Object.entries(await he(_)))b(l,s,u);for(const[s,u]of Object.entries(await be(_)))b(l,s,u);await o("rewrite-person"),await Me(_),await De(_),await o("prune");const F=await se(n,d,h,t),v=t.kind==="hosted"?We(t.pathPrefixes??[]):[];await o("rewrite-paths"),await le(n,d,v),await ue(n,d,v,a,e.run_id),await fe(n,d),await Se(_);const J=await ke(_);await ce(n,d,c,t.installId,e.person),await o("rewrite-ids");const T=await Ce(_,J);await o("drop");const G=await me(n,d,c),q=await Oe(_);for(const[s,u]of Object.entries({...F}))b(l,s,u);for(const[s,u]of Object.entries(q))b(l,s,u);for(const[s,u]of Object.entries(await we(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,s,u);await ye(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Te(_),await pe(n,d,c,t.installId);for(const[s,u]of Object.entries(await de(n,d,c)))b(l,s,u);b(l,"idempotency_keys",await oe(n,d,c)),await o("pre-check");const $=new Map([["messages",["seq"]],...te.map(s=>[s,["seq"]])]);await re(n,d,c,h,I,new Set,$),await o("blobs"),await Ie(n,d,c,e.person,a,e.run_id,f),await o("copy"),await A(e.person,()=>D(async s=>{await r.assertOwned({extendLeaseMs:Ve});const u=await ne({db:s,runId:e.run_id,schema:d,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await tt(s,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Ke(s,d,e.run_id,t);const M=await Je({db:s,blobs:a,runId:e.run_id,person:e.person,objectMap:T.object});for(const[Y,z]of Object.entries(M.inserted))u.inserted[Y]=z.length;return P.push(...M.unresolvedPlugins),await s.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...et(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),w=!0,await i.atStep?.("committed")}await o("verify");const y=await Ne(n,e.run_id,d,c,h,t.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=B.manifest(e.run_id);await a.put(O,await at(e.run_id)),await W(n,e.run_id);for(const l of He(e.run_id))await a.delete(l);await Ee(a,e.run_id),await D(async l=>{await Fe(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof ze)throw t;const c=xe(t,p);Ye({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await W(n,e.run_id).catch(()=>{}),w||await ve(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}m(Ot,"processRun");function xe(e,r){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:r,code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}m(xe,"failureOf");function b(e,r,i){(e[r]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=i}m(b,"addDropped");function et(e,r){for(const[i,a]of Object.entries(r.inserted))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[i,a]of Object.entries(r.mapped))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(et,"withInserted");async function tt(e,r,i){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(i.map(p=>p.rev_id)))).map(p=>p.rev_id)),n=i.filter(p=>!a.has(p.rev_id)),d=new Map;for(const p of i)d.set(p.document,[...d.get(p.document)??[],p]);for(const[p,o]of d){const w=await x(e,p);w!==null&&await Z(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await N(e,r,"revisions",n.map(p=>[p.rev_id])),await N(e,r,"revision_parents",n.flatMap(p=>p.parents.map(o=>[p.rev_id,o]))),n.length}m(tt,"arrive");async function at(e){const i=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return V(Buffer.from(i.map(a=>JSON.stringify({table:a.table_name,keys:ie(a.inserted_keys)})).join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`))}
|
|
3
|
+
`))}m(at,"manifestFile");export{Ve as COPY_LEASE_MS,Qe as GRANT_WAIT_MS,Ot as processRun};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var j=Object.defineProperty;var
|
|
2
|
-
JOIN ${o(e,t)} s ON s.${r(i)}::text = km.source_key`}else
|
|
1
|
+
var j=Object.defineProperty;var $=(n,N)=>j(n,"name",{value:N,configurable:!0});import{KEY_MAPPED_TABLES as v}from"../bundle/layout.js";import{keyMatch as h,q as r,rowKey as W}from"./catalog.js";import{archiveCutoffs as H,BODY_TYPES as J}from"../../events/run-event-chunks.js";import{MEMORY_READS_RETENTION_MS as x}from"../../canvas/memory-reads.js";import{PURGE_RETENTION_MS as B}from"../../storage/purge.js";import{decodeKeys as Y}from"./copy.js";const o=$((n,N)=>`${r(n)}.${r(N)}`,"sq"),P={messages:["seq"]},K=["claimed_by","lease_expires_at"],X={worktrees:["attempts","next_attempt_at","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json"]},q=10*6e4;function M(n,N,e,c,s,m=[]){if(e==="objects")return`${c}."id" IN (${s})`;if(m.includes(e))return"false";const a=[];e==="object_kinds"&&a.push(`${c}."owner" IN (${s})`);for(const E of n.foreignKeys){if(E.table!==e||!E.cascade||E.columns.length!==1)continue;const S=`${c}.${r(E.columns[0])}`;if(E.parent==="objects"){a.push(`${S} IN (${s})`);continue}const O=M(n,N,E.parent,"p",s,[...m,e]);O!=="false"&&a.push(`${S} IN (SELECT p.${r(E.parentColumns[0])} FROM ${o(N,E.parent)} p WHERE ${O})`)}return a.length===0?"false":`(${a.join(" OR ")})`}$(M,"removedWithPurgedObject");function I(n,N,e){const c=Date.now()+q,s=[];if(e==="run_events"){const{bodyCutoff:E,controlCutoff:S}=H(c);s.push(`(s.ts < '${S}' OR (s.ts < '${E}' AND s.type IN (${J.map(O=>`'${O}'`).join(", ")})))`)}e==="memory_reads"&&s.push(`s.at < '${new Date(c-x).toISOString()}'`);const m=`SELECT o.id FROM ${o(N,"objects")} o WHERE o.deleted_at IS NOT NULL AND (o.type = 'node' OR o.deleted_at < '${new Date(c-B).toISOString()}')`,a=M(n,N,e,"s",m);return a!=="false"&&s.push(a),s.length===0?"false":`(${s.join(" OR ")})`}$(I,"removedByMaintenance");async function oe(n,N,e,c,s,m){const a={},E={},S=await n.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(N);await n.exec(`CREATE TABLE IF NOT EXISTS ${r(e)}._filled (tbl text NOT NULL, k jsonb NOT NULL)`),await n.exec(`DROP TABLE IF EXISTS ${r(e)}._m; CREATE TABLE ${r(e)}._m (tbl text NOT NULL, k jsonb NOT NULL)`);for(const{table_name:t,inserted_keys:d}of S){const _=s.tables.get(t);if(_===void 0)continue;const u=Y(d);if(u.length===0)continue;await n.prepare(`DELETE FROM ${r(e)}._m WHERE tbl = ?`).run(t);for(let i=0;i<u.length;i+=5e3)await n.prepare(`INSERT INTO ${r(e)}._m SELECT ?, e FROM jsonb_array_elements(?::jsonb) e`).run(t,JSON.stringify(u.slice(i,i+5e3)));await n.exec(`ANALYZE ${r(e)}._m`);const T=[..._.identity,...P[t]??[],...K,...X[t]??[]].map(i=>`'${i.replace(/'/g,"''")}'`).join(", ")||"''",l=$(i=>`to_jsonb(${i}) - ARRAY[${T}]::text[]`,"strip"),p=W(_);let A;if(t in v){const i=v[t];A=`JOIN import_key_map km ON km.source_install_id = '${m.replace(/'/g,"''")}' AND km.table_name = '${t}' AND km.target_key = m.k ->> 0
|
|
2
|
+
JOIN ${o(e,t)} s ON s.${r(i)}::text = km.source_key`}else A=`JOIN ${o(e,t)} s ON ${p.map((i,w)=>`s.${r(i)}::text = m.k ->> ${w}`).join(" AND ")}`;const F=` AND NOT EXISTS (SELECT 1 FROM ${o(e,"_filled")} f WHERE f.tbl = '${t}' AND f.k = m.k)`+(t==="revisions"?` AND m.k ->> 0 NOT IN (SELECT rev_id FROM ${o(e,"_arr_revisions")})`:t==="revision_parents"?` AND NOT EXISTS (SELECT 1 FROM ${o(e,"_arr_parents")} a WHERE a.child = m.k ->> 0 AND a.parent = m.k ->> 1)`:""),k=`FROM ${o(e,"_m")} m LEFT JOIN ${o(c,t)} t ON ${h(_,p,"t","m.k")} ${A.replace("JOIN","LEFT JOIN")} WHERE m.tbl = '${t}'${F}`,U=`${k} AND ((t.${r(p[0])} IS NULL AND NOT (s.${r(p[0])} IS NOT NULL AND ${I(s,e,t)})) OR s.${r(p[0])} IS NULL OR (${l("t")}) <> (${l("s")}))`,D=await n.prepareUncached(`SELECT count(*) AS n, array_agg(k) FILTER (WHERE rn <= 10) AS keys FROM (SELECT m.k::text AS k, row_number() OVER () AS rn ${U}) d`).get(),C=Number(D.n);if(C>0&&(a[t]={count:C,keys:D.keys??[]}),I(s,e,t)!=="false"){const i=Number((await n.prepareUncached(`SELECT count(*) AS n ${k} AND t.${r(p[0])} IS NULL AND s.${r(p[0])} IS NOT NULL AND ${I(s,e,t)}`).get()).n);i>0&&(E[t]=i)}}for(const[t,d]of[["revisions",`FROM ${o(e,"_m")} m JOIN ${o(e,"_arr_revisions")} a ON a.rev_id = m.k ->> 0 LEFT JOIN revisions t ON t.rev_id = a.rev_id
|
|
3
3
|
WHERE m.tbl = 'revisions' AND (t.rev_id IS NULL OR t.document <> a.document OR t.body_hash <> a.body_hash OR t.rationale IS DISTINCT FROM a.rationale OR t.created_at <> a.created_at)`],["revision_parents",`FROM ${o(e,"_m")} m JOIN ${o(e,"_arr_parents")} a ON a.child = m.k ->> 0 AND a.parent = m.k ->> 1 LEFT JOIN revision_parents t ON t.child = a.child AND t.parent = a.parent
|
|
4
|
-
WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const
|
|
5
|
-
INSERT INTO ${
|
|
6
|
-
UNION ALL SELECT key, false FROM ${o(e,"_dropped")} WHERE tbl = 'objects') u GROUP BY key; ANALYZE ${
|
|
7
|
-
CROSS JOIN LATERAL (VALUES ${
|
|
8
|
-
WHERE m.tbl = ? GROUP BY v.col ORDER BY v.col`).all(t);for(const{col:
|
|
4
|
+
WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const _=Number((await n.prepareUncached(`SELECT count(*) AS n ${d}`).get()).n);_>0&&(a[`${t}.arrived`]={count:_,keys:[]})}const O={},R=o(e,"_ids");await n.exec(`DROP TABLE IF EXISTS ${R}; CREATE TABLE ${R} (key text PRIMARY KEY, mapped boolean NOT NULL);
|
|
5
|
+
INSERT INTO ${R} SELECT key, bool_or(mapped) FROM (SELECT source AS key, true AS mapped FROM ${o(e,"_idmap")} WHERE kind = 'object'
|
|
6
|
+
UNION ALL SELECT key, false FROM ${o(e,"_dropped")} WHERE tbl = 'objects') u GROUP BY key; ANALYZE ${R}`);let L=!1;for(const{table_name:t}of S){const d=s.tables.get(t);if(d===void 0||L||d.primaryKey.length===0)continue;const _=(await n.prepareUncached("SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND data_type = 'text'").all(c,t)).map(l=>l.column_name).filter(l=>!(d.primaryKey.includes(l)&&t==="objects"));if(_.length===0)continue;const u=_.map(l=>`('${l.replace(/'/g,"''")}', t.${r(l)})`).join(", "),T=await n.prepareUncached(`SELECT v.col AS col, count(*) AS n FROM ${o(e,"_m")} m JOIN ${o(c,t)} t ON ${h(d,d.primaryKey,"t","m.k")}
|
|
7
|
+
CROSS JOIN LATERAL (VALUES ${u}) v(col, val) JOIN ${R} i ON i.key = v.val${t==="messages"?" AND i.mapped":""}
|
|
8
|
+
WHERE m.tbl = ? GROUP BY v.col ORDER BY v.col`).all(t);for(const{col:l,n:p}of T)L=!0,a[`${t}.${l}`]={count:Number(p),keys:["holds a dropped object id"]}}O.no_dropped_id=!L;const b=S.find(t=>t.table_name==="revisions");let y=!0,f=0;if(b!==void 0){const t=`FROM ${o(e,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 WHERE m.tbl = 'revisions' AND NOT EXISTS (SELECT 1 FROM bodies b WHERE b.hash = r.body_hash)`;y=await n.prepare(`SELECT 1 AS lost ${t} AND EXISTS (SELECT 1 FROM ${o(e,"bodies")} s WHERE s.hash = r.body_hash) LIMIT 1`).get()===void 0,f=Number((await n.prepare(`SELECT count(*) AS n ${t} AND NOT EXISTS (SELECT 1 FROM ${o(e,"bodies")} s WHERE s.hash = r.body_hash)`).get()).n)}O.revision_bodies_readable=y,O.revision_bodies_canonical=b===void 0||await n.prepare(`SELECT 1 AS wrong FROM ${o(e,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 JOIN bodies b ON b.hash = r.body_hash
|
|
9
9
|
WHERE m.tbl = 'revisions' AND encode(sha256(convert_to(b.text, 'UTF8')), 'hex') <> b.hash LIMIT 1`).get()===void 0;const g=await n.prepare(`SELECT 1 AS found FROM (
|
|
10
10
|
SELECT month, payer, funding, COALESCE(sub, '') AS sub, grantee, COALESCE(provider, '') AS provider, COALESCE(SUM(usd), 0) AS usd, COALESCE(SUM(billed_usd), 0) AS billed
|
|
11
11
|
FROM charges WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${o(e,"charges")}) GROUP BY 1, 2, 3, 4, 5, 6) c
|
|
12
12
|
FULL JOIN charge_totals t ON t.month = c.month AND t.payer = c.payer AND t.funding = c.funding AND t.sub = c.sub AND t.grantee = c.grantee AND t.provider = c.provider
|
|
13
|
-
WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${o(e,"charges")}) AND (c.month IS NULL OR t.month IS NULL OR c.usd <> t.usd OR c.billed <> t.billed_usd) LIMIT 1`).get();return O.charge_totals_equal_recompute=g===void 0,{ok:Object.keys(a).length===0&&Object.values(O).every(Boolean),differences:a,...Object.keys(E).length>0?{archived:E}:{},...f>0?{source_missing_bodies:f}:{},invariants:O}}
|
|
13
|
+
WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${o(e,"charges")}) AND (c.month IS NULL OR t.month IS NULL OR c.usd <> t.usd OR c.billed <> t.billed_usd) LIMIT 1`).get();return O.charge_totals_equal_recompute=g===void 0,{ok:Object.keys(a).length===0&&Object.values(O).every(Boolean),differences:a,...Object.keys(E).length>0?{archived:E}:{},...f>0?{source_missing_bodies:f}:{},invariants:O}}$(oe,"verifyRun");export{oe as verifyRun};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.744",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.744",
|
|
162
|
+
"@north-light/plugin": "0.3.744",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -52,7 +52,9 @@ export async function rosterEdges(visible = null) {
|
|
|
52
52
|
const ids = visible === null ? null : [...visible];
|
|
53
53
|
const rows = ids === null
|
|
54
54
|
? await treeEdges(await openDb(), '')
|
|
55
|
-
|
|
55
|
+
// `IN (SELECT unnest(...))`, not `= ANY(...)`: the planner hashes the set instead of scanning the array per joined row
|
|
56
|
+
// (thousands of ids made `ANY` a linear filter: 5.6 s against 0.3 s on the fleet database).
|
|
57
|
+
: await treeEdges(await openDb(), 'AND wo.id IN (SELECT unnest(?::text[])) AND oo.id IN (SELECT unnest(?::text[]))', ids, ids);
|
|
56
58
|
return rows.map(({ from_id, to_id, active, created }) => ({ from_id, to_id, active, created }));
|
|
57
59
|
}
|
|
58
60
|
/** `subscriber` asks to watch `publisher` (an `ask` watch, in the tree). Re-running sets the
|
|
@@ -61,6 +61,9 @@ export async function copyRows(input) {
|
|
|
61
61
|
await db.prepareUncached(`UPDATE ${S('review_comments')} c SET created_seq = m.target_key::bigint FROM import_key_map m
|
|
62
62
|
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(source.installId);
|
|
63
63
|
const order = copyOrder(catalog);
|
|
64
|
+
// Rows the fill step creates have no staged row: kept in staging for verify, and appended to the manifest after the loop so rollback removes them.
|
|
65
|
+
await db.exec(`CREATE TABLE IF NOT EXISTS ${S('_filled')} (tbl text NOT NULL, k jsonb NOT NULL)`);
|
|
66
|
+
const filled = [];
|
|
64
67
|
for (const table of order) {
|
|
65
68
|
if (table in KEY_MAPPED_TABLES)
|
|
66
69
|
continue;
|
|
@@ -68,7 +71,7 @@ export async function copyRows(input) {
|
|
|
68
71
|
if (table === 'profiles') {
|
|
69
72
|
if (order.indexOf('identities') > order.indexOf('profiles'))
|
|
70
73
|
throw new ImportLaneError('copy', 'bundle_invalid', 'identities must be copied before profiles');
|
|
71
|
-
await fillEnvironments(db, schema, target, source, input.person);
|
|
74
|
+
filled.push(...await fillEnvironments(db, schema, target, source, input.person));
|
|
72
75
|
}
|
|
73
76
|
const info = catalog.tables.get(table);
|
|
74
77
|
const staged = Number((await db.prepareUncached(`SELECT count(*) AS n FROM ${S(table)}`).get()).n);
|
|
@@ -115,6 +118,10 @@ export async function copyRows(input) {
|
|
|
115
118
|
await manifest(table, inserted.map((row) => Object.values(row)));
|
|
116
119
|
result.mapped[table] = staged - inserted.length;
|
|
117
120
|
}
|
|
121
|
+
for (const f of filled)
|
|
122
|
+
await db.prepare(`INSERT INTO ${S('_filled')} VALUES (?, ?::jsonb)`).run(f.table, JSON.stringify(f.key));
|
|
123
|
+
for (const table of new Set(filled.map((f) => f.table)))
|
|
124
|
+
await appendManifest(db, runId, table, filled.filter((f) => f.table === table).map((f) => f.key));
|
|
118
125
|
// The rollup is recomputed from the copied charges for every (month, payer) the bundle held: an additive upsert would double on a rerun.
|
|
119
126
|
await db.prepareUncached(`DELETE FROM ${T('charge_totals')} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${S('charges')})`).run();
|
|
120
127
|
await db.prepareUncached(`INSERT INTO ${T('charge_totals')} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
@@ -130,3 +137,13 @@ export async function copyRows(input) {
|
|
|
130
137
|
await db.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(), runId);
|
|
131
138
|
return result;
|
|
132
139
|
}
|
|
140
|
+
/** Adds keys to a table's manifest row, creating it when the copy inserted no row of that table. */
|
|
141
|
+
export async function appendManifest(tx, runId, table, keys) {
|
|
142
|
+
if (keys.length === 0)
|
|
143
|
+
return;
|
|
144
|
+
const existing = await tx.prepare('SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?').get(runId, table);
|
|
145
|
+
if (existing === undefined)
|
|
146
|
+
await tx.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encodeKeys(keys));
|
|
147
|
+
else
|
|
148
|
+
await tx.prepare('UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?').run(encodeKeys([...decodeKeys(existing.inserted_keys), ...keys]), runId, table);
|
|
149
|
+
}
|
|
@@ -120,22 +120,35 @@ export async function dropExistingWatches(db, schema, target) {
|
|
|
120
120
|
const watches = await db.prepareUncached(`DELETE FROM ${sq(schema, 'watches')} s WHERE EXISTS (SELECT 1 ${same})`).run();
|
|
121
121
|
return { watches: Number(watches.changes), watch_subscriptions: Number(subs.changes) };
|
|
122
122
|
}
|
|
123
|
+
/** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
|
|
124
|
+
* row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
|
|
125
|
+
export async function dropExistingIdempotencyKeys(db, schema, target) {
|
|
126
|
+
const done = await db.prepareUncached(`DELETE FROM ${sq(schema, 'idempotency_keys')} s WHERE EXISTS (SELECT 1 FROM ${sq(target, 'idempotency_keys')} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();
|
|
127
|
+
return Number(done.changes);
|
|
128
|
+
}
|
|
123
129
|
/** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
|
|
124
130
|
* absent). Runs in the copy transaction: it writes target objects. */
|
|
125
131
|
export async function fillEnvironments(tx, schema, target, source, person) {
|
|
126
132
|
const S = (t) => sq(schema, t);
|
|
127
|
-
|
|
133
|
+
const filled = [];
|
|
128
134
|
const profiles = await tx.prepareUncached(`SELECT id, grantee FROM ${S('profiles')} WHERE environment_id IS NULL ORDER BY id`).all();
|
|
129
135
|
for (const profile of profiles) {
|
|
130
136
|
let environment = source.kind === 'machine' ? source.environmentObject ?? null : null;
|
|
131
137
|
if (source.kind === 'hosted') {
|
|
132
138
|
const existing = await tx.prepareUncached(`SELECT environment_id FROM ${sq(target, 'profiles')} WHERE id = ?`).get(profile.id);
|
|
133
|
-
|
|
139
|
+
if (existing?.environment_id != null)
|
|
140
|
+
environment = existing.environment_id;
|
|
141
|
+
else {
|
|
142
|
+
environment = await createProfileBlaxelEnvironment(tx, { profileId: profile.id, grantee: profile.grantee ?? 'app:terminal', person });
|
|
143
|
+
filled.push({ table: 'objects', key: [environment] }, { table: 'environments', key: [environment] });
|
|
144
|
+
for (const r of await tx.prepareUncached('SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?').all(environment)) {
|
|
145
|
+
filled.push({ table: 'relations', key: [r['resource_type'], r['resource_id'], r['relation'], r['subject_type'], r['subject_id'], r['subject_relation']] });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
134
148
|
}
|
|
135
149
|
if (environment === null)
|
|
136
150
|
throw new ImportLaneError('fill', 'bundle_invalid', `profile ${profile.id} has no environment and the source names none`);
|
|
137
151
|
await tx.prepareUncached(`UPDATE ${S('profiles')} SET environment_id = ? WHERE id = ?`).run(environment, profile.id);
|
|
138
|
-
filled += 1;
|
|
139
152
|
}
|
|
140
153
|
return filled;
|
|
141
154
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.744",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.744",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.744",
|
|
31
|
+
"@north-light/identity": "0.3.744"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.744",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.744",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.744",
|
|
32
|
+
"@north-light/plugin": "0.3.744",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.744",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.744",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.744",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.744",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.744",
|
|
11927
|
+
"@north-light/identity": "0.3.744"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.744",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.744",
|
|
11936
|
+
"@north-light/identity": "0.3.744",
|
|
11937
|
+
"@north-light/plugin": "0.3.744",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|