@north-light/cli 0.3.669 → 0.3.671

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.
Files changed (86) hide show
  1. package/dist/api/client.js +1 -1
  2. package/dist/api/contract.d.ts +1 -1
  3. package/dist/api/contract.js +1 -1
  4. package/dist/api/dto/bash-jobs.d.ts +2 -0
  5. package/dist/api/dto/execution-start.d.ts +7 -0
  6. package/dist/clients/attach/viewer.js +1 -1
  7. package/dist/commands/node/bash.js +3 -3
  8. package/dist/core/bash-job-supervisor.js +3 -3
  9. package/dist/core/canvas/canvas.d.ts +10 -1
  10. package/dist/core/canvas/canvas.js +18 -18
  11. package/dist/core/canvas/schema-pg/022-create-request-lease.sql +5 -0
  12. package/dist/core/canvas/schema-pg/023-machine-calls-job-stop.sql +7 -0
  13. package/dist/core/canvas/schema-version.d.ts +1 -1
  14. package/dist/core/canvas/schema-version.js +1 -1
  15. package/dist/core/grants/sync.js +1 -1
  16. package/dist/core/runtime/broker/bash-job-launch.d.ts +4 -0
  17. package/dist/core/runtime/broker/bash-job-launch.js +1 -1
  18. package/dist/core/runtime/broker/boot-state.d.ts +8 -0
  19. package/dist/core/runtime/broker/boot-state.js +1 -1
  20. package/dist/core/runtime/broker/cycle-start.d.ts +8 -1
  21. package/dist/core/runtime/broker/cycle-start.js +2 -2
  22. package/dist/core/runtime/broker/turn-admission.d.ts +4 -1
  23. package/dist/core/runtime/broker/turn-admission.js +1 -1
  24. package/dist/core/runtime/broker.js +1 -1
  25. package/dist/core/runtime/runner/blaxel/runner.js +2 -2
  26. package/dist/core/runtime/runner/machine/call.js +2 -2
  27. package/dist/core/runtime/runner/machine/executor.d.ts +3 -3
  28. package/dist/core/runtime/runner/machine/executor.js +1 -1
  29. package/dist/core/runtime/runner/machine/ops.d.ts +18 -1
  30. package/dist/core/runtime/runner/machine/ops.js +1 -1
  31. package/dist/core/runtime/runner/types.d.ts +2 -1
  32. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  33. package/dist/daemon/api/handlers/delivery.js +1 -1
  34. package/dist/daemon/api/handlers/messages.js +2 -2
  35. package/dist/daemon/api/handlers/nodes.js +1 -1
  36. package/dist/daemon/cron/machine-fire.d.ts +3 -0
  37. package/dist/daemon/cron/machine-fire.js +1 -1
  38. package/dist/daemon/crtrd.js +16 -16
  39. package/dist/daemon/due-sources.d.ts +1 -1
  40. package/dist/daemon/due-sources.js +1 -1
  41. package/dist/daemon/due.js +7 -7
  42. package/dist/daemon/machine-daemon.js +1 -1
  43. package/dist/daemon/machine-link/job-sweep.d.ts +7 -0
  44. package/dist/daemon/machine-link/job-sweep.js +1 -1
  45. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  46. package/dist/daemon/reconcilers/machine-offline.d.ts +6 -0
  47. package/dist/daemon/reconcilers/machine-offline.js +7 -0
  48. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -1
  49. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  50. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  51. package/dist/pi-extensions/canvas-stophook.js +1 -1
  52. package/dist/pi-extensions/canvas-tool-guide.d.ts +3 -1
  53. package/dist/pi-extensions/canvas-tool-guide.js +4 -4
  54. package/package.json +3 -3
  55. package/packages/crouter-api/dist/api/client.js +1 -1
  56. package/packages/crouter-api/dist/api/contract.js +1 -1
  57. package/packages/crouter-api/dist/api/dto/execution-start.js +0 -1
  58. package/packages/crouter-api/dist/commands/node/bash.js +7 -4
  59. package/packages/crouter-api/dist/core/bash-job-supervisor.js +15 -2
  60. package/packages/crouter-api/dist/core/canvas/canvas.js +23 -2
  61. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  62. package/packages/crouter-api/dist/core/grants/sync.js +3 -0
  63. package/packages/crouter-api/dist/core/runtime/broker/bash-job-launch.js +4 -5
  64. package/packages/crouter-api/dist/core/runtime/revive-all.js +108 -0
  65. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
  66. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
  67. package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +13 -2
  68. package/packages/crouter-api/dist/daemon/cron/armed-context.js +140 -0
  69. package/packages/crouter-api/dist/daemon/cron/capture.js +50 -0
  70. package/packages/crouter-api/dist/daemon/cron/closed.js +108 -0
  71. package/packages/crouter-api/dist/daemon/cron/disposition.js +63 -0
  72. package/packages/crouter-api/dist/daemon/cron/ended.js +80 -0
  73. package/packages/crouter-api/dist/daemon/cron/escalation.js +136 -0
  74. package/packages/crouter-api/dist/daemon/cron/held.js +20 -0
  75. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +177 -0
  76. package/packages/crouter-api/dist/daemon/cron/narrowed.js +34 -0
  77. package/packages/crouter-api/dist/daemon/cron/recurrence.js +38 -0
  78. package/packages/crouter-api/dist/daemon/cron/run-token.js +37 -0
  79. package/packages/crouter-api/dist/daemon/cron/settle.js +78 -0
  80. package/packages/crouter-api/dist/daemon/cron/sinks.js +70 -0
  81. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +1 -1
  82. package/packages/crouter-api/package.json +1 -1
  83. package/packages/crouter-identity/package.json +1 -1
  84. package/packages/crouter-plugin/package.json +3 -3
  85. package/runtime.lock.json +14 -14
  86. package/scripts/sandbox-bootstrap.sh +4 -0
