@north-light/cli 0.3.709 → 0.3.711

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 (153) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/clients/attach/input/capabilities.js +1 -1
  4. package/dist/clients/attach/input/controller.d.ts +1 -1
  5. package/dist/clients/attach/input/controller.js +2 -2
  6. package/dist/clients/attach/render/chat-view.d.ts +13 -2
  7. package/dist/clients/attach/render/chat-view.js +2 -2
  8. package/dist/clients/attach/session/input-wiring.d.ts +2 -2
  9. package/dist/clients/attach/session/layout-record.d.ts +15 -0
  10. package/dist/clients/attach/session/layout-record.js +1 -0
  11. package/dist/clients/attach/session/reconnect.d.ts +8 -1
  12. package/dist/clients/attach/session/reconnect.js +1 -1
  13. package/dist/clients/attach/session/teardown.d.ts +2 -0
  14. package/dist/clients/attach/session/teardown.js +3 -3
  15. package/dist/clients/attach/slash/dispatch.js +2 -2
  16. package/dist/clients/attach/slash/recover.d.ts +10 -0
  17. package/dist/clients/attach/slash/recover.js +3 -0
  18. package/dist/clients/attach/viewer.js +520 -516
  19. package/dist/commands/human/prompts.js +1 -1
  20. package/dist/commands/human/request.js +1 -1
  21. package/dist/commands/sys/doctor.js +1 -1
  22. package/dist/commands/sys/tutorial/scenario.js +2 -2
  23. package/dist/core/broker-client/client.d.ts +2 -0
  24. package/dist/core/broker-client/client.js +1 -1
  25. package/dist/core/broker-client/transport-relay.d.ts +6 -0
  26. package/dist/core/broker-client/transport-relay.js +1 -1
  27. package/dist/core/broker-client/transport.d.ts +4 -0
  28. package/dist/core/canvas/daemon-actions.d.ts +1 -1
  29. package/dist/core/canvas/daemon-actions.js +7 -7
  30. package/dist/core/canvas/deliveries.d.ts +1 -1
  31. package/dist/core/canvas/deliveries.js +21 -21
  32. package/dist/core/canvas/executions.d.ts +1 -1
  33. package/dist/core/canvas/executions.js +1 -1
  34. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
  35. package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
  36. package/dist/core/canvas/reconciler-leases.d.ts +4 -0
  37. package/dist/core/canvas/reconciler-leases.js +5 -5
  38. package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
  39. package/dist/core/canvas/schema-version.d.ts +1 -1
  40. package/dist/core/canvas/schema-version.js +1 -1
  41. package/dist/core/conversation-store/client.js +2 -2
  42. package/dist/core/conversation-store/index.d.ts +5 -2
  43. package/dist/core/conversation-store/row-store.js +14 -12
  44. package/dist/core/graph/package-docs.js +5 -5
  45. package/dist/core/graph/package-publish.js +4 -3
  46. package/dist/core/human/requests.js +19 -19
  47. package/dist/core/import/load/run.js +2 -2
  48. package/dist/core/runtime/broker/client-registry.d.ts +1 -1
  49. package/dist/core/runtime/broker/client-registry.js +1 -1
  50. package/dist/core/runtime/broker/turn-replies.js +3 -1
  51. package/dist/core/runtime/broker-protocol.d.ts +4 -4
  52. package/dist/core/runtime/broker-protocol.js +3 -3
  53. package/dist/core/runtime/broker-request.d.ts +2 -0
  54. package/dist/core/runtime/broker-request.js +1 -1
  55. package/dist/core/runtime/broker.js +1 -1
  56. package/dist/core/runtime/model-swap.d.ts +2 -1
  57. package/dist/core/runtime/model-swap.js +1 -1
  58. package/dist/core/runtime/placement-tmux.d.ts +2 -1
  59. package/dist/core/runtime/placement-tmux.js +1 -1
  60. package/dist/core/runtime/runner/machine/call.js +2 -2
  61. package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
  62. package/dist/core/runtime/runner/machine/ops.js +1 -1
  63. package/dist/core/runtime/session-cycles.d.ts +21 -0
  64. package/dist/core/runtime/session-cycles.js +1 -1
  65. package/dist/core/runtime/tmux-driver.d.ts +7 -0
  66. package/dist/core/runtime/tmux-driver.js +6 -6
  67. package/dist/core/worktree-machine.d.ts +4 -1
  68. package/dist/core/worktree-machine.js +1 -1
  69. package/dist/core/worktree-sweep.d.ts +14 -3
  70. package/dist/core/worktree-sweep.js +4 -4
  71. package/dist/daemon/api/app-listener.js +1 -1
  72. package/dist/daemon/api/handlers/charges.d.ts +1 -1
  73. package/dist/daemon/api/handlers/charges.js +1 -1
  74. package/dist/daemon/api/handlers/conversations.js +4 -3
  75. package/dist/daemon/api/handlers/environments.d.ts +1 -1
  76. package/dist/daemon/api/handlers/environments.js +1 -1
  77. package/dist/daemon/api/handlers/limits.js +1 -1
  78. package/dist/daemon/api/handlers/nodes.js +1 -1
  79. package/dist/daemon/api/operations.js +1 -1
  80. package/dist/daemon/api/router.js +1 -1
  81. package/dist/daemon/cron/live-runs.d.ts +3 -0
  82. package/dist/daemon/cron/live-runs.js +1 -1
  83. package/dist/daemon/cron/machine-fire.js +1 -1
  84. package/dist/daemon/crtrd.js +12 -12
  85. package/dist/daemon/due-sources.d.ts +1 -1
  86. package/dist/daemon/due-sources.js +1 -1
  87. package/dist/daemon/due.js +7 -7
  88. package/dist/daemon/fleet.d.ts +1 -1
  89. package/dist/daemon/fleet.js +4 -4
  90. package/dist/daemon/human/finish.js +3 -3
  91. package/dist/daemon/human/settle.js +1 -1
  92. package/dist/daemon/reconcilers/action-lane.js +1 -1
  93. package/dist/daemon/reconcilers/delivery-lane.js +2 -2
  94. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  95. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  96. package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
  97. package/dist/daemon/runs/observer.d.ts +4 -0
  98. package/dist/daemon/runs/observer.js +1 -1
  99. package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
  100. package/package.json +4 -3
  101. package/packages/crouter-api/dist/api/contract.js +1 -1
  102. package/packages/crouter-api/dist/clients/attach/input/capabilities.js +1 -0
  103. package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
  104. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
  105. package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
  106. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
  107. package/packages/crouter-api/dist/clients/attach/session/teardown.js +2 -0
  108. package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
  109. package/packages/crouter-api/dist/clients/attach/slash/recover.js +133 -0
  110. package/packages/crouter-api/dist/clients/attach/viewer.js +24 -5
  111. package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
  112. package/packages/crouter-api/dist/commands/human/request.js +3 -0
  113. package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
  114. package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
  115. package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
  116. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
  117. package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
  118. package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
  119. package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
  120. package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
  121. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  122. package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
  123. package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
  124. package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
  125. package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
  126. package/packages/crouter-api/dist/core/human/requests.js +2 -2
  127. package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
  128. package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
  129. package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
  130. package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
  131. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +3 -3
  132. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
  133. package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
  134. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
  135. package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
  136. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
  137. package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
  138. package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
  139. package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
  140. package/packages/crouter-api/dist/daemon/api/router.js +1 -4
  141. package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
  142. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
  143. package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
  144. package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
  145. package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
  146. package/packages/crouter-api/package.json +1 -1
  147. package/packages/crouter-identity/package.json +1 -1
  148. package/packages/crouter-plugin/package.json +3 -3
  149. package/runtime.lock.json +14 -14
  150. package/scripts/install-runtime.mjs +18 -1
  151. package/scripts/lib/install-source.mjs +49 -0
  152. package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
  153. package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
