infra-kit 0.3.13 → 0.3.15

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/LICENSE +21 -0
  2. package/dist/chunk-KATIE633.js +247 -0
  3. package/dist/chunk-KATIE633.js.map +7 -0
  4. package/dist/chunk-MKMT6KQT.js +10 -0
  5. package/dist/chunk-MKMT6KQT.js.map +7 -0
  6. package/dist/chunk-OKO3DKIM.js +7 -0
  7. package/dist/{chunk-QLAQ7F4M.js.map → chunk-OKO3DKIM.js.map} +4 -4
  8. package/dist/{chunk-RVTI3AL2.js → chunk-VDBJ73LS.js} +5 -5
  9. package/dist/chunk-VDBJ73LS.js.map +7 -0
  10. package/dist/{chunk-DPCWCXJD.js → chunk-VFU2USJG.js} +2 -2
  11. package/dist/{chunk-DPCWCXJD.js.map → chunk-VFU2USJG.js.map} +2 -2
  12. package/dist/chunk-XR6HR4LL.js +6 -0
  13. package/dist/{chunk-SSBYKOHY.js.map → chunk-XR6HR4LL.js.map} +4 -4
  14. package/dist/chunk-YDW6324A.js +2 -0
  15. package/dist/chunk-YDW6324A.js.map +7 -0
  16. package/dist/cli.js +9 -9
  17. package/dist/cli.js.map +3 -3
  18. package/dist/dev-server.js +24 -32
  19. package/dist/dev-server.js.map +4 -4
  20. package/dist/dev-wizard-run-AU7SZJV7.js +2 -0
  21. package/dist/{dev-wizard-run-XM5L23UP.js.map → dev-wizard-run-AU7SZJV7.js.map} +1 -1
  22. package/dist/mcp.js +1 -1
  23. package/dist/mcp.js.map +4 -4
  24. package/dist/persistent-ink-dev-ui-QNFTO2B2.js +2 -0
  25. package/dist/persistent-ink-dev-ui-QNFTO2B2.js.map +7 -0
  26. package/dist/update-check.js +1 -1
  27. package/dist/update-check.js.map +1 -1
  28. package/package.json +28 -28
  29. package/readme.md +1 -1
  30. package/dist/chunk-2QJAIOPI.js +0 -2
  31. package/dist/chunk-2QJAIOPI.js.map +0 -7
  32. package/dist/chunk-LMAO6FEM.js +0 -238
  33. package/dist/chunk-LMAO6FEM.js.map +0 -7
  34. package/dist/chunk-QLAQ7F4M.js +0 -7
  35. package/dist/chunk-RVTI3AL2.js.map +0 -7
  36. package/dist/chunk-SHFPI4QA.js +0 -2
  37. package/dist/chunk-SHFPI4QA.js.map +0 -7
  38. package/dist/chunk-SSBYKOHY.js +0 -4
  39. package/dist/dev-wizard-run-XM5L23UP.js +0 -2
  40. package/dist/persistent-ink-dev-ui-PLLSRSGL.js +0 -2
  41. package/dist/persistent-ink-dev-ui-PLLSRSGL.js.map +0 -7
@@ -0,0 +1,10 @@
1
+ import{a as z}from"./chunk-LKKKDB6V.js";import{J as m,V as q,ba as H,da as K,g as U,m as j}from"./chunk-XR6HR4LL.js";import{execFile as me,execFileSync as de}from"node:child_process";import x from"node:process";var fe=5e3,ge=100,V=2e3,X="/bin/ps",xe=1e3,Y=["-eo","pid=,ppid=,pgid=,lstart="],Z=8<<20,ee=e=>e.split(`
2
+ `).flatMap(r=>{let[t,o,n,...i]=r.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let a=Number(t),c=Number(o),u=Number(n);return!Number.isInteger(a)||!Number.isInteger(c)||!Number.isInteger(u)?[]:[{pid:a,ppid:c,pgid:u,lstart:i.join(" ")}]}),re=e=>{let r=new Map;for(let t of e)t.pid===t.pgid&&r.set(t.pgid,t.lstart);return r},we=(e,r,t)=>{let o=re(r);return oe(e,r,t).flatMap(n=>{let i=o.get(n);return i==null||i===""?[]:[{pgid:n,leaderStart:i}]})},te=(e,r)=>{let t=re(r);return e.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},Q=(e,r)=>te(e,r).flatMap(t=>{try{x.kill(-t,"SIGKILL")}catch{return[]}return[t]}),oe=(e,r,t)=>{let o=new Map;for(let c of r){let u=o.get(c.ppid);u?u.push(c):o.set(c.ppid,[c])}let n=new Set([e]),i=new Set([e]),a=[e];for(let c=0;c<a.length;c+=1)for(let u of o.get(a[c]??-1)??[])i.has(u.pid)||(i.add(u.pid),n.add(u.pgid),a.push(u.pid));return[...n].filter(c=>c>1&&c!==t)},L=()=>{try{return ee(de(X,[...Y],{encoding:"utf8",maxBuffer:Z}))}catch{return[]}},ye=async()=>new Promise(e=>{me(X,[...Y],{encoding:"utf8",maxBuffer:Z},(r,t)=>{e(r?[]:ee(t))})}),Pe=(e,r,t)=>t.some(o=>o.pid===e&&o.ppid===r),A=(e,r)=>{let t=r.find(o=>o.pid===x.pid)?.pgid;return oe(e,r,t)},ne=e=>{try{return x.kill(-e,0),!0}catch{return!1}},I=(e,r)=>{for(let t of e)try{x.kill(-t,r)}catch{}},w=new Set,Se=(e,r,t)=>{let o=A(e,r),n=t.flatMap(i=>te(i,r));return[...new Set([...o,...n])]},se=()=>{let e=L(),r=[...w].map(t=>t());I(Se(x.pid,e,r),"SIGKILL")},be=async e=>new Promise(r=>{setTimeout(r,e)}),N=async(e,r)=>{let t=Date.now()+r,o=e;for(;o.length>0&&Date.now()<t&&(o=o.filter(ne),o.length!==0);)await be(ge);return o};function vr(e,r=fe,t,o=L){e.unref();let n=!1,i=!1,a=[],c=null,u=()=>a;w.add(u);let p=()=>{c&&clearInterval(c),c=null},d=async()=>{await N(a.map(s=>s.pgid),V),w.delete(u)},f=s=>{let l=e.pid;if(l==null||i||n||s.length===0)return;let v=s.find(R=>R.pid===x.pid)?.pgid,h=we(l,s,v);h.length>0&&(a=h)},g=async()=>{e.pid==null||i||n||f(await ye())};f(L()),c=setInterval(()=>{g()},xe),c.unref();let b=s=>{n||t?.(s)};return e.on("exit",(s,l)=>{i=!0,p(),n||(Q(a,o()),d()),b(`exited unexpectedly (code=${s??"null"}, signal=${l??"null"})`)}),e.on("error",s=>{b(`failed to spawn: ${s.message}`)}),{kill:async()=>{n=!0,p();let s=e.pid;if(s==null){w.delete(u);return}if(e.exitCode!==null||e.signalCode!==null){Q(a,o()),await d();return}let l=o();if(l.length>0&&!Pe(s,x.pid,l))return;let v=A(s,l);I(v,"SIGTERM");let h=await N(v,r);if(h.length===0){w.delete(u);return}let R=A(s,o()),J=[...new Set([...h,...R])].filter(ne);I(J,"SIGKILL"),await N(J,V),w.delete(u)}}}import{constants as he}from"node:os";import E from"node:process";var ke=["SIGINT","SIGTERM","SIGHUP"],ve=he.signals,Ee=2,T=e=>128+(ve[e]??Ee),Ce=2e4,Re=e=>{E.exit(e)},Ne=(e,r)=>{E.on(e,r)},Le=(e,r)=>{E.off(e,r)},Ae=(e,r)=>{let t=setTimeout(e,r);return t.unref(),()=>{clearTimeout(t)}},_=e=>{try{E.stderr.write(e)}catch{}},Ie=(e,r)=>{let t=r instanceof Error?`${r.message}
3
+ ${r.stack??"(no stack)"}`:String(r);_(`
4
+ \u2717 Teardown failed while handling ${e}: ${t}
5
+ `)},Lr=({onSignal:e,exit:r=Re,register:t=Ne,unregister:o=Le,forceReap:n=se,teardownDeadlineMs:i=Ce,setTimer:a=Ae,describeStall:c=()=>"unknown",fileReport:u=()=>{}})=>{let p=null,d=null,f=new Map,g=()=>{for(let[s,l]of f)o(s,l);f.clear()},b=s=>{if(p!==null){if(s!==p)return;_(`
6
+ \u26A0 Received ${s} again \u2014 force-quitting.
7
+ `),d?.(),n(),g(),r(T(s));return}p=s,d=a(()=>{let l=`
8
+ \u26A0 Teardown deadline exceeded at stage=${c()} after ${i}ms \u2014 force-quitting.
9
+ `;_(l),u(l),n(),g(),r(T(s))},i),(async()=>{try{await e(s)}catch(l){Ie(s,l)}finally{d?.(),g(),r(T(s))}})()};for(let s of ke){let l=()=>b(s);f.set(s,l),t(s,l)}return g};import Te from"node:process";import{$ as O}from"zx";var _e=async()=>{try{return await O`cmux --version`.quiet(),!0}catch{return!1}},Oe=async e=>{let{cwd:r,title:t,layout:o}=e,n=JSON.stringify(o),a=(await O({env:{...Te.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${t} --cwd ${r} --focus false --layout ${n}`).stdout;return Me(a)},De=async e=>{try{await O`cmux close-workspace --workspace ${e}`.quiet()}catch(r){m.debug({error:r,ref:e},"cmux: skipped closing dev workspace")}},Me=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in new-workspace output");return r[0]};import{$ as Ge}from"zx";import{realpath as $e}from"node:fs/promises";import{$ as ie}from"zx";var C=async e=>{try{return await $e(e)}catch{return e}},D=async()=>{try{let[e,r]=await Promise.all([ie`cmux workspace list --json`.quiet(),ie`cmux workspace-group list --json`.quiet()]),t=JSON.parse(e.stdout).workspaces??[],o=JSON.parse(r.stdout).groups??[],n=new Set(o.map(a=>a.anchor_workspace_ref).filter(a=>typeof a=="string")),i=new Map;for(let a of t)!a.current_directory||n.has(a.ref)||i.set(await C(a.current_directory),a.ref);return i}catch(e){return m.debug({error:e},"cmux: skipped listing workspaces by cwd"),new Map}};var We=async e=>{try{let t=(await D()).get(await C(e));if(!t)return;await Ge`cmux workspace close ${t}`.quiet()}catch(r){m.debug({error:r,cwd:e},"cmux: skipped closing workspace by cwd")}};import{$ as M}from"zx";var ae=async e=>{try{let r=(await M`cmux workspace-group list --json`.quiet()).stdout;return(JSON.parse(r).groups??[]).find(n=>n.name===e)?.ref??null}catch(r){return m.debug({error:r,name:e},"cmux: skipped group lookup"),null}},Be=async(e,r)=>{try{let o=(await M`cmux workspace-group create --name ${e} --from ${r.join(",")}`).stdout.match(/workspace_group:\d+/)?.[0]??await ae(e);return o&&await M`cmux workspace-group pin ${o}`.quiet(),o??null}catch(t){return m.warn({error:t,name:e},"\u26A0\uFE0F cmux: failed to create workspace group"),null}};import{$ as y}from"zx";var Fe=async e=>{let{cwd:r,title:t,group:o}=e,n=H(await K()),i=o?(await y`cmux workspace create --cwd ${r} --group ${o} --group-placement end`).stdout:(await y`cmux workspace create --cwd ${r}`).stdout,a=Ue(i),c=(await y`cmux list-pane-surfaces --workspace ${a}`).stdout,u=Je(c);return await y`cmux new-split right --workspace ${a} --surface ${u}`,n==="three-pane"&&await y`cmux new-split down --workspace ${a} --surface ${u}`,t&&await y`cmux workspace rename --workspace ${a} --title ${t}`,a},Je=e=>{let r=e.match(/surface:\d+/);if(!r)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return r[0]},Ue=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in workspace create output");return r[0]};var je=e=>{let{branch:r}=e,t=U(r);return t?j(t):r};var qe=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),ce=e=>e instanceof Error&&qe.has(e.name),nt=e=>{if(ce(e))return!0;let r=e?.cause;return ce(r)};import{loadDev as He}from"@slip-stream-kit/config/internal";import Ke from"node:path";var ze=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let n of Object.keys(q(o,r).proxy))t.add(n);return[...t]},Ve=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async n=>{try{let a=(await He(Ke.join(e,"apps",n,"ui")))?.proxy?.routes;if(!a)return;t[n]=Object.fromEntries(Object.entries(a).map(([c,u])=>[c,u.packageName]))}catch(i){o.push({app:n,message:i instanceof Error?i.message:String(i)})}})),{routePkg:(n,i)=>t[n]?.[i],loadErrors:o}},ut=async(e,r,t,o)=>{let{routePkg:n,loadErrors:i}=await Ve(e,ze(r,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(a=>[a.name,a.packageName])),routePkg:n},loadErrors:i}};import{execFile as Qe}from"node:child_process";import{createHash as Xe}from"node:crypto";import{existsSync as ue,readFileSync as k}from"node:fs";import Ye from"node:http";import Ze from"node:https";import er from"node:net";import{homedir as rr}from"node:os";import{dirname as $,join as P}from"node:path";import S from"node:process";import tr from"node:tls";import{fileURLToPath as or}from"node:url";import{promisify as nr}from"node:util";var sr=nr(Qe),ir=e=>{let r=JSON.parse(k(e,"utf-8")),t=typeof r.bin=="string"?r.bin:r.bin?.portless;return t==null||t===""?null:t},ar=()=>{try{let e=$(or(import.meta.url));for(;;){let r=P(e,"node_modules","portless","package.json");if(ue(r)){let o=ir(r);return o==null?null:P($(r),o)}let t=$(e);if(t===e)return null;e=t}}catch{return null}},G,le=()=>(G===void 0&&(G=ar()),G),cr=/^[\w@%+=:,./-]+$/,ur="'\\''",lr=e=>cr.test(e)?e:`'${e.replaceAll("'",ur)}'`,vt=(e,r)=>{let t=[r.execPath??S.execPath,r.bin,...e];return(r.sudo===!0?"sudo ":"")+t.map(lr).join(" ")},pr=1500,W=1500,mr="x-portless",B="127.0.0.1",dr="localhost",fr="/Library/LaunchDaemons/sh.portless.proxy.plist",gr="/etc/systemd/system/portless.service",xr=(e=ue)=>{try{return S.platform==="darwin"?e(fr)?"yes":"no":S.platform==="linux"?e(gr)?"yes":"no":"unknown"}catch{return"unknown"}},wr=e=>new Promise(r=>{let t=er.connect({host:B,port:e}),o=n=>{t.destroy(),r(n)};t.setTimeout(W),t.once("connect",()=>{o(!0)}),t.once("timeout",()=>{o(!1)}),t.once("error",()=>{o(!1)})}),yr=(e,r)=>new Promise(t=>{let n=(r?Ze.request:Ye.request)({host:B,port:e,method:"HEAD",path:"/",timeout:W,...r?{rejectUnauthorized:!1,servername:dr}:{}},i=>{i.resume(),t(i.headers[mr]==="1")});n.on("error",()=>{t(!1)}),n.on("timeout",()=>{n.destroy(),t(!1)}),n.end()}),Pr=async(e,{timeoutMs:r})=>{let t=le();if(t==null)throw new Error("portless is not installed (not resolvable from node_modules)");await sr(S.execPath,[t,...e],{signal:AbortSignal.timeout(r),encoding:"utf-8",env:z(S.env)})},F=()=>S.env.PORTLESS_STATE_DIR??P(rr(),".portless"),Sr="ca.pem",br="ca.trusted",pe=()=>P(F(),Sr),Et=()=>{try{let e=k(P(F(),br),"utf-8").trim();return e===""?!1:Xe("sha256").update(k(pe())).digest("hex")===e.toLowerCase()}catch{return!1}},Ct=(e,r)=>new Promise(t=>{let o;try{o=k(pe())}catch{t({ok:!1,code:"ENOENT"});return}let n=tr.connect({host:B,port:e,servername:r,ca:[o],rejectUnauthorized:!0},()=>{let i=n.authorizationError,a=n.authorized;n.destroy(),t(a?{ok:!0}:{ok:!1,code:i?.code??i?.message??"UNKNOWN"})});n.setTimeout(W),n.once("timeout",()=>{n.destroy(),t({ok:!1,code:"ETIMEDOUT"})}),n.once("error",i=>{n.destroy(),t({ok:!1,code:i.code??"UNKNOWN"})})}),Rt=()=>{try{let e=JSON.parse(k(P(F(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(r=>{let{hostname:t,port:o}=r??{};return typeof t!="string"||t===""||typeof o!="number"?[]:[{name:t,port:o}]}):[]}catch{return[]}},Nt=(e={})=>{let r=e.bin===void 0?le():e.bin,t=e.run??Pr,o=e.isListening??wr,n=e.isProxyServing??yr,i=e.isServiceInstalled??xr,a=e.timeoutMs??pr,c=null,u=async s=>{try{return await t(s,{timeoutMs:a}),!0}catch{return!1}},p=async()=>(c??=await u(["--version"]),c);return{binPath:()=>r,isAvailable:p,isProxyServing:async(s,l)=>!await p()||!await o(s)?!1:n(s,l),probeProxy:async(s,l)=>await o(s)?await n(s,l)?"serving":"not-portless":"daemon-down",isServiceInstalled:i,registerAlias:async(s,l)=>await p()?u(["alias",s,String(l)]):!1,removeAlias:async s=>{await p()&&await u(["alias","--remove",s])}}};export{ut as a,ar as b,vt as c,wr as d,yr as e,pe as f,Et as g,Ct as h,Rt as i,Nt as j,se as k,vr as l,T as m,Lr as n,C as o,D as p,We as q,ae as r,Be as s,_e as t,Oe as u,De as v,Fe as w,je as x,nt as y};
10
+ //# sourceMappingURL=chunk-MKMT6KQT.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/managed-child.ts", "../src/dev/signal-shutdown.ts", "../src/integrations/cmux/open-dev-workspace.ts", "../src/integrations/cmux/close-workspace-by-cwd.ts", "../src/integrations/cmux/list-workspaces-by-cwd.ts", "../src/integrations/cmux/cmux-groups.ts", "../src/integrations/cmux/open-workspace-with-layout.ts", "../src/integrations/cmux/workspace-title.ts", "../src/lib/errors/is-prompt-cancellation.ts", "../src/dev/preset-proxy-context.ts", "../src/dev/proxy/portless-driver.ts"],
4
+ "sourcesContent": ["/**\n * Shared supervision for the dev-server's long-lived, detached child processes\n * (`turbo watch build`, `turbo run dev`). Both are deep trees\n * (`sh \u2192 pnpm \u2192 node \u2192 turbo \u2192 \u2026`) spawned `detached` so they form their own process\n * group; teardown signals the whole GROUP (`process.kill(-pid, \u2026)`), not just the wrapper.\n *\n * Signalling turbo's group is NOT enough on its own: turbo puts every task it runs\n * (`vite`, `tsc -b`, \u2026) into a process group of its OWN, so `kill(-turboPid, \u2026)` reaches\n * turbo but never its tasks. Turbo normally forwards the signal and reaps them, but when it\n * is slower than the grace window a bare `SIGKILL` on turbo's group kills the only process\n * that knows the task groups \u2014 stranding orphaned vite servers that hold their ports until\n * the next run fails with `EADDRINUSE`.\n *\n * So teardown snapshots the descendant process groups BEFORE signalling (once turbo dies its\n * children reparent to init and can no longer be found by walking `ppid`), waits for the whole\n * set to exit, and only then force-kills whatever is left.\n *\n * The same fact \u2014 reparenting blinds the `ppid` walk \u2014 is why a snapshot taken only at teardown is not\n * enough. When turbo dies on its OWN (a crash, an OOM kill) there is no teardown to snapshot from, and\n * the tasks it never reaped are already unreachable. So the snapshot is instead kept ROLLING for the\n * child's whole life, and each group is stamped with its leader's `lstart`: a pgid is a bare integer the\n * kernel will happily recycle, and the leader's start time is the only proof that the group we are about\n * to SIGKILL is still the one we saw.\n *\n * That rolling snapshot lives in a per-child closure, which is exactly what the SECOND-SIGNAL force path\n * (`killDescendantGroupsNow`, used by both `signal-shutdown`'s force-quit and `crash-barrier`'s fatal\n * path) cannot reach on its own \u2014 it only ever does a live `ppid` walk from `process.pid`, the same walk\n * that goes blind the moment a child dies. So every supervised child's snapshot is also published to a\n * module-level `registry` (see below), letting that force path find a descendant which reparented to init\n * before ITS parent's `exit` even fired \u2014 the one case a live walk structurally cannot cover.\n */\nimport { execFile, execFileSync } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport process from 'node:process'\n\n/** Handle to a supervised child; `kill()` reaps its whole process tree and resolves when gone. */\nexport interface ManagedChild {\n kill: () => Promise<void>\n}\n\n/**\n * Grace before escalating SIGTERM \u2192 SIGKILL. Long enough for turbo to stop its tasks itself\n * (typically well under a second) and short enough that Ctrl-C still feels immediate. Escalating\n * is safe now that every task group is killed as a set, so this need not cover the worst case.\n * The happy path never waits the full window \u2014 teardown returns as soon as the groups are gone.\n */\nconst DEFAULT_GRACE_MS = 5000\n\n/** Poll interval while waiting for the doomed process groups to exit. */\nconst POLL_MS = 100\n\n/** How long to wait for the kernel to reap a group after SIGKILL before giving up on confirmation. */\nconst REAP_TIMEOUT_MS = 2000\n\n/** Absolute path to `ps` \u2014 present on both macOS and Linux, and immune to `PATH` substitution. */\nconst PS_BIN = '/bin/ps'\n\n/**\n * How often the live process table is sampled while a supervised child is alive, to keep\n * {@link ManagedChild}'s group snapshot current. See {@link superviseChild} for why a snapshot taken\n * only at kill-time is too late. Async (`execFile`, not `execFileSync`), so it never blocks the event\n * loop the in-process backends share.\n */\nconst SAMPLE_INTERVAL_MS = 1000\n\n/** `ps` columns: the `ppid` walk needs pid/ppid/pgid, and the reuse guard needs the leader's `lstart`. */\nconst PS_ARGS = ['-eo', 'pid=,ppid=,pgid=,lstart='] as const\n\n/** Cap on `ps` output; a busy machine's full process table stays far below this. */\nconst PS_MAX_BUFFER = 8 << 20\n\n/** One row of `ps -eo pid=,ppid=,pgid=,lstart=`. */\nexport interface ProcRow {\n pid: number\n ppid: number\n pgid: number\n /** The process's start time as `ps` prints it (`Mon Jul 13 13:21:14 2026`); `''` when unavailable. */\n lstart: string\n}\n\n/**\n * The subset of a {@link ProcRow} that describes the process TREE. The `ppid` walk needs nothing else,\n * so the functions that only walk take this \u2014 `lstart` is the reuse guard's concern, not the topology's.\n */\nexport type TopologyRow = Pick<ProcRow, 'pid' | 'ppid' | 'pgid'>\n\n/**\n * Parse `ps -eo pid=,ppid=,pgid=,lstart=`, skipping any line that doesn't start with three integers.\n * `lstart` is whitespace-separated and multi-token, so it is everything after the third column.\n */\nexport const parseProcRows = (raw: string): ProcRow[] => {\n return raw.split('\\n').flatMap((line) => {\n const [rawPid, rawPpid, rawPgid, ...rest] = line.trim().split(/\\s+/)\n\n if (rawPid == null || rawPpid == null || rawPgid == null) return []\n\n const pid = Number(rawPid)\n const ppid = Number(rawPpid)\n const pgid = Number(rawPgid)\n\n if (!Number.isInteger(pid) || !Number.isInteger(ppid) || !Number.isInteger(pgid)) return []\n\n return [{ pid, ppid, pgid, lstart: rest.join(' ') }]\n })\n}\n\n/**\n * A process group, stamped with its LEADER's start time at the moment the group was observed.\n *\n * The start time is the whole point. A pgid on its own is a bare integer: by the time we come to reap\n * it the kernel may have recycled it onto an unrelated process, and `kill(-pgid, \u2026)` would then destroy\n * a stranger's group. The leader's `lstart` is the identity that survives \u2014 a recycled pgid necessarily\n * has a NEWER birth time than the one recorded, so it is refused.\n */\nexport interface GroupSnapshot {\n pgid: number\n leaderStart: string\n}\n\n/** Map every process group in `rows` to its leader's start time (the leader is the pid equal to the pgid). */\nconst leaderStarts = (rows: ProcRow[]): Map<number, string> => {\n const starts = new Map<number, string>()\n\n for (const row of rows) {\n if (row.pid === row.pgid) starts.set(row.pgid, row.lstart)\n }\n\n return starts\n}\n\n/**\n * {@link collectDoomedGroups}, but each group is stamped with its leader's start time so it can be\n * validated later. Groups whose leader is not in `rows` are dropped: with no leader there is nothing to\n * stamp, so nothing could prove the group is still the one we saw, and the reuse guard must fail closed.\n *\n * @example\n * const rows = [\n * { pid: 10, ppid: 1, pgid: 10, lstart: 'Mon Jul 13 13:00:00 2026' },\n * { pid: 20, ppid: 10, pgid: 20, lstart: 'Mon Jul 13 13:00:01 2026' },\n * ]\n * snapshotGroups(10, rows) // => [{ pgid: 10, leaderStart: '\u202613:00:00\u2026' }, { pgid: 20, leaderStart: '\u202613:00:01\u2026' }]\n */\nexport const snapshotGroups = (rootPid: number, rows: ProcRow[], excludePgid?: number): GroupSnapshot[] => {\n const starts = leaderStarts(rows)\n\n return collectDoomedGroups(rootPid, rows, excludePgid).flatMap((pgid) => {\n const leaderStart = starts.get(pgid)\n\n if (leaderStart == null || leaderStart === '') return []\n\n return [{ pgid, leaderStart }]\n })\n}\n\n/**\n * pgids in `snapshot` whose leader's start time still matches `rows` \u2014 the reuse guard shared by every\n * path that reaps from a snapshot instead of a live walk: {@link reapSnapshot} (the per-child crash/kill\n * reap) and {@link collectForceReapTargets} (the force-reap path, reaping every REGISTERED child's\n * snapshot). Extracted so the two can never drift apart \u2014 a registry-sourced pgid must clear the exact\n * same check a per-child reap does before either signals it.\n */\nconst validSnapshotPgids = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n const starts = leaderStarts(rows)\n\n return snapshot.flatMap(({ pgid, leaderStart }) => {\n return starts.get(pgid) === leaderStart ? [pgid] : []\n })\n}\n\n/**\n * SIGKILL every snapshotted group whose leader is STILL the same process, and return the pgids killed.\n *\n * A group whose leader has since exited is skipped (nothing to kill, and no way to prove ownership of\n * whatever else may share the pgid). A group whose leader's start time no longer matches is a recycled\n * pgid belonging to a stranger \u2014 skipped, loudly and deliberately. This is the guard that makes reaping\n * from a stale snapshot safe, and it is why the snapshot records `lstart` at all.\n */\nexport const reapSnapshot = (snapshot: readonly GroupSnapshot[], rows: ProcRow[]): number[] => {\n return validSnapshotPgids(snapshot, rows).flatMap((pgid) => {\n try {\n process.kill(-pgid, 'SIGKILL')\n } catch {\n // Raced us to exit (ESRCH) \u2014 nothing to kill.\n return []\n }\n\n return [pgid]\n })\n}\n\n/**\n * Distinct process groups of every transitive descendant of `rootPid`, plus `rootPid`'s own\n * group. Group `0`/`1` and `excludePgid` (our own group \u2014 a detached child can never share it,\n * but a mis-parsed row must never make us signal ourselves) are filtered out.\n *\n * @example\n * const rows = [{ pid: 10, ppid: 1, pgid: 10 }, { pid: 20, ppid: 10, pgid: 20 }]\n * collectDoomedGroups(10, rows, 5) // => [10, 20]\n */\nexport const collectDoomedGroups = (rootPid: number, rows: TopologyRow[], excludePgid?: number): number[] => {\n const childrenOf = new Map<number, TopologyRow[]>()\n\n for (const row of rows) {\n const siblings = childrenOf.get(row.ppid)\n\n if (siblings) siblings.push(row)\n else childrenOf.set(row.ppid, [row])\n }\n\n const groups = new Set<number>([rootPid])\n const seen = new Set<number>([rootPid])\n const queue = [rootPid]\n\n for (let i = 0; i < queue.length; i += 1) {\n for (const child of childrenOf.get(queue[i] ?? -1) ?? []) {\n if (seen.has(child.pid)) continue\n seen.add(child.pid)\n groups.add(child.pgid)\n queue.push(child.pid)\n }\n }\n\n return [...groups].filter((pgid) => {\n return pgid > 1 && pgid !== excludePgid\n })\n}\n\n/**\n * Snapshot the live process table; an empty list on failure degrades to group-only teardown.\n * `ps` is invoked by absolute path (not via `PATH`, unlike the `pnpm` the engines shell out to)\n * so a writable `PATH` entry can never substitute the binary we hand a kill list to.\n */\nconst snapshotProcRows = (): ProcRow[] => {\n try {\n return parseProcRows(execFileSync(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }))\n } catch {\n return []\n }\n}\n\n/**\n * {@link snapshotProcRows}, off the event loop. The rolling sampler runs on a timer for the whole life\n * of a dev session, and the in-process backends share this loop \u2014 a synchronous `ps` every second would\n * stall every request that lands during it. Resolves to `[]` on failure, degrading to the previous\n * snapshot rather than clobbering it.\n */\nconst snapshotProcRowsAsync = async (): Promise<ProcRow[]> => {\n return new Promise((resolve) => {\n execFile(PS_BIN, [...PS_ARGS], { encoding: 'utf8', maxBuffer: PS_MAX_BUFFER }, (error, stdout) => {\n resolve(error ? [] : parseProcRows(stdout))\n })\n })\n}\n\n/** Does `pid` currently exist and name a direct child of `parentPid`? Guards against pid reuse. */\nexport const isChildOf = (pid: number, parentPid: number, rows: TopologyRow[]): boolean => {\n return rows.some((row) => {\n return row.pid === pid && row.ppid === parentPid\n })\n}\n\n/**\n * The groups to signal for `rootPid`'s tree, excluding our own group so a mis-parsed `ps` row can\n * never make the dev-server signal itself.\n */\nconst doomedGroupsOf = (rootPid: number, rows: ProcRow[]): number[] => {\n const ownPgid = rows.find((row) => {\n return row.pid === process.pid\n })?.pgid\n\n return collectDoomedGroups(rootPid, rows, ownPgid)\n}\n\n/** Is the process group led by `pgid` still alive? (`kill(-pgid, 0)` throws ESRCH when gone.) */\nconst groupAlive = (pgid: number): boolean => {\n try {\n process.kill(-pgid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\n/** Send `signal` to every named process group, ignoring groups that already exited. */\nconst signalGroups = (pgids: number[], signal: NodeJS.Signals): void => {\n for (const pgid of pgids) {\n try {\n process.kill(-pgid, signal)\n } catch {\n // Already gone (ESRCH) \u2014 nothing to signal.\n }\n }\n}\n\n/**\n * Live accessors into every currently-supervised child's rolling {@link GroupSnapshot} list \u2014 populated by\n * {@link superviseChild} on spawn, removed only once that child's own groups are CONFIRMED gone (see\n * `deregisterAfter` inside it, not the child's bare `exit` event). This is what lets\n * {@link killDescendantGroupsNow} \u2014 the second-signal force path and the crash-barrier's fatal path \u2014\n * reach a descendant that reparented to init before ITS parent's `exit` fired: a live `ppid` walk from\n * `process.pid` cannot see such a descendant (see the module doc block for why), but a snapshot recorded\n * while the parent was still alive can.\n *\n * INVARIANT \u2014 never regress this: a registry-sourced pgid is signalled ONLY after\n * {@link validSnapshotPgids} confirms its leader's start time still matches a FRESH `ps` snapshot. An\n * ungated union would SIGKILL a recycled pgid \u2014 a hazard the live walk cannot have, since it only ever\n * names processes that are alive right now.\n */\nconst registry = new Set<() => readonly GroupSnapshot[]>()\n\n/**\n * The pgids {@link killDescendantGroupsNow} should signal: every group in the live `ppid` walk from\n * `rootPid` (unchanged semantics \u2014 see {@link doomedGroupsOf}), UNIONED with every registry-sourced\n * snapshot that survives {@link validSnapshotPgids} against the same `rows`. Live-walk pgids are not\n * lstart-gated \u2014 they carry no snapshot to validate against, and are live by construction; only the\n * registry-sourced half needs the reuse guard.\n *\n * Pulled out of `killDescendantGroupsNow` as a pure function so the union/dedupe logic can be tested\n * against a fake process table and fake registry snapshots, without spawning real processes or waiting on\n * a real `ps`.\n *\n * @example\n * // pgid 20 is unreachable from rootPid (reparented to init) but was recorded before its parent died.\n * collectForceReapTargets(1000, freshRows, [[{ pgid: 20, leaderStart: '\u2026' }]]) // => [20]\n */\nexport const collectForceReapTargets = (\n rootPid: number,\n rows: ProcRow[],\n registrySnapshots: readonly (readonly GroupSnapshot[])[],\n): number[] => {\n const live = doomedGroupsOf(rootPid, rows)\n const fromRegistry = registrySnapshots.flatMap((snapshot) => {\n return validSnapshotPgids(snapshot, rows)\n })\n\n return [...new Set([...live, ...fromRegistry])]\n}\n\n/**\n * SIGKILL every process group descended from this process, right now \u2014 plus every REGISTERED\n * supervised-child snapshot that still validates, so a group that reparented to init before its parent's\n * `exit` fired is not left behind just because the live `ppid` walk can no longer see it.\n *\n * The force-quit path (a second Ctrl-C) abandons the graceful teardown, but it must not abandon the\n * CHILDREN: they hold the dev ports, and the next start would 502 against their stale portless\n * aliases. So this is the blunt counterpart to {@link superviseChild}'s teardown \u2014 no SIGTERM grace,\n * no escalation, no waiting for the kernel to reap. Straight to SIGKILL.\n *\n * Synchronous by contract: the caller exits the process on the very next line, so anything deferred\n * to a later tick would never run. Cost is one `ps` (tens of ms) plus a `kill` per group; that is the\n * whole latency budget a user who just hit Ctrl-C twice is willing to spend.\n */\nexport const killDescendantGroupsNow = (): void => {\n const rows = snapshotProcRows()\n const registrySnapshots = [...registry].map((getGroups) => {\n return getGroups()\n })\n\n signalGroups(collectForceReapTargets(process.pid, rows, registrySnapshots), 'SIGKILL')\n}\n\n/** Resolve after `ms`, used to pace the teardown polling loop. */\nconst sleep = async (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/** Poll `pgids` until every group has exited or `timeoutMs` elapses; returns the survivors. */\nconst waitForExit = async (pgids: number[], timeoutMs: number): Promise<number[]> => {\n const deadline = Date.now() + timeoutMs\n let alive = pgids\n\n while (alive.length > 0 && Date.now() < deadline) {\n alive = alive.filter(groupAlive)\n if (alive.length === 0) break\n await sleep(POLL_MS)\n }\n\n return alive\n}\n\n/**\n * Called when a supervised child dies on its OWN \u2014 a natural `exit` or a spawn `error` that was\n * NOT initiated by {@link ManagedChild.kill}. `detail` is a short human description of the cause.\n * The runner uses it to surface a silently-dead `turbo watch`/`turbo run dev` engine (which stops\n * rebuilds/HMR with no other signal) instead of leaving the session looking healthy.\n */\nexport type UnexpectedExitHandler = (detail: string) => void\n\n/**\n * Wrap a detached child: `unref()` it (so it never keeps the loop alive) and return a handle\n * whose `kill()` reaps the child AND every process group turbo spawned beneath it.\n *\n * Snapshot first, signal second: after turbo exits its tasks reparent to init, so the `ppid`\n * walk that finds them must run while turbo is still alive. Then SIGTERM every doomed group,\n * poll until all are gone, and SIGKILL the survivors. Resolves once nothing is left.\n *\n * That covers the ORDERLY death, where we choose the moment and can walk the tree first. It does not\n * cover turbo CRASHING, because reparenting happens at termination \u2014 strictly before Node hands us the\n * `exit` event \u2014 so by then the walk is already blind. A rolling snapshot (see `sample`) is therefore\n * kept for the child's whole life, and both the crash path and a `kill()` on an already-dead child reap\n * from it, validating each group against its leader's start time so a recycled pgid is never killed.\n *\n * `onUnexpectedExit` (optional) fires when the child dies WITHOUT `kill()` having been called \u2014\n * the \"engine died silently\" case. A `killing` latch, set at the top of `kill()` before any signal\n * goes out, suppresses the callback for the exit our own teardown causes, so it reports only genuine\n * crashes. The `error` listener is load-bearing beyond reporting: a {@link ChildProcess} that emits\n * `error` (e.g. `pnpm` ENOENT) with no listener throws as an uncaught exception and would take the\n * whole dev session down.\n */\nexport function superviseChild(\n child: ChildProcess,\n graceMs: number = DEFAULT_GRACE_MS,\n onUnexpectedExit?: UnexpectedExitHandler,\n /**\n * Test-only seam: overrides the `ps` snapshot used by this child's own reap ATTEMPTS (the crash-time\n * reap in the `exit` handler, and `kill()`'s reaps) \u2014 never the rolling sampler, which always uses the\n * real one. Defaults to the real synchronous `ps` call for every production caller. Lets a test simulate\n * a transient `ps` failure (an empty read) without needing to race the real one.\n */\n snapshotRowsOverride: () => ProcRow[] = snapshotProcRows,\n): ManagedChild {\n // Don't keep the parent event loop alive on the child; the runner owns lifecycle via kill().\n child.unref()\n\n // Latched by kill() before it signals, so the child's own teardown exit is not misreported as a crash.\n let killing = false\n // Set by the `exit` listener, so a sampler callback still in flight cannot clobber the final snapshot.\n let exited = false\n /** Last known process groups beneath this child, refreshed while it is alive. See the sampler below. */\n let groups: GroupSnapshot[] = []\n let sampler: NodeJS.Timeout | null = null\n\n /** Live accessor registered in {@link registry} for the whole life of this child \u2014 see `deregisterAfter`. */\n const getGroups = (): readonly GroupSnapshot[] => {\n return groups\n }\n\n registry.add(getGroups)\n\n const stopSampling = (): void => {\n if (sampler) clearInterval(sampler)\n sampler = null\n }\n\n /**\n * Drop this child's accessor from {@link registry} once every group it ever recorded is CONFIRMED gone\n * \u2014 never merely because `exit` fired or a reap attempt ran. A reap attempt can fail to kill anything\n * for a legitimate reason (a stale/empty `ps` read) while the descendant is still very much alive, and\n * removing the entry THEN would strand it: nothing else remembers those pgids once this closure is gone.\n * Bounded by `REAP_TIMEOUT_MS` so a group this genuinely cannot reap (a foreign process now holding a\n * recycled pgid) does not pin a dead entry in the registry forever.\n */\n const deregisterAfter = async (): Promise<void> => {\n await waitForExit(\n groups.map((g) => {\n return g.pgid\n }),\n REAP_TIMEOUT_MS,\n )\n registry.delete(getGroups)\n }\n\n /**\n * Turn a fresh `ps` read into an updated {@link groups}. An empty result is discarded rather than\n * stored: `ps` failing, or racing the child's own death, must degrade to the previous snapshot, never\n * erase it. Shared by the synchronous first sample below and the async rolling {@link sample}, so the\n * two can never compute the group set differently.\n */\n const applySample = (rows: ProcRow[]): void => {\n const pid = child.pid\n\n if (pid == null || exited || killing || rows.length === 0) return\n\n const ownPgid = rows.find((row) => {\n return row.pid === process.pid\n })?.pgid\n const next = snapshotGroups(pid, rows, ownPgid)\n\n if (next.length > 0) groups = next\n }\n\n /**\n * Refresh {@link groups} while the child is alive.\n *\n * This is what makes a crash survivable. Reaping walks `ppid` from the child \u2014 but a process that\n * dies has ALREADY reparented its children to init by the time Node delivers `exit`, so a walk\n * started from the corpse finds only the corpse's own group. Verified: while turbo is alive the walk\n * yields `[turbo, vite]`; inside the `exit` handler it yields `[turbo]`, and vite (`ppid=1`, still\n * running, still holding its port) is unreachable forever. There is no window to race \u2014 the only way\n * to know vite's group after turbo dies is to have written it down BEFORE turbo died.\n *\n * Async (`snapshotProcRowsAsync`) so the rolling tick never blocks the event loop the in-process\n * backends share \u2014 see the FIRST sample below for why that leaves a narrow window this function alone\n * cannot close.\n */\n const sample = async (): Promise<void> => {\n if (child.pid == null || exited || killing) return\n\n applySample(await snapshotProcRowsAsync())\n }\n\n // Synchronous, not `void sample()`: a child that crashes within `sample()`'s first async `ps` round\n // trip (tens of ms) would otherwise have no snapshot recorded at all, and the `exit` handler's\n // `reapSnapshot(groups, \u2026)` would run against an empty `groups` and reap nothing \u2014 the exact\n // spawn\u2192first-snapshot window W11 closes. One small `ps` exec, before this function ever returns,\n // costs the same one-time block on the shared event loop that `killDescendantGroupsNow`'s synchronous\n // `ps` call already spends on every force-quit \u2014 paid once per spawn instead of once per Ctrl-C.\n applySample(snapshotProcRows())\n\n sampler = setInterval(() => {\n void sample()\n }, SAMPLE_INTERVAL_MS)\n // The timer must never be the reason the process stays alive \u2014 it outlives nothing.\n sampler.unref()\n\n const reportUnexpected = (detail: string): void => {\n if (killing) return\n onUnexpectedExit?.(detail)\n }\n\n child.on('exit', (code, signal) => {\n exited = true\n stopSampling()\n\n // The child died WITHOUT us killing it \u2014 a turbo crash, or an OOM kill. Turbo puts each of its\n // tasks in a process group of its OWN, and a turbo that dies this way reaps none of them, so\n // `vite`/`tsc` survive holding their ports. Nothing can find them by walking (see `sample`), and\n // the `kill()` below would bail on an already-exited child. Reaping from the snapshot here is the\n // only thing standing between a crashed engine and a permanently orphaned dev server.\n //\n // `deregisterAfter` (not a bare delete) \u2014 this reap attempt reading a stale/empty `ps` snapshot must\n // not be mistaken for the descendants actually being gone; the registry entry is the only remaining\n // record of them until a later confirmation (or force-reap) proves they are.\n if (!killing) {\n reapSnapshot(groups, snapshotRowsOverride())\n void deregisterAfter()\n }\n\n reportUnexpected(`exited unexpectedly (code=${code ?? 'null'}, signal=${signal ?? 'null'})`)\n })\n child.on('error', (error: Error) => {\n reportUnexpected(`failed to spawn: ${error.message}`)\n })\n\n return {\n kill: async (): Promise<void> => {\n // Latch FIRST: the child WILL emit `exit` during the reap below, and that exit is ours, not a crash.\n killing = true\n stopSampling()\n\n const pid = child.pid\n\n if (pid == null) {\n // Never spawned a real pid \u2014 nothing was ever tracked, so nothing to confirm.\n registry.delete(getGroups)\n\n return\n }\n\n // Once the child is reaped the OS may recycle `pid` onto an unrelated process, and `kill(-pid, \u2026)`\n // would then destroy a stranger's group \u2014 so an exited child is never walked. It is not simply\n // skipped either: a turbo that CRASHED left its task groups running, and this is the Ctrl-C that\n // has to clear them. The snapshot is the only surviving handle on those groups, and `reapSnapshot`\n // re-validates each one against its leader's start time, so a recycled pgid is refused.\n if (child.exitCode !== null || child.signalCode !== null) {\n reapSnapshot(groups, snapshotRowsOverride())\n await deregisterAfter()\n\n return\n }\n\n const rows = snapshotRowsOverride()\n\n // The cheap check above misses a child reaped just now, so confirm `pid` is still ours: a\n // detached child keeps us as its parent, so a foreign `ppid` means the pid was recycled.\n // Skipped when `ps` failed (empty `rows`) \u2014 then only the guard above stands. The registry entry is\n // deliberately left alone here: this state is genuinely ambiguous (did the pid really get\n // recycled, or did `ps` just fail?), and the safe default is to let a later reap re-decide with a\n // fresh read, not to guess by dropping the one record we have.\n if (rows.length > 0 && !isChildOf(pid, process.pid, rows)) return\n\n const doomed = doomedGroupsOf(pid, rows)\n\n // Negative pid \u2192 the whole group (detached made the child a group leader). Turbo forwards\n // this to its tasks; the extra task groups are signalled directly in case it doesn't.\n signalGroups(doomed, 'SIGTERM')\n\n const stragglers = await waitForExit(doomed, graceMs)\n\n if (stragglers.length === 0) {\n // Every doomed group (this child's own, plus every task group the live walk found) exited\n // within grace \u2014 confirmed by the `waitForExit` above, so no further wait is needed here.\n registry.delete(getGroups)\n\n return\n }\n\n // Re-snapshot before forcing: turbo is still alive (that's why we're here), so its tree is\n // still walkable, and `turbo watch build` may have started a task AFTER the first snapshot.\n // Union with the known stragglers, whose groups may already have left turbo's subtree.\n const late = doomedGroupsOf(pid, snapshotRowsOverride())\n const forced = [...new Set([...stragglers, ...late])].filter(groupAlive)\n\n // Killing turbo's group alone would orphan exactly these, so they are killed as a set.\n signalGroups(forced, 'SIGKILL')\n\n // A SIGKILLed leader lingers as an unreaped zombie for a few ms, and `kill(pgid, 0)` still\n // succeeds against it. Wait for the kernel to finish so callers that exit the process\n // immediately after `kill()` resolves aren't racing the teardown they just awaited.\n await waitForExit(forced, REAP_TIMEOUT_MS)\n registry.delete(getGroups)\n },\n }\n}\n", "/**\n * Signal-driven graceful shutdown, shared by every long-lived dev entry point.\n *\n * Three invariants:\n *\n * 1. Only a REPEAT OF THE SAME SIGNAL is an escape hatch. It is tempting to treat any second\n * signal as \"the user pressed Ctrl-C again, get out now\" \u2014 that was the old rule, and it\n * silently orphaned every child. A process manager in front of us relays its own signal after\n * the TTY's, so ONE Ctrl-C under `pnpm exec` arrives as SIGINT *then* SIGTERM:\n *\n * $ pnpm exec node -e \"process.on('SIGINT',\u2026); process.on('SIGTERM',\u2026)\"\n * ^C GOT SIGINT\n * GOT SIGTERM <- pnpm relaying, NOT a second keypress\n *\n * Under the old rule that relay force-quit the teardown a few hundred ms in and abandoned the\n * turbo/vite children (which sit in their own process groups). Keying the escape on the FIRST\n * signal's type fixes it without losing the hatch: a real second Ctrl-C re-sends SIGINT, and a\n * supervisor escalating SIGTERM -> SIGTERM still force-quits. `npm`/`yarn` relay the same way,\n * so this must live here, in the library, not in one consumer's `dev` script.\n * 2. Force-quitting must still not orphan. Even a genuine double Ctrl-C leaves children holding\n * ports (the next start then 502s), so the force path SIGKILLs the descendant process groups\n * before exiting. Bounded and synchronous \u2014 no grace, no escalation, no waiting for reaping.\n * 3. A signal-terminated process must not report exit code 0. The old handlers ran\n * `finally { process.exit(0) }`, which also swallowed a rejecting teardown without a word.\n * Here the rejection goes to stderr and the code stays `128 + signo` \u2014 even on a failed\n * teardown, because the process genuinely WAS signal-terminated, no conventional code means\n * \"signal-terminated but cleanup failed\", and inventing one would break the SIGTERM -> 143\n * contract supervisors rely on. The failure is surfaced by logging, not by the code.\n */\nimport { constants } from 'node:os'\nimport process from 'node:process'\n\nimport { killDescendantGroupsNow } from 'src/dev/managed-child'\n\n/**\n * The signals a resident dev process tears down on.\n *\n * SIGHUP is here for invariant 2: the terminal going away (window closed, ssh dropped) is delivered to\n * the foreground process group, so `dev` gets it \u2014 but its turbo/vite children DON'T, because they sit\n * in their own detached process groups. Without a handler, `dev` takes SIGHUP's default kill, never runs\n * `killDescendantGroupsNow`, and leaves the whole tree alive holding the dev ports; the next start then\n * 502s. Closing a terminal is the single most common way to walk away from a dev server, so this is the\n * likeliest orphan path, not an exotic one.\n */\nconst HANDLED_SIGNALS: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']\n\n/**\n * `os.constants.signals` typed for lookup by an arbitrary {@link NodeJS.Signals}. The platform\n * table omits signals that do not exist on the host, so the index is genuinely partial.\n */\nconst SIGNAL_NUMBERS: Partial<Record<NodeJS.Signals, number>> = constants.signals\n\n/** Fallback signal number when the host table lacks the signal: SIGINT, yielding the usual 130. */\nconst FALLBACK_SIGNO = 2\n\n/**\n * The POSIX exit code for a process terminated by `signal`: `128 + signo`.\n *\n * A shell reports SIGINT as 130 and SIGTERM as 143. Exiting 0 after a signal tells a supervisor\n * the process stopped voluntarily, which is a lie.\n *\n * @example\n * exitCodeForSignal('SIGINT') // 130\n * exitCodeForSignal('SIGTERM') // 143\n */\nexport const exitCodeForSignal = (signal: NodeJS.Signals): number => {\n return 128 + (SIGNAL_NUMBERS[signal] ?? FALLBACK_SIGNO)\n}\n\n/**\n * Seams for {@link registerSignalShutdown}. Each exists because the real implementation is\n * untestable in-process: `process.exit` kills the test runner, and delivering a real POSIX\n * signal to the runner is unsafe and flaky.\n */\nexport interface SignalShutdownDeps {\n /** The context-specific teardown. May reject; the rejection is logged, never swallowed. */\n onSignal: (signal: NodeJS.Signals) => Promise<void>\n /**\n * Terminate the process. Typed as returning `void`, not `never`, so a test can pass a plain\n * recording fake: a `never` fake would have to throw a sentinel, and that throw would reject the\n * in-flight teardown promise. Nothing meaningful runs after a call, so a returning fake is safe.\n */\n exit?: (code: number) => void\n /** Subscribe `handler` to `signal`. Defaults to `process.on`. */\n register?: (signal: NodeJS.Signals, handler: () => void) => void\n /**\n * Unsubscribe `handler` from `signal`. Defaults to `process.off`. Called once the teardown this module\n * owns is over \u2014 graceful completion, the force-quit escape, or the deadline \u2014 so a process whose\n * `exit` seam does not actually terminate (a test, or a caller with its own reasons to keep running)\n * is not left with a dangling SIGINT/SIGTERM/SIGHUP handler from a session that already ended.\n */\n unregister?: (signal: NodeJS.Signals, handler: () => void) => void\n /**\n * Reap surviving descendant process groups on the force-quit path, where the normal teardown is\n * abandoned mid-flight. Synchronous by contract: the process exits on the next line, so anything\n * deferred to a later tick would never run. Defaults to {@link killDescendantGroupsNow}.\n */\n forceReap?: () => void\n /** How long a teardown may run before it is force-quit. See {@link TEARDOWN_DEADLINE_MS}. */\n teardownDeadlineMs?: number\n /**\n * Timer seam, returning its own cancel. Defaults to `setTimeout`/`clearTimeout`; a test injects a fake\n * so the deadline is fired deliberately rather than waited out.\n */\n setTimer?: (handler: () => void, ms: number) => () => void\n /**\n * Name the teardown step still in flight when the deadline trips \u2014 the CLI entry wires this to\n * `runner.shutdownStage`.\n *\n * This module holds NO reference to the runner and so cannot read a stage on its own. Without the seam\n * the deadline degrades into a plain force-quit and the incident's central question (\"`shutdown()`\n * demonstrably ran \u2014 so where did it wedge?\") survives the fix meant to answer it.\n */\n describeStall?: () => string\n /**\n * File the deadline report where it can still be read. The entry routes it into the per-service log sink:\n * on the path this deadline exists for, the terminal is exactly what is gone, so stderr is not a channel.\n * Defaults to a no-op \u2014 library code has no sink to file into.\n */\n fileReport?: (text: string) => void\n}\n\n/**\n * How long a teardown may run before the process force-quits: 20 s, well past a healthy reap (a turbo tree\n * escalates SIGTERM\u2192SIGKILL per child, seconds at worst) and far short of \"forever\".\n *\n * This module used to argue that NO deadline should be armed: *\"any value safe enough not to preempt a\n * legitimate teardown would fire later than a user's second Ctrl-C, and a supervisor sends its own SIGKILL\n * on its own grace.\"* That reasoning quietly ASSUMES A HUMAN IS PRESENT to press Ctrl-C twice \u2014 and the\n * incident that put this here is precisely the case where there is none: the terminal is gone, the operator\n * is not watching, and no supervisor sits above an interactive `ik dev`. Five processes took SIGHUP, ran\n * `shutdown()`, wedged, and spun for five hours writing 455 GB. The escape hatch the old design leaned on\n * cannot be pressed by anyone who has already walked away.\n */\nconst TEARDOWN_DEADLINE_MS = 20_000\n\nconst defaultExit = (code: number): void => {\n process.exit(code)\n}\n\nconst defaultRegister = (signal: NodeJS.Signals, handler: () => void): void => {\n process.on(signal, handler)\n}\n\nconst defaultUnregister = (signal: NodeJS.Signals, handler: () => void): void => {\n process.off(signal, handler)\n}\n\nconst defaultSetTimer = (handler: () => void, ms: number): (() => void) => {\n const timer = setTimeout(handler, ms)\n\n // `unref` so the deadline itself never HOLDS the process open: if the loop empties, the teardown is done\n // and Node exits on its own. A wedged teardown always has live handles (children, listening servers), so\n // the timer phase is still reached \u2014 the probe proved the fault storm does not starve it either.\n timer.unref()\n\n return (): void => {\n clearTimeout(timer)\n }\n}\n\n/**\n * Write to stderr, swallowing a failed write.\n *\n * `stderr.write` can throw (EPIPE, when the parent closed the pipe). Every caller here is on the\n * exit path, and failing to REPORT something must never break that path \u2014 the process still has to\n * die with the right code. A lost message is recoverable; a process that survives its own SIGINT\n * is not.\n */\nconst writeStderr = (message: string): void => {\n try {\n process.stderr.write(message)\n } catch {\n // stderr is gone; there is nowhere left to report to.\n }\n}\n\n/** Report a rejected teardown \u2014 message AND stack, so a wedge is never silent. */\nconst writeTeardownFailure = (signal: NodeJS.Signals, error: unknown): void => {\n const detail = error instanceof Error ? `${error.message}\\n${error.stack ?? '(no stack)'}` : String(error)\n\n writeStderr(`\\n\u2717 Teardown failed while handling ${signal}: ${detail}\\n`)\n}\n\n/**\n * Wire SIGINT/SIGTERM to `onSignal`, then exit `128 + signo`.\n *\n * The first signal runs the teardown. While it is in flight, a signal of a DIFFERENT type is a\n * relay from the process manager above us (`pnpm exec` turns one Ctrl-C into SIGINT + SIGTERM) and\n * is ignored, so the teardown survives to reap its children. A repeat of the FIRST signal is the\n * real escape hatch: it force-quits without touching `onSignal` again, SIGKILLing the descendant\n * groups on the way out so nothing is left holding a port.\n *\n * A {@link TEARDOWN_DEADLINE_MS} deadline IS armed \u2014 read its doc block before removing it, because this\n * module used to explain at length why one should not be. That explanation assumed a human at the keyboard\n * to press Ctrl-C a second time; the incident it now guards against is the case where nobody is there.\n *\n * Mechanically the deadline depends on `terminal-liveness`: with a fault storm live, teardown competes with\n * ~100k blocking `writeSync` calls per second, and a deadline shipped into a machine that cannot honour it\n * is decoration. The storm is cut at its source first; this is what stops the wedge that follows.\n *\n * Returns a `detach` function that drops the SIGINT/SIGTERM/SIGHUP listeners this call installed. Every\n * exit path (graceful completion, the second-signal escape, and the deadline) already calls it before\n * exiting, so a real process never needs it \u2014 `exit` terminates first. It exists for a caller whose `exit`\n * seam does NOT terminate the process (every test in this suite), so a session that already ended does not\n * leave dangling handlers behind for the next one in the same process.\n *\n * @example\n * registerSignalShutdown({\n * onSignal: async (signal) => {\n * process.stdout.write(`Received ${signal}, shutting down...`)\n * await runner.shutdown()\n * },\n * describeStall: () => runner.shutdownStage,\n * })\n */\nexport const registerSignalShutdown = ({\n onSignal,\n exit = defaultExit,\n register = defaultRegister,\n unregister = defaultUnregister,\n forceReap = killDescendantGroupsNow,\n teardownDeadlineMs = TEARDOWN_DEADLINE_MS,\n setTimer = defaultSetTimer,\n describeStall = () => {\n return 'unknown'\n },\n fileReport = () => {},\n}: SignalShutdownDeps): (() => void) => {\n /** The signal that opened the teardown \u2014 `null` until the first one lands. */\n let firstSignal: NodeJS.Signals | null = null\n /** Cancels the armed deadline \u2014 on a completed teardown, and on the second-signal escape. */\n let cancelDeadline: (() => void) | null = null\n /** Every handler this call installed, so `detach` can drop exactly those and nothing else. */\n const handlers = new Map<NodeJS.Signals, () => void>()\n\n /**\n * Drop every listener this call installed. Runs at the end of EVERY exit path below (graceful\n * completion, the second-signal escape, and the deadline) \u2014 not just the happy one \u2014 so a caller whose\n * `exit` seam does not actually terminate the process (a test, or a future non-terminating consumer)\n * is never left holding SIGINT/SIGTERM/SIGHUP handlers from a session that already ended. Idempotent:\n * a second call finds an empty map and does nothing.\n */\n const detach = (): void => {\n for (const [signal, handler] of handlers) {\n unregister(signal, handler)\n }\n handlers.clear()\n }\n\n const handle = (signal: NodeJS.Signals): void => {\n if (firstSignal !== null) {\n // A DIFFERENT signal while tearing down is the process manager in front of us relaying its\n // own (pnpm/npm turn one Ctrl-C into SIGINT + SIGTERM), never a second keypress. Ignoring it\n // is what lets the teardown finish and reap the children. Only a repeat of the signal that\n // STARTED the teardown is the user (or a supervisor) genuinely asking again.\n if (signal !== firstSignal) return\n\n writeStderr(`\\n\u26A0 Received ${signal} again \u2014 force-quitting.\\n`)\n cancelDeadline?.()\n // Abandoning the teardown must still not abandon the children: they hold the dev ports, and\n // the next start would 502 against their stale portless aliases.\n forceReap()\n detach()\n exit(exitCodeForSignal(signal))\n\n return\n }\n\n firstSignal = signal\n\n // The human's escape hatch, armed for the case where there is no human. Same destination as a second\n // Ctrl-C \u2014 reap the descendant groups, exit `128 + signo` \u2014 but it also NAMES the step that wedged, and\n // files that name where it can still be read once the terminal is gone.\n cancelDeadline = setTimer(() => {\n const report = `\\n\u26A0 Teardown deadline exceeded at stage=${describeStall()} after ${teardownDeadlineMs}ms \u2014 force-quitting.\\n`\n\n writeStderr(report)\n fileReport(report)\n forceReap()\n detach()\n exit(exitCodeForSignal(signal))\n }, teardownDeadlineMs)\n\n void (async (): Promise<void> => {\n try {\n await onSignal(signal)\n } catch (error) {\n writeTeardownFailure(signal, error)\n } finally {\n // `finally`, so the exit survives anything the catch body might later throw: a process must\n // never outlive its own signal. Not the old `finally { process.exit(0) }` bug \u2014 that one\n // exited zero without logging; this logs first, then exits the honest code.\n cancelDeadline?.()\n detach()\n exit(exitCodeForSignal(signal))\n }\n })()\n }\n\n for (const signal of HANDLED_SIGNALS) {\n const handler = (): void => {\n return handle(signal)\n }\n\n handlers.set(signal, handler)\n register(signal, handler)\n }\n\n return detach\n}\n", "import process from 'node:process'\nimport { $ } from 'zx'\n\nimport type { CmuxLayoutNode } from 'src/dev/cmux-layout'\nimport { logger } from 'src/lib/logger'\n\n/** Args for {@link openCmuxDevWorkspace}: the workspace root, title, and pane layout tree. */\ninterface OpenCmuxDevWorkspaceArgs {\n cwd: string\n title: string\n layout: CmuxLayoutNode\n}\n\n/**\n * True iff the `cmux` CLI is invokable (i.e. `cmux --version` resolves). Used to\n * gate `--cmux` mode and fall back to single-process dev when cmux is absent.\n */\nexport const isCmuxAvailable = async (): Promise<boolean> => {\n try {\n await $`cmux --version`.quiet()\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Open ONE cmux workspace rooted at `cwd`, laid out per `layout` (one pane per\n * command). Runs in a `CMUX_QUIET=1` scoped env to suppress cmux's one-time compat\n * notice, then parses and returns the `workspace:<id>` ref from stdout.\n */\nexport const openCmuxDevWorkspace = async (args: OpenCmuxDevWorkspaceArgs): Promise<string> => {\n const { cwd, title, layout } = args\n const layoutJson = JSON.stringify(layout)\n\n const $cmux = $({ env: { ...process.env, CMUX_QUIET: '1' } })\n const output = (await $cmux`cmux new-workspace --name ${title} --cwd ${cwd} --focus false --layout ${layoutJson}`)\n .stdout\n\n return parseWorkspaceRef(output)\n}\n\n/**\n * Best-effort close of the cmux workspace `ref`, tearing down the workspace and\n * every pane process. Silently no-ops (debug-logged) if cmux isn't running or the\n * close fails, mirroring {@link file://./close-workspace-by-cwd.ts}.\n */\nexport const closeCmuxDevWorkspace = async (ref: string): Promise<void> => {\n try {\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, ref }, 'cmux: skipped closing dev workspace')\n }\n}\n\n/**\n * Extract the `workspace:<id>` ref from `cmux new-workspace` output (e.g.\n * `OK workspace:5`). Throws a clear error when no ref is present.\n *\n * @example\n * parseWorkspaceRef('OK workspace:5\\n') // => 'workspace:5'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in new-workspace output')\n }\n\n return match[0]\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { listCmuxWorkspacesByCwd, realpathForCmuxCwd } from './list-workspaces-by-cwd'\n\n/**\n * Best-effort close of the cmux workspace rooted at `cwd`. Resolves the workspace\n * ref via {@link listCmuxWorkspacesByCwd} (which excludes group anchors, so this\n * can never close a group header) and closes it. Silently no-ops if cmux isn't\n * running, no workspace matches the cwd, or the close fails.\n *\n * Called BEFORE `git worktree remove`, so `cwd` still exists and normalizes the\n * same way as cmux's reported `current_directory`.\n */\nexport const closeCmuxWorkspaceByCwd = async (cwd: string): Promise<void> => {\n try {\n const byCwd = await listCmuxWorkspacesByCwd()\n\n const ref = byCwd.get(await realpathForCmuxCwd(cwd))\n\n if (!ref) {\n return\n }\n\n await $`cmux workspace close ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, cwd }, 'cmux: skipped closing workspace by cwd')\n }\n}\n", "import { realpath } from 'node:fs/promises'\nimport { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxWorkspaceListEntry {\n ref: string\n current_directory: string | null\n}\n\ninterface CmuxGroupListEntry {\n anchor_workspace_ref: string | null\n}\n\n/**\n * Resolve `path` through the filesystem, falling back to the input when it can't\n * be resolved (e.g. the directory was already removed). Both the cmux-reported\n * cwd and the caller's target cwd are normalized the same way so a macOS\n * `/var`\u2192`/private/var` style symlink can't make two equal paths compare unequal\n * (the realpath-asymmetry footgun this repo has been burned by before).\n */\nconst safeRealpath = async (path: string): Promise<string> => {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n\n/**\n * Build a `realpath(cwd) \u2192 workspace ref` map of every currently-open cmux\n * workspace, keyed on its working directory. This is the dedup/close identity for\n * infra-kit's worktree workspaces \u2014 unique per worktree, and (unlike the title)\n * stable after the repo-name title prefix was dropped (two repos can share a\n * branch name like `fix-post-script-ci-cd`, but never a worktree path).\n *\n * Two entries are deliberately excluded:\n * - workspaces with no `current_directory` (e.g. `infra-kit dev` panes) \u2014 they\n * carry no worktree identity;\n * - group ANCHOR workspaces \u2014 cmux reports the anchor's cwd as the main-repo\n * root, so it collides with the real main-checkout workspace. Keying an\n * anchor into the map would shadow the main workspace (breaking dedup) and,\n * worse, let close-by-cwd close the group header. Anchors are dropped up front\n * via `workspace-group list`'s `anchor_workspace_ref`.\n *\n * Returns an empty map if cmux isn't running or the output can't be parsed \u2014\n * callers treat \"empty\" as \"unknown, proceed as if nothing is open\".\n */\nexport const listCmuxWorkspacesByCwd = async (): Promise<Map<string, string>> => {\n try {\n const [workspacesOutput, groupsOutput] = await Promise.all([\n $`cmux workspace list --json`.quiet(),\n $`cmux workspace-group list --json`.quiet(),\n ])\n\n const workspaces = (JSON.parse(workspacesOutput.stdout).workspaces ?? []) as CmuxWorkspaceListEntry[]\n const groups = (JSON.parse(groupsOutput.stdout).groups ?? []) as CmuxGroupListEntry[]\n\n const anchorRefs = new Set(\n groups\n .map((group) => {\n return group.anchor_workspace_ref\n })\n .filter((ref): ref is string => {\n return typeof ref === 'string'\n }),\n )\n\n const byCwd = new Map<string, string>()\n\n for (const workspace of workspaces) {\n if (!workspace.current_directory || anchorRefs.has(workspace.ref)) {\n continue\n }\n\n byCwd.set(await safeRealpath(workspace.current_directory), workspace.ref)\n }\n\n return byCwd\n } catch (error) {\n logger.debug({ error }, 'cmux: skipped listing workspaces by cwd')\n\n return new Map()\n }\n}\n\n/** Exported for callers that need the same normalization when looking up a target cwd. */\nexport { safeRealpath as realpathForCmuxCwd }\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxGroupListEntry {\n ref: string\n name: string\n}\n\n/**\n * Return the `workspace_group:N` ref of the sidebar group titled exactly `name`,\n * or `null` if no such group exists (or cmux is unreachable). Group names are the\n * repo name (basename of the main-repo root), so worktree workspaces for one repo\n * all resolve to the same group regardless of which worktree the command runs in.\n */\nexport const findCmuxGroupRefByName = async (name: string): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group list --json`.quiet()).stdout\n\n const groups = (JSON.parse(output).groups ?? []) as CmuxGroupListEntry[]\n\n const match = groups.find((group) => {\n return group.name === name\n })\n\n return match?.ref ?? null\n } catch (error) {\n logger.debug({ error, name }, 'cmux: skipped group lookup')\n\n return null\n }\n}\n\n/**\n * Create a pinned sidebar group named `name` seeded with EXACTLY `fromRefs`, and\n * return its ref (or `null` on failure).\n *\n * `--from` is load-bearing: `cmux workspace-group create` defaults `--from` to the\n * currently-selected/caller workspace, so omitting it silently captures an\n * unrelated workspace (and, under the `--all` fan-out, steals a sibling repo's\n * freshly-created workspace). Passing the seed refs explicitly makes creation\n * deterministic and capture-free \u2014 no snapshot/self-heal needed. The group also\n * gets a synthetic anchor workspace (its header row), matching how the user's\n * groups are already shaped.\n */\nexport const createCmuxGroupFrom = async (name: string, fromRefs: string[]): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group create --name ${name} --from ${fromRefs.join(',')}`).stdout\n\n const ref = output.match(/workspace_group:\\d+/)?.[0] ?? (await findCmuxGroupRefByName(name))\n\n if (ref) {\n await $`cmux workspace-group pin ${ref}`.quiet()\n }\n\n return ref ?? null\n } catch (error) {\n logger.warn({ error, name }, '\u26A0\uFE0F cmux: failed to create workspace group')\n\n return null\n }\n}\n", "import { $ } from 'zx'\n\nimport { getInfraKitConfig, resolveCmuxLayout } from 'src/lib/infra-kit-config'\n\ninterface OpenCmuxWorkspaceArgs {\n cwd: string\n title?: string\n /**\n * When set, the workspace is created directly inside this sidebar group\n * (`workspace_group:N` ref) via `--group`, appended at the end so existing\n * members aren't reordered. Omit to create an ungrouped workspace (e.g. the\n * first worktree of a repo, which then seeds a new group).\n */\n group?: string\n}\n\n/**\n * Opens a new cmux workspace rooted at `cwd`, with panes arranged per the\n * configured `worktrees.cmux.layout` (resolved via {@link resolveCmuxLayout},\n * default `two-columns`):\n * two-columns \u2014 left | right, both full-height (two panes)\n * three-pane \u2014 left-top / left-bottom | full-height right (three panes)\n * All panes inherit `cwd` from the workspace. Returns the created\n * `workspace:N` ref so callers can seed a group from it.\n */\nexport const openCmuxWorkspaceWithLayout = async (args: OpenCmuxWorkspaceArgs): Promise<string> => {\n const { cwd, title, group } = args\n\n const layout = resolveCmuxLayout(await getInfraKitConfig())\n\n const newWorkspaceOutput = group\n ? (await $`cmux workspace create --cwd ${cwd} --group ${group} --group-placement end`).stdout\n : (await $`cmux workspace create --cwd ${cwd}`).stdout\n\n const workspaceRef = parseWorkspaceRef(newWorkspaceOutput)\n\n const surfacesOutput = (await $`cmux list-pane-surfaces --workspace ${workspaceRef}`).stdout\n\n const leftTopRef = parseFirstSurfaceRef(surfacesOutput)\n\n // Both layouts share the vertical split into left | right columns; only the\n // legacy three-pane layout additionally splits the left column top/bottom.\n await $`cmux new-split right --workspace ${workspaceRef} --surface ${leftTopRef}`\n\n if (layout === 'three-pane') {\n await $`cmux new-split down --workspace ${workspaceRef} --surface ${leftTopRef}`\n }\n\n if (title) {\n await $`cmux workspace rename --workspace ${workspaceRef} --title ${title}`\n }\n\n return workspaceRef\n}\n\n/**\n * Extracts the first `surface:<id>` reference from the output of\n * `cmux list-pane-surfaces`. Used to locate the initial (primary) pane\n * surface so subsequent splits can be anchored relative to it.\n *\n * @example\n * const output = 'surface:12 (active)\\nsurface:13\\n'\n * parseFirstSurfaceRef(output) // => 'surface:12'\n */\nconst parseFirstSurfaceRef = (output: string): string => {\n const match = output.match(/surface:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate initial surface in list-pane-surfaces output')\n }\n\n return match[0]\n}\n\n/**\n * Extracts the `workspace:<id>` reference from the output of\n * `cmux workspace create`. The returned ref is used to target the newly\n * created workspace in follow-up `cmux` commands (splits, rename, etc.).\n *\n * @example\n * const output = 'created workspace:7\\n'\n * parseWorkspaceRef(output) // => 'workspace:7'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in workspace create output')\n }\n\n return match[0]\n}\n", "import { displayLabel, parseBranchName } from 'src/lib/release-id'\n\ninterface BuildCmuxWorkspaceTitleArgs {\n branch: string\n}\n\n/**\n * Builds the cmux workspace title for a worktree. The title is now just the\n * branch's display label \u2014 the repo name is NOT prefixed, because every worktree\n * workspace lives inside a per-repo sidebar GROUP whose header already carries the\n * repo name (e.g. group `hulyo-monorepo` \u2192 workspaces titled `1.48.0`,\n * `checkout-redesign`, `dev`). Release branches render via their release-id label\n * (`release/v1.48.0` \u2192 `1.48.0`, `release/checkout-redesign` \u2192 `checkout-redesign`);\n * non-release branches fall back to the raw branch string.\n *\n * Note: the title is NO LONGER a dedup/close key \u2014 that role moved to the\n * workspace cwd (see {@link listCmuxWorkspacesByCwd}), because dropping the repo\n * prefix makes titles collide across repos (both hulyo and travelist can have a\n * `fix-post-script-ci-cd` branch).\n */\nexport const buildCmuxWorkspaceTitle = (args: BuildCmuxWorkspaceTitleArgs): string => {\n const { branch } = args\n\n const id = parseBranchName(branch)\n\n return id ? displayLabel(id) : branch\n}\n", "/**\n * Names of the error classes thrown when an interactive prompt ends without a\n * value. From `@inquirer/core`: `ExitPromptError` (Ctrl-C \u2014 and ONLY Ctrl-C:\n * inquirer binds no escape key, so it raises this from readline's SIGINT) and\n * `AbortPromptError` (the prompt was aborted via an `AbortSignal`, which is how\n * Esc arrives \u2014 see lib/prompts/escapable-context). From our own Ink pickers:\n * `PromptCancelledError` (see ./prompt-cancelled-error), which is registered here\n * rather than impersonating an inquirer class name. All are intentional\n * cancellations, not failures.\n */\nconst CANCELLATION_ERROR_NAMES = new Set(['ExitPromptError', 'AbortPromptError', 'PromptCancelledError'])\n\nconst hasCancellationName = (value: unknown): boolean => {\n return value instanceof Error && CANCELLATION_ERROR_NAMES.has(value.name)\n}\n\n/**\n * True when `error` represents a user (or signal) cancellation of an interactive\n * prompt \u2014 Ctrl-C anywhere, or Esc, which reaches an `@inquirer` prompt as an\n * abort and an Ink picker as a `PromptCancelledError`. Matched by `name` rather\n * than `instanceof` so it stays correct\n * even when pnpm dedupes more than one copy of `@inquirer/core` into the tree\n * (an `instanceof` check fails across realms/duplicate classes).\n *\n * Also unwraps one level of `cause`, so a cancellation re-wrapped in an\n * {@link ./operation-error.OperationError} is still recognised at the top-level\n * error boundary.\n *\n * @example\n * try {\n * await checkbox({ message: 'Select release branches', choices })\n * } catch (err) {\n * if (isPromptCancellation(err)) process.exit(0) // clean back-out, not an error\n * throw err\n * }\n */\nexport const isPromptCancellation = (error: unknown): boolean => {\n if (hasCancellationName(error)) return true\n\n const cause = (error as { cause?: unknown } | null | undefined)?.cause\n\n return hasCancellationName(cause)\n}\n", "/**\n * Assembles the impure {@link PresetProxyContext} `validatePresetProxy` needs, so the STATIC\n * proxy-locality rule in `presets.ts` never has to touch the filesystem or `loadDev` itself.\n *\n * Shared by two callers that must never disagree about what \"satisfiable\" means:\n * - `infra-kit audit` (`commands/audit/preset-proxy-check.ts`) \u2014 checks every preset.\n * - `infra-kit dev <preset>` (`dev-server.ts`) \u2014 checks only the one preset about to run, BEFORE\n * any server spawns.\n */\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\n\nimport { resolvePreset } from 'src/dev/presets'\nimport type { DiscoveredParts, PresetProxyContext } from 'src/dev/presets'\nimport type { DevPresets } from 'src/lib/infra-kit-config'\n\n/** A frontend config that a preset references but that failed to load (bad/invalid config). */\nexport interface LoadError {\n app: string\n message: string\n}\n\ninterface RoutePkgLookup {\n routePkg: PresetProxyContext['routePkg']\n loadErrors: LoadError[]\n}\n\n/**\n * The set of frontend app folders any preset's proxy override actually references \u2014\n * the only configs the caller needs to load. Scoping to these keeps an unrelated\n * broken frontend config from failing (or crashing) a check it was never relevant to.\n */\nconst collectReferencedApps = (presets: DevPresets, discovered: DiscoveredParts): string[] => {\n const apps = new Set<string>()\n\n for (const preset of Object.values(presets)) {\n for (const app of Object.keys(resolvePreset(preset, discovered).proxy)) {\n apps.add(app)\n }\n }\n\n return [...apps]\n}\n\n/**\n * Load each referenced frontend's `dev.proxy.routes` into a sync `(app, route) \u2192 pkg`\n * lookup. A config that throws (schema-invalid, import error) is captured as a\n * {@link LoadError} instead of rejecting, so one bad config yields an actionable\n * result rather than crashing the whole check.\n */\nconst buildRoutePkgLookup = async (root: string, apps: string[]): Promise<RoutePkgLookup> => {\n const routesByApp: Record<string, Record<string, string>> = {}\n const loadErrors: LoadError[] = []\n\n await Promise.all(\n apps.map(async (app) => {\n try {\n const dev = await loadDev(path.join(root, 'apps', app, 'ui'))\n const routes = dev?.proxy?.routes\n\n if (!routes) return\n\n routesByApp[app] = Object.fromEntries(\n Object.entries(routes).map(([route, route_]) => {\n return [route, route_.packageName]\n }),\n )\n } catch (error) {\n loadErrors.push({ app, message: error instanceof Error ? error.message : String(error) })\n }\n }),\n )\n\n return {\n routePkg: (app, route) => {\n return routesByApp[app]?.[route]\n },\n loadErrors,\n }\n}\n\n/** Result of {@link buildPresetProxyContext}: the assembled context, plus any config that failed to load. */\nexport interface PresetProxyContextResult {\n ctx: PresetProxyContext\n loadErrors: LoadError[]\n}\n\n/**\n * Build the {@link PresetProxyContext} `validatePresetProxy` needs for `presets`: a sync\n * `(app, route) \u2192 pkg` lookup from each referenced frontend's `infra-kit.config.ts`\n * (the SAME file, through the same `loadDev`, that the vite helper resolves at runtime), plus\n * the api package name for every discovered api app.\n *\n * @example\n * const { ctx, loadErrors } = await buildPresetProxyContext('/repo', presets, discovered, apiApps)\n * const issues = validatePresetProxy(presets, ctx)\n */\nexport const buildPresetProxyContext = async (\n root: string,\n presets: DevPresets,\n discovered: DiscoveredParts,\n apiApps: { name: string; packageName: string }[],\n): Promise<PresetProxyContextResult> => {\n const { routePkg, loadErrors } = await buildRoutePkgLookup(root, collectReferencedApps(presets, discovered))\n\n return {\n ctx: {\n discovered,\n apiPkgByApp: Object.fromEntries(\n apiApps.map((a) => {\n return [a.name, a.packageName]\n }),\n ),\n routePkg,\n },\n loadErrors,\n }\n}\n", "/**\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, a cmux runner, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set (a space, a paren \u2014 both of\n * which appear in real install paths like `/Applications/My Editor.app`) gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nconst shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless service\n * install` hands the user a command that dies with `sudo: portless: command not found`. `sudo` makes it\n * strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve `portless`\n * loses it the moment the command is elevated.\n *\n * We therefore print what the driver itself runs (see {@link defaultRun}): the current interpreter, by\n * absolute path, invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the\n * command works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * This is not merely cosmetic. portless's `service install` writes **the interpreter and script path it was\n * invoked with** straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n * `process.argv[1]`), so the command printed here is the command that gets installed as a **root system\n * daemon**. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as root.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + words.map(shellQuote).join(' ')\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_PLIST_PATH = '/Library/LaunchDaemons/sh.portless.proxy.plist'\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was **unsound**: portless's\n * `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n * process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n * stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n * old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n * were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Validating the chain here would collapse two different\n * failures \u2014 a daemon that is down, and a CA that was never trusted \u2014 into one indistinguishable error,\n * with two different fixes (a root `service install` vs the sudo-free `trust`). Trust is a separate,\n * explicitly-validating probe (doctor's CA check).\n */\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n isAvailable,\n isProxyServing: serving,\n probeProxy,\n isServiceInstalled,\n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AI,EAAW,GAEhCsC,EAAetC,EAAMO,CAAG,EAgC/B,WAvBiB,MAAOP,EAAcO,IAChC,MAAM8B,EAAYrC,CAAI,EAEpB,MAAMsC,EAAetC,EAAMO,CAAG,EAAK,UAAY,eAFhB,cAuBvC,mBAAAgC,EACA,cAnBoB,MAAOI,EAAc3C,IACnC,MAAM0C,EAAY,EAEjBD,EAAO,CAAC,QAASE,EAAM,OAAO3C,CAAI,CAAC,CAAC,EAFR,GAmBnC,YAdkB,MAAO2C,GAAgC,CACnD,MAAMD,EAAY,GACxB,MAAMD,EAAO,CAAC,QAAS,WAAYE,CAAI,CAAC,CAC1C,CAYA,CACF",
6
+ "names": ["execFile", "execFileSync", "process", "DEFAULT_GRACE_MS", "POLL_MS", "REAP_TIMEOUT_MS", "PS_BIN", "SAMPLE_INTERVAL_MS", "PS_ARGS", "PS_MAX_BUFFER", "parseProcRows", "raw", "line", "rawPid", "rawPpid", "rawPgid", "rest", "pid", "ppid", "pgid", "leaderStarts", "rows", "starts", "row", "snapshotGroups", "rootPid", "excludePgid", "collectDoomedGroups", "leaderStart", "validSnapshotPgids", "snapshot", "reapSnapshot", "childrenOf", "siblings", "groups", "seen", "queue", "i", "child", "snapshotProcRows", "snapshotProcRowsAsync", "resolve", "error", "stdout", "isChildOf", "parentPid", "doomedGroupsOf", "ownPgid", "groupAlive", "signalGroups", "pgids", "signal", "registry", "collectForceReapTargets", "registrySnapshots", "live", "fromRegistry", "killDescendantGroupsNow", "getGroups", "sleep", "ms", "waitForExit", "timeoutMs", "deadline", "alive", "superviseChild", "graceMs", "onUnexpectedExit", "snapshotRowsOverride", "killing", "exited", "sampler", "stopSampling", "deregisterAfter", "g", "applySample", "next", "sample", "reportUnexpected", "detail", "code", "doomed", "stragglers", "late", "forced", "constants", "process", "HANDLED_SIGNALS", "SIGNAL_NUMBERS", "constants", "FALLBACK_SIGNO", "exitCodeForSignal", "signal", "TEARDOWN_DEADLINE_MS", "defaultExit", "code", "process", "defaultRegister", "handler", "defaultUnregister", "defaultSetTimer", "ms", "timer", "writeStderr", "message", "writeTeardownFailure", "error", "detail", "registerSignalShutdown", "onSignal", "exit", "register", "unregister", "forceReap", "killDescendantGroupsNow", "teardownDeadlineMs", "setTimer", "describeStall", "fileReport", "firstSignal", "cancelDeadline", "handlers", "detach", "handle", "report", "process", "$", "isCmuxAvailable", "$", "openCmuxDevWorkspace", "args", "cwd", "title", "layout", "layoutJson", "output", "process", "parseWorkspaceRef", "closeCmuxDevWorkspace", "ref", "error", "logger", "match", "$", "realpath", "$", "safeRealpath", "path", "realpath", "listCmuxWorkspacesByCwd", "workspacesOutput", "groupsOutput", "$", "workspaces", "groups", "anchorRefs", "group", "ref", "byCwd", "workspace", "error", "logger", "closeCmuxWorkspaceByCwd", "cwd", "ref", "listCmuxWorkspacesByCwd", "safeRealpath", "$", "error", "logger", "$", "findCmuxGroupRefByName", "name", "output", "$", "group", "error", "logger", "createCmuxGroupFrom", "fromRefs", "ref", "$", "openCmuxWorkspaceWithLayout", "args", "cwd", "title", "group", "layout", "resolveCmuxLayout", "getInfraKitConfig", "newWorkspaceOutput", "$", "workspaceRef", "parseWorkspaceRef", "surfacesOutput", "leftTopRef", "parseFirstSurfaceRef", "output", "match", "buildCmuxWorkspaceTitle", "args", "branch", "id", "parseBranchName", "displayLabel", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause", "loadDev", "path", "collectReferencedApps", "presets", "discovered", "apps", "preset", "app", "resolvePreset", "buildRoutePkgLookup", "root", "routesByApp", "loadErrors", "routes", "loadDev", "path", "route", "route_", "error", "buildPresetProxyContext", "apiApps", "routePkg", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "formatPortlessCommand", "args", "options", "words", "process", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name"]
7
+ }
@@ -0,0 +1,7 @@
1
+ import{J as f,ca as w,d as E}from"./chunk-XR6HR4LL.js";import{q as O}from"./chunk-CHETBZ6M.js";import{a as k,b as S}from"./chunk-X46DP23W.js";import d from"node:fs/promises";import c from"node:path";import{z as s}from"zod";var i=class extends Error{env;constructor(r,o=null){super(r),this.name="EnvAuthError",this.env=o}},B=t=>t instanceof i;import C from"node:fs/promises";import D from"node:os";var $=async t=>{try{return await C.access(t),!0}catch{return!1}},p=t=>{let r=D.homedir();return t.startsWith(r)?`~${t.slice(r.length)}`:t};var I="tokens.json",u=1,y=384,T=448,N=s.object({version:s.literal(u).default(u),envs:s.record(s.string().min(1),s.string().min(1))}).strict(),g=async()=>{let t=await w();return c.join(c.dirname(t.userProject),I)},h=async()=>{let t=await g(),r;try{r=await d.readFile(t,"utf-8")}catch{return null}let o;try{o=JSON.parse(r)}catch(n){throw new i(`Invalid JSON in the token store at ${p(t)}: ${n.message}
2
+ Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let e=N.safeParse(o);if(!e.success)throw new i(`Invalid token store at ${p(t)}: ${s.prettifyError(e.error)}
3
+ Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return e.data},x=async t=>{let r=await g(),o=c.dirname(r),e=c.dirname(o),n=c.dirname(e);for(let a of[n,e,o])await d.mkdir(a,{recursive:!0,mode:T}),await d.chmod(a,T);O(r,`${JSON.stringify(t,null,2)}
4
+ `,y),await d.chmod(r,y)},_=async(t,r)=>{let o=await h();await x({version:u,envs:{...o?.envs,[t]:r}})},j=async t=>{let r=await h();if(!r||!(t in r.envs))return;let o={...r.envs};delete o[t],await x({version:u,envs:o})};var A=()=>{let t="",r=[],o=!1;return{start(e){t=e,r=[],o=!1},setInteractive(){o=!0},addOption(e,n){r.push({flag:e,value:n})},formatOptions(){return r.map(e=>typeof e.value=="boolean"?e.value?e.flag:"":Array.isArray(e.value)?`${e.flag} "${e.value.join(", ")}"`:`${e.flag} "${e.value}"`).filter(Boolean).join(" ")},snapshot(){return r.length===0?null:{formattedOptions:this.formatOptions()}},print(){!o||r.length===0||!t||f.info(`\u{1F4DF} Equivalent command:
5
+ pnpm exec infra-kit ${t} ${this.formatOptions()}
6
+ `)},reset(){t="",r=[],o=!1}}},v=A();import P from"node:process";var F=27,b=async(t,r)=>{let o=new AbortController,e={...r,signal:o.signal};if(E()||!P.stdin.isTTY)return t(e);let n=P.stdin,a=l=>{l.length===1&&l[0]===F&&o.abort()};k();try{let l=t(e);return n.isPaused()&&n.resume(),n.on("data",a),await l}finally{n.removeListener("data",a),S()}};import R from"@inquirer/confirm";import J from"node:process";var m=class extends Error{constructor(r="Operation cancelled by the operator"){super(r),this.name="CommandDeclinedError"}},mt=t=>t instanceof m;var K=async(t,r,o={})=>{let e=t?!0:await b(n=>R({message:r},n));if(t||v.setInteractive(),!e){if(o.throwOnDecline)throw new m;f.info("Operation cancelled. Exiting..."),J.exit(0)}};export{i as a,B as b,$ as c,p as d,g as e,h as f,_ as g,j as h,v as i,mt as j,b as k,K as l};
7
+ //# sourceMappingURL=chunk-OKO3DKIM.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts", "../src/lib/path-display/path-display.ts", "../src/lib/command-echo/command-echo.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/command-echo/confirm-or-exit.ts"],
4
- "sourcesContent": ["// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n *\n * HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were dropped\n * for it \u2014 do not re-add either without re-deciding that:\n *\n * - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version key,\n * and a store the CLI refuses to read is a store the human cannot write.\n * - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout. That\n * guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so `~/work/api`\n * and `~/oss/api` share ONE token directory and repo B could load (and then overwrite) repo A's\n * credentials. It was removed anyway, knowingly: it also made the CLI refuse every hand-written\n * store, which carries no such field. Hand-authorability wins; the basename-collision risk is\n * ACCEPTED. A weakened version of the guard (warn-and-continue, or \"only check when present\") is\n * NOT the compromise here \u2014 it would re-introduce the same refusal for anyone who did write the\n * field. If you want the guard back, key the store directory on something collision-free instead.\n */\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 it cannot heal on a 30s retry, only a human can fix it \u2014 and env\n // auto-load's sticky marker is keyed on that CLASS. Thrown as a plain Error these were classified\n // TRANSIENT, so a corrupt store went silent on the backgrounded shell-startup spawn and the user's\n // env simply stopped loading with nothing ever said. `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): env auto-load must tell a user\n * apart from a TRANSIENT failure (network, timeout, Doppler down \u2014 heals itself, 30s backoff, stay\n * quiet) and a DURABLE one (no token, a corrupt token store, a foreign token store \u2014 never heals, and\n * only a human can fix it). Only the durable class earns the STICKY marker that survives the\n * backgrounded shell-startup spawn and is replayed onto the next interactive command; a durable\n * failure misclassified as transient is TOTAL SILENCE, forever, on the one path the whole feature\n * exists to survive.\n *\n * That classification therefore has to travel WITH the error, not be re-derived by grepping a message\n * some other module owns \u2014 and it has to be throwable from EVERY module that can produce the class.\n * `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned base type\n * could not be thrown there without a layering inversion and an import cycle. Hence a neutral base\n * here in `lib/errors`, with `DopplerAuthError extends EnvAuthError` for the subset of failures that\n * are specifically \"Doppler refused the token we sent\".\n *\n * The defect class this closes is \"a durable failure that is not type-detectable\". Adding a new\n * durable failure and forgetting to type it is exactly how this shipped silent twice \u2014 so throw this\n * (or a subclass), never a plain `Error`, for anything a user must fix before env-load can work.\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * This is the default `isAuthFailure` of `lib/env-autoload`'s `runEnvAutoLoad`. It is deliberately\n * WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only one of the\n * durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store never reaches\n * the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\n\n/**\n * Shared path-display helpers for CLI output. Extracted from `commands/config`\n * and `commands/init/migrate-config` (which each had private copies) so config\n * surfaces print paths consistently. Keep this dependency-light (node builtins\n * only) \u2014 it is imported by several commands.\n */\n\n/**\n * Resolve whether a file is reachable, suppressing ENOENT (and any access error)\n * into a boolean. Used to render `[\u2713]`/`[ ]` existence markers.\n *\n * @example\n * await fileExists('/etc/hosts') // => true\n * await fileExists('/nope.txt') // => false\n */\nexport const fileExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath)\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Replace the user's home prefix with `~` so logged paths stay short and portable\n * across machines. Leaves non-home paths untouched.\n *\n * @example\n * // os.homedir() === '/Users/arthur'\n * tildify('/Users/arthur/.infra-kit/infra-kit.json') // => '~/.infra-kit/infra-kit.json'\n * tildify('/etc/hosts') // => '/etc/hosts'\n */\nexport const tildify = (filePath: string): string => {\n const home = os.homedir()\n\n return filePath.startsWith(home) ? `~${filePath.slice(home.length)}` : filePath\n}\n", "import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the command ran off the CLI (an MCP tool), where a `pnpm exec` line would be\n * nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { isMcpMode } from 'src/lib/mcp-mode'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\nconst ESC_BYTE = 0x1b\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation.\n *\n * The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal\n * goes into the prompt context, `@inquirer/core` rejects with an `AbortPromptError`\n * when it fires, that name is already in `CANCELLATION_ERROR_NAMES`\n * (lib/errors/is-prompt-cancellation), and `entry/cli.ts` catches it at the top\n * level \u2192 \"Operation cancelled.\" \u2192 exit 0. All this adds is the thing that calls\n * `abort()`.\n *\n * DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b`\n * byte. Deliberately NOT readline `keypress`: that delivers a lone Esc only after its\n * escape-sequence timeout (~523ms measured), and the `escapeCodeTimeout` dial that\n * would shorten it is process-global and first-armer-wins \u2014 a second\n * `emitKeypressEvents` call on `process.stdin` is SILENTLY IGNORED, so the dial\n * degrades to a no-op with no error and no failing test. The raw listener costs ~24ms\n * and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n * (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is\n * involved. Node `data` listeners broadcast, so this one does not steal bytes from\n * readline: arrows and Enter keep working while it is attached.\n *\n * FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk.\n * Focus events (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports\n * (`\\x1b[M\u2026`) are all multi-byte, and inquirer enables none of them.\n *\n * FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE\n * chunk, i.e. Esc immediately followed by another key) is silently dropped and the\n * prompt stays open. The fix would be Ink's 20ms deferred abort \u2014 hold the lone Esc,\n * cancel it if a follow-up chunk lands. That is a logged NON-GOAL; do not pre-build it.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a\n * sufficient guard \u2014 see lib/mcp-mode for why `stdio: 'inherit'` defeats it.\n */\nexport const withEscape = async <T>(run: (context: PromptContext) => Promise<T>, base?: PromptContext): Promise<T> => {\n const controller = new AbortController()\n const context: PromptContext = { ...base, signal: controller.signal }\n\n if (isMcpMode() || !process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "import confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\n/**\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise it prompts the user, marks the echo as interactive, and\n * exits cleanly if the user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nexport const confirmOrExit = async (confirmedCommand: boolean | undefined, message: string): Promise<void> => {\n const answer = confirmedCommand\n ? true\n : await withEscape((context) => {\n return confirm({ message }, context)\n })\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n"],
5
- "mappings": "6IAKA,OAAOA,MAAQ,mBACf,OAAOC,MAAU,YACjB,OAAS,KAAAC,MAAS,MCsBX,IAAMC,EAAN,cAA2B,KAAM,CAO7B,IAET,YAAYC,EAAiBC,EAAqB,KAAM,CACtD,MAAMD,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,IAAMC,CACb,CACF,EAgBaC,EAAoBC,GACxBA,aAAiBJ,EC5D1B,OAAOK,MAAQ,mBACf,OAAOC,MAAQ,UAiBR,IAAMC,EAAa,MAAOC,GAAuC,CACtE,GAAI,CACF,aAAMH,EAAG,OAAOG,CAAQ,EAEjB,EACT,MAAQ,CACN,MAAO,EACT,CACF,EAWaC,EAAWD,GAA6B,CACnD,IAAME,EAAOJ,EAAG,QAAQ,EAExB,OAAOE,EAAS,WAAWE,CAAI,EAAI,IAAIF,EAAS,MAAME,EAAK,MAAM,CAAC,GAAKF,CACzE,EFnBA,IAAMG,EAAmB,cAGnBC,EAAsB,EAGtBC,EAAkB,IAGlBC,EAAiB,IAqBjBC,EAAmBC,EACtB,OAAO,CACN,QAASA,EAAE,QAAQJ,CAAmB,EAAE,QAAQA,CAAmB,EACnE,KAAMI,EAAE,OAAOA,EAAE,OAAO,EAAE,IAAI,CAAC,EAAGA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CACrD,CAAC,EACA,OAAO,EAeGC,EAAoB,SAA6B,CAC5D,IAAMC,EAAQ,MAAMC,EAAuB,EAE3C,OAAOC,EAAK,KAAKA,EAAK,QAAQF,EAAM,WAAW,EAAGP,CAAgB,CACpE,EAeaU,EAAiB,SAAwC,CACpE,IAAMC,EAAY,MAAML,EAAkB,EAEtCM,EAEJ,GAAI,CACFA,EAAM,MAAMC,EAAG,SAASF,EAAW,OAAO,CAC5C,MAAQ,CACN,OAAO,IACT,CAOA,IAAIG,EAEJ,G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,IAAMV,GAAUI,EAAW,MAAM,CACpE,EAMAO,EAAa,EAEb,GAAI,CASF,IAAMC,EAAUV,EAAIG,CAAO,EAS3B,OAAIG,EAAM,SAAS,GAAGA,EAAM,OAAO,EAEnCA,EAAM,GAAG,OAAQC,CAAM,EAEhB,MAAMG,CACf,QAAE,CAGAJ,EAAM,eAAe,OAAQC,CAAM,EAGnCI,EAAa,CACf,CACF,ECxGA,OAAOC,MAAa,oBACpB,OAAOC,MAAa,eA+Bb,IAAMC,EAAgB,MAAOC,EAAuCC,IAAmC,CAC5G,IAAMC,EAASF,EACX,GACA,MAAMG,EAAYC,GACTC,EAAQ,CAAE,QAAAJ,CAAQ,EAAGG,CAAO,CACpC,EAEAJ,GACHM,EAAY,eAAe,EAGxBJ,IACHK,EAAO,KAAK,iCAAiC,EAC7CC,EAAQ,KAAK,CAAC,EAElB",
6
- "names": ["fs", "path", "z", "EnvAuthError", "message", "env", "isEnvAuthFailure", "error", "fs", "os", "fileExists", "filePath", "tildify", "home", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs", "createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "process", "ESC_BYTE", "withEscape", "run", "base", "controller", "context", "isMcpMode", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "confirmOrExit", "confirmedCommand", "message", "answer", "withEscape", "context", "confirm", "commandEcho", "logger", "process"]
3
+ "sources": ["../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts", "../src/lib/path-display/path-display.ts", "../src/lib/command-echo/command-echo.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts"],
4
+ "sourcesContent": ["// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n *\n * HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were dropped\n * for it \u2014 do not re-add either without re-deciding that:\n *\n * - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version key,\n * and a store the CLI refuses to read is a store the human cannot write.\n * - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout. That\n * guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so `~/work/api`\n * and `~/oss/api` share ONE token directory and repo B could load (and then overwrite) repo A's\n * credentials. It was removed anyway, knowingly: it also made the CLI refuse every hand-written\n * store, which carries no such field. Hand-authorability wins; the basename-collision risk is\n * ACCEPTED. A weakened version of the guard (warn-and-continue, or \"only check when present\") is\n * NOT the compromise here \u2014 it would re-introduce the same refusal for anyone who did write the\n * field. If you want the guard back, key the store directory on something collision-free instead.\n */\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 it cannot heal on a 30s retry, only a human can fix it \u2014 and env\n // auto-load's sticky marker is keyed on that CLASS. Thrown as a plain Error these were classified\n // TRANSIENT, so a corrupt store went silent on the backgrounded shell-startup spawn and the user's\n // env simply stopped loading with nothing ever said. `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): env auto-load must tell a user\n * apart from a TRANSIENT failure (network, timeout, Doppler down \u2014 heals itself, 30s backoff, stay\n * quiet) and a DURABLE one (no token, a corrupt token store, a foreign token store \u2014 never heals, and\n * only a human can fix it). Only the durable class earns the STICKY marker that survives the\n * backgrounded shell-startup spawn and is replayed onto the next interactive command; a durable\n * failure misclassified as transient is TOTAL SILENCE, forever, on the one path the whole feature\n * exists to survive.\n *\n * That classification therefore has to travel WITH the error, not be re-derived by grepping a message\n * some other module owns \u2014 and it has to be throwable from EVERY module that can produce the class.\n * `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned base type\n * could not be thrown there without a layering inversion and an import cycle. Hence a neutral base\n * here in `lib/errors`, with `DopplerAuthError extends EnvAuthError` for the subset of failures that\n * are specifically \"Doppler refused the token we sent\".\n *\n * The defect class this closes is \"a durable failure that is not type-detectable\". Adding a new\n * durable failure and forgetting to type it is exactly how this shipped silent twice \u2014 so throw this\n * (or a subclass), never a plain `Error`, for anything a user must fix before env-load can work.\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * This is the default `isAuthFailure` of `lib/env-autoload`'s `runEnvAutoLoad`. It is deliberately\n * WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only one of the\n * durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store never reaches\n * the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\n\n/**\n * Shared path-display helpers for CLI output. Extracted from `commands/config`\n * and `commands/init/migrate-config` (which each had private copies) so config\n * surfaces print paths consistently. Keep this dependency-light (node builtins\n * only) \u2014 it is imported by several commands.\n */\n\n/**\n * Resolve whether a file is reachable, suppressing ENOENT (and any access error)\n * into a boolean. Used to render `[\u2713]`/`[ ]` existence markers.\n *\n * @example\n * await fileExists('/etc/hosts') // => true\n * await fileExists('/nope.txt') // => false\n */\nexport const fileExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath)\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Replace the user's home prefix with `~` so logged paths stay short and portable\n * across machines. Leaves non-home paths untouched.\n *\n * @example\n * // os.homedir() === '/Users/arthur'\n * tildify('/Users/arthur/.infra-kit/infra-kit.json') // => '~/.infra-kit/infra-kit.json'\n * tildify('/etc/hosts') // => '/etc/hosts'\n */\nexport const tildify = (filePath: string): string => {\n const home = os.homedir()\n\n return filePath.startsWith(home) ? `~${filePath.slice(home.length)}` : filePath\n}\n", "import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the command ran off the CLI (an MCP tool), where a `pnpm exec` line would be\n * nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { isMcpMode } from 'src/lib/mcp-mode'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\nconst ESC_BYTE = 0x1b\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation.\n *\n * The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal\n * goes into the prompt context, `@inquirer/core` rejects with an `AbortPromptError`\n * when it fires, that name is already in `CANCELLATION_ERROR_NAMES`\n * (lib/errors/is-prompt-cancellation), and `entry/cli.ts` catches it at the top\n * level \u2192 \"Operation cancelled.\" \u2192 exit 0. All this adds is the thing that calls\n * `abort()`.\n *\n * DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b`\n * byte. Deliberately NOT readline `keypress`: that delivers a lone Esc only after its\n * escape-sequence timeout (~523ms measured), and the `escapeCodeTimeout` dial that\n * would shorten it is process-global and first-armer-wins \u2014 a second\n * `emitKeypressEvents` call on `process.stdin` is SILENTLY IGNORED, so the dial\n * degrades to a no-op with no error and no failing test. The raw listener costs ~24ms\n * and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n * (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is\n * involved. Node `data` listeners broadcast, so this one does not steal bytes from\n * readline: arrows and Enter keep working while it is attached.\n *\n * FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk.\n * Focus events (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports\n * (`\\x1b[M\u2026`) are all multi-byte, and inquirer enables none of them.\n *\n * FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE\n * chunk, i.e. Esc immediately followed by another key) is silently dropped and the\n * prompt stays open. The fix would be Ink's 20ms deferred abort \u2014 hold the lone Esc,\n * cancel it if a follow-up chunk lands. That is a logged NON-GOAL; do not pre-build it.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a\n * sufficient guard \u2014 see lib/mcp-mode for why `stdio: 'inherit'` defeats it.\n */\nexport const withEscape = async <T>(run: (context: PromptContext) => Promise<T>, base?: PromptContext): Promise<T> => {\n const controller = new AbortController()\n const context: PromptContext = { ...base, signal: controller.signal }\n\n if (isMcpMode() || !process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "import confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\n/**\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise it prompts the user, marks the echo as interactive, and\n * exits cleanly if the user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nexport interface ConfirmOrExitOptions {\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n const answer = confirmedCommand\n ? true\n : await withEscape((context) => {\n return confirm({ message }, context)\n })\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It exists so a\n * command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n * directory, a lock \u2014 can unwind through its own `finally` blocks and release it,\n * instead of `confirmOrExit` calling `process.exit(0)` and skipping every one of\n * them.\n *\n * That distinction is load-bearing rather than stylistic. In a plan \u2192 confirm \u2192\n * apply design, declining is a *first-class expected outcome*, not an edge case,\n * so the most ordinary non-happy path is exactly the one that would leak.\n *\n * It is also not a prompt cancellation: Esc means \"I never answered\" and already\n * has its own handling. This means \"I answered, and the answer was no.\"\n *\n * Callers that opt in via `throwOnDecline` are responsible for catching it and\n * exiting 0 \u2014 a decline is a successful outcome of the command, not a failure.\n */\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n"],
5
+ "mappings": "8IAKA,OAAOA,MAAQ,mBACf,OAAOC,MAAU,YACjB,OAAS,KAAAC,MAAS,MCsBX,IAAMC,EAAN,cAA2B,KAAM,CAO7B,IAET,YAAYC,EAAiBC,EAAqB,KAAM,CACtD,MAAMD,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,IA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,IAAMC,EAAN,cAAmC,KAAM,CAC9C,YAAYC,EAAU,sCAAuC,CAC3D,MAAMA,CAAO,EACb,KAAK,KAAO,sBACd,CACF,EAGaC,GAAqBC,GACzBA,aAAiBH,EDqBnB,IAAMI,EAAgB,MAC3BC,EACAC,EACAC,EAAgC,CAAC,IACf,CAClB,IAAMC,EAASH,EACX,GACA,MAAMI,EAAYC,GACTC,EAAQ,CAAE,QAAAL,CAAQ,EAAGI,CAAO,CACpC,EAML,GAJKL,GACHO,EAAY,eAAe,EAGzB,CAACJ,EAAQ,CACX,GAAID,EAAQ,eACV,MAAM,IAAIM,EAGZC,EAAO,KAAK,iCAAiC,EAC7CC,EAAQ,KAAK,CAAC,CAChB,CACF",
6
+ "names": ["fs", "path", "z", "EnvAuthError", "message", "env", "isEnvAuthFailure", "error", "fs", "os", "fileExists", "filePath", "tildify", "home", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setToken", "env", "token", "existing", "removeToken", "envs", "createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "process", "ESC_BYTE", "withEscape", "run", "base", "controller", "context", "isMcpMode", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "confirmOrExit", "confirmedCommand", "message", "options", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process"]
7
7
  }
@@ -1,6 +1,6 @@
1
- import p from"node:process";var u=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],f=80,s={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",teal:"\x1B[36m",green:"\x1B[32m",blue:"\x1B[34m",red:"\x1B[31m"},h="\r\x1B[2K",m=/\x1B\[[0-9;]*m|\x1B\]8;;.*?\x1B\\/g,$=o=>o.replace(m,""),l=o=>String(o).padStart(2,"0"),v=o=>`${l(o.getHours())}:${l(o.getMinutes())}:${l(o.getSeconds())}`,x=o=>`${(o/1e3).toFixed(1)}s`,c=o=>{let t=Math.max(0,Math.floor(o/1e3)),e=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return e>0?`${e}h${l(r)}m`:r>0?`${r}m${l(i)}s`:`${i}s`},R=o=>`https://${o.alias}${o.prefixUrl}`,g=class{deps;spinnerTimer=null;spinnerPhase="";spinnerFrame=0;constructor(t={}){this.deps={write:t.write??(e=>{p.stdout.write(e)}),appendLog:t.appendLog??(()=>{}),isTTY:t.isTTY??!!p.stdout.isTTY,now:t.now??(()=>new Date),verbose:t.verbose??!1}}color(t,e){return this.deps.isTTY?`${t}${e}${s.reset}`:e}hyperlink(t,e){return!this.deps.isTTY||t===""?e:`\x1B]8;;file://${encodeURI(t).replace(/[#?]/g,i=>`%${i.charCodeAt(0).toString(16).toUpperCase()}`)}\x1B\\${e}\x1B]8;;\x1B\\`}teeOnly(t,e){this.deps.appendLog(`[${this.deps.now().toISOString()}] [${e.toUpperCase()}] ${$(t)}
2
- `)}tee(t,e){this.teeOnly(t,e)}dispose(){}emit(t){if(this.spinnerTimer!=null&&this.deps.isTTY){this.deps.write(`${h}${t}
1
+ import h from"node:process";var p=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],f=80,s={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",teal:"\x1B[36m",green:"\x1B[32m",blue:"\x1B[34m",red:"\x1B[31m"},d="\r\x1B[2K",m=/\x1B\[[0-9;]*m|\x1B\]8;;.*?\x1B\\/g,$=o=>o.replace(m,""),u=o=>String(o).padStart(2,"0"),v=o=>`${(o/1e3).toFixed(1)}s`,c=o=>{let t=Math.max(0,Math.floor(o/1e3)),e=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return e>0?`${e}h${u(r)}m`:r>0?`${r}m${u(i)}s`:`${i}s`},R=o=>`https://${o.alias}${o.prefixUrl}`,g=class{deps;spinnerTimer=null;spinnerPhase="";spinnerFrame=0;constructor(t={}){this.deps={write:t.write??(e=>{h.stdout.write(e)}),appendLog:t.appendLog??(()=>{}),isTTY:t.isTTY??!!h.stdout.isTTY,now:t.now??(()=>new Date),verbose:t.verbose??!1}}color(t,e){return this.deps.isTTY?`${t}${e}${s.reset}`:e}hyperlink(t,e){return!this.deps.isTTY||t===""?e:`\x1B]8;;file://${encodeURI(t).replace(/[#?]/g,i=>`%${i.charCodeAt(0).toString(16).toUpperCase()}`)}\x1B\\${e}\x1B]8;;\x1B\\`}teeOnly(t,e){this.deps.appendLog(`[${this.deps.now().toISOString()}] [${e.toUpperCase()}] ${$(t)}
2
+ `)}tee(t,e){this.teeOnly(t,e)}dispose(){}emit(t){if(this.spinnerTimer!=null&&this.deps.isTTY){this.deps.write(`${d}${t}
3
3
  `),this.paintSpinner();return}this.deps.write(`${t}
4
- `)}log(t,e="info",r={}){(e!=="debug"||this.deps.verbose)&&this.emit(t),r.tee!==!1&&this.tee(t,e)}narrate(t){this.deps.verbose&&this.emit(t),this.tee(t,"info")}logFn=(t,e="info")=>{this.log(t,e)};paintSpinner(){let t=u[this.spinnerFrame%u.length];this.deps.write(`${h}${this.color(s.teal,t)} ${this.color(s.dim,this.spinnerPhase)}`)}bootStep(t){if(this.tee(t,"info"),this.spinnerPhase=t,!this.deps.isTTY){this.deps.write(`${t}
5
- `);return}this.spinnerTimer==null&&(this.spinnerTimer=setInterval(()=>{this.spinnerFrame+=1,this.paintSpinner()},f),this.spinnerTimer.unref?.()),this.paintSpinner()}stopSpinner(){this.spinnerTimer!=null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null),this.deps.isTTY&&this.deps.write(h)}errorCount(t){let e=`\u26A0 ${t}`;return t>0?this.color(`${s.bold}${s.red}`,e):this.color(s.dim,e)}tagCell(t,e,r){return this.color((r??0)>0?s.red:s.teal,t.padEnd(e))}healthDot(t){switch(t){case"ok":return this.color(s.green,"\u25CF ok");case"down":return this.color(s.red,"\u25CF down");case"starting":return this.color(s.dim,"\u25CC starting");case"unverified":return this.color(s.dim,"\u25CD ?");default:return""}}ready(t){this.stopSpinner();let e=this.formatReadyLines(t);for(let r of e)this.emit(r),this.tee(r,"info")}tagWidth(t){return[...t.endpoints.map(r=>r.tag),...t.uiRefs.map(r=>r.tag),...(t.failed??[]).map(r=>r.tag),...(t.degraded??[]).map(r=>`${r.tag} ${r.route}`)].reduce((r,i)=>Math.max(r,i.length),0)}titleLine(t){let e=[t.target,t.watch?"watch":null,t.release].filter(a=>!!a).join(" \xB7 "),r=t.failed?.length??0,i=x(t.elapsedMs),n=r>0?this.color(s.red,`${r} failed \xB7 started in ${i}`):this.color(s.green,`ready in ${i}`);return` ${this.color(s.bold,"infra-kit dev")} ${this.color(s.dim,e)} ${n}`}legendLines(t){let e=t.watch&&t.watchSummary?`watching ${t.watchSummary}`:"watch off",r=this.hyperlink(t.logHref,t.logPath),i=`${e} logs \u2192 ${r}`,n="\u2500".repeat(60);return[` ${this.color(s.dim,i)}`,` ${this.color(s.dim,n)}`]}uiRefLine(t,e,r){let i=r==null?"":` ${this.errorCount(r)}`;return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.dim,"no managed port (vite prints its own URL)")}${i}`}statusFields(t){let e=[];return t.uptimeMs!=null&&e.push(this.color(s.dim,`up ${c(t.uptimeMs)}`)),t.rpm!=null&&t.rpm>0&&e.push(this.color(s.dim,`${t.rpm}/min`)),t.restarts!=null&&t.restarts>0&&e.push(this.color(s.dim,`\u21BA${t.restarts}`)),t.errors!=null&&e.push(this.errorCount(t.errors)),e.join(" ")}endpointLine(t,e,r){let i=r?this.healthDot(t.health):"",n=this.statusFields(t),a=[i,n].filter(Boolean).join(" ");return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.blue,t.url)}${a?` ${a}`:""}`}failedLine(t,e){return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.red,"\u25CF failed")} ${this.color(s.dim,t.reason)}`}degradedLine(t,e){let r=`${t.tag} ${t.route}`,i=t.fallback==="cloud"?"\u25CF cloud (local backend down)":"\u25CF dead alias (local backend down)",n=t.target?` ${this.color(s.dim,t.target)}`:"";return` ${this.color(s.red,"\u26A0")} ${this.color(s.teal,r.padEnd(e))} ${this.color(s.red,i)}${n}`}proxyLines(t){if(t.length===0)return[];let e=Math.max(...t.map(r=>r.route.length));return t.map((r,i)=>{let n=i===t.length-1?"\u2514":"\u251C",a=r.source==="local"?this.color(s.green,"\u25CF"):this.color(s.dim,"\u25CB"),d=r.target?` ${this.color(s.blue,r.target)}`:"";return` ${this.color(s.dim,n)} ${this.color(s.teal,r.route.padEnd(e))} ${a} ${this.color(s.dim,r.source)}${d}`})}formatLines(t,{withHealthDot:e}){let r=this.tagWidth(t),i=["",this.titleLine(t),""];for(let n of t.endpoints)i.push(this.endpointLine(n,r,e)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.failed??[])i.push(this.failedLine(n,r));for(let n of t.uiRefs)i.push(this.uiRefLine(n,r,n.errors)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.degraded??[])i.push(this.degradedLine(n,r));return i.push("",...this.legendLines(t)),i}formatHeaderLines(t){return this.formatLines(t,{withHealthDot:!1})}formatFooterLines(t){let e=this.tagWidth(t),r=t.endpoints.map(i=>{let n=this.healthDot(i.health),a=this.statusFields(i),d=[n,a].filter(Boolean).join(" ");return` ${this.tagCell(i.tag,e,i.errors)} ${d}`});for(let i of t.uiRefs)i.errors!=null&&r.push(` ${this.tagCell(i.tag,e,i.errors)} ${this.errorCount(i.errors)}`);for(let i of t.degraded??[])r.push(this.degradedLine(i,e));if(t.sessionUptimeMs!=null){let i=`up ${c(t.sessionUptimeMs)}`;r.push(` ${this.color(s.dim,i)}`)}return r}formatReadyLines(t){return this.formatLines(t,{withHealthDot:!0})}event(t){let e=v(this.deps.now()),r=` ${this.color(s.dim,e)} ${this.color(s.teal,t.tag)} ${t.text}`;this.emit(r),this.tee(`${t.tag} ${t.text}`,"info")}};export{v as a,R as b,g as c};
6
- //# sourceMappingURL=chunk-RVTI3AL2.js.map
4
+ `)}log(t,e="info",r={}){(e!=="debug"||this.deps.verbose)&&this.emit(t),r.tee!==!1&&this.tee(t,e)}narrate(t){this.deps.verbose&&this.emit(t),this.tee(t,"info")}logFn=(t,e="info")=>{this.log(t,e)};paintSpinner(){let t=p[this.spinnerFrame%p.length];this.deps.write(`${d}${this.color(s.teal,t)} ${this.color(s.dim,this.spinnerPhase)}`)}bootStep(t){if(this.tee(t,"info"),this.spinnerPhase=t,!this.deps.isTTY){this.deps.write(`${t}
5
+ `);return}this.spinnerTimer==null&&(this.spinnerTimer=setInterval(()=>{this.spinnerFrame+=1,this.paintSpinner()},f),this.spinnerTimer.unref?.()),this.paintSpinner()}stopSpinner(){this.spinnerTimer!=null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null),this.deps.isTTY&&this.deps.write(d)}errorCount(t){let e=`\u26A0 ${t}`;return t>0?this.color(`${s.bold}${s.red}`,e):this.color(s.dim,e)}tagCell(t,e,r){return this.color((r??0)>0?s.red:s.teal,t.padEnd(e))}healthDot(t){switch(t){case"ok":return this.color(s.green,"\u25CF ok");case"down":return this.color(s.red,"\u25CF down");case"starting":return this.color(s.dim,"\u25CC starting");case"unverified":return this.color(s.dim,"\u25CD ?");default:return""}}ready(t){this.stopSpinner();let e=this.formatReadyLines(t);for(let r of e)this.emit(r),this.tee(r,"info")}tagWidth(t){return[...t.endpoints.map(r=>r.tag),...t.uiRefs.map(r=>r.tag),...(t.failed??[]).map(r=>r.tag),...(t.degraded??[]).map(r=>`${r.tag} ${r.route}`)].reduce((r,i)=>Math.max(r,i.length),0)}titleLine(t){let e=[t.target,t.watch?"watch":null,t.release].filter(a=>!!a).join(" \xB7 "),r=t.failed?.length??0,i=v(t.elapsedMs),n=r>0?this.color(s.red,`${r} failed \xB7 started in ${i}`):this.color(s.green,`ready in ${i}`);return` ${this.color(s.bold,"infra-kit dev")} ${this.color(s.dim,e)} ${n}`}legendLines(t){let e=t.watch&&t.watchSummary?`watching ${t.watchSummary}`:"watch off",r=this.hyperlink(t.logHref,t.logPath),i=`${e} logs \u2192 ${r}`,n="\u2500".repeat(60);return[` ${this.color(s.dim,i)}`,` ${this.color(s.dim,n)}`]}uiRefLine(t,e,r){let i=r==null?"":` ${this.errorCount(r)}`;return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.dim,"no managed port (vite prints its own URL)")}${i}`}statusFields(t){let e=[];return t.uptimeMs!=null&&e.push(this.color(s.dim,`up ${c(t.uptimeMs)}`)),t.rpm!=null&&t.rpm>0&&e.push(this.color(s.dim,`${t.rpm}/min`)),t.restarts!=null&&t.restarts>0&&e.push(this.color(s.dim,`\u21BA${t.restarts}`)),t.errors!=null&&e.push(this.errorCount(t.errors)),e.join(" ")}endpointLine(t,e,r){let i=r?this.healthDot(t.health):"",n=this.statusFields(t),a=[i,n].filter(Boolean).join(" ");return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.blue,t.url)}${a?` ${a}`:""}`}failedLine(t,e){return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.red,"\u25CF failed")} ${this.color(s.dim,t.reason)}`}degradedLine(t,e){let r=`${t.tag} ${t.route}`,i=t.fallback==="cloud"?"\u25CF cloud (local backend down)":"\u25CF dead alias (local backend down)",n=t.target?` ${this.color(s.dim,t.target)}`:"";return` ${this.color(s.red,"\u26A0")} ${this.color(s.teal,r.padEnd(e))} ${this.color(s.red,i)}${n}`}proxyLines(t){if(t.length===0)return[];let e=Math.max(...t.map(r=>r.route.length));return t.map((r,i)=>{let n=i===t.length-1?"\u2514":"\u251C",a=r.source==="local"?this.color(s.green,"\u25CF"):this.color(s.dim,"\u25CB"),l=r.target?` ${this.color(s.blue,r.target)}`:"";return` ${this.color(s.dim,n)} ${this.color(s.teal,r.route.padEnd(e))} ${a} ${this.color(s.dim,r.source)}${l}`})}formatLines(t,{withHealthDot:e}){let r=this.tagWidth(t),i=["",this.titleLine(t),""];for(let n of t.endpoints)i.push(this.endpointLine(n,r,e)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.failed??[])i.push(this.failedLine(n,r));for(let n of t.uiRefs)i.push(this.uiRefLine(n,r,n.errors)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.degraded??[])i.push(this.degradedLine(n,r));return i.push("",...this.legendLines(t)),i}formatHeaderLines(t){return this.formatLines(t,{withHealthDot:!1})}formatFooterLines(t){let e=this.tagWidth(t),r=t.endpoints.map(i=>{let n=this.healthDot(i.health),a=this.statusFields(i),l=[n,a].filter(Boolean).join(" ");return` ${this.tagCell(i.tag,e,i.errors)} ${l}`});for(let i of t.uiRefs)i.errors!=null&&r.push(` ${this.tagCell(i.tag,e,i.errors)} ${this.errorCount(i.errors)}`);for(let i of t.degraded??[])r.push(this.degradedLine(i,e));if(t.sessionUptimeMs!=null){let i=`up ${c(t.sessionUptimeMs)}`;r.push(` ${this.color(s.dim,i)}`)}return r}formatReadyLines(t){return this.formatLines(t,{withHealthDot:!0})}};export{R as a,g as b};
6
+ //# sourceMappingURL=chunk-VDBJ73LS.js.map