@north-light/cli 0.3.756 → 0.3.757

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/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.756",
3
+ "version": "0.3.757",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.756",
9
+ "version": "0.3.757",
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.756",
32
- "@north-light/plugin": "0.3.756",
31
+ "@north-light/identity": "0.3.757",
32
+ "@north-light/plugin": "0.3.757",
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.756",
11905
+ "version": "0.3.757",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.756",
11910
+ "version": "0.3.757",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.756",
11915
+ "version": "0.3.757",
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.756",
11923
+ "version": "0.3.757",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.756",
11927
- "@north-light/identity": "0.3.756"
11926
+ "@north-light/api": "0.3.757",
11927
+ "@north-light/identity": "0.3.757"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.756",
11932
+ "version": "0.3.757",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.756",
11936
- "@north-light/identity": "0.3.756",
11937
- "@north-light/plugin": "0.3.756",
11935
+ "@north-light/api": "0.3.757",
11936
+ "@north-light/identity": "0.3.757",
11937
+ "@north-light/plugin": "0.3.757",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -1,12 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
- import { DatabaseSync } from 'node:sqlite';
5
4
  import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, readdir, readlink, rename, rm, symlink, writeFile } from 'node:fs/promises';
6
5
  import { existsSync } from 'node:fs';
7
6
  import { homedir, hostname, userInfo } from 'node:os';
8
7
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
- import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { fileURLToPath } from 'node:url';
10
9
  import { ENTRY_NAMES, GENERATION_ID, MANIFEST_KEYS, MANIFEST_SCHEMA, PACKAGE_NAME, contained, isKnownPackageName, isSealed, publishedMarkerPath, runtimeHome, sortInventory, validateManifestShape } from '../bin/runtime-generation-manifest.mjs';
11
10
  import { patchPiTreeRootOrdering } from './patch-pi-tree-root-ordering.mjs';
12
11
  import { smokeValidate } from './runtime-smoke.mjs';