@@ -273,6 +273,7 @@ const nodeBashKill = defineLeaf({
273
273
  { name: 'node_id', type: 'string', required: true, constraint: 'The owning node.' },
274
274
  { name: 'signaled', type: 'boolean', required: true, constraint: 'True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet.' },
275
275
  { name: 'stop_pending_on_machine', type: 'boolean', required: true, constraint: 'True when the job’s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet.' },
276
+ { name: 'stop_queue_error', type: 'string', required: false, constraint: 'The error when the job ended here but the stop for its machine could not be queued, so the process may still be running there; null otherwise.' },
276
277
  ],
277
278
  outputKind: 'object',
278
279
  effects: [
@@ -291,11 +292,13 @@ const nodeBashKill = defineLeaf({
291
292
  throw new InputError({ error: 'invalid_job_id', message: `invalid background job id: ${jobId}`, next: 'Use a job id reported by `crtr node bash list`.' });
292
293
  }
293
294
  const stopped = await cliClient().stopBashJob(node.node_id, jobId);
294
- return { node_id: node.node_id, signaled: stopped.signaled, stop_pending_on_machine: stopped.stop_pending_on_machine === true };
295
+ return { node_id: node.node_id, signaled: stopped.signaled, stop_pending_on_machine: stopped.stop_pending_on_machine === true, ...(stopped.stop_queue_error === undefined ? {} : { stop_queue_error: stopped.stop_queue_error }) };
295
296
  },
296
- render: (result) => result['stop_pending_on_machine'] === true
297
- ? `Ended a background bash job for ${result['node_id']}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`
298
- : `Canceled a background bash job for ${result['node_id']}${result['signaled'] === true ? '' : ' (no observed job process was still running)'}.`,
297
+ render: (result) => typeof result['stop_queue_error'] === 'string'
298
+ ? `Ended the background bash job for ${result['node_id']}, but the stop could not be queued for its machine (${result['stop_queue_error']}); the process may still be running there. Check with \`ps\` on that machine.`
299
+ : result['stop_pending_on_machine'] === true
300
+ ? `Ended a background bash job for ${result['node_id']}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`
301
+ : `Canceled a background bash job for ${result['node_id']}${result['signaled'] === true ? '' : ' (no observed job process was still running)'}.`,
299
302
  });
