@north-light/cli 0.3.670 → 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 (75) 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/boot-state.d.ts +8 -0
  17. package/dist/core/runtime/broker/boot-state.js +1 -1
  18. package/dist/core/runtime/broker/cycle-start.d.ts +8 -1
  19. package/dist/core/runtime/broker/cycle-start.js +2 -2
  20. package/dist/core/runtime/broker/turn-admission.d.ts +4 -1
  21. package/dist/core/runtime/broker/turn-admission.js +1 -1
  22. package/dist/core/runtime/broker.js +1 -1
  23. package/dist/core/runtime/runner/machine/call.js +2 -2
  24. package/dist/core/runtime/runner/machine/executor.d.ts +3 -3
  25. package/dist/core/runtime/runner/machine/executor.js +1 -1
  26. package/dist/core/runtime/runner/machine/ops.d.ts +18 -1
  27. package/dist/core/runtime/runner/machine/ops.js +1 -1
  28. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  29. package/dist/daemon/api/handlers/delivery.js +1 -1
  30. package/dist/daemon/api/handlers/nodes.js +1 -1
  31. package/dist/daemon/cron/machine-fire.d.ts +3 -0
  32. package/dist/daemon/cron/machine-fire.js +1 -1
  33. package/dist/daemon/crtrd.js +16 -16
  34. package/dist/daemon/due-sources.d.ts +1 -1
  35. package/dist/daemon/due-sources.js +1 -1
  36. package/dist/daemon/due.js +7 -7
  37. package/dist/daemon/machine-daemon.js +1 -1
  38. package/dist/daemon/machine-link/job-sweep.d.ts +7 -0
  39. package/dist/daemon/machine-link/job-sweep.js +1 -1
  40. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  41. package/dist/daemon/reconcilers/machine-offline.d.ts +6 -0
  42. package/dist/daemon/reconcilers/machine-offline.js +7 -0
  43. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  44. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  45. package/dist/pi-extensions/canvas-stophook.js +1 -1
  46. package/package.json +3 -3
  47. package/packages/crouter-api/dist/api/client.js +1 -1
  48. package/packages/crouter-api/dist/api/contract.js +1 -1
  49. package/packages/crouter-api/dist/api/dto/execution-start.js +0 -1
  50. package/packages/crouter-api/dist/commands/node/bash.js +7 -4
  51. package/packages/crouter-api/dist/core/bash-job-supervisor.js +15 -2
  52. package/packages/crouter-api/dist/core/canvas/canvas.js +23 -2
  53. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  54. package/packages/crouter-api/dist/core/grants/sync.js +3 -0
  55. package/packages/crouter-api/dist/core/runtime/revive-all.js +108 -0
  56. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
  57. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
  58. package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +13 -2
  59. package/packages/crouter-api/dist/daemon/cron/armed-context.js +140 -0
  60. package/packages/crouter-api/dist/daemon/cron/capture.js +50 -0
  61. package/packages/crouter-api/dist/daemon/cron/closed.js +108 -0
  62. package/packages/crouter-api/dist/daemon/cron/disposition.js +63 -0
  63. package/packages/crouter-api/dist/daemon/cron/ended.js +80 -0
  64. package/packages/crouter-api/dist/daemon/cron/escalation.js +136 -0
  65. package/packages/crouter-api/dist/daemon/cron/held.js +20 -0
  66. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +177 -0
  67. package/packages/crouter-api/dist/daemon/cron/narrowed.js +34 -0
  68. package/packages/crouter-api/dist/daemon/cron/recurrence.js +38 -0
  69. package/packages/crouter-api/dist/daemon/cron/run-token.js +37 -0
  70. package/packages/crouter-api/dist/daemon/cron/settle.js +78 -0
  71. package/packages/crouter-api/dist/daemon/cron/sinks.js +70 -0
  72. package/packages/crouter-api/package.json +1 -1
  73. package/packages/crouter-identity/package.json +1 -1
  74. package/packages/crouter-plugin/package.json +3 -3
  75. package/runtime.lock.json +14 -14
