@north-light/api 0.3.741 → 0.3.743

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.
@@ -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>;
@@ -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
+ }
@@ -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<number>;
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. */
@@ -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
- let filled = 0;
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
- environment = existing?.environment_id ?? await createProfileBlaxelEnvironment(tx, { profileId: profile.id, grantee: profile.grantee ?? 'app:terminal', person });
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
  import { type HealthDTO, type StartupPhaseDTO } from '../api/index.js';
2
2
  import type { DumpResult } from '../core/import/export/dump.js';
3
- /** Env keys that must NEVER reach the daemon process. Restarting crtrd is
3
+ /** Non-`CRTR_*` env keys that must NEVER reach the daemon process. Restarting crtrd is
4
4
  * overwhelmingly done from inside an agent node's own bash tool (`crtr sys
5
5
  * daemon stop && start`), which inherits that node's FULL env — its identity
6
6
  * (`CRTR_NODE_ID`/`CRTR_KIND`/…, the `nodeEnv()` shape in `core/runtime/
@@ -15,10 +15,10 @@ import type { DumpResult } from '../core/import/export/dump.js';
15
15
  * relaunch it ever attempts, for its whole lifetime — the 2026-07-06 diagnosis
16
16
  * root cause behind 19 nodes killed with "failed to relaunch and is now dead". */
17
17
  export declare const DAEMON_ENV_STRIP_KEYS: readonly string[];
18
- /** A copy of `process.env` with every `DAEMON_ENV_STRIP_KEYS` entry removed.
19
- * Deliberate global config the user actually wants the daemon to see —
20
- * `CRTR_HOME`, `CRTR_SUBTREE`, `CRTR_LOG`, `CRTR_DEBUG`, etc. — passes through
21
- * untouched; only the node-identity/engine-poisoning surface is stripped. */
18
+ /** Whether a daemon process inherits this env name. */
19
+ export declare function daemonKeepsEnv(key: string): boolean;
20
+ /** A copy of `process.env` for a daemon process: the ordinary host env and the operator `CRTR_*` settings pass; every
21
+ * per-execution `CRTR_*` name and every `DAEMON_ENV_STRIP_KEYS` entry is dropped. */
22
22
  export declare function sanitizedDaemonEnv(): NodeJS.ProcessEnv;
23
23
  /** A crtrd declares its owning canvas in argv, so ownership is an exact match
24
24
  * on this process's canvas home. Untagged daemons retain their own
@@ -23,7 +23,7 @@ import { envNoDaemonAutostart } from '../shared/env.js';
23
23
  import { waitForDaemonAvailability } from '../api/index.js';
24
24
  import { localClient } from '../api/node-transport.js';
25
25
  // Daemon env sanitization
26
- /** Env keys that must NEVER reach the daemon process. Restarting crtrd is
26
+ /** Non-`CRTR_*` env keys that must NEVER reach the daemon process. Restarting crtrd is
27
27
  * overwhelmingly done from inside an agent node's own bash tool (`crtr sys
28
28
  * daemon stop && start`), which inherits that node's FULL env — its identity
29
29
  * (`CRTR_NODE_ID`/`CRTR_KIND`/…, the `nodeEnv()` shape in `core/runtime/
@@ -38,19 +38,6 @@ import { localClient } from '../api/node-transport.js';
38
38
  * relaunch it ever attempts, for its whole lifetime — the 2026-07-06 diagnosis
39
39
  * root cause behind 19 nodes killed with "failed to relaunch and is now dead". */