300
303
  const nodeBashQuiet = defineLeaf({
301
304
  name: 'quiet',
@@ -28,7 +28,8 @@ const LOG_COLLECTOR_SCRIPT = [
28
28
  * `job.activity`: line 1 `<epoch-ms of the last activity> <epoch-ms of this sample>`, then one watched file path per line.
29
29
  * Self-contained (Node built-ins only) so a sandboxed job host can run it unchanged. Process tree and open
30
30
  * files come from /proc where it exists, else `ps` and `lsof`; a missing `lsof` degrades to CPU and the job
31
- * log alone. Arguments: supervisor pid, job log path, activity file path. */
31
+ * log alone. Arguments: supervisor pid, job log path, activity file path, then optionally the machine daemon's socket, node id and job id:
32
+ * when given, it POSTs `/job-activity` to the daemon when the last-activity time has moved, at most once per CRTR_BASH_ACTIVITY_NOTIFY_MS (default 5 min). */
32
33
  const ACTIVITY_SAMPLER_SCRIPT = [
33
34
  'const fs = require("node:fs"), cp = require("node:child_process");',
34
35
  'const rootPid = Number(process.argv[1]), out = process.argv[3];',
@@ -99,6 +100,17 @@ const ACTIVITY_SAMPLER_SCRIPT = [
99
100
  '}',
100
101
  'let lastActivity = Date.now(), prevAt = lastActivity, prevCpu = new Map(), watched = [logPath];',
101
102
  'try { prevCpu = tree(processes()); } catch {}',
103
+ 'const socket = process.argv[4], node = process.argv[5], job = process.argv[6];',
104
+ 'const notifyEvery = Number(process.env.CRTR_BASH_ACTIVITY_NOTIFY_MS) || 300000;',
105
+ 'let notified = lastActivity, notifiedAt = 0;',
106
+ // Best effort, bounded: the daemon reports this job's fresh activity once; a missing daemon or any failure is ignored.
107
+ 'function notify() {',
108
+ ' if (!socket) return;',
109
+ ' notified = lastActivity; notifiedAt = Date.now();',
110
+ ' const req = require("node:http").request({ socketPath: socket, path: "/job-activity", method: "POST", headers: { "content-type": "application/json" }, timeout: 3000 }, (res) => res.resume());',
111
+ ' req.on("error", () => {}); req.on("timeout", () => req.destroy());',
112
+ ' req.end(JSON.stringify({ node, job }));',
113
+ '}',
102
114
  'function record() {',
103
115
  ' fs.writeFileSync(out + ".tmp", lastActivity + " " + prevAt + "\\n" + watched.join("\\n") + "\\n");',
104
116
  ' fs.renameSync(out + ".tmp", out);',
@@ -126,6 +138,7 @@ const ACTIVITY_SAMPLER_SCRIPT = [
126
138
  ' prevAt = at;',
127
139
  ' prevCpu = cpus;',
128
140
  ' record();',
141
+ ' if (lastActivity !== notified && at - notifiedAt >= notifyEvery) notify();',
129
142
  '}',
130
143
  'record();',
131
144
  'setInterval(() => { try { sample(); } catch {} }, interval);',
@@ -143,7 +156,7 @@ const EXIT_NOTIFY_SCRIPT = [
143
156
  /** File-backed command supervisor. Beside the job it runs the activity sampler. It writes the exit code to job.exit and, for a foreground
144
157
  * command, claims job.done; the daemon reads job.exit of a backgrounded job and publishes `exited`. */
145
158
  export const BASH_JOB_SUPERVISOR_SCRIPT = [
146
- '"$8" -e ' + JSON.stringify(ACTIVITY_SAMPLER_SCRIPT) + ' "$$" "$2" "$9" &',
159
+ '"$8" -e ' + JSON.stringify(ACTIVITY_SAMPLER_SCRIPT) + ' "$$" "$2" "$9" "${10:-}" "${11:-}" "${12:-}" &',
147
160
  'sampler=$!',
148
161
  'n=$(command -v nice)',
149
162
  '${n:+"$n" -n "$7"} "$6" "$1" 2>&1 | "$8" -e ' + JSON.stringify(LOG_COLLECTOR_SCRIPT) + ' "$2"',
@@ -229,12 +229,33 @@ export async function recordCreateRequestNode(requestKey, nodeId) {
229
229
  * after a daemon restart resumes the same identity instead of minting another.
230
230
  * Only the first caller binds: two API processes holding one unbound key race
231
231
  * here, and each gets back the id the key actually names. */
232
- export async function reserveCreateRequestNode(requestKey, nodeId) {
232
+ export async function reserveCreateRequestNode(requestKey, nodeId, owner) {
233
233
  const db = await openDb();
234
- await db.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(nodeId, requestKey);
234
+ await db.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL")
235
+ .run(nodeId, owner, Date.now() + CREATE_LEASE_MS, requestKey);
235
236
  const bound = await db.prepareUncached('SELECT node_id FROM create_requests WHERE request_key = ?').get(requestKey);
236
237
  return bound?.node_id ?? null;
237
238
  }
239
+ /** How long a create's lease lasts without renewal; its owner renews it every {@link CREATE_LEASE_RENEW_MS}. */
240
+ export const CREATE_LEASE_MS = 30_000;
241
+ export const CREATE_LEASE_RENEW_MS = 10_000;
242
+ /** Take over a bound, unfinished create whose owner's lease has lapsed (or never existed). True when `owner` now holds it. */
243
+ export async function claimCreateLease(requestKey, nodeId, owner) {
244
+ const now = Date.now();
245
+ const result = await (await openDb()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)")
246
+ .run(owner, now + CREATE_LEASE_MS, requestKey, nodeId, now);
247
+ return Number(result.changes) > 0;
248
+ }
249
+ /** Extend the lease while `owner` still holds it. */
250
+ export async function renewCreateLease(requestKey, owner) {
251
+ await (await openDb()).prepareUncached('UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?')
252
+ .run(Date.now() + CREATE_LEASE_MS, requestKey, owner);
253
+ }
254
+ /** Whether another owner's lease on the key is still unexpired. */
255
+ export async function createLeaseLive(requestKey) {
256
+ const row = await (await openDb()).prepareUncached('SELECT lease_expires_at FROM create_requests WHERE request_key = ?').get(requestKey);
257
+ return row?.lease_expires_at != null && Number(row.lease_expires_at) > Date.now();
258
+ }
238
259
  export async function completeCreateRequest(requestKey, nodeId) {
239
260
  await (await openDb()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(requestKey, nodeId);
240
261
  }
@@ -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 = 21;
9
+ export const CANVAS_SCHEMA_VERSION = 23;
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. */
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { crtrHome } from '../canvas/paths.js';
5
5
  import { withCanvasWrite } from '../canvas/db.js';
6
+ import { reconcilePackages } from '../graph/package-reconcile.js';
6
7
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
7
8
  import { emitEvent } from '../events/emit.js';
8
9
  import { describeOutboundFailure, outboundFetch, outboundJson, outboundRefusal } from '../events/outbound.js';
@@ -135,6 +136,8 @@ async function bindLatePerson(resolved) {
135
136
  setPersonId(resolved.id);
136
137
  await adoptInstallPerson(resolved.id);
137
138
  const result = await retireLocalPerson();
139
+ // The boot reconcile was skipped while the person was unresolved.
140
+ await withCanvasWrite(async (db) => await reconcilePackages(db));
138
141
  emitEvent({ level: 'info', event: 'daemon.person.resolved', fields: { person_id: resolved.id, source: resolved.source } });
139
142
  emitEvent({ level: 'info', event: 'daemon.person.retired', fields: { person_id: result.person, retired: result.retired, columns: result.columns } });
140
143
  }
@@ -19,11 +19,10 @@ import { brokerApiUrl, startBrokerBashJob } from './daemon-ops.js';
19
19
  export function bashJobsUseLauncher() {
20
20
  return process.platform === 'linux' && brokerApiUrl() === undefined;
21
21
  }
22
- /** The supervisor's optional notify arguments: the machine daemon's socket, the node and the job, only on a Mac that is a machine environment and whose broker
23
- * talks to the local daemon. A sandbox broker (`CRTR_API_URL`) has no machine daemon beside it, so it passes none and the supervisor skips the notice. */
24
- function exitNotifyArgs(nodeId, jobId) {
25
- if (brokerApiUrl() !== undefined)
26
- return [];
22
+ /** The supervisor's optional notify arguments: the machine daemon's socket, the node and the job, only where a machine daemon runs beside the broker — an
23
+ * install with `machine.json`, i.e. a Mac that is a machine environment. That Mac's brokers also have `CRTR_API_URL` set, so it says nothing about the
24
+ * machine daemon. A sandbox has no `machine.json`, so it passes none and the supervisor skips the notice. */
25
+ export function exitNotifyArgs(nodeId, jobId) {
27
26
  try {
28
27
  if (readMachineConfig() === undefined)
29
28
  return [];
@@ -0,0 +1,108 @@
1
+ // revive-all — resume EVERY disconnected node in one shot.
2
+ //
3
+ // After a mass-disconnect event (a reboot, a killed login/tmux session, a mass
4
+ // crash, or the daemon being down a while) many nodes end up with their
5
+ // canvas.db row + saved conversation intact but NO broker engine running. The
6
+ // daemon recovers active|idle rows during its row-driven supervision tick and
7
+ // from broker exit events during its own epoch, but it deliberately never touches
8
+ // terminal/dormant states, so the operator is left reviving survivors one id at
9
+ // a time.
10
+ //
11
+ // This module is the single sweep: `listDisconnected` selects every DISCONNECTED
12
+ // node (engine not running, but a resumable saved session exists), and
13
+ // `reviveAll` RESUMEs each via reviveNode — the only sanctioned launcher, which
14
+ // self-guards the double-spawn. The selection predicate (`isDisconnected`) is
15
+ // pure so the scope rules are unit-testable without booting a single process.
16
+ import { listNodes, getNode } from '../canvas/index.js';
17
+ import { recordedPidLiveness } from '../canvas/pid.js';
18
+ import { reviveNode } from './revive.js';
19
+ import { filterAsync } from '../async-array.js';
20
+ /** Statuses a node lands in DELIBERATELY: a worker that finished its own work
21
+ * (`done`) or a node a human closed/reaped (`canceled`). The daemon never
22
+ * auto-revives these (see reapDeadResidue in crtrd.ts), and revive-all leaves
23
+ * them alone too — resurrecting finished and closed conversations en masse would
24
+ * flood the canvas with work nobody asked to reopen. `dead` is NOT here: a crash
25
+ * is involuntary, so it is swept. (Silas, 2026-06-13: no opt-in to include these
26
+ * — the exclusion is unconditional.) */
27
+ export const TERMINAL_BY_CHOICE = ['done', 'canceled'];
28
+ /** True when `meta` has no natural future cycle ahead of it. A frozen row is
29
+ * excluded because its mark records a thaw cycle already owed. */
30
+ export function hasNoNaturalCycle(meta) {
31
+ return meta.frozen_at == null && (meta.final_report != null || TERMINAL_BY_CHOICE.includes(meta.status));
32
+ }
33
+ /** True when `meta`'s engine is NOT running but it has a resumable saved session
34
+ * — the precise "disconnected" predicate.
35
+ *
36
+ * - engine not running: no live `pi_pid` (a dead/absent broker pid).
37
+ * - reconnectable: a captured pi session marker (`pi_session_file` or
38
+ * `pi_session_id`) — without one there is nothing to reopen. reviveNode
39
+ * resumes by the `.jsonl` path when it still exists, else relaunches fresh (a
40
+ * bare `pi_session_id` alone does not resume — the broker preflight rejects
41
+ * it — so such a node comes back fresh).
42
+ * - `human`-kind rows are the `crtr human` bridge, never a pi engine, so they
43
+ * are never "disconnected" (mirrors the daemon's superviseTick carve-out).
44
+ * - unfrozen terminal-by-choice (`done`/`canceled`) is excluded.
45
+ * - a node that already pushed its FINAL REPORT (`final_report` set) FINISHED
46
+ * its own work — it is excluded regardless of status. A crash mid-reap can
47
+ * leave it `dead` (not terminal-by-choice) with its report already committed;
48
+ * resurrecting it as `active` strands it re-reviving forever and cannot
49
+ * re-reap (the stuck-node incident). Mass revive must never resurrect
50
+ * finished work; an explicit `node lifecycle revive <id>` still can.
51
+ *
52
+ * Pure: the liveness probe is injected so scope is unit-testable without real
53
+ * processes. */
54
+ export function isDisconnected(meta, isAlive) {
55
+ if (meta.kind === 'human')
56
+ return false;
57
+ if (isAlive(meta.pi_pid))
58
+ return false; // engine running → connected
59
+ if (meta.pi_session_id == null && meta.pi_session_file == null)
60
+ return false; // nothing to resume
61
+ if (hasNoNaturalCycle(meta))
62
+ return false; // finished its own work, or terminal-by-choice — never mass-revive
63
+ return true;
64
+ }
65
+ /** Every disconnected node on the canvas — the set a revive-all WOULD relaunch.
66
+ * This is the PREVIEW: it has no side effects, so the command can list the
67
+ * candidates and gate on confirmation before any engine is launched. */
68
+ export async function listDisconnected() {
69
+ const out = [];
70
+ for (const row of await listNodes()) {
71
+ const meta = await getNode(row.node_id);
72
+ // IDENTITY-aware AND requires CONFIRMED alive: a bare isPidAlive would
73
+ // misread a recycled pi_pid as "engine running" and SKIP the node, so it
74
+ // never reaches reviveNode's own identity-aware double-launch guard
75
+ // guard. `dead` OR `indeterminate` both count as disconnected/eligible
76
+ // here — only a
77
+ // positively confirmed-alive read is treated as "still connected".
78
+ if (meta !== null && isDisconnected(meta, (pid) => recordedPidLiveness(pid, meta.pi_pid_identity) === 'alive'))
79
+ out.push(meta);
80
+ }
81
+ return out;
82
+ }
83
+ /** RESUME every disconnected node. reviveNode is the ONLY sanctioned launcher
84
+ * and self-guards the double-spawn (a node whose broker pid is already live is a
85
+ * no-op), so this is a thin orchestrator over `listDisconnected`: revive each
86
+ * with resume:true. One failing node never aborts the sweep — its error is
87
+ * collected and the rest proceed. */
88
+ export async function reviveAll(include = async () => true) {
89
+ const result = { revived: [], failed: [], frozen: [] };
90
+ for (const meta of (await filterAsync(await listDisconnected(), include))) {
91
+ try {
92
+ // Reconnecting a disconnected broker is recovery, not a wake — a node
93
+ // waiting on an armed deadline keeps it across the sweep. A sweep over a
94
+ // whole canvas is the likeliest way to meet the cap, and every node in it
95
+ // is one the daemon wants back: freeze the overflow and let the tick
96
+ // bring them up as slots free.
97
+ const outcome = (await reviveNode(meta.node_id, { resume: true, recovery: true, capacity: 'freeze' })).outcome;
98
+ if (outcome === 'frozen')
99
+ result.frozen.push(meta.node_id);
100
+ else
101
+ result.revived.push(meta.node_id);
102
+ }
103
+ catch (err) {
104
+ result.failed.push({ node_id: meta.node_id, error: err.message });
105
+ }
106
+ }
107
+ return result;
108
+ }
@@ -11,7 +11,7 @@ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '.
11
11
  /** Seconds a caller waits: `start` 60, every other op 15 (design). The `worktree.*` ops run Git under a repository lock that waits up to
12
12
  * 25 s, so they get 60 too (`worktree.finalize` also asks origin, bounded at 10 s). */
13
13
  export const MACHINE_CALL_TIMEOUT_S = {
14
- start: 60, wake: 15, stop: 15, status: 15, 'status.all': 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15,
14
+ start: 60, wake: 15, stop: 15, status: 15, 'status.all': 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15, 'job.stop': 15,
15
15
  'worktree.create': 60, 'worktree.rollback': 60, 'worktree.close': 60, 'worktree.abandon': 60, 'worktree.finalize': 60,
16
16
  'repo.identify': 15,
17
17
  };
@@ -1,4 +1,4 @@
1
- export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel',
1
+ export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
2
2
  'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'repo.identify'];
3
3
  /** No live link row for the environment: the caller leaves its work pending and retries on its own backoff. */
4
4
  export class MachineOfflineError extends Error {
@@ -1,6 +1,7 @@
1
1
  // Daemon-owned surfaces for one node's background bash jobs: a job is a canvas row
2
2
  // (see core/graph/jobs.ts); its process runs under the broker's supervisor, which
3
3
  // reports pgid, activity, output and exit through `report`.
4
+ import { queueJobStop } from '../../cron/machine-fire.js';
4
5
  import { killBashJobObject, recordBashJobObject } from '../../../core/spaces/stop.js';
5
6
  import { readerFor } from '../reader.js';
6
7
  import { join } from 'node:path';
@@ -218,7 +219,7 @@ async function handleStop(ctx) {
218
219
  const job = (await runningJobs(await openDb(), nodeId)).find((candidate) => candidate.jobId === jobId);
219
220
  if (job === undefined)
220
221
  throw new ApiError(404, 'job_not_found', `no running background job ${jobId} for ${nodeId}`);
221
- // A sandbox job is stopped where it runs: ending its row makes the broker's next report answer 409, and the reporter signals.
222
+ // A sandbox job is stopped where it runs: a `job.stop` machine call is queued once the row ends.
222
223
  const remote = await ownerRunsRemotely(await openDb(), nodeId);
223
224
  if (!remote && (job.pgid === null || job.pgidIdentity === null))
224
225
  throw new ApiError(409, 'job_not_stoppable', `job ${jobId} reported no trusted process identity`);
@@ -228,6 +229,16 @@ async function handleStop(ctx) {
228
229
  const reader = await readerFor(db, ctx);
229
230
  return reader.class === 'person' ? reader.person : reader.class === 'app' ? reader.app : reader.node;
230
231
  });
232
+ // The row has ended, so a failed queue cannot be reported as a failed kill: say the process may still be running.
233
+ let stopQueueError;
234
+ if (remote) {
235
+ try {
236
+ await queueJobStop(nodeId, jobId);
237
+ }
238
+ catch (err) {
239
+ stopQueueError = err instanceof Error ? err.message : String(err);
240
+ }
241
+ }
231
242
  const node = await getNode(nodeId);
232
243
  if (node !== null && !isBrokerLive(node)) {
233
244
  try {
@@ -235,7 +246,7 @@ async function handleStop(ctx) {
235
246
  }
236
247
  catch { /* the notice remains durable */ }
237
248
  }
238
- const result = { node_id: nodeId, job_id: jobId, signaled, ...(remote ? { stop_pending_on_machine: true } : {}) };
249
+ const result = { node_id: nodeId, job_id: jobId, signaled, ...(remote ? { stop_pending_on_machine: true } : {}), ...(stopQueueError === undefined ? {} : { stop_queue_error: stopQueueError }) };
239
250
  return { status: 200, body: result };
240
251
  }
241
252
  /** The broker backgrounded a command: record it as the node's job row (id = job id). */
@@ -0,0 +1,140 @@
1
+ import { envHomeOverride } from '../../shared/env.js';
2
+ import { loadProfileManifest, lookupProfile } from '../../core/profiles/manifest.js';
3
+ import { localEnvironmentSecrets } from '../../core/secrets/environment-owner.js';
4
+ import { ADMITTED_HOST_PATH_ENV, buildOperationalEnvBase } from '../../core/runtime/spawn-env.js';
5
+ import { getNode } from '../../core/canvas/canvas.js';
6
+ import { contextDir } from '../../core/canvas/paths.js';
7
+ import { appendRunEvent } from '../../core/runs/events.js';
8
+ import { payerOfGrant } from '../../core/grants/mirror.js';
9
+ import { scopeAllowed } from '../../core/scopes.js';
10
+ import { cronPrincipalOf } from './authority.js';
11
+ import { personId } from '../../core/canvas/person.js';
12
+ /** The cron's profile, re-validated now and returned in canonical id form.
13
+ *
14
+ * A DELETED profile is the spec's root fallback: null. An UNREADABLE one is
15
+ * not — the profile is still there, so running as root would execute the
16
+ * command under an identity nobody armed, with the profile's own env store and
17
+ * purview silently replaced. That throws, and the run fails loudly once
18
+ * instead of running wrong on every tick. */
19
+ export function resolveLiveProfile(c) {
20
+ if (c.profile == null)
21
+ return null;
22
+ let lookup;
23
+ try {
24
+ lookup = lookupProfile(c.profile);
25
+ }
26
+ catch {
27
+ return null; // an ambiguous NAME resolves no better than a deleted profile
28
+ }
29
+ if (lookup.kind === 'resolved')
30
+ return lookup.entry.profileId;
31
+ if (lookup.kind === 'absent')
32
+ return null;
33
+ throw new ArmedContextError(`the armed profile "${c.profile}" is still on this host but its manifest could not be read (${lookup.manifestPath}) — running as root would silently give this cron a different identity, env store, and purview. Repair the manifest, or re-arm the cron under a profile that resolves.`);
34
+ }
35
+ export function cronBirthPrincipalOf(c) {
36
+ return { ...cronPrincipalOf(c), cron_id: c.cron_id, origin_run_id: c.origin_run_id, isolated: c.isolated, creator: c.created_by };
37
+ }
38
+ export async function cronBirthPlacement(p, nodeId) {
39
+ const creator = p.creator === null ? null : await getNode(p.creator);
40
+ if (creator !== null && p.origin_run_id !== null && creator.run_id === p.origin_run_id &&
41
+ (await getNode(p.origin_run_id))?.deleting_at == null &&
42
+ creator.grantee === p.grantee && (creator.sub ?? personId()) === p.sub && (creator.grant_id ?? null) === p.grant_id &&
43
+ (p.scopes === null ? creator.scopes == null : p.scopes.every((scope) => scopeAllowed(creator.scopes, scope)))) {
44
+ return { parent: creator.node_id, ...(p.scopes === null ? {} : { scopes: [...p.scopes] }) };
45
+ }
46
+ const bounded = p.scopes === null ? {} : { scopes: [...p.scopes] };
47
+ // Every root birth carries the checked principal as its run (the terminal included), so the node
48
+ // keeps exactly the grant and sub that were checked, whatever the terminal grant is by the time it spawns.
49
+ // A null grant_id (a terminal cron on a runtime with no issuer) stays null.
50
+ return {
51
+ root: true, rootLifecycle: 'terminal', ...bounded,
52
+ run: { grantee: p.grantee, sub: p.sub, grant_id: p.grant_id, client_id: null, metadata_json: JSON.stringify(p.cron_id === null ? { exec: true } : { cron_id: p.cron_id }),
53
+ run_id: nodeId, event_cursor: 1,
54
+ usage_json: JSON.stringify({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 }) },
55
+ // A node born with an explicit `run` does not get its `run.started` event from the spawner.
56
+ withinCreate: async (db, row) => {
57
+ await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: await payerOfGrant(p.grant_id), usage: JSON.parse(row.usage_json) });
58
+ },
59
+ };
60
+ }
61
+ // The escalation node must still report an unreadable manifest, so its own spawn falls back to root.
62
+ export function resolveLiveProfileOrRoot(c) {
63
+ try {
64
+ return resolveLiveProfile(c);
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ export function resolveLiveProfileName(c) {
71
+ if (c.profile == null)
72
+ return undefined;
73
+ try {
74
+ return loadProfileManifest(c.profile).manifest.name;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ /** A stored context cannot be rebuilt; the run fails rather than running under a context nobody armed. */
81
+ export class ArmedContextError extends Error {
82
+ constructor(message) {
83
+ super(message);
84
+ this.name = 'ArmedContextError';
85
+ }
86
+ }
87
+ // Invalid snapshots are corruption: dropping `--env` would run under an environment nobody armed, so fail instead.
88
+ export function parseArmedEnv(envJson) {
89
+ if (envJson == null)
90
+ return {};
91
+ let parsed;
92
+ try {
93
+ parsed = JSON.parse(envJson);
94
+ }
95
+ catch (err) {
96
+ throw new ArmedContextError(`the armed env snapshot is not valid JSON (${err.message}) — this cron's stored env_json is corrupt, so the run would silently drop every armed variable. Re-arm the cron with a valid --env.`);
97
+ }
98
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
99
+ throw new ArmedContextError("the armed env snapshot is not a JSON object — this cron's stored env_json is corrupt. Re-arm the cron with a valid --env.");
100
+ }
101
+ const extraEnv = {};
102
+ for (const [k, v] of Object.entries(parsed)) {
103
+ if (typeof v !== 'string') {
104
+ throw new ArmedContextError(`the armed env snapshot's value for "${k}" is not a string — this cron's stored env_json is corrupt, so the run would silently drop that variable. Re-arm the cron with a valid --env.`);
105
+ }
106
+ extraEnv[k] = v;
107
+ }
108
+ return extraEnv;
109
+ }
110
+ /** Rebuild the armed context. Corrupt snapshots and unreadable profiles fail rather than silently changing its identity or environment. */
111
+ export async function buildArmedRunContext(c, runId) {
112
+ const extraEnv = parseArmedEnv(c.env_json);
113
+ const isTerminal = c.grantee === 'app:terminal';
114
+ const profileId = isTerminal ? resolveLiveProfile(c) : null;
115
+ const operationalEnv = buildOperationalEnvBase({ targetCwd: c.cwd, targetProfileId: profileId, skipSpawnAllow: !isTerminal });
116
+ const env = {
117
+ ...operationalEnv,
118
+ ...await localEnvironmentSecrets(profileId, c.grantee),
119
+ ...extraEnv,
120
+ ...(profileId !== null ? { CRTR_PROFILE_ID: profileId } : {}),
121
+ CRTR_CRON_ID: c.cron_id,
122
+ CRTR_CRON_NAME: c.name,
123
+ CRTR_RUN_ID: runId,
124
+ };
125
+ // Preserve the daemon identity: otherwise child `crtr` resolves the default canvas.
126
+ const canvasHomeOverride = envHomeOverride();
127
+ if (canvasHomeOverride !== undefined && canvasHomeOverride !== '') {
128
+ env['CRTR_HOME'] = canvasHomeOverride;
129
+ }
130
+ if (c.anchor_node != null) {
131
+ env['CRTR_ANCHOR'] = c.anchor_node;
132
+ // The anchor node's own context dir, as nodeEnv() gives the node itself. An
133
+ // unanchored cron has no node, so it gets none — and a vanished anchor gets none either.
134
+ const anchor = await getNode(c.anchor_node);
135
+ if (anchor !== null)
136
+ env['CRTR_CONTEXT_DIR'] = contextDir(anchor.node_id, anchor.grantee);
137
+ }
138
+ env[ADMITTED_HOST_PATH_ENV] = operationalEnv[ADMITTED_HOST_PATH_ENV];
139
+ return { profileId, env };
140
+ }
@@ -0,0 +1,50 @@
1
+ // src/daemon/cron/capture.ts — output capture for a cron run's child process,
2
+ // plus the timing/hash constants the capture and kill mechanics share.
3
+ import { createHash } from 'node:crypto';
4
+ /** Output head caps for the run log (spec: "capped, e.g. 4KB"). */
5
+ export const CRON_OUTPUT_HEAD_BYTES = 4 * 1024;
6
+ /** Bound between the run-timeout SIGTERM and a forced SIGKILL escalation, so
7
+ * a signal-trapping command cannot stall teardown's detached drain. */
8
+ export const CRON_KILL_GRACE_MS = 2000;
9
+ /** Poll interval while waiting for a SIGTERMed stale-lease run to actually die
10
+ * (each probe is a `ps` call, so this is deliberately coarse). */
11
+ export const CRON_DEATH_POLL_MS = 250;
12
+ /** sha256 of empty stdout — the change-detection hash a run that produced no
13
+ * output carries (a failed spawn, a recovered stale lease). */
14
+ export const EMPTY_STDOUT_SHA256 = createHash('sha256').update('').digest('hex');
15
+ /** A byte-capped capture of one output stream's head. Bytes are buffered and
16
+ * decoded exactly once, at the end — decoding per chunk both mis-measured the
17
+ * cap (UTF-16 code units, not bytes) and corrupted any multi-byte sequence
18
+ * that straddled a chunk boundary. Truncation is MARKED, never silent: a
19
+ * clipped body reads as complete output to whoever receives the delivery. */
20
+ export function newHeadCapture(headBytes = CRON_OUTPUT_HEAD_BYTES) {
21
+ const chunks = [];
22
+ let bytes = 0;
23
+ let wasTruncated = false;
24
+ return {
25
+ take(chunk) {
26
+ const room = headBytes - bytes;
27
+ if (room <= 0) {
28
+ wasTruncated = true;
29
+ return;
30
+ }
31
+ if (chunk.length > room) {
32
+ chunks.push(chunk.subarray(0, room));
33
+ bytes = headBytes;
34
+ wasTruncated = true;
35
+ return;
36
+ }
37
+ chunks.push(chunk);
38
+ bytes += chunk.length;
39
+ },
40
+ decode() {
41
+ return Buffer.concat(chunks).toString('utf8');
42
+ },
43
+ truncated() {
44
+ return wasTruncated;
45
+ },
46
+ };
47
+ }
48
+ export function formatCronOutputHead(text, truncated) {
49
+ return truncated ? `${text}\n[… output truncated at ${CRON_OUTPUT_HEAD_BYTES} bytes]` : text;
50
+ }
@@ -0,0 +1,108 @@
1
+ // src/daemon/cron/closed.ts — settling one run that ended: the record of a CLOSED run and the two ways it settles (observed exit,
2
+ // or a launch that never produced a child). Shared by the local executor (cron-run.ts) and the machine dispatcher (machine-fire.ts).
3
+ import { CRON_OUTPUT_HEAD_BYTES, EMPTY_STDOUT_SHA256 } from './capture.js';
4
+ import { decideHeldSettle, EXIT_HELD, HELD_DELIVERED } from './held.js';
5
+ import { settleRun } from './settle.js';
6
+ /** Settle one closed child: choose the outcome (replaced short-circuit, owed
7
+ * gate, or the full disposition), then hand it to the one settle tail. */
8
+ export async function settleClosedRun(c, run) {
9
+ const { runId, outOfBand, startedAtIso, finishedAtMs, code, timedOut, processError } = run;
10
+ // The owed-gate branch (exit 75): a peer of the wasReplaced short-circuit —
11
+ // skip disposition entirely (no delivery, no escalation, no pause, no
12
+ // on-change hash, no one-shot consumption) and settle the row's held state
13
+ // with the lease release instead. The exclusions are deliberate: a manual
14
+ // `cron run` must not change scheduling state; a timeout-killed or
15
+ // launch-failed run is a real failure even if a stray 75 surfaces; a replaced
16
+ // or self-canceled run's existing short-circuits win.
17
+ const heldDeferred = !outOfBand &&
18
+ !timedOut &&
19
+ processError == null &&
20
+ code === EXIT_HELD &&
21
+ !run.wasReplaced &&
22
+ !run.wasSelfCanceled;
23
+ let outcome;
24
+ let lease;
25
+ if (run.wasReplaced) {
26
+ // Record it, no disposition, no escalation, and leave `held` untouched
27
+ // (the gate is still unresolved).
28
+ outcome = { kind: 'stated', delivered: 'replaced (overlap=replace)' };
29
+ lease = 'release';
30
+ }
31
+ else if (heldDeferred) {
32
+ // The occurrence is NOT spent — even a one-shot is retained (like a paused
33
+ // escalated one-shot is). Park/re-due and the lease release are one write.
34
+ // A row canceled mid-run has nothing to settle.
35
+ outcome = { kind: 'stated', delivered: HELD_DELIVERED };
36
+ lease = await decideHeldSettle(c, startedAtIso, finishedAtMs) ?? 'release';
37
+ }
38
+ else {
39
+ outcome = {
40
+ kind: 'disposed',
41
+ ctx: {
42
+ runId,
43
+ startedAtIso,
44
+ exitCode: timedOut ? -1 : code,
45
+ timedOut,
46
+ runTimeoutS: c.run_timeout_s,
47
+ processErrorMessage: processError != null ? processError.message : null,
48
+ stdoutHead: run.stdoutHead,
49
+ stdoutSha256: run.stdoutSha256,
50
+ stderrHead: run.stderrHead,
51
+ },
52
+ selfCanceled: run.wasSelfCanceled,
53
+ };
54
+ // An ordinary scheduled disposition settlement resolves the gate, so it
55
+ // unparks a held row; an out-of-band run leaves `held` untouched.
56
+ lease = outOfBand ? 'release' : { kind: 'clear' };
57
+ }
58
+ return settleRun(c, {
59
+ outOfBand,
60
+ outcome,
61
+ record: {
62
+ runId,
63
+ startedAtIso,
64
+ finishedAtMs,
65
+ durationMs: finishedAtMs - run.startedAtMs,
66
+ exitCode: timedOut ? -1 : code,
67
+ stdoutHead: run.stdoutHead === '' ? null : run.stdoutHead,
68
+ stderrHead: processError != null
69
+ ? `run process error: ${processError.message}`.slice(0, CRON_OUTPUT_HEAD_BYTES)
70
+ : run.stderrHead === ''
71
+ ? null
72
+ : run.stderrHead,
73
+ },
74
+ lease,
75
+ });
76
+ }
77
+ /** Settle a claimed run that failed before its launched child could be observed. */
78
+ export function settleUnspawnedRun(c, run, lead, err) {
79
+ const finishedAtMs = Date.now();
80
+ const stderrHead = `${lead}: ${err.message}`.slice(0, CRON_OUTPUT_HEAD_BYTES);
81
+ return settleRun(c, {
82
+ outOfBand: run.outOfBand,
83
+ outcome: {
84
+ kind: 'disposed',
85
+ ctx: {
86
+ runId: run.runId,
87
+ startedAtIso: run.startedAtIso,
88
+ exitCode: null,
89
+ timedOut: false,
90
+ runTimeoutS: c.run_timeout_s,
91
+ processErrorMessage: err.message,
92
+ stdoutHead: '',
93
+ stdoutSha256: EMPTY_STDOUT_SHA256,
94
+ stderrHead,
95
+ },
96
+ },
97
+ record: {
98
+ runId: run.runId,
99
+ startedAtIso: run.startedAtIso,
100
+ finishedAtMs,
101
+ durationMs: finishedAtMs - run.startedAtMs,
102
+ exitCode: null,
103
+ stdoutHead: null,
104
+ stderrHead,
105
+ },
106
+ lease: 'release',
107
+ });
108
+ }