@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
@@ -91,7 +91,9 @@ export async function publish(db, input, publishedBy) {
91
91
  emitEvent({ level: 'warn', event: 'daemon.packages.superseded', fields: { app: snapshot.app, snapshot_version: snapshot.version, published_version: row.version, snapshot_revision: snapshot.revision ?? 'none', published_revision: row.revision === null ? 'none' : Number(row.revision) } });
92
92
  return report;
93
93
  }
94
- const sameBytes = row.digest === snapshot.digest && row.withdrawn_at === null;
94
+ // A shipped document whose head text has no `bodies` row (a release before text moved into the table kept it only in the file) forces a
95
+ // converge, which heals the row, even when the package bytes are unchanged.
96
+ const sameBytes = row.digest === snapshot.digest && row.withdrawn_at === null && !(await missesBody(db, owner.id));
95
97
  if (!sameBytes) {
96
98
  const reposFn = async (cwd, person) => await checkoutsForCwd(db, cwd, person);
97
99
  const seen = new Set();
@@ -112,6 +114,11 @@ export async function publish(db, input, publishedBy) {
112
114
  WHERE app = ?`).run(snapshot.origin, snapshot.version, snapshot.revision, snapshot.source, snapshot.launchKinds === null ? null : canonicalJson(snapshot.launchKinds), snapshot.digest, now, publishedBy, owner.id);
113
115
  return report;
114
116
  }
117
+ /** Whether a live shipped document of `app` has a revision whose text is missing from `bodies`. */
118
+ async function missesBody(db, app) {
119
+ return await db.prepare(`SELECT 1 FROM objects o JOIN documents d ON d.object = o.id AND d.source_path IS NOT NULL JOIN revisions r ON r.document = o.id
120
+ WHERE o.type = 'document' AND o.owner = ? AND o.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM bodies b WHERE b.hash = r.body_hash) LIMIT 1`).get(app) !== undefined;
121
+ }
115
122
  /** A package folder that does not exist ships nothing: a plugin without a `memory/` folder. */
116
123
  export function emptyPackageSnapshot(meta) {
117
124
  return snapshotOf({ revision: null, source: null, launchKinds: null, objectKinds: null, ...meta }, [], [], createHash('sha256'));
@@ -186,7 +186,7 @@ export async function listOpenInboxRequests() {
186
186
  /** Every open request a person is being asked to act on: the inbox's set (`listOpenInboxRequests`), plus
187
187
  * answerable pages kept out of the inbox. This is the set the attach viewer's inbox strip shows. */
188
188
  export async function listPendingAsks() {
189
- return (await many(await openDb(), `state = 'open' AND requester_node_id IS NOT NULL AND ((inbox_listed = 1 AND ${NOT_OTHER_APP_QUESTION}) OR (kind = 'page' AND inbox_listed = 0 AND settleable = 1))`, [], 'created_at ASC, request_id ASC'))
189
+ return (await many(await openDb(), `state = 'open' AND requester_node_id IS NOT NULL AND (kind = 'review' OR NOT ${pageIsNoticeSql('specification_json')}) AND ((inbox_listed = 1 AND ${NOT_OTHER_APP_QUESTION}) OR (kind = 'page' AND inbox_listed = 0 AND settleable = 1))`, [], 'created_at ASC, request_id ASC'))
190
190
  .filter((request) => request.inbox_listed || pageAwaitsResponse(JSON.parse(request.specification_json)));
191
191
  }
192
192
  export async function openRequestsByRequester(nodeId) {
@@ -202,7 +202,7 @@ export async function hasOpenReplyBearingRequestByRequester(nodeId) {
202
202
  }
203
203
  /** Indexed attention projection: only open inbox-listed requests with a reply target keep a node wakeable. */
204
204
  export async function listOpenReplyBearingRequests() {
205
- return await many(await openDb(), "state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL", [], 'created_at DESC, request_id DESC');
205
+ return await many(await openDb(), `state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL AND (kind = 'review' OR NOT ${pageIsNoticeSql('specification_json')})`, [], 'created_at DESC, request_id DESC');
206
206
  }
207
207
  export async function listBindingRequests() { return await many(await openDb(), "kind = 'review' AND state = 'binding'"); }
208
208
  export async function listSubmitRequestedRequests() { return await many(await openDb(), "kind = 'review' AND state = 'open' AND submit_requested_at IS NOT NULL"); }
@@ -0,0 +1,6 @@
1
+ // A broker declares its owning canvas in argv at spawn:
2
+ // `broker-cli.js --canvas-home <home> --epoch <id> <nodeId>`.
3
+ // Untagged brokers and brokers of another home are not ours to count or kill.
4
+ export function brokerCommandDeclaresCanvasHome(command, home) {
5
+ return command.includes(` --canvas-home ${home} `);
6
+ }
@@ -17,12 +17,12 @@
17
17
  // follow pi.
18
18
  import { StringDecoder } from 'node:string_decoder';
19
19
  // Client → broker frames
20
- /** The welcome holds at most the last SNAPSHOT_TAIL messages; older ones are read with `crtr canvas read`. */
21
- export const SNAPSHOT_TAIL = 100;
20
+ /** A requested welcome bound: at most this many of the newest messages. Absent or invalid asks for the
21
+ * default window (`welcomeWindow` in session-cycles.ts: two earlier cycles, then the current cycle by size). */
22
22
  export function normalizeSnapshotTail(value) {
23
23
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
24
- return SNAPSHOT_TAIL;
25
- return Math.min(value, SNAPSHOT_TAIL);
24
+ return undefined;
25
+ return value;
26
26
  }
27
27
  export function toolCallIds(messages) {
28
28
  const ids = new Set();
@@ -35,7 +35,7 @@ export class BrokerUnreachableError extends Error {
35
35
  export function oneShotControllerRequest(opts) {
36
36
  return new Promise(async (resolve, reject) => {
37
37
  // A daemon-internal controller: its connect outcome says nothing about any person's viewer, so it records no viewer fault.
38
- const client = new BrokerClient(opts.nodeId, { transport: new SocketTransport(opts.nodeId, { recordsViewerFaults: false }) });
38
+ const client = new BrokerClient(opts.nodeId, { transport: opts.transport ?? new SocketTransport(opts.nodeId, { recordsViewerFaults: false }) });
39
39
  const clientId = randomUUID();
40
40
  const frameId = randomUUID();
41
41
  let settled = false;
@@ -29,11 +29,12 @@ export function isBrokerLive(node) {
29
29
  * `intent` is the routing contract the CALLER derived from the RAW token
30
30
  * (`explicitModelIntent`); `spec` is already normalized, so its shape no longer
31
31
  * says whether the pick was portable. Undefined means an exact model. */
32
- export function setModelLive(nodeId, spec, intent) {
32
+ export function setModelLive(nodeId, spec, intent, transport) {
33
33
  // `set_model` carries no frame id, so the ack is matched on `for` alone.
34
34
  let resolvedSpec;
35
35
  return oneShotControllerRequest({
36
36
  nodeId,
37
+ transport,
37
38
  what: 'the model switch',
38
39
  ackFor: 'set_model',
39
40
  frame: () => ({ type: 'set_model', model: spec, ...(intent !== undefined ? { intent } : {}) }),
@@ -16,11 +16,11 @@
16
16
  // tmux-driver.ts — it is the sanctioned pure-tmux seam, re-exporting the driver
17
17
  // verbs other modules need so they never import the driver directly.
18
18
  import { envHomeOverride } from '../../shared/env.js';
19
- import { paneLocation, ensureSession, openNodeWindow, splitWindow, selectLayout, } from './tmux-driver.js';
19
+ import { paneLocation, ensureSession, openNodeWindow, splitWindow, selectLayout, shellQuote, } from './tmux-driver.js';
20
20
  import { BROKER_VIEW_SOCKET_WAIT_MS } from './view-socket.js';
21
21
  // Re-export the pure tmux driver verbs the CLI/viewer consumers need without
22
22
  // exposing the canvas focuses table or sending command modules to the raw driver.
23
- export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
23
+ export { paneExists, paneLocation, paneCoordinates, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
24
24
  export { installTmuxBindings } from './tmux-bindings.js';
25
25
  // view.sock readiness — the one shared broker-cold-start primitive
26
26
  export { BROKER_VIEW_SOCKET_WAIT_MS, waitForBrokerViewSocket } from './view-socket.js';
@@ -45,7 +45,7 @@ export function viewerSplitEnv() {
45
45
  * - `besidePane` → a SPLIT beside that pane in its own session (the focus
46
46
  * open-beside-the-caller path); `session` is then only a fallback. */
47
47
  export function openViewerPane(nodeId, session, opts = {}) {
48
- const command = `crtr surface attach to ${nodeId}`;
48
+ const command = `crtr surface attach to ${nodeId}` + (opts.canvas === undefined ? '' : ` --canvas ${shellQuote(opts.canvas)}`);
49
49
  // When the broker may not have bound view.sock yet (a viewer opened right after
50
50
  // a fresh spawn), hand the attach pane CRTR_ATTACH_WAIT_MS so it POLLS the
51
51
  // socket until it accepts instead of failing fast on a cold socket and closing
@@ -12,7 +12,7 @@ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '.
12
12
  * 25 s, so they get 60 too (`worktree.finalize` also asks origin, bounded at 10 s). */
13
13
  export const MACHINE_CALL_TIMEOUT_S = {
14
14
  start: 60, wake: 15, stop: 15, status: 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15, 'job.stop': 15,
15
- 'worktree.create': 60, 'worktree.rollback': 60, 'worktree.close': 60, 'worktree.abandon': 60, 'worktree.finalize': 60,
15
+ 'worktree.create': 60, 'worktree.rollback': 60, 'worktree.close': 60, 'worktree.abandon': 60, 'worktree.finalize': 60, 'worktree.sweep': 60,
16
16
  'repo.identify': 15,
17
17
  };
18
18
  const REREAD_MS = 1000;
@@ -0,0 +1,235 @@
1
+ // src/core/runtime/runner/machine/executor.ts — what the Mac does for each call the control plane sends over the machine link (design-import I13).
2
+ //
3
+ // DB-free: a machine-role crtrd has no local Postgres. `start` uses the start bundle the call carries, writes the run dir's `broker-launch.json`, and
4
+ // spawns `broker-cli` with the token on fd 3.
5
+ // The broker finds itself by the `--epoch <execution id>` in its argv: `wake`, `stop` and `status` scan the process table for it.
6
+ import { spawn } from 'node:child_process';
7
+ import { closeSync, existsSync, mkdirSync, openSync, statSync } from 'node:fs';
8
+ import { rm } from 'node:fs/promises';
9
+ import { basename, dirname, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { emitEvent } from '../../../events/emit.js';
12
+ import { contextDir, jobDir, nodeRunDir, crtrHome, viewSocketPath } from '../../../canvas/paths.js';
13
+ import { captureTeardownSnapshot, isAnyPidAlive, killProcessTreePids, listProcessTableAsync } from '../../../canvas/pid.js';
14
+ import { scopesFilePath } from '../../../canvas/paths.js';
15
+ import { writeFileBeneath } from '../../../spaces/open-beneath.js';
16
+ import { FRONT_DOOR_ENV } from '../../front-door-env.js';
17
+ import { brokerCommandDeclaresCanvasHome } from '../../broker-ownership.js';
18
+ import { isShippedCanvasExtension } from '../../../canvas/extensions.js';
19
+ import { CANVAS_EXTENSIONS, mergeCanvasExtensions } from '../../canvas-extensions.js';
20
+ import { layoutRoot, runtimeRoot } from '../../../layout.js';
21
+ import { composeAppProcessEnv, overlayBrokerEnv } from '../../spawn-env.js';
22
+ const brokerEntry = () => join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'broker-cli.js');
23
+ const killGroup = (pid) => { if (pid !== undefined)
24
+ try {
25
+ process.kill(-pid, 'SIGKILL');
26
+ }
27
+ catch { /* gone */ } };
28
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29
+ /** Broker processes: `{pid, execution, node}` for each `broker-cli.js ... --epoch <execution> <node>` command line. Throws when the process table cannot
30
+ * be read: an unreadable table is not an empty one, and a caller that read it as "no brokers" would start a second broker or report a stop that did not happen. */
31
+ export async function findBrokers() {
32
+ const out = [];
33
+ const table = await listProcessTableAsync();
34
+ if (table === null)
35
+ throw new Error('the process table could not be read, so which brokers are running is unknown');
36
+ for (const { pid, command } of table) {
37
+ const m = /broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(command);
38
+ if (m !== null)
39
+ out.push({ pid, execution: m[1], node: m[2], command });
40
+ }
41
+ return out;
42
+ }
43
+ /** The launch recipe's env keys that name a path in the control plane's filesystem. The control plane builds the recipe on its own layout (a Linux pod:
44
+ * `/work/crtr`, `/opt/crouter/runtime`), so none of them is a path on this machine: the home and runtime home are dropped (this machine's own are
45
+ * pinned by `machineBrokerEnv`), and the context dir and scopes file are derived from this machine's layout. */
46
+ const CONTROL_PLANE_HOME_KEYS = ['CRTR_HOME', 'CRTR_RUNTIME_HOME'];
47
+ /** `launch.env` with every machine-local path key replaced by this machine's own; everything else (identity, kind, profile, settings) is the bundle's. */
48
+ function localLaunchEnv(env, node) {
49
+ const out = { ...env };
50
+ for (const key of CONTROL_PLANE_HOME_KEYS)
51
+ delete out[key];
52
+ if (out['CRTR_CONTEXT_DIR'] !== undefined)
53
+ out['CRTR_CONTEXT_DIR'] = contextDir(node.id, out['CRTR_GRANTEE'] ?? node.app);
54
+ if (out['CRTR_SCOPES_FILE'] !== undefined)
55
+ out['CRTR_SCOPES_FILE'] = scopesFilePath(node.id);
56
+ return out;
57
+ }
58
+ /** The recipe's `-e` extension paths name files of the control plane's install (`/opt/crouter/runtime/generations/...`), and its release may ship a different
59
+ * set of canvas extensions than this install. So the mandatory canvas extensions are this install's complete list (`mergeCanvasExtensions`), whatever the recipe
60
+ * carried of them; the recipe's own extensions are kept and must exist on this machine, or the launch is refused. Every other argument is the recipe's. */
61
+ export function localExtensionArgv(argv) {
62
+ // A canvas hook of the control plane's release is dropped whether or not this install still ships it: this install's own list replaces them.
63
+ // `isShippedCanvasExtension` knows the hooks by name; `system-prompt-entry` is mandatory but not one of them, and a hook this install retired has no local file.
64
+ const stem = (path) => basename(path).replace(/\.[jt]s$/, '');
65
+ const mandatoryStems = new Set(CANVAS_EXTENSIONS.map(stem));
66
+ const shipped = (path) => isShippedCanvasExtension(path) || (basename(dirname(path)) === 'pi-extensions' && (mandatoryStems.has(stem(path)) || (stem(path).startsWith('canvas-') && !existsSync(path))));
67
+ const rest = [];
68
+ const custom = [];
69
+ for (let i = 0; i < argv.length; i++) {
70
+ if (argv[i] === '-e' && argv[i + 1] !== undefined) {
71
+ const path = argv[++i];
72
+ if (shipped(path))
73
+ continue;
74
+ if (!existsSync(path))
75
+ throw new Error(`extension ${path} does not exist on this machine`);
76
+ custom.push(path);
77
+ }
78
+ else
79
+ rest.push(argv[i]);
80
+ }
81
+ return [...mergeCanvasExtensions(custom).flatMap((path) => ['-e', path]), ...rest];
82
+ }
83
+ /** The recipe this machine's broker reads from `broker-launch.json` (the broker merges its `env` into `process.env` and loads its `argv` extensions):
84
+ * the control plane's recipe with the machine-local paths above. */
85
+ export function machineLaunchRecipe(launchJson, node, start) {
86
+ const recipe = JSON.parse(launchJson);
87
+ return JSON.stringify({ ...recipe, argv: localExtensionArgv(recipe.argv), env: localLaunchEnv(recipe.env ?? {}, node), ...(start === undefined ? {} : { start }) });
88
+ }
89
+ /** The env a machine's broker starts with: what the process runner's `buildBrokerEnv` builds for the same node. The environment's secret rows come from the
90
+ * control plane in the start bundle with the profile's metadata (this role has no database and no profiles, so the profile is never looked up here); the operational base, the profile's metadata, the app's pi dir and the launch recipe's env
91
+ * go over them in `buildBrokerEnv`'s order, and the link's own settings are pinned last. The recipe's path-shaped keys are this machine's (`localLaunchEnv`). */
92
+ export function machineBrokerEnv(bundle, deps, executionId) {
93
+ const launch = bundle.launch;
94
+ const env = overlayBrokerEnv({ argv: [], env: localLaunchEnv(launch.env ?? {}, bundle.node) }, composeAppProcessEnv(bundle.node.cwd, null, bundle.node.app, bundle.machine_env ?? {}, {}));
95
+ return Object.assign(env, { CRTR_HOME: layoutRoot(), CRTR_RUNTIME_HOME: process.env['CRTR_RUNTIME_HOME'] ?? runtimeRoot(), CRTR_API_URL: deps.apiUrl, CRTR_EXECUTION_ID: executionId, CRTR_ENVIRONMENT_ID: deps.environmentId, CRTR_VIEW_WSS: '0', [FRONT_DOOR_ENV]: '1' });
96
+ }
97
+ /** Stop one broker and its whole process tree: SIGTERM, `graceMs` for it to exit, then SIGTERM and SIGKILL to what remains of the tree. */
98
+ async function stopBroker(pid, graceMs, excludePid) {
99
+ // The tree is captured before any signal: once the broker dies, its detached children are reparented away from it and a later walk cannot find them.
100
+ const { tree, identities } = captureTeardownSnapshot(pid, null, excludePid);
101
+ if (identities === null)
102
+ return { confirmed: false, error: `the process tree of broker ${pid} could not be read, so shutdown cannot be confirmed` };
103
+ const waitUntilDead = async (pids, ms) => {
104
+ for (let waited = 0; isAnyPidAlive(pids); waited += 100) {
105
+ if (waited >= ms)
106
+ return false;
107
+ await sleep(100);
108
+ }
109
+ return true;
110
+ };
111
+ try {
112
+ process.kill(pid, 'SIGTERM');
113
+ }
114
+ catch { /* gone */ }
115
+ await waitUntilDead([pid], graceMs);
116
+ // The broker is down or ignored SIGTERM; whatever of its tree remains (detached bash work included) is ended.
117
+ killProcessTreePids(tree, 'SIGTERM', identities);
118
+ if (await waitUntilDead(tree, 2_000))
119
+ return { confirmed: true };
120
+ killProcessTreePids(tree, 'SIGKILL', identities);
121
+ return await waitUntilDead(tree, 5_000) ? { confirmed: true } : { confirmed: false, error: `broker process tree of ${pid} survived SIGKILL` };
122
+ }
123
+ /** Stop every broker of this crtr home (a machine daemon starting with no sign-in, design-crtr-northlight-signin component 5). A broker of another
124
+ * home on the same computer (its `--canvas-home` differs) is not touched. Rejects when the process table cannot be read or a broker's tree survives
125
+ * SIGKILL, so the caller never reports stopped while something of this home may still run. */
126
+ export async function stopAllBrokers(graceMs = 10_000) {
127
+ const outcomes = await Promise.all((await findBrokers()).filter((broker) => brokerCommandDeclaresCanvasHome(broker.command, crtrHome())).map((broker) => stopBroker(broker.pid, graceMs)));
128
+ const survivors = outcomes.filter((outcome) => !outcome.confirmed);
129
+ if (survivors.length > 0)
130
+ throw new Error(survivors.map((outcome) => outcome.error ?? 'a broker did not stop').join('; '));
131
+ }
132
+ export function createMachineExecutor(deps) {
133
+ const stopGraceMs = (deps.stopGraceS ?? 10) * 1000;
134
+ const brokerOf = async (executionId) => (await findBrokers()).find((b) => b.execution === executionId);
135
+ return {
136
+ async start(args, signal) {
137
+ const timings = {};
138
+ let stepStart = performance.now();
139
+ const stepDone = (name) => { const now = performance.now(); timings[name] = Math.round((now - stepStart) * 10) / 10; stepStart = now; };
140
+ const existing = await brokerOf(args.executionId);
141
+ stepDone('process_lookup');
142
+ if (existing !== undefined)
143
+ return { pid: existing.pid, timings };
144
+ signal?.throwIfAborted();
145
+ // Known launch errors are refused now, so the control plane reads a launch failure, not a silent start.
146
+ if (!existsSync(args.cwd) || !statSync(args.cwd).isDirectory())
147
+ throw new Error(`the node's cwd ${args.cwd} is not a directory on this machine`);
148
+ if (!existsSync(brokerEntry()))
149
+ throw new Error(`the broker entry ${brokerEntry()} does not exist`);
150
+ // A control plane older than this Mac (a rollback, or a pod still rolling) may send a start from its runner without one.
151
+ if (args.bundle === undefined)
152
+ throw new Error('the control plane carried no start bundle: it runs an older release than this Mac');
153
+ const { bundle } = args;
154
+ const launch = bundle.launch;
155
+ const runDir = nodeRunDir(args.nodeId);
156
+ mkdirSync(runDir, { recursive: true });
157
+ writeFileBeneath(runDir, join(runDir, 'broker-launch.json'), machineLaunchRecipe(args.launchJson, bundle.node, args.start), { atomic: true, mode: 0o600 });
158
+ if (launch.env?.['CRTR_SCOPES_FILE'] !== undefined)
159
+ writeFileBeneath(runDir, scopesFilePath(args.nodeId), JSON.stringify(launch.scopes ?? []), { atomic: true });
160
+ const logDir = jobDir(args.nodeId);
161
+ mkdirSync(logDir, { recursive: true });
162
+ const logFd = openSync(join(logDir, 'broker.log'), 'a');
163
+ const env = machineBrokerEnv(bundle, deps, args.executionId);
164
+ delete env['CRTR_NODE_TOKEN'];
165
+ stepDone('file_writes');
166
+ try {
167
+ // The link may have dropped meanwhile: the control plane already read this call as unanswered, so nothing is spawned for it.
168
+ signal?.throwIfAborted();
169
+ const child = spawn(process.execPath, [brokerEntry(), '--canvas-home', crtrHome(), '--epoch', args.executionId, args.nodeId], { cwd: args.cwd, detached: true, stdio: ['ignore', logFd, logFd, 'pipe'], env });
170
+ // Listening from the spawn on, so a broker that dies before the launch finishes is still reported once it has.
171
+ let exited;
172
+ let launched = false;
173
+ const report = () => { if (exited !== undefined)
174
+ deps.onExit?.({ execution: args.executionId, node: args.nodeId, ...exited }); };
175
+ child.once('exit', (code, signal) => { exited = { code, signal }; if (launched)
176
+ report(); });
177
+ const pipe = child.stdio[3];
178
+ if (pipe === null || pipe === undefined || !('end' in pipe)) {
179
+ killGroup(child.pid);
180
+ throw new Error('broker token pipe did not open');
181
+ }
182
+ const pid = await new Promise((resolve, reject) => {
183
+ child.once('error', reject);
184
+ child.once('spawn', () => {
185
+ child.off('error', reject);
186
+ // After spawn, a pipe failure is a launch failure; a later child exit is ordinary status recovery.
187
+ pipe.once('error', (error) => { killGroup(child.pid); reject(error); });
188
+ pipe.end(args.nodeToken, (error) => { if (error)
189
+ reject(error);
190
+ else
191
+ resolve(child.pid); });
192
+ });
193
+ });
194
+ launched = true;
195
+ report();
196
+ child.unref();
197
+ stepDone('spawn_and_token_pipe');
198
+ emitEvent({ level: 'info', event: 'machine.start.timing', node_id: args.nodeId, fields: { execution: args.executionId, ...timings } });
199
+ return { pid, timings };
200
+ }
201
+ finally {
202
+ closeSync(logFd);
203
+ }
204
+ },
205
+ async wake({ execution }) {
206
+ const broker = await brokerOf(execution.executionId);
207
+ if (broker === undefined)
208
+ return 'no_broker';
209
+ try {
210
+ process.kill(broker.pid, 'SIGUSR1');
211
+ return 'signalled';
212
+ }
213
+ catch (error) {
214
+ if (error.code === 'ESRCH')
215
+ return 'no_broker';
216
+ throw error;
217
+ }
218
+ },
219
+ async stop({ execution, options }) {
220
+ const broker = await brokerOf(execution.executionId);
221
+ return broker === undefined ? { confirmed: true } : await stopBroker(broker.pid, stopGraceMs, options.excludePid);
222
+ },
223
+ async status({ execution }) {
224
+ const broker = await brokerOf(execution.executionId);
225
+ return broker === undefined ? { state: 'gone' } : { state: 'running', pid: broker.pid };
226
+ },
227
+ async delete({ nodeId }) {
228
+ await rm(nodeRunDir(nodeId), { recursive: true, force: true });
229
+ return null;
230
+ },
231
+ async viewer({ execution }) {
232
+ return { kind: 'unix', path: viewSocketPath(execution.nodeId) };
233
+ },
234
+ };
235
+ }
@@ -1,5 +1,5 @@
1
1
  export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