@@ -0,0 +1,136 @@
1
+ // src/daemon/cron/escalation.ts — the cron failure path: pause the row and
2
+ // spawn a terminal node holding everything it needs to deal with the failure.
3
+ // Pausing IS the dedup — a paused row is never due, so nothing refires while
4
+ // the escalation node works.
5
+ import { getNode } from '../../core/canvas/canvas.js';
6
+ import { nodeAgentDir } from '../../core/canvas/node-agent-paths.js';
7
+ import { newNodeId } from '../../core/runtime/nodes.js';
8
+ import { fullName } from '../../core/canvas/labels.js';
9
+ import { listCronRuns, setCronState } from '../../core/canvas/crons.js';
10
+ import { emitEvent } from '../../core/events/emit.js';
11
+ import { spawnChild } from '../../core/runtime/spawn.js';
12
+ import { cronWakeOrigin } from '../../core/runtime/bearings.js';
13
+ import { cadenceDisplay } from '../../core/wake.js';
14
+ import { cronBirthPlacement, cronBirthPrincipalOf, resolveLiveProfileOrRoot } from './armed-context.js';
15
+ import { checkCronBirth } from './authority.js';
16
+ export function failureSummary(ctx, deliveryFailure) {
17
+ if (deliveryFailure !== null)
18
+ return deliveryFailure;
19
+ if (ctx.timedOut)
20
+ return `run timed out after ${ctx.runTimeoutS}s (killed; recorded exit -1)`;
21
+ if (ctx.processErrorMessage !== null)
22
+ return `run process error: ${ctx.processErrorMessage}`;
23
+ return `command exited ${ctx.exitCode ?? '(no exit observed)'}`;
24
+ }
25
+ /** The escalation node's kickoff: the cron's identity/config, this failure,
26
+ * the run-log ring, the creating-node reference, and a mandate that names its
27
+ * actual options (resume after verifying / cancel / ask the human). */
28
+ async function buildEscalationKickoff(c, ctx, deliveryFailure) {
29
+ const creator = c.created_by != null ? await getNode(c.created_by) : null;
30
+ const creatorLine = c.created_by == null
31
+ ? 'created by: (no creating node recorded)'
32
+ : creator !== null
33
+ ? `created by: node ${c.created_by} ("${fullName(creator)}") — still on the canvas; consider telling it what happened`
34
+ : `created by: node ${c.created_by} (now gone)`;
35
+ const schedule = c.recur != null ? `every ${cadenceDisplay(c.recur)}` : `one-shot at ${c.fire_at}`;
36
+ const priorRuns = (await listCronRuns(c.cron_id))
37
+ .slice(0, 10)
38
+ .map((r) => {
39
+ const exit = r.exit_code === null ? 'no exit' : `exit ${r.exit_code}`;
40
+ const head = (r.stderr_head ?? r.stdout_head ?? '').split('\n')[0]?.slice(0, 120) ?? '';
41
+ return `- ${r.started} — ${exit}, ${r.duration_ms}ms — ${r.delivered ?? ''}${head !== '' ? ` — ${head}` : ''}`;
42
+ });
43
+ return [
44
+ `A scheduled cron FAILED and has paused itself. You were spawned to deal with it.`,
45
+ '',
46
+ `- cron: "${c.name}" (${c.cron_id})`,
47
+ `- schedule: ${schedule}${c.tz != null ? ` (tz ${c.tz})` : ''}`,
48
+ `- context: cwd ${c.cwd}${c.profile != null ? `, profile ${c.profile}` : ''}`,
49
+ `- ${creatorLine}`,
50
+ `- this failure: ${failureSummary(ctx, deliveryFailure)}`,
51
+ '',
52
+ '## The command',
53
+ '',
54
+ '```bash',
55
+ c.command,
56
+ '```',
57
+ '',
58
+ '## This run',
59
+ '',
60
+ `- exit: ${ctx.timedOut ? '-1 (timeout)' : String(ctx.exitCode)}`,
61
+ `- stdout (head): ${ctx.stdoutHead === '' ? '(empty)' : ''}`,
62
+ ...(ctx.stdoutHead !== '' ? ['```', ctx.stdoutHead, '```'] : []),
63
+ `- stderr (head): ${ctx.stderrHead === '' ? '(empty)' : ''}`,
64
+ ...(ctx.stderrHead !== '' ? ['```', ctx.stderrHead, '```'] : []),
65
+ '',
66
+ '## Recent runs (most recent first, this failure not yet recorded)',
67
+ '',
68
+ ...(priorRuns.length > 0 ? priorRuns : ['(no prior runs recorded)']),
69
+ '',
70
+ '## Your mandate',
71
+ '',
72
+ `Diagnose why it failed and decide what to do:`,
73
+ `- Transient or fixable: fix the environment/command context, verify with \`crtr cron run ${c.cron_id}\` (fires now, out of band, shows you the result), then \`crtr cron resume ${c.cron_id}\` to re-arm it.`,
74
+ `- Obsolete: \`crtr cron cancel ${c.cron_id}\`.`,
75
+ `- The user's call (or the fix needs a change you cannot make): \`crtr human send\`.`,
76
+ '',
77
+ 'The cron stays paused until someone resumes it — nothing refires while you work.',
78
+ ].join('\n');
79
+ }
80
+ /** Pause the cron and spawn the escalation node in the cron's originating
81
+ * profile (root fallback). Returns the run-log `delivered` string. Never
82
+ * throws: an escalation spawn failure is recorded and logged, the pause
83
+ * stands (the row must not keep refiring a broken command). */
84
+ export async function escalateFailure(c, ctx, deliveryFailure) {
85
+ await setCronState(c.cron_id, 'paused');
86
+ try {
87
+ // The escalation node is a birth of the cron's grant like any other: with the grant gone or
88
+ // narrowed there is nothing it may start, so the cron stays paused and says so.
89
+ const principal = cronBirthPrincipalOf(c);
90
+ const authority = await checkCronBirth(principal, { kind: 'general', cwd: c.cwd, profile: resolveLiveProfileOrRoot(c) });
91
+ if (!authority.allowed) {
92
+ emitEvent({ level: 'warn', event: 'cron.birth.refused', fields: { cron_id: c.cron_id, grant_id: c.grant_id, reason: authority.reason, stage: 'escalation' } });
93
+ return `failure: cron paused; no escalation node (refused: ${authority.reason})`;
94
+ }
95
+ const nodeId = await newNodeId();
96
+ const placement = await cronBirthPlacement({ ...principal, scopes: authority.scopes }, nodeId);
97
+ const res = await spawnChild({
98
+ nodeId, kind: 'general',
99
+ isolated: c.isolated,
100
+ cwd: c.isolated ? await nodeAgentDir(nodeId, c.grantee) : c.cwd,
101
+ prompt: await buildEscalationKickoff(c, ctx, deliveryFailure),
102
+ // The spec's word is TERMINAL: a node that deals with this failure and
103
+ // reaps. With no compatible creator it is a terminal root run of the cron's grant.
104
+ ...placement,
105
+ readiness: 'launch',
106
+ profile: resolveLiveProfileOrRoot(c),
107
+ wakeOrigin: await cronWakeOrigin(c, 'node_birth'),
108
+ });
109
+ emitEvent({
110
+ level: 'info',
111
+ event: 'cron.failure.escalated',
112
+ fields: { cron_id: c.cron_id, name: c.name, escalation_node: res.node.node_id },
113
+ });
114
+ return `failure: cron paused, escalation node ${res.node.node_id} spawned`;
115
+ }
116
+ catch (err) {
117
+ emitEvent({
118
+ level: 'error',
119
+ event: 'cron.escalation.spawn_failed',
120
+ error: err,
121
+ fields: { cron_id: c.cron_id, name: c.name },
122
+ });
123
+ return `failure: cron paused; escalation spawn failed: ${err.message}`;
124
+ }
125
+ }
126
+ /** The delivery-failure line an escalated crashed ONE-SHOT carries: its side
127
+ * effects may already have landed in full, so a human/agent decides whether to
128
+ * redo it rather than the daemon re-firing it. */
129
+ export function crashedOneShotSummary(why) {
130
+ return [
131
+ `${why}.`,
132
+ 'This is a ONE-SHOT, so it has been PAUSED rather than released: its side effects may have completed in full,',
133
+ 'and re-firing would enact them a second time. Determine whether the work actually landed, then either',
134
+ '`crtr cron run` it to redo it deliberately, or `crtr cron cancel` it.',
135
+ ].join(' ');
136
+ }
@@ -0,0 +1,20 @@
1
+ import { getCron } from '../../core/canvas/crons.js';
2
+ // Exit 75 parks an owed occurrence; the daemon honors the gate but does not implement it.
3
+ export const EXIT_HELD = 75;
4
+ export const HELD_DELIVERED = 'deferred (exit 75) — held for poke';
5
+ // A held one-shot without expiry is poke-only; leaving it past due would re-fire every tick.
6
+ const HELD_ONE_SHOT_FAR_FUTURE = '9999-12-31T23:59:59.999Z';
7
+ // Re-read `last_poke_at`: a poke can land while the gate check runs.
8
+ export async function decideHeldSettle(c, startedAtIso, finishedAtMs) {
9
+ const fresh = await getCron(c.cron_id);
10
+ if (fresh === null)
11
+ return undefined;
12
+ if (fresh.state === 'active' && fresh.last_poke_at !== null && startedAtIso < fresh.last_poke_at) {
13
+ // A mid-run poke cannot unpark a lease, so re-due an active row; paused rows must remain parked.
14
+ return { kind: 'redue', nowIso: new Date(finishedAtMs).toISOString() };
15
+ }
16
+ if (c.recur != null) {
17
+ return { kind: 'park' };
18
+ }
19
+ return { kind: 'park', fireAt: fresh.expires_at ?? HELD_ONE_SHOT_FAR_FUTURE };
20
+ }
@@ -0,0 +1,177 @@
1
+ // src/daemon/cron/machine-fire.ts — the control plane's side of a cron whose profile's environment is a machine (design-import I13).
2
+ // On a cloud role `startCron` sends such a cron to the machine as a leased `cron.run` call instead of spawning it here.
3
+ //
4
+ // Exactly once: the cron run id (`CRTR_RUN_ID`) is minted once per fire and every send of that fire carries it. The Mac records the id
5
+ // before it spawns (`machine-exec.ts`), so a send that follows a dropped link returns the first send's result instead of running the
6
+ // command again. A scheduled fire whose machine has no live link at its due time is not claimed at all and stays due. A fire that was
7
+ // claimed stays owed under its run id across an outage of any length: it is sent again until the machine answers, and a control plane
8
+ // that crashed after claiming picks the same run id up from the cron row (`resumeMachineFire`) instead of calling the run crashed.
9
+ import { randomUUID } from 'node:crypto';
10
+ import { setTimeout as delay } from 'node:timers/promises';
11
+ import { openDb } from '../../core/canvas/db.js';
12
+ import { isCloudRole } from '../../core/canvas/person.js';
13
+ import { withCanvasWrite } from '../../core/canvas/db.js';
14
+ import { getNode } from '../../core/canvas/canvas.js';
15
+ import { callMachine } from '../../core/runtime/runner/machine/call.js';
16
+ import { machineEnvironmentOfNode } from '../../core/runtime/runner/machine/runner.js';
17
+ import { machineEnvironmentOfProfile } from '../../core/runtime/runner/machine/environment.js';
18
+ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '../../core/runtime/runner/machine/ops.js';
19
+ import { environmentSecrets } from '../../core/secrets/environment-secrets.js';
20
+ import { profileInApp } from '../../core/secrets/environment-owner.js';
21
+ import { getCron } from '../../core/canvas/crons.js';
22
+ import { emitEvent } from '../../core/events/emit.js';
23
+ import { runTokenFor } from './run-token.js';
24
+ import { parseArmedEnv } from './armed-context.js';
25
+ import { CRON_OUTPUT_HEAD_BYTES } from './capture.js';
26
+ import { settleClosedRun, settleUnspawnedRun } from './closed.js';
27
+ import { clearLiveRun, registerLiveRun } from './live-runs.js';
28
+ import { advanceRecurrence } from './recurrence.js';
29
+ /** Seconds past the run's timeout a send waits for its answer. */
30
+ const ANSWER_SLACK_S = 15;
31
+ const RESEND_EVERY_MS = 2_000;
32
+ /** The machine environment a cron runs on, or null when it runs here (a Mac's own daemon, a cron with no profile, a Blaxel profile). */
33
+ export async function machineEnvironmentOfCron(c) {
34
+ if (!isCloudRole() || c.profile == null)
35
+ return null;
36
+ return await machineEnvironmentOfProfile(c.profile);
37
+ }
38
+ export async function machineLinkLive(environmentId) {
39
+ return (await (await openDb()).prepare('SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?').get(environmentId, new Date().toISOString())) !== undefined;
40
+ }
41
+ /** The env the machine adds to its own: the profile's and app's stored variables (never the deployment's, which are the control plane's), the armed `--env`, and the cron's ids. */
42
+ async function prepareRun(c, runId) {
43
+ const profile = c.profile;
44
+ const row = await (await openDb()).prepare('SELECT person FROM profiles WHERE id = ?').get(profile);
45
+ if (row === undefined)
46
+ throw new Error(`profile ${profile} of cron ${c.cron_id} is not in the control plane`);
47
+ const secrets = await environmentSecrets({ person: row.person, app: c.grantee, ownerProfile: profile, ownerProfileInApp: await profileInApp(profile, c.grantee), includeDeployment: false });
48
+ const isTerminal = c.grantee === 'app:terminal';
49
+ const anchor = c.anchor_node != null ? await getNode(c.anchor_node) : null;
50
+ const env = { ...secrets, ...parseArmedEnv(c.env_json), ...(isTerminal ? { CRTR_PROFILE_ID: profile } : {}), CRTR_CRON_ID: c.cron_id, CRTR_CRON_NAME: c.name, CRTR_RUN_ID: runId, CRTR_API_TOKEN: runTokenFor(runId),
51
+ ...(c.anchor_node != null ? { CRTR_ANCHOR: c.anchor_node } : {}) };
52
+ return { env, grantee: c.grantee, profileId: profile, contextAnchor: anchor === null ? null : { node: anchor.node_id, grantee: anchor.grantee ?? c.grantee } };
53
+ }
54
+ /** One send of the fire: a leased `cron.run` call. Throws MachineOfflineError, MachineLostError or MachineCallFailedError. */
55
+ export async function sendCronRun(c, environmentId, runId, prepared) {
56
+ const waitMs = (c.run_timeout_s + ANSWER_SLACK_S) * 1000;
57
+ return await callMachine(environmentId, 'cron.run', { runId, cronId: c.cron_id, command: c.command, cwd: c.cwd, ...prepared, timeoutS: c.run_timeout_s,
58
+ leaseExpiresAt: new Date(Date.now() + waitMs).toISOString() }, { timeoutMs: waitMs });
59
+ }
60
+ /** Owe the machine a cancel of this run. The call is queued without a link check: an offline machine takes it when its link returns
61
+ * (the machine's own record of the run id decides whether that stops a running command or keeps a late `cron.run` from starting). */
62
+ export async function queueCronCancel(environmentId, runId) {
63
+ await queueMachineCall(environmentId, 'cron.cancel', { runId });
64
+ }
65
+ /** Owe the Mac a stop of this background job's process tree, queued the same way; a job the Mac no longer knows is a no-op there.
66
+ * Nothing is queued for a node that does not run on a machine environment. */
67
+ export async function queueJobStop(node, job) {
68
+ const environmentId = await machineEnvironmentOfNode(node);
69
+ if (environmentId !== null)
70
+ await queueMachineCall(environmentId, 'job.stop', { node, job });
71
+ }
72
+ async function queueMachineCall(environmentId, op, args) {
73
+ await withCanvasWrite(async (db) => {
74
+ await db.prepare('INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)')
75
+ .run(randomUUID(), environmentId, op, JSON.stringify(args), new Date().toISOString());
76
+ await db.prepare('SELECT pg_notify(?, ?)').get('crtr_signal', `machine:${environmentId}`);
77
+ });
78
+ }
79
+ /** Fire `c` on its machine and settle the run. Resolves with the settled record, or null when the cron ended while the run was owed.
80
+ * The caller holds the cron's run lease and has already passed the authority and start checks; `admit` runs once the run is registered. */
81
+ export async function fireOnMachine(c, fire, admit) {
82
+ const { runId, outOfBand, startedAtIso, startedAtMs } = fire;
83
+ let prepared;
84
+ try {
85
+ if (c.isolated)
86
+ throw new Error('an isolated cron needs a root launcher, which a machine does not have');
87
+ prepared = await prepareRun(c, runId);
88
+ if (!outOfBand && c.recur != null) {
89
+ const recurrenceError = await advanceRecurrence(c, startedAtMs);
90
+ if (recurrenceError !== null)
91
+ throw recurrenceError;
92
+ }
93
+ }
94
+ catch (err) {
95
+ return await settleUnspawnedRun(c, { runId, outOfBand, startedAtIso, startedAtMs }, 'run could not be armed', err);
96
+ }
97
+ return await driveFire(c, fire, prepared, admit);
98
+ }
99
+ /** A control plane that took a cron's run lease over from one that ended mid-fire: the same run id goes to the machine again, so the machine
100
+ * returns the stored result or joins the live run. A fresh id is never minted for this occurrence. Resolves with the settled record. */
101
+ export async function resumeMachineFire(c, environmentId) {
102
+ const runId = c.run_execution_id;
103
+ const startedAtIso = c.run_started_at;
104
+ const startedAtMs = Date.parse(startedAtIso);
105
+ const outOfBand = c.run_out_of_band;
106
+ const fire = { environmentId, runId, outOfBand, startedAtIso, startedAtMs };
107
+ let prepared;
108
+ try {
109
+ prepared = await prepareRun(c, runId);
110
+ // The crashed life may have died before it advanced the slot; advancing is idempotent (a recurrence already moved past this start stays).
111
+ if (!outOfBand && c.recur != null && Date.parse(c.fire_at) <= startedAtMs) {
112
+ const recurrenceError = await advanceRecurrence(c, startedAtMs);
113
+ if (recurrenceError !== null)
114
+ throw recurrenceError;
115
+ }
116
+ }
117
+ catch (err) {
118
+ return await settleUnspawnedRun(c, fire, 'run could not be armed', err);
119
+ }
120
+ return await driveFire(c, fire, prepared, () => undefined);
121
+ }
122
+ async function driveFire(c, fire, prepared, admit) {
123
+ const { environmentId, runId, outOfBand, startedAtIso, startedAtMs } = fire;
124
+ const live = { runId, replaced: false, selfCanceled: false, kill: () => {
125
+ void queueCronCancel(environmentId, runId).catch((error) => {
126
+ emitEvent({ level: 'error', event: 'cron.machine.cancel_failed', error, fields: { cron_id: c.cron_id, run_id: runId } });
127
+ });
128
+ } };
129
+ registerLiveRun(c.cron_id, live);
130
+ admit();
131
+ try {
132
+ let result = null;
133
+ let failure = null;
134
+ while (result === null && failure === null) {
135
+ try {
136
+ const answer = await sendCronRun(c, environmentId, runId, prepared);
137
+ if (answer.notStarted !== true) {
138
+ result = answer;
139
+ break;
140
+ }
141
+ emitEvent({ level: 'warn', event: 'cron.machine.resend', fields: { cron_id: c.cron_id, run_id: runId, why: answer.stderrHead } });
142
+ }
143
+ catch (error) {
144
+ if (error instanceof MachineCallFailedError) {
145
+ failure = error;
146
+ break;
147
+ }
148
+ if (!(error instanceof MachineOfflineError) && !(error instanceof MachineLostError))
149
+ throw error;
150
+ // A manual run is answered at once: the person is waiting and nothing ran. A scheduled fire stays owed under its run id, for as long as it takes.
151
+ if (outOfBand && error instanceof MachineOfflineError) {
152
+ failure = error;
153
+ break;
154
+ }
155
+ emitEvent({ level: 'warn', event: 'cron.machine.resend', fields: { cron_id: c.cron_id, run_id: runId, why: error.message } });
156
+ }
157
+ // The cron ended while this run was owed: its cancel is queued for the machine, and there is nothing left to settle against.
158
+ if (!live.selfCanceled && await getCron(c.cron_id) === null)
159
+ return null;
160
+ await delay(RESEND_EVERY_MS);
161
+ }
162
+ if (failure !== null)
163
+ return await settleUnspawnedRun(c, { runId, outOfBand, startedAtIso, startedAtMs }, 'run failed on the machine', failure);
164
+ const { exitCode, stdoutHead, stderrHead, durationMs, stdoutSha256 } = result;
165
+ const timedOut = exitCode === -1;
166
+ const processError = exitCode === null ? new Error((stderrHead ?? 'the machine reported no exit').slice(0, CRON_OUTPUT_HEAD_BYTES)) : null;
167
+ const wasReplaced = live.replaced;
168
+ const wasSelfCanceled = live.selfCanceled;
169
+ return await settleClosedRun(c, {
170
+ runId, outOfBand, startedAtIso, startedAtMs, finishedAtMs: startedAtMs + durationMs, code: timedOut ? null : exitCode, timedOut, processError,
171
+ stdoutHead: stdoutHead ?? '', stderrHead: stderrHead ?? '', stdoutSha256, wasReplaced, wasSelfCanceled,
172
+ });
173
+ }
174
+ finally {
175
+ clearLiveRun(c.cron_id, runId);
176
+ }
177
+ }
@@ -0,0 +1,34 @@
1
+ // src/daemon/cron/narrowed.ts — a scheduled fire refused by the cron authority check that paused
2
+ // the cron. Whoever armed it is told, so the work does not stop silently. Scopes are never widened here.
3
+ import { getNode } from '../../core/canvas/canvas.js';
4
+ import { newNodeId } from '../../core/runtime/nodes.js';
5
+ import { resolveLiveProfileName } from './armed-context.js';
6
+ import { canTakeMail } from './ended.js';
7
+ /** The notice for a cron paused by a refused fire: mail to the node that armed it while that node can still take mail,
8
+ * otherwise a human ticket. `message` is the refusal. */
9
+ export async function narrowedNotice(c, message) {
10
+ const creator = c.created_by === null ? null : await getNode(c.created_by);
11
+ const body = [
12
+ `Cron "${c.name}" (${c.cron_id}) was paused: ${message}.`,
13
+ '',
14
+ 'Its scheduled fire was refused by the authority check, so it did not run. The cron will not fire again until you act. Nothing was widened.',
15
+ '',
16
+ `- To keep it: fix what the refusal names (for a lost scope, restore it on the grant), then \`crtr cron resume ${c.cron_id}\`.`,
17
+ `- To drop it: \`crtr cron cancel ${c.cron_id}\`, and arm the cron again if the work still matters.`,
18
+ ].join('\n');
19
+ const label = `⏰ cron ${c.name} paused: fire refused`;
20
+ // A waking mail to the node a cancel-on-wake cron is anchored to would delete this cron, so that one goes to a human.
21
+ const wakeWouldDelete = c.cancel_on_wake && c.anchor_node === creator?.node_id;
22
+ if (creator !== null && !wakeWouldDelete && await canTakeMail(creator)) {
23
+ return { kind: 'node', destinationNodeId: creator.node_id, senderNodeId: null, label, stdout: body, urgency: 'urgent' };
24
+ }
25
+ return {
26
+ kind: 'action',
27
+ adapter: {
28
+ adapter: 'cron_human', cronId: c.cron_id, requestId: await newNodeId(), title: label,
29
+ summary: `A scheduled cron was paused because its fire was refused.`, sessionName: `cron ${c.name} (${c.cron_id})`,
30
+ profileName: resolveLiveProfileName(c) ?? null,
31
+ },
32
+ bodyJson: { stdout: body },
33
+ };
34
+ }
@@ -0,0 +1,38 @@
1
+ // src/daemon/cron/recurrence.ts — the crash-safe step before a scheduled run: a recurrence moves to its next slot.
2
+ import { advanceCron, setCronState } from '../../core/canvas/crons.js';
3
+ import { emitEvent } from '../../core/events/emit.js';
4
+ import { nextSlotAfter } from '../../core/wake.js';
5
+ /** Settle the schedule BEFORE the run: a recurrence advances to its next slot
6
+ * now, so a crash mid-run never re-fires this slot (the lease guards the
7
+ * intra-life overlap; the advanced fire_at guards the crash window).
8
+ *
9
+ * Returns the process error to hand `close` when the recurrence cannot be
10
+ * parsed, else null. That row can never be scheduled again as written — but
11
+ * DELETING it would destroy the user's config AND its whole run history with
12
+ * no record and no escalation, the one outcome the spec has no vocabulary for.
13
+ * It takes the failure path instead, so the row PAUSES and an escalation node
14
+ * arrives holding the parse error. `fire_at` is deliberately left past-due: a
15
+ * paused row is not due, and once someone fixes the recurrence a `cron resume`
16
+ * fires immediately. */
17
+ export async function advanceRecurrence(c, startedAtMs) {
18
+ let nextFire;
19
+ try {
20
+ nextFire = nextSlotAfter(c.recur, new Date(startedAtMs));
21
+ }
22
+ catch (err) {
23
+ emitEvent({
24
+ level: 'error',
25
+ event: 'cron.recur.unparseable',
26
+ error: err,
27
+ fields: { cron_id: c.cron_id, name: c.name, recur: c.recur },
28
+ });
29
+ // Pause HERE, not only via the escalation: `fire_at` was never advanced, so
30
+ // an on_output='silent' row (whose failure path never escalates and never
31
+ // pauses) would otherwise re-fire this unschedulable command on every
32
+ // single tick, forever.
33
+ await setCronState(c.cron_id, 'paused');
34
+ return new Error(`unparseable recurrence ${JSON.stringify(c.recur)}: ${err.message} — this cron cannot be rescheduled until its recurrence is fixed (\`crtr cron cancel\` and re-arm it), so it has been paused.`);
35
+ }
36
+ await advanceCron(c.cron_id, nextFire);
37
+ return null;
38
+ }
@@ -0,0 +1,37 @@
1
+ // src/daemon/cron/run-token.ts — the bearer a machine cron's `crtr` calls carry (proposal-mac-cli-auth, option R1).
2
+ // `crtr_run_<run id>.<hex HMAC of the run id under the secrets key>`: derived, never stored, so a resend of the same fire carries the same
3
+ // token. The control plane accepts it only while the cron row names that run as running, and answers as the same `cron` principal
4
+ // `run-socket.ts` builds for a local run.
5
+ import { createHmac, timingSafeEqual } from 'node:crypto';
6
+ import { openDb } from '../../core/canvas/db.js';
7
+ import { getCron } from '../../core/canvas/crons.js';
8
+ import { loadSecretsKey } from '../../core/secrets/key.js';
9
+ export const RUN_TOKEN_PREFIX = 'crtr_run_';
10
+ const mac = (runId) => createHmac('sha256', loadSecretsKey().key).update(`cron-run:${runId}`).digest('hex');
11
+ export const runTokenFor = (runId) => `${RUN_TOKEN_PREFIX}${runId}.${mac(runId)}`;
12
+ /** The run id a well-formed token with a valid MAC names, else null. */
13
+ export function runIdOfToken(token) {
14
+ if (!token.startsWith(RUN_TOKEN_PREFIX))
15
+ return null;
16
+ const body = token.slice(RUN_TOKEN_PREFIX.length);
17
+ const dot = body.lastIndexOf('.');
18
+ if (dot <= 0)
19
+ return null;
20
+ const runId = body.slice(0, dot);
21
+ const given = Buffer.from(body.slice(dot + 1));
22
+ const expected = Buffer.from(mac(runId));
23
+ return given.length === expected.length && timingSafeEqual(given, expected) ? runId : null;
24
+ }
25
+ /** The cron principal of the run `token` names, or null when the token is invalid or the run is no longer the cron's running one. */
26
+ export async function cronPrincipalForRunToken(token) {
27
+ const runId = runIdOfToken(token);
28
+ if (runId === null)
29
+ return null;
30
+ const row = await (await openDb()).prepare("SELECT cron_id FROM crons WHERE run_execution_id = ? AND run_state = 'running'").get(runId);
31
+ const c = row === undefined ? null : await getCron(row.cron_id);
32
+ if (c === null || c.run_execution_id !== runId || c.run_state !== 'running')
33
+ return null;
34
+ // `uid` -1: no local peer. It is read only by the per-execution socket's own peer check and by broker-class handlers.
35
+ return { class: 'cron', kind: 'cron', cron: c.cron_id, app: c.grantee, sub: c.sub, grant: c.grant_id, scopes: c.scopes, execution: runId, from_exec: c.armed_from_exec,
36
+ origin_run: c.origin_run_id, isolated: c.isolated, anchor: c.anchor_node, uid: -1 };
37
+ }
@@ -0,0 +1,78 @@
1
+ import { consumeCron, recordCronRunLocked, releaseCronRunLease, setCronState, } from '../../core/canvas/crons.js';
2
+ import { withCanvasWrite } from '../../core/canvas/db.js';
3
+ import { enqueueDaemonAction } from '../../core/canvas/daemon-actions.js';
4
+ import { enqueueNodeMail } from '../../core/feed/messages.js';
5
+ import { emitEvent } from '../../core/events/emit.js';
6
+ import { narrowedNotice } from './narrowed.js';
7
+ import { disposeSettledRun } from './disposition.js';
8
+ function occurrenceStaysOwed(lease) {
9
+ return typeof lease === 'object' && (lease.kind === 'park' || lease.kind === 'redue');
10
+ }
11
+ export async function settleRun(c, input) {
12
+ const { outOfBand, outcome, record, lease } = input;
13
+ let delivered;
14
+ let paused;
15
+ let obligation;
16
+ if (outcome.kind === 'disposed') {
17
+ const disposition = await disposeSettledRun(c, outcome.ctx, outOfBand, outcome.selfCanceled ?? false);
18
+ delivered = disposition.delivered;
19
+ paused = disposition.paused;
20
+ obligation = disposition.obligation;
21
+ }
22
+ else if (outcome.kind === 'refused') {
23
+ delivered = `refused: ${outcome.reason}`;
24
+ // A narrowed scope never comes back on its own, so a recurring cron is paused too. Whatever pauses a cron, its armer is told.
25
+ const narrowed = !outOfBand && outcome.reason === 'scope_narrowed';
26
+ paused = !outOfBand && (c.recur == null || narrowed);
27
+ if (paused)
28
+ await setCronState(c.cron_id, 'paused');
29
+ if (paused)
30
+ obligation = await narrowedNotice(c, outcome.message);
31
+ emitEvent({
32
+ level: 'warn',
33
+ event: 'cron.fire.refused',
34
+ fields: { cron_id: c.cron_id, execution_id: record.runId, grant_id: c.grant_id, reason: outcome.reason, out_of_band: outOfBand },
35
+ });
36
+ }
37
+ else {
38
+ delivered = outcome.delivered;
39
+ paused = outcome.paused ?? false;
40
+ }
41
+ const written = await withCanvasWrite(async (db) => {
42
+ if (obligation !== undefined) {
43
+ if (obligation.kind === 'node') {
44
+ const enqueued = await enqueueNodeMail(obligation.destinationNodeId, {
45
+ kind: 'message', label: obligation.label, senderNodeId: obligation.senderNodeId,
46
+ bodyJson: { body: obligation.stdout }, urgency: obligation.urgency, wake: 1,
47
+ idempotencyKey: record.runId,
48
+ });
49
+ if (outcome.kind !== 'refused')
50
+ delivered = `delivered: ${enqueued.deliveryId}`;
51
+ }
52
+ else if (obligation.kind === 'action') {
53
+ const actionId = await enqueueDaemonAction({ adapter: obligation.adapter, bodyJson: obligation.bodyJson, idempotencyKey: record.runId });
54
+ if (outcome.kind !== 'refused')
55
+ delivered = `delivered: ${actionId}`;
56
+ }
57
+ }
58
+ const entry = {
59
+ run_id: record.runId,
60
+ cron_id: c.cron_id,
61
+ started: record.startedAtIso,
62
+ finished: new Date(record.finishedAtMs).toISOString(),
63
+ duration_ms: record.durationMs,
64
+ exit_code: record.exitCode,
65
+ stdout_head: record.stdoutHead,
66
+ stderr_head: record.stderrHead,
67
+ delivered,
68
+ };
69
+ await recordCronRunLocked(db, entry);
70
+ return entry;
71
+ });
72
+ if (lease !== 'none')
73
+ await releaseCronRunLease(c.cron_id, record.runId, lease === 'release' ? undefined : lease);
74
+ // Retain out-of-band, paused, and held rows; their occurrence is not spent.
75
+ if (!outOfBand && c.recur == null && !paused && !occurrenceStaysOwed(lease))
76
+ await consumeCron(c.cron_id);
77
+ return written;
78
+ }
@@ -0,0 +1,70 @@
1
+ import { newNodeId } from '../../core/runtime/nodes.js';
2
+ import { nodeAgentDir } from '../../core/canvas/node-agent-paths.js';
3
+ import { getNode } from '../../core/canvas/canvas.js';
4
+ import { parseCronSink } from '../../core/canvas/crons.js';
5
+ import { hasNoNaturalCycle } from '../../core/runtime/revive-all.js';
6
+ import { isParked } from '../../core/runtime/lifecycle.js';
7
+ import { cronWakeOrigin } from '../../core/runtime/bearings.js';
8
+ import { emitEvent } from '../../core/events/emit.js';
9
+ import { cronBirthPrincipalOf, resolveLiveProfile, resolveLiveProfileName } from './armed-context.js';
10
+ import { checkCronBirth } from './authority.js';
11
+ /** Resolve a completed run into a durable obligation. No sink effect happens here. */
12
+ export async function resolveCronSink(c, runId, stdout) {
13
+ const sink = parseCronSink(c.sink);
14
+ if (sink === null)
15
+ return { kind: 'none', delivered: 'no sink armed — nothing delivered' };
16
+ if (sink.kind === 'node') {
17
+ const meta = await getNode(sink.node);
18
+ if (meta === null)
19
+ throw new Error(`node sink ${sink.node} is gone`);
20
+ if (hasNoNaturalCycle(meta) && !isParked(meta)) {
21
+ throw new Error(`node sink ${sink.node} has no natural cycle ahead (done or finalized)`);
22
+ }
23
+ return {
24
+ kind: 'node',
25
+ destinationNodeId: sink.node,
26
+ senderNodeId: c.created_by !== null && await getNode(c.created_by) !== null ? c.created_by : null,
27
+ label: `⏰ cron ${c.name}`,
28
+ stdout,
29
+ urgency: c.tier,
30
+ };
31
+ }
32
+ if (sink.kind === 'spawn') {
33
+ // The birth is checked now so a refused one settles this run `refused` (no escalation), and
34
+ // again when the action is delivered.
35
+ const stored = cronBirthPrincipalOf(c);
36
+ const authority = await checkCronBirth(stored, { kind: sink.spawn, cwd: c.cwd, profile: resolveLiveProfile(c) });
37
+ if (!authority.allowed) {
38
+ emitEvent({ level: 'warn', event: 'cron.birth.refused', fields: { cron_id: c.cron_id, grant_id: c.grant_id, reason: authority.reason, stage: 'enqueue' } });
39
+ return { kind: 'none', delivered: `refused: ${authority.reason}`, refused: true };
40
+ }
41
+ const principal = { ...stored, scopes: authority.scopes };
42
+ const nodeId = await newNodeId();
43
+ const prompt = [
44
+ `Scheduled cron "${c.name}" (${c.cron_id}) fired and delivered its output to you as your kickoff.`,
45
+ '',
46
+ '## Command output',
47
+ '',
48
+ stdout,
49
+ ].join('\n');
50
+ return {
51
+ kind: 'action',
52
+ adapter: {
53
+ adapter: 'cron_spawn', cronId: c.cron_id, nodeId, kind: sink.spawn,
54
+ cwd: c.isolated ? await nodeAgentDir(nodeId, c.grantee) : c.cwd, isolated: c.isolated,
55
+ principal,
56
+ profile: resolveLiveProfile(c), wakeOrigin: await cronWakeOrigin(c, 'node_birth'), prompt,
57
+ },
58
+ bodyJson: { runId, stdout },
59
+ };
60
+ }
61
+ return {
62
+ kind: 'action',
63
+ adapter: {
64
+ adapter: 'cron_human', cronId: c.cron_id, requestId: await newNodeId(), title: `⏰ cron ${c.name}`,
65
+ summary: `Scheduled cron "${c.name}" delivered output for your attention.`, sessionName: `cron ${c.name} (${c.cron_id})`,
66
+ profileName: resolveLiveProfileName(c) ?? null,
67
+ },
68
+ bodyJson: { runId, stdout },
69
+ };
70
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.670",
3
+ "version": "0.3.671",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.670",
3
+ "version": "0.3.671",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.670",
3
+ "version": "0.3.671",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.670",
31
- "@north-light/identity": "0.3.670"
30
+ "@north-light/api": "0.3.671",
31
+ "@north-light/identity": "0.3.671"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {