@north-light/cli 0.3.651 → 0.3.653

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 (41) hide show
  1. package/dist/build-root.js +1 -1
  2. package/dist/clients/attach/chrome/ticket-panel.js +1 -1
  3. package/dist/clients/attach/viewer.js +487 -489
  4. package/dist/clients/inbox/controller.d.ts +6 -6
  5. package/dist/clients/inbox/controller.js +1 -1
  6. package/dist/clients/inbox/tui.js +1 -1
  7. package/dist/commands/human/queue.js +1 -1
  8. package/dist/commands/sys/daemon.js +1 -1
  9. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -1
  10. package/dist/core/canvas/managed-worktree-sweep-candidates.js +1 -1
  11. package/dist/core/canvas/schema-pg/017-machine-worktree-ops.sql +7 -0
  12. package/dist/core/canvas/schema-version.d.ts +1 -1
  13. package/dist/core/canvas/schema-version.js +1 -1
  14. package/dist/core/command-plugins/compose.d.ts +5 -1
  15. package/dist/core/command-plugins/compose.js +1 -1
  16. package/dist/core/human/convention.d.ts +1 -3
  17. package/dist/core/human/convention.js +2 -2
  18. package/dist/core/human/types.d.ts +0 -7
  19. package/dist/core/runtime/runner/machine/call.d.ts +2 -1
  20. package/dist/core/runtime/runner/machine/call.js +2 -2
  21. package/dist/core/runtime/runner/machine/executor.d.ts +1 -1
  22. package/dist/core/runtime/runner/machine/ops.d.ts +59 -1
  23. package/dist/core/runtime/runner/machine/ops.js +1 -1
  24. package/dist/core/runtime/spawn.js +2 -2
  25. package/dist/core/worktree-close.d.ts +27 -0
  26. package/dist/core/worktree-close.js +6 -6
  27. package/dist/core/worktree-machine.d.ts +27 -0
  28. package/dist/core/worktree-machine.js +1 -0
  29. package/dist/core/worktree-mutation-async.d.ts +31 -0
  30. package/dist/core/worktree-mutation-async.js +7 -7
  31. package/dist/daemon/api/handlers/human-requests.js +1 -1
  32. package/dist/daemon/api/handlers/nodes.js +1 -1
  33. package/dist/daemon/api/handlers/reports.js +5 -5
  34. package/dist/daemon/api/handlers/worktree.js +1 -1
  35. package/dist/daemon/machine-daemon.js +1 -1
  36. package/dist/daemon/manage.js +3 -3
  37. package/package.json +2 -2
  38. package/packages/crouter-identity/package.json +1 -1
  39. package/runtime.lock.json +13 -13
  40. package/dist/core/human/claim.d.ts +0 -23
  41. package/dist/core/human/claim.js +0 -3
