@north-light/api 0.3.728 → 0.3.730

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.
@@ -88,6 +88,7 @@ export async function beginExecution(nodeId, input) {
88
88
  if (superseded.changes > 0)
89
89
  await clearPendingParkIn(db, nodeId);
90
90
  await revokeNodeTokens(db, 'node_id', nodeId, at);
91
+ await db.prepare('UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL').run(nodeId);
91
92
  const executionId = randomUUID();
92
93
  const attempt = input.attempt ?? Number((await db.prepare('SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?').get(nodeId)).next);
93
94
  await db.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)")
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 32;
4
+ export declare const CANVAS_SCHEMA_VERSION = 33;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -6,7 +6,7 @@
6
6
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
7
7
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
8
8
  * one below the live database's `schema_min_reader`. */
9
- export const CANVAS_SCHEMA_VERSION = 32;
9
+ export const CANVAS_SCHEMA_VERSION = 33;
10
10
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
11
11
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
12
12
  * it is put in a `search_path` connection option. */
@@ -41,6 +41,7 @@ import { clearFinalReportIfMatches, getFinalReport, getNode, updateNode } from '
41
41
  import { subscribersOf } from '../canvas/tree.js';
42
42
  import { InputError } from '../io.js';
43
43
  import { transition } from './lifecycle.js';
44
+ import { assertCheckoutNotRemoved } from './revive.js';
44
45
  import { noticeChangedWhileDone } from './ledger.js';