2
- 'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'repo.identify'];
2
+ 'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'worktree.sweep', 'repo.identify'];
3
3
  /** No live link row for the environment: the caller leaves its work pending and retries on its own backoff. */
4
4
  export class MachineOfflineError extends Error {
5
5
  environmentId;
@@ -40,23 +40,105 @@ export function identifiedMessages(entries, leafId) {
40
40
  const byId = new Map(entries.map((e) => [e.id, e]));
41
41
  return buildContextEntries(entries, leafId, byId).flatMap((entry) => sessionEntryToContextMessages(entry).map((message) => ({ id: entry.id, message: message })));
42
42
  }
43
+ /** An earlier cycle's message as display text: user and assistant text only, without the yield's abort. */
44
+ function earlierText(item) {
45
+ const m = item.message;
46
+ if (m.role !== 'user' && m.role !== 'assistant')
47
+ return undefined;
48
+ const content = typeof m.content === 'string' ? m.content : m.content.filter((part) => part.type === 'text');
49
+ return content.length > 0 ? { ...item, message: { ...withoutYieldAbort(m), content } } : undefined;
50
+ }
51
+ function isCycleMarker(entry) {
52
+ return entry?.type === 'custom' && entry.customType === CRTR_CYCLE_CUSTOM_TYPE;
53
+ }
54
+ /** The line shown where a cycle starts. */
55
+ export function cycleDivider(marker) {
56
+ const data = marker.data;
57
+ return { id: marker.id, message: { role: 'custom', customType: CRTR_CYCLE_CUSTOM_TYPE, content: `cycle ${data?.cycle ?? ''} begins with a fresh context window`, display: true, timestamp: new Date(marker.timestamp).getTime() } };
58
+ }
59
+ /** True for the line `cycleDivider` shows where a cycle starts. */
60
+ export function isCycleDivider(message) {
61
+ return message.role === 'custom' && message.customType === CRTR_CYCLE_CUSTOM_TYPE;
62
+ }
43
63
  /** A whole conversation for display: each earlier cycle as user and assistant
44
64
  * text only, one line where each cycle starts, then the current cycle in full. */
45
65
  export function transcriptMessages(entries, leafId) {
46
66
  const out = [];
47
67
  for (const marker of entries) {
48
- if (marker.type !== 'custom' || marker.customType !== CRTR_CYCLE_CUSTOM_TYPE)
68
+ if (!isCycleMarker(marker))
49
69
  continue;
50
70
  const data = marker.data;
51
71
  for (const item of data?.fromLeaf ? identifiedMessages(entries, data.fromLeaf) : []) {
52
- const m = item.message;
53
- if (m.role !== 'user' && m.role !== 'assistant')
54
- continue;
55
- const content = typeof m.content === 'string' ? m.content : m.content.filter((part) => part.type === 'text');
56
- if (content.length > 0)
57
- out.push({ ...item, message: { ...withoutYieldAbort(m), content } });
72
+ const text = earlierText(item);
73
+ if (text !== undefined)
74
+ out.push(text);
58
75
  }
59
- out.push({ id: marker.id, message: { role: 'custom', customType: CRTR_CYCLE_CUSTOM_TYPE, content: `cycle ${data?.cycle ?? ''} begins with a fresh context window`, display: true, timestamp: new Date(marker.timestamp).getTime() } });
76
+ out.push(cycleDivider(marker));
60
77
  }
61
78
  return [...out, ...identifiedMessages(entries, leafId)];
62
79
  }
80
+ /** Up to `count` cycles before the current one, oldest first, as `transcriptMessages` shows them, from
81
+ * `entries`: the end of the conversation before `currentMarker`, which may start inside an earlier cycle.
82
+ * A cycle cut by that start shows its newest messages only. Ends with `currentMarker`'s divider. */
83
+ export function earlierCycleMessages(entries, currentMarker, count) {
84
+ if (!isCycleMarker(currentMarker))
85
+ return [];
86
+ const byId = new Map(entries.map((e) => [e.id, e]));
87
+ const cycles = [];
88
+ let marker = currentMarker;
89
+ while (cycles.length < count) {
90
+ const leaf = marker.data?.fromLeaf;
91
+ if (!leaf || !byId.has(leaf))
92
+ break;
93
+ const messages = identifiedMessages(entries, leaf).flatMap((item) => earlierText(item) ?? []);
94
+ let root = byId.get(leaf);
95
+ while (root.parentId && byId.has(root.parentId))
96
+ root = byId.get(root.parentId);
97
+ cycles.unshift(isCycleMarker(root) ? [cycleDivider(root), ...messages] : messages);
98
+ if (!isCycleMarker(root))
99
+ break;
100
+ marker = root;
101
+ }
102
+ // The oldest cycle shown begins at its first message; its own start line belongs to the cycle before it.
103
+ if (cycles.length > 0 && cycles[0][0] !== undefined && isCycleDivider(cycles[0][0].message))
104
+ cycles[0] = cycles[0].slice(1);
105
+ return [...cycles.flat(), cycleDivider(currentMarker)];
106
+ }
107
+ /** Earlier cycles a welcome shows. */
108
+ export const WELCOME_EARLIER_CYCLES = 2;
109
+ /** Bytes of the conversation before the current cycle a broker reads for its welcome's earlier cycles. */
110
+ export const WELCOME_EARLIER_BYTES = 4 * 1024 * 1024;
111
+ /** JSON bytes of the current cycle a welcome carries: its newest messages that fit. */
112
+ export const WELCOME_CURRENT_BYTES = 2 * 1024 * 1024;
113
+ /** A welcome's window over a display transcript (`transcriptMessages` shape): the last
114
+ * `WELCOME_EARLIER_CYCLES` earlier cycles in full, then the current cycle's newest messages
115
+ * within `WELCOME_CURRENT_BYTES` of JSON (always at least the newest). Returns the index of the
116
+ * first message kept; `size` gives a message's JSON bytes. */
117
+ export function welcomeWindow(messages, size) {
118
+ let current = 0;
119
+ for (let i = messages.length - 1; i >= 0; i--)
120
+ if (isCycleDivider(messages[i])) {
121
+ current = i + 1;
122
+ break;
123
+ }
124
+ let start = messages.length;
125
+ let bytes = 0;
126
+ while (start > current) {
127
+ bytes += size(messages[start - 1]);
128
+ if (bytes > WELCOME_CURRENT_BYTES && start < messages.length)
129
+ break;
130
+ start--;
131
+ }
132
+ if (start > current)
133
+ return { start };
134
+ // The whole current cycle fits: keep the earlier cycles too, from after the start line of the oldest one shown.
135
+ let dividers = 0;
136
+ for (let i = current - 1; i >= 0; i--) {
137
+ if (!isCycleDivider(messages[i]))
138
+ continue;
139
+ dividers++;
140
+ if (dividers > WELCOME_EARLIER_CYCLES)
141
+ return { start: i + 1 };
142
+ }
143
+ return { start: 0 };
144
+ }
@@ -314,6 +314,17 @@ export function paneLocation(pane) {
314
314
  return null;
315
315
  return { session: match[1], window: match[2] };
316
316
  }
317
+ /** A pane's session and window and pane position, as a person counts them (`#{window_index}`, `#{pane_index}`). Null if the pane is gone or tmux fails. */
318
+ export function paneCoordinates(pane) {
319
+ // Space-separated like paneLocation: tmux -p escapes tabs and control characters. The window name is last, so it may hold spaces.
320
+ const r = tmux(['display-message', '-p', '-t', pane, '#{window_index} #{pane_index} #{session_name}@@@#{window_name}']);
321
+ if (!r.ok)
322
+ return null;
323
+ const match = /^(\d+) (\d+) (.+?)@@@(.*)$/s.exec(r.stdout);
324
+ if (match === null)
325
+ return null;
326
+ return { session: match[3], windowIndex: Number(match[1]), paneIndex: Number(match[2]), windowName: match[4] };
327
+ }
317
328
  /** The index tmux shows for a window target (`#{window_index}`) — the number a
318
329
  * person sees in the status line and presses after the prefix. Null if the
319
330
  * target is gone or tmux fails. */
@@ -8,6 +8,10 @@ import { abandonWorktreeAndRepoint, getNode } from './canvas/index.js';
8
8
  import { isCloudRole } from './canvas/person-state.js';
9
9
  import { callMachine } from './runtime/runner/machine/call.js';
10
10
  import { machineEnvironmentOfProfile } from './runtime/runner/machine/environment.js';
11
+ import { MachineOfflineError } from './runtime/runner/machine/ops.js';
12
+ import { findBrokers } from './runtime/runner/machine/executor.js';
13
+ import { deleteTrashAsync } from './worktree-remove.js';
14
+ import { sweepManagedWorktreeOnHost } from './worktree-sweep.js';
11
15
  import { closeManagedWorktreeOnHost, concludedCloseResult, persistCloseOutcome } from './worktree-close.js';
12
16
  import { abandonManagedWorktreeOnHost, createManagedWorktreeAsync, finalizeManagedWorktreeOnHost, rollbackManagedWorktreeAsync } from './worktree-mutation-async.js';
13
17
  import { persistClosedWorktreeState, WorktreeError } from './worktree.js';
@@ -29,6 +33,13 @@ export const machineWorktreeHandlers = {
29
33
  'worktree.close': (args) => answer(() => closeManagedWorktreeOnHost(args.nodeId, args.worktree)),
30
34
  'worktree.abandon': (args) => answer(() => abandonManagedWorktreeOnHost(args.nodeId, args.worktree, args.by)),
31
35
  'worktree.finalize': (args) => answer(() => finalizeManagedWorktreeOnHost(args.nodeId, args.worktree)),
36
+ // The node is still gone while no broker of it runs on this Mac, which owns its brokers.
37
+ // An unreadable process table counts as a running broker. The trash is deleted after the answer, so a large checkout cannot outlast the call.
38
+ 'worktree.sweep': (args) => answer(async () => {
39
+ const swept = await sweepManagedWorktreeOnHost(args.worktree, { stillEligible: () => findBrokers().then((brokers) => !brokers.some((b) => b.node === args.nodeId), () => false) }, async () => args.dependentCwds);
40
+ void deleteTrashAsync(args.worktree.path, swept.trash);
41
+ return swept;
42
+ }),
32
43
  };
33
44
  // ---------------------------------------------------------------------------------------------------------------- the control plane's side
34
45
  /** The machine environment that holds a node's checkouts: on a cloud role, the one its profile points at; else null (Git runs here). */
@@ -90,3 +101,12 @@ export async function finalizeManagedWorktreeOnMachine(environmentId, nodeId) {
90
101
  }
91
102
  return outcome.kind === 'open' ? { ...outcome, worktree: wt } : outcome;
92
103
  }
104
+ /** The sweep's Git work on the Mac that holds the node's checkout; the lane writes the rows from the answer. */
105
+ export function sweepOnMachine(environmentId, nodeId) {
106
+ const none = { base: null, upstream: null, branch: null, checkout: null };
107
+ return (worktree, dependentCwds) => callWorktree(environmentId, 'worktree.sweep', { nodeId, worktree, dependentCwds }).catch((error) => ({
108
+ // Offline says nothing about the checkout: no refusal, no backoff. A lost or timed-out call is a failure, retried with backoff.
109
+ outcome: error instanceof MachineOfflineError ? { status: 'skipped', reason: 'machine_offline' } : { status: 'failed', reason: 'machine_call_failed', detail: error instanceof Error ? error.message : String(error) },
110
+ observed: none,
111
+ }));
112
+ }