@@ -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
+ }
@@ -194,7 +194,7 @@ export const OPERATIONS = [
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
196
  { name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
197
- { name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person'], resource: 'profile' },
197
+ { name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], 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' },
200
200
  { name: 'profiles.get.118', method: 'GET', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
@@ -247,13 +247,13 @@ export const OPERATIONS = [
247
247
  { name: 'focus.delete.147', method: 'DELETE', path: '/v1/focuses/:focus_id', classes: ['person', 'broker'], resource: 'none' },
248
248
  { name: 'delivery.retry', method: 'POST', path: '/v1/deliveries/:delivery_id/retry', classes: ['person', 'broker'], resource: 'none' },
249
249
  // Person only: an app (or a broker acting for one) never sets its own limits.
250
- { name: 'limits.show', method: 'GET', path: '/v1/limits', classes: ['person'], resource: 'none' },
250
+ { name: 'limits.show', method: 'GET', path: '/v1/limits', classes: ['person', 'broker'], resource: 'none' },
251
251
  { name: 'limits.set', method: 'PUT', path: '/v1/limits/apps/:app', classes: ['person'], resource: 'none' },
252
252
  { name: 'limits.remove', method: 'DELETE', path: '/v1/limits/apps/:app', classes: ['person'], resource: 'none' },
253
253
  // The money ledger. `charges.list` is stage `objects` so the app listener serves it (an app sees only rows whose grantee it is).
254
254
  { name: 'charges.list', method: 'GET', path: '/v1/charges', classes: ['person', 'app', 'broker'], resource: 'none', stage: 'objects' },
255
255
  // Dollar limits, distinct from the per-app memory and disk limits above. Person only.
256
- { name: 'spend_limits.list', method: 'GET', path: '/v1/spend-limits', classes: ['person'], resource: 'none' },
256
+ { name: 'spend_limits.list', method: 'GET', path: '/v1/spend-limits', classes: ['person', 'broker'], resource: 'none' },
257
257
  { name: 'spend_limits.set', method: 'PUT', path: '/v1/spend-limits/:id', classes: ['person'], resource: 'none' },
258
258
  { name: 'spend_limits.remove', method: 'DELETE', path: '/v1/spend-limits/:id', classes: ['person'], resource: 'none' },
259
259
  { name: 'space.list', method: 'GET', path: '/v1/spaces', classes: ['person', 'broker'], resource: 'none' },
@@ -39,10 +39,7 @@ async function authorizeHumanBody(operation, principal, params, query, body) {
39
39
  // Creation only: `GET /v1/human/reviews` (the list) shares this path and carries no body.
40
40
  if (operation.method === 'POST' && (path === '/v1/human/requests' || path === '/v1/human/reviews')) {
41
41
  const origin = path.endsWith('/reviews') ? fields['origin_node_id'] : fields['requester_node_id'];
42
- // A page with no reply route names no requester (`requester_node_id: null`): nothing is addressed to any node, and the
43
- // handler rejects `delivery.reply` without a requester. A request naming a node must still name the caller.
44
- const displayOnly = path === '/v1/human/requests' && (origin === undefined || origin === null);
45
- if (origin !== principal.node && !displayOnly)
42
+ if (origin !== principal.node)
46
43
  throw new ApiError(403, 'other_app_run', 'a broker may create a human request only for its own node');
47
44
  const source = fields['source'];
48
45
  if (source && typeof source === 'object' && 'nodeId' in source && source.nodeId !== principal.node)
@@ -1,22 +1,21 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { claimReconcilerLease, renewReconcilerLease } from '../../core/canvas/reconciler-leases.js';
2
+ import { DAEMON_OWNER_LANE, claimReconcilerLease, renewReconcilerLease } from '../../core/canvas/reconciler-leases.js';
3
3
  import { openDb } from '../../core/canvas/db.js';
4
4
  export const cronDaemonInstanceId = randomUUID();
5
5
  /** A process that owns cron run leases keeps this heartbeat: a `reconciler_leases` row keyed by its instance id. Another process
6
6
  * recovers a run it does not own only once that owner's heartbeat has lapsed, so a live peer still building a run's context
7
7
  * (no pid recorded yet) is never taken for a crashed one. */
8
- const CRON_OWNER_LANE = 'cron-owner';
9
8
  export const CRON_OWNER_HEARTBEAT_TTL_MS = 15_000;
10
9
  const CRON_OWNER_HEARTBEAT_EVERY_MS = 5_000;
11
10
  let heartbeat;
12
11
  let lastBeatAt = 0;
13
12
  async function beat() {
14
- if (await renewReconcilerLease(CRON_OWNER_LANE, cronDaemonInstanceId, cronDaemonInstanceId, CRON_OWNER_HEARTBEAT_TTL_MS)) {
13
+ if (await renewReconcilerLease(DAEMON_OWNER_LANE, cronDaemonInstanceId, cronDaemonInstanceId, CRON_OWNER_HEARTBEAT_TTL_MS)) {
15
14
  lastBeatAt = Date.now();
16
15
  return;
17
16
  }
18
17
  // Absent (first beat) or lapsed (this process stalled): take it again under the same owner.
19
- await claimReconcilerLease(CRON_OWNER_LANE, cronDaemonInstanceId, cronDaemonInstanceId, CRON_OWNER_HEARTBEAT_TTL_MS);
18
+ await claimReconcilerLease(DAEMON_OWNER_LANE, cronDaemonInstanceId, cronDaemonInstanceId, CRON_OWNER_HEARTBEAT_TTL_MS);
20
19
  lastBeatAt = Date.now();
21
20
  }
22
21
  /** Call before naming this process the owner of a cron run lease. Keeps the heartbeat alive from then on; the heartbeat stops
@@ -35,7 +34,7 @@ export async function ensureCronOwnerLease() {
35
34
  /** Whether `owner` (another process's instance id) has a live heartbeat. */
36
35
  export async function cronOwnerAlive(owner) {
37
36
  const row = await (await openDb()).prepare('SELECT 1 AS alive FROM reconciler_leases WHERE lane = ? AND key = ? AND expires_at > ?')
38
- .get(CRON_OWNER_LANE, owner, new Date().toISOString());
37
+ .get(DAEMON_OWNER_LANE, owner, new Date().toISOString());
39
38
  return row !== undefined;
40
39
  }
41
40
  const liveRuns = new Map();
@@ -13,6 +13,7 @@ import { openDb } from '../../core/canvas/db.js';
13
13
  import { isCloudRole } from '../../core/canvas/person.js';
14
14
  import { withCanvasWrite } from '../../core/canvas/db.js';
15
15
  import { getNode } from '../../core/canvas/canvas.js';
16
+ import { contextDir } from '../../core/canvas/paths.js';
16
17
  import { runnerForEnvironment } from '../../core/runtime/runner/index.js';
17
18
  import { callMachine } from '../../core/runtime/runner/machine/call.js';
18
19
  import { machineEnvironmentOfNode } from '../../core/runtime/runner/machine/runner.js';
@@ -178,7 +179,7 @@ async function driveFire(c, fire, prepared, admit) {
178
179
  clearLiveRun(c.cron_id, runId);
179
180
  }
180
181
  }
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
+ /** The sandbox's `CRTR_HOME` (scripts/sandbox-start.mjs), where the app home sits. The context dir is not under it: the node's launch env carries the control plane's `contextDir`. */
182
183
  const SANDBOX_CRTR_HOME = '/var/lib/crtr';
183
184
  /** 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
185
  * control plane that recovers the run (`resume`) reads the first start instead of running the command again. */
@@ -199,8 +200,7 @@ export async function fireInSandbox(c, fire, admit, resume = false) {
199
200
  throw new Error('an isolated cron needs a root launcher, which a sandbox does not have');
200
201
  const prepared = await prepareRun(c, runId);
201
202
  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') } : {}) };
203
+ env = { ...prepared.env, CRTR_API_URL: apiUrl, HOME: join(SANDBOX_CRTR_HOME, 'apps', c.grantee.replace(/^app:/, ''), 'home'), ...(anchor !== null ? { CRTR_CONTEXT_DIR: contextDir(anchor.node, anchor.grantee) } : {}) };
204
204
  // A recovered run's slot may already have moved past this start; advancing again is a no-op then.
205
205
  if (!outOfBand && c.recur != null && (!resume || Date.parse(c.fire_at) <= startedAtMs)) {
206
206
  const recurrenceError = await advanceRecurrence(c, startedAtMs);
@@ -1,5 +1,6 @@
1
1
  import { getRequest, getRequestByInboxTicket, presentationDir } from '../../core/human/requests.js';
2
2
  import { buildPageSummary } from '../../core/human/summary.js';
3
+ import { pageAwaitsResponse } from '../../core/human/page-schema.js';
3
4
  import { validateFinalPageResponses } from '../../core/human/tickets.js';
4
5
  import { composeHumanCompletion } from '../../core/human/completion.js';
5
6
  import { describePageAnswer } from '../../core/human/answer.js';
@@ -106,7 +107,7 @@ async function cancelBody(request, dismissed, reason) {
106
107
  return body + await feedbackAddendum(request);
107
108
  }
108
109
  function notification(request, disposition, body, result) {
109
- if (request.requester_node_id === null)
110
+ if (request.requester_node_id === null || !pageAwaitsResponse(manifest(request)))
110
111
  return undefined;
111
112
  return { label: firstLine(body), disposition, body_json: { body, result } };
112
113
  }
@@ -25,9 +25,6 @@ export async function settleHumanRequest(input) {
25
25
  return { outcome: 'already_settled', request: winner };
26
26
  }
27
27
  const notification = typeof input.notification === 'function' ? await input.notification(won) : input.notification;
28
- if (won.requester_node_id !== null && notification === undefined) {
29
- throw new Error(`request ${won.request_id} needs a requester notification`);
30
- }
31
28
  if (won.action_json !== null && won.kind === 'page' && input.completion_action === undefined) {
32
29
  throw new Error(`request ${won.request_id} needs its frozen completion action`);
33
30
  }
@@ -39,9 +36,7 @@ export async function settleHumanRequest(input) {
39
36
  }
40
37
  let settlementDeliveryId = null;
41
38
  let actionDeliveryId = null;
42
- if (won.requester_node_id !== null) {
43
- if (notification === undefined)
44
- throw new Error(`request ${won.request_id} needs a requester notification`);
39
+ if (won.requester_node_id !== null && notification !== undefined) {
45
40
  settlementDeliveryId = (await enqueueNodeMail(won.requester_node_id, {
46
41
  kind: 'completed', label: notification.label, senderName: 'crtrd',
47
42
  ...(notification.body_ref === undefined ? {} : { bodyRef: notification.body_ref }),
@@ -330,7 +330,7 @@ class RunObserver {
330
330
  }
331
331
  /** The transport to the node's live broker, from where its runner says viewers connect: this machine's `view.sock`, or
332
332
  * the `/view` WebSocket behind a sandbox's preview. */
333
- async function viewTransport(nodeId) {
333
+ export async function viewTransport(nodeId) {
334
334
  const execution = await liveExecutionForNode(nodeId);
335
335
  if (execution === null)
336
336
  return new SocketTransport(nodeId, { recordsViewerFaults: false });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.709",
3
+ "version": "0.3.711",
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.709",
3
+ "version": "0.3.711",
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.709",
3
+ "version": "0.3.711",
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.709",
31
- "@north-light/identity": "0.3.709"
30
+ "@north-light/api": "0.3.711",
31
+ "@north-light/identity": "0.3.711"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {