@north-light/cli 0.3.708 → 0.3.710

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 (162) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/crons.d.ts +3 -0
  4. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  5. package/dist/clients/attach/chrome/roster.js +6 -6
  6. package/dist/clients/attach/chrome/status-line.d.ts +1 -1
  7. package/dist/clients/attach/chrome/status-line.js +1 -1
  8. package/dist/clients/attach/input/capabilities.js +1 -1
  9. package/dist/clients/attach/input/controller.d.ts +4 -0
  10. package/dist/clients/attach/input/controller.js +3 -3
  11. package/dist/clients/attach/overlays/graph.d.ts +3 -2
  12. package/dist/clients/attach/overlays/graph.js +1 -1
  13. package/dist/clients/attach/render/chat-view.d.ts +2 -0
  14. package/dist/clients/attach/render/chat-view.js +1 -1
  15. package/dist/clients/attach/render/doc-links.d.ts +1 -1
  16. package/dist/clients/attach/session/chrome-refresh.js +1 -1
  17. package/dist/clients/attach/session/connection.d.ts +10 -9
  18. package/dist/clients/attach/session/connection.js +1 -1
  19. package/dist/clients/attach/session/context.d.ts +1 -1
  20. package/dist/clients/attach/session/document-links.d.ts +1 -1
  21. package/dist/clients/attach/session/document-links.js +1 -1
  22. package/dist/clients/attach/session/identity.d.ts +2 -0
  23. package/dist/clients/attach/session/identity.js +1 -1
  24. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  25. package/dist/clients/attach/session/input-wiring.js +1 -1
  26. package/dist/clients/attach/session/keys.d.ts +2 -0
  27. package/dist/clients/attach/session/keys.js +1 -1
  28. package/dist/clients/attach/session/layout-record.d.ts +13 -0
  29. package/dist/clients/attach/session/layout-record.js +1 -0
  30. package/dist/clients/attach/session/pane-tag.d.ts +3 -1
  31. package/dist/clients/attach/session/pane-tag.js +1 -1
  32. package/dist/clients/attach/session/reconnect.js +1 -1
  33. package/dist/clients/attach/session/teardown.d.ts +4 -2
  34. package/dist/clients/attach/session/teardown.js +9 -7
  35. package/dist/clients/attach/slash/dispatch.js +2 -2
  36. package/dist/clients/attach/slash/recover.d.ts +10 -0
  37. package/dist/clients/attach/slash/recover.js +2 -0
  38. package/dist/clients/attach/viewer.d.ts +7 -5
  39. package/dist/clients/attach/viewer.js +563 -558
  40. package/dist/commands/node/wait.js +2 -6
  41. package/dist/core/broker-client/client.d.ts +6 -3
  42. package/dist/core/broker-client/client.js +1 -1
  43. package/dist/core/canvas/crons.d.ts +11 -1
  44. package/dist/core/canvas/crons.js +14 -14
  45. package/dist/core/canvas/executions.js +1 -1
  46. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
  47. package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
  48. package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
  49. package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
  50. package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
  51. package/dist/core/canvas/schema-version.d.ts +1 -1
  52. package/dist/core/canvas/schema-version.js +1 -1
  53. package/dist/core/command.js +5 -5
  54. package/dist/core/feed/messages.d.ts +5 -0
  55. package/dist/core/feed/messages.js +5 -5
  56. package/dist/core/runtime/bearings.js +4 -4
  57. package/dist/core/runtime/boot-root.js +4 -4
  58. package/dist/core/runtime/broker-request.d.ts +2 -0
  59. package/dist/core/runtime/broker-request.js +1 -1
  60. package/dist/core/runtime/broker.js +1 -1
  61. package/dist/core/runtime/lifecycle.js +2 -2
  62. package/dist/core/runtime/model-swap.d.ts +2 -1
  63. package/dist/core/runtime/model-swap.js +1 -1
  64. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  65. package/dist/core/runtime/placement-tmux.js +1 -1
  66. package/dist/core/runtime/revive.js +2 -2
  67. package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
  68. package/dist/core/runtime/runner/blaxel/client.js +1 -1
  69. package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
  70. package/dist/core/runtime/runner/blaxel/runner.js +3 -3
  71. package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
  72. package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
  73. package/dist/core/runtime/runner/machine/call.js +2 -2
  74. package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
  75. package/dist/core/runtime/runner/machine/ops.js +1 -1
  76. package/dist/core/runtime/runner/types.d.ts +19 -3
  77. package/dist/core/runtime/tmux-driver.d.ts +7 -0
  78. package/dist/core/runtime/tmux-driver.js +6 -6
  79. package/dist/core/worktree-machine.d.ts +4 -1
  80. package/dist/core/worktree-machine.js +1 -1
  81. package/dist/core/worktree-sweep.d.ts +14 -3
  82. package/dist/core/worktree-sweep.js +4 -4
  83. package/dist/daemon/api/bridge.d.ts +5 -0
  84. package/dist/daemon/api/bridge.js +3 -3
  85. package/dist/daemon/api/handlers/crons.d.ts +2 -0
  86. package/dist/daemon/api/handlers/crons.js +1 -1
  87. package/dist/daemon/api/handlers/nodes.js +1 -1
  88. package/dist/daemon/api/operations.js +1 -1
  89. package/dist/daemon/cron/ended.d.ts +3 -0
  90. package/dist/daemon/cron/ended.js +2 -2
  91. package/dist/daemon/cron/lease-recovery.js +1 -1
  92. package/dist/daemon/cron/machine-fire.d.ts +9 -2
  93. package/dist/daemon/cron/machine-fire.js +1 -1
  94. package/dist/daemon/cron/passes.js +1 -1
  95. package/dist/daemon/cron-run.js +2 -2
  96. package/dist/daemon/fleet.d.ts +1 -1
  97. package/dist/daemon/fleet.js +4 -4
  98. package/dist/daemon/machine-link/client.js +1 -1
  99. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  100. package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
  101. package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
  102. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  103. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  104. package/dist/daemon/runs/observer.d.ts +4 -0
  105. package/dist/daemon/runs/observer.js +1 -1
  106. package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
  107. package/package.json +3 -3
  108. package/packages/crouter-api/dist/api/contract.js +1 -1
  109. package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
  110. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
  111. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
  112. package/packages/crouter-api/dist/clients/attach/input/capabilities.js +3 -1
  113. package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
  114. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
  115. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
  116. package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
  117. package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
  118. package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
  119. package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
  120. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
  121. package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
  122. package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
  123. package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
  124. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
  125. package/packages/crouter-api/dist/clients/attach/session/teardown.js +9 -4
  126. package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
  127. package/packages/crouter-api/dist/clients/attach/slash/recover.js +111 -0
  128. package/packages/crouter-api/dist/clients/attach/viewer.js +86 -31
  129. package/packages/crouter-api/dist/commands/node/wait.js +2 -10
  130. package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
  131. package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
  132. package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
  133. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  134. package/packages/crouter-api/dist/core/command.js +3 -0
  135. package/packages/crouter-api/dist/core/feed/messages.js +15 -0
  136. package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
  137. package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
  138. package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
  139. package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
  140. package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
  141. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  142. package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
  143. package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
  144. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
  145. package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
  146. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
  147. package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
  148. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
  149. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
  150. package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
  151. package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
  152. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  153. package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
  154. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
  155. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  156. package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
  157. package/packages/crouter-api/package.json +1 -1
  158. package/packages/crouter-identity/package.json +1 -1
  159. package/packages/crouter-plugin/package.json +3 -3
  160. package/runtime.lock.json +14 -14
  161. package/dist/core/runtime/starting-screen.d.ts +0 -12
  162. package/dist/core/runtime/starting-screen.js +0 -9
@@ -0,0 +1,439 @@
1
+ // The ONE authority that physically disposes of a managed worktree after its
2
+ // owning node is gone.
3
+ //
4
+ // Close, cancel, crash, and prune do not each grow a cleanup hook: they only
5
+ // change durable state, and this primitive derives everything it does from that
6
+ // state. It is idempotent and restartable, because Git effects and canvas
7
+ // metadata are not one transaction — a crash between any two steps is resumed
8
+ // by the next pass rather than repaired by hand.
9
+ //
10
+ // EVERY Git call here is `gitAsync`. This runs inside crtrd, whose event loop
11
+ // also drives broker supervision and the API socket; a `spawnSync` in this path
12
+ // would stall the whole daemon for the duration of every Git call, and a Git
13
+ // call on a large repository is not short.
14
+ import { createHash } from 'node:crypto';
15
+ import { existsSync, realpathSync } from 'node:fs';
16
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
17
+ import { completeCleanup, getNode, recordSweepAttempt, resumableNodeCwds } from './canvas/index.js';
18
+ import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
19
+ import { gitAsync } from './git.js';
20
+ import { proveBranchContained, upstreamTip } from './worktree-containment.js';
21
+ import { refDeleteTransactionStdin } from './worktree-landing.js';
22
+ import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
23
+ import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, samePath, worktreeLockPathForCommonDir } from './worktree.js';
24
+ /** Escalating recheck interval, in minutes, indexed by consecutive refusal. The
25
+ * last tier is the cap AND the quarantine threshold: at that point the record
26
+ * needs a human, so it is listed by `crtr sys worktrees` and costs one cheap
27
+ * fingerprint read an hour until something about it actually changes. */
28
+ const BACKOFF_MINUTES = [2, 5, 15, 30, 60];
29
+ const QUARANTINE_ATTEMPTS = BACKOFF_MINUTES.length;
30
+ /** A record this sweep still owns: open, or closed without proven cleanup. An
31
+ * abandoned record is deliberately out of scope — abandon already removed the
32
+ * checkout and retains its branch for a person on purpose. */
33
+ export function isReconcilable(wt) {
34
+ if (wt == null || wt.state === 'abandoned')
35
+ return false;
36
+ return wt.state === 'open' || wt.cleanup !== 'complete';
37
+ }
38
+ /** Whether the sweep should examine this record on a pass starting at `now`. A
39
+ * record with no recorded refusal is always due. */
40
+ export function isDueForSweep(wt, now) {
41
+ const next = wt.sweep?.next_attempt;
42
+ if (next === undefined)
43
+ return true;
44
+ const at = Date.parse(next);
45
+ return Number.isNaN(at) || at <= now;
46
+ }
47
+ // Git plumbing, all async
48
+ async function revParseRef(cwd, ref) {
49
+ const res = await gitAsync(['rev-parse', '--verify', '--quiet', ref], cwd);
50
+ return res.status === 0 ? res.stdout.trim() : null;
51
+ }
52
+ function detailOf(res) {
53
+ return (res.stderr.trim() || res.stdout.trim()).trim();
54
+ }
55
+ async function commonGitDirAsync(cwd) {
56
+ const res = await gitAsync(['rev-parse', '--git-common-dir'], cwd);
57
+ if (res.status !== 0)
58
+ return null;
59
+ try {
60
+ return realpathSync(resolve(cwd, res.stdout.trim()));
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }
66
+ async function isRebaseInProgressAsync(cwd) {
67
+ for (const logical of ['rebase-merge', 'rebase-apply']) {
68
+ const res = await gitAsync(['rev-parse', '--git-path', logical], cwd);
69
+ if (res.status !== 0)
70
+ return null;
71
+ if (existsSync(resolve(cwd, res.stdout.trim())))
72
+ return true;
73
+ }
74
+ return false;
75
+ }
76
+ /** The repository's main checkout, from a `git worktree list --porcelain` blob:
77
+ * Git always lists it first. Every administrative command runs from there, so
78
+ * removing a linked checkout never runs Git from inside the directory it is
79
+ * deleting. */
80
+ function mainWorktreePath(porcelain) {
81
+ for (const line of porcelain.split('\n')) {
82
+ if (line.startsWith('worktree '))
83
+ return line.slice('worktree '.length).trim();
84
+ }
85
+ return null;
86
+ }
87
+ /** Git's own spelling of the recorded checkout when it is registered to the
88
+ * recorded branch, else null. Ownership is a path IDENTITY question, not a
89
+ * string question — `samePath` resolves both spellings — and the answer is
90
+ * Git's canonical path so every later Git call names the checkout the way the
91
+ * repository's administrative metadata does. */
92
+ function registeredCheckoutPath(porcelain, path, branch) {
93
+ let current = null;
94
+ for (const line of porcelain.split('\n')) {
95
+ if (line.startsWith('worktree '))
96
+ current = line.slice('worktree '.length).trim();
97
+ else if (current !== null && line === `branch refs/heads/${branch}` && samePath(current, path))
98
+ return current;
99
+ }
100
+ return null;
101
+ }
102
+ // Content containment is shared with explicit close. A delivered branch is
103
+ // never rebased onto a local base merely because that base later diverged.
104
+ // Change detection
105
+ /** Base, upstream, and branch tips plus checkout state as they are right now.
106
+ * A pass that reads the same values as the refusal that preceded it can stop
107
+ * there: nothing that decided the refusal has moved. An unreadable checkout
108
+ * records `null`, which never compares equal, so uncertainty always re-proves. */
109
+ async function observe(wt) {
110
+ const present = existsSync(wt.path);
111
+ const cwd = present ? wt.path : wt.repo_root;
112
+ const base = await revParseRef(cwd, `refs/heads/${wt.base_ref}`);
113
+ const upstream = await upstreamTip(cwd, wt.base_ref);
114
+ const branch = await revParseRef(cwd, `refs/heads/${wt.branch}`);
115
+ if (!present)
116
+ return { base, upstream: upstream?.sha ?? null, branch, checkout: 'absent' };
117
+ const head = await gitAsync(['rev-parse', 'HEAD'], wt.path);
118
+ const status = await gitAsync(['status', '--porcelain'], wt.path);
119
+ const checkout = head.status !== 0 || status.status !== 0
120
+ ? null
121
+ : createHash('sha256').update(`${head.stdout.trim()}\n${status.stdout}`).digest('hex');
122
+ return { base, upstream: upstream?.sha ?? null, branch, checkout };
123
+ }
124
+ function sameObservation(a, b) {
125
+ if (a.checkout === null || b.checkout === null)
126
+ return false;
127
+ return a.base === b.base && a.upstream === b.upstream && a.branch === b.branch && a.checkout === b.checkout;
128
+ }
129
+ // Recording an unfinished pass
130
+ /** Persist why this pass did not finish, with the fingerprint it decided
131
+ * against and an escalated recheck time. This NEVER writes completion and
132
+ * never drops the authoritative record: the checkout, the branch, and the node
133
+ * metadata that proves who owns them all survive a refusal. */
134
+ async function recordUnfinished(nodeId, wt, outcome, observed, now, guard) {
135
+ if (outcome.status !== 'refused' && outcome.status !== 'failed')
136
+ return;
137
+ // A node that came back to life owns its own record again: backoff written
138
+ // from a pass it invalidated would sit on the revived node's metadata.
139
+ if (!await guard.stillEligible())
140
+ return;
141
+ const attempts = (wt.sweep?.attempts ?? 0) + 1;
142
+ const minutes = BACKOFF_MINUTES[Math.min(attempts, BACKOFF_MINUTES.length) - 1] ?? BACKOFF_MINUTES[0];
143
+ const current = (await getNode(nodeId))?.managed_worktree;
144
+ if (current == null || !isReconcilable(current))
145
+ return;
146
+ await recordSweepAttempt(nodeId, {
147
+ reason: outcome.reason,
148
+ ...(outcome.detail === undefined ? {} : { detail: outcome.detail }),
149
+ observed,
150
+ attempts,
151
+ lastAttemptAt: new Date(now).toISOString(),
152
+ nextAttemptAt: new Date(now + minutes * 60_000).toISOString(),
153
+ quarantined: attempts >= QUARANTINE_ATTEMPTS,
154
+ });
155
+ }
156
+ // Landing a blocked close the sweep is allowed to finish
157
+ /** Finish the land this node already asked for and was blocked on. The sweep
158
+ * reaches here ONLY for a record carrying `land_intent`: a node that crashed
159
+ * mid-work and never called close does not get its half-finished commits
160
+ * fast-forwarded onto a shared base branch. */
161
+ async function finishBlockedLand(wt, porcelain, guard) {
162
+ const baseSha = await revParseRef(wt.path, `refs/heads/${wt.base_ref}`);
163
+ if (baseSha === null)
164
+ return { ok: false, detail: `local base branch '${wt.base_ref}' does not resolve` };
165
+ if (!await guard.stillEligible())
166
+ return { ok: false, detail: 'node is no longer terminal', ineligible: true };
167
+ const rebase = await gitAsync(['rebase', baseSha], wt.path);
168
+ if (rebase.status !== 0) {
169
+ // A conflicted rebase must never be left in progress: the next pass would
170
+ // read a mid-operation checkout and refuse forever.
171
+ await gitAsync(['rebase', '--abort'], wt.path);
172
+ return { ok: false, detail: detailOf(rebase) };
173
+ }
174
+ const landedSha = await revParseRef(wt.path, 'HEAD');
175
+ if (landedSha === null)
176
+ return { ok: false, detail: 'could not read the rebased worktree tip' };
177
+ if ((await gitAsync(['merge-base', '--is-ancestor', baseSha, landedSha], wt.path)).status !== 0) {
178
+ return { ok: false, detail: `the rebased branch is not a fast-forward of '${wt.base_ref}'` };
179
+ }
180
+ const baseCheckout = checkoutPathForBranchInList(porcelain, wt.base_ref);
181
+ if (baseCheckout === null) {
182
+ if (!await guard.stillEligible())
183
+ return { ok: false, detail: 'node is no longer terminal', ineligible: true };
184
+ const update = await gitAsync(['update-ref', `refs/heads/${wt.base_ref}`, landedSha, baseSha], wt.path);
185
+ return update.status === 0 ? { ok: true, landedSha } : { ok: false, detail: detailOf(update) };
186
+ }
187
+ const head = await gitAsync(['rev-parse', 'HEAD'], baseCheckout);
188
+ if (head.status !== 0 || head.stdout.trim() !== baseSha) {
189
+ return { ok: false, detail: `base checkout ${baseCheckout} is not at ${baseSha}` };
190
+ }
191
+ if (!await guard.stillEligible())
192
+ return { ok: false, detail: 'node is no longer terminal', ineligible: true };
193
+ // Git carries disjoint uncommitted changes and refuses, changing nothing, on overlap.
194
+ const merged = await gitAsync(['merge', '--ff-only', landedSha], baseCheckout);
195
+ return merged.status === 0 ? { ok: true, landedSha } : { ok: false, detail: detailOf(merged) };
196
+ }
197
+ /** The one outcome for "the node came back" — never a failure, never recorded as
198
+ * a refusal, because nothing about the worktree is wrong. */
199
+ const NODE_REVIVED = { status: 'skipped', reason: 'node_no_longer_terminal' };
200
+ /** The one outcome for "another unfinished node runs inside this checkout".
201
+ * Like a revived owner it is not a defect of the worktree, so it is never
202
+ * recorded as a refusal: a recorded refusal carries a backoff, and the
203
+ * worktree's git state — what a recorded refusal is compared against — does not
204
+ * change when the dependent finishes. Each pass simply asks again. */
205
+ const CHECKOUT_IN_USE = { status: 'skipped', reason: 'checkout_in_use' };
206
+ function isWithinDirectory(root, path) {
207
+ const rel = relative(root, path);
208
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
209
+ }
210
+ /** Does any resumable node (one the runtime can still bring back to life) other than the owner have its cwd in `checkout`, or
211
+ * beneath it? Both spellings of each path are compared, because a recorded cwd
212
+ * keeps the spelling it was given while the checkout may be reached through a
213
+ * symlink, and a cwd that no longer exists can only be compared lexically. */
214
+ async function checkoutHasDependents(dependentCwds, checkout) {
215
+ const roots = [resolve(checkout), canonicalPath(checkout)];
216
+ return (await dependentCwds()).some((cwd) => {
217
+ const spellings = [resolve(cwd), canonicalPath(cwd)];
218
+ return roots.some((root) => spellings.some((spelling) => isWithinDirectory(root, spelling)));
219
+ });
220
+ }
221
+ /** Dispose of one node's managed worktree, or explain why it must survive.
222
+ *
223
+ * Ownership is proved from crouter's own node record, never from
224
+ * `git worktree list`: a checkout the user or another tool created has no node
225
+ * record and is never reachable from here. Under the repository lock the
226
+ * recorded path is confirmed REGISTERED to the recorded branch — a path match
227
+ * alone is not ownership — and removal is `git worktree remove <recorded
228
+ * path>` without `--force`. `git worktree prune` is never run: it is
229
+ * repo-wide and would touch administrative entries for worktrees crouter does
230
+ * not own.
231
+ *
232
+ * Effects are ordered checkout → branch → metadata so every interruption is
233
+ * resumable: a crash before removal retries from pending; after removal but
234
+ * before the branch delete, the branch is still an intact ref the next pass
235
+ * finds; after both, the next pass observes both absent and marks complete. */
236
+ export async function reconcileManagedWorktree(nodeId, guard, now = Date.now(), host) {
237
+ const wt = (await getNode(nodeId))?.managed_worktree;
238
+ if (!isReconcilable(wt) || wt == null)
239
+ return { status: 'skipped', reason: 'already_reconciled' };
240
+ const { outcome, observed, trash } = host === undefined
241
+ ? await sweepManagedWorktreeOnHost(wt, guard, async () => (await resumableNodeCwds(nodeId)).map(({ cwd }) => cwd))
242
+ : await host(wt, (await resumableNodeCwds(nodeId)).map(({ cwd }) => cwd));
243
+ if (host === undefined)
244
+ await deleteTrashAsync(wt.path, trash);
245
+ if (outcome.status === 'complete')
246
+ return await persistComplete(nodeId, wt, guard);
247
+ await recordUnfinished(nodeId, wt, outcome, observed, now, guard);
248
+ return outcome;
249
+ }
250
+ /** The sweep's Git work on the computer that holds the checkout, with no database: `complete` here means the checkout and branch are
251
+ * gone; the caller writes the rows. */
252
+ export async function sweepManagedWorktreeOnHost(wt, guard, dependentCwds) {
253
+ const none = { base: null, upstream: null, branch: null, checkout: null };
254
+ // Checked before any Git call so a checkout that stays in use costs one query
255
+ // per pass. The decision that counts is made again under the lock, immediately
256
+ // before each removal, where spawn admission into the checkout is excluded.
257
+ if (existsSync(wt.path) && await checkoutHasDependents(dependentCwds, wt.path))
258
+ return { outcome: CHECKOUT_IN_USE, observed: none };
259
+ const cwd = existsSync(wt.path) ? wt.path : wt.repo_root;
260
+ if (!existsSync(cwd)) {
261
+ return { outcome: { status: 'refused', reason: 'repo_unavailable', detail: `neither the recorded checkout nor repository root exists, so ${wt.branch} cannot be proved absent` }, observed: none };
262
+ }
263
+ const commonDir = await commonGitDirAsync(cwd);
264
+ if (commonDir === null) {
265
+ return { outcome: { status: 'failed', reason: 'git_dir_unreadable', detail: `could not resolve the git common dir from ${cwd}` }, observed: none };
266
+ }
267
+ let observed = none;
268
+ let outcome;
269
+ const trash = [];
270
+ try {
271
+ outcome = await withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
272
+ if (!await guard.stillEligible())
273
+ return NODE_REVIVED;
274
+ observed = await observe(wt);
275
+ if (wt.sweep !== undefined && sameObservation(wt.sweep.observed, observed)) {
276
+ return { status: 'refused', reason: wt.sweep.reason, ...(wt.sweep.detail === undefined ? {} : { detail: wt.sweep.detail }), unchanged: true };
277
+ }
278
+ return existsSync(wt.path)
279
+ ? await reconcilePresentCheckout(wt, guard, dependentCwds, trash)
280
+ : await concludeAbsentCheckout(wt, observed, guard);
281
+ }, {
282
+ timeoutMs: WORKTREE_LOCK_WAIT_MS,
283
+ timeoutError: () => new Error(`timed out waiting for the managed-worktree lock on ${commonDir}`),
284
+ });
285
+ }
286
+ catch (err) {
287
+ outcome = { status: 'failed', reason: 'lock_unavailable', detail: err instanceof Error ? err.message : String(err) };
288
+ }
289
+ // The removal above moved the checkout's files to the trash under the lock;
290
+ // deleting them takes long enough that the caller does it after the lock, and on a Mac after answering.
291
+ return { outcome, observed, ...(trash[0] === undefined ? {} : { trash: trash[0] }) };
292
+ }
293
+ /** Record completion against the record as it stands NOW, never the copy this
294
+ * pass began with: the fresh read is what keeps a concurrently-rewritten record
295
+ * (a revived node's, or one a human edited) from being overwritten with this
296
+ * pass's stale fields. A record that moved out from under the pass is left
297
+ * alone — its checkout and branch are already gone, so the next pass observes
298
+ * both absent and concludes it cleanly. */
299
+ async function persistComplete(nodeId, wt, guard) {
300
+ if (!await guard.stillEligible())
301
+ return NODE_REVIVED;
302
+ const current = (await getNode(nodeId))?.managed_worktree;
303
+ if (current == null || current.path !== wt.path || current.branch !== wt.branch) {
304
+ return { status: 'skipped', reason: 'record_changed' };
305
+ }
306
+ await completeCleanup(nodeId);
307
+ return { status: 'complete' };
308
+ }
309
+ /** Resume a record whose checkout is already gone — the crash-after-removal
310
+ * case, and the case where the checkout was removed by hand. Filesystem
311
+ * absence proves nothing about commits, so the branch is still proved before
312
+ * it is deleted. */
313
+ async function concludeAbsentCheckout(wt, observed, guard) {
314
+ const admin = wt.repo_root;
315
+ if (observed.branch === null) {
316
+ // Distinguish "the ref is gone" from "the read failed"; only the first
317
+ // authorizes concluding this record.
318
+ const exists = await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${wt.branch}`], admin);
319
+ if (exists.status !== 1)
320
+ return { status: 'failed', reason: 'branch_inspection_failed', detail: detailOf(exists) };
321
+ return { status: 'complete' };
322
+ }
323
+ const list = await gitAsync(['worktree', 'list', '--porcelain'], admin);
324
+ if (list.status !== 0)
325
+ return { status: 'failed', reason: 'worktree_list_failed', detail: detailOf(list) };
326
+ // The recorded path being absent does NOT mean the branch has no checkout:
327
+ // `git worktree move` relocates one. Deleting a branch checked out elsewhere
328
+ // would bypass Git's own protection and could abandon uncommitted work there.
329
+ const elsewhere = checkoutPathForBranchInList(list.stdout, wt.branch);
330
+ if (elsewhere !== null) {
331
+ return { status: 'refused', reason: 'branch_checked_out_elsewhere', detail: `${wt.branch} is checked out at ${elsewhere}` };
332
+ }
333
+ const proof = await proveBranchContained(admin, wt, observed.branch);
334
+ if (proof === null) {
335
+ return { status: 'refused', reason: 'unlanded_work', detail: `${wt.branch} carries content no base or upstream ref contains; its checkout is already gone, so the branch is the only copy` };
336
+ }
337
+ return deleteBranchAndComplete(wt, admin, observed.branch, proof, guard);
338
+ }
339
+ /** The ordinary case: a checkout that still exists and whose owner is gone. */
340
+ async function reconcilePresentCheckout(wt, guard, dependentCwds, trash) {
341
+ const list = await gitAsync(['worktree', 'list', '--porcelain'], wt.path);
342
+ if (list.status !== 0)
343
+ return { status: 'failed', reason: 'worktree_list_failed', detail: detailOf(list) };
344
+ // An explicit `close` already proved a branch-moved checkout's identity and
345
+ // authorized its later disposal for THIS exact branch — never adopted here.
346
+ // Only the recorded authorization changes which branch this pass expects;
347
+ // everything else below is re-verified exactly as for an ordinary record.
348
+ const disposal = wt.disposal;
349
+ const expectedBranch = disposal?.observed_branch ?? wt.branch;
350
+ const registeredPath = registeredCheckoutPath(list.stdout, wt.path, expectedBranch);
351
+ if (registeredPath === null) {
352
+ return { status: 'refused', reason: 'not_registered', detail: `${wt.path} is not registered to refs/heads/${expectedBranch}; crtr will not act on a path it cannot prove it owns` };
353
+ }
354
+ const main = mainWorktreePath(list.stdout);
355
+ if (main === null || samePath(main, registeredPath) || !existsSync(main)) {
356
+ return { status: 'refused', reason: 'repo_unavailable', detail: `the repository's main checkout is unavailable, so ${wt.path} cannot be removed from outside itself` };
357
+ }
358
+ const midOperation = await isRebaseInProgressAsync(wt.path);
359
+ if (midOperation === null)
360
+ return { status: 'failed', reason: 'git_path_failed', detail: `could not inspect in-progress operations in ${wt.path}` };
361
+ if (midOperation)
362
+ return { status: 'refused', reason: 'rebase_in_progress', detail: `${wt.path} is mid-rebase` };
363
+ const head = await gitAsync(['rev-parse', '--abbrev-ref', 'HEAD'], wt.path);
364
+ if (head.status !== 0)
365
+ return { status: 'failed', reason: 'branch_check_failed', detail: detailOf(head) };
366
+ if (head.stdout.trim() !== expectedBranch) {
367
+ return { status: 'refused', reason: 'wrong_branch', detail: `expected ${expectedBranch}, found ${head.stdout.trim() === 'HEAD' ? 'detached HEAD' : head.stdout.trim()}` };
368
+ }
369
+ // Uncommitted work blocks removal unconditionally. No containment proof
370
+ // overrides this: those reason about committed content, and nothing here has
371
+ // any claim on changes a person or a dead node never committed.
372
+ const status = await gitAsync(['status', '--porcelain'], wt.path);
373
+ if (status.status !== 0)
374
+ return { status: 'failed', reason: 'status_failed', detail: detailOf(status) };
375
+ if (status.stdout.trim() !== '') {
376
+ return { status: 'refused', reason: 'dirty_worktree', detail: `${wt.path} has uncommitted changes` };
377
+ }
378
+ let branchSha = await revParseRef(wt.path, 'HEAD');
379
+ if (branchSha === null)
380
+ return { status: 'failed', reason: 'head_unreadable', detail: `could not read HEAD in ${wt.path}` };
381
+ if (disposal !== undefined) {
382
+ // Re-verify the exact identity `close` authorized before mutating anything.
383
+ // A mismatch invalidates the authorization instead of adopting whatever is
384
+ // observed now — only the explicit command that wrote it may refresh it.
385
+ const commonDir = await commonGitDirAsync(wt.path);
386
+ if (commonDir !== disposal.common_dir || branchSha !== disposal.observed_sha) {
387
+ return { status: 'refused', reason: 'disposal_authorization_stale', detail: `${wt.path} changed since \`close\` authorized its disposal; rerun \`crtr node worktree close\` from that node to re-authorize, or ask the user with \`crtr human send\`` };
388
+ }
389
+ if (!await guard.stillEligible())
390
+ return NODE_REVIVED;
391
+ if (await checkoutHasDependents(dependentCwds, registeredPath))
392
+ return CHECKOUT_IN_USE;
393
+ const { result: removed, trash: moved } = await removeWorktreeCheckoutAsync(main, registeredPath);
394
+ if (moved !== undefined)
395
+ trash.push(moved);
396
+ if (removed.status !== 0)
397
+ return { status: 'refused', reason: 'worktree_remove_failed', detail: detailOf(removed) };
398
+ // `disposal.observed_branch` is not a `crtr/*` branch crouter created — it
399
+ // is preserved, never deleted, unlike the ordinary path below.
400
+ return { status: 'complete' };
401
+ }
402
+ let proof = await proveBranchContained(wt.path, wt, branchSha);
403
+ if (proof === null && wt.land_intent !== undefined) {
404
+ const landed = await finishBlockedLand(wt, list.stdout, guard);
405
+ if (!landed.ok)
406
+ return landed.ineligible === true ? NODE_REVIVED : { status: 'refused', reason: 'land_blocked', detail: landed.detail };
407
+ branchSha = landed.landedSha;
408
+ proof = await proveBranchContained(wt.path, wt, branchSha);
409
+ }
410
+ if (proof === null) {
411
+ return { status: 'refused', reason: 'unlanded_work', detail: `${wt.branch} carries commits its base does not contain, and this node never asked to land them` };
412
+ }
413
+ // The last read-only moment. Everything past here destroys something, so the
414
+ // guard answers immediately before each step rather than once at the top.
415
+ if (!await guard.stillEligible())
416
+ return NODE_REVIVED;
417
+ if (await checkoutHasDependents(dependentCwds, registeredPath))
418
+ return CHECKOUT_IN_USE;
419
+ const { result: removed, trash: moved } = await removeWorktreeCheckoutAsync(main, registeredPath);
420
+ if (moved !== undefined)
421
+ trash.push(moved);
422
+ if (removed.status !== 0)
423
+ return { status: 'refused', reason: 'worktree_remove_failed', detail: detailOf(removed) };
424
+ return await deleteBranchAndComplete(wt, main, branchSha, proof, guard);
425
+ }
426
+ /** Compare-and-delete the branch against the EXACT SHAs the proof inspected,
427
+ * then record completion. A lost race leaves the branch intact, so the work
428
+ * stays reachable — and leaves the record incomplete, so its node metadata is
429
+ * still protected from prune and the next pass retries. */
430
+ async function deleteBranchAndComplete(wt, admin, branchSha, proof, guard) {
431
+ if (!await guard.stillEligible())
432
+ return NODE_REVIVED;
433
+ const stdin = refDeleteTransactionStdin(wt.branch, branchSha, proof.containingRef, proof.containingSha);
434
+ const transaction = await gitAsync(['update-ref', '--stdin'], admin, stdin);
435
+ if (transaction.status !== 0) {
436
+ return { status: 'refused', reason: 'branch_delete_failed', detail: detailOf(transaction) };
437
+ }
438
+ return { status: 'complete' };
439
+ }
@@ -154,7 +154,7 @@ export const OPERATIONS = [
154
154
  { name: 'model_auth.cancel', method: 'POST', path: '/v1/model-auth/flows/:flow_id/cancel', classes: ['person', 'broker'], resource: 'none' },
155
155
  { name: 'model_auth.get', method: 'GET', path: '/v1/model-auth/flows/:flow_id', classes: ['person', 'broker'], resource: 'none' },
156
156
  { name: 'nodes.post.85', method: 'POST', path: '/v1/nodes', classes: ['person', 'broker', 'cron'], resource: 'node-own', scope: 'crtr:act' },
157
- { name: 'nodes.get.86', method: 'GET', path: '/v1/nodes', classes: ['person', 'broker'], resource: 'nodes-list' },
157
+ { name: 'nodes.get.86', method: 'GET', path: '/v1/nodes', classes: ['person', 'broker', 'cron'], resource: 'nodes-list' },
158
158
  { name: 'nodes.post.87', method: 'POST', path: '/v1/nodes/revive-all', classes: ['person', 'broker'], resource: 'none' },
159
159
  { name: 'nodes.get.88', method: 'GET', path: '/v1/nodes/:id', classes: ['person', 'broker', 'cron', 'forwarded'], resource: 'node-read' },
160
160
  { name: 'nodes.get.89', method: 'GET', path: '/v1/nodes/:id/snapshot', classes: ['person', 'broker', 'cron'], resource: 'node-read' },
@@ -193,7 +193,7 @@ export const OPERATIONS = [
193
193
  { name: 'profile.env.list', method: 'GET', path: '/v1/profiles/:name/env', classes: ['person', 'app', 'broker'], resource: 'profile' },
194
194
  { name: 'profile.env.set', method: 'PUT', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
195
195
  { name: 'profile.env.remove', method: 'DELETE', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
196
- { name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], resource: 'profile' },
196
+ { name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
197
197
  { name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person'], resource: 'profile' },
198
198
  { name: 'profiles.delete.116', method: 'DELETE', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
199
199
  { name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker'], resource: 'profile', stage: 'chat' },
@@ -7,24 +7,27 @@ import { CRON_RUN_RING, cancelCron, listCronRuns, parseCronSink } from '../../co
7
7
  import { hasNoNaturalCycle } from '../../core/runtime/revive-all.js';
8
8
  import { isParked } from '../../core/runtime/lifecycle.js';
9
9
  import { enqueueNodeMail } from '../../core/feed/messages.js';
10
+ import { emitEvent } from '../../core/events/emit.js';
10
11
  import { cadenceDisplay } from '../../core/wake.js';
11
- import { machineEnvironmentOfCron, queueCronCancel } from './machine-fire.js';
12
+ import { cronEnvironment, queueCronCancel } from './machine-fire.js';
13
+ import { runnerForEnvironment } from '../../core/runtime/runner/index.js';
12
14
  const SENT = /^delivered: /;
13
15
  const EMPTY_OK = (r) => r.exit_code === 0 && (r.stdout_head ?? '') === '';
14
16
  /** Real runs only: the overlap pass writes a marker row that is not a run. */
15
17
  function realRuns(runs) {
16
18
  return runs.filter((r) => r.exit_code !== null || !(r.delivered ?? '').startsWith('skipped'));
17
19
  }
18
- function endedMessage(c, end, runs) {
20
+ function endedMessage(c, end, runs, toSink) {
19
21
  const real = realRuns(runs);
20
22
  // The run log keeps the last CRON_RUN_RING rows, so a full ring means the true count is unknown.
21
23
  const full = runs.length >= CRON_RUN_RING;
22
24
  const lastSent = real.find((r) => SENT.test(r.delivered ?? ''));
23
25
  const cause = end.kind === 'expired'
24
26
  ? `expired at ${c.expires_at} and was deleted${c.held ? ' while held by exit 75; the pending occurrence never fired' : ''}`
25
- : `was canceled by ${end.by} and deleted`;
27
+ : end.kind === 'max_fires' ? `reached its maximum of ${end.max} fires and was deleted`
28
+ : `was canceled by ${end.by} and deleted`;
26
29
  const lines = [
27
- `Cron "${c.name}" (${c.cron_id}, ${c.recur != null ? cadenceDisplay(c.recur) : 'one-shot'}) ${cause}. It was delivering to you, so nothing will wake you from it any more.`,
30
+ `Cron "${c.name}" (${c.cron_id}, ${c.recur != null ? cadenceDisplay(c.recur) : 'one-shot'}) ${cause}. ${toSink ? 'It was delivering to you, so nothing will wake you from it any more.' : 'It was anchored on you.'}`,
28
31
  '',
29
32
  `- runs made: ${full ? `at least ${real.length} (the run log keeps the last ${CRON_RUN_RING} entries)` : real.length}`,
30
33
  lastSent !== undefined
@@ -39,7 +42,7 @@ function endedMessage(c, end, runs) {
39
42
  if (real.length > 0 && real.every(EMPTY_OK)) {
40
43
  lines.push('', 'Every recorded run exited 0 with empty stdout, so the check may have been failing without saying so. A pipeline exits with its last stage, so `probe 2>&1 | grep … | jq …` hides a failed probe unless the command starts with `set -o pipefail`.');
41
44
  }
42
- return { label: `⏰ cron ${c.name} ${end.kind === 'expired' ? 'expired' : 'canceled'}`, body: lines.join('\n') };
45
+ return { label: `⏰ cron ${c.name} ${end.kind === 'canceled' ? 'canceled' : end.kind === 'max_fires' ? 'ended' : 'expired'}`, body: lines.join('\n') };
43
46
  }
44
47
  /** enqueueNodeMail throws for a node whose run root is being deleted; a throw would roll back the delete and stall the whole due pass. */
45
48
  async function runIsDeleting(node) {
@@ -55,21 +58,29 @@ export async function canTakeMail(node) {
55
58
  * that can still take mail: gone, deleting, or finalized with no wake ahead. */
56
59
  export async function endCron(c, end, options) {
57
60
  const sink = parseCronSink(c.sink);
58
- const target = sink?.kind === 'node' ? await getNode(sink.node) : null;
61
+ // A cron that used all its fires tells its anchor, whatever its output sink (NL-1110); every other end tells the node sink.
62
+ const targetId = end?.kind === 'max_fires' && c.anchor_node !== null ? c.anchor_node : sink?.kind === 'node' ? sink.node : null;
63
+ const target = targetId !== null ? await getNode(targetId) : null;
59
64
  const notify = end !== null && target !== null && await canTakeMail(target);
60
- // A run on a machine is not a local process the delete can signal: owe the machine a cancel of that run id. It is delivered when the link is up
65
+ // A run on a machine or in a sandbox is not a local process the delete can signal. A machine is owed a cancel of that run id, delivered when the link is up
61
66
  // (at once, or on reconnect), including for a `cron.run` the machine never received.
62
67
  if (c.run_state === 'running' && c.run_execution_id !== null && options?.preserveRunningProcess !== true) {
63
- const machine = await machineEnvironmentOfCron(c);
64
- if (machine !== null)
65
- await queueCronCancel(machine, c.run_execution_id);
68
+ const environment = await cronEnvironment(c);
69
+ if (environment?.kind === 'machine')
70
+ await queueCronCancel(environment.id, c.run_execution_id);
71
+ // A sandbox process is killed now; a Blaxel failure is logged and the delete goes ahead (the run timeout or recovery ends the process).
72
+ if (environment?.kind === 'blaxel' && c.anchor_node != null) {
73
+ await runnerForEnvironment('blaxel').cronCancel?.(c.anchor_node, c.run_execution_id).catch((error) => {
74
+ emitEvent({ level: 'error', event: 'cron.sandbox.cancel_failed', error, fields: { cron_id: c.cron_id, run_id: c.run_execution_id } });
75
+ });
76
+ }
66
77
  }
67
78
  return await withCanvasWrite(async () => {
68
79
  const runs = notify ? await listCronRuns(c.cron_id) : [];
69
80
  if (!await cancelCron(c.cron_id, options))
70
81
  return false;
71
82
  if (notify) {
72
- const { label, body } = endedMessage(c, end, runs);
83
+ const { label, body } = endedMessage(c, end, runs, sink?.kind === 'node' && sink.node === target.node_id);
73
84
  await enqueueNodeMail(target.node_id, {
74
85
  kind: 'message', label, senderNodeId: null, bodyJson: { body }, urgency: 'normal', wake: 1,
75
86
  idempotencyKey: `cron-ended:${c.cron_id}`,
@@ -6,15 +6,16 @@
6
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
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
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';
9
+ import { createHash, randomUUID } from 'node:crypto';
10
+ import { join } from 'node:path';
10
11
  import { setTimeout as delay } from 'node:timers/promises';
11
12
  import { openDb } from '../../core/canvas/db.js';
12
13
  import { isCloudRole } from '../../core/canvas/person.js';
13
14
  import { withCanvasWrite } from '../../core/canvas/db.js';
14
15
  import { getNode } from '../../core/canvas/canvas.js';
16
+ import { runnerForEnvironment } from '../../core/runtime/runner/index.js';
15
17
  import { callMachine } from '../../core/runtime/runner/machine/call.js';
16
18
  import { machineEnvironmentOfNode } from '../../core/runtime/runner/machine/runner.js';
17
- import { machineEnvironmentOfProfile } from '../../core/runtime/runner/machine/environment.js';
18
19
  import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '../../core/runtime/runner/machine/ops.js';
19
20
  import { environmentSecrets } from '../../core/secrets/environment-secrets.js';
20
21
  import { profileInApp } from '../../core/secrets/environment-owner.js';
@@ -22,18 +23,20 @@ import { getCron } from '../../core/canvas/crons.js';
22
23
  import { emitEvent } from '../../core/events/emit.js';
23
24
  import { runTokenFor } from './run-token.js';
24
25
  import { parseArmedEnv } from './armed-context.js';
25
- import { CRON_OUTPUT_HEAD_BYTES } from './capture.js';
26
+ import { CRON_OUTPUT_HEAD_BYTES, formatCronOutputHead } from './capture.js';
26
27
  import { settleClosedRun, settleUnspawnedRun } from './closed.js';
27
28
  import { clearLiveRun, registerLiveRun } from './live-runs.js';
28
29
  import { advanceRecurrence } from './recurrence.js';
29
30
  /** Seconds past the run's timeout a send waits for its answer. */
30
31
  const ANSWER_SLACK_S = 15;
31
32
  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) {
33
+ /** Where a cron runs off this process: its profile's machine or Blaxel environment on a cloud role, or null when it runs here (a Mac's own
34
+ * daemon, a local runtime, a cron with no profile). */
35
+ export async function cronEnvironment(c) {
34
36
  if (!isCloudRole() || c.profile == null)
35
37
  return null;
36
- return await machineEnvironmentOfProfile(c.profile);
38
+ const row = await (await openDb()).prepare('SELECT e.object AS id, e.kind AS kind FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?').get(c.profile);
39
+ return row ?? null;
37
40
  }
38
41
  export async function machineLinkLive(environmentId) {
39
42
  return (await (await openDb()).prepare('SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?').get(environmentId, new Date().toISOString())) !== undefined;
@@ -175,3 +178,63 @@ async function driveFire(c, fire, prepared, admit) {
175
178
  clearLiveRun(c.cron_id, runId);
176
179
  }
177
180
  }
181
+ /** Where a hosted node's files sit inside its sandbox: `CRTR_HOME` and the `apps/<app>/{home,nodes/<id>/context}` layout of scripts/sandbox-start.mjs. */
182
+ const SANDBOX_CRTR_HOME = '/var/lib/crtr';
183
+ /** Fire `c` in its anchor node's sandbox through the Blaxel runner and settle the run. The same run id names the sandbox process, so a
184
+ * control plane that recovers the run (`resume`) reads the first start instead of running the command again. */
185
+ export async function fireInSandbox(c, fire, admit, resume = false) {
186
+ const { runId, outOfBand, startedAtIso, startedAtMs } = fire;
187
+ let env;
188
+ let runner;
189
+ try {
190
+ runner = runnerForEnvironment('blaxel');
191
+ if (runner.cronRun === undefined || runner.cronCancel === undefined)
192
+ throw new Error('the registered Blaxel runner cannot run crons');
193
+ const apiUrl = process.env['CRTR_PUBLIC_API_URL'];
194
+ if (!apiUrl)
195
+ throw new Error('CRTR_PUBLIC_API_URL is not set, so a sandbox cron could not reach the API');
196
+ if (c.anchor_node == null)
197
+ throw new Error('a hosted cron runs in its anchor node\'s sandbox, and this cron has no anchor node');
198
+ if (c.isolated)
199
+ throw new Error('an isolated cron needs a root launcher, which a sandbox does not have');
200
+ const prepared = await prepareRun(c, runId);
201
+ const anchor = prepared.contextAnchor;
202
+ env = { ...prepared.env, CRTR_API_URL: apiUrl, HOME: join(SANDBOX_CRTR_HOME, 'apps', c.grantee.replace(/^app:/, ''), 'home'),
203
+ ...(anchor !== null ? { CRTR_CONTEXT_DIR: join(SANDBOX_CRTR_HOME, 'apps', anchor.grantee.replace(/^app:/, ''), 'nodes', anchor.node, 'context') } : {}) };
204
+ // A recovered run's slot may already have moved past this start; advancing again is a no-op then.
205
+ if (!outOfBand && c.recur != null && (!resume || Date.parse(c.fire_at) <= startedAtMs)) {
206
+ const recurrenceError = await advanceRecurrence(c, startedAtMs);
207
+ if (recurrenceError !== null)
208
+ throw recurrenceError;
209
+ }
210
+ }
211
+ catch (err) {
212
+ return await settleUnspawnedRun(c, fire, 'run could not be armed', err);
213
+ }
214
+ const anchorNode = c.anchor_node;
215
+ const live = { runId, replaced: false, selfCanceled: false, kill: () => {
216
+ void runner.cronCancel(anchorNode, runId).catch((error) => {
217
+ emitEvent({ level: 'error', event: 'cron.sandbox.cancel_failed', error, fields: { cron_id: c.cron_id, run_id: runId } });
218
+ });
219
+ } };
220
+ registerLiveRun(c.cron_id, live);
221
+ admit();
222
+ try {
223
+ let result;
224
+ try {
225
+ result = await runner.cronRun(anchorNode, { runId, command: c.command, cwd: c.cwd, env, timeoutS: c.run_timeout_s, startedAtMs });
226
+ }
227
+ catch (err) {
228
+ return await settleUnspawnedRun(c, fire, 'run failed in the sandbox', err);
229
+ }
230
+ const head = (text) => text.length > CRON_OUTPUT_HEAD_BYTES ? formatCronOutputHead(text.slice(0, CRON_OUTPUT_HEAD_BYTES), true) : text;
231
+ return await settleClosedRun(c, {
232
+ runId, outOfBand, startedAtIso, startedAtMs, finishedAtMs: Date.now(), code: result.exitCode, timedOut: result.timedOut, processError: result.error === undefined ? null : new Error(result.error),
233
+ stdoutHead: head(result.stdout), stderrHead: head(result.stderr), stdoutSha256: createHash('sha256').update(result.stdout).digest('hex'),
234
+ wasReplaced: live.replaced, wasSelfCanceled: live.selfCanceled,
235
+ });
236
+ }
237
+ finally {
238
+ clearLiveRun(c.cron_id, runId);
239
+ }
240
+ }