@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,5 +1,4 @@
1
1
  import { CrtrClient } from '../api/index.js';
2
- import { CrtrError } from '../core/errors.js';
3
2
  import type { CanvasSource } from '../core/canvas/source.js';
4
3
  import type { NodeStatus, SubscriptionRef } from '../core/canvas/types.js';
5
4
  import type { Scope } from '../types.js';
@@ -46,10 +45,6 @@ export declare function remoteTarget(): {
46
45
  * a node on a Mac moved into Northlight (`machine.json`; its machine daemon serves no `/v1`) or a fleet node (`CRTR_API_URL` names the control plane).
47
46
  * `remoteTarget()` reports undefined for it because the transport is a local socket. */
48
47
  export declare function relayReachesControlPlane(): boolean;
49
- /** A move whose cloud run reached `done` but whose computer has not switched over: the account holds the records, the local daemon stays drained,
50
- * and no command may run against either side until `crtr sys signin` finishes it (design D14). The record is deleted only once the machine-role daemon
51
- * is up (`finishMove`, or that daemon's own start), so a `machine.json` written before a failed restart does not lift this. */
52
- export declare function moveUnfinished(): CrtrError | undefined;
53
48
  /** The local-socket `CrtrClient` every CLI verb uses. Autostart is on by
54
49
  * default: on a cold socket the injected `onColdSocket` hook fires
55
50
  * `ensureDaemon()` (spawns crtrd detached via the branded host), then the
@@ -1,4 +1,4 @@
1
- var T=Object.defineProperty;var a=(r,t)=>T(r,"name",{value:t,configurable:!0});import{closeSync as E,existsSync as N,fstatSync as A,openSync as O,readFileSync as m,readSync as x}from"node:fs";import{dirname as I,join as l}from"node:path";import{gunzipSync as M}from"node:zlib";import{CrtrClient as p,ApiError as u}from"../api/index.js";import{localClient as f}from"../api/node-transport.js";import{northlightFetch as P,notSignedIn as F,readPersonCredential as U}from"../core/directory/person-credential.js";import{isMoveCommitted as D,moveUnfinishedError as k,readMachineConfig as w}from"../daemon/machine-link/config.js";import{northlightUnreachable as K}from"../core/directory/reach.js";import{apiErrorToCliError as _}from"../core/io.js";import{autostartDisabled as b,daemonAutostartStartupFailure as L,ensureDaemon as B}from"../daemon/manage.js";import{DAEMON_STARTUP_WINDOW_MS as C}from"../daemon/startup-policy.js";import{readState as W}from"../core/config.js";import{resolveRemoteCanvasTarget as j}from"../core/remote-canvas-target.js";import{RemoteCanvasSource as G}from"../core/canvas/remote-canvas-source.js";import{BROKER_RELEASED_MARKER as z,BROKER_RELAY_GENERATION as V,crtrHome as q}from"../core/canvas/paths.js";import{envTestNodeSocketWindowMs as H,isSandboxedNode as Y,providerProjectionOverBrokerRelay as $}from"../shared/env.js";import{CrtrError as g,ownerOnly as J}from"../core/errors.js";import{ExitCode as v}from"../types.js";function d(r){return{...r,fault:r.fault??null}}a(d,"withRowFault");function X(r,t){throw r instanceof u?_(r,t):r}a(X,"rethrowAsCliError");async function Nt(r){try{return await y().getNode(r)}catch(t){if(t instanceof u&&t.status===404)return null;X(t)}}a(Nt,"getNodeOrNull");const Q="crtr_run_",Z=4096,tt=20;function et(){let r;try{r=O(l(q(),"crtrd.log"),"r");const{size:t}=A(r),e=Math.max(0,t-Z),s=t-e;if(s<=0)return;const n=Buffer.alloc(s);x(r,n,0,s,e);const o=n.toString("utf8").split(`
2
- `).filter(c=>c.trim()!=="").slice(-tt).join(`
1
+ var T=Object.defineProperty;var a=(r,t)=>T(r,"name",{value:t,configurable:!0});import{closeSync as N,existsSync as E,fstatSync as A,openSync as O,readFileSync as p,readSync as I}from"node:fs";import{dirname as x,join as l}from"node:path";import{gunzipSync as M}from"node:zlib";import{CrtrClient as m,ApiError as u}from"../api/index.js";import{localClient as f}from"../api/node-transport.js";import{northlightFetch as P,notSignedIn as F,readPersonCredential as D}from"../core/directory/person-credential.js";import{readMachineConfig as w}from"../daemon/machine-link/config.js";import{northlightUnreachable as k}from"../core/directory/reach.js";import{apiErrorToCliError as _}from"../core/io.js";import{autostartDisabled as b,daemonAutostartStartupFailure as U,ensureDaemon as K}from"../daemon/manage.js";import{DAEMON_STARTUP_WINDOW_MS as g}from"../daemon/startup-policy.js";import{readState as L}from"../core/config.js";import{resolveRemoteCanvasTarget as B}from"../core/remote-canvas-target.js";import{RemoteCanvasSource as W}from"../core/canvas/remote-canvas-source.js";import{BROKER_RELEASED_MARKER as j,BROKER_RELAY_GENERATION as G,crtrHome as z}from"../core/canvas/paths.js";import{envTestNodeSocketWindowMs as V,isSandboxedNode as q,providerProjectionOverBrokerRelay as H}from"../shared/env.js";import{CrtrError as C,ownerOnly as Y}from"../core/errors.js";import{ExitCode as R}from"../types.js";function d(r){return{...r,fault:r.fault??null}}a(d,"withRowFault");function $(r,t){throw r instanceof u?_(r,t):r}a($,"rethrowAsCliError");async function St(r){try{return await y().getNode(r)}catch(t){if(t instanceof u&&t.status===404)return null;$(t)}}a(St,"getNodeOrNull");const J="crtr_run_",X=4096,Q=20;function Z(){let r;try{r=O(l(z(),"crtrd.log"),"r");const{size:t}=A(r),e=Math.max(0,t-X),s=t-e;if(s<=0)return;const n=Buffer.alloc(s);I(r,n,0,s,e);const o=n.toString("utf8").split(`
2
+ `).filter(c=>c.trim()!=="").slice(-Q).join(`
3
3
  `).trim();return o===""?void 0:`crtrd.log (tail):
4
- ${o}`}catch{return}finally{if(r!==void 0)try{E(r)}catch{}}}a(et,"readColdStartDiagnostic");const nt=a(()=>!process.env.CRTR_API_SOCKET&&!!process.env.CRTR_API_URL&&!!process.env.CRTR_API_TOKEN?.startsWith(Q),"usesRunToken");function rt(){if(process.env.CRTR_API_SOCKET)return;const r=process.env.CRTR_API_TOKEN,t=process.env.CRTR_API_URL;if(nt()&&r&&t)return{client:a(i=>new p({baseUrl:t,headers:{authorization:`Bearer ${r}`},...i!==void 0?{timeoutMs:i}:{}}),"client")};const e=w();if(e===void 0)return;if(U()===void 0)throw F("this computer is imported into Northlight, so crtr needs your sign-in");const s=P(e.directoryUrl,e.apiUrl),n=a((i,o)=>s(i,o).catch(c=>{throw c instanceof g?R(c):c}),"authed");return{client:a(i=>it(new p({baseUrl:e.apiUrl,fetch:n,...i!==void 0?{timeoutMs:i}:{}}),e.apiUrl),"client")}}a(rt,"remoteTarget");function st(){return!!process.env.CRTR_API_SOCKET&&(w()!==void 0||$())}a(st,"relayReachesControlPlane");function it(r,t){return new Proxy(r,{get(e,s){const n=Reflect.get(e,s,e);return typeof n!="function"?n:(...i)=>{const o=n.apply(e,i);return o instanceof Promise?o.catch(c=>{throw c instanceof u&&c.code==="request_timeout"?R(K(c,t)):c}):o}}})}a(it,"unreachableOnTimeout");function R(r){const t=typeof r.details?.next=="string"?r.details.next:void 0;return new u(r.exitCode===v.NETWORK?503:401,r.code,r.message,{error:r.code,message:r.message,...t===void 0?{}:{next:t}})}a(R,"asApiError");function ot(){return D()?k():void 0}a(ot,"moveUnfinished");function y(r){if(r?.local!==!0){const s=ot();if(s!==void 0)throw s}if(r?.local===!0&&st())throw new g("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",v.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});const t=r?.local===!0?void 0:rt();if(t!==void 0)return t.client(r?.timeoutMs);const e=process.env.CRTR_API_SOCKET;if(e){const s=a(()=>{if(!N(e))try{const i=I(e),o=m(l(i,z),"utf8"),c=m(l(i,V),"utf8");if(o===c&&o!=="")return new u(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},"availabilityFailure"),n=s();if(n!==void 0)throw _(n,"Run the command from the node's own turn instead.");return f({autostart:!1,availabilityFailure:s,coldStartPollWindowMs:(b()?H():void 0)??C,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}})}return b()?f({autostart:!1,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}}):f({...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},onColdSocket:a(async()=>{B()},"onColdSocket"),coldStartDiagnostic:et,coldStartFailure:L,coldStartPollWindowMs:C})}a(y,"cliClient");const at=2e3;class S{static{a(this,"ApiCanvasSource")}client;rosterCache=null;rosterInFlight=null;constructor(t=y()){this.client=t}async roster(){const t=Date.now();return this.rosterCache!==null&&t-this.rosterCache.at<at?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(e=>{const s={snapshot:e,subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i={node_id:n.to_id,active:n.active,created:n.created},o={node_id:n.from_id,active:n.active,created:n.created},c=s.subscriptions.get(n.from_id);c===void 0?s.subscriptions.set(n.from_id,[i]):c.push(i);const h=s.subscribers.get(n.to_id);h===void 0?s.subscribers.set(n.to_id,[o]):h.push(o)}return this.rosterCache={at:Date.now(),index:s},s}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(t){try{return await t()}catch(e){if(e instanceof u&&e.status===404)return null;throw e}}async getNode(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async getRow(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async listNodes(t){const e=t?.status,s=t?.under===void 0?{}:{under:t.under,under_inclusive:!0};let n;if(Array.isArray(e)){const i=new Set(e);n=(await this.client.listNodes(s)).filter(c=>i.has(c.status))}else n=await this.client.listNodes({...e!==void 0?{status:e}:{},...s});return n.map(i=>d(i))}async browseSnapshot(){const t=await this.client.canvasBrowseCompressed(),e=JSON.parse(M(t).toString("utf8")),s={subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i=s.subscriptions.get(n.from_id)??[];i.push({node_id:n.to_id,active:n.active,created:n.created}),s.subscriptions.set(n.from_id,i);const o=s.subscribers.get(n.to_id)??[];o.push({node_id:n.from_id,active:n.active,created:n.created}),s.subscribers.set(n.to_id,o)}return this.rosterCache={at:Date.now(),index:s},e.nodes.map(n=>d(n))}async panelView(t){return await this.client.canvasView(t)}async panelRoster(){const t=await this.roster();return t.snapshot!==void 0?t.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(t){return this.roster().then(e=>e.subscriptions.get(t)??[])}async subscribersOf(t){return this.roster().then(e=>e.subscribers.get(t)??[])}async view(t){const e=new Set([t]),s=[],n=(await this.subscriptionsOf(t)).map(i=>i.node_id);for(;n.length>0;){const i=n.shift();if(!e.has(i)){e.add(i),s.push(i);for(const o of await this.subscriptionsOf(i))e.has(o.node_id)||n.push(o.node_id)}}return s}async ticketCountsForNodes(t){return(await this.client.attentionCounts([...t])).counts}async ticketCountsForView(t){return this.ticketCountsForNodes([t,...await this.view(t)])}async newestReport(t){return(await this.client.getReports(t,{limit:1}))[0]??null}async hasActiveLiveSubscription(t){const e=(await this.subscriptionsOf(t)).filter(s=>s.active);for(const s of e){const n=await this.getRow(s.node_id);if(n&&(n.status==="active"||n.status==="idle"))return!0}return!1}}function At(r,t=Y()){const e=r?.scope??"user";if(t){if(r?.canvasName!==void 0)throw J("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new S}const s=r?.canvasName??W(e).activeCanvas??null;if(!s)return new S;const{previewEndpoint:n,relayToken:i}=j(s,e);return new G(n,i)}a(At,"cliCanvasSource");export{S as ApiCanvasSource,Z as COLD_START_DIAGNOSTIC_TAIL_BYTES,At as cliCanvasSource,y as cliClient,Nt as getNodeOrNull,ot as moveUnfinished,et as readColdStartDiagnostic,st as relayReachesControlPlane,rt as remoteTarget,X as rethrowAsCliError,nt as usesRunToken};
4
+ ${o}`}catch{return}finally{if(r!==void 0)try{N(r)}catch{}}}a(Z,"readColdStartDiagnostic");const tt=a(()=>!process.env.CRTR_API_SOCKET&&!!process.env.CRTR_API_URL&&!!process.env.CRTR_API_TOKEN?.startsWith(J),"usesRunToken");function et(){if(process.env.CRTR_API_SOCKET)return;const r=process.env.CRTR_API_TOKEN,t=process.env.CRTR_API_URL;if(tt()&&r&&t)return{client:a(i=>new m({baseUrl:t,headers:{authorization:`Bearer ${r}`},...i!==void 0?{timeoutMs:i}:{}}),"client")};const e=w();if(e===void 0)return;if(D()===void 0)throw F("this computer is imported into Northlight, so crtr needs your sign-in");const s=P(e.directoryUrl,e.apiUrl),n=a((i,o)=>s(i,o).catch(c=>{throw c instanceof C?v(c):c}),"authed");return{client:a(i=>rt(new m({baseUrl:e.apiUrl,fetch:n,...i!==void 0?{timeoutMs:i}:{}}),e.apiUrl),"client")}}a(et,"remoteTarget");function nt(){return!!process.env.CRTR_API_SOCKET&&(w()!==void 0||H())}a(nt,"relayReachesControlPlane");function rt(r,t){return new Proxy(r,{get(e,s){const n=Reflect.get(e,s,e);return typeof n!="function"?n:(...i)=>{const o=n.apply(e,i);return o instanceof Promise?o.catch(c=>{throw c instanceof u&&c.code==="request_timeout"?v(k(c,t)):c}):o}}})}a(rt,"unreachableOnTimeout");function v(r){const t=typeof r.details?.next=="string"?r.details.next:void 0;return new u(r.exitCode===R.NETWORK?503:401,r.code,r.message,{error:r.code,message:r.message,...t===void 0?{}:{next:t}})}a(v,"asApiError");function y(r){if(r?.local===!0&&nt())throw new C("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",R.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});const t=r?.local===!0?void 0:et();if(t!==void 0)return t.client(r?.timeoutMs);const e=process.env.CRTR_API_SOCKET;if(e){const s=a(()=>{if(!E(e))try{const i=x(e),o=p(l(i,j),"utf8"),c=p(l(i,G),"utf8");if(o===c&&o!=="")return new u(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},"availabilityFailure"),n=s();if(n!==void 0)throw _(n,"Run the command from the node's own turn instead.");return f({autostart:!1,availabilityFailure:s,coldStartPollWindowMs:(b()?V():void 0)??g,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}})}return b()?f({autostart:!1,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}}):f({...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},onColdSocket:a(async()=>{K()},"onColdSocket"),coldStartDiagnostic:Z,coldStartFailure:U,coldStartPollWindowMs:g})}a(y,"cliClient");const st=2e3;class S{static{a(this,"ApiCanvasSource")}client;rosterCache=null;rosterInFlight=null;constructor(t=y()){this.client=t}async roster(){const t=Date.now();return this.rosterCache!==null&&t-this.rosterCache.at<st?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(e=>{const s={snapshot:e,subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i={node_id:n.to_id,active:n.active,created:n.created},o={node_id:n.from_id,active:n.active,created:n.created},c=s.subscriptions.get(n.from_id);c===void 0?s.subscriptions.set(n.from_id,[i]):c.push(i);const h=s.subscribers.get(n.to_id);h===void 0?s.subscribers.set(n.to_id,[o]):h.push(o)}return this.rosterCache={at:Date.now(),index:s},s}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(t){try{return await t()}catch(e){if(e instanceof u&&e.status===404)return null;throw e}}async getNode(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async getRow(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async listNodes(t){const e=t?.status,s=t?.under===void 0?{}:{under:t.under,under_inclusive:!0};let n;if(Array.isArray(e)){const i=new Set(e);n=(await this.client.listNodes(s)).filter(c=>i.has(c.status))}else n=await this.client.listNodes({...e!==void 0?{status:e}:{},...s});return n.map(i=>d(i))}async browseSnapshot(){const t=await this.client.canvasBrowseCompressed(),e=JSON.parse(M(t).toString("utf8")),s={subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i=s.subscriptions.get(n.from_id)??[];i.push({node_id:n.to_id,active:n.active,created:n.created}),s.subscriptions.set(n.from_id,i);const o=s.subscribers.get(n.to_id)??[];o.push({node_id:n.from_id,active:n.active,created:n.created}),s.subscribers.set(n.to_id,o)}return this.rosterCache={at:Date.now(),index:s},e.nodes.map(n=>d(n))}async panelView(t){return await this.client.canvasView(t)}async panelRoster(){const t=await this.roster();return t.snapshot!==void 0?t.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(t){return this.roster().then(e=>e.subscriptions.get(t)??[])}async subscribersOf(t){return this.roster().then(e=>e.subscribers.get(t)??[])}async view(t){const e=new Set([t]),s=[],n=(await this.subscriptionsOf(t)).map(i=>i.node_id);for(;n.length>0;){const i=n.shift();if(!e.has(i)){e.add(i),s.push(i);for(const o of await this.subscriptionsOf(i))e.has(o.node_id)||n.push(o.node_id)}}return s}async ticketCountsForNodes(t){return(await this.client.attentionCounts([...t])).counts}async ticketCountsForView(t){return this.ticketCountsForNodes([t,...await this.view(t)])}async newestReport(t){return(await this.client.getReports(t,{limit:1}))[0]??null}async hasActiveLiveSubscription(t){const e=(await this.subscriptionsOf(t)).filter(s=>s.active);for(const s of e){const n=await this.getRow(s.node_id);if(n&&(n.status==="active"||n.status==="idle"))return!0}return!1}}function Tt(r,t=q()){const e=r?.scope??"user";if(t){if(r?.canvasName!==void 0)throw Y("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new S}const s=r?.canvasName??L(e).activeCanvas??null;if(!s)return new S;const{previewEndpoint:n,relayToken:i}=B(s,e);return new W(n,i)}a(Tt,"cliCanvasSource");export{S as ApiCanvasSource,X as COLD_START_DIAGNOSTIC_TAIL_BYTES,Tt as cliCanvasSource,y as cliClient,St as getNodeOrNull,Z as readColdStartDiagnostic,nt as relayReachesControlPlane,et as remoteTarget,$ as rethrowAsCliError,tt as usesRunToken};
@@ -1 +1 @@
1
- var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});import{cliClient as s,moveUnfinished as d,relayReachesControlPlane as m,remoteTarget as c}from"./api-client.js";import{CrtrError as u}from"../core/errors.js";import{ExitCode as l}from"../types.js";import{processGeneration as f,readPackageVersion as i}from"./sys/shared.js";async function w(){const e=f();if(e===null)return;const t=d();if(t!==void 0)throw t;if(c()!==void 0||m())return;const n=await s().status();if(n.generation_id===null||n.generation_id===e.id)return;const r=n.generation_id;throw new u("daemon_generation_mismatch",`this crtr is generation ${e.id} (${i()}), but the running crtrd is ${r===void 0?"too old to report its generation":`generation ${r}`} (${n.runtime_version})`,l.NETWORK,{cli_generation:e.id,cli_version:i(),daemon_generation:r??null,daemon_version:n.runtime_version,next:"Run `crtr sys daemon restart` to move the daemon onto this generation."})}o(w,"assertLocalDaemonMatchesCli");export{w as assertLocalDaemonMatchesCli};
1
+ var i=Object.defineProperty;var t=(n,e)=>i(n,"name",{value:e,configurable:!0});import{cliClient as a,relayReachesControlPlane as s,remoteTarget as m}from"./api-client.js";import{CrtrError as d}from"../core/errors.js";import{ExitCode as c}from"../types.js";import{processGeneration as l,readPackageVersion as o}from"./sys/shared.js";async function p(){const n=l();if(n===null||m()!==void 0||s())return;const e=await a().status();if(e.generation_id===null||e.generation_id===n.id)return;const r=e.generation_id;throw new d("daemon_generation_mismatch",`this crtr is generation ${n.id} (${o()}), but the running crtrd is ${r===void 0?"too old to report its generation":`generation ${r}`} (${e.runtime_version})`,c.NETWORK,{cli_generation:n.id,cli_version:o(),daemon_generation:r??null,daemon_version:e.runtime_version,next:"Run `crtr sys daemon restart` to move the daemon onto this generation."})}t(p,"assertLocalDaemonMatchesCli");export{p as assertLocalDaemonMatchesCli};
@@ -1,6 +1,4 @@
1
1
  import { ImportCloud } from '../../../core/import/export/cloud.js';
2
- import { type MoveRecord } from '../../../daemon/machine-link/config.js';
3
- import { type SignInPrompt } from '../../../core/directory/person-credential.js';
4
2
  /** 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). */
5
3
  export declare function defaultDirectoryUrl(): string;
6
4
  /** End the daemon's drain and confirm the daemon answers `drained: false`, retrying a lost answer: the daemon persists its drain before it waits for
@@ -26,37 +24,6 @@ export interface ExportStep {
26
24
  }
27
25
  /** One export: open the run (or use hosting's), upload blobs, drain, dump, upload rows and stores, load, wait for `done`. `step.name` is the step in
28
26
  * progress, so a failure can name it. The drain ends here when the run did not reach `done`, and stays on when it did. */
29
- export declare function exportRun(kind: 'machine' | 'hosted', cloud: ImportCloud, existingRun: string | undefined, step: ExportStep, onStarted?: (runId: string) => void, onFailed?: () => void): Promise<string>;
30
- /** 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
31
- * link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
32
- * crtrd in machine role, and the move record's deletion. Safe to repeat. */
33
- export declare function finishMove(move: MoveRecord): Promise<void>;
27
+ export declare function exportRun(kind: 'hosted', cloud: ImportCloud, existingRun: string | undefined, step: ExportStep, onStarted?: (runId: string) => void, onFailed?: () => void): Promise<string>;
34
28
  /** 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. */
35
29
  export declare function registerThisMac(directoryUrl: string): Promise<void>;
36
- /** 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
37
- * 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
38
- * `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`. */
39
- export declare function runMove(opts: {
40
- directoryUrl: string;
41
- apiUrl?: string;
42
- notify: string | null;
43
- }): Promise<{
44
- runId: string;
45
- account: string;
46
- timings: string;
47
- }>;
48
- /** 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
49
- * refuses; one whose exporter died is settled against the control plane, and only its positive answer moves it: a run that reached `done` becomes
50
- * `committed` (returned, so the caller finishes the switch-over); a run still loading there refuses until it settles; a run that failed or never
51
- * loaded is a failed move, undone here (record deleted and drain ended and confirmed, sign-in revoked, the asking node told). Any other outcome —
52
- * 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
53
- * `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`.
54
- * Answers the committed record, or undefined when no move is left (an `activated` record only awaits its notification, which the machine daemon sends). */
55
- export declare function settleEarlierMove(show?: (prompt: SignInPrompt & {
56
- complete: string;
57
- }) => void): Promise<MoveRecord | undefined>;
58
- /** 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,
59
- * 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.
60
- * Retries every minute while the settle cannot finish (the control plane unreachable, the run still loading); a run that reached `done` stays `committed`
61
- * for `crtr sys signin`. Returns when there is nothing to settle, the exporter is alive, or `stopped()` says the daemon is closing. */
62
- export declare function settleMoveAtDaemonStart(stopped: () => boolean, onRetry: (error: unknown) => void): Promise<void>;
@@ -1,10 +1,6 @@
1
- var W=Object.defineProperty;var d=(e,t)=>W(e,"name",{value:t,configurable:!0});import{mkdtempSync as X,readFileSync as L,readdirSync as R,rmSync as Q}from"node:fs";import{tmpdir as Z}from"node:os";import{join as g}from"node:path";import{CrtrError as s,general as tt}from"../../../core/errors.js";import{ExitCode as h}from"../../../types.js";import{cliClient as T}from"../../api-client.js";import{ImportCloud as A,STORE_FILE as et,STORE_ORDER as rt}from"../../../core/import/export/cloud.js";import{Uploader as nt,localObjects as F,reviewSourceObject as ot}from"../../../core/import/export/files.js";import{BODIES_TABLE as P,bundleKeys as M}from"../../../core/import/bundle/layout.js";import{crtrVersion as it}from"../../../shared/crtr-version.js";import{nodeArchive as at}from"../../../core/import/export/archive.js";import{buildSourceJson as st}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as ct,runDaemonImportDump as dt,runDaemonInstallId as lt,spawnDaemon as ut,stopAllDaemons as ft}from"../../../daemon/manage.js";import{deleteMoveRecord as U,moveUnfinishedError as mt,readMachineConfig as wt,readMoveRecord as D,writeMachineConfig as pt,writeMachineCredential as ht,writeMoveRecord as b}from"../../../daemon/machine-link/config.js";import{notifyMoveFinished as gt}from"../../../daemon/machine-link/move-notify.js";import{registerSignedInMac as yt}from"../../../core/directory/join.js";import{controlPlaneUrl as _t,forgetSignIn as Et,personAccount as B,personBearer as I,readPersonCredential as $t,signIn as St,signOut as vt}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as Ut}from"../../../core/directory/issuer.js";import{isPidAlive as j}from"../../../core/canvas/pid.js";const y=d(e=>new Promise(t=>setTimeout(t,e)),"sleep");function ee(){return wt()?.directoryUrl??$t()?.directoryUrl??Ut}d(ee,"defaultDirectoryUrl");async function J(e){let t="the daemon still reports a drain";for(let r=1;r<=3;r++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}r<3&&await y(1e3)}throw new s("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,h.GENERAL,{next:"Run `crtr sys import resume`."})}d(J,"endDrainConfirmed");async function It(e,t){e||await J(t)}d(It,"settleDrainAtEnd");const xt=3e4;async function Nt(e,t,r){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(c){const l=c instanceof s?c.details?.status:void 0;if(c instanceof s&&(c.code==="not_signed_in"||typeof l=="number"&&l<500&&l!==408&&l!==429))throw new s("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${c.message}`,h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${c instanceof Error?c.message:String(c)}
2
- `),await y(n),n=Math.min(n*2,xt);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw tt(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&r!==void 0)throw r;await y(2e3)}}d(Nt,"awaitRunOutcome");async function Rt(e,t,r,n,i=()=>{},c=()=>{}){let l=Date.now();const o=d((f,m)=>{const p=Date.now(),v=`${f}=${((p-l)/1e3).toFixed(1)}s`;n.timings.push(v),process.stderr.write(`${f} ${((p-l)/1e3).toFixed(1)}s
3
- `),l=p,n.name=m},"next"),u=X(g(Z(),"crtr-import-")),S=T({local:!0});let _=!1,x=!1,E=!1,$;try{n.name="start";const{installId:f}=await lt(),m=r===void 0?await t.start({source_install_id:f,source_kind:e,release:it()}):{run_id:r};i(m.run_id),n.name="blobs";const p=new nt(t,m.run_id,a=>process.stderr.write(`${a}
4
- `));await p.upload(F()),await ct(u);const v=new Set,O=d(async(a,w)=>{await p.uploadBytes(M.rowPart(m.run_id,a,w.replace(/\.jsonl\.zst$/,"")),L(g(u,"rows",a,w))),v.add(`${a}/${w}`)},"uploadPart");for(const a of R(g(u,"rows",P)))await O(P,a);o("blobs","drain"),_=!0,await S.drainDaemon({settle_limit_ms:6e5}),o("drain","dump"),await p.upload(F());const N=await dt(u,e),k=[];for(const a of N.requests){const w=ot(a.id,a.dir,a.file);w!==null&&k.push(w)}await p.upload(k),o("dump","upload");for(const a of R(g(u,"rows")))for(const w of R(g(u,"rows",a)))v.has(`${a}/${w}`)||await O(a,w);const C=[];if(e==="hosted")for(const a of N.runningNodes){const{data:w,prefixes:K}=await at(a);C.push(...K),await p.uploadBytes(M.nodeFiles(m.run_id,a.node),w)}await p.uploadBytes(M.source(m.run_id),Buffer.from(JSON.stringify(st(N.source,C))));const z=JSON.parse(L(g(u,et),"utf8"));for(const a of rt)await t.putStore(m.run_id,a,z[a]);o("upload","load"),E=!0;let G;try{await t.load(m.run_id)}catch(a){G=a}try{await Nt(t,m.run_id,G)}catch(a){throw a instanceof s&&a.code==="move_outcome_unknown"||(E=!1),a}return E=!1,x=!0,o("load","restart"),m.run_id}catch(f){throw $=f,f}finally{if(Q(u,{recursive:!0,force:!0}),!x&&!E&&c(),_&&!E)try{await It(x,S)}catch(f){if($===void 0)throw f;const m=f instanceof s?f.code:"drain_not_ended";throw new s(m,`${$ instanceof Error?$.message:String($)} (and ${f instanceof Error?f.message:String(f)})`,h.GENERAL,{next:"Run `crtr sys import resume`."})}}}d(Rt,"exportRun");async function Tt(e){await gt(e);const t=new A(e.apiUrl,()=>I(e.directoryUrl));let r;try{r=await t.machineCredential(e.runId)}catch(n){if(!(n instanceof s)||n.details?.code!=="credential_exists")throw n;r=await t.machineCredential(e.runId,!0)}ht(r.credential),pt({apiUrl:e.apiUrl,environmentId:r.environment_id,runId:e.runId,directoryUrl:e.directoryUrl,account:e.account}),await At(e.directoryUrl),await ft(),await ut(),U()}d(Tt,"finishMove");async function At(e){try{await yt(e,await I(e))}catch(t){process.stderr.write(`this computer was not registered with the directory: ${t instanceof Error?t.message:String(t)}
1
+ var k=Object.defineProperty;var u=(e,t)=>k(e,"name",{value:t,configurable:!0});import{mkdtempSync as U,readFileSync as C,readdirSync as R,rmSync as F}from"node:fs";import{tmpdir as P}from"node:os";import{join as w}from"node:path";import{CrtrError as p,general as j}from"../../../core/errors.js";import{ExitCode as $}from"../../../types.js";import{cliClient as G}from"../../api-client.js";import{STORE_FILE as J,STORE_ORDER as H}from"../../../core/import/export/cloud.js";import{Uploader as Y,localObjects as v,reviewSourceObject as q}from"../../../core/import/export/files.js";import{BODIES_TABLE as A,bundleKeys as x}from"../../../core/import/bundle/layout.js";import{crtrVersion as z}from"../../../shared/crtr-version.js";import{nodeArchive as K}from"../../../core/import/export/archive.js";import{buildSourceJson as V}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as X,runDaemonImportDump as Q,runDaemonInstallId as W}from"../../../daemon/manage.js";import{readMachineConfig as Z}from"../../../daemon/machine-link/config.js";import{registerSignedInMac as rr}from"../../../core/directory/join.js";import{personBearer as tr,readPersonCredential as er}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as or}from"../../../core/directory/issuer.js";const D=u(e=>new Promise(t=>setTimeout(t,e)),"sleep");function Or(){return Z()?.directoryUrl??er()?.directoryUrl??or}u(Or,"defaultDirectoryUrl");async function nr(e){let t="the daemon still reports a drain";for(let f=1;f<=3;f++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}f<3&&await D(1e3)}throw new p("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,$.GENERAL,{next:"Run `crtr sys import resume`."})}u(nr,"endDrainConfirmed");async function ar(e,t){e||await nr(t)}u(ar,"settleDrainAtEnd");const ir=3e4;async function sr(e,t,f){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(d){const m=d instanceof p?d.details?.status:void 0;if(d instanceof p&&(d.code==="not_signed_in"||typeof m=="number"&&m<500&&m!==408&&m!==429))throw new p("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${d.message}`,$.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${d instanceof Error?d.message:String(d)}
2
+ `),await D(n),n=Math.min(n*2,ir);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw j(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&f!==void 0)throw f;await D(2e3)}}u(sr,"awaitRunOutcome");async function br(e,t,f,n,i=()=>{},d=()=>{}){let m=Date.now();const h=u((o,a)=>{const c=Date.now(),y=`${o}=${((c-m)/1e3).toFixed(1)}s`;n.timings.push(y),process.stderr.write(`${o} ${((c-m)/1e3).toFixed(1)}s
3
+ `),m=c,n.name=a},"next"),l=U(w(P(),"crtr-import-")),O=G({local:!0});let b=!1,E=!1,_=!1,g;try{n.name="start";const{installId:o}=await W(),a=f===void 0?await t.start({source_install_id:o,source_kind:e,release:z()}):{run_id:f};i(a.run_id),n.name="blobs";const c=new Y(t,a.run_id,r=>process.stderr.write(`${r}
4
+ `));await c.upload(v()),await X(l);const y=new Set,T=u(async(r,s)=>{await c.uploadBytes(x.rowPart(a.run_id,r,s.replace(/\.jsonl\.zst$/,"")),C(w(l,"rows",r,s))),y.add(`${r}/${s}`)},"uploadPart");for(const r of R(w(l,"rows",A)))await T(A,r);h("blobs","drain"),b=!0,await O.drainDaemon({settle_limit_ms:6e5}),h("drain","dump"),await c.upload(v());const S=await Q(l,e),I=[];for(const r of S.requests){const s=q(r.id,r.dir,r.file);s!==null&&I.push(s)}await c.upload(I),h("dump","upload");for(const r of R(w(l,"rows")))for(const s of R(w(l,"rows",r)))y.has(`${r}/${s}`)||await T(r,s);const N=[];if(e==="hosted")for(const r of S.runningNodes){const{data:s,prefixes:M}=await K(r);N.push(...M),await c.uploadBytes(x.nodeFiles(a.run_id,r.node),s)}await c.uploadBytes(x.source(a.run_id),Buffer.from(JSON.stringify(V(S.source,N))));const L=JSON.parse(C(w(l,J),"utf8"));for(const r of H)await t.putStore(a.run_id,r,L[r]);h("upload","load"),_=!0;let B;try{await t.load(a.run_id)}catch(r){B=r}try{await sr(t,a.run_id,B)}catch(r){throw r instanceof p&&r.code==="move_outcome_unknown"||(_=!1),r}return _=!1,E=!0,h("load","restart"),a.run_id}catch(o){throw g=o,o}finally{if(F(l,{recursive:!0,force:!0}),!E&&!_&&d(),b&&!_)try{await ar(E,O)}catch(o){if(g===void 0)throw o;const a=o instanceof p?o.code:"drain_not_ended";throw new p(a,`${g instanceof Error?g.message:String(g)} (and ${o instanceof Error?o.message:String(o)})`,$.GENERAL,{next:"Run `crtr sys import resume`."})}}}u(br,"exportRun");async function Tr(e){try{await rr(e,await tr(e))}catch(t){process.stderr.write(`this computer was not registered with the directory: ${t instanceof Error?t.message:String(t)}
5
5
  Run \`crtr sys signin\` again to register it.
6
- `)}}d(At,"registerThisMac");const V=3,Mt=3e4;async function re(e){const t={name:"sign-in",timings:[]};let r,n="",i;try{const o=await B(e.directoryUrl),u=e.apiUrl??await _t(e.directoryUrl),S=new A(u,()=>I(e.directoryUrl));i={apiUrl:u,directoryUrl:e.directoryUrl,account:o,notify:e.notify,notified:!1,pid:process.pid},await Rt("machine",S,void 0,t,_=>{n=_,b({...i,runId:_,state:"running"})},U)}catch(o){throw o instanceof s&&o.code==="move_outcome_unknown"?o:await H(t.name,o,e.notify)}r={...i,runId:n,state:"committed"},b(r);let c;const l=Date.now();for(let o=1;o<=V;o++)try{return await Tt(r),t.timings.push(`restart=${((Date.now()-l)/1e3).toFixed(1)}s`),process.stderr.write(`restart ${((Date.now()-l)/1e3).toFixed(1)}s
7
- `),{runId:r.runId,account:r.account.display,timings:t.timings.join(" ")}}catch(u){c=u,process.stderr.write(`switch-over attempt ${o} failed: ${u instanceof Error?u.message:String(u)}
8
- `),o<V&&await y(Mt),r=D()??r}throw mt(c instanceof Error?c.message:String(c))}d(re,"runMove");async function H(e,t,r){const n=t instanceof Error?t.message:String(t),i=t instanceof s&&t.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",c=`The move to Northlight failed at ${e}: ${n}. ${i}.`,l=await q(c,r),o=t instanceof s&&t.code!=="error"?t.code:t instanceof s&&typeof t.details?.code=="string"?t.details.code:"move_failed";return new s(o,`the move to Northlight failed at ${e}: ${n}. ${i}, and ${Y(l)}`,h.GENERAL)}d(H,"undoMove");const Y=d(e=>e===void 0?"this computer is signed out.":`this computer's sign-in was removed here but could not be revoked at Northlight (${e}); revoke it on your Northlight account page.`,"signedOutText");async function q(e,t){U();let r;try{await vt()}catch(n){Et(),r=n instanceof Error?n.message:String(n),process.stderr.write(`could not revoke the sign-in at Northlight: ${r}
9
- `)}if(t===null)return r;try{await T({local:!0}).sendMessage(t,{from:null,body:`${e} Tell the person the move failed.${r===void 0?"":` ${Y(r)}`}`})}catch(n){process.stderr.write(`could not message ${t}: ${n instanceof Error?n.message:String(n)}
10
- `)}return r}d(q,"dropMove");async function Dt(e){const t=D();if(t===void 0||t.state==="activated")return;const r=d(async()=>{await St(t.directoryUrl,e,{accept:d(async o=>o.account.id===t.account.id?void 0:new s("signin_other_account",`This computer's move belongs to the Northlight account ${t.account.display}. Sign in to that account.`,h.USAGE),"accept")})},"signBackIn");if(t.state==="committed"){if(e!==void 0)try{await B(t.directoryUrl)}catch(o){if(!(o instanceof s&&o.code==="not_signed_in"))throw o;await r()}return t}if(t.pid>0&&j(t.pid))throw new s("move_running",`a move to Northlight is already running (process ${t.pid}).`,h.USAGE,{next:"Wait for it to finish; the node that asked is messaged when it does."});const n=d(()=>new A(t.apiUrl,()=>I(t.directoryUrl)).get(t.runId),"ask");let i;try{i=await n()}catch(o){if(!(o instanceof s&&o.code==="not_signed_in")||e===void 0)throw o;await r(),i=await n()}if(i.state==="done"){const o={...t,state:"committed"};return b(o),o}if(i.state==="loading"||i.state==="committed")throw new s("move_running","Northlight is still loading this computer's records from an earlier move.",h.USAGE,{next:"Retry in a minute."});if(i.state!=="failed"&&i.state!=="rolled_back"&&i.state!=="uploading")throw new s("move_outcome_unknown","Northlight did not report a settled outcome for this move.",h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});const c=i.failure?.step??"an earlier step",l=i.failure==null?"the process that was moving this computer stopped before Northlight had the records":i.failure.message;U();try{await J(T({local:!0}))}catch(o){throw await H(c,new s("drain_not_ended",`${l} (and ${o instanceof Error?o.message:String(o)})`,h.GENERAL),t.notify)}await q(`The move to Northlight failed at ${c}: ${l}. crtr is still local and working as before.`,t.notify)}d(Dt,"settleEarlierMove");const bt=6e4,Ot=5e3;async function ne(e,t){for(await y(Ot);!e();){const r=D();if(r===void 0||r.state!=="running"||r.pid>0&&j(r.pid))return;try{await Dt();return}catch(n){if(t(n),n instanceof s&&n.code==="not_signed_in")return}await y(bt)}}d(ne,"settleMoveAtDaemonStart");export{Nt as awaitRunOutcome,ee as defaultDirectoryUrl,J as endDrainConfirmed,Rt as exportRun,Tt as finishMove,At as registerThisMac,re as runMove,It as settleDrainAtEnd,Dt as settleEarlierMove,ne as settleMoveAtDaemonStart};
6
+ `)}}u(Tr,"registerThisMac");export{sr as awaitRunOutcome,Or as defaultDirectoryUrl,nr as endDrainConfirmed,br as exportRun,Tr as registerThisMac,ar as settleDrainAtEnd};
@@ -1,4 +1 @@
1
- /** 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,
2
- * so it is never in a broker's process tree. */
3
- export declare const WAIT_FOR_PID_ENV = "CRTR_IMPORT_WAIT_PID";
4
1
  export declare const sysImportBranch: import("../../../core/command.js").BranchDef;
@@ -1 +1 @@
1
- var g=Object.defineProperty;var i=(e,t)=>g(e,"name",{value:t,configurable:!0});import{defineBranch as w,defineLeaf as y}from"../../../core/command.js";import{general as v,usage as r}from"../../../core/errors.js";import{ImportCloud as k}from"../../../core/import/export/cloud.js";import{ensureSignedIn as p}from"../../../core/directory/person-credential.js";import{isPidAlive as _}from"../../../core/canvas/pid.js";import{showSignIn as d}from"../signin.js";import{insideBroker as R}from"../join.js";import{defaultDirectoryUrl as f,exportRun as T,settleEarlierMove as b,finishMove as I,runMove as O}from"./move.js";import{resume as N}from"./resume.js";import{retry as q}from"./retry.js";const U="CRTR_IMPORT_WAIT_PID";async function x(e){for(;_(e);)await new Promise(t=>setTimeout(t,200))}i(x,"waitForExit");const M=y({name:"start",description:"export this runtime into the person's Northlight account",whenToUse:"moving this computer or hosted runtime's canvas into Northlight: run it from a plain terminal, not from inside a node",help:{name:"sys import start",summary:"upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them",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 \u2014 machine credential, `runtime/machine.json`, daemon restarted in machine role \u2014 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`.",params:[{kind:"flag",name:"kind",type:"enum",choices:["machine","hosted"],required:!0,constraint:"`machine` for a person's computer, `hosted` for a hosted runtime (also archives running nodes' files)."},{kind:"flag",name:"api-url",type:"string",required:!1,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."},{kind:"flag",name:"run",type:"string",required:!1,constraint:"An import run hosting opened for this runtime (only with `--kind hosted`); its import token is read from `CRTR_IMPORT_TOKEN`."},{kind:"flag",name:"directory-url",type:"string",required:!1,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."},{kind:"flag",name:"notify",type:"string",required:!1,constraint:"With `--kind machine`: a node id told by message when the move fails or finishes."}],output:[{name:"run_id",type:"string",required:!0,constraint:"The import run."},{name:"state",type:"string",required:!0,constraint:"Final state of the run, `done`."},{name:"timings",type:"string",required:!0,constraint:"Per-step seconds."}],outputKind:"object",effects:["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`.","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.","Machine with `--notify`: sends that node one message when the move fails or finishes.","Opens a temporary directory holding the opened file stores (0600), removed before the command ends."]},run:i(async e=>{const t=e.kind,o=e.run===void 0?void 0:String(e.run),n=e.apiUrl===void 0?void 0:String(e.apiUrl),h=e.notify===void 0?null:String(e.notify);if(t==="hosted"){if(n===void 0)throw r("--kind hosted needs --api-url: the control plane hosting opened the run on");if(h!==null)throw r("--notify names the node that asked for a computer's move: use it only with --kind machine")}else if(o!==void 0)throw r("--run takes an existing run, which only a hosted import has: use --kind hosted");const s=Number(process.env[U]??"");if(Number.isInteger(s)&&s>0&&await x(s),R())throw v("import_inside_node: run this from a plain terminal; a node's broker ends with the daemon restart",{code:"import_inside_node"});if(t==="machine"){const a=await b(d);if(a!==void 0)return await I(a),{run_id:a.runId,state:"done",timings:""};const l=e.directoryUrl===void 0?f():String(e.directoryUrl);await p(l,d);const c=await O({directoryUrl:l,...n===void 0?{}:{apiUrl:n},notify:h});return{run_id:c.runId,state:"done",timings:c.timings}}const m=(o===void 0?await p(f(),d):process.env.CRTR_IMPORT_TOKEN??"").trim();if(m==="")throw r("set CRTR_IMPORT_TOKEN to the run's import token");const u={name:"start",timings:[]};return{run_id:await T("hosted",new k(n,m),o,u),state:"done",timings:u.timings.join(" ")}},"run"),render:i(e=>`<import run="${e.run_id}" state="${e.state}" timings="${e.timings}"/>`,"render")}),$=w({name:"import",description:"move this runtime into the person's Northlight account",whenToUse:"importing this computer or hosted runtime into Northlight",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."},children:[M,N,q]});export{U as WAIT_FOR_PID_ENV,$ as sysImportBranch};
1
+ var a=Object.defineProperty;var n=(e,t)=>a(e,"name",{value:t,configurable:!0});import{defineBranch as d,defineLeaf as m}from"../../../core/command.js";import{general as h,usage as s}from"../../../core/errors.js";import{ImportCloud as u}from"../../../core/import/export/cloud.js";import{ensureSignedIn as p}from"../../../core/directory/person-credential.js";import{showSignIn as l}from"../signin.js";import{insideBroker as f}from"../join.js";import{defaultDirectoryUrl as c,exportRun as g}from"./move.js";import{resume as y}from"./resume.js";const w=m({name:"start",description:"export this hosted runtime into the person's Northlight account",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",help:{name:"sys import start",summary:"upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them",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`.",params:[{kind:"flag",name:"kind",type:"enum",choices:["hosted"],required:!0,constraint:"`hosted`, the only kind: a hosted runtime (also archives running nodes' files)."},{kind:"flag",name:"api-url",type:"string",required:!0,constraint:"Control plane base URL (http or https) hosting opened the run on."},{kind:"flag",name:"run",type:"string",required:!1,constraint:"An import run hosting opened for this runtime; its import token is read from `CRTR_IMPORT_TOKEN`."}],output:[{name:"run_id",type:"string",required:!0,constraint:"The import run."},{name:"state",type:"string",required:!0,constraint:"Final state of the run, `done`."},{name:"timings",type:"string",required:!0,constraint:"Per-step seconds."}],outputKind:"object",effects:["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`.","Opens a temporary directory holding the opened file stores (0600), removed before the command ends."]},run:n(async e=>{const t=e.run===void 0?void 0:String(e.run),r=String(e.apiUrl??"");if(r==="")throw s("--kind hosted needs --api-url: the control plane hosting opened the run on");if(f())throw h("import_inside_node: run this from a plain terminal; a node's broker ends with the daemon restart",{code:"import_inside_node"});const o=(t===void 0?await p(c(),l):process.env.CRTR_IMPORT_TOKEN??"").trim();if(o==="")throw s("set CRTR_IMPORT_TOKEN to the run's import token");const i={name:"start",timings:[]};return{run_id:await g("hosted",new u(r,o),t,i),state:"done",timings:i.timings.join(" ")}},"run"),render:n(e=>`<import run="${e.run_id}" state="${e.state}" timings="${e.timings}"/>`,"render")}),x=d({name:"import",description:"move this hosted runtime into the person's Northlight account",whenToUse:"importing a hosted runtime into Northlight",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."},children:[w,y]});export{x as sysImportBranch};
@@ -1,2 +1,2 @@
1
- var O=Object.defineProperty;var i=(e,n)=>O(e,"name",{value:n,configurable:!0});import{spawn as w}from"node:child_process";import{mkdirSync as R,openSync as P}from"node:fs";import{dirname as v,join as U}from"node:path";import{defineLeaf as y}from"../../core/command.js";import{CrtrError as a}from"../../core/errors.js";import{controlPlaneUrl as C,personAccount as k,personBearer as _,readPersonCredential as b,signIn as m,signOut as x}from"../../core/directory/person-credential.js";import{hasLocalCanvas as T,moveRecordPath as I,readMachineConfig as l,readOrCreateInstallId as L,writeMachineConfig as D,writeMachineCredential as M}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as j,sanitizedDaemonEnv as q,spawnDaemon as h,stopAllDaemons as g}from"../../daemon/manage.js";import{hostname as G}from"node:os";import{northlightUnreachable as p}from"../../core/directory/reach.js";import{envNodeId as B}from"../../shared/env.js";import{ExitCode as c}from"../../types.js";import{insideBroker as N}from"./join.js";import{defaultDirectoryUrl as F,finishMove as z,registerThisMac as E,runMove as H,settleEarlierMove as K}from"./import/move.js";import{WAIT_FOR_PID_ENV as J}from"./import/start.js";function V(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{w(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}i(V,"openBrowser");function u(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
- `),V(e.complete)}i(u,"showSignIn");function W(e){return async n=>{if(e.runId===void 0)return e.account===void 0||e.account.id===n.account.id?void 0:new a("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,c.USAGE);let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(r){return p(r,e.apiUrl)}if(!t.ok)return t.status===404?new a("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,c.USAGE):new a("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,c.GENERAL,{next:"Retry `crtr sys signin`."})}}i(W,"sameAccountOnly");function S(e){const n=U(v(I()),"move.log");R(v(n),{recursive:!0});const t=P(n,"a",384),r=q();for(const o of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete r[o];r[J]=String(process.pid);const s=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];w(process.execPath,s,{detached:!0,stdio:["ignore",t,t],env:r}).unref()}i(S,"startDetachedMove");async function Q(e){const n=b()===void 0?(await m(e,u),await k(e)):await k(e),t=await C(e),r=await _(e),s=i(async $=>{try{return await fetch(new URL(`/v1/machines${$?"?rotate=1":""}`,t),{method:"POST",headers:{authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({install_id:L(),name:G().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch(A){throw p(A,t)}},"post");let o=await s(!1);o.status===409&&(await o.clone().text()).includes("credential_exists")&&(o=await s(!0));const f=await o.text();if(!o.ok)throw new a("machine_registration_failed",`Northlight refused to register this computer (HTTP ${o.status}): ${f.slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signin` again."});const d=JSON.parse(f);if(typeof d.credential!="string"||typeof d.environment_id!="string")throw new a("machine_registration_failed","Northlight answered without a credential",c.GENERAL);return M(d.credential),D({apiUrl:t,environmentId:d.environment_id,directoryUrl:e,account:n}),await E(e),await g(),await h(),{account:n.display}}i(Q,"registerFreshComputer");const X=i(e=>`Signed in as ${e}. 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.`,"MOVING"),fe=y({name:"signin",description:"sign this computer's crtr in to the person's Northlight account and register it as one of their machines",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`",help:{name:"sys signin",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",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`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."},{name:"moved",type:"boolean",required:!1,constraint:"Present when this command moved the records, or finished an earlier move's switch-over."},{name:"moving",type:"boolean",required:!1,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."}],outputKind:"object",effects:["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.","Starts the local daemon first when it is not running, and waits until it serves.","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`.","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.","On a moved computer: restarts the daemon so it reconnects to Northlight.","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."]},run:i(async e=>{(l()!==void 0||T())&&await h();const n=e.directoryUrl===void 0?F():String(e.directoryUrl),t=await K(u);if(t!==void 0)return N()?(S(void 0),{account:t.account.display,moving:!0}):(await z(t),{account:t.account.display,moved:!0});const r=l();if(r!==void 0){const{account:o}=await m(n,u,{accept:W(r)});return await E(n),await g(),await h(),{account:o}}if(!T())return await Q(n);const{account:s}=await m(n,u);return N()?(S(B()),{account:s,moving:!0}):(await H({directoryUrl:n,notify:null}),{account:s,moved:!0})},"run"),render:i(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${X(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function Y(){return await g(),await h(),(await j()).signed_in===!1}i(Y,"stopMovedComputer");async function Z(e){if(b()===void 0)return;const n=await _(e.directoryUrl);let t;try{t=await fetch(new URL(`/v1/machines/${e.environmentId}`,e.apiUrl),{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(3e4)})}catch(r){throw p(r,e.apiUrl)}if(!t.ok&&t.status!==404)throw new a("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${t.status}): ${(await t.text()).slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signout` again."})}i(Z,"revokeMachine");const we=y({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:i(async()=>{const e=l();e!==void 0&&await Z(e);const{signedOut:n,revoked:t}=await x(),r=e===void 0?!1:await Y();return{signed_out:n,revoked:t,stopped:r}},"run"),render:i(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{Q as registerFreshComputer,u as showSignIn,fe as sysSigninLeaf,we as sysSignoutLeaf};
1
+ var N=Object.defineProperty;var r=(e,n)=>N(e,"name",{value:n,configurable:!0});import{spawn as A}from"node:child_process";import{defineLeaf as m}from"../../core/command.js";import{CrtrError as o}from"../../core/errors.js";import{controlPlaneUrl as E,personAccount as w,personBearer as f,readPersonCredential as y,signIn as v,signOut as S}from"../../core/directory/person-credential.js";import{hasLocalCanvas as $,readMachineConfig as h,readOrCreateInstallId as U,writeMachineConfig as x,writeMachineCredential as C}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as L,spawnDaemon as d,stopAllDaemons as u}from"../../daemon/manage.js";import{hostname as O}from"node:os";import{northlightUnreachable as l}from"../../core/directory/reach.js";import{ExitCode as a}from"../../types.js";import{defaultDirectoryUrl as R,registerThisMac as _}from"./import/move.js";function P(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{A(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}r(P,"openBrowser");function k(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
+ `),P(e.complete)}r(k,"showSignIn");function j(e){return async n=>{if(e.runId===void 0)return e.account===void 0||e.account.id===n.account.id?void 0:new o("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,a.USAGE);let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(i){return l(i,e.apiUrl)}if(!t.ok)return t.status===404?new o("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,a.USAGE):new o("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,a.GENERAL,{next:"Retry `crtr sys signin`."})}}r(j,"sameAccountOnly");async function D(e){const n=y()===void 0?(await v(e,k),await w(e)):await w(e),t=await E(e),i=await f(e),g=r(async b=>{try{return await fetch(new URL(`/v1/machines${b?"?rotate=1":""}`,t),{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({install_id:U(),name:O().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch(T){throw l(T,t)}},"post");let s=await g(!1);s.status===409&&(await s.clone().text()).includes("credential_exists")&&(s=await g(!0));const p=await s.text();if(!s.ok)throw new o("machine_registration_failed",`Northlight refused to register this computer (HTTP ${s.status}): ${p.slice(0,300)}`,a.GENERAL,{next:"Run `crtr sys signin` again."});const c=JSON.parse(p);if(typeof c.credential!="string"||typeof c.environment_id!="string")throw new o("machine_registration_failed","Northlight answered without a credential",a.GENERAL);return C(c.credential),x({apiUrl:t,environmentId:c.environment_id,directoryUrl:e,account:n}),await _(e),await u(),await d(),{account:n.display}}r(D,"registerFreshComputer");const X=m({name:"signin",description:"sign this computer's crtr in to the person's Northlight account and register it as one of their machines",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`",help:{name:"sys signin",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",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`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."}],outputKind:"object",effects:["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.","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.","On a registered computer: restarts the daemon so it reconnects to Northlight.","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."]},run:r(async e=>{h()!==void 0&&await d();const n=e.directoryUrl===void 0?R():String(e.directoryUrl),t=h();if(t!==void 0){const{account:i}=await v(n,k,{accept:j(t)});return await _(n),await u(),await d(),{account:i}}if($())throw new o("local_canvas_unsupported","this computer holds a local crtr canvas, and moving one into Northlight is no longer supported.",a.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."});return await D(n)},"run"),render:r(e=>`<signin account="${e.account}"/>`,"render")});async function I(){return await u(),await d(),(await L()).signed_in===!1}r(I,"stopMovedComputer");async function G(e){if(y()===void 0)return;const n=await f(e.directoryUrl);let t;try{t=await fetch(new URL(`/v1/machines/${e.environmentId}`,e.apiUrl),{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(3e4)})}catch(i){throw l(i,e.apiUrl)}if(!t.ok&&t.status!==404)throw new o("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${t.status}): ${(await t.text()).slice(0,300)}`,a.GENERAL,{next:"Run `crtr sys signout` again."})}r(G,"revokeMachine");const Y=m({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:r(async()=>{const e=h();e!==void 0&&await G(e);const{signedOut:n,revoked:t}=await S(),i=e===void 0?!1:await I();return{signed_out:n,revoked:t,stopped:i}},"run"),render:r(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{D as registerFreshComputer,k as showSignIn,X as sysSigninLeaf,Y as sysSignoutLeaf};
@@ -1,3 +1,5 @@
1
+ /** A dead or canceled node's checkout (and whatever its repo's teardown stops) is swept this long after the node ended, so a crashed node can still be revived first. */
2
+ export declare const ENDED_NODE_GRACE_MS: number;
1
3
  /** Find only terminal nodes with an unreconciled, explicitly disposable worktree. A node that ever ran in a Blaxel sandbox
2
4
  * is never a candidate: its sandbox is its worktree and the control plane has no checkout to sweep (D102). A node whose profile
3
5
  * points at an imported Mac is a candidate only while that Mac's link is live: its checkout is swept on the Mac.
@@ -1,5 +1,5 @@
1
- var d=Object.defineProperty;var s=(t,o)=>d(t,"name",{value:o,configurable:!0});import{openDb as i}from"./db.js";async function l(t){const o=await(await i()).prepare(`
2
- SELECT w.node_id, w.sweep_observed_json, w.next_attempt_at,
1
+ var d=Object.defineProperty;var s=(t,o)=>d(t,"name",{value:o,configurable:!0});import{openDb as _}from"./db.js";import{UNSEEN_WAKE_MAIL_SQL as i}from"./deliveries.js";const N=60*6e4;async function p(t){const o=await(await _()).prepare(`
2
+ SELECT w.node_id, w.state AS w_state, n.status AS node_status, COALESCE(n.outcome_at, n.last_activity_at, n.created) AS ended_at, w.sweep_observed_json, w.next_attempt_at,
3
3
  w.abandoned_json, w.land_intent_json, w.disposal_json
4
4
  FROM worktrees w
5
5
  JOIN nodes n ON n.node_id = w.node_id
@@ -10,6 +10,8 @@ var d=Object.defineProperty;var s=(t,o)=>d(t,"name",{value:o,configurable:!0});i
10
10
  WHERE p.id = n.profile_id AND NOT EXISTS (SELECT 1 FROM machine_links l WHERE l.environment = env.object AND l.lease_expires_at > ?))
11
11
  AND w.state IN ('open', 'closed')
12
12
  AND (w.state = 'open' OR w.cleanup_state IS NULL OR w.cleanup_state != 'complete')
13
- AND (w.state = 'closed' OR (n.status = 'done' AND n.final_report IS NOT NULL))
13
+ AND (w.state = 'closed' OR (n.status = 'done' AND n.final_report IS NOT NULL)
14
+ OR (n.status IN ('dead', 'canceled') AND n.frozen_at IS NULL AND n.deleting_at IS NULL
15
+ AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = n.node_id AND ${i("d")})))
14
16
  ORDER BY n.created
15
- `).all(new Date(t).toISOString()),a=[];for(const e of o){try{for(const n of[e.sweep_observed_json,e.abandoned_json,e.land_intent_json,e.disposal_json])n!==null&&JSON.parse(n)}catch{continue}if(e.sweep_observed_json!==null&&e.next_attempt_at!==null){const n=Date.parse(e.next_attempt_at);if(!Number.isNaN(n)&&n>t)continue}a.push(e.node_id)}return a}s(l,"managedWorktreeSweepCandidates");export{l as managedWorktreeSweepCandidates};
17
+ `).all(new Date(t).toISOString()),a=[];for(const e of o){try{for(const n of[e.sweep_observed_json,e.abandoned_json,e.land_intent_json,e.disposal_json])n!==null&&JSON.parse(n)}catch{continue}if(e.node_status!=="done"&&e.w_state==="open"){const n=Date.parse(e.ended_at??"");if(!Number.isNaN(n)&&n+N>t)continue}if(e.sweep_observed_json!==null&&e.next_attempt_at!==null){const n=Date.parse(e.next_attempt_at);if(!Number.isNaN(n)&&n>t)continue}a.push(e.node_id)}return a}s(p,"managedWorktreeSweepCandidates");export{N as ENDED_NODE_GRACE_MS,p as managedWorktreeSweepCandidates};
@@ -130,7 +130,7 @@ export interface RootDef {
130
130
  kind: 'root';
131
131
  help: RootHelp;
132
132
  subtrees: BranchDef[];
133
- /** Why a moved computer could not read the account's provider commands (`not_signed_in`, `northlight_unreachable`, `move_unfinished`). The tree
133
+ /** Why a moved computer could not read the account's provider commands (`not_signed_in`, `northlight_unreachable`). The tree
134
134
  * was built without them, so a top-level name it lacks may be one of those commands: the dispatcher raises this instead of `unknown_path`. */
135
135
  providerCatalogFailure?: ApiError | CrtrError;
136
136
  }
@@ -1,13 +1,12 @@
1
- var A=Object.defineProperty;var p=(i,d)=>A(i,"name",{value:d,configurable:!0});import{existsSync as b,statSync as M}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as $}from"../../build-root.js";import{FRONT_DOOR_ENV as W}from"./front-door-env.js";import{frontDoorBootPrompt as B}from"./first-run-offer.js";import{readMachineConfig as P}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as V}from"./node-id-token.js";import{markTourOffered as G,recordSetupCompleted as U,setupCompleted as R,tourOfferPending as Y}from"./setup-marker.js";function T(i){try{return b(i)&&M(i).isDirectory()}catch{return!1}}p(T,"isDir");const j=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function J(){let i=!1;const d=p(()=>{i=!0},"onSigint");process.once("SIGINT",d);try{const{runSetup:r}=await import("../../commands/sys/setup-wizard.js"),e=await r();if(i){const l=new Error("Interrupted");throw l.name="AbortError",l}await U(e)}finally{process.removeListener("SIGINT",d)}}p(J,"runFirstSetup");function X(i){let d=process.cwd(),r,e,l,f=!1,u,g;const o=[];for(let c=0;c<i.length;c++){const n=i[c];if(n==="--name")r=i[++c];else if(n==="--kind")e=i[++c];else if(n==="--profile")l=i[++c];else if(n==="--pick-profile")f=!0;else if(n==="--continue"||n==="-c")u="continue";else if(n==="--resume"||n==="-r"){u="pick";const w=i[c+1];w!==void 0&&V(w)&&!T(h(w))&&(g=w,c++)}else n.startsWith("--")||o.push(n)}o.length>0&&T(h(o[0]))&&(d=h(o.shift()));const m=o.length>0?o.join(" "):void 0;return{cwd:d,prompt:m,name:r,kind:e,profile:l,pickProfile:f,resume:u,resumeId:g}}p(X,"parseRootArgs");import{FRONT_DOOR_ENV as ae}from"./front-door-env.js";async function oe(i){const d=i.slice(2),r=d[0];if(process.env[W]||r==="-h"||r==="--help"||r==="--version"||r==="-v"||r!==void 0&&$.includes(r))return!1;if(r!==void 0){const t=/\s/.test(r),s=!r.startsWith("-")&&T(h(r)),a=j.has(r);if(!t&&!s&&!a)return!1;if(s){const{buildRoot:D}=await import("../../build-root.js");if((await D()).subtrees.some(L=>L.name===r))return!1}}const e=X(d),l=p(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:t}=await import("../profiles/manifest.js");e.profile=t(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await l();const f=process.stdin.isTTY&&process.stdout.isTTY;if(P()===void 0){f||(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));const{hasLocalCanvas:t}=await import("../../daemon/machine-link/config.js");t()&&process.stderr.write(`This computer's crtr keeps its records locally. Local installs are ending; sign in to Northlight to move them into your account.
2
- `);const{sysSigninLeaf:s}=await import("../../commands/sys/signin.js");try{await s.run({},{}),await(await import("../../commands/person-settings.js")).loadPersonSettingsViaApi()}catch(a){process.stderr.write(`${a instanceof Error?a.message:String(a)}
3
- `),process.exit(1)}}let u=!1;const g=f&&!R()&&(await(await import("../../commands/api-client.js")).cliClient().getModelAuthReadiness({cwd:e.cwd})).hosted_endpoint;f&&!R()&&!g&&(await J(),u=!0);let o=null,m,c=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:t,noResumeTargetMessage:s}=await import("./resume-root.js"),a=await t(e.resumeId);"error"in a&&(process.stderr.write(`${a.error}
4
- `),process.exit(1)),"none"in a?(e.resumeId.includes("-")&&(process.stderr.write(`${s(e.resumeId)}
5
- `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=a.node.profile_id,m=a.node.node_id,T(a.node.cwd)&&(c=a.node.cwd))}if(m===void 0){const{selectProfileForCwd:t,selectProfileForCwdReadOnly:s}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
1
+ var L=Object.defineProperty;var p=(i,a)=>L(i,"name",{value:a,configurable:!0});import{existsSync as b,statSync as M}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as $}from"../../build-root.js";import{FRONT_DOOR_ENV as W}from"./front-door-env.js";import{frontDoorBootPrompt as B}from"./first-run-offer.js";import{readMachineConfig as R}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as V}from"./node-id-token.js";import{markTourOffered as G,recordSetupCompleted as U,setupCompleted as y,tourOfferPending as Y}from"./setup-marker.js";function I(i){try{return b(i)&&M(i).isDirectory()}catch{return!1}}p(I,"isDir");const j=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function J(){let i=!1;const a=p(()=>{i=!0},"onSigint");process.once("SIGINT",a);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const l=new Error("Interrupted");throw l.name="AbortError",l}await U(e)}finally{process.removeListener("SIGINT",a)}}p(J,"runFirstSetup");function X(i){let a=process.cwd(),t,e,l,f=!1,u,g;const o=[];for(let d=0;d<i.length;d++){const s=i[d];if(s==="--name")t=i[++d];else if(s==="--kind")e=i[++d];else if(s==="--profile")l=i[++d];else if(s==="--pick-profile")f=!0;else if(s==="--continue"||s==="-c")u="continue";else if(s==="--resume"||s==="-r"){u="pick";const w=i[d+1];w!==void 0&&V(w)&&!I(h(w))&&(g=w,d++)}else s.startsWith("--")||o.push(s)}o.length>0&&I(h(o[0]))&&(a=h(o.shift()));const m=o.length>0?o.join(" "):void 0;return{cwd:a,prompt:m,name:t,kind:e,profile:l,pickProfile:f,resume:u,resumeId:g}}p(X,"parseRootArgs");import{FRONT_DOOR_ENV as ae}from"./front-door-env.js";async function oe(i){const a=i.slice(2),t=a[0];if(process.env[W]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&$.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),n=!t.startsWith("-")&&I(h(t)),c=j.has(t);if(!r&&!n&&!c)return!1;if(n){const{buildRoot:D}=await import("../../build-root.js");if((await D()).subtrees.some(A=>A.name===t))return!1}}const e=X(a),l=p(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:r}=await import("../profiles/manifest.js");e.profile=r(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await l();const f=process.stdin.isTTY&&process.stdout.isTTY;if(R()===void 0){f||(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));const{sysSigninLeaf:r}=await import("../../commands/sys/signin.js");try{await r.run({},{}),await(await import("../../commands/person-settings.js")).loadPersonSettingsViaApi()}catch(n){process.stderr.write(`${n instanceof Error?n.message:String(n)}
2
+ `),process.exit(1)}}let u=!1;const g=f&&!y()&&(await(await import("../../commands/api-client.js")).cliClient().getModelAuthReadiness({cwd:e.cwd})).hosted_endpoint;f&&!y()&&!g&&(await J(),u=!0);let o=null,m,d=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:n}=await import("./resume-root.js"),c=await r(e.resumeId);"error"in c&&(process.stderr.write(`${c.error}
3
+ `),process.exit(1)),"none"in c?(e.resumeId.includes("-")&&(process.stderr.write(`${n(e.resumeId)}
4
+ `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=c.node.profile_id,m=c.node.node_id,I(c.node.cwd)&&(d=c.node.cwd))}if(m===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:n}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
6
5
  Choose a profile
7
- `),o=e.profile??(f?await t(e.cwd,void 0,e.pickProfile,!1):s(e.cwd))}const{cliClient:n}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:w,hasConfiguredProviderCredential:k},v]=await Promise.all([import("./provider-credential-gate.js"),o===null?[]:n().listProfileEnv(o).then(t=>t.names)]),S=p(async()=>{const t=await n().getModelAuthReadiness({cwd:e.cwd,...o===null?{}:{profile:o}});return t.credential==="ready"||t.hosted_endpoint},"startable");if(!await k(v)&&!await S()){f||w();const{runFrontDoorLogin:t}=await import("./front-door-login.js");await t()||w()}const{inTmux:y}=await import("./placement-tmux.js");if(f&&!y()){const{TMUX_STARTED_ENV:t,handoffToTmux:s}=await import("./tmux-handoff.js");process.env[t]===void 0&&s(d,m!==void 0?null:o,c)}const[{bootRoot:N},{resumeRoot:C},{rendererWarning:O,missingPackageWarning:_,piAgentDir:x}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const t=_(x());t!==null&&process.stderr.write(`
8
- ${t}
6
+ `),o=e.profile??(f?await r(e.cwd,void 0,e.pickProfile,!1):n(e.cwd))}const{cliClient:s}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:w,hasConfiguredProviderCredential:k},S]=await Promise.all([import("./provider-credential-gate.js"),o===null?[]:s().listProfileEnv(o).then(r=>r.names)]),v=p(async()=>{const r=await s().getModelAuthReadiness({cwd:e.cwd,...o===null?{}:{profile:o}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await k(S)&&!await v()){f||w();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||w()}const{inTmux:P}=await import("./placement-tmux.js");if(f&&!P()){const{TMUX_STARTED_ENV:r,handoffToTmux:n}=await import("./tmux-handoff.js");process.env[r]===void 0&&n(a,m!==void 0?null:o,d)}const[{bootRoot:N},{resumeRoot:O},{rendererWarning:_,missingPackageWarning:x,piAgentDir:C}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=x(C());r!==null&&process.stderr.write(`
7
+ ${r}
9
8
 
10
- `);const s=O();s!==null&&process.stderr.write(`
11
- ${s}
9
+ `);const n=_();n!==null&&process.stderr.write(`
10
+ ${n}
12
11
 
13
- `)}catch{}if(m!==void 0){const{resumeNodeById:t}=await import("./resume-root.js");await t(m)}if(e.resume!==void 0&&await C(e.cwd,e.resume==="pick")==="aborted")return!0;const I=f&&(u||await Y()),{prompt:E,initialWhip:F}=B({offerTour:I,signedIn:I&&P()!==void 0,userPrompt:e.prompt});return I&&y()&&await G(),await N({...e,prompt:E,initialWhip:F,selectedProfileId:o??void 0}),!0}p(oe,"maybeBootRoot");export{ae as FRONT_DOOR_ENV,oe as maybeBootRoot,X as parseRootArgs};
12
+ `)}catch{}if(m!==void 0){const{resumeNodeById:r}=await import("./resume-root.js");await r(m)}if(e.resume!==void 0&&await O(e.cwd,e.resume==="pick")==="aborted")return!0;const T=f&&(u||await Y()),{prompt:E,initialWhip:F}=B({offerTour:T,signedIn:T&&R()!==void 0,userPrompt:e.prompt});return T&&P()&&await G(),await N({...e,prompt:E,initialWhip:F,selectedProfileId:o??void 0}),!0}p(oe,"maybeBootRoot");export{ae as FRONT_DOOR_ENV,oe as maybeBootRoot,X as parseRootArgs};
@@ -56,7 +56,7 @@ export declare const CONFIG_SETTINGS_COVERAGE: {
56
56
  applies: string;
57
57
  group: "updates";
58
58
  order: number;
59
- format: (config: ScopeConfig) => "notify" | "off" | "apply";
59
+ format: (config: ScopeConfig) => "off" | "notify" | "apply";
60
60
  cycle: (config: ScopeConfig, delta: number) => void;
61
61
  setFromString: (config: ScopeConfig, raw: string) => "auto_update.crtr must be notify, apply, or false" | null;
62
62
  };
@@ -68,7 +68,7 @@ export declare const CONFIG_SETTINGS_COVERAGE: {
68
68
  applies: string;
69
69
  group: "updates";
70
70
  order: number;
71
- format: (config: ScopeConfig) => "notify" | "off" | "apply";
71
+ format: (config: ScopeConfig) => "off" | "notify" | "apply";
72
72
  cycle: (config: ScopeConfig, delta: number) => void;
73
73
  setFromString: (config: ScopeConfig, raw: string) => "auto_update.content must be notify, apply, or false" | null;
74
74
  };
@@ -1,10 +1,10 @@
1
- var N=Object.defineProperty;var o=(t,e)=>N(t,"name",{value:e,configurable:!0});import{existsSync as d,mkdirSync as j,readFileSync as G,realpathSync as K,rmSync as z,writeFileSync as J}from"node:fs";import{basename as Q,dirname as U,isAbsolute as V,join as D,relative as X,resolve as Y,sep as S}from"node:path";import{abandonWorktreeAndRepoint as Z,getNode as b,readWorktree as ee}from"./canvas/index.js";import{isPidAlive as te}from"./canvas/pid.js";import{InputError as ae}from"./io.js";import{CONFIG_FILE as re,CRTR_DIR_NAME as M,STATE_FILE as ne}from"../types.js";import{withExclusiveDirectoryLockAsync as C}from"./exclusive-lock.js";import{gitAsync as s}from"./git.js";import{WORKTREE_LOCK_WAIT_MS as oe,canonicalPath as L,checkoutPathForBranchInList as ie,isManagedWorktreeBase as se,managedWorktreesRoot as ce,managedWorktreePath as he,persistClosedWorktreeState as y,worktreeLockPathForCommonDir as P,WorktreeError as c,branchIsPushedAtCurrentTip as le}from"./worktree.js";import{proveBranchContained as de}from"./worktree-containment.js";import{refDeleteTransactionStdin as ue}from"./worktree-landing.js";import{deleteTrashAsync as H,removeWorktreeCheckoutAsync as pe}from"./worktree-remove.js";const O=o(()=>Math.min(oe,25e3),"lockWaitMs");function g(t){return(t.stderr.trim()||t.stdout.trim()).trim()}o(g,"detailOf");async function h(t,e,a,r){const n=await s(e,t);if(n.status!==0)throw new c(a,`git ${e.join(" ")} failed`,r,g(n));return n.stdout.trim()}o(h,"runGit");async function R(t){return K(Y(t,await h(t,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.")))}o(R,"commonGitDir");async function m(t,e){const a=await R(t);return C(P(a),e,{timeoutMs:O(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting for the managed-worktree lock in ${a}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(m,"withRepositoryLock");function fe(t,e){const a=L(ce()),r=X(a,L(t));if(r===""||r===".."||r.startsWith(`..${S}`)||V(r))return null;const n=r.split(S)[0];return n===e?null:D(a,n)}o(fe,"foreignManagedCheckout");async function Oe(t,e,a){const r=fe(t,e);if(r===null)return a();const n=await ee(Q(r));return n===null?a():m(n.repo_root,async()=>{if(!d(t))throw new ae({error:"cwd_missing",message:`cwd is not an existing directory: ${t}`,received:t,field:"cwd",next:"Pass an existing directory; the managed checkout it was in has been cleaned up."});return a()})}o(Oe,"admitIntoManagedCheckout");async function v(t,e){const a=`refs/heads/${e}`,r=await s(["show-ref","--verify","--quiet",a],t);if(r.status===1&&r.executionFailed!==!0)throw new c("missing_base_branch",`managed worktree base '${e}' does not name an existing local branch`,"The base must be a local branch that landing can fast-forward \u2014 freshen your local branch from origin first (rebase-not-merge), then base on it.");if(r.status!==0)throw new c("base_branch_inspection_failed",`could not inspect local base branch '${e}' (git show-ref exited with status ${r.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${r.status}
2
- stderr: ${r.stderr.trim()||"<empty>"}`);return h(t,["rev-parse","--verify",a],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o(v,"resolveLandableBase");function me(t,e){try{const a=D(e,"info","exclude");j(U(a),{recursive:!0});let r="";try{r=G(a,"utf8")}catch{}const n=[`/${M}/${re}`,`/${M}/${ne}`];if(n.every(i=>r.split(`
3
- `).map(u=>u.trim()).includes(i)))return;J(a,`${r}${r!==""&&!r.endsWith(`
1
+ var j=Object.defineProperty;var o=(t,e)=>j(t,"name",{value:e,configurable:!0});import{existsSync as l,mkdirSync as G,readFileSync as K,realpathSync as z,rmSync as J,writeFileSync as Q}from"node:fs";import{basename as D,dirname as U,isAbsolute as V,join as M,relative as X,resolve as Y,sep as C}from"node:path";import{abandonWorktreeAndRepoint as Z,getNode as _,readWorktree as ee}from"./canvas/index.js";import{isPidAlive as te}from"./canvas/pid.js";import{InputError as ae}from"./io.js";import{CONFIG_FILE as re,CRTR_DIR_NAME as L,STATE_FILE as ne}from"../types.js";import{withExclusiveDirectoryLockAsync as P}from"./exclusive-lock.js";import{gitAsync as s}from"./git.js";import{WORKTREE_LOCK_WAIT_MS as oe,canonicalPath as H,checkoutPathForBranchInList as ie,isManagedWorktreeBase as se,managedWorktreesRoot as ce,managedWorktreePath as he,persistClosedWorktreeState as v,worktreeLockPathForCommonDir as F,WorktreeError as c,branchIsPushedAtCurrentTip as le}from"./worktree.js";import{proveBranchContained as de}from"./worktree-containment.js";import{runWorktreeScript as pe}from"./worktree-scripts.js";import{refDeleteTransactionStdin as ue}from"./worktree-landing.js";import{deleteTrashAsync as O,removeWorktreeCheckoutAsync as fe}from"./worktree-remove.js";const R=o(()=>Math.min(oe,25e3),"lockWaitMs");function $(t){return(t.stderr.trim()||t.stdout.trim()).trim()}o($,"detailOf");async function h(t,e,a,r){const n=await s(e,t);if(n.status!==0)throw new c(a,`git ${e.join(" ")} failed`,r,$(n));return n.stdout.trim()}o(h,"runGit");async function T(t){return z(Y(t,await h(t,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.")))}o(T,"commonGitDir");async function m(t,e){const a=await T(t);return P(F(a),e,{timeoutMs:R(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting for the managed-worktree lock in ${a}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(m,"withRepositoryLock");function we(t,e){const a=H(ce()),r=X(a,H(t));if(r===""||r===".."||r.startsWith(`..${C}`)||V(r))return null;const n=r.split(C)[0];return n===e?null:M(a,n)}o(we,"foreignManagedCheckout");async function Te(t,e,a){const r=we(t,e);if(r===null)return a();const n=await ee(D(r));return n===null?a():m(n.repo_root,async()=>{if(!l(t))throw new ae({error:"cwd_missing",message:`cwd is not an existing directory: ${t}`,received:t,field:"cwd",next:"Pass an existing directory; the managed checkout it was in has been cleaned up."});return a()})}o(Te,"admitIntoManagedCheckout");async function A(t,e){const a=`refs/heads/${e}`,r=await s(["show-ref","--verify","--quiet",a],t);if(r.status===1&&r.executionFailed!==!0)throw new c("missing_base_branch",`managed worktree base '${e}' does not name an existing local branch`,"The base must be a local branch that landing can fast-forward \u2014 freshen your local branch from origin first (rebase-not-merge), then base on it.");if(r.status!==0)throw new c("base_branch_inspection_failed",`could not inspect local base branch '${e}' (git show-ref exited with status ${r.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${r.status}
2
+ stderr: ${r.stderr.trim()||"<empty>"}`);return h(t,["rev-parse","--verify",a],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o(A,"resolveLandableBase");function me(t,e){try{const a=M(e,"info","exclude");G(U(a),{recursive:!0});let r="";try{r=K(a,"utf8")}catch{}const n=[`/${L}/${re}`,`/${L}/${ne}`];if(n.every(i=>r.split(`
3
+ `).map(u=>u.trim()).includes(i)))return;Q(a,`${r}${r!==""&&!r.endsWith(`
4
4
  `)?`
5
5
  `:""}# crtr: exclude crtr's own untracked project-scope bookkeeping (auto-added at managed-worktree creation)
6
6
  ${n.filter(i=>!r.split(`
7
7
  `).map(u=>u.trim()).includes(i)).join(`
8
8
  `)}
9
- `)}catch{}}o(me,"seedExclude");async function Re(t){await m(t.repo_root,async()=>{const e=await s(["rev-parse","--verify",`refs/heads/${t.branch}`],t.repo_root);if(e.status!==0||e.stdout.trim()!==t.base_sha)return;const a=await s(["worktree","list","--porcelain"],t.repo_root);if(a.status===0){if(a.stdout.split(`
10
- `).some(r=>r.trim()===`branch refs/heads/${t.branch}`)){if((await s(["worktree","remove","--force",t.path],t.repo_root)).status!==0)return}else if(d(t.path))try{z(t.path,{recursive:!0,force:!0})}catch{return}await s(["update-ref","-d",`refs/heads/${t.branch}`,t.base_sha],t.repo_root)}})}o(Re,"rollbackManagedWorktreeAsync");async function Te(t,e,a="main"){const r=await h(t,["rev-parse","--show-toplevel"],"not_git_repo","Pass --cwd <real repo> pointing inside a git repository.");if(se(r))throw new c("managed_worktree_base",`cwd ${r} is a managed worktree and cannot be used as a managed worktree base`,"Pass `--cwd` pointing at the repository\u2019s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.");const n=await R(r);return C(P(n),async()=>{const i=await v(r,a),u=he(e),l=`crtr/${e}`;if(d(u))throw new c("worktree_path_exists",`managed worktree path already exists: ${u}`,"Remove the stale path or choose a fresh node id.");if((await s(["show-ref","--verify","--quiet",`refs/heads/${l}`],r)).status===0)throw new c("worktree_branch_exists",`managed worktree branch already exists: ${l}`,"Remove the stale branch or choose a fresh node id.");const _={state:"open",path:u,branch:l,repo_root:r,base_ref:a,base_sha:i,created:new Date().toISOString()};await h(r,["branch",l,i],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");const f=await s(["worktree","add",u,l],r);if(f.status!==0)throw await s(["update-ref","-d",`refs/heads/${l}`,i],r),new c("worktree_add_failed","git worktree add failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.",g(f));return me(r,n),_},{timeoutMs:O(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${n}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(Te,"createManagedWorktreeAsync");async function $(t){if(t.state!=="open"||!d(t.path))return null;const e=await s(["rev-parse","--abbrev-ref","HEAD"],t.path),a=await s(["status","--porcelain"],t.path),r=await s(["rev-parse","HEAD"],t.path);if(e.status!==0||e.stdout.trim()!==t.branch||a.status!==0||a.stdout.trim()!==""||r.status!==0)return null;const n=await s(["rev-parse","--git-path","rebase-merge"],t.path);return n.status!==0||d(n.stdout.trim())?null:r.stdout.trim()}o($,"cleanTip");async function A(t,e){try{const a=await v(t.path,t.base_ref);return(await s(["merge-base","--is-ancestor",e,a],t.path)).status===0}catch(a){if(a instanceof c&&a.code==="missing_base_branch")return e===t.base_sha;throw a}}o(A,"containedInLocalBase");function we(t){return{node_id:"",branch:t.branch,worktree_path:t.path,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${t.path} remains intact.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${t.branch} remains checked out at ${t.path}.`}}o(we,"deferred");async function x(t){if(t.state!=="open"||d(t.path))return null;const e=`refs/heads/${t.branch}`,a=await s(["show-ref","--verify","--quiet",e],t.repo_root);if(a.status===1&&a.executionFailed!==!0)return{branchSha:null};if(a.status!==0)return null;const r=await s(["rev-parse","--verify",e],t.repo_root);if(r.status!==0)return null;const n=r.stdout.trim(),i=await s(["worktree","list","--porcelain"],t.repo_root);if(i.status!==0||ie(i.stdout,t.branch)!==null)return null;const u=await de(t.repo_root,t,n);return u===null?null:{branchSha:n,containment:u}}o(x,"proveAbsentPathManagedWorktree");function be(t,e,a){return d(e.path)?null:a.branchSha===null?{node_id:t,branch:e.branch,worktree_path:e.path,worktree_removed:!0,branch_deleted:!0}:a.containment===void 0?null:{node_id:t,branch:e.branch,worktree_path:e.path,worktree_removed:!0,branch_deleted:!1,branch_delete_error:`local branch ${e.branch} is delivered but retained because its checkout status can change outside crtr's repository lock.`}}o(be,"absentPathDrop");async function T(t,e){const a=await x(e);if(a===null)return null;const r=be(t,e,a);return r===null?null:{dropped:r,landedSha:a.branchSha??e.base_sha}}o(T,"concludeAbsentLocked");async function _e(t){const e=(await b(t))?.managed_worktree;return e==null||e.state!=="open"||d(e.path)||await x(e)===null?null:m(e.repo_root,async()=>{const a=(await b(t))?.managed_worktree;if(a==null||a.state!=="open")return null;const r=await T(t,a);return r!==null&&await y(t,a,"complete"),r})}o(_e,"concludeAbsentManagedWorktreeAsync");async function ke(t,e){return e.state!=="open"||d(e.path)||await x(e)===null?null:m(e.repo_root,()=>T(t,e))}o(ke,"concludeAbsentManagedWorktreeOnHost");async function F(t,e,a){const r=await $(e);return r===null||r!==a||!await A(e,r)?null:{...we(e),node_id:t}}o(F,"autoDropCleanLocked");async function Fe(t){const e=(await b(t))?.managed_worktree;if(e==null||e.state!=="open")return null;if(!d(e.path))return(await _e(t))?.dropped??null;const a=await $(e);return a===null||!await A(e,a)?null:m(e.path,async()=>{const r=(await b(t))?.managed_worktree;if(r==null||r.state!=="open")return null;const n=await F(t,r,a);return n!==null&&await y(t,r,"pending"),n})}o(Fe,"autoDropCleanManagedWorktreeAsync");async function Ie(t,e){if(!d(e.path)){const r=await ke(t,e);return r===null?{kind:"open",missing:!0}:{kind:"dropped",dropped:r.dropped,cleanup:"complete"}}const a=await $(e);if(a!==null&&await A(e,a)){const r=await m(e.path,()=>F(t,e,a));if(r!==null)return{kind:"dropped",dropped:r,cleanup:"pending"}}return await le(e)?{kind:"pushed"}:{kind:"open",missing:!d(e.path)}}o(Ie,"finalizeManagedWorktreeOnHost");async function I(t){for(const e of["rebase-merge","rebase-apply"]){const a=await s(["rev-parse","--git-path",e],t);if(a.status!==0||d(a.stdout.trim()))return!0}return!1}o(I,"rebaseInProgress");async function ye(t,e,a){return a.persist.kind==="closed"?await y(t,e,"complete"):await Z(t,{cwd:e.repo_root,abandoned:a.persist.abandoned}),a.result}o(ye,"persistAbandonOutcome");function ge(t){return new c("node_running",`node ${t} is still running`,"Abandon requires a stopped node with no live broker process. From the running owner, use `crtr node worktree close` to land locally, or make the checkout clean, push its current tip to origin, and rerun `crtr push final`.")}o(ge,"nodeRunningError");async function Be(t,e){const a=(await b(t))?.managed_worktree;if(a==null||a.state!=="open")throw new c("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to abandon for this node.");const r=[];try{return await m(a.path,async()=>{const n=await b(t),i=n?.managed_worktree;if(n===null||i===void 0||i===null||i.state!=="open")throw new c("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to abandon for this node.");if(n.status==="active"||n.status==="idle"||te(n.pi_pid))throw ge(t);return ye(t,i,await B(t,i,e,r))})}finally{await H(a.path,r[0])}}o(Be,"abandonManagedWorktreeAsync");async function qe(t,e,a){const r=[];try{return await m(e.path,()=>B(t,e,a,r))}finally{await H(e.path,r[0])}}o(qe,"abandonManagedWorktreeOnHost");async function k(t,e){const{result:a,trash:r}=await pe(t.repo_root,t.path);if(r!==void 0&&e.push(r),a.status!==0)throw new c("worktree_remove_failed",`git worktree remove ${t.path} failed`,"Inspect the worktree manually, then retry.",g(a))}o(k,"removeCheckout");async function B(t,e,a,r){if(!d(e.path))throw new c("worktree_missing",`managed worktree path is missing: ${e.path}`,"Inspect the branch and worktree registration, then retry.");const n=o((p,w,E=e.branch)=>({kind:"abandoned",abandoned:{branch:E,tip_sha:p,at:w,by:a}}),"abandoned"),i=await h(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),u=await s(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path);if(i!==e.branch){if(u.status===0||i==="HEAD")throw new c("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${i==="HEAD"?"detached HEAD":i})`,`Inspect ${e.path}, then rerun \`crtr node worktree abandon\`.`);if(await I(e.path)||await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new c("dirty_worktree","managed worktree has uncommitted changes",`Commit or stash them in ${e.path}, then rerun \`crtr node worktree abandon\`.`);const p=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the worktree manually, then retry.");return await k(e,r),{result:{node_id:t,branch:i,tip_sha:p,worktree_path:e.path,branch_deleted:!1},persist:n(p,new Date().toISOString(),i)}}const l=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");let _=null;try{const p=await v(e.path,e.base_ref);(await s(["merge-base","--is-ancestor",l,p],e.path)).status===0&&(_=p)}catch(p){if(!(p instanceof c)||p.code!=="missing_base_branch")throw p}const f=new Date().toISOString(),q=await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.");if(_!==null&&l===e.base_sha){const p=await h(e.repo_root,["rev-parse",`${l}^{tree}`],"abandon_tree_failed","Inspect the branch manually, then retry."),w=await h(e.repo_root,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit-tree",p,"-p",l,"-m","crtr-abandon","-m",`Crtr-Abandon: ${t} ${f}`],"abandon_commit_failed","Inspect the branch manually, then retry.");return await h(e.repo_root,["update-ref",`refs/heads/${e.branch}`,w,l],"abandon_marker_failed","The branch changed while abandon was starting; inspect the worktree, then retry."),await k(e,r),(await s(["update-ref","--stdin"],e.repo_root,ue(e.branch,w,`refs/heads/${e.base_ref}`,_))).status===0?{result:{node_id:t,branch:e.branch,tip_sha:w,worktree_path:e.path,branch_deleted:!0},persist:{kind:"closed"}}:{result:{node_id:t,branch:e.branch,tip_sha:w,worktree_path:e.path,branch_deleted:!1},persist:n(w,f)}}if(!await I(e.path)&&q==="")return await k(e,r),{result:{node_id:t,branch:e.branch,tip_sha:l,worktree_path:e.path,branch_deleted:!1},persist:n(l,f)};await h(e.path,["add","--all"],"abandon_stage_failed","Inspect the worktree manually, then retry."),await h(e.path,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit","--allow-empty","-m","crtr-abandon","-m",`Crtr-Abandon: ${t} ${f}`],"abandon_commit_failed","Inspect the worktree manually, then retry.");const W=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");return await k(e,r),{result:{node_id:t,branch:e.branch,tip_sha:W,worktree_path:e.path,branch_deleted:!1},persist:n(W,f)}}o(B,"abandonLocked");export{Be as abandonManagedWorktreeAsync,qe as abandonManagedWorktreeOnHost,Oe as admitIntoManagedCheckout,Fe as autoDropCleanManagedWorktreeAsync,_e as concludeAbsentManagedWorktreeAsync,ke as concludeAbsentManagedWorktreeOnHost,Te as createManagedWorktreeAsync,Ie as finalizeManagedWorktreeOnHost,Re as rollbackManagedWorktreeAsync};
9
+ `)}catch{}}o(me,"seedExclude");async function be(t){await m(t.repo_root,async()=>{const e=await s(["rev-parse","--verify",`refs/heads/${t.branch}`],t.repo_root);if(e.status!==0||e.stdout.trim()!==t.base_sha)return;const a=await s(["worktree","list","--porcelain"],t.repo_root);if(a.status===0){if(a.stdout.split(`
10
+ `).some(r=>r.trim()===`branch refs/heads/${t.branch}`)){if((await s(["worktree","remove","--force",t.path],t.repo_root)).status!==0)return}else if(l(t.path))try{J(t.path,{recursive:!0,force:!0})}catch{return}await s(["update-ref","-d",`refs/heads/${t.branch}`,t.base_sha],t.repo_root)}})}o(be,"rollbackManagedWorktreeAsync");async function Ie(t,e,a="main"){const r=await h(t,["rev-parse","--show-toplevel"],"not_git_repo","Pass --cwd <real repo> pointing inside a git repository.");if(se(r))throw new c("managed_worktree_base",`cwd ${r} is a managed worktree and cannot be used as a managed worktree base`,"Pass `--cwd` pointing at the repository\u2019s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.");const n=await T(r),i=await P(F(n),async()=>{const f=await A(r,a),w=he(e),p=`crtr/${e}`;if(l(w))throw new c("worktree_path_exists",`managed worktree path already exists: ${w}`,"Remove the stale path or choose a fresh node id.");if((await s(["show-ref","--verify","--quiet",`refs/heads/${p}`],r)).status===0)throw new c("worktree_branch_exists",`managed worktree branch already exists: ${p}`,"Remove the stale branch or choose a fresh node id.");const g={state:"open",path:w,branch:p,repo_root:r,base_ref:a,base_sha:f,created:new Date().toISOString()};await h(r,["branch",p,f],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");const k=await s(["worktree","add",w,p],r);if(k.status!==0)throw await s(["update-ref","-d",`refs/heads/${p}`,f],r),new c("worktree_add_failed","git worktree add failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.",$(k));return me(r,n),g},{timeoutMs:R(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${n}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")}),u=await pe("worktree-setup",D(i.path),i);if(u.status==="failed")throw await be(i),new c("worktree_setup_failed",".dev/worktree-setup failed","Fix the repository's .dev/worktree-setup on its base branch, then retry spawning with --worktree.",u.detail);return i}o(Ie,"createManagedWorktreeAsync");async function x(t){if(t.state!=="open"||!l(t.path))return null;const e=await s(["rev-parse","--abbrev-ref","HEAD"],t.path),a=await s(["status","--porcelain"],t.path),r=await s(["rev-parse","HEAD"],t.path);if(e.status!==0||e.stdout.trim()!==t.branch||a.status!==0||a.stdout.trim()!==""||r.status!==0)return null;const n=await s(["rev-parse","--git-path","rebase-merge"],t.path);return n.status!==0||l(n.stdout.trim())?null:r.stdout.trim()}o(x,"cleanTip");async function W(t,e){try{const a=await A(t.path,t.base_ref);return(await s(["merge-base","--is-ancestor",e,a],t.path)).status===0}catch(a){if(a instanceof c&&a.code==="missing_base_branch")return e===t.base_sha;throw a}}o(W,"containedInLocalBase");function _e(t){return{node_id:"",branch:t.branch,worktree_path:t.path,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${t.path} remains intact.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${t.branch} remains checked out at ${t.path}.`}}o(_e,"deferred");async function E(t){if(t.state!=="open"||l(t.path))return null;const e=`refs/heads/${t.branch}`,a=await s(["show-ref","--verify","--quiet",e],t.repo_root);if(a.status===1&&a.executionFailed!==!0)return{branchSha:null};if(a.status!==0)return null;const r=await s(["rev-parse","--verify",e],t.repo_root);if(r.status!==0)return null;const n=r.stdout.trim(),i=await s(["worktree","list","--porcelain"],t.repo_root);if(i.status!==0||ie(i.stdout,t.branch)!==null)return null;const u=await de(t.repo_root,t,n);return u===null?null:{branchSha:n,containment:u}}o(E,"proveAbsentPathManagedWorktree");function ke(t,e,a){return l(e.path)?null:a.branchSha===null?{node_id:t,branch:e.branch,worktree_path:e.path,worktree_removed:!0,branch_deleted:!0}:a.containment===void 0?null:{node_id:t,branch:e.branch,worktree_path:e.path,worktree_removed:!0,branch_deleted:!1,branch_delete_error:`local branch ${e.branch} is delivered but retained because its checkout status can change outside crtr's repository lock.`}}o(ke,"absentPathDrop");async function I(t,e){const a=await E(e);if(a===null)return null;const r=ke(t,e,a);return r===null?null:{dropped:r,landedSha:a.branchSha??e.base_sha}}o(I,"concludeAbsentLocked");async function ye(t){const e=(await _(t))?.managed_worktree;return e==null||e.state!=="open"||l(e.path)||await E(e)===null?null:m(e.repo_root,async()=>{const a=(await _(t))?.managed_worktree;if(a==null||a.state!=="open")return null;const r=await I(t,a);return r!==null&&await v(t,a,"complete"),r})}o(ye,"concludeAbsentManagedWorktreeAsync");async function ge(t,e){return e.state!=="open"||l(e.path)||await E(e)===null?null:m(e.repo_root,()=>I(t,e))}o(ge,"concludeAbsentManagedWorktreeOnHost");async function B(t,e,a){const r=await x(e);return r===null||r!==a||!await W(e,r)?null:{..._e(e),node_id:t}}o(B,"autoDropCleanLocked");async function Be(t){const e=(await _(t))?.managed_worktree;if(e==null||e.state!=="open")return null;if(!l(e.path))return(await ye(t))?.dropped??null;const a=await x(e);return a===null||!await W(e,a)?null:m(e.path,async()=>{const r=(await _(t))?.managed_worktree;if(r==null||r.state!=="open")return null;const n=await B(t,r,a);return n!==null&&await v(t,r,"pending"),n})}o(Be,"autoDropCleanManagedWorktreeAsync");async function qe(t,e){if(!l(e.path)){const r=await ge(t,e);return r===null?{kind:"open",missing:!0}:{kind:"dropped",dropped:r.dropped,cleanup:"complete"}}const a=await x(e);if(a!==null&&await W(e,a)){const r=await m(e.path,()=>B(t,e,a));if(r!==null)return{kind:"dropped",dropped:r,cleanup:"pending"}}return await le(e)?{kind:"pushed"}:{kind:"open",missing:!l(e.path)}}o(qe,"finalizeManagedWorktreeOnHost");async function q(t){for(const e of["rebase-merge","rebase-apply"]){const a=await s(["rev-parse","--git-path",e],t);if(a.status!==0||l(a.stdout.trim()))return!0}return!1}o(q,"rebaseInProgress");async function ve(t,e,a){return a.persist.kind==="closed"?await v(t,e,"complete"):await Z(t,{cwd:e.repo_root,abandoned:a.persist.abandoned}),a.result}o(ve,"persistAbandonOutcome");function $e(t){return new c("node_running",`node ${t} is still running`,"Abandon requires a stopped node with no live broker process. From the running owner, use `crtr node worktree close` to land locally, or make the checkout clean, push its current tip to origin, and rerun `crtr push final`.")}o($e,"nodeRunningError");async function Ne(t,e){const a=(await _(t))?.managed_worktree;if(a==null||a.state!=="open")throw new c("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to abandon for this node.");const r=[];try{return await m(a.path,async()=>{const n=await _(t),i=n?.managed_worktree;if(n===null||i===void 0||i===null||i.state!=="open")throw new c("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to abandon for this node.");if(n.status==="active"||n.status==="idle"||te(n.pi_pid))throw $e(t);return ve(t,i,await N(t,i,e,r))})}finally{await O(a.path,r[0])}}o(Ne,"abandonManagedWorktreeAsync");async function je(t,e,a){const r=[];try{return await m(e.path,()=>N(t,e,a,r))}finally{await O(e.path,r[0])}}o(je,"abandonManagedWorktreeOnHost");async function y(t,e){const{result:a,trash:r}=await fe(t.repo_root,t.path);if(r!==void 0&&e.push(r),a.status!==0)throw new c("worktree_remove_failed",`git worktree remove ${t.path} failed`,"Inspect the worktree manually, then retry.",$(a))}o(y,"removeCheckout");async function N(t,e,a,r){if(!l(e.path))throw new c("worktree_missing",`managed worktree path is missing: ${e.path}`,"Inspect the branch and worktree registration, then retry.");const n=o((d,b,S=e.branch)=>({kind:"abandoned",abandoned:{branch:S,tip_sha:d,at:b,by:a}}),"abandoned"),i=await h(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),u=await s(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path);if(i!==e.branch){if(u.status===0||i==="HEAD")throw new c("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${i==="HEAD"?"detached HEAD":i})`,`Inspect ${e.path}, then rerun \`crtr node worktree abandon\`.`);if(await q(e.path)||await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new c("dirty_worktree","managed worktree has uncommitted changes",`Commit or stash them in ${e.path}, then rerun \`crtr node worktree abandon\`.`);const d=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the worktree manually, then retry.");return await y(e,r),{result:{node_id:t,branch:i,tip_sha:d,worktree_path:e.path,branch_deleted:!1},persist:n(d,new Date().toISOString(),i)}}const f=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");let w=null;try{const d=await A(e.path,e.base_ref);(await s(["merge-base","--is-ancestor",f,d],e.path)).status===0&&(w=d)}catch(d){if(!(d instanceof c)||d.code!=="missing_base_branch")throw d}const p=new Date().toISOString(),g=await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.");if(w!==null&&f===e.base_sha){const d=await h(e.repo_root,["rev-parse",`${f}^{tree}`],"abandon_tree_failed","Inspect the branch manually, then retry."),b=await h(e.repo_root,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit-tree",d,"-p",f,"-m","crtr-abandon","-m",`Crtr-Abandon: ${t} ${p}`],"abandon_commit_failed","Inspect the branch manually, then retry.");return await h(e.repo_root,["update-ref",`refs/heads/${e.branch}`,b,f],"abandon_marker_failed","The branch changed while abandon was starting; inspect the worktree, then retry."),await y(e,r),(await s(["update-ref","--stdin"],e.repo_root,ue(e.branch,b,`refs/heads/${e.base_ref}`,w))).status===0?{result:{node_id:t,branch:e.branch,tip_sha:b,worktree_path:e.path,branch_deleted:!0},persist:{kind:"closed"}}:{result:{node_id:t,branch:e.branch,tip_sha:b,worktree_path:e.path,branch_deleted:!1},persist:n(b,p)}}if(!await q(e.path)&&g==="")return await y(e,r),{result:{node_id:t,branch:e.branch,tip_sha:f,worktree_path:e.path,branch_deleted:!1},persist:n(f,p)};await h(e.path,["add","--all"],"abandon_stage_failed","Inspect the worktree manually, then retry."),await h(e.path,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit","--allow-empty","-m","crtr-abandon","-m",`Crtr-Abandon: ${t} ${p}`],"abandon_commit_failed","Inspect the worktree manually, then retry.");const k=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");return await y(e,r),{result:{node_id:t,branch:e.branch,tip_sha:k,worktree_path:e.path,branch_deleted:!1},persist:n(k,p)}}o(N,"abandonLocked");export{Ne as abandonManagedWorktreeAsync,je as abandonManagedWorktreeOnHost,Te as admitIntoManagedCheckout,Be as autoDropCleanManagedWorktreeAsync,ye as concludeAbsentManagedWorktreeAsync,ge as concludeAbsentManagedWorktreeOnHost,Ie as createManagedWorktreeAsync,qe as finalizeManagedWorktreeOnHost,be as rollbackManagedWorktreeAsync};
@@ -0,0 +1,13 @@
1
+ import type { ManagedWorktree } from './canvas/index.js';
2
+ export type WorktreeScript = 'worktree-setup' | 'worktree-teardown';
3
+ /** Fixed, not configurable. */
4
+ export declare const WORKTREE_SCRIPT_TIMEOUT_MS: number;
5
+ export type WorktreeScriptResult = {
6
+ status: 'absent';
7
+ } | {
8
+ status: 'ok';
9
+ } | {
10
+ status: 'failed';
11
+ detail: string;
12
+ };
13
+ export declare function runWorktreeScript(script: WorktreeScript, nodeId: string, wt: ManagedWorktree, timeoutMs?: number): Promise<WorktreeScriptResult>;
@@ -0,0 +1,5 @@
1
+ var h=Object.defineProperty;var a=(t,o)=>h(t,"name",{value:o,configurable:!0});import{spawn as v}from"node:child_process";import{chmod as w,mkdtemp as C,rm as y,writeFile as I}from"node:fs/promises";import{tmpdir as P}from"node:os";import{join as p}from"node:path";import{gitAsync as T}from"./git.js";const b=5*6e4,g=20;function $(t){return t.trim().split(`
2
+ `).slice(-g).join(`
3
+ `)}a($,"tail");async function N(t,o,r,l=b){const f=`refs/heads/${r.base_ref}`,c=`${f}:.dev/${t}`;if((await T(["cat-file","-e",c],r.repo_root)).status!==0)return{status:"absent"};const n=await T(["show",c],r.repo_root);if(n.status!==0)return{status:"failed",detail:`could not read .dev/${t} from ${f}: ${n.stderr.trim()}`};const m=await C(p(P(),"crtr-worktree-script-"));try{const d=p(m,t);return await I(d,n.stdout),await w(d,493),await new Promise(E=>{const i=v(d,[],{cwd:r.path,stdio:["ignore","ignore","pipe"],env:{...process.env,CRTR_NODE_ID:o,CRTR_WORKTREE_PATH:r.path,CRTR_REPO_ROOT:r.repo_root,CRTR_BASE_REF:r.base_ref,COMPOSE_PROJECT_NAME:`crtr-${o}`}});let s="",_=!1,R=!1;const u=a(e=>{R||(R=!0,clearTimeout(O),E(e))},"finish"),O=setTimeout(()=>{_=!0,i.kill("SIGKILL"),u({status:"failed",detail:`.dev/${t} timed out after ${Math.round(l/1e3)}s
4
+ ${$(s)}`.trim()})},l);i.stderr.on("data",e=>{s=(s+e.toString("utf8")).slice(-16384)}),i.on("error",e=>u({status:"failed",detail:`could not run .dev/${t}: ${e.message}`})),i.on("close",(e,S)=>{_||u(e===0?{status:"ok"}:{status:"failed",detail:`.dev/${t} exited ${e??`by ${S}`}
5
+ ${$(s)}`.trim()})})})}finally{await y(m,{recursive:!0,force:!0})}}a(N,"runWorktreeScript");export{b as WORKTREE_SCRIPT_TIMEOUT_MS,N as runWorktreeScript};