@@ -1,3 +1,3 @@
1
- var me=Object.defineProperty;var d=(e,o)=>me(e,"name",{value:o,configurable:!0});import{accessSync as he,constants as pe}from"node:fs";import{isAbsolute as _e,resolve as ke,join as ve}from"node:path";import{appSpace as ge}from"../layout.js";import{ApiError as ne}from"../../api/errors.js";import{spawnNode as ye,forkSourceNode as be,currentNodeContext as xe,rootOfSpine as $e,newNodeId as Se,preflightNodeId as Ce}from"./nodes.js";import{resolveProfileOperand as Ee}from"../profiles/manifest.js";import{selectProfileForCwd as Re,selectProfileForCwdReadOnly as Oe}from"../profiles/select.js";import{buildLaunchSpecAsync as oe,buildPiArgv as Ie}from"./launch.js";import{runsOnBlaxel as Fe,sandboxWorktreeRequest as Pe}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Be,rollbackManagedWorktreeAsync as De}from"../worktree-mutation-async.js";import{usage as w,brokerLaunchFailed as D}from"../errors.js";import{writeGoal as Ne}from"./kickoff.js";import{appendSituationalContext as Le,formatSituationalProse as Me}from"./situational-context.js";import{ensureRoadmap as Te}from"./roadmap.js";import{buildWakeBearings as Ae}from"./bearings.js";import{encodeKickoffOrigin as We,KICKOFF_ORIGIN_ENV as je}from"./stamp/protocol.js";import{carryInitialInput as ze}from"../runs/initial-input.js";import{ExecutionCapReached as He,beginExecution as Ke,crtrHome as Ge,getNode as u,fullName as re,jobDir as Ue,recordExecutionPid as Ve,abortExecution as j,setFrozen as z}from"../canvas/index.js";import{contextDir as H,nodeAgentDir as K}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as Xe}from"../spaces/open-beneath.js";import{conversationIdFromPath as N,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as qe,boundFleet as Ye,brokerThresholdsForDaemon as te}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{emitEvent as L}from"../events/emit.js";import{remoteEnvironmentOf as Qe}from"./blaxel-environment.js";import{openViewerWindow as Ze,focusOf as en,windowOfPane as nn}from"./placement.js";import{awaitBrokerViewSocket as on}from"./view-socket.js";import{readLogSnapshot as rn}from"../events/read.js";import{transition as v}from"./lifecycle.js";import{beginBootFaultAttempt as tn}from"../canvas/recovery.js";import{headlessBrokerHost as G}from"./host.js";import{ensureDaemon as an}from"../../daemon/manage.js";import{readConfig as dn}from"../config.js";import{modelRequestFromConfig as sn,unregisteredConcreteModel as ln,unroutableConcreteModel as cn}from"../model-routes.js";import{openModelRegistry as un}from"./model-registry.js";import{MODEL_SPEC_NEXT as fn}from"./model-selection.js";import{forkNodeLedger as wn}from"./ledger.js";import{appRungForGrant as mn}from"../llm/app-rungs.js";import{APP_FAMILY as U}from"../model-routes.js";import{discoverLifecycleHookRegistry as hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as pn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as _n}from"../async-array.js";import{checkStart as kn}from"./start-check.js";function g(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(g,"launchFailureOutcome");async function vn(e,o,a){try{return await G.launch(e,o,a)}catch(r){try{await v(e,"crash",{reason:"launch_failed",outcome:g(r)})}catch{}const t=r.message;throw D(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d(vn,"launchBrokerOrCrash");function gn(e){return rn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d(gn,"lastStartupStep");function yn(e,o){const a=gn(e),r=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(o.reason==="exited"){const{code:t,signal:s}=o.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${r}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(o.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${r}`,fields:{reason:"timeout",waited_ms:o.waitedMs,last_startup_step:a}}}d(yn,"notReadyDescription");async function bn(e,o){try{await v(e,"crash",{reason:"launch_failed",outcome:g(o)})}catch{}try{G.teardown(e)}catch{}}d(bn,"crashAndTearDown");async function xn(e){const o=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=o.filter(t=>t.id===e),r=a.length>0?a:o.filter(t=>t.id.startsWith(e));if(r.length===0)throw w(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(r.length>1)throw w(`--fork-from '${e}': ambiguous \u2014 ${r.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return r[0].path}d(xn,"resolveSessionUuid");async function ie(e){const o=e.trim();if(o==="")throw w("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(o.includes("/")||o.endsWith(".jsonl")){const r=N(_e(o)?o:ke(process.cwd(),o));if(r===null)throw w(`--fork-from '${o}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(r)).path}const a=await u(o);if(a!==null){const r=a.pi_session_file;if(r==null||r==="")throw w(`node ${o} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=N(r);if(t===null)throw w(`node ${o} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await xn(o)}d(ie,"resolveForkSource");async function $n(e,o,a,r={}){return e===null?null:e!==void 0&&e!==""?Ee(e).profileId:o!==null?(await u(o))?.profile_id??null:r.readOnlySelection===!0?Oe(a):Re(a)}d($n,"resolveProfileId");function ae(e){const o=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return sn(e.model,o,e.modelExact===!0)}d(ae,"requestFromLaunch");async function de(e,o,a){const r=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await mn(o,r,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:U,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${U}/${t.strength}`}}}d(de,"appPaidLaunch");async function se(e,o,a){if(e===void 0||e.kind==="logical"&&e.family!==U)return;const r=await ln(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await un(),o);if(r!==void 0)throw w(`model '${r.request.spec}' is not registered in this daemon.`,{received:r.request.spec,next:fn});const t=await cn(e,o);if(t!==void 0)throw w(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(se,"assertLaunchModelRegistered");function Sn(e,o,a){const r=e??o??null;if(!a&&r===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return r}d(Sn,"resolveSpawner");async function le(e,o,a){try{an()}catch{}const r=xe(),t=e.root===!0,s=Sn(e.parent,r.nodeId??null,t),l=e.mode??"base",y=e.rootLifecycle??(t?"resident":"terminal"),ce=t&&y==="resident",R=s===null?null:await u(s),V=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Ce(e.nodeId);const b=e.forkFrom!==void 0?await ie(e.forkFrom):void 0,M=b===void 0?null:await be(b),T=await _n([R,V,M],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(T&&e.isolated===!1)throw new ne(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const O=T||e.isolated===!0;if(O&&e.worktree===!0)throw new ne(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const C=e.worktree===!0,m=O||C?e.nodeId??await Se():e.nodeId,I=O?e.run!==void 0&&t&&!T?e.cwd:ve(ge(e.run?.grantee??R?.grantee??"app:terminal").nodes,m):e.cwd,h=await $n(e.profile,s,I),X=e.run?.grant_id??R?.grant_id??null,E=e.run??V??R??M,q=await de((await oe(e.kind,l,{lifecycle:y,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:I,profileId:h,app:E?.grantee??"app:terminal"})).launch,X,e.model);await se(ae(q),{cwd:I,profileId:h}),await kn({grantee:E?.grantee??"app:terminal",sub:E?.sub,grant_id:E?.grant_id});const Y=M?.node_id??null;let x,F=I;const A=C&&await Fe(h)?await Pe(h,e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0;try{C&&A===void 0&&(x=await Be(e.worktreeCwd??e.cwd,m,e.worktreeBase),F=x.path);const f=C?await de((await oe(e.kind,l,{lifecycle:y,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:F,profileId:h,app:E?.grantee??"app:terminal"})).launch,X,e.model):q;A!==void 0&&(f.worktree=A),C&&await se(ae(f),{cwd:F,profileId:h});const n=await ye({kind:e.kind,mode:l,lifecycle:y,cwd:F,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:Y,spawnedBy:t?s??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:O,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:b,modelOverride:e.model===void 0?void 0:f.model,...x!==void 0?{managedWorktree:x}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await wn(n.node_id,Y??null)}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}if(await Ne(n.node_id,e.prompt),e.situationalContext!==void 0&&await Le(n.node_id,Me(e.situationalContext)),o!==void 0)try{o(n.node_id)}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}const W=e.prompt!=="",ue=`${W&&e.wakeOrigin!==void 0?`${Ae(e.wakeOrigin)}
1
+ var he=Object.defineProperty;var d=(e,o)=>he(e,"name",{value:o,configurable:!0});import{accessSync as pe,constants as ke}from"node:fs";import{isAbsolute as _e,resolve as ve,join as ge}from"node:path";import{appSpace as ye}from"../layout.js";import{ApiError as oe}from"../../api/errors.js";import{spawnNode as be,forkSourceNode as xe,currentNodeContext as $e,rootOfSpine as Ce,newNodeId as Se,preflightNodeId as Oe}from"./nodes.js";import{resolveProfileOperand as Ee}from"../profiles/manifest.js";import{selectProfileForCwd as Re,selectProfileForCwdReadOnly as Ie}from"../profiles/select.js";import{buildLaunchSpecAsync as re,buildPiArgv as Fe}from"./launch.js";import{runsOnBlaxel as Me,sandboxWorktreeRequest as Be}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Pe,rollbackManagedWorktreeAsync as De}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Ne,rollbackManagedWorktreeOnMachine as Le,worktreeMachineOf as Te}from"../worktree-machine.js";import{usage as w,brokerLaunchFailed as N}from"../errors.js";import{writeGoal as Ae}from"./kickoff.js";import{appendSituationalContext as We,formatSituationalProse as je}from"./situational-context.js";import{ensureRoadmap as ze}from"./roadmap.js";import{buildWakeBearings as He}from"./bearings.js";import{encodeKickoffOrigin as Ke,KICKOFF_ORIGIN_ENV as Ge}from"./stamp/protocol.js";import{carryInitialInput as Ue}from"../runs/initial-input.js";import{ExecutionCapReached as Ve,beginExecution as Xe,crtrHome as qe,getNode as u,fullName as te,jobDir as Ye,recordExecutionPid as Je,abortExecution as z,setFrozen as H}from"../canvas/index.js";import{contextDir as K,nodeAgentDir as G}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as Qe}from"../spaces/open-beneath.js";import{conversationIdFromPath as L,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as Ze,boundFleet as en,brokerThresholdsForDaemon as ie}from"./fleet.js";import{admitBrokerMemory as nn}from"./memory-admission.js";import{emitEvent as T}from"../events/emit.js";import{remoteEnvironmentOf as on}from"./blaxel-environment.js";import{openViewerWindow as rn,focusOf as tn,windowOfPane as an}from"./placement.js";import{awaitBrokerViewSocket as dn}from"./view-socket.js";import{readLogSnapshot as sn}from"../events/read.js";import{transition as g}from"./lifecycle.js";import{beginBootFaultAttempt as ln}from"../canvas/recovery.js";import{headlessBrokerHost as U}from"./host.js";import{ensureDaemon as cn}from"../../daemon/manage.js";import{readConfig as un}from"../config.js";import{modelRequestFromConfig as fn,unregisteredConcreteModel as wn,unroutableConcreteModel as mn}from"../model-routes.js";import{openModelRegistry as hn}from"./model-registry.js";import{MODEL_SPEC_NEXT as pn}from"./model-selection.js";import{forkNodeLedger as kn}from"./ledger.js";import{appRungForGrant as _n}from"../llm/app-rungs.js";import{APP_FAMILY as V}from"../model-routes.js";import{discoverLifecycleHookRegistry as vn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as gn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as yn}from"../async-array.js";import{checkStart as bn}from"./start-check.js";function y(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(y,"launchFailureOutcome");async function xn(e,o,a){try{return await U.launch(e,o,a)}catch(r){try{await g(e,"crash",{reason:"launch_failed",outcome:y(r)})}catch{}const t=r.message;throw N(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d(xn,"launchBrokerOrCrash");function $n(e){return sn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d($n,"lastStartupStep");function Cn(e,o){const a=$n(e),r=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(o.reason==="exited"){const{code:t,signal:s}=o.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${r}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(o.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${r}`,fields:{reason:"timeout",waited_ms:o.waitedMs,last_startup_step:a}}}d(Cn,"notReadyDescription");async function Sn(e,o){try{await g(e,"crash",{reason:"launch_failed",outcome:y(o)})}catch{}try{U.teardown(e)}catch{}}d(Sn,"crashAndTearDown");async function On(e){const o=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=o.filter(t=>t.id===e),r=a.length>0?a:o.filter(t=>t.id.startsWith(e));if(r.length===0)throw w(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(r.length>1)throw w(`--fork-from '${e}': ambiguous \u2014 ${r.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return r[0].path}d(On,"resolveSessionUuid");async function ae(e){const o=e.trim();if(o==="")throw w("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(o.includes("/")||o.endsWith(".jsonl")){const r=L(_e(o)?o:ve(process.cwd(),o));if(r===null)throw w(`--fork-from '${o}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(r)).path}const a=await u(o);if(a!==null){const r=a.pi_session_file;if(r==null||r==="")throw w(`node ${o} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=L(r);if(t===null)throw w(`node ${o} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await On(o)}d(ae,"resolveForkSource");async function En(e,o,a,r={}){return e===null?null:e!==void 0&&e!==""?Ee(e).profileId:o!==null?(await u(o))?.profile_id??null:r.readOnlySelection===!0?Ie(a):Re(a)}d(En,"resolveProfileId");function de(e){const o=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return fn(e.model,o,e.modelExact===!0)}d(de,"requestFromLaunch");async function se(e,o,a){const r=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await _n(o,r,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:V,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${V}/${t.strength}`}}}d(se,"appPaidLaunch");async function le(e,o,a){if(e===void 0||e.kind==="logical"&&e.family!==V)return;const r=await wn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await hn(),o);if(r!==void 0)throw w(`model '${r.request.spec}' is not registered in this daemon.`,{received:r.request.spec,next:pn});const t=await mn(e,o);if(t!==void 0)throw w(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(le,"assertLaunchModelRegistered");function Rn(e,o,a){const r=e??o??null;if(!a&&r===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return r}d(Rn,"resolveSpawner");async function ce(e,o,a){try{cn()}catch{}const r=$e(),t=e.root===!0,s=Rn(e.parent,r.nodeId??null,t),l=e.mode??"base",b=e.rootLifecycle??(t?"resident":"terminal"),ue=t&&b==="resident",E=s===null?null:await u(s),X=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Oe(e.nodeId);const x=e.forkFrom!==void 0?await ae(e.forkFrom):void 0,A=x===void 0?null:await xe(x),W=await yn([E,X,A],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(W&&e.isolated===!1)throw new oe(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const R=W||e.isolated===!0;if(R&&e.worktree===!0)throw new oe(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const $=e.worktree===!0,m=R||$?e.nodeId??await Se():e.nodeId,I=R?e.run!==void 0&&t&&!W?e.cwd:ge(ye(e.run?.grantee??E?.grantee??"app:terminal").nodes,m):e.cwd,h=await En(e.profile,s,I),q=e.run?.grant_id??E?.grant_id??null,O=e.run??X??E??A,Y=await se((await re(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:I,profileId:h,app:O?.grantee??"app:terminal"})).launch,q,e.model);await le(de(Y),{cwd:I,profileId:h}),await bn({grantee:O?.grantee??"app:terminal",sub:O?.sub,grant_id:O?.grant_id});const J=A?.node_id??null;let p,F=I;const M=$&&await Me(h)?await Be(h,e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0,B=$&&M===void 0?await Te(h):null;try{$&&M===void 0&&(p=B!==null?await Ne(B,e.worktreeCwd??e.cwd,m,e.worktreeBase):await Pe(e.worktreeCwd??e.cwd,m,e.worktreeBase),F=p.path);const f=$?await se((await re(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:F,profileId:h,app:O?.grantee??"app:terminal"})).launch,q,e.model):Y;M!==void 0&&(f.worktree=M),$&&await le(de(f),{cwd:F,profileId:h});const n=await be({kind:e.kind,mode:l,lifecycle:b,cwd:F,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:J,spawnedBy:t?s??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:R,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:x,modelOverride:e.model===void 0?void 0:f.model,...p!==void 0?{managedWorktree:p}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await kn(n.node_id,J??null)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(await Ae(n.node_id,e.prompt),e.situationalContext!==void 0&&await We(n.node_id,je(e.situationalContext)),o!==void 0)try{o(n.node_id)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const j=e.prompt!=="",fe=`${j&&e.wakeOrigin!==void 0?`${He(e.wakeOrigin)}
2
2
 
3
- `:""}${e.prompt}`;l==="orchestrator"&&await Te(n.node_id,{goal:e.prompt.trim()}),await Cn(n);let J;if(b!==void 0)try{const i=N(b);if(i===null)throw new Error(`invalid fork source ${b}`);const c=await S().fork(i,n.node_id);J=(await S().header(c)).path}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}const p=Ie(n,{prompt:ue,resumeSessionPath:J});if(p.env={...p.env,CRTR_SUBTREE:await $e(n.node_id)},W){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};p.env[je]=We(i),await ze(p,n)}const _=Ye();if(await Qe(n.profile_id??null)!==null)return await z(n.node_id,new Date().toISOString()),L({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const Q=await _.reserveSlot(n.node_id),k=Q?await Je(n.node_id):null;if(k?.verdict==="too_small"){_.releaseReservation(n.node_id);const i=qe(k);throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}if(!Q||k?.verdict==="denied")return k?.verdict==="denied"&&_.releaseReservation(n.node_id),await z(n.node_id,new Date().toISOString()),L({level:"info",event:"broker.frozen",node_id:n.node_id,fields:k?.verdict==="denied"?{reason:"app_memory",free_bytes:k.free_bytes,needed_bytes:k.needed_bytes}:{reason:"broker_cap",live_count:await _.occupancy(),hard_cap:te().automaticReviveCap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const fe=await tn(n.node_id),{automaticReviveCap:we}=te();let $;try{$=await Ke(n.node_id,{daemonEpoch:_.epoch(),cap:we})}catch(i){if(!(i instanceof He))throw i;return _.releaseReservation(n.node_id),await z(n.node_id,new Date().toISOString()),L({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null}}p.env={...p.env,CRTR_EXECUTION_ID:$};let P;try{P=await vn(n.node_id,p,{cwd:n.cwd,name:re(n),resuming:!1})}catch(i){throw await j($,{reason:"launch_failed"}),i}finally{_.releaseReservation(n.node_id)}if(P.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await j($,{reason:"launch_failed"}),await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),D(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await Ve($,n.node_id,P.pid)==="shutdown")throw await j($,{reason:"superseded"}),G.teardown(n.node_id),D(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(ce&&e.readiness==="await"){const i=await on(n.node_id,P.exited);if(!i.ready){const c=yn(n.node_id,i);L({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:c.fields});const B=await fe.explanation();throw await bn(n.node_id,new Error(B??c.text)),D(B!==null?`the root broker ${n.node_id} could not start \u2014 ${B}`:`the root broker ${n.node_id} ${c.text} \u2014 it was not started.`,B!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let Z=null,ee=null;if(!t&&s!==null&&dn("user").auto_open_child_viewers)try{const i=await en(s);if(i!==null&&i.pane!==null&&i.pane!==""){const c=await Ze(n.node_id,i.session??"",{name:re(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:W});c!==null&&c.pane!==null&&c.pane!==""&&(ee=c.session,Z=nn(c.pane))}}catch{}return{node:await u(n.node_id),frozen:!1,window:Z,session:ee}}catch(f){throw x!==void 0&&m!==void 0&&await u(m)===null&&await De(x),f}}d(le,"spawnChildPrepared");async function yo(e){return le(e)}d(yo,"spawnChild");async function Cn(e){const o=hn(e.cwd,e.profile_id).plans.get("node:start")??[];await pn(o,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await K(e.node_id),contextDir:await H(e.node_id),jobDir:Ue(e.node_id)},runtime:{isBirth:!0,canvasHome:Ge(),profile:e.profile_id??null}})}d(Cn,"invokeBirthLifecycleHooks");const En=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function bo(e,o,a){const r=await u(e);if(r===null)throw w(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=await ie(e),s=await H(e);try{await S().header(N(t)),he(s,pe.R_OK)}catch(l){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${l.message}`)}return le({kind:r.kind,mode:"base",cwd:r.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...a===void 0?{}:{actor:a},profile:r.profile_id,model:r.model_override??void 0,...o===void 0?{}:{scopes:o}},async l=>{const y=await H(l);Xe(await K(e),s,await K(l),y,En)})}d(bo,"forkNode");export{de as appPaidLaunch,se as assertLaunchModelRegistered,bo as forkNode,Cn as invokeBirthLifecycleHooks,ie as resolveForkSource,$n as resolveProfileId,Sn as resolveSpawner,yo as spawnChild,le as spawnChildPrepared};
3
+ `:""}${e.prompt}`;l==="orchestrator"&&await ze(n.node_id,{goal:e.prompt.trim()}),await In(n);let Q;if(x!==void 0)try{const i=L(x);if(i===null)throw new Error(`invalid fork source ${x}`);const c=await S().fork(i,n.node_id);Q=(await S().header(c)).path}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const k=Fe(n,{prompt:fe,resumeSessionPath:Q});if(k.env={...k.env,CRTR_SUBTREE:await Ce(n.node_id)},j){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};k.env[Ge]=Ke(i),await Ue(k,n)}const _=en();if(await on(n.profile_id??null)!==null)return await H(n.node_id,new Date().toISOString()),T({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const Z=await _.reserveSlot(n.node_id),v=Z?await nn(n.node_id):null;if(v?.verdict==="too_small"){_.releaseReservation(n.node_id);const i=Ze(v);throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(!Z||v?.verdict==="denied")return v?.verdict==="denied"&&_.releaseReservation(n.node_id),await H(n.node_id,new Date().toISOString()),T({level:"info",event:"broker.frozen",node_id:n.node_id,fields:v?.verdict==="denied"?{reason:"app_memory",free_bytes:v.free_bytes,needed_bytes:v.needed_bytes}:{reason:"broker_cap",live_count:await _.occupancy(),hard_cap:ie().automaticReviveCap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const we=await ln(n.node_id),{automaticReviveCap:me}=ie();let C;try{C=await Xe(n.node_id,{daemonEpoch:_.epoch(),cap:me})}catch(i){if(!(i instanceof Ve))throw i;return _.releaseReservation(n.node_id),await H(n.node_id,new Date().toISOString()),T({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null}}k.env={...k.env,CRTR_EXECUTION_ID:C};let P;try{P=await xn(n.node_id,k,{cwd:n.cwd,name:te(n),resuming:!1})}catch(i){throw await z(C,{reason:"launch_failed"}),i}finally{_.releaseReservation(n.node_id)}if(P.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await z(C,{reason:"launch_failed"}),await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),N(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await Je(C,n.node_id,P.pid)==="shutdown")throw await z(C,{reason:"superseded"}),U.teardown(n.node_id),N(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(ue&&e.readiness==="await"){const i=await dn(n.node_id,P.exited);if(!i.ready){const c=Cn(n.node_id,i);T({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:c.fields});const D=await we.explanation();throw await Sn(n.node_id,new Error(D??c.text)),N(D!==null?`the root broker ${n.node_id} could not start \u2014 ${D}`:`the root broker ${n.node_id} ${c.text} \u2014 it was not started.`,D!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ee=null,ne=null;if(!t&&s!==null&&un("user").auto_open_child_viewers)try{const i=await tn(s);if(i!==null&&i.pane!==null&&i.pane!==""){const c=await rn(n.node_id,i.session??"",{name:te(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:j});c!==null&&c.pane!==null&&c.pane!==""&&(ne=c.session,ee=an(c.pane))}}catch{}return{node:await u(n.node_id),frozen:!1,window:ee,session:ne}}catch(f){throw p!==void 0&&m!==void 0&&await u(m)===null&&(B!==null?await Le(B,p):await De(p)),f}}d(ce,"spawnChildPrepared");async function So(e){return ce(e)}d(So,"spawnChild");async function In(e){const o=vn(e.cwd,e.profile_id).plans.get("node:start")??[];await gn(o,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await G(e.node_id),contextDir:await K(e.node_id),jobDir:Ye(e.node_id)},runtime:{isBirth:!0,canvasHome:qe(),profile:e.profile_id??null}})}d(In,"invokeBirthLifecycleHooks");const Fn=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function Oo(e,o,a){const r=await u(e);if(r===null)throw w(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=await ae(e),s=await K(e);try{await S().header(L(t)),pe(s,ke.R_OK)}catch(l){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${l.message}`)}return ce({kind:r.kind,mode:"base",cwd:r.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...a===void 0?{}:{actor:a},profile:r.profile_id,model:r.model_override??void 0,...o===void 0?{}:{scopes:o}},async l=>{const b=await K(l);Qe(await G(e),s,await G(l),b,Fn)})}d(Oo,"forkNode");export{se as appPaidLaunch,le as assertLaunchModelRegistered,Oo as forkNode,In as invokeBirthLifecycleHooks,ae as resolveForkSource,En as resolveProfileId,Rn as resolveSpawner,So as spawnChild,ce as spawnChildPrepared};
@@ -1,4 +1,31 @@
1
+ import { type ManagedWorktree } from './canvas/index.js';
2
+ import { type AbsentWorktreeConclusion } from './worktree-mutation-async.js';
1
3
  import { type CloseManagedWorktreeResult } from './worktree.js';
4
+ /** What an explicit close decided, without the database. `closed`: persist the record closed with cleanup pending (after recording
5
+ * `disposal` when present) and answer `result`. `blocked`: the rebase succeeded but the base could not be fast-forwarded; record the
6
+ * land intent `blocked`, then throw `land_base_failed`. Plain data: the outcome crosses the machine link. */
7
+ export type CloseOutcome = {
8
+ kind: 'closed';
9
+ result: CloseManagedWorktreeResult;
10
+ disposal?: NonNullable<ManagedWorktree['disposal']>;
11
+ } | {
12
+ kind: 'blocked';
13
+ blocked: string;
14
+ next: string;
15
+ detail: string;
16
+ };
17
+ /** Apply a close decision to the canvas: the one place close writes rows. */
18
+ export declare function persistCloseOutcome(nodeId: string, wt: ManagedWorktree, outcome: CloseOutcome): Promise<CloseManagedWorktreeResult>;
2
19
  /** Async daemon executor for explicit close. The lock wait and every Git
3
20
  * subprocess yield to the daemon event loop. */
4
21
  export declare function closeManagedWorktreeAsync(nodeId: string): Promise<CloseManagedWorktreeResult>;
22
+ /** What a close on the computer that holds the checkout (an imported Mac) did: `concluded` when the checkout path was gone and its
23
+ * branch is proven delivered (persist cleanup `complete`, answer from `conclusion`), else the close decision. */
24
+ export type CloseOnHostOutcome = {
25
+ kind: 'concluded';
26
+ conclusion: AbsentWorktreeConclusion;
27
+ } | CloseOutcome;
28
+ /** {@link closeManagedWorktreeAsync}'s Git work with no database: the control plane sent the open record and persists the outcome. */
29
+ export declare function closeManagedWorktreeOnHost(nodeId: string, wt: ManagedWorktree): Promise<CloseOnHostOutcome>;
30
+ /** The result `closeManagedWorktreeAsync` answers for a concluded absent checkout. */
31
+ export declare function concludedCloseResult(nodeId: string, conclusion: AbsentWorktreeConclusion): CloseManagedWorktreeResult;
@@ -1,6 +1,6 @@
1
- var P=Object.defineProperty;var c=(t,r)=>P(t,"name",{value:r,configurable:!0});import{existsSync as $,realpathSync as R}from"node:fs";import{resolve as q}from"node:path";import{getNode as v,recordDisposalGrant as B,recordLandIntent as M}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as O}from"./exclusive-lock.js";import{gitAsync as i}from"./git.js";import{proveBranchContained as x}from"./worktree-containment.js";import{concludeAbsentManagedWorktreeAsync as F}from"./worktree-mutation-async.js";import{parseStatusPorcelain as G,planLandIntoCheckout as I}from"./worktree-landing.js";import{WORKTREE_LOCK_WAIT_MS as T,checkoutPathForBranchInList as N,missingWorktreeRecoveryHint as j,persistClosedWorktreeState as A,samePath as K,worktreeLockPathForCommonDir as z,WorktreeError as h}from"./worktree.js";import{shellQuote as E}from"../shared/shell-quote.js";function w(t){return(t.stderr.trim()||t.stdout.trim()).trim()}c(w,"detailOf");async function u(t,r,e,o){const a=await i(r,t);if(a.status!==0)throw new h(e,`git ${r.join(" ")} failed`,o,w(a));return a.stdout.trim()}c(u,"runGit");async function H(t){const r=await u(t,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.");return R(q(t,r))}c(H,"commonGitDir");async function Q(t,r){const e=`refs/heads/${r}`,o=await i(["show-ref","--verify","--quiet",e],t);if(o.status===1&&o.executionFailed!==!0)throw new h("missing_base_branch",`managed worktree base '${r}' 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(o.status!==0){const a=o.processError===void 0?"":`
2
- process error: ${o.processError}`;throw new h("base_branch_inspection_failed",`could not inspect local base branch '${r}' (git show-ref exited with status ${o.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${o.status}
3
- stderr: ${o.stderr.trim()||"<empty>"}${a}`)}return u(t,["rev-parse","--verify",e],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}c(Q,"resolveLandableBase");async function J(t){for(const r of["rebase-merge","rebase-apply"]){const e=await u(t,["rev-parse","--git-path",r],"git_path_failed","Inspect the worktree manually, then retry.");if($(e))return!0}return!1}c(J,"rebaseInProgress");async function L(t,r,e){const o=await i(["worktree","list","--porcelain"],t);if(o.status!==0)return!1;let a=null;for(const n of o.stdout.split(`
4
- `))if(n.startsWith("worktree "))a=n.slice(9).trim();else if(a!==null&&K(a,r)&&n===`branch refs/heads/${e}`)return!0;return!1}c(L,"registeredWorktree");function D(t){return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${t.path} remains intact. After its node exits, run \`git -C ${E(t.repo_root)} worktree remove ${E(t.path)}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${t.branch} remains checked out at ${t.path}; delete it only after that checkout is removed and its landed commit is still contained in ${t.base_ref}.`}}c(D,"deferredCleanupResult");async function U(t,r){const e=(await v(t))?.managed_worktree;e==null||e.state!=="open"||await M(t,{at:new Date().toISOString(),blocked:r})}c(U,"recordBlockedLandIntent");async function W(t,r){const e=await i(["rev-parse","--verify","--quiet","refs/stash"],t);e.status===0&&e.stdout.trim()===r&&await i(["stash","drop"],t)}c(W,"dropStashIfStillTip");async function V(t,r,e,o){const a=await i(["status","--porcelain"],t);if(a.status!==0)return{ok:!1,detail:w(a)};const n=await i(["diff","--name-only",e,o],t);if(n.status!==0)return{ok:!1,detail:w(n)};const f=n.stdout.split(`
5
- `).map(_=>_.trim()).filter(_=>_!==""),k=I(G(a.stdout),f);if(k.kind==="refuse")return{ok:!1,detail:`untracked files in ${t} would be overwritten by the incoming commits: ${k.collisions.join(", ")}`};const p=c(async()=>{const _=await i(["merge","--ff-only",o],t);return _.status===0?{ok:!0}:{ok:!1,detail:w(_)}},"merge");if(k.kind==="direct")return p();const b=await i(["rev-parse","--verify","--quiet","refs/stash"],t),g=b.status===0?b.stdout.trim():null,y=await i(["stash","push","--message",`crtr landing ${r}`],t);if(y.status!==0)return{ok:!1,detail:w(y)};const m=await i(["rev-parse","--verify","--quiet","refs/stash"],t),l=m.status===0?m.stdout.trim():null;if(l===null||l===g)return p();const s=`local changes from ${t} are retained in stash ${l}; recover them with \`git -C ${E(t)} stash apply ${l}\` and resolve any conflict.`,d=await p();return d.ok?(await i(["stash","apply",l],t)).status===0?(await W(t,l),{ok:!0}):(await i(["reset","--hard",o],t),{ok:!0,stash:`the shared base checkout was reset to landed commit ${o} because local changes conflicted with it. ${s}`}):(await i(["stash","apply",l],t)).status===0?(await W(t,l),d):{ok:!1,detail:`${d.detail}
6
- ${s}`}}c(V,"landIntoBaseCheckout");async function S(t){const r=await v(t);if(r===null)throw new h("unknown_node",`unknown node: ${t}`,"Run this from a live node, or pass a real node id once that command supports it.");const e=r?.managed_worktree?.state==="open"?r.managed_worktree:null;if(e===null)throw new h("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to close for this node.");if(!$(e.path))throw new h("worktree_missing",`managed worktree path is missing: ${e.path}`,j(e));if(await J(e.path))throw new h("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(await u(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new h("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${e.path}, then rerun \`crtr node worktree close\`.`);const a=await u(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),n=await u(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(a!==e.branch){if((await i(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path)).status===0||a==="HEAD"||!await L(e.repo_root,e.path,a))throw new h("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${a==="HEAD"?"detached HEAD":a})`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);if(await x(e.path,e,n)===null)throw new h("branch_moved_unlanded",`managed worktree's recorded branch ${e.branch} no longer exists; its checkout is now on ${a} at ${n}, which carries content local base branch '${e.base_ref}' does not yet contain`,`Land or push ${a} through its own workflow before closing.`);const d=await H(e.path);if(!await L(e.repo_root,e.path,a)||await u(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==a||await u(e.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==n)throw new h("wrong_branch",`managed worktree at ${e.path} changed while closing`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);return await B(t,{observed_branch:a,observed_sha:n,common_dir:d,authorized:new Date().toISOString()}),await A(t,e,"pending"),{node_id:t,branch:a,worktree_path:e.path,landed_sha:n,...D(e),branch_delete_error:`${a} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}if(await x(e.path,e,n)!==null)return await A(t,e,"pending"),{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:n,...D(e)};let f;try{f=await Q(e.path,e.base_ref)}catch(s){if(!(s instanceof h)||s.code!=="missing_base_branch"||n!==e.base_sha)throw s;return await A(t,e,"pending"),{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:e.base_sha,...D(e)}}const k=await i(["rebase",f],e.path);if(k.status!==0)throw new h("rebase_failed",`rebase onto local base branch '${e.base_ref}' did not complete`,`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`,w(k));const p=await u(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),b=c(async(s,d,_)=>(await U(t,s),new h("land_base_failed",s,d,_)),"blocked"),g=await i(["merge-base","--is-ancestor",f,p],e.path);if(g.status!==0)throw await b(`rebased worktree is not a fast-forward of local base branch '${e.base_ref}'`,"Ask the user how to land this managed worktree.",w(g));const y=await u(e.path,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry."),m=N(y,e.base_ref);let l;if(m!==null){const s=await i(["rev-parse","HEAD"],m);if(s.status!==0||s.stdout.trim()!==f)throw await b(`local base branch '${e.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${m}, then rerun \`crtr node worktree close\`.`,s.status!==0?w(s):`expected ${f}, found ${s.stdout.trim()}`);const d=await V(m,e.branch,f,p);if(!d.ok)throw await b(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,`Local base branch '${e.base_ref}' is checked out at ${m} in a state that blocks a fast-forward.`,d.detail);l=d.stash}else{const s=await i(["update-ref",`refs/heads/${e.base_ref}`,p,f],e.path);if(s.status!==0)throw await b(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,"Ask the user how to land this managed worktree.",w(s))}return await A(t,e,"pending"),{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:p,...D(e),...l===void 0?{}:{base_checkout_stash:l}}}c(S,"closeLocked");async function ie(t){const r=(await v(t))?.managed_worktree;if(r==null||r.state!=="open")return S(t);if(!$(r.path)){const n=await F(t);if(n!==null)return{node_id:t,branch:n.dropped.branch,worktree_path:n.dropped.worktree_path,landed_sha:n.landedSha,worktree_removed:!0,branch_deleted:n.dropped.branch_deleted,...n.dropped.branch_delete_error===void 0?{}:{branch_delete_error:n.dropped.branch_delete_error}}}const e=(await v(t))?.managed_worktree;if(e==null||e.state!=="open")return S(t);const o=$(e.path)?e.path:e.repo_root,a=await H(o);return O(z(a),()=>S(t),{timeoutMs:Math.min(T,25e3),timeoutError:c(()=>new h("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${a}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}c(ie,"closeManagedWorktreeAsync");export{ie as closeManagedWorktreeAsync};
1
+ var P=Object.defineProperty;var s=(t,e)=>P(t,"name",{value:e,configurable:!0});import{existsSync as b,realpathSync as q}from"node:fs";import{resolve as I}from"node:path";import{getNode as $,recordDisposalGrant as B,recordLandIntent as F}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as H}from"./exclusive-lock.js";import{gitAsync as i}from"./git.js";import{proveBranchContained as S}from"./worktree-containment.js";import{concludeAbsentManagedWorktreeAsync as G,concludeAbsentManagedWorktreeOnHost as T}from"./worktree-mutation-async.js";import{parseStatusPorcelain as N,planLandIntoCheckout as j}from"./worktree-landing.js";import{WORKTREE_LOCK_WAIT_MS as W,checkoutPathForBranchInList as K,missingWorktreeRecoveryHint as z,persistClosedWorktreeState as Q,samePath as C,worktreeLockPathForCommonDir as L,WorktreeError as l}from"./worktree.js";import{shellQuote as D}from"../shared/shell-quote.js";function u(t){return(t.stderr.trim()||t.stdout.trim()).trim()}s(u,"detailOf");async function d(t,e,a,r){const n=await i(e,t);if(n.status!==0)throw new l(a,`git ${e.join(" ")} failed`,r,u(n));return n.stdout.trim()}s(d,"runGit");async function E(t){const e=await d(t,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.");return q(I(t,e))}s(E,"commonGitDir");async function J(t,e){const a=`refs/heads/${e}`,r=await i(["show-ref","--verify","--quiet",a],t);if(r.status===1&&r.executionFailed!==!0)throw new l("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){const n=r.processError===void 0?"":`
2
+ process error: ${r.processError}`;throw new l("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}
3
+ stderr: ${r.stderr.trim()||"<empty>"}${n}`)}return d(t,["rev-parse","--verify",a],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}s(J,"resolveLandableBase");async function U(t){for(const e of["rebase-merge","rebase-apply"]){const a=await d(t,["rev-parse","--git-path",e],"git_path_failed","Inspect the worktree manually, then retry.");if(b(a))return!0}return!1}s(U,"rebaseInProgress");async function M(t,e,a){const r=await i(["worktree","list","--porcelain"],t);if(r.status!==0)return!1;let n=null;for(const c of r.stdout.split(`
4
+ `))if(c.startsWith("worktree "))n=c.slice(9).trim();else if(n!==null&&C(n,e)&&c===`branch refs/heads/${a}`)return!0;return!1}s(M,"registeredWorktree");function v(t){return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${t.path} remains intact. After its node exits, run \`git -C ${D(t.repo_root)} worktree remove ${D(t.path)}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${t.branch} remains checked out at ${t.path}; delete it only after that checkout is removed and its landed commit is still contained in ${t.base_ref}.`}}s(v,"deferredCleanupResult");async function O(t,e){const a=await i(["rev-parse","--verify","--quiet","refs/stash"],t);a.status===0&&a.stdout.trim()===e&&await i(["stash","drop"],t)}s(O,"dropStashIfStillTip");async function V(t,e,a,r){const n=await i(["status","--porcelain"],t);if(n.status!==0)return{ok:!1,detail:u(n)};const c=await i(["diff","--name-only",a,r],t);if(c.status!==0)return{ok:!1,detail:u(c)};const y=c.stdout.split(`
5
+ `).map(_=>_.trim()).filter(_=>_!==""),f=j(N(n.stdout),y);if(f.kind==="refuse")return{ok:!1,detail:`untracked files in ${t} would be overwritten by the incoming commits: ${f.collisions.join(", ")}`};const p=s(async()=>{const _=await i(["merge","--ff-only",r],t);return _.status===0?{ok:!0}:{ok:!1,detail:u(_)}},"merge");if(f.kind==="direct")return p();const w=await i(["rev-parse","--verify","--quiet","refs/stash"],t),A=w.status===0?w.stdout.trim():null,m=await i(["stash","push","--message",`crtr landing ${e}`],t);if(m.status!==0)return{ok:!1,detail:u(m)};const k=await i(["rev-parse","--verify","--quiet","refs/stash"],t),o=k.status===0?k.stdout.trim():null;if(o===null||o===A)return p();const h=`local changes from ${t} are retained in stash ${o}; recover them with \`git -C ${D(t)} stash apply ${o}\` and resolve any conflict.`,g=await p();return g.ok?(await i(["stash","apply",o],t)).status===0?(await O(t,o),{ok:!0}):(await i(["reset","--hard",r],t),{ok:!0,stash:`the shared base checkout was reset to landed commit ${r} because local changes conflicted with it. ${h}`}):(await i(["stash","apply",o],t)).status===0?(await O(t,o),g):{ok:!1,detail:`${g.detail}
6
+ ${h}`}}s(V,"landIntoBaseCheckout");async function x(t){const e=await $(t);if(e===null)throw new l("unknown_node",`unknown node: ${t}`,"Run this from a live node, or pass a real node id once that command supports it.");const a=e?.managed_worktree?.state==="open"?e.managed_worktree:null;if(a===null)throw new l("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to close for this node.");return X(t,a,await R(t,a))}s(x,"closeLocked");async function X(t,e,a){if(a.kind==="blocked"){const r=(await $(t))?.managed_worktree;throw r!=null&&r.state==="open"&&await F(t,{at:new Date().toISOString(),blocked:a.blocked}),new l("land_base_failed",a.blocked,a.next,a.detail)}return a.disposal!==void 0&&await B(t,a.disposal),await Q(t,e,"pending"),a.result}s(X,"persistCloseOutcome");async function R(t,e){if(!b(e.path))throw new l("worktree_missing",`managed worktree path is missing: ${e.path}`,z(e));if(await U(e.path))throw new l("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(await d(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new l("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${e.path}, then rerun \`crtr node worktree close\`.`);const r=await d(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),n=await d(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(r!==e.branch){if((await i(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path)).status===0||r==="HEAD"||!await M(e.repo_root,e.path,r))throw new l("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${r==="HEAD"?"detached HEAD":r})`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);if(await S(e.path,e,n)===null)throw new l("branch_moved_unlanded",`managed worktree's recorded branch ${e.branch} no longer exists; its checkout is now on ${r} at ${n}, which carries content local base branch '${e.base_ref}' does not yet contain`,`Land or push ${r} through its own workflow before closing.`);const h=await E(e.path);if(!await M(e.repo_root,e.path,r)||await d(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==r||await d(e.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==n)throw new l("wrong_branch",`managed worktree at ${e.path} changed while closing`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);return{kind:"closed",disposal:{observed_branch:r,observed_sha:n,common_dir:h,authorized:new Date().toISOString()},result:{node_id:t,branch:r,worktree_path:e.path,landed_sha:n,...v(e),branch_delete_error:`${r} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}}if(await S(e.path,e,n)!==null)return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:n,...v(e)}};let c;try{c=await J(e.path,e.base_ref)}catch(o){if(!(o instanceof l)||o.code!=="missing_base_branch"||n!==e.base_sha)throw o;return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:e.base_sha,...v(e)}}}const y=await i(["rebase",c],e.path);if(y.status!==0)throw new l("rebase_failed",`rebase onto local base branch '${e.base_ref}' did not complete`,`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`,u(y));const f=await d(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),p=s((o,h,g)=>({kind:"blocked",blocked:o,next:h,detail:g}),"blocked"),w=await i(["merge-base","--is-ancestor",c,f],e.path);if(w.status!==0)return p(`rebased worktree is not a fast-forward of local base branch '${e.base_ref}'`,"Ask the user how to land this managed worktree.",u(w));const A=await d(e.path,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry."),m=K(A,e.base_ref);let k;if(m!==null){const o=await i(["rev-parse","HEAD"],m);if(o.status!==0||o.stdout.trim()!==c)return p(`local base branch '${e.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${m}, then rerun \`crtr node worktree close\`.`,o.status!==0?u(o):`expected ${c}, found ${o.stdout.trim()}`);const h=await V(m,e.branch,c,f);if(!h.ok)return p(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,`Local base branch '${e.base_ref}' is checked out at ${m} in a state that blocks a fast-forward.`,h.detail);k=h.stash}else{const o=await i(["update-ref",`refs/heads/${e.base_ref}`,f,c],e.path);if(o.status!==0)return p(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,"Ask the user how to land this managed worktree.",u(o))}return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:f,...v(e),...k===void 0?{}:{base_checkout_stash:k}}}}s(R,"closeOutcome");async function he(t){const e=(await $(t))?.managed_worktree;if(e==null||e.state!=="open")return x(t);if(!b(e.path)){const c=await G(t);if(c!==null)return Y(t,c)}const a=(await $(t))?.managed_worktree;if(a==null||a.state!=="open")return x(t);const r=b(a.path)?a.path:a.repo_root,n=await E(r);return H(L(n),()=>x(t),{timeoutMs:Math.min(W,25e3),timeoutError:s(()=>new l("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")})}s(he,"closeManagedWorktreeAsync");async function de(t,e){if(!b(e.path)){const r=await T(t,e);if(r!==null)return{kind:"concluded",conclusion:r}}const a=await E(b(e.path)?e.path:e.repo_root);return H(L(a),()=>R(t,e),{timeoutMs:Math.min(W,25e3),timeoutError:s(()=>new l("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${a}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}s(de,"closeManagedWorktreeOnHost");function Y(t,e){return{node_id:t,branch:e.dropped.branch,worktree_path:e.dropped.worktree_path,landed_sha:e.landedSha,worktree_removed:!0,branch_deleted:e.dropped.branch_deleted,...e.dropped.branch_delete_error===void 0?{}:{branch_delete_error:e.dropped.branch_delete_error}}}s(Y,"concludedCloseResult");export{he as closeManagedWorktreeAsync,de as closeManagedWorktreeOnHost,Y as concludedCloseResult,X as persistCloseOutcome};
@@ -0,0 +1,27 @@
1
+ import { type ManagedWorktree } from './canvas/index.js';
2
+ import type { MachineOp, MachineOpTable } from './runtime/runner/machine/ops.js';
3
+ import { type AbandonManagedWorktreeResult, type AutoDroppedWorktree, type CloseManagedWorktreeResult } from './worktree.js';
4
+ type WorktreeOp = Extract<MachineOp, `worktree.${string}`>;
5
+ /** The handlers a machine-role crtrd registers on its link for the `worktree.*` ops. Each reads no database. */
6
+ export declare const machineWorktreeHandlers: {
7
+ [O in WorktreeOp]: (args: MachineOpTable[O]['args']) => Promise<MachineOpTable[O]['result']>;
8
+ };
9
+ /** The machine environment that holds a node's checkouts: on a cloud role, the one its profile points at; else null (Git runs here). */
10
+ export declare function worktreeMachineOf(profileId: string | null | undefined): Promise<string | null>;
11
+ export declare function createManagedWorktreeOnMachine(environmentId: string, cwd: string, nodeId: string, baseRef?: string): Promise<ManagedWorktree>;
12
+ export declare function rollbackManagedWorktreeOnMachine(environmentId: string, worktree: ManagedWorktree): Promise<void>;
13
+ export declare function closeManagedWorktreeOnMachine(environmentId: string, nodeId: string): Promise<CloseManagedWorktreeResult>;
14
+ /** The running check stays here, on the node's row: the broker's pid is a process on the Mac, not on this host. */
15
+ export declare function abandonManagedWorktreeOnMachine(environmentId: string, nodeId: string, by: string): Promise<AbandonManagedWorktreeResult>;
16
+ /** The push-final guard for a node on a machine: `dropped` (record closed), `pushed` (finish, checkout kept), or `open` (refuse). */
17
+ export declare function finalizeManagedWorktreeOnMachine(environmentId: string, nodeId: string): Promise<{
18
+ kind: 'dropped';
19
+ dropped: AutoDroppedWorktree;
20
+ } | {
21
+ kind: 'pushed';
22
+ } | {
23
+ kind: 'open';
24
+ missing: boolean;
25
+ worktree: ManagedWorktree;
26
+ }>;
27
+ export {};
@@ -0,0 +1 @@
1
+ var k=Object.defineProperty;var o=(e,r)=>k(e,"name",{value:r,configurable:!0});import{abandonWorktreeAndRepoint as f,getNode as w}from"./canvas/index.js";import{isCloudRole as p}from"./canvas/person-state.js";import{callMachine as m}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as h}from"./runtime/runner/machine/environment.js";import{closeManagedWorktreeOnHost as M,concludedCloseResult as g,persistCloseOutcome as W}from"./worktree-close.js";import{abandonManagedWorktreeOnHost as b,createManagedWorktreeAsync as y,finalizeManagedWorktreeOnHost as O,rollbackManagedWorktreeAsync as x}from"./worktree-mutation-async.js";import{persistClosedWorktreeState as d,WorktreeError as a}from"./worktree.js";async function i(e){try{return{value:await e()}}catch(r){if(!(r instanceof a))throw r;return{refused:{code:r.code,message:r.message,next:r.next,...r.detail===void 0?{}:{detail:r.detail}}}}}o(i,"answer");const E={"worktree.create":o(e=>i(()=>y(e.cwd,e.nodeId,e.baseRef)),"worktree.create"),"worktree.rollback":o(e=>i(async()=>(await x(e.worktree),null)),"worktree.rollback"),"worktree.close":o(e=>i(()=>M(e.nodeId,e.worktree)),"worktree.close"),"worktree.abandon":o(e=>i(()=>b(e.nodeId,e.worktree,e.by)),"worktree.abandon"),"worktree.finalize":o(e=>i(()=>O(e.nodeId,e.worktree)),"worktree.finalize")};async function N(e){return e==null||!p()?null:h(e)}o(N,"worktreeMachineOf");async function c(e,r,t){const n=await m(e,r,t);if("refused"in n)throw new a(n.refused.code,n.refused.message,n.refused.next,n.refused.detail);return n.value}o(c,"callWorktree");function q(e,r,t,n){return c(e,"worktree.create",{cwd:r,nodeId:t,...n===void 0?{}:{baseRef:n}})}o(q,"createManagedWorktreeOnMachine");async function F(e,r){await c(e,"worktree.rollback",{worktree:r})}o(F,"rollbackManagedWorktreeOnMachine");async function l(e,r){const t=await w(e);if(t===null)throw new a("unknown_node",`unknown node: ${e}`,"Run this from a live node, or pass a real node id once that command supports it.");const n=t.managed_worktree;if(n==null||n.state!=="open")throw new a("no_managed_worktree",`node ${e} has no open managed worktree`,`Nothing to ${r} for this node.`);return n}o(l,"openWorktree");async function P(e,r){const t=await l(r,"close"),n=await c(e,"worktree.close",{nodeId:r,worktree:t});return n.kind==="concluded"?(await d(r,t,"complete"),g(r,n.conclusion)):W(r,t,n)}o(P,"closeManagedWorktreeOnMachine");async function S(e,r,t){const n=await l(r,"abandon"),u=(await w(r))?.status;if(u==="active"||u==="idle")throw new a("node_running",`node ${r} 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`.");const s=await c(e,"worktree.abandon",{nodeId:r,worktree:n,by:t});return s.persist.kind==="closed"?await d(r,n,"complete"):await f(r,{cwd:n.repo_root,abandoned:s.persist.abandoned}),s.result}o(S,"abandonManagedWorktreeOnMachine");async function j(e,r){const t=await l(r,"close"),n=await c(e,"worktree.finalize",{nodeId:r,worktree:t});return n.kind==="dropped"?(await d(r,t,n.cleanup),{kind:"dropped",dropped:n.dropped}):n.kind==="open"?{...n,worktree:t}:n}o(j,"finalizeManagedWorktreeOnMachine");export{S as abandonManagedWorktreeOnMachine,P as closeManagedWorktreeOnMachine,q as createManagedWorktreeOnMachine,j as finalizeManagedWorktreeOnMachine,E as machineWorktreeHandlers,F as rollbackManagedWorktreeOnMachine,N as worktreeMachineOf};
@@ -19,5 +19,36 @@ export interface AbsentWorktreeConclusion {
19
19
  /** Conclude an absent checkout only from the same branch-delivery proof used by
20
20
  * push-final and explicit close. */
21
21
  export declare function concludeAbsentManagedWorktreeAsync(nodeId: string): Promise<AbsentWorktreeConclusion | null>;
22
+ /** {@link concludeAbsentManagedWorktreeAsync} on the computer that holds the checkout (an imported Mac), with no database: the
23
+ * control plane sent the recorded worktree and persists cleanup `complete` for a non-null result. */
24
+ export declare function concludeAbsentManagedWorktreeOnHost(nodeId: string, wt: ManagedWorktree): Promise<AbsentWorktreeConclusion | null>;
22
25
  export declare function autoDropCleanManagedWorktreeAsync(nodeId: string): Promise<AutoDroppedWorktree | null>;
26
+ /** What `push final` may do with an open managed worktree, decided on the computer that holds it: `dropped` closes the record with
27
+ * `cleanup`, `pushed` lets the node finish with its checkout kept, `open` refuses (`missing`: the checkout path is gone). */
28
+ export type FinalizeWorktreeOutcome = {
29
+ kind: 'dropped';
30
+ dropped: AutoDroppedWorktree;
31
+ cleanup: 'pending' | 'complete';
32
+ } | {
33
+ kind: 'pushed';
34
+ } | {
35
+ kind: 'open';
36
+ missing: boolean;
37
+ };
38
+ /** The push-final guard's Git work on the computer that holds the checkout (an imported Mac), with no database. */
39
+ export declare function finalizeManagedWorktreeOnHost(nodeId: string, wt: ManagedWorktree): Promise<FinalizeWorktreeOutcome>;
40
+ /** What an abandon did to the checkout and how its record is persisted: `closed` (cleanup complete) when the branch was deleted,
41
+ * else `abandoned` with the retained tip. */
42
+ export interface AbandonOutcome {
43
+ result: AbandonManagedWorktreeResult;
44
+ persist: {
45
+ kind: 'closed';
46
+ } | {
47
+ kind: 'abandoned';
48
+ abandoned: NonNullable<ManagedWorktree['abandoned']>;
49
+ };
50
+ }
23
51
  export declare function abandonManagedWorktreeAsync(nodeId: string, by: string): Promise<AbandonManagedWorktreeResult>;
52
+ /** {@link abandonManagedWorktreeAsync}'s Git work on the computer that holds the checkout (an imported Mac), with no database: the
53
+ * control plane checked the node is stopped, sent the recorded worktree, and persists the returned outcome. */
54
+ export declare function abandonManagedWorktreeOnHost(nodeId: string, wt: ManagedWorktree, by: string): Promise<AbandonOutcome>;
@@ -1,10 +1,10 @@
1
- var O=Object.defineProperty;var o=(e,a)=>O(e,"name",{value:a,configurable:!0});import{existsSync as p,mkdirSync as B,readFileSync as q,realpathSync as I,rmSync as N,writeFileSync as j}from"node:fs";import{basename as G,dirname as K,isAbsolute as z,join as x,relative as J,resolve as Q,sep as E}from"node:path";import{abandonWorktreeAndRepoint as U,getNode as m,readWorktree as V}from"./canvas/index.js";import{isPidAlive as X}from"./canvas/pid.js";import{InputError as Y}from"./io.js";import{CONFIG_FILE as Z,CRTR_DIR_NAME as S,STATE_FILE as ee}from"../types.js";import{withExclusiveDirectoryLockAsync as W}from"./exclusive-lock.js";import{gitAsync as i}from"./git.js";import{WORKTREE_LOCK_WAIT_MS as te,canonicalPath as D,checkoutPathForBranchInList as re,isManagedWorktreeBase as ae,managedWorktreesRoot as ne,managedWorktreePath as oe,persistClosedWorktreeState as k,worktreeLockPathForCommonDir as M,WorktreeError as c}from"./worktree.js";import{proveBranchContained as ie}from"./worktree-containment.js";import{refDeleteTransactionStdin as se}from"./worktree-landing.js";import{deleteTrashAsync as ce,removeWorktreeCheckoutAsync as he}from"./worktree-remove.js";const C=o(()=>Math.min(te,25e3),"lockWaitMs");function v(e){return(e.stderr.trim()||e.stdout.trim()).trim()}o(v,"detailOf");async function h(e,a,r,n){const t=await i(a,e);if(t.status!==0)throw new c(r,`git ${a.join(" ")} failed`,n,v(t));return t.stdout.trim()}o(h,"runGit");async function L(e){return I(Q(e,await h(e,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.")))}o(L,"commonGitDir");async function _(e,a){const r=await L(e);return W(M(r),a,{timeoutMs:C(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting for the managed-worktree lock in ${r}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(_,"withRepositoryLock");function ue(e,a){const r=D(ne()),n=J(r,D(e));if(n===""||n===".."||n.startsWith(`..${E}`)||z(n))return null;const t=n.split(E)[0];return t===a?null:x(r,t)}o(ue,"foreignManagedCheckout");async function Me(e,a,r){const n=ue(e,a);if(n===null)return r();const t=await V(G(n));return t===null?r():_(t.repo_root,async()=>{if(!p(e))throw new Y({error:"cwd_missing",message:`cwd is not an existing directory: ${e}`,received:e,field:"cwd",next:"Pass an existing directory; the managed checkout it was in has been cleaned up."});return r()})}o(Me,"admitIntoManagedCheckout");async function $(e,a){const r=`refs/heads/${a}`,n=await i(["show-ref","--verify","--quiet",r],e);if(n.status===1&&n.executionFailed!==!0)throw new c("missing_base_branch",`managed worktree base '${a}' 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(n.status!==0)throw new c("base_branch_inspection_failed",`could not inspect local base branch '${a}' (git show-ref exited with status ${n.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${n.status}
2
- stderr: ${n.stderr.trim()||"<empty>"}`);return h(e,["rev-parse","--verify",r],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o($,"resolveLandableBase");function le(e,a){try{const r=x(a,"info","exclude");B(K(r),{recursive:!0});let n="";try{n=q(r,"utf8")}catch{}const t=[`/${S}/${Z}`,`/${S}/${ee}`];if(t.every(s=>n.split(`
3
- `).map(l=>l.trim()).includes(s)))return;j(r,`${n}${n!==""&&!n.endsWith(`
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(`
4
4
  `)?`
5
5
  `:""}# crtr: exclude crtr's own untracked project-scope bookkeeping (auto-added at managed-worktree creation)
6
- ${t.filter(s=>!n.split(`
7
- `).map(l=>l.trim()).includes(s)).join(`
6
+ ${n.filter(i=>!r.split(`
7
+ `).map(u=>u.trim()).includes(i)).join(`
8
8
  `)}
9
- `)}catch{}}o(le,"seedExclude");async function Ce(e){await _(e.repo_root,async()=>{const a=await i(["rev-parse","--verify",`refs/heads/${e.branch}`],e.repo_root);if(a.status!==0||a.stdout.trim()!==e.base_sha)return;const r=await i(["worktree","list","--porcelain"],e.repo_root);if(r.status===0){if(r.stdout.split(`
10
- `).some(n=>n.trim()===`branch refs/heads/${e.branch}`)){if((await i(["worktree","remove","--force",e.path],e.repo_root)).status!==0)return}else if(p(e.path))try{N(e.path,{recursive:!0,force:!0})}catch{return}await i(["update-ref","-d",`refs/heads/${e.branch}`,e.base_sha],e.repo_root)}})}o(Ce,"rollbackManagedWorktreeAsync");async function Le(e,a,r="main"){const n=await h(e,["rev-parse","--show-toplevel"],"not_git_repo","Pass --cwd <real repo> pointing inside a git repository.");if(ae(n))throw new c("managed_worktree_base",`cwd ${n} 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 t=await L(n);return W(M(t),async()=>{const s=await $(n,r),l=oe(a),u=`crtr/${a}`;if(p(l))throw new c("worktree_path_exists",`managed worktree path already exists: ${l}`,"Remove the stale path or choose a fresh node id.");if((await i(["show-ref","--verify","--quiet",`refs/heads/${u}`],n)).status===0)throw new c("worktree_branch_exists",`managed worktree branch already exists: ${u}`,"Remove the stale branch or choose a fresh node id.");const b={state:"open",path:l,branch:u,repo_root:n,base_ref:r,base_sha:s,created:new Date().toISOString()};await h(n,["branch",u,s],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");const f=await i(["worktree","add",l,u],n);if(f.status!==0)throw await i(["update-ref","-d",`refs/heads/${u}`,s],n),new c("worktree_add_failed","git worktree add failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.",v(f));return le(n,t),b},{timeoutMs:C(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${t}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(Le,"createManagedWorktreeAsync");async function P(e){if(e.state!=="open"||!p(e.path))return null;const a=await i(["rev-parse","--abbrev-ref","HEAD"],e.path),r=await i(["status","--porcelain"],e.path),n=await i(["rev-parse","HEAD"],e.path);if(a.status!==0||a.stdout.trim()!==e.branch||r.status!==0||r.stdout.trim()!==""||n.status!==0)return null;const t=await i(["rev-parse","--git-path","rebase-merge"],e.path);return t.status!==0||p(t.stdout.trim())?null:n.stdout.trim()}o(P,"cleanTip");async function F(e,a){try{const r=await $(e.path,e.base_ref);return(await i(["merge-base","--is-ancestor",a,r],e.path)).status===0}catch(r){if(r instanceof c&&r.code==="missing_base_branch")return a===e.base_sha;throw r}}o(F,"containedInLocalBase");function de(e){return{node_id:"",branch:e.branch,worktree_path:e.path,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${e.path} remains intact.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${e.branch} remains checked out at ${e.path}.`}}o(de,"deferred");async function R(e){if(e.state!=="open"||p(e.path))return null;const a=`refs/heads/${e.branch}`,r=await i(["show-ref","--verify","--quiet",a],e.repo_root);if(r.status===1&&r.executionFailed!==!0)return{branchSha:null};if(r.status!==0)return null;const n=await i(["rev-parse","--verify",a],e.repo_root);if(n.status!==0)return null;const t=n.stdout.trim(),s=await i(["worktree","list","--porcelain"],e.repo_root);if(s.status!==0||re(s.stdout,e.branch)!==null)return null;const l=await ie(e.repo_root,e,t);return l===null?null:{branchSha:t,containment:l}}o(R,"proveAbsentPathManagedWorktree");async function pe(e,a,r){return p(a.path)?null:r.branchSha===null?(await k(e,a,"complete"),{node_id:e,branch:a.branch,worktree_path:a.path,worktree_removed:!0,branch_deleted:!0}):r.containment===void 0?null:(await k(e,a,"complete"),{node_id:e,branch:a.branch,worktree_path:a.path,worktree_removed:!0,branch_deleted:!1,branch_delete_error:`local branch ${a.branch} is delivered but retained because its checkout status can change outside crtr's repository lock.`})}o(pe,"autoDropAbsentPathManagedWorktreeLocked");async function fe(e){const a=(await m(e))?.managed_worktree;return a==null||a.state!=="open"||p(a.path)||await R(a)===null?null:_(a.repo_root,async()=>{const r=(await m(e))?.managed_worktree;if(r==null||r.state!=="open")return null;const n=await R(r);if(n===null)return null;const t=await pe(e,r,n);return t===null?null:{dropped:t,landedSha:n.branchSha??r.base_sha}})}o(fe,"concludeAbsentManagedWorktreeAsync");async function Pe(e){const a=(await m(e))?.managed_worktree;if(a==null||a.state!=="open")return null;if(!p(a.path))return(await fe(e))?.dropped??null;const r=await P(a);return r===null||!await F(a,r)?null:_(a.path,async()=>{const n=(await m(e))?.managed_worktree;if(n==null||n.state!=="open")return null;const t=await P(n);return t===null||t!==r||!await F(n,t)?null:(await k(e,n,"pending"),{...de(n),node_id:e})})}o(Pe,"autoDropCleanManagedWorktreeAsync");async function T(e){for(const a of["rebase-merge","rebase-apply"]){const r=await i(["rev-parse","--git-path",a],e);if(r.status!==0||p(r.stdout.trim()))return!0}return!1}o(T,"rebaseInProgress");async function y(e,a,r,n,t,s=a.branch){await U(e,{cwd:a.repo_root,abandoned:{branch:s,tip_sha:r,at:n,by:t}})}o(y,"persistAbandoned");async function Fe(e,a){const r=(await m(e))?.managed_worktree;if(r==null||r.state!=="open")throw new c("no_managed_worktree",`node ${e} has no open managed worktree`,"Nothing to abandon for this node.");const n=[];try{return await _(r.path,()=>we(e,a,n))}finally{await ce(r.path,n[0])}}o(Fe,"abandonManagedWorktreeAsync");async function g(e,a){const{result:r,trash:n}=await he(e.repo_root,e.path);if(n!==void 0&&a.push(n),r.status!==0)throw new c("worktree_remove_failed",`git worktree remove ${e.path} failed`,"Inspect the worktree manually, then retry.",v(r))}o(g,"removeCheckout");async function we(e,a,r){const n=await m(e),t=n?.managed_worktree;if(n===null||t===void 0||t===null||t.state!=="open")throw new c("no_managed_worktree",`node ${e} has no open managed worktree`,"Nothing to abandon for this node.");if(n.status==="active"||n.status==="idle"||X(n.pi_pid))throw new c("node_running",`node ${e} 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`.");if(!p(t.path))throw new c("worktree_missing",`managed worktree path is missing: ${t.path}`,"Inspect the branch and worktree registration, then retry.");const s=await h(t.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),l=await i(["show-ref","--verify","--quiet",`refs/heads/${t.branch}`],t.path);if(s!==t.branch){if(l.status===0||s==="HEAD")throw new c("wrong_branch",`managed worktree is not on its recorded branch (expected ${t.branch}, found ${s==="HEAD"?"detached HEAD":s})`,`Inspect ${t.path}, then rerun \`crtr node worktree abandon\`.`);if(await T(t.path)||await h(t.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 ${t.path}, then rerun \`crtr node worktree abandon\`.`);const d=await h(t.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the worktree manually, then retry.");await g(t,r);const w=new Date().toISOString();return await y(e,t,d,w,a,s),{node_id:e,branch:s,tip_sha:d,worktree_path:t.path,branch_deleted:!1}}const u=await h(t.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");let b=null;try{const d=await $(t.path,t.base_ref);(await i(["merge-base","--is-ancestor",u,d],t.path)).status===0&&(b=d)}catch(d){if(!(d instanceof c)||d.code!=="missing_base_branch")throw d}const f=new Date().toISOString(),H=await h(t.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.");if(b!==null&&u===t.base_sha){const d=await h(t.repo_root,["rev-parse",`${u}^{tree}`],"abandon_tree_failed","Inspect the branch manually, then retry."),w=await h(t.repo_root,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit-tree",d,"-p",u,"-m","crtr-abandon","-m",`Crtr-Abandon: ${e} ${f}`],"abandon_commit_failed","Inspect the branch manually, then retry.");return await h(t.repo_root,["update-ref",`refs/heads/${t.branch}`,w,u],"abandon_marker_failed","The branch changed while abandon was starting; inspect the worktree, then retry."),await g(t,r),(await i(["update-ref","--stdin"],t.repo_root,se(t.branch,w,`refs/heads/${t.base_ref}`,b))).status===0?(await k(e,t,"complete"),{node_id:e,branch:t.branch,tip_sha:w,worktree_path:t.path,branch_deleted:!0}):(await y(e,t,w,f,a),{node_id:e,branch:t.branch,tip_sha:w,worktree_path:t.path,branch_deleted:!1})}if(!await T(t.path)&&H==="")return await g(t,r),await y(e,t,u,f,a),{node_id:e,branch:t.branch,tip_sha:u,worktree_path:t.path,branch_deleted:!1};await h(t.path,["add","--all"],"abandon_stage_failed","Inspect the worktree manually, then retry."),await h(t.path,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit","--allow-empty","-m","crtr-abandon","-m",`Crtr-Abandon: ${e} ${f}`],"abandon_commit_failed","Inspect the worktree manually, then retry.");const A=await h(t.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");return await g(t,r),await y(e,t,A,f,a),{node_id:e,branch:t.branch,tip_sha:A,worktree_path:t.path,branch_deleted:!1}}o(we,"abandonLocked");export{Fe as abandonManagedWorktreeAsync,Me as admitIntoManagedCheckout,Pe as autoDropCleanManagedWorktreeAsync,fe as concludeAbsentManagedWorktreeAsync,Le as createManagedWorktreeAsync,Ce as rollbackManagedWorktreeAsync};
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};
@@ -1 +1 @@
1
- var P=Object.defineProperty;var o=(e,t)=>P(e,"name",{value:t,configurable:!0});import{statSync as N}from"node:fs";import{isAbsolute as T}from"node:path";import{ApiError as s}from"../../../api/index.js";import{readDaemonActionById as C}from"../../../core/canvas/daemon-actions.js";import{isSafeNodeId as I}from"../../../core/canvas/paths.js";import{getNode as b}from"../../../core/canvas/canvas.js";import{assertScope as $}from"../../../core/scopes.js";import{resolvePageComponents as g}from"../../../core/config.js";import{resolveHumanAction as D}from"../../../core/human-actions.js";import{HUMAN_ACTION_NAME_PATTERN as x}from"../../../core/human/action-binding.js";import{createPageRequest as J,getRequest as F}from"../../../core/human/requests.js";import{preparePageSource as M}from"../../../core/human/page-authoring.js";import{PageCompilerError as B}from"../../../core/human/page-errors.js";import{publishPage as G,validatePageTicketResponses as H}from"../../../core/human/tickets.js";import{cancelHumanTicket as L,resolvePageTicket as U}from"../../human/finish.js";import{inboxPageProjection as K}from"./inbox-page.js";import{actsAsPerson as X,appOf as z}from"../router.js";const V=1e3,q=200,m={placement:"inline",inbox:!0,reply:!1},v=["sessionName","askedBy","emittedAt","profileName","nodeId"];function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(c,"isPlainObject");function l(e,t,n){for(const r of Object.keys(e))if(!t.includes(r))throw new s(400,"invalid_request",`unexpected field in ${n}: ${r}`)}o(l,"requireNoExtraKeys");function i(e){return new s(400,"invalid_request",e)}o(i,"invalid");function w(e){if(!c(e))throw i("`page` must be an object");if(l(e,["dialect","source"],"`page`"),e.dialect!=="jsx"&&e.dialect!=="html")throw i('`page.dialect` must be "jsx" or "html"');if(typeof e.source!="string"||e.source.trim()==="")throw i("`page.source` must be the authored page text");return{dialect:e.dialect,source:e.source}}o(w,"validatePage");function A(e,t){const n=e??t;if(n!=="inline"&&n!=="panel")throw i('`delivery.placement` must be "inline" or "panel"');return n}o(A,"validatePlacement");function Y(e,t){if(e===void 0)return m;if(!c(e))throw i("`delivery` must be an object");l(e,["placement","inbox","reply"],"`delivery`");const n=e.inbox??m.inbox,r=e.reply??m.reply;if(typeof n!="boolean")throw i("`delivery.inbox` must be boolean");if(typeof r!="boolean")throw i("`delivery.reply` must be boolean");if(r&&t===null)throw i("`delivery.reply` requires `requester_node_id`");return{placement:A(e.placement,m.placement),inbox:n,reply:r}}o(Y,"validateCreateDelivery");function Q(e,t){if(e===void 0)return t;if(!c(e))throw i("`delivery` must be an object");return l(e,["placement"],"`delivery`"),{...t,placement:A(e.placement,t.placement)}}o(Q,"validateReplaceDelivery");function W(e){if(e===void 0)return;if(!c(e))throw i("`source` must be an object");l(e,v,"`source`");const t={};for(const n of v){const r=e[n];if(r!==void 0){if(typeof r!="string"||r==="")throw i(`\`source.${n}\` must be a nonempty string`);t[n]=r}}return t}o(W,"validateSource");function Z(e){if(typeof e!="string"||e==="")throw i("`creator_cwd` is required");if(!T(e))throw i("`creator_cwd` must be an absolute path");try{if(!N(e).isDirectory())throw i(`\`creator_cwd\` is not a directory: ${e}`)}catch(t){throw t instanceof s?t:i(`\`creator_cwd\` does not exist: ${e}`)}return e}o(Z,"validateCreatorCwd");function ee(e){if(e!==void 0){if(!c(e))throw i("`action` must be an object");if(l(e,["name","payload"],"`action`"),typeof e.name!="string"||!x.test(e.name))throw i("`action.name` must be a declared action name");return{name:e.name,payload:e.payload??null}}}o(ee,"validateActionSelection");function te(e){if(e==null)return null;if(typeof e!="string"||!I(e))throw i("`requester_node_id` must be a safe node id or null");return e}o(te,"validateRequesterNodeId");function ne(e){if(!c(e))throw i("request body is required");l(e,["page","delivery","source","requester_node_id","creator_cwd","action"],"the request body");const t=W(e.source),n=te(e.requester_node_id),r=ee(e.action);return{page:w(e.page),delivery:Y(e.delivery,n),...t===void 0?{}:{source:t},requesterNodeId:n,creatorCwd:Z(e.creator_cwd),...r===void 0?{}:{action:r}}}o(ne,"validateCreateRequest");function re(e,t){if(!c(e))throw i("request body is required");return l(e,["page","delivery"],"the request body"),{page:w(e.page),delivery:Q(e.delivery,t)}}o(re,"validateReplaceRequest");function _(e,t,n){if(e!==void 0){if(typeof e!="string"||e.trim()===""||e.length>n)throw i(`\`${t}\` must be nonempty after trim and at most ${n} characters`);return e}}o(_,"optionalBoundedString");function oe(e){if(!c(e))throw i("request body is required");if(l(e,["responses","actor"],"the request body"),!c(e.responses))throw i("`responses` must be an object");const t=_(e.actor,"actor",q);return{responses:e.responses,...t===void 0?{}:{actor:t}}}o(oe,"validateRespondRequest");function ie(e){if(e===void 0)return{};if(!c(e))throw i("request body must be an object");l(e,["reason","actor"],"the request body");const t=_(e.reason,"reason",V),n=_(e.actor,"actor",q);return{...t===void 0?{}:{reason:t},...n===void 0?{}:{actor:n}}}o(ie,"validateSettleRequest");function h(e){const t=e.params.request_id;if(typeof t!="string"||t==="")throw i("request id is required");return t}o(h,"requestId");async function f(e){const t=await F(e);if(t===null||t.kind!=="page")throw new s(404,"not_found","no request with that id");return t}o(f,"requirePageRequest");function S(e){try{const t=JSON.parse(e.specification_json);if(!c(t))throw new Error("not an object");return t}catch{throw new s(500,"internal","the request specification could not be read")}}o(S,"manifest");function ae(e){if(e.result_json===null)return null;try{return JSON.parse(e.result_json)}catch{throw new s(500,"internal","the request result could not be read")}}o(ae,"terminalResult");function se(e){if(e.action_json===null)return null;try{const t=JSON.parse(e.action_json);if(t.schema!=="crtr.human-action-binding/v1"||typeof t.name!="string")throw new Error("invalid action");return t}catch{throw new s(500,"internal","the request action could not be read")}}o(se,"frozenAction");function de(e){return e.state!=="settled"?"pending":e.outcome==="answered"?"answered":e.outcome==="dismissed"?"dismissed":"canceled"}o(de,"requestState");async function ce(e){if(e.action_delivery_id===null)return{state:"none",attempt:0};const t=await C(e.action_delivery_id);if(t===null)return{state:"none",attempt:0};const n=t.state==="acknowledged"?"accepted":t.state==="permanent_failed"?"permanent_failed":t.state==="handed_off"?"running":"pending",r={state:n,attempt:t.attempts};return n==="pending"&&t.nextAttemptAt!==null&&(r.next_attempt_at=new Date(t.nextAttemptAt).toISOString()),t.acknowledgedAt!==null&&(r.accepted_at=new Date(t.acknowledgedAt).toISOString()),t.failedAt!==null&&(r.permanent_failed_at=new Date(t.failedAt).toISOString()),t.lastFailure!==null&&(r.last_failure=t.lastFailure),r}o(ce,"deliveryDetail");async function y(e){const t=S(e),n=ae(e),r=de(e),a={request_id:e.request_id,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,kind:e.kind,state:r,title:e.title,source:t.source??{},emitted_at:t.source?.emittedAt??e.created_at};e.subtitle!==null&&(a.subtitle=e.subtitle),e.kind==="page"&&(a.page=await K(e)),n!==null&&(a.settled_at=e.settled_at??e.updated_at,n.kind==="page"&&r==="answered"&&(a.responses=n.responses),n.kind==="canceled"&&n.reason!==void 0&&(a.reason=n.reason),n.kind==="page"&&n.actor!==void 0&&(a.actor=n.actor),n.kind==="canceled"&&n.actor!==void 0&&(a.actor=n.actor));const u=se(e);return u!==null&&(a.action={name:u.name,payload:u.payload},a.delivery=await ce(e)),a}o(y,"requestToDTO");function k(e,t,n,r){try{return M({dialect:e,document:t,source:n,delivery:r,productKinds:g()})}catch(a){throw a instanceof B?a:i(a instanceof Error?a.message:"the page could not be prepared")}}o(k,"prepareOrReject");async function ue(e){const t=ne(e.body),n=t.requesterNodeId??t.source?.nodeId;if(n!=null){const d=await b(n);d!==null&&$(d,"crtr:act")}let r;if(t.action!==void 0){const d=D(t.action.name,t.creatorCwd);if("kind"in d){const E=d.kind==="unknown_action"?`no action named ${d.name} is declared from ${t.creatorCwd}`:`${d.name} is declared in ${d.configOrigin} but unusable: ${d.reason}`;throw new s(400,d.kind,E)}const p=n==null?null:await b(n);if(n&&!p)throw new s(404,"not_found","action requester node not found");if(p&&!X(e.principal)&&p.grantee!==z(e.principal))throw new s(403,"permission_error","action requester belongs to another app");r=JSON.stringify({schema:"crtr.human-action-binding/v1",name:t.action.name,payload:t.action.payload,creatorCwd:t.creatorCwd,configOrigin:d.configOrigin,argv:d.argv,cwd:d.cwd,app:p?.grantee??(e.principal.class==="broker"?e.principal.app:"app:terminal")})}const a=k(t.page.dialect,t.page.source,t.source,t.delivery),u=await J({prepared:a,requester_node_id:t.requesterNodeId,...r===void 0?{}:{action_json:r}});return{status:201,body:{request_id:u.request_id,request_dir:u.request_dir,state:"pending",...t.action===void 0?{}:{action:{name:t.action.name}},delivery_state:"none"}}}o(ue,"handleCreate");async function le(e){return{status:200,body:await y(await f(h(e)))}}o(le,"handleGet");async function fe(e){const t=await f(h(e));if(t.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");const n=S(t),r=re(e.body,n.delivery),a=k(r.page.dialect,r.page.source,n.source,r.delivery);try{await G(t.request_dir,a)}catch(u){throw u instanceof Error&&u.message===`page request is not open: ${t.request_id}`?new s(409,"already_settled","the request already has a terminal result"):u}return{status:200,body:await y(await f(t.request_id))}}o(fe,"handleReplace");function O(e){return e instanceof s?e:e instanceof Error&&e.message.includes("unknown page request")?new s(404,"not_found","no request with that id"):e instanceof Error&&e.message==="page_has_no_response_lifecycle"?new s(409,"not_settleable","this request carries no response lifecycle"):new s(500,"internal","the request could not be settled")}o(O,"settlementError");function R(e){if(e.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");if(!e.settleable)throw new s(409,"not_settleable","this request carries no response lifecycle")}o(R,"requireSettleable");async function pe(e){const t=await f(h(e)),n=oe(e.body);R(t);try{await H(t.request_dir,n.responses)}catch(r){throw i(r instanceof Error?r.message:"the response map is invalid")}try{await U(t.request_id,n.responses,n.actor===void 0?{}:{actor:n.actor})}catch(r){throw O(r)}return{status:200,body:await y(await f(t.request_id))}}o(pe,"handleRespond");async function j(e,t){const n=await f(h(e)),r=ie(e.body);R(n);try{await L(n.request_id,{...r,disposition:t})}catch(a){throw O(a)}return{status:200,body:await y(await f(n.request_id))}}o(j,"settle");function me(){return{status:200,body:{components:[...g()]}}}o(me,"handleComponents");const Ce=[{method:"GET",pattern:"/v1/human/components",handler:o(()=>me(),"handler")},{method:"POST",pattern:"/v1/human/requests",scope:"crtr:act",handler:ue},{method:"GET",pattern:"/v1/human/requests/:request_id",handler:le},{method:"POST",pattern:"/v1/human/requests/:request_id/replace",handler:fe},{method:"POST",pattern:"/v1/human/requests/:request_id/respond",handler:pe},{method:"POST",pattern:"/v1/human/requests/:request_id/dismiss",handler:o(e=>j(e,"dismissed"),"handler")},{method:"POST",pattern:"/v1/human/requests/:request_id/cancel",handler:o(e=>j(e,"canceled"),"handler")}];export{Ce as humanRequestRoutes};
1
+ var P=Object.defineProperty;var o=(e,t)=>P(e,"name",{value:t,configurable:!0});import{statSync as N}from"node:fs";import{isAbsolute as C}from"node:path";import{ApiError as s}from"../../../api/index.js";import{readDaemonActionById as T}from"../../../core/canvas/daemon-actions.js";import{isSafeNodeId as I}from"../../../core/canvas/paths.js";import{isCloudRole as $}from"../../../core/canvas/person-state.js";import{getNode as b}from"../../../core/canvas/canvas.js";import{assertScope as D}from"../../../core/scopes.js";import{resolvePageComponents as g}from"../../../core/config.js";import{resolveHumanAction as x}from"../../../core/human-actions.js";import{HUMAN_ACTION_NAME_PATTERN as J}from"../../../core/human/action-binding.js";import{createPageRequest as F,getRequest as M}from"../../../core/human/requests.js";import{preparePageSource as B}from"../../../core/human/page-authoring.js";import{PageCompilerError as G}from"../../../core/human/page-errors.js";import{publishPage as H,validatePageTicketResponses as L}from"../../../core/human/tickets.js";import{cancelHumanTicket as U,resolvePageTicket as K}from"../../human/finish.js";import{inboxPageProjection as X}from"./inbox-page.js";import{actsAsPerson as z,appOf as V}from"../router.js";const Y=1e3,q=200,m={placement:"inline",inbox:!0,reply:!1},v=["sessionName","askedBy","emittedAt","profileName","nodeId"];function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(c,"isPlainObject");function l(e,t,n){for(const r of Object.keys(e))if(!t.includes(r))throw new s(400,"invalid_request",`unexpected field in ${n}: ${r}`)}o(l,"requireNoExtraKeys");function i(e){return new s(400,"invalid_request",e)}o(i,"invalid");function w(e){if(!c(e))throw i("`page` must be an object");if(l(e,["dialect","source"],"`page`"),e.dialect!=="jsx"&&e.dialect!=="html")throw i('`page.dialect` must be "jsx" or "html"');if(typeof e.source!="string"||e.source.trim()==="")throw i("`page.source` must be the authored page text");return{dialect:e.dialect,source:e.source}}o(w,"validatePage");function A(e,t){const n=e??t;if(n!=="inline"&&n!=="panel")throw i('`delivery.placement` must be "inline" or "panel"');return n}o(A,"validatePlacement");function Q(e,t){if(e===void 0)return m;if(!c(e))throw i("`delivery` must be an object");l(e,["placement","inbox","reply"],"`delivery`");const n=e.inbox??m.inbox,r=e.reply??m.reply;if(typeof n!="boolean")throw i("`delivery.inbox` must be boolean");if(typeof r!="boolean")throw i("`delivery.reply` must be boolean");if(r&&t===null)throw i("`delivery.reply` requires `requester_node_id`");return{placement:A(e.placement,m.placement),inbox:n,reply:r}}o(Q,"validateCreateDelivery");function W(e,t){if(e===void 0)return t;if(!c(e))throw i("`delivery` must be an object");return l(e,["placement"],"`delivery`"),{...t,placement:A(e.placement,t.placement)}}o(W,"validateReplaceDelivery");function Z(e){if(e===void 0)return;if(!c(e))throw i("`source` must be an object");l(e,v,"`source`");const t={};for(const n of v){const r=e[n];if(r!==void 0){if(typeof r!="string"||r==="")throw i(`\`source.${n}\` must be a nonempty string`);t[n]=r}}return t}o(Z,"validateSource");function ee(e){if(typeof e!="string"||e==="")throw i("`creator_cwd` is required");if(!C(e))throw i("`creator_cwd` must be an absolute path");if($())return e;try{if(!N(e).isDirectory())throw i(`\`creator_cwd\` is not a directory: ${e}`)}catch(t){throw t instanceof s?t:i(`\`creator_cwd\` does not exist: ${e}`)}return e}o(ee,"validateCreatorCwd");function te(e){if(e!==void 0){if(!c(e))throw i("`action` must be an object");if(l(e,["name","payload"],"`action`"),typeof e.name!="string"||!J.test(e.name))throw i("`action.name` must be a declared action name");return{name:e.name,payload:e.payload??null}}}o(te,"validateActionSelection");function ne(e){if(e==null)return null;if(typeof e!="string"||!I(e))throw i("`requester_node_id` must be a safe node id or null");return e}o(ne,"validateRequesterNodeId");function re(e){if(!c(e))throw i("request body is required");l(e,["page","delivery","source","requester_node_id","creator_cwd","action"],"the request body");const t=Z(e.source),n=ne(e.requester_node_id),r=te(e.action);return{page:w(e.page),delivery:Q(e.delivery,n),...t===void 0?{}:{source:t},requesterNodeId:n,creatorCwd:ee(e.creator_cwd),...r===void 0?{}:{action:r}}}o(re,"validateCreateRequest");function oe(e,t){if(!c(e))throw i("request body is required");return l(e,["page","delivery"],"the request body"),{page:w(e.page),delivery:W(e.delivery,t)}}o(oe,"validateReplaceRequest");function _(e,t,n){if(e!==void 0){if(typeof e!="string"||e.trim()===""||e.length>n)throw i(`\`${t}\` must be nonempty after trim and at most ${n} characters`);return e}}o(_,"optionalBoundedString");function ie(e){if(!c(e))throw i("request body is required");if(l(e,["responses","actor"],"the request body"),!c(e.responses))throw i("`responses` must be an object");const t=_(e.actor,"actor",q);return{responses:e.responses,...t===void 0?{}:{actor:t}}}o(ie,"validateRespondRequest");function ae(e){if(e===void 0)return{};if(!c(e))throw i("request body must be an object");l(e,["reason","actor"],"the request body");const t=_(e.reason,"reason",Y),n=_(e.actor,"actor",q);return{...t===void 0?{}:{reason:t},...n===void 0?{}:{actor:n}}}o(ae,"validateSettleRequest");function h(e){const t=e.params.request_id;if(typeof t!="string"||t==="")throw i("request id is required");return t}o(h,"requestId");async function f(e){const t=await M(e);if(t===null||t.kind!=="page")throw new s(404,"not_found","no request with that id");return t}o(f,"requirePageRequest");function S(e){try{const t=JSON.parse(e.specification_json);if(!c(t))throw new Error("not an object");return t}catch{throw new s(500,"internal","the request specification could not be read")}}o(S,"manifest");function se(e){if(e.result_json===null)return null;try{return JSON.parse(e.result_json)}catch{throw new s(500,"internal","the request result could not be read")}}o(se,"terminalResult");function de(e){if(e.action_json===null)return null;try{const t=JSON.parse(e.action_json);if(t.schema!=="crtr.human-action-binding/v1"||typeof t.name!="string")throw new Error("invalid action");return t}catch{throw new s(500,"internal","the request action could not be read")}}o(de,"frozenAction");function ce(e){return e.state!=="settled"?"pending":e.outcome==="answered"?"answered":e.outcome==="dismissed"?"dismissed":"canceled"}o(ce,"requestState");async function ue(e){if(e.action_delivery_id===null)return{state:"none",attempt:0};const t=await T(e.action_delivery_id);if(t===null)return{state:"none",attempt:0};const n=t.state==="acknowledged"?"accepted":t.state==="permanent_failed"?"permanent_failed":t.state==="handed_off"?"running":"pending",r={state:n,attempt:t.attempts};return n==="pending"&&t.nextAttemptAt!==null&&(r.next_attempt_at=new Date(t.nextAttemptAt).toISOString()),t.acknowledgedAt!==null&&(r.accepted_at=new Date(t.acknowledgedAt).toISOString()),t.failedAt!==null&&(r.permanent_failed_at=new Date(t.failedAt).toISOString()),t.lastFailure!==null&&(r.last_failure=t.lastFailure),r}o(ue,"deliveryDetail");async function y(e){const t=S(e),n=se(e),r=ce(e),a={request_id:e.request_id,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,kind:e.kind,state:r,title:e.title,source:t.source??{},emitted_at:t.source?.emittedAt??e.created_at};e.subtitle!==null&&(a.subtitle=e.subtitle),e.kind==="page"&&(a.page=await X(e)),n!==null&&(a.settled_at=e.settled_at??e.updated_at,n.kind==="page"&&r==="answered"&&(a.responses=n.responses),n.kind==="canceled"&&n.reason!==void 0&&(a.reason=n.reason),n.kind==="page"&&n.actor!==void 0&&(a.actor=n.actor),n.kind==="canceled"&&n.actor!==void 0&&(a.actor=n.actor));const u=de(e);return u!==null&&(a.action={name:u.name,payload:u.payload},a.delivery=await ue(e)),a}o(y,"requestToDTO");function k(e,t,n,r){try{return B({dialect:e,document:t,source:n,delivery:r,productKinds:g()})}catch(a){throw a instanceof G?a:i(a instanceof Error?a.message:"the page could not be prepared")}}o(k,"prepareOrReject");async function le(e){const t=re(e.body),n=t.requesterNodeId??t.source?.nodeId;if(n!=null){const d=await b(n);d!==null&&D(d,"crtr:act")}let r;if(t.action!==void 0){const d=x(t.action.name,t.creatorCwd);if("kind"in d){const E=d.kind==="unknown_action"?`no action named ${d.name} is declared from ${t.creatorCwd}`:`${d.name} is declared in ${d.configOrigin} but unusable: ${d.reason}`;throw new s(400,d.kind,E)}const p=n==null?null:await b(n);if(n&&!p)throw new s(404,"not_found","action requester node not found");if(p&&!z(e.principal)&&p.grantee!==V(e.principal))throw new s(403,"permission_error","action requester belongs to another app");r=JSON.stringify({schema:"crtr.human-action-binding/v1",name:t.action.name,payload:t.action.payload,creatorCwd:t.creatorCwd,configOrigin:d.configOrigin,argv:d.argv,cwd:d.cwd,app:p?.grantee??(e.principal.class==="broker"?e.principal.app:"app:terminal")})}const a=k(t.page.dialect,t.page.source,t.source,t.delivery),u=await F({prepared:a,requester_node_id:t.requesterNodeId,...r===void 0?{}:{action_json:r}});return{status:201,body:{request_id:u.request_id,request_dir:u.request_dir,state:"pending",...t.action===void 0?{}:{action:{name:t.action.name}},delivery_state:"none"}}}o(le,"handleCreate");async function fe(e){return{status:200,body:await y(await f(h(e)))}}o(fe,"handleGet");async function pe(e){const t=await f(h(e));if(t.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");const n=S(t),r=oe(e.body,n.delivery),a=k(r.page.dialect,r.page.source,n.source,r.delivery);try{await H(t.request_dir,a)}catch(u){throw u instanceof Error&&u.message===`page request is not open: ${t.request_id}`?new s(409,"already_settled","the request already has a terminal result"):u}return{status:200,body:await y(await f(t.request_id))}}o(pe,"handleReplace");function O(e){return e instanceof s?e:e instanceof Error&&e.message.includes("unknown page request")?new s(404,"not_found","no request with that id"):e instanceof Error&&e.message==="page_has_no_response_lifecycle"?new s(409,"not_settleable","this request carries no response lifecycle"):new s(500,"internal","the request could not be settled")}o(O,"settlementError");function R(e){if(e.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");if(!e.settleable)throw new s(409,"not_settleable","this request carries no response lifecycle")}o(R,"requireSettleable");async function me(e){const t=await f(h(e)),n=ie(e.body);R(t);try{await L(t.request_dir,n.responses)}catch(r){throw i(r instanceof Error?r.message:"the response map is invalid")}try{await K(t.request_id,n.responses,n.actor===void 0?{}:{actor:n.actor})}catch(r){throw O(r)}return{status:200,body:await y(await f(t.request_id))}}o(me,"handleRespond");async function j(e,t){const n=await f(h(e)),r=ae(e.body);R(n);try{await U(n.request_id,{...r,disposition:t})}catch(a){throw O(a)}return{status:200,body:await y(await f(n.request_id))}}o(j,"settle");function he(){return{status:200,body:{components:[...g()]}}}o(he,"handleComponents");const $e=[{method:"GET",pattern:"/v1/human/components",handler:o(()=>he(),"handler")},{method:"POST",pattern:"/v1/human/requests",scope:"crtr:act",handler:le},{method:"GET",pattern:"/v1/human/requests/:request_id",handler:fe},{method:"POST",pattern:"/v1/human/requests/:request_id/replace",handler:pe},{method:"POST",pattern:"/v1/human/requests/:request_id/respond",handler:me},{method:"POST",pattern:"/v1/human/requests/:request_id/dismiss",handler:o(e=>j(e,"dismissed"),"handler")},{method:"POST",pattern:"/v1/human/requests/:request_id/cancel",handler:o(e=>j(e,"canceled"),"handler")}];export{$e as humanRequestRoutes};