40
40
  export const DAEMON_ENV_STRIP_KEYS = [
41
- // Node identity (nodeEnv() shape) — meaningless for a process supervising
42
- // many nodes rather than being one.
43
- 'CRTR_NODE_ID',
44
- 'CRTR_KIND',
45
- 'CRTR_MODE',
46
- 'CRTR_LIFECYCLE',
47
- 'CRTR_NODE_CWD',
48
- 'CRTR_CONTEXT_DIR',
49
- 'CRTR_CYCLES',
50
- 'CRTR_PROFILE_ID',
51
- 'CRTR_PARENT_NODE_ID',
52
- // Recursion-guard flag — only meaningful inside a pi engine process.
53
- 'CRTR_FRONT_DOOR',
54
41
  // Ambient tmux identity of whatever shell first autostarted the daemon. The
55
42
  // daemon is a headless supervisor with no pane of its own, but `spawnNode`
56
43
  // reads `currentTmux()` for a --root's foreground viewer placement; a stale
@@ -63,22 +50,46 @@ export const DAEMON_ENV_STRIP_KEYS = [
63
50
  // unaffected — the tmux CLI reaches the server via its default socket.
64
51
  'TMUX',
65
52
  'TMUX_PANE',
66
- // Engine-resolution seams NOT overridden per child launch — the proven and
67
- // suspected poison vectors.
68
- 'CRTR_BROKER_ENGINE',
69
- 'CRTR_PI_BINARY',
70
53
  // Generic Node.js env poisoning (a stray dev/debug flag from the restarting
71
54
  // shell).
72
55
  'NODE_OPTIONS',
73
56
  ];
74
- /** A copy of `process.env` with every `DAEMON_ENV_STRIP_KEYS` entry removed.
75
- * Deliberate global config the user actually wants the daemon to see —
76
- * `CRTR_HOME`, `CRTR_SUBTREE`, `CRTR_LOG`, `CRTR_DEBUG`, etc. — passes through
77
- * untouched; only the node-identity/engine-poisoning surface is stripped. */
57
+ /** The `CRTR_*` names the daemon keeps: deployment and operator settings for the whole canvas. Every other `CRTR_*` name is
58
+ * dropped, because crtr sets the rest on one node, cron, job or broker (its identity, its relay socket, its tokens, its
59
+ * model), and a daemon started from that shell would otherwise act as that one execution. `CRTR_API_SOCKET` reaching the
60
+ * daemon made a Mac's self-update restart refuse with `no_local_daemon`. `CRTR_BROKER_ENGINE` and `CRTR_PI_BINARY` stay
61
+ * out on purpose: an inherited engine override broke every broker relaunch on 2026-07-06. A new operator setting the
62
+ * daemon must read is added here; a new per-execution name needs nothing. */
63
+ const DAEMON_CRTR_ENV_NAMES = new Set([
64
+ 'CRTR_HOME', 'CRTR_RUNTIME_HOME', 'CRTR_PIDFILE', 'CRTR_RUNTIME', 'CRTR_INSTALL_ID',
65
+ 'CRTR_LOG', 'CRTR_DEBUG', 'CRTR_DEBUG_PID_LIVENESS', 'CRTR_TIMING', 'CRTR_TIMING_PROC',
66
+ 'CRTR_NO_DAEMON_AUTOSTART', 'CRTR_NO_AUTO_UPDATE', 'CRTR_NO_AUTO_INIT', 'CRTR_NO_EXPORTS', 'CRTR_LAYOUT_REFUSE',
67
+ 'CRTR_POSTGRES_HOME', 'CRTR_DATABASE_URL', 'CRTR_DATABASE_SCHEMA', 'CRTR_DATABASE_POOL_MAX', 'CRTR_SCHEMA_DATABASE_URL',
68
+ 'CRTR_DOCUMENT_PORT', 'CRTR_LAUNCHER_SOCKET', 'CRTR_API_ADDRESS', 'CRTR_DIRECTORY_URL', 'CRTR_PUBLIC_API_URL',
69
+ 'CRTR_CANVAS_URL', 'CRTR_CANVAS_CLIENT_ID', 'CRTR_CANVAS_JWK_FILE', 'CRTR_SECRETS_KEY', 'CRTR_IMPORT_SERVICE_TOKEN',
70
+ 'CRTR_PACKAGES_TOKEN', 'CRTR_FEEDBACK_ENDPOINT', 'CRTR_FEEDBACK_TOKEN', 'CRTR_SUPPORT_REPO',
71
+ 'CRTR_BRANDED_HOST', 'CRTR_CODESIGN_IDENTITY', 'CRTR_PLUGIN_REVALIDATE_TTL_MS', 'CRTR_IMPORT_BLOB_WORKERS',
72
+ 'CRTR_MAX_LIVE_BROKERS', 'CRTR_WARN_LIVE_BROKERS', 'CRTR_BROKER_RSS_CAP_MB', 'CRTR_UNATTENDED_PARK_MS', 'CRTR_WARM_POOL',
73
+ 'CRTR_STREAM_WATCHDOG_MS', 'CRTR_CONVERSATION_COMMIT_DEADLINE_MS', 'CRTR_NAME_MODEL', 'CRTR_MODEL_PROVIDER',
74
+ 'CRTR_BROKER_SIGNAL_LONG_PROOF',
75
+ ]);
76
+ /** Operator setting families the daemon keeps whole. `CRTR_TEST_` and `CRTR_FAULT_` are test-lane settings a lane exports for the daemon it starts. */
77
+ const DAEMON_CRTR_ENV_PREFIXES = ['CRTR_DB_', 'CRTR_BOOT_', 'CRTR_R2_', 'CRTR_LEDGER_', 'CRTR_BASH_', 'CRTR_WATCHER_', 'CRTR_RECAP_', 'CRTR_MODEL_AUTH_', 'CRTR_TEST_', 'CRTR_FAULT_'];
78
+ /** Whether a daemon process inherits this env name. */
79
+ export function daemonKeepsEnv(key) {
80
+ if (DAEMON_ENV_STRIP_KEYS.includes(key))
81
+ return false;
82
+ if (!key.startsWith('CRTR_'))
83
+ return true;
84
+ return DAEMON_CRTR_ENV_NAMES.has(key) || DAEMON_CRTR_ENV_PREFIXES.some((prefix) => key.startsWith(prefix));
85
+ }
86
+ /** A copy of `process.env` for a daemon process: the ordinary host env and the operator `CRTR_*` settings pass; every
87
+ * per-execution `CRTR_*` name and every `DAEMON_ENV_STRIP_KEYS` entry is dropped. */
78
88
  export function sanitizedDaemonEnv() {
79
- const env = { ...process.env };
80
- for (const key of DAEMON_ENV_STRIP_KEYS)
81
- delete env[key];
89
+ const env = {};
90
+ for (const [key, value] of Object.entries(process.env))
91
+ if (daemonKeepsEnv(key))
92
+ env[key] = value;
82
93
  return env;
83
94
  }
84
95
  // Entry point resolution
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.741",
3
+ "version": "0.3.743",
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",