45
46
  async function currentFinalReport(nodeId) {
46
47
  return await getFinalReport(nodeId);
@@ -123,6 +124,10 @@ async function isManagerOf(callerNodeId, nodeId) {
123
124
  * Writing lifecycle first leaves a failed latch CAS with the canonical-final
124
125
  * pointer intact. Both writes finish before either delivery channel begins. */
125
126
  export async function commitReopenResident(nodeId, expectedFinalReport, callerNodeId) {
127
+ // A node whose managed checkout was removed can never run again: refuse before any reopen write.
128
+ const before = await getNode(nodeId);
129
+ if (before !== null)
130
+ assertCheckoutNotRemoved(nodeId, before);
126
131
  const finalReport = await currentFinalReport(nodeId);
127
132
  if (!(await isManagerOf(callerNodeId, nodeId)))
128
133
  await updateNode(nodeId, { lifecycle: 'resident' });
@@ -111,7 +111,8 @@ export declare function assertRecordedCwdExists(nodeId: string, meta: NodeMeta):
111
111
  blaxelEnvironment: string | null;
112
112
  remoteMachine: boolean;
113
113
  }>;
114
- /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
114
+ /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them; its cwd now names the shared repository
115
+ * root, so a launch would edit the base checkout. Refuse on any host, before a caller changes state. */
115
116
  export declare function assertCheckoutNotRemoved(nodeId: string, meta: NodeMeta): void;
116
117
  /** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
117
118
  export declare function runNodeStartHooks(nodeId: string, meta: NodeMeta, isBirth: boolean): Promise<void>;
@@ -228,6 +228,10 @@ async function decideReviveAsCaller(nodeId, opts, wakeParked) {
228
228
  if (meta.final_report !== null) {
229
229
  throw new Error(`reviveNode: refusing to revive ${nodeId} — its finalization latch is set (final_report=${meta.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);
230
230
  }
231
+ // A removed managed checkout refuses every start, before the start checks so its reason is the one recorded. An attach that only
232
+ // looks at a parked node starts nothing; cleanup completes only after the engine exits, so no live broker is refused.
233
+ if (wakeParked || !(meta.lifecycle === 'resident' && isParked(meta)))
234
+ await refuseRemovedCheckout(nodeId, meta);
231
235
  assertProfileActive(meta.profile_id);
232
236
  // An unsandboxed machine runs terminal agents only: refuse before any lifecycle hook or other prelaunch executable runs as the app.
233
237
  assertGranteeRunsHere(meta.grantee);
@@ -368,7 +372,8 @@ export async function assertRecordedCwdExists(nodeId, meta) {
368
372
  }
369
373
  return { blaxelEnvironment, remoteMachine };
370
374
  }
371
- /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
375
+ /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them; its cwd now names the shared repository
376
+ * root, so a launch would edit the base checkout. Refuse on any host, before a caller changes state. */
372
377
  export function assertCheckoutNotRemoved(nodeId, meta) {
373
378
  const worktree = meta.managed_worktree;
374
379
  if (worktree?.state !== 'closed' || worktree.cleanup !== 'complete')
@@ -379,6 +384,21 @@ export function assertCheckoutNotRemoved(nodeId, meta) {
379
384
  next: `Start a new node in ${worktree.repo_root}.`,
380
385
  });
381
386
  }
387
+ /** Every start path goes through reviveNode, so this is where a removed checkout is refused. A wake that has no caller to report
388
+ * to (a tick reopen of a parked resident, a stranded or idle-released launch) leaves the row live; it is settled dead with the
389
+ * reason as its outcome, which `crtr node inspect show` prints, so the tick does not select it again. */
390
+ async function refuseRemovedCheckout(nodeId, meta) {
391
+ try {
392
+ assertCheckoutNotRemoved(nodeId, meta);
393
+ }
394
+ catch (error) {
395
+ if (meta.status === 'active' || meta.status === 'idle') {
396
+ await transition(nodeId, 'crash', { reason: 'launch_failed', outcome: { detail: { schema: 'crtr.node-outcome-detail/v1', message: error.message } } });
397
+ await clearFrozen(nodeId);
398
+ }
399
+ throw error;
400
+ }
401
+ }
382
402
  /** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
383
403
  export async function runNodeStartHooks(nodeId, meta, isBirth) {
384
404
  const lifecycleHooks = discoverLifecycleHookRegistry(meta.cwd, meta.profile_id).plans.get('node:start') ?? [];
@@ -1,8 +1,19 @@
1
+ /** A launch that has not reached `running` in this long never will: its row no longer keeps the node's sandbox. */
2
+ export declare const STALE_LAUNCH_MS: number;
1
3
  /** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
2
4
  * those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
3
5
  export declare function deleteNodeSandboxes(nodeIds: readonly string[]): Promise<string[]>;
4
6
  /** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
5
- * (its fires run there). Called after each of those ends; a failure is left to the sandbox's idle expiry. A parked node is not ended:
6
- * wake mail reopens it in the same sandbox. The check and the DELETE run holding the node row's lock, which `beginExecution` also
7
- * takes, so no new execution can start in the sandbox between them. */
7
+ * (its fires run there). Called after each of those ends; a failure is left to the retention pass. A parked node is not ended:
8
+ * wake mail reopens it in the same sandbox. A launch stuck in `launching` past {@link STALE_LAUNCH_MS} does not hold the sandbox.
9
+ * The check and the DELETE run holding the node row's lock, which `beginExecution` also takes, so no new execution can start in
10
+ * the sandbox between them. */
8
11
  export declare function deleteSandboxOfEndedNode(nodeId: string): void;
12
+ /** Delete the sandbox of every finished, canceled, dead or parked node quiet for `quietMs`, keeping its rows; app runs included.
13
+ * `quiet` decides the activity test ({@link lastActivityMs} reads disk too); `held` excludes nodes retention must not touch.
14
+ * Each node is marked `sandbox_deleted_at` so later passes skip it until a new execution clears the mark. Returns the deleted count. */
15
+ export declare function deleteQuietNodeSandboxes(opts: {
16
+ quiet: (nodeId: string) => Promise<boolean>;
17
+ held: (nodeId: string) => Promise<boolean>;
18
+ now?: number;
19
+ }): Promise<number>;
@@ -3,6 +3,15 @@
3
3
  // on the Blaxel runner deletes the sandbox). Every path that deletes node rows calls this first.
4
4
  import { afterCommit, openDb, withCanvasWrite } from '../../canvas/db.js';
5
5
  import { emitEvent } from '../../events/emit.js';
6
+ /** A launch that has not reached `running` in this long never will: its row no longer keeps the node's sandbox. */
7
+ export const STALE_LAUNCH_MS = 60 * 60_000;
8
+ /** SQL true when node `n` has an execution that still holds its sandbox: a running one, or a launch younger than {@link STALE_LAUNCH_MS}.
9
+ * Binds one parameter, the stale-launch cutoff as an ISO time. */
10
+ const OPEN_EXECUTION = `EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id
11
+ AND (x.state = 'running' OR (x.state = 'launching' AND x.started_at > ?)))`;
12
+ function staleLaunchCutoff(now = Date.now()) {
13
+ return new Date(now - STALE_LAUNCH_MS).toISOString();
14
+ }
6
15
  /** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
7
16
  * those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
8
17
  export async function deleteNodeSandboxes(nodeIds) {
@@ -23,18 +32,57 @@ export async function deleteNodeSandboxes(nodeIds) {
23
32
  return failed;
24
33
  }
25
34
  /** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
26
- * (its fires run there). Called after each of those ends; a failure is left to the sandbox's idle expiry. A parked node is not ended:
27
- * wake mail reopens it in the same sandbox. The check and the DELETE run holding the node row's lock, which `beginExecution` also
28
- * takes, so no new execution can start in the sandbox between them. */
35
+ * (its fires run there). Called after each of those ends; a failure is left to the retention pass. A parked node is not ended:
36
+ * wake mail reopens it in the same sandbox. A launch stuck in `launching` past {@link STALE_LAUNCH_MS} does not hold the sandbox.
37
+ * The check and the DELETE run holding the node row's lock, which `beginExecution` also takes, so no new execution can start in
38
+ * the sandbox between them. */
29
39
  export function deleteSandboxOfEndedNode(nodeId) {
30
40
  afterCommit(() => void withCanvasWrite(async (db) => {
31
41
  const ended = await db.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
32
42
  AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
33
43
  AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
34
- AND NOT EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited')
44
+ AND NOT ${OPEN_EXECUTION}
35
45
  AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
36
- FOR UPDATE OF n`).get(nodeId);
37
- if (ended !== undefined)
38
- await (await import('./index.js')).runnerForExecution('blaxel').delete(nodeId);
46
+ FOR UPDATE OF n`).get(nodeId, staleLaunchCutoff());
47
+ if (ended === undefined)
48
+ return;
49
+ await (await import('./index.js')).runnerForExecution('blaxel').delete(nodeId);
50
+ await db.prepare('UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?').run(new Date().toISOString(), nodeId);
39
51
  }).catch((error) => { emitEvent({ level: 'error', event: 'canvas.node_sandbox.delete_failed', node_id: nodeId, error }); }));
40
52
  }