@@ -165,13 +164,6 @@ async function removeStage(root) {
165
164
  * currently serving generation selected. The daemon-side migration guard is a
166
165
  * second line of defense for generations installed by older installers. */
167
166
  async function assertCanvasSchemaCompatible(stage) {
168
- const migrationsUrl = pathToFileURL(join(stage, 'dist', 'core', 'canvas', 'migrations.js')).href;
169
- const candidate = await import(migrationsUrl);
170
- const supported = candidate.MIGRATIONS?.length;
171
- if (!Number.isSafeInteger(supported) || supported < 0) {
172
- throw new Error('candidate runtime does not expose a valid canvas migration version');
173
- }
174
-
175
167
  const root = process.env.CRTR_HOME || (process.platform === 'linux' ? '/' : join(homedir(), '.crouter'));
176
168
  const runtime = join(root, 'runtime');
177
169
  // A machine (runtime/machine.json, written by the import) runs no canvas database: its control plane is the cloud's, and the cluster
@@ -181,27 +173,6 @@ async function assertCanvasSchemaCompatible(stage) {
181
173
  await assertPostgresSchemaCompatible(stage, runtime);
182
174
  return;
183
175
  }
184
-
185
- // No Postgres cluster yet: the canvas is still the SQLite file the next daemon boot imports.
186
- const dbPath = join(runtime, 'canvas.db');
187
- try {
188
- await lstat(dbPath);
189
- } catch (error) {
190
- if (error?.code === 'ENOENT') return; // no live database yet
191
- throw error;
192
- }
193
- const db = new DatabaseSync(dbPath, { readOnly: true });
194
- try {
195
- const { user_version: current } = db.prepare('PRAGMA user_version').get();
196
- if (current > supported) {
197
- throw new Error(
198
- `refusing to select runtime with canvas schema ${supported}: ` +
199
- `the live database is already at version ${current}; install a descendant build instead`,
200
- );
201
- }
202
- } finally {
203
- db.close();
204
- }
205
176
  }
206
177
 
207
178
  /** Refuse a candidate whose version is below `canvas_meta.schema_min_reader` (absent: `schema_version`) in the live Postgres
@@ -1,46 +0,0 @@
1
- import { DatabaseSync } from 'node:sqlite';
2
- import pg from 'pg';
3
- export declare const IMPORT_MARK_KEY = "imported_from_sqlite";
4
- /** Written by `crtr sys db export-sqlite`; the Postgres data is stale against the exported canvas.db from then on. */
5
- export declare const EXPORT_MARK_KEY = "exported_to_sqlite";
6
- /** Every canvas table, in dependency order (a table follows every table its foreign keys name). The import and the
7
- * rollback export both copy exactly this list. */
8
- export declare const TABLE_ORDER: readonly ["objects", "documents", "revisions", "revision_parents", "jobs", "identities", "custom_objects", "context_sessions", "peer_stubs", "object_kinds", "watches", "watch_subscriptions", "exposures", "rules", "edges", "unresolved_links", "nodes", "focuses", "canvas_meta", "runtime_state", "warm_pool", "sessions", "executions", "worktrees", "node_faults", "node_tokens", "node_outcome_deliveries", "deleted_isolated_nodes", "create_requests", "waits", "messages", "message_sequence", "message_causes", "deliveries", "structured_requests", "daemon_actions", "human_requests", "human_action_deliveries", "review_comments", "review_comment_events", "run_events", "idempotency_keys", "grants", "memory_reads", "app_users", "uploads", "upload_uses", "shares", "audit_rows", "provider_approvals", "crons", "cron_runs", "peer_outbox", "peer_locations", "peer_ingested", "peer_ingested_destinations"];
9
- /** Columns holding `objects.rowid` in SQLite and `objects.id` in Postgres. */
10
- export declare const OBJECT_COLUMNS: Record<string, readonly string[]>;
11
- /** `optional`: the column may be left out of an INSERT (nullable, or it has a default or is an identity). */
12
- export interface PgColumn {
13
- name: string;
14
- type: string;
15
- identity: boolean;
16
- optional: boolean;
17
- }
18
- export interface ImportTableStat {
19
- table: string;
20
- rows: number;
21
- ms: number;
22
- }
23
- export interface ImportResult {
24
- tables: ImportTableStat[];
25
- verifyMs: number;
26
- totalMs: number;
27
- /** Per `table.column`, the NUL characters replaced with U+FFFD so jsonb would accept the value. */
28
- nulReplaced: Record<string, number>;
29
- }
30
- type Log = (message: string) => void;
31
- export declare function quote(identifier: string): string;
32
- export declare function pgColumns(client: pg.Client): Promise<Map<string, PgColumn[]>>;
33
- /** Copy an already-migrated SQLite database into the connected Postgres database, in one transaction. */
34
- export declare function copySqliteToPostgres(sqlite: DatabaseSync, client: pg.Client, options?: {
35
- log?: Log;
36
- }): Promise<ImportResult>;
37
- /** canvas.db → canvas.db.imported, with its -wal/-shm. An existing .imported (an earlier import, then a rollback export) is set aside, never overwritten. */
38
- export declare function renameImportedDatabase(path?: string): void;
39
- /**
40
- * Daemon boot: import `canvas.db` into the database at `url` if there is one. Holds the on-disk migration lock for
41
- * the whole import so `manage.ts` does not reap a daemon mid-copy. Re-entry: with the mark present and canvas.db
42
- * still there (a crash between commit and rename) the rename is finished and nothing is copied.
43
- * Returns null when there was nothing to do.
44
- */
45
- export declare function importSqliteCanvasIfPresent(url: string, log?: Log): Promise<ImportResult | null>;
46
- export {};
@@ -1,19 +0,0 @@
1
- var X=Object.defineProperty;var p=(s,t)=>X(s,"name",{value:t,configurable:!0});import{DatabaseSync as z}from"node:sqlite";import{createHash as Z,randomBytes as ee}from"node:crypto";import{existsSync as L,mkdirSync as te,renameSync as H}from"node:fs";import{dirname as oe}from"node:path";import se from"pg";import{withExclusiveDirectoryLockAsync as re}from"../exclusive-lock.js";import{DAEMON_STARTUP_WINDOW_MS as ne}from"../../daemon/startup-policy.js";import{migrate as ae}from"./migrations.js";import{readLegacyPrivacy as ie}from"../graph/types.js";import{LEGACY_LOCAL_PERSON as ce}from"./legacy-person.js";import{REBUILD_ALL_TOTALS as ue}from"../ledger/totals.js";import{canvasDbPath as U,onDiskMigrationLockPath as de}from"./paths.js";import{canvasSearchPathOptions as pe}from"./schema-version.js";const k="imported_from_sqlite",B="exported_to_sqlite",M=1e4,N=["objects","documents","revisions","revision_parents","jobs","identities","custom_objects","context_sessions","peer_stubs","object_kinds","watches","watch_subscriptions","exposures","rules","edges","unresolved_links","nodes","focuses","canvas_meta","runtime_state","warm_pool","sessions","executions","worktrees","node_faults","node_tokens","node_outcome_deliveries","deleted_isolated_nodes","create_requests","waits","messages","message_sequence","message_causes","deliveries","structured_requests","daemon_actions","human_requests","human_action_deliveries","review_comments","review_comment_events","run_events","idempotency_keys","grants","memory_reads","app_users","uploads","upload_uses","shares","audit_rows","provider_approvals","crons","cron_runs","peer_outbox","peer_locations","peer_ingested","peer_ingested_destinations"],me=new Set(["sqlite_sequence","sqlite_stat1","sqlite_stat4","reviews","usage","grantee_usage","provider_receipts"]),Ee={objects:["owner"],documents:["object"],revisions:["document","author"],jobs:["object"],identities:["object"],custom_objects:["object"],context_sessions:["node"],peer_stubs:["object"],object_kinds:["owner"],watches:["watcher","object","link_app"],exposures:["node","object"],rules:["object","owner"],edges:["src","dst"],unresolved_links:["src"]},W=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated"]),fe={canvas_meta:"key",message_sequence:"id"};function G(){return ee(16).toString("hex")}p(G,"newId");function f(s){return`"${s.replace(/"/g,'""')}"`}p(f,"quote");function we(s){switch(s){case"bigint":return"bigint[]";case"double precision":return"float8[]";case"bytea":return"bytea[]";case"text":case"jsonb":return"text[]";default:throw new Error(`import: no array type for Postgres column type ${s}`)}}p(we,"arrayType");async function le(s){const t=await s.query(`SELECT c.relname AS tbl, a.attname AS col, format_type(a.atttypid, a.atttypmod) AS type, a.attidentity <> '' AS identity, (NOT a.attnotnull OR a.atthasdef OR a.attidentity <> '') AS optional
2
- FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
3
- WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind = 'r' AND a.attnum > 0 AND NOT a.attisdropped
4
- ORDER BY c.relname, a.attnum`),e=new Map;for(const a of t.rows){const n=e.get(a.tbl)??[];n.push({name:a.col,type:a.type,identity:a.identity,optional:a.optional}),e.set(a.tbl,n)}return e}p(le,"pgColumns");const _e="\uFFFD";function he(s){if(!s.includes("\\u0000"))return{text:s,replaced:0};let t;try{t=JSON.parse(s)}catch{return{text:s,replaced:0}}let e=0;const a=p(d=>{const i=d.split("\0");return e+=i.length-1,i.join(_e)},"clean"),n=p(d=>typeof d=="string"?a(d):Array.isArray(d)?d.map(n):d!==null&&typeof d=="object"?Object.fromEntries(Object.entries(d).map(([i,_])=>[a(i),n(_)])):d,"walk"),c=n(t);return e===0?{text:s,replaced:e}:{text:JSON.stringify(c),replaced:e}}p(he,"scrubNul");async function ye(s,t,e,a,n,c,d){for(let i=0;i<a.length;i++)for(const _ of e){const o=n[c.indexOf(_)][i];if(o!=null){await s.query("SAVEPOINT import_probe");try{await s.query("SELECT $1::jsonb",[o]),await s.query("RELEASE SAVEPOINT import_probe")}catch(u){return await s.query("ROLLBACK TO SAVEPOINT import_probe"),new Error(`import: ${t}.${_.name} at ${d(a[i])} is not a value jsonb accepts: ${u.message}`,{cause:u})}}}}p(ye,"describeJsonbFailure");function v(s,t,e,a,n){if(n==null)return null;const c=s.get(Number(n));if(c===void 0)throw new Error(`import: ${e}.${a} references ${t} rowid ${String(n)}, which does not exist`);return c}p(v,"lookup");async function $e(s,t,e,a,n,c){const d=s.prepare(`PRAGMA table_info(${f(e)})`).all(),i=new Set(d.map(r=>r.name)),_=p(r=>r==="seq"||r==="watch_id"||r==="subscription_id","minted"),o=a.filter(r=>i.has(r.name)||_(r.name)||!r.optional),w=!s.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(e).sql.toUpperCase().includes("WITHOUT ROWID"),$=new Set(Ee[e]??[]),y=[];for(const r of o)if(r.name==="seq"&&!i.has("seq")){if(!w)throw new Error(`import: ${e} needs seq from rowid but has none`);y.push("rowid AS seq")}else if(r.name==="watch_id"||r.name==="subscription_id")y.push("NULL AS "+f(r.name));else if(i.has(r.name))y.push(f(r.name));else throw new Error(`import: SQLite table ${e} has no column ${r.name}`);w&&y.push("rowid AS _rowid");const h=e==="canvas_meta"?` WHERE key NOT IN (${[...W].map(r=>`'${r}'`).join(",")})`:"",b=s.prepare(`SELECT ${y.join(", ")} FROM ${f(e)}${h}${w?" ORDER BY rowid":""}`),S=o.map(r=>f(r.name)),R=o.map((r,m)=>`$${m+1}::${we(r.type)}`),O=o.map((r,m)=>`c${m}`),A=o.map((r,m)=>r.type==="jsonb"?`c${m}::jsonb`:`c${m}`);let j=`INSERT INTO ${f(e)} (${S.join(", ")}) SELECT ${A.join(", ")} FROM unnest(${R.join(", ")}) AS u(${O.join(", ")})`;const C=fe[e];if(C!==void 0){const r=o.filter(m=>m.name!==C).map(m=>`${f(m.name)} = EXCLUDED.${f(m.name)}`);j+=` ON CONFLICT (${f(C)}) DO UPDATE SET ${r.join(", ")}`}const D=e==="objects",x=o.filter(r=>r.type==="jsonb"),I=w?"_rowid":o[0].name,J=p(r=>`${w?"rowid":I} ${String(r[I])}`,"key");let P=0,g=[];const F=p(async()=>{if(g.length===0)return;const r=o.map(()=>new Array(g.length));if(g.forEach((m,T)=>{o.forEach((E,Q)=>{let l=m[E.name];if(e==="objects"&&E.name==="privacy"?l=ie(l):E.name==="watch_id"||E.name==="subscription_id"?l=G():e==="revision_parents"&&(E.name==="child"||E.name==="parent")?l=v(n.revisions,"revision",e,E.name,l):e==="watch_subscriptions"&&E.name==="watch"?l=v(n.watches,"watch",e,E.name,l):$.has(E.name)&&(l=D?null:v(n.objects,"object",e,E.name,l)),E.type==="bytea"&&l instanceof Uint8Array&&!Buffer.isBuffer(l)&&(l=Buffer.from(l.buffer,l.byteOffset,l.byteLength)),E.type==="jsonb"&&typeof l=="string"){const q=he(l);q.replaced>0&&(l=q.text,c.set(`${e}.${E.name}`,(c.get(`${e}.${E.name}`)??0)+q.replaced))}r[Q][T]=l??null}),e==="watches"&&n.watches.set(Number(m._rowid),r[o.findIndex(E=>E.name==="watch_id")][T])}),x.length===0)await t.query(j,r);else{await t.query("SAVEPOINT import_batch");try{await t.query(j,r)}catch(m){throw await t.query("ROLLBACK TO SAVEPOINT import_batch"),await ye(t,e,x,g,r,o,J)??m}await t.query("RELEASE SAVEPOINT import_batch")}P+=g.length,g=[]},"flush");for(const r of b.iterate())e==="objects"&&n.objects.set(Number(r._rowid),r.id),e==="revisions"&&n.revisions.set(Number(r._rowid),r.rev_id),g.push(r),g.length>=M&&await F();if(await F(),D){const r=s.prepare("SELECT id, owner FROM objects WHERE owner IS NOT NULL").all();for(let m=0;m<r.length;m+=M){const T=r.slice(m,m+M);await t.query("UPDATE objects o SET owner = v.owner FROM unnest($1::text[], $2::text[]) AS v(id, owner) WHERE o.id = v.id",[T.map(E=>E.id),T.map(E=>v(n.objects,"object","objects","owner",E.owner))])}}return P}p($e,"copyTable");async function Se(s,t){for(const[e,a]of t)for(const n of a)n.identity&&await s.query(`SELECT setval(pg_get_serial_sequence($1, $2), COALESCE((SELECT max(${f(n.name)}) FROM ${f(e)}), 1), (SELECT max(${f(n.name)}) IS NOT NULL FROM ${f(e)}))`,[f(e),n.name])}p(Se,"advanceIdentities");function Y(s,t,e=""){return Number(s.prepare(`SELECT count(*) AS n FROM ${f(t)}${e}`).get().n)}p(Y,"sqliteCount");async function ge(s,t,e){const a=[];for(const o of N){if(o==="canvas_meta")continue;const u=Y(s,o),w=Number((await t.query(`SELECT count(*) AS n FROM ${f(o)}`)).rows[0].n);u!==w&&a.push(`${o}: SQLite ${u} rows, Postgres ${w}`)}for(const o of s.prepare(`SELECT key, value FROM canvas_meta WHERE key NOT IN (${[...W].map(u=>`'${u}'`).join(",")})`).all())(await t.query("SELECT value FROM canvas_meta WHERE key = $1",[o.key])).rows[0]?.value!==o.value&&a.push(`canvas_meta ${o.key}: value differs`);const n=p(o=>{const u=Z("sha256");for(const w of o)u.update(w).update(`
5
- `);return u.digest("hex")},"hash"),c=s.prepare("SELECT id FROM objects ORDER BY rowid").all().map(o=>o.id),d=(await t.query("SELECT id FROM objects ORDER BY seq")).rows.map(o=>o.id);n(c)!==n(d)&&a.push("objects: ids in insertion order differ");const i=s.prepare("SELECT o.id AS id, p.id AS owner FROM objects o JOIN objects p ON p.rowid = o.owner ORDER BY o.rowid").all(),_=(await t.query("SELECT id, owner FROM objects WHERE owner IS NOT NULL ORDER BY seq")).rows;n(i.map(o=>`${o.id}>${o.owner}`))!==n(_.map(o=>`${o.id}>${o.owner}`))&&a.push("objects: owner links differ");for(const[o,u]of[["run_events","body_json"],["messages","body_json"],["deliveries","last_failure_json"]]){const w=Number(s.prepare(`SELECT COALESCE(sum(length(CAST(${f(u)} AS TEXT))), 0) AS n FROM ${f(o)}`).get().n),$=e.get(o).find(b=>b.name===u).type,y=$==="jsonb"?`${f(u)}::text`:f(u);if($==="jsonb")continue;const h=Number((await t.query(`SELECT COALESCE(sum(length(${y})), 0)::bigint AS n FROM ${f(o)}`)).rows[0].n);w!==h&&a.push(`${o}.${u}: total length SQLite ${w}, Postgres ${h}`)}if(a.length>0)throw new Error(`SQLite \u2192 Postgres import verification failed (rolled back; canvas.db untouched):
6
- ${a.join(`
7
- `)}`)}p(ge,"verify");async function be(s,t){const e=s.prepare("SELECT grantee, month, payer, source, served_model, input_tokens, output_tokens, cached_tokens, usd_equivalent FROM usage").all();if(e.length===0)return 0;const n=(await t.query("SELECT value FROM canvas_meta WHERE key = 'person_id'")).rows[0]?.value??ce,c=p((o,u=String)=>e.map(w=>w[o]===null?null:u(w[o])),"column"),d=await t.query(`INSERT INTO charges (id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, provider)
8
- SELECT 'legacy:' || u.grantee || ':' || u.month || ':' || u.payer || ':' || u.source || ':' || u.served_model,
9
- NULL, u.month || '-01T00:00:00.000Z', u.month,
10
- CASE WHEN u.source = 'model' THEN 'model' ELSE 'tool' END,
11
- CASE WHEN u.source = 'model' THEN u.served_model ELSE substr(u.source, 10) END,
12
- CASE WHEN u.source = 'model' THEN jsonb_build_object('input', u.input_tokens, 'output', u.output_tokens, 'cache_read', u.cached_tokens, 'cache_write', 0) END,
13
- u.usd_equivalent,
14
- CASE WHEN u.payer = 'app' THEN u.grantee ELSE $1::text END,
15
- CASE WHEN u.payer = 'app' THEN 'endpoint' WHEN u.source = 'model' THEN 'legacy' ELSE 'bill' END,
16
- $1::text, u.grantee,
17
- CASE WHEN u.source = 'model' THEN NULL ELSE 'app:' || substr(u.source, 10) END
18
- FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::bigint[], $8::bigint[], $9::bigint[], $10::float8[])
19
- AS u(grantee, month, payer, source, served_model, input_tokens, output_tokens, cached_tokens, usd_equivalent)`,[n,c("grantee"),c("month"),c("payer"),c("source"),c("served_model"),c("input_tokens"),c("output_tokens"),c("cached_tokens"),c("usd_equivalent",Number)]);for(const o of ue)await t.query(o);const i=(await t.query("SELECT count(*)::int AS n, COALESCE(SUM(usd), 0)::float8 AS usd FROM charges WHERE id LIKE 'legacy:%'")).rows[0],_=e.reduce((o,u)=>o+Number(u.usd_equivalent??0),0);if(d.rowCount!==e.length||i.n!==e.length||Math.abs(i.usd-_)>1e-4)throw new Error(`import: the usage \u2192 charges copy does not match (${e.length} usage rows, ${d.rowCount} charges inserted, ${i.n} legacy charges; usd ${_} vs ${i.usd})`);return e.length}p(be,"importLegacyUsage");async function Re(s,t,e={}){const a=e.log??(()=>{}),n=Date.now(),c=await le(t),d=s.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(h=>h.name),i=d.filter(h=>!me.has(h)&&!N.includes(h));if(i.length>0)throw new Error(`import: SQLite tables with no copy rule: ${i.join(", ")}`);const _=N.filter(h=>!c.has(h));if(_.length>0)throw new Error(`import: Postgres tables missing from the schema: ${_.join(", ")}`);const o=d.includes("reviews")?Y(s,"reviews"):0;if(o>0)throw new Error(`import: the legacy reviews table still holds ${o} rows after the SQLite migration chain`);const u={objects:new Map,revisions:new Map,watches:new Map},w=[],$=new Map;let y=0;await t.query("BEGIN");try{await t.query("ALTER TABLE nodes DISABLE TRIGGER USER"),await t.query("ALTER TABLE deliveries DISABLE TRIGGER USER");for(const S of N){const R=Date.now(),O=await $e(s,t,S,c.get(S),u,$),A=Date.now()-R;w.push({table:S,rows:O,ms:A}),a(`import ${S}: ${O} rows in ${A} ms`)}await t.query("ALTER TABLE nodes ENABLE TRIGGER USER"),await t.query("ALTER TABLE deliveries ENABLE TRIGGER USER"),await Se(t,c);const h=await be(s,t);h>0&&a(`import usage: ${h} rows into charges`);const b=Date.now();await ge(s,t,c),y=Date.now()-b,a(`import verify: ${y} ms`),await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2)",[k,JSON.stringify({at:new Date().toISOString(),rows:w.reduce((S,R)=>S+R.rows,0)})]),await t.query("COMMIT")}catch(h){throw await t.query("ROLLBACK").catch(()=>{}),h}return $.size>0&&a(`import: replaced NUL (\\u0000) with U+FFFD in jsonb values: ${[...$].map(([h,b])=>`${h} ${b}`).join(", ")}`),{tables:w,verifyMs:y,totalMs:Date.now()-n,nulReplaced:Object.fromEntries($)}}p(Re,"copySqliteToPostgres");const K=["","-wal","-shm"];function V(s=U()){if(L(`${s}.imported`)){const t=`${s}.imported.${Date.now()}`;for(const e of K)L(`${s}.imported${e}`)&&H(`${s}.imported${e}`,`${t}${e}`)}for(const t of K)L(`${s}${t}`)&&H(`${s}${t}`,`${s}.imported${t}`)}p(V,"renameImportedDatabase");async function Pe(s,t=()=>{}){const e=U();if(!L(e))return null;const a=de();return te(oe(a),{recursive:!0,mode:448}),re(a,async()=>{if(!L(e))return null;const n=new se.Client({connectionString:s,application_name:`crtr-import-${process.pid}`,options:pe()});await n.connect();try{const c=await n.query("SELECT key FROM canvas_meta WHERE key = ANY($1)",[[k,B]]),d=new Set(c.rows.map(o=>o.key));if(d.has(k)){if(d.has(B))throw new Error(`${e} was written by \`crtr sys db export-sqlite\` and the Postgres database predates it; importing would drop the exported writes. Stop the daemon and delete the Postgres cluster (runtime/pg/data) to import ${e} afresh, or move ${e} aside to keep using Postgres.`);return V(e),t(`import: finished the rename of ${e} (already imported)`),null}const i=new z(e);let _;try{i.exec("PRAGMA busy_timeout = 5000;"),i.exec("PRAGMA foreign_keys = ON;"),ae(i),_=await Re(i,n,{log:t})}finally{i.close()}return V(e),t(`import: ${_.tables.reduce((o,u)=>o+u.rows,0)} rows in ${_.totalMs} ms; canvas.db renamed to canvas.db.imported`),_}finally{await n.end().catch(()=>{})}},{timeoutMs:ne,timeoutError:p(()=>new Error(`timed out waiting for the canvas import lock: ${a}`),"timeoutError")})}p(Pe,"importSqliteCanvasIfPresent");export{B as EXPORT_MARK_KEY,k as IMPORT_MARK_KEY,Ee as OBJECT_COLUMNS,N as TABLE_ORDER,Re as copySqliteToPostgres,Pe as importSqliteCanvasIfPresent,le as pgColumns,f as quote,V as renameImportedDatabase};
@@ -1,16 +0,0 @@
1
- import { DatabaseSync } from 'node:sqlite';
2
- export declare const MIGRATIONS: ReadonlyArray<(db: DatabaseSync) => void>;
3
- /** Bring `db` up to the latest schema version. Reads `user_version`, runs each
4
- * pending migration in order, and bumps `user_version` after each so the work
5
- * is gated and idempotent: re-running is a no-op once `user_version` reaches
6
- * `MIGRATIONS.length`. Forward-only.
7
- *
8
- * ATOMIC AND RESTARTABLE: each step AND its `user_version` bump run inside one
9
- * `BEGIN IMMEDIATE`/`COMMIT` (SQLite journals `user_version` with the
10
- * transaction, so a rollback restores it too). An interrupted or failing step
11
- * therefore leaves the db exactly at the previous version with none of its
12
- * writes committed — a half-applied step can never wedge every later open. The
13
- * write lock also serializes concurrent openers; the version is re-read after
14
- * acquiring it so a step another process just applied is skipped rather than
15
- * re-run. */
16
- export declare function migrate(db: DatabaseSync): void;