@north-light/cli 0.3.760 → 0.3.762

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 (49) hide show
  1. package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
  2. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  3. package/dist/cli.js +5 -5
  4. package/dist/clients/attach/config.js +1 -1
  5. package/dist/clients/attach/viewer.js +467 -467
  6. package/dist/commands/api-client.d.ts +0 -5
  7. package/dist/commands/api-client.js +3 -3
  8. package/dist/commands/daemon-generation.js +1 -1
  9. package/dist/commands/sys/import/move.d.ts +1 -34
  10. package/dist/commands/sys/import/move.js +5 -9
  11. package/dist/commands/sys/import/start.d.ts +0 -3
  12. package/dist/commands/sys/import/start.js +1 -1
  13. package/dist/commands/sys/signin.js +2 -2
  14. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -0
  15. package/dist/core/canvas/managed-worktree-sweep-candidates.js +6 -4
  16. package/dist/core/command.d.ts +1 -1
  17. package/dist/core/runtime/front-door.js +9 -10
  18. package/dist/core/user-settings.d.ts +2 -2
  19. package/dist/core/worktree-mutation-async.js +5 -5
  20. package/dist/core/worktree-scripts.d.ts +13 -0
  21. package/dist/core/worktree-scripts.js +5 -0
  22. package/dist/core/worktree-sweep.js +4 -4
  23. package/dist/daemon/api/handlers/daemon.js +1 -1
  24. package/dist/daemon/crtrd.js +12 -12
  25. package/dist/daemon/import-dump-run.js +4 -4
  26. package/dist/daemon/machine-daemon.js +1 -1
  27. package/dist/daemon/machine-link/config.d.ts +0 -24
  28. package/dist/daemon/machine-link/config.js +4 -4
  29. package/dist/daemon/manage.d.ts +1 -1
  30. package/package.json +3 -3
  31. package/packages/crouter-api/dist/clients/attach/config.js +2 -1
  32. package/packages/crouter-api/dist/commands/api-client.js +1 -12
  33. package/packages/crouter-api/dist/commands/sys/import/move.js +5 -205
  34. package/packages/crouter-api/dist/commands/sys/import/start.js +15 -51
  35. package/packages/crouter-api/dist/commands/sys/signin.js +13 -54
  36. package/packages/crouter-api/dist/core/worktree-mutation-async.js +11 -3
  37. package/packages/crouter-api/dist/core/worktree-scripts.js +72 -0
  38. package/packages/crouter-api/dist/core/worktree-sweep.js +10 -1
  39. package/packages/crouter-api/dist/daemon/machine-link/config.js +1 -27
  40. package/packages/crouter-api/package.json +1 -1
  41. package/packages/crouter-identity/package.json +1 -1
  42. package/packages/crouter-plugin/package.json +3 -3
  43. package/runtime.lock.json +14 -14
  44. package/dist/commands/sys/import/retry.d.ts +0 -1
  45. package/dist/commands/sys/import/retry.js +0 -1
  46. package/dist/daemon/machine-link/move-notify.d.ts +0 -4
  47. package/dist/daemon/machine-link/move-notify.js +0 -1
  48. package/packages/crouter-api/dist/commands/sys/import/retry.js +0 -38
  49. package/packages/crouter-api/dist/daemon/machine-link/move-notify.js +0 -15
@@ -1,26 +1,21 @@
1
- // The exporter's run (design-import "Exporter") and the move of a person's computer into their Northlight account (design-crtr-northlight-signin
2
- // component 4): `exportRun` uploads, drains, dumps and loads one run; `runMove` wraps it for a computer with the move record, the two commit
3
- // boundaries (the cloud run reaching `done`; activation) and the messages to the node that asked; `finishMove` is activation, shared with
4
- // `crtr sys signin` finishing an unfinished switch-over.
1
+ // The hosted exporter's run (design-import "Exporter"): `exportRun` uploads, drains, dumps and loads one run. `registerThisMac` is `crtr sys signin`'s directory registration.
5
2
  import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
6
3
  import { tmpdir } from 'node:os';
7
4
  import { join } from 'node:path';
8
5
  import { CrtrError, general } from '../../../core/errors.js';
9
6
  import { ExitCode } from '../../../types.js';
10
7
  import { cliClient } from '../../api-client.js';
11
- import { ImportCloud, STORE_FILE, STORE_ORDER } from '../../../core/import/export/cloud.js';
8
+ import { STORE_FILE, STORE_ORDER } from '../../../core/import/export/cloud.js';
12
9
  import { Uploader, localObjects, reviewSourceObject } from '../../../core/import/export/files.js';
13
10
  import { BODIES_TABLE, bundleKeys } from '../../../core/import/bundle/layout.js';
14
11
  import { crtrVersion } from '../../../shared/crtr-version.js';
15
12
  import { nodeArchive } from '../../../core/import/export/archive.js';
16
13
  import { buildSourceJson } from '../../../core/import/export/source.js';
17
- import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId, spawnDaemon, stopAllDaemons } from '../../../daemon/manage.js';
18
- import { deleteMoveRecord, moveUnfinishedError, readMachineConfig, readMoveRecord, writeMachineConfig, writeMachineCredential, writeMoveRecord } from '../../../daemon/machine-link/config.js';
19
- import { notifyMoveFinished } from '../../../daemon/machine-link/move-notify.js';
14
+ import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId } from '../../../daemon/manage.js';
15
+ import { readMachineConfig } from '../../../daemon/machine-link/config.js';
20
16
  import { registerSignedInMac } from '../../../core/directory/join.js';
21
- import { controlPlaneUrl, forgetSignIn, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../../core/directory/person-credential.js';
17
+ import { personBearer, readPersonCredential } from '../../../core/directory/person-credential.js';
22
18
  import { NORTHLIGHT_DIRECTORY_URL } from '../../../core/directory/issuer.js';
23
- import { isPidAlive } from '../../../core/canvas/pid.js';
24
19
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
25
20
  /** The directory a sign-in or move uses when none is typed: `runtime/machine.json`'s, else the stored sign-in's, else Northlight's (design D5). */
26
21
  export function defaultDirectoryUrl() {
@@ -198,29 +193,6 @@ export async function exportRun(kind, cloud, existingRun, step, onStarted = () =
198
193
  }
199
194
  }
200
195
  }
201
- /** Activation, the second commit boundary: the asking node's message first (stored in the account as mail; the node can wake only once the machine
202
- * link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
203
- * crtrd in machine role, and the move record's deletion. Safe to repeat. */
204
- export async function finishMove(move) {
205
- await notifyMoveFinished(move);
206
- const cloud = new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl));
207
- let credential;
208
- try {
209
- credential = await cloud.machineCredential(move.runId);
210
- }
211
- catch (error) {
212
- if (!(error instanceof CrtrError) || error.details?.['code'] !== 'credential_exists')
213
- throw error;
214
- credential = await cloud.machineCredential(move.runId, true);
215
- }
216
- writeMachineCredential(credential.credential);
217
- writeMachineConfig({ apiUrl: move.apiUrl, environmentId: credential.environment_id, runId: move.runId, directoryUrl: move.directoryUrl, account: move.account });
218
- await registerThisMac(move.directoryUrl);
219
- await stopAllDaemons();
220
- await spawnDaemon();
221
- // Only now has the computer switched over: until the machine-role daemon is up the record keeps every command at `move_unfinished`.
222
- deleteMoveRecord();
223
- }
224
196
  /** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
225
197
  export async function registerThisMac(directoryUrl) {
226
198
  try {
@@ -231,175 +203,3 @@ export async function registerThisMac(directoryUrl) {
231
203
  process.stderr.write(`this computer was not registered with the directory: ${error instanceof Error ? error.message : String(error)}\nRun \`crtr sys signin\` again to register it.\n`);
232
204
  }
233
205
  }
234
- const ACTIVATION_ATTEMPTS = 3;
235
- const ACTIVATION_GAP_MS = 30_000;
236
- /** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
237
- * sign-in is revoked and deleted, the move record goes, and `notify` (a node) is told through the local daemon. After `done` the move record says
238
- * `committed` and activation is retried three times over a minute; still failing, the record, the sign-in and the drain stay for `crtr sys signin`. */
239
- export async function runMove(opts) {
240
- const step = { name: 'sign-in', timings: [] };
241
- let move;
242
- let runId = '';
243
- let base;
244
- try {
245
- const account = await personAccount(opts.directoryUrl);
246
- const apiUrl = opts.apiUrl ?? await controlPlaneUrl(opts.directoryUrl);
247
- const cloud = new ImportCloud(apiUrl, () => personBearer(opts.directoryUrl));
248
- base = { apiUrl, directoryUrl: opts.directoryUrl, account, notify: opts.notify, notified: false, pid: process.pid };
249
- await exportRun('machine', cloud, undefined, step, (id) => { runId = id; writeMoveRecord({ ...base, runId: id, state: 'running' }); }, deleteMoveRecord);
250
- }
251
- catch (error) {
252
- // Once `load` was sent and its outcome is unknown, the record and the drain stay: the next starter (`crtr sys signin`, the local daemon's start)
253
- // asks the control plane and settles the move.
254
- if (error instanceof CrtrError && error.code === 'move_outcome_unknown')
255
- throw error;
256
- throw await undoMove(step.name, error, opts.notify);
257
- }
258
- // The run is `done`: from here nothing may undo the move, so a failed record write is reported as it is and the `running` record settles to `committed` later.
259
- move = { ...base, runId, state: 'committed' };
260
- writeMoveRecord(move);
261
- let last;
262
- const activating = Date.now();
263
- for (let attempt = 1; attempt <= ACTIVATION_ATTEMPTS; attempt++) {
264
- try {
265
- await finishMove(move);
266
- step.timings.push(`restart=${((Date.now() - activating) / 1000).toFixed(1)}s`);
267
- process.stderr.write(`restart ${((Date.now() - activating) / 1000).toFixed(1)}s\n`);
268
- return { runId: move.runId, account: move.account.display, timings: step.timings.join(' ') };
269
- }
270
- catch (error) {
271
- last = error;
272
- process.stderr.write(`switch-over attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}\n`);
273
- if (attempt < ACTIVATION_ATTEMPTS)
274
- await sleep(ACTIVATION_GAP_MS);
275
- move = readMoveRecord() ?? move;
276
- }
277
- }
278
- throw moveUnfinishedError(last instanceof Error ? last.message : String(last));
279
- }
280
- /** Undo a move that never reached `done` (the drain is already confirmed ended), tell the asking node, and return the error to throw. */
281
- async function undoMove(step, error, notify) {
282
- const reason = error instanceof Error ? error.message : String(error);
283
- const still = error instanceof CrtrError && error.code === 'drain_not_ended' ? 'crtr is still local, but its pause could not be ended: run `crtr sys import resume`' : 'crtr is still local and working as before';
284
- const failed = `The move to Northlight failed at ${step}: ${reason}. ${still}.`;
285
- const revokeFailure = await dropMove(failed, notify);
286
- const code = error instanceof CrtrError && error.code !== 'error' ? error.code : (error instanceof CrtrError && typeof error.details?.['code'] === 'string' ? error.details['code'] : 'move_failed');
287
- return new CrtrError(code, `the move to Northlight failed at ${step}: ${reason}. ${still}, and ${signedOutText(revokeFailure)}`, ExitCode.GENERAL);
288
- }
289
- /** What the person is told about the sign-in a failed move removes: revoked at Northlight, or removed here only. */
290
- const signedOutText = (revokeFailure) => revokeFailure === undefined ? 'this computer is signed out.' : `this computer's sign-in was removed here but could not be revoked at Northlight (${revokeFailure}); revoke it on your Northlight account page.`;
291
- /** The shared end of a failed move: delete the record, sign this computer out, and tell the node that asked (a failed revoke is added to its
292
- * message). Returns why the sign-in could not be revoked at Northlight, or undefined when it was revoked or already ended: the secret is deleted here either way,
293
- * so a failed revoke leaves one that is still valid there. */
294
- async function dropMove(message, notify) {
295
- deleteMoveRecord();
296
- let revokeFailure;
297
- try {
298
- await signOut();
299
- }
300
- catch (error) {
301
- forgetSignIn();
302
- revokeFailure = error instanceof Error ? error.message : String(error);
303
- process.stderr.write(`could not revoke the sign-in at Northlight: ${revokeFailure}\n`);
304
- }
305
- if (notify === null)
306
- return revokeFailure;
307
- try {
308
- await cliClient({ local: true }).sendMessage(notify, { from: null, body: `${message} Tell the person the move failed.${revokeFailure === undefined ? '' : ` ${signedOutText(revokeFailure)}`}` });
309
- }
310
- catch (sendError) {
311
- process.stderr.write(`could not message ${notify}: ${sendError instanceof Error ? sendError.message : String(sendError)}\n`);
312
- }
313
- return revokeFailure;
314
- }
315
- /** Where an earlier move stands before a new sign-in or move starts, and when the local daemon starts. A `running` record whose exporter is alive
316
- * refuses; one whose exporter died is settled against the control plane, and only its positive answer moves it: a run that reached `done` becomes
317
- * `committed` (returned, so the caller finishes the switch-over); a run still loading there refuses until it settles; a run that failed or never
318
- * loaded is a failed move, undone here (record deleted and drain ended and confirmed, sign-in revoked, the asking node told). Any other outcome —
319
- * the control plane unreachable or refusing, no working sign-in — leaves the record and the drain as they are and throws. With no working sign-in
320
- * `show` signs back in first, and only to the account that owns the move (another account is refused, nothing written); without `show` (the daemon) it throws `not_signed_in`.
321
- * Answers the committed record, or undefined when no move is left (an `activated` record only awaits its notification, which the machine daemon sends). */
322
- export async function settleEarlierMove(show) {
323
- const move = readMoveRecord();
324
- if (move === undefined || move.state === 'activated')
325
- return undefined;
326
- const signBackIn = async () => {
327
- await signIn(move.directoryUrl, show, { accept: async (approved) => approved.account.id === move.account.id ? undefined
328
- : new CrtrError('signin_other_account', `This computer's move belongs to the Northlight account ${move.account.display}. Sign in to that account.`, ExitCode.USAGE) });
329
- };
330
- if (move.state === 'committed') {
331
- if (show !== undefined) {
332
- try {
333
- await personAccount(move.directoryUrl);
334
- }
335
- catch (error) {
336
- if (!(error instanceof CrtrError && error.code === 'not_signed_in'))
337
- throw error;
338
- await signBackIn();
339
- }
340
- }
341
- return move;
342
- }
343
- if (move.pid > 0 && isPidAlive(move.pid)) {
344
- throw new CrtrError('move_running', `a move to Northlight is already running (process ${move.pid}).`, ExitCode.USAGE, { next: 'Wait for it to finish; the node that asked is messaged when it does.' });
345
- }
346
- const ask = () => new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl)).get(move.runId);
347
- let run;
348
- try {
349
- run = await ask();
350
- }
351
- catch (error) {
352
- if (!(error instanceof CrtrError && error.code === 'not_signed_in') || show === undefined)
353
- throw error;
354
- await signBackIn();
355
- run = await ask();
356
- }
357
- if (run.state === 'done') {
358
- const committed = { ...move, state: 'committed' };
359
- writeMoveRecord(committed);
360
- return committed;
361
- }
362
- if (run.state === 'loading' || run.state === 'committed') {
363
- throw new CrtrError('move_running', 'Northlight is still loading this computer\'s records from an earlier move.', ExitCode.USAGE, { next: 'Retry in a minute.' });
364
- }
365
- if (run.state !== 'failed' && run.state !== 'rolled_back' && run.state !== 'uploading') {
366
- throw new CrtrError('move_outcome_unknown', 'Northlight did not report a settled outcome for this move.', ExitCode.GENERAL, { next: 'Run `crtr sys signin` to settle the move.' });
367
- }
368
- const step = run.failure?.step ?? 'an earlier step';
369
- const reason = run.failure == null ? 'the process that was moving this computer stopped before Northlight had the records' : run.failure.message;
370
- deleteMoveRecord();
371
- try {
372
- await endDrainConfirmed(cliClient({ local: true }));
373
- }
374
- catch (error) {
375
- throw await undoMove(step, new CrtrError('drain_not_ended', `${reason} (and ${error instanceof Error ? error.message : String(error)})`, ExitCode.GENERAL), move.notify);
376
- }
377
- await dropMove(`The move to Northlight failed at ${step}: ${reason}. crtr is still local and working as before.`, move.notify);
378
- return undefined;
379
- }
380
- const DAEMON_SETTLE_GAP_MS = 60_000;
381
- /** The daemon answers its own socket only once startup is done, which is a moment after the settle is scheduled. */
382
- const DAEMON_SETTLE_FIRST_MS = 5_000;
383
- /** The local daemon's start is a starter of the move record (design-crtr-northlight-signin component 4): a `running` record whose exporter died (a crash,
384
- * a reboot) leaves the daemon drained and the asking node untold until someone runs `crtr sys signin`, so the daemon settles it itself once it serves.
385
- * Retries every minute while the settle cannot finish (the control plane unreachable, the run still loading); a run that reached `done` stays `committed`
386
- * for `crtr sys signin`. Returns when there is nothing to settle, the exporter is alive, or `stopped()` says the daemon is closing. */
387
- export async function settleMoveAtDaemonStart(stopped, onRetry) {
388
- await sleep(DAEMON_SETTLE_FIRST_MS);
389
- while (!stopped()) {
390
- const move = readMoveRecord();
391
- if (move === undefined || move.state !== 'running' || (move.pid > 0 && isPidAlive(move.pid)))
392
- return;
393
- try {
394
- await settleEarlierMove();
395
- return;
396
- }
397
- catch (error) {
398
- onRetry(error);
399
- // No working sign-in: only the person signing back in (`crtr sys signin`) can settle it, so asking again every minute cannot help.
400
- if (error instanceof CrtrError && error.code === 'not_signed_in')
401
- return;
402
- }
403
- await sleep(DAEMON_SETTLE_GAP_MS);
404
- }
405
- }
@@ -1,36 +1,25 @@
1
1
  // `crtr sys import start`: the source side of an import (design-import, "Exporter"). Uploads blobs, drains the daemon, dumps the rows and file
2
- // stores, uploads them, asks the control plane to load, and on a computer switches this install to the machine role (`./move.ts`).
2
+ // stores, uploads them, asks the control plane to load, and (`./move.ts`).
3
3
  import { defineBranch, defineLeaf } from '../../../core/command.js';
4
4
  import { general, usage } from '../../../core/errors.js';
5
5
  import { ImportCloud } from '../../../core/import/export/cloud.js';
6
6
  import { ensureSignedIn } from '../../../core/directory/person-credential.js';
7
- import { isPidAlive } from '../../../core/canvas/pid.js';
8
7
  import { showSignIn } from '../signin.js';
9
8
  import { insideBroker } from '../join.js';
10
- import { defaultDirectoryUrl, exportRun, settleEarlierMove, finishMove, runMove } from './move.js';
9
+ import { defaultDirectoryUrl, exportRun } from './move.js';
11
10
  import { resume } from './resume.js';
12
- import { retry } from './retry.js';
13
- /** Set by `crtr sys signin` on the detached exporter it starts from inside a node: the signin process, which the exporter outlives before it drains,
14
- * so it is never in a broker's process tree. */
15
- export const WAIT_FOR_PID_ENV = 'CRTR_IMPORT_WAIT_PID';
16
- async function waitForExit(pid) {
17
- while (isPidAlive(pid))
18
- await new Promise((resolve) => setTimeout(resolve, 200));
19
- }
20
11
  const start = defineLeaf({
21
12
  name: 'start',
22
- description: 'export this runtime into the person\'s Northlight account',
23
- whenToUse: 'moving this computer or hosted runtime\'s canvas into Northlight: run it from a plain terminal, not from inside a node',
13
+ description: 'export this hosted runtime into the person\'s Northlight account',
14
+ whenToUse: 'hosting runs it inside a hosted runtime to move that runtime\'s canvas into Northlight: from a plain terminal, not from inside a node',
24
15
  help: {
25
16
  name: 'sys import start',
26
17
  summary: 'upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them',
27
- guide: 'Order: open the run, upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before; a computer\'s move also signs it out. On `done` the daemon stays drained: a hosted runtime until hosting quiesces it (`crtr sys import resume` ends it), a computer until it has switched over — machine credential, `runtime/machine.json`, daemon restarted in machine role — which is retried three times over a minute and otherwise finished by `crtr sys signin`. A machine import signs the person in first when this computer has no stored sign-in. `crtr sys signin` normally starts a computer\'s move itself. With `--run`, hosting has already opened the run: the exporter uses it and reads that run\'s import token from the environment variable `CRTR_IMPORT_TOKEN`.',
18
+ guide: 'Order: open the run (hosting already did, with `--run`), upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, archive running nodes\' files, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before. On `done` the daemon stays drained until hosting quiesces it (`crtr sys import resume` ends it). The run\'s import token is read from the environment variable `CRTR_IMPORT_TOKEN`.',
28
19
  params: [
29
- { kind: 'flag', name: 'kind', type: 'enum', choices: ['machine', 'hosted'], required: true, constraint: '`machine` for a person\'s computer, `hosted` for a hosted runtime (also archives running nodes\' files).' },
30
- { kind: 'flag', name: 'api-url', type: 'string', required: false, constraint: 'Control plane base URL (http or https). Required with `--kind hosted`; with `--kind machine` the default is the control plane the person\'s sign-in is for.' },
31
- { kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime (only with `--kind hosted`); its import token is read from `CRTR_IMPORT_TOKEN`.' },
32
- { kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https) the person signs in against, with `--kind machine`. Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
33
- { kind: 'flag', name: 'notify', type: 'string', required: false, constraint: 'With `--kind machine`: a node id told by message when the move fails or finishes.' },
20
+ { kind: 'flag', name: 'kind', type: 'enum', choices: ['hosted'], required: true, constraint: '`hosted`, the only kind: a hosted runtime (also archives running nodes\' files).' },
21
+ { kind: 'flag', name: 'api-url', type: 'string', required: true, constraint: 'Control plane base URL (http or https) hosting opened the run on.' },
22
+ { kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime; its import token is read from `CRTR_IMPORT_TOKEN`.' },
34
23
  ],
35
24
  output: [
36
25
  { name: 'run_id', type: 'string', required: true, constraint: 'The import run.' },
@@ -40,41 +29,16 @@ const start = defineLeaf({
40
29
  outputKind: 'object',
41
30
  effects: [
42
31
  'Drains the local daemon (no new wake or cron fire); the drain is a `runtime_state` row, so it survives a daemon restart. Ended on a failure before `done`; kept after `done`.',
43
- 'Machine: writes `runtime/import/move.json` (0600) from the run\'s start until the switch-over, then deletes it. On `done`: writes `runtime/machine.json` and `runtime/secrets/machine-credential` (0600) and restarts the daemon in machine role. On a failure before `done`: revokes and deletes the stored sign-in.',
44
- 'Machine with `--notify`: sends that node one message when the move fails or finishes.',
45
32
  'Opens a temporary directory holding the opened file stores (0600), removed before the command ends.',
46
33
  ],
47
34
  },
48
35
  run: async (input) => {
49
- const kind = input['kind'];
50
36
  const existingRun = input['run'] === undefined ? undefined : String(input['run']);
51
- const apiUrl = input.apiUrl === undefined ? undefined : String(input.apiUrl);
52
- const notify = input['notify'] === undefined ? null : String(input['notify']);
53
- if (kind === 'hosted') {
54
- if (apiUrl === undefined)
55
- throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
56
- if (notify !== null)
57
- throw usage('--notify names the node that asked for a computer\'s move: use it only with --kind machine');
58
- }
59
- else if (existingRun !== undefined) {
60
- throw usage('--run takes an existing run, which only a hosted import has: use --kind hosted');
61
- }
62
- const waitFor = Number(process.env[WAIT_FOR_PID_ENV] ?? '');
63
- if (Number.isInteger(waitFor) && waitFor > 0)
64
- await waitForExit(waitFor);
37
+ const apiUrl = String(input.apiUrl ?? '');
38
+ if (apiUrl === '')
39
+ throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
65
40
  if (insideBroker())
66
41
  throw general('import_inside_node: run this from a plain terminal; a node\'s broker ends with the daemon restart', { code: 'import_inside_node' });
67
- if (kind === 'machine') {
68
- const earlier = await settleEarlierMove(showSignIn);
69
- if (earlier !== undefined) {
70
- await finishMove(earlier);
71
- return { run_id: earlier.runId, state: 'done', timings: '' };
72
- }
73
- const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
74
- await ensureSignedIn(directoryUrl, showSignIn);
75
- const moved = await runMove({ directoryUrl, ...(apiUrl === undefined ? {} : { apiUrl }), notify });
76
- return { run_id: moved.runId, state: 'done', timings: moved.timings };
77
- }
78
42
  const token = (existingRun === undefined ? await ensureSignedIn(defaultDirectoryUrl(), showSignIn) : process.env['CRTR_IMPORT_TOKEN'] ?? '').trim();
79
43
  if (token === '')
80
44
  throw usage('set CRTR_IMPORT_TOKEN to the run\'s import token');
@@ -86,8 +50,8 @@ const start = defineLeaf({
86
50
  });
87
51
  export const sysImportBranch = defineBranch({
88
52
  name: 'import',
89
- description: 'move this runtime into the person\'s Northlight account',
90
- whenToUse: 'importing this computer or hosted runtime into Northlight',
91
- help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database, and on a computer switches it to the machine role.' },
92
- children: [start, resume, retry],
53
+ description: 'move this hosted runtime into the person\'s Northlight account',
54
+ whenToUse: 'importing a hosted runtime into Northlight',
55
+ help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database.' },
56
+ children: [start, resume],
93
57
  });
@@ -1,19 +1,14 @@
1
1
  // `crtr sys signin` / `crtr sys signout`: the person's own sign-in on this computer (proposal-mac-cli-auth, option A).
2
2
  import { spawn } from 'node:child_process';
3
- import { mkdirSync, openSync } from 'node:fs';
4
- import { dirname, join } from 'node:path';
5
3
  import { defineLeaf } from '../../core/command.js';
6
4
  import { CrtrError } from '../../core/errors.js';
7
5
  import { controlPlaneUrl, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../core/directory/person-credential.js';
8
- import { hasLocalCanvas, moveRecordPath, readMachineConfig, readOrCreateInstallId, writeMachineConfig, writeMachineCredential } from '../../daemon/machine-link/config.js';
9
- import { probeDaemonHealth, sanitizedDaemonEnv, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
6
+ import { hasLocalCanvas, readMachineConfig, readOrCreateInstallId, writeMachineConfig, writeMachineCredential } from '../../daemon/machine-link/config.js';
7
+ import { probeDaemonHealth, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
10
8
  import { hostname } from 'node:os';
11
9
  import { northlightUnreachable } from '../../core/directory/reach.js';
12
- import { envNodeId } from '../../shared/env.js';
13
10
  import { ExitCode } from '../../types.js';
14
- import { insideBroker } from './join.js';
15
- import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
16
- import { WAIT_FOR_PID_ENV } from './import/start.js';
11
+ import { defaultDirectoryUrl, registerThisMac } from './import/move.js';
17
12
  /** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
18
13
  function openBrowser(url) {
19
14
  const [command, args] = process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
@@ -50,19 +45,6 @@ function sameAccountOnly(machine) {
50
45
  return new CrtrError('signin_unchecked', `the control plane did not say which account owns this computer (HTTP ${response.status}); nothing was written.`, ExitCode.GENERAL, { next: 'Retry `crtr sys signin`.' });
51
46
  };
52
47
  }
53
- /** Start the move in a process of its own: a node's tool call cannot run it, because the drain waits for that very turn to end and the restart
54
- * ends the broker it runs under. The exporter waits for this process to exit, so it is outside every broker's process tree when it drains. */
55
- function startDetachedMove(notify) {
56
- const log = join(dirname(moveRecordPath()), 'move.log');
57
- mkdirSync(dirname(log), { recursive: true });
58
- const fd = openSync(log, 'a', 0o600);
59
- const env = sanitizedDaemonEnv();
60
- for (const key of ['CRTR_API_SOCKET', 'CRTR_API_TOKEN', 'CRTR_API_URL'])
61
- delete env[key];
62
- env[WAIT_FOR_PID_ENV] = String(process.pid);
63
- const args = [...process.execArgv, process.argv[1], 'sys', 'import', 'start', '--kind', 'machine', ...(notify === undefined ? [] : ['--notify', notify])];
64
- spawn(process.execPath, args, { detached: true, stdio: ['ignore', fd, fd], env }).unref();
65
- }
66
48
  /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
67
49
  * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
68
50
  export async function registerFreshComputer(directoryUrl) {
@@ -94,47 +76,32 @@ export async function registerFreshComputer(directoryUrl) {
94
76
  await spawnDaemon();
95
77
  return { account: account.display };
96
78
  }
97
- const MOVING = (account) => `Signed in as ${account}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`;
98
79
  export const sysSigninLeaf = defineLeaf({
99
80
  name: 'signin',
100
81
  description: 'sign this computer\'s crtr in to the person\'s Northlight account and register it as one of their machines',
101
- whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`',
82
+ whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in`',
102
83
  help: {
103
84
  name: 'sys signin',
104
- summary: 'pair this computer with the person\'s Northlight account in the browser, move this computer\'s records into it, and register it with the directory',
105
- guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account\'s move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account\'s machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
85
+ summary: 'pair this computer with the person\'s Northlight account in the browser, register it as one of their machines, and register it with the directory',
86
+ guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. A computer already registered accepts only the account it was registered under. A computer holding a local canvas and no `runtime/machine.json` is refused with `local_canvas_unsupported`: moving a local canvas into Northlight is no longer supported. A computer is also registered with the directory: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
106
87
  params: [
107
88
  { kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
108
89
  ],
109
90
  output: [
110
91
  { name: 'account', type: 'string', required: true, constraint: 'The account this computer is now signed in as.' },
111
- { name: 'moved', type: 'boolean', required: false, constraint: 'Present when this command moved the records, or finished an earlier move\'s switch-over.' },
112
- { name: 'moving', type: 'boolean', required: false, constraint: 'Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails.' },
113
92
  ],
114
93
  outputKind: 'object',
115
94
  effects: [
116
95
  'Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.',
117
- 'Starts the local daemon first when it is not running, and waits until it serves.',
118
- 'On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account\'s result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.',
119
- 'On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
120
- 'On a moved computer: restarts the daemon so it reconnects to Northlight.',
96
+ 'On a computer with no `machine.json`: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
97
+ 'On a registered computer: restarts the daemon so it reconnects to Northlight.',
121
98
  'Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity.',
122
99
  ],
123
100
  },
124
101
  run: async (input) => {
125
- // A computer with local records needs its daemon (the move reads the canvas through it) and a machine's daemon is the machine role; a fresh computer starts none until it is registered.
126
- if (readMachineConfig() !== undefined || hasLocalCanvas())
102
+ if (readMachineConfig() !== undefined)
127
103
  await spawnDaemon();
128
104
  const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
129
- const unfinished = await settleEarlierMove(showSignIn);
130
- if (unfinished !== undefined) {
131
- if (insideBroker()) {
132
- startDetachedMove(undefined);
133
- return { account: unfinished.account.display, moving: true };
134
- }
135
- await finishMove(unfinished);
136
- return { account: unfinished.account.display, moved: true };
137
- }
138
105
  const machine = readMachineConfig();
139
106
  if (machine !== undefined) {
140
107
  const { account } = await signIn(directoryUrl, showSignIn, { accept: sameAccountOnly(machine) });
@@ -143,19 +110,11 @@ export const sysSigninLeaf = defineLeaf({
143
110
  await spawnDaemon();
144
111
  return { account };
145
112
  }
146
- if (!hasLocalCanvas())
147
- return await registerFreshComputer(directoryUrl);
148
- const { account } = await signIn(directoryUrl, showSignIn);
149
- if (insideBroker()) {
150
- startDetachedMove(envNodeId());
151
- return { account, moving: true };
152
- }
153
- await runMove({ directoryUrl, notify: null });
154
- return { account, moved: true };
113
+ if (hasLocalCanvas())
114
+ throw new CrtrError('local_canvas_unsupported', 'this computer holds a local crtr canvas, and moving one into Northlight is no longer supported.', ExitCode.USAGE, { next: 'Remove the local canvas (the `pg`, `canvas.db` and `canvas.db.imported` entries under the runtime folder) to sign this computer in fresh.' });
115
+ return await registerFreshComputer(directoryUrl);
155
116
  },
156
- render: (r) => r['moving'] === true
157
- ? `<signin account="${r['account']}" moving="true">${MOVING(String(r['account']))}</signin>`
158
- : `<signin account="${r['account']}"${r['moved'] === true ? ' moved="true"' : ''}/>`,
117
+ render: (r) => `<signin account="${r['account']}"/>`,
159
118
  });
160
119
  /** Restart crtrd on a moved computer after sign-out; the machine daemon, finding no sign-in, stops every agent and cron on this computer and only
161
120
  * then answers `/healthz` with `signed_in: false`. Answers whether it did. */
@@ -8,6 +8,7 @@ import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
8
8
  import { gitAsync } from './git.js';
9
9
  import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, isManagedWorktreeBase, managedWorktreesRoot, managedWorktreePath, persistClosedWorktreeState, worktreeLockPathForCommonDir, WorktreeError, branchIsPushedAtCurrentTip } from './worktree.js';
10
10
  import { proveBranchContained } from './worktree-containment.js';
11
+ import { runWorktreeScript } from './worktree-scripts.js';
11
12
  import { refDeleteTransactionStdin } from './worktree-landing.js';
12
13
  import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
13
14
  // A function, not a constant: `runtime/nodes.ts` imports this module and sits in an import cycle with `worktree.ts`, so a module-level read of its exports would run before they exist.
@@ -116,7 +117,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
116
117
  throw new WorktreeError('managed_worktree_base', `cwd ${repoRoot} is a managed worktree and cannot be used as a managed worktree base`, 'Pass `--cwd` pointing at the repository’s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.');
117
118
  }
118
119
  const commonDir = await commonGitDir(repoRoot);
119
- return withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
120
+ const wt = await withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
120
121
  const baseSha = await resolveLandableBase(repoRoot, baseRef);
121
122
  const path = managedWorktreePath(nodeId);
122
123
  const branch = `crtr/${nodeId}`;
@@ -124,7 +125,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
124
125
  throw new WorktreeError('worktree_path_exists', `managed worktree path already exists: ${path}`, 'Remove the stale path or choose a fresh node id.');
125
126
  if ((await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], repoRoot)).status === 0)
126
127
  throw new WorktreeError('worktree_branch_exists', `managed worktree branch already exists: ${branch}`, 'Remove the stale branch or choose a fresh node id.');
127
- const wt = { state: 'open', path, branch, repo_root: repoRoot, base_ref: baseRef, base_sha: baseSha, created: new Date().toISOString() };
128
+ const created = { state: 'open', path, branch, repo_root: repoRoot, base_ref: baseRef, base_sha: baseSha, created: new Date().toISOString() };
128
129
  await runGit(repoRoot, ['branch', branch, baseSha], 'worktree_branch_create_failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.');
129
130
  const added = await gitAsync(['worktree', 'add', path, branch], repoRoot);
130
131
  if (added.status !== 0) {
@@ -132,8 +133,15 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
132
133
  throw new WorktreeError('worktree_add_failed', 'git worktree add failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.', detailOf(added));
133
134
  }
134
135
  seedExclude(repoRoot, commonDir);
135
- return wt;
136
+ return created;
136
137
  }, { timeoutMs: lockWaitMs(), timeoutError: () => new WorktreeError('worktree_lock_timeout', `timed out waiting to create a managed worktree in ${commonDir}`, 'Wait for the other managed-worktree operation to finish, then retry.') });
138
+ // Outside the repository lock: a script may take minutes. A failed setup fails creation and the half-prepared checkout is removed the normal way.
139
+ const setup = await runWorktreeScript('worktree-setup', basename(wt.path), wt);
140
+ if (setup.status === 'failed') {
141
+ await rollbackManagedWorktreeAsync(wt);
142
+ throw new WorktreeError('worktree_setup_failed', '.dev/worktree-setup failed', 'Fix the repository\'s .dev/worktree-setup on its base branch, then retry spawning with --worktree.', setup.detail);
143
+ }
144
+ return wt;
137
145
  }
138
146
  async function cleanTip(wt) {
139
147
  if (wt.state !== 'open' || !existsSync(wt.path))
@@ -0,0 +1,72 @@
1
+ // A repository's optional `.dev/worktree-setup` and `.dev/worktree-teardown` executables.
2
+ //
3
+ // crtr decides WHEN they run (after a managed worktree is created, and as the first step of its sweep); the
4
+ // repository decides WHAT they do. Each script is read from the worktree's base branch in the primary checkout,
5
+ // never from the worktree itself, so a node's own commits cannot change what crtr executes. A missing file is no step.
6
+ // Async only: the sweep runs on the daemon's event loop.
7
+ import { spawn } from 'node:child_process';
8
+ import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { gitAsync } from './git.js';
12
+ /** Fixed, not configurable. */
13
+ export const WORKTREE_SCRIPT_TIMEOUT_MS = 5 * 60_000;
14
+ const STDERR_TAIL_LINES = 20;
15
+ function tail(text) {
16
+ return text.trim().split('\n').slice(-STDERR_TAIL_LINES).join('\n');
17
+ }
18
+ export async function runWorktreeScript(script, nodeId, wt, timeoutMs = WORKTREE_SCRIPT_TIMEOUT_MS) {
19
+ const ref = `refs/heads/${wt.base_ref}`;
20
+ const spec = `${ref}:.dev/${script}`;
21
+ const exists = await gitAsync(['cat-file', '-e', spec], wt.repo_root);
22
+ if (exists.status !== 0)
23
+ return { status: 'absent' };
24
+ const body = await gitAsync(['show', spec], wt.repo_root);
25
+ if (body.status !== 0)
26
+ return { status: 'failed', detail: `could not read .dev/${script} from ${ref}: ${body.stderr.trim()}` };
27
+ const dir = await mkdtemp(join(tmpdir(), 'crtr-worktree-script-'));
28
+ try {
29
+ const file = join(dir, script);
30
+ await writeFile(file, body.stdout);
31
+ await chmod(file, 0o755);
32
+ return await new Promise((resolve) => {
33
+ const child = spawn(file, [], {
34
+ cwd: wt.path,
35
+ stdio: ['ignore', 'ignore', 'pipe'],
36
+ env: {
37
+ ...process.env,
38
+ CRTR_NODE_ID: nodeId,
39
+ CRTR_WORKTREE_PATH: wt.path,
40
+ CRTR_REPO_ROOT: wt.repo_root,
41
+ CRTR_BASE_REF: wt.base_ref,
42
+ COMPOSE_PROJECT_NAME: `crtr-${nodeId}`,
43
+ },
44
+ });
45
+ let stderr = '';
46
+ let timedOut = false;
47
+ let settled = false;
48
+ const finish = (result) => {
49
+ if (settled)
50
+ return;
51
+ settled = true;
52
+ clearTimeout(timer);
53
+ resolve(result);
54
+ };
55
+ const timer = setTimeout(() => {
56
+ timedOut = true;
57
+ child.kill('SIGKILL');
58
+ finish({ status: 'failed', detail: `.dev/${script} timed out after ${Math.round(timeoutMs / 1000)}s\n${tail(stderr)}`.trim() });
59
+ }, timeoutMs);
60
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-16_384); });
61
+ child.on('error', (err) => finish({ status: 'failed', detail: `could not run .dev/${script}: ${err.message}` }));
62
+ child.on('close', (code, signal) => {
63
+ if (timedOut)
64
+ return;
65
+ finish(code === 0 ? { status: 'ok' } : { status: 'failed', detail: `.dev/${script} exited ${code ?? `by ${signal}`}\n${tail(stderr)}`.trim() });
66
+ });
67
+ });
68
+ }
69
+ finally {
70
+ await rm(dir, { recursive: true, force: true });
71
+ }
72
+ }
@@ -13,12 +13,13 @@
13
13
  // call on a large repository is not short.
14
14
  import { createHash } from 'node:crypto';
15
15
  import { existsSync, realpathSync } from 'node:fs';
16
- import { isAbsolute, relative, resolve, sep } from 'node:path';
16
+ import { basename, isAbsolute, relative, resolve, sep } from 'node:path';
17
17
  import { completeCleanup, getNode, recordSweepAttempt, resumableNodeCwds } from './canvas/index.js';
18
18
  import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
19
19
  import { gitAsync } from './git.js';
20
20
  import { proveBranchContained, upstreamTip } from './worktree-containment.js';
21
21
  import { refDeleteTransactionStdin } from './worktree-landing.js';
22
+ import { runWorktreeScript } from './worktree-scripts.js';
22
23
  import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
23
24
  import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, samePath, worktreeLockPathForCommonDir } from './worktree.js';
24
25
  /** Escalating recheck interval, in minutes, indexed by consecutive refusal. The
@@ -256,6 +257,14 @@ export async function sweepManagedWorktreeOnHost(wt, guard, dependentCwds) {
256
257
  // before each removal, where spawn admission into the checkout is excluded.
257
258
  if (existsSync(wt.path) && await checkoutHasDependents(dependentCwds, wt.path))
258
259
  return { outcome: CHECKOUT_IN_USE, observed: none };
260
+ // The repository's teardown comes before every Git disposal step, outside the repository lock (it may take minutes). A failure keeps the checkout so a person can rerun it.
261
+ if (existsSync(wt.path)) {
262
+ const teardown = await runWorktreeScript('worktree-teardown', basename(wt.path), wt);
263
+ if (teardown.status === 'failed')
264
+ return { outcome: { status: 'refused', reason: 'teardown_failed', detail: teardown.detail }, observed: none };
265
+ if (!await guard.stillEligible())
266
+ return { outcome: NODE_REVIVED, observed: none };
267
+ }
259
268
  const cwd = existsSync(wt.path) ? wt.path : wt.repo_root;
260
269
  if (!existsSync(cwd)) {
261
270
  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 };