53
+ /** Delete the sandbox of every finished, canceled, dead or parked node quiet for `quietMs`, keeping its rows; app runs included.
54
+ * `quiet` decides the activity test ({@link lastActivityMs} reads disk too); `held` excludes nodes retention must not touch.
55
+ * Each node is marked `sandbox_deleted_at` so later passes skip it until a new execution clears the mark. Returns the deleted count. */
56
+ export async function deleteQuietNodeSandboxes(opts) {
57
+ const cutoff = staleLaunchCutoff(opts.now);
58
+ const candidates = await (await openDb()).prepare(`SELECT n.node_id FROM nodes n WHERE n.status IN ('done', 'canceled', 'dead')
59
+ AND n.sandbox_deleted_at IS NULL
60
+ AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
61
+ AND NOT ${OPEN_EXECUTION}
62
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)`).all(cutoff);
63
+ let deleted = 0;
64
+ for (const { node_id } of candidates) {
65
+ if (!await opts.quiet(node_id) || await opts.held(node_id))
66
+ continue;
67
+ try {
68
+ const done = await withCanvasWrite(async (db) => {
69
+ // Re-check under the node lock `beginExecution` takes, so no execution starts in the sandbox while it is deleted.
70
+ const still = await db.prepare(`SELECT 1 AS ok FROM nodes n WHERE n.node_id = ? AND n.status IN ('done', 'canceled', 'dead')
71
+ AND n.sandbox_deleted_at IS NULL AND NOT ${OPEN_EXECUTION}
72
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
73
+ FOR UPDATE OF n`).get(node_id, cutoff);
74
+ if (still === undefined)
75
+ return false;
76
+ await (await import('./index.js')).runnerForExecution('blaxel').delete(node_id);
77
+ await db.prepare('UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?').run(new Date().toISOString(), node_id);
78
+ return true;
79
+ });
80
+ if (done)
81
+ deleted++;
82
+ }
83
+ catch (error) {
84
+ emitEvent({ level: 'error', event: 'canvas.node_sandbox.delete_failed', node_id, error });
85
+ }
86
+ }
87
+ return deleted;
88
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.728",
3
+ "version": "0.3.730",
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",