@lovek4d/kickflip 0.7.7 → 0.8.0

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.
package/bin/install.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var J=Object.defineProperty;var y=(e,s)=>J(e,"name",{value:s,configurable:!0});import r from"node:fs";import v from"node:os";import n from"node:path";import{SKILLS_SOURCE as I,addArgv as D,addCommand as M,missingSkills as K}from"../shared/skills.mjs";import{cloneRoot as O}from"../shared/repos.mjs";import{hubService as q,runCommand as _}from"../shared/service.mjs";import{tailscaleBin as B,tailscaleInstallHint as H}from"../shared/tailscale.mjs";const z="/opt/homebrew/bin/node",P=y((e=process.execPath,s=z)=>e.startsWith("/opt/homebrew/Cellar/")&&r.existsSync(s)?s:e,"nodeBin"),ct=y((e,s,t=O())=>`${P()} ${n.join(t,"bin","wait-events.mjs")} ${e} ${s}`,"watcherCommand");function G(e,{home:s=v.homedir(),skillsDir:t=n.join(s,".claude","skills"),cloneRoot:c=O()}={}){if(typeof e!="string"||!n.isAbsolute(e))return e;const o=n.relative(c,e);if(o===".."||o.startsWith(`..${n.sep}`)||n.isAbsolute(o))return e;const a=n.resolve(t,"kickflip");let i=!1;try{i=r.realpathSync(a)===r.realpathSync(c)}catch{}return i?n.join(a,o):e}y(G,"storedPath");function Q({home:e=v.homedir(),skillsDir:s=n.join(e,".claude","skills"),cloneRoot:t=O()}={}){const c=r.realpathSync(t),o=[["kickflip",c],["kickflip-hooks",n.join(c,"hooks-plugin")]].map(([u,p])=>{if(!r.statSync(p,{throwIfNoEntry:!1})?.isDirectory())throw new Error(`not a directory: ${p}`);const f=u==="kickflip"?p:n.resolve(s,"kickflip","hooks-plugin"),h=n.resolve(s,u),m=r.lstatSync(h,{throwIfNoEntry:!1});let j;if(m){let g;try{g=r.realpathSync(h)}catch(b){if(b.code!=="ENOENT")throw b}m.isSymbolicLink()?g!==r.realpathSync(p)&&(j=`refusing to replace link ${h} -> ${r.readlinkSync(h)}; remove that link explicitly, then rerun kickflip doctor --fix`):(!m.isDirectory()||g!==r.realpathSync(p))&&(j=`refusing to replace real path ${h}; move it aside explicitly, then rerun kickflip doctor --fix`)}return{link:h,target:f,created:!m,...j?{refusal:j}:{}}}),a=n.join(c,"bin","statusline.mjs");if(!r.statSync(a,{throwIfNoEntry:!1})?.isFile())throw new Error(`not a file: ${a}`);const i=n.join(e,".claude","statusline.sh"),S=n.resolve(s,"kickflip","bin","statusline.mjs"),l=r.lstatSync(i,{throwIfNoEntry:!1});let w=!1,k;if(l)if(!l.isSymbolicLink())k=`refusing to replace real path ${i}; move it aside explicitly, then rerun kickflip doctor --fix`;else{let u;try{u=r.realpathSync(i)}catch(m){if(m.code!=="ENOENT")throw m}const p=n.join(e,".claude","kickflip","sites");let f=p;try{f=r.realpathSync(p)}catch{}const h=!!u&&[p,f].some(m=>u.startsWith(m+n.sep));u&&u!==r.realpathSync(a)&&!h&&(k=`refusing to replace link ${i} -> ${r.readlinkSync(i)}; remove that link explicitly, then rerun kickflip doctor --fix`),w=h||n.resolve(n.dirname(i),r.readlinkSync(i))!==S||!u}return o.push({link:i,target:S,created:!l,...w?{replaced:!0}:{},...k?{refusal:k}:{}}),o}y(Q,"inspectLinks");function R({home:e=v.homedir(),skillsDir:s=n.join(e,".claude","skills"),cloneRoot:t=O(),dryRun:c=!1}={}){const o=Q({home:e,skillsDir:s,cloneRoot:t}),a=o.find(i=>i.refusal);if(a)throw new Error(a.refusal);if(c)return o;r.mkdirSync(s,{recursive:!0}),r.mkdirSync(n.join(e,".claude"),{recursive:!0});for(const{link:i,target:S,created:l,replaced:w}of o)w&&r.unlinkSync(i),(l||w)&&r.symlinkSync(S,i,i===n.join(e,".claude","statusline.sh")?"file":"dir");return o}y(R,"installLinks");function V(e,s=v.homedir()){const t=n.join(s,".claude","statusline.sh"),c=[t,`"${t}"`,`'${t.replaceAll("'","'\\''")}'`,"~/.claude/statusline.sh","$HOME/.claude/statusline.sh",'"$HOME/.claude/statusline.sh"',"${HOME}/.claude/statusline.sh",'"${HOME}/.claude/statusline.sh"'];return e?.type==="command"&&c.includes(e.command)}y(V,"ownsStatusLine");const U='node "$HOME/.claude/skills/kickflip/hooks-plugin/hooks/watcher-stop.mjs"',X=y(e=>(Array.isArray(e?.hooks?.Stop)?e.hooks.Stop:[]).some(s=>Array.isArray(s?.hooks)&&s.hooks.some(t=>t?.type==="command"&&/\/hooks-plugin\/hooks\/watcher-stop\.mjs\b/.test(t.command))),"hasWatcherStop");async function Y({port:e=Number(process.env.KICKFLIP_HUB_PORT||4500),fetch:s=globalThis.fetch}={}){try{const t=await s(`http://127.0.0.1:${e}/_hub/status.json`,{signal:AbortSignal.timeout(1500)});if(!t.ok)return null;const c=await t.json();return Array.isArray(c?.sites)?c:null}catch{return null}}y(Y,"hubStatus");function W(e){const s=Object.entries(e?.Web||{}).filter(([t])=>!/:\d+$/.test(t)||t.endsWith(":443")).flatMap(([,t])=>Object.entries(t.Handlers||{}));return{root:s.find(([t])=>t==="/")?.[1]?.Proxy||null,paths:[...new Set(s.map(([t])=>t))]}}y(W,"tailscaleRoot");function lt(e,{run:s=_,platform:t=process.platform,tailscale:c=B({platform:t})}={}){if(!c)throw new Error(`Tailscale isn't installed on this host; ${H(t)}`);const o=s(c,["status","--json"]);let a=null;try{a=o.status===0?JSON.parse(o.stdout):null}catch{}if(a?.BackendState!=="Running")throw new Error("Tailscale isn't running on this host; start it, or run tailscale up");const i=a.Self?.DNSName?.replace(/\.$/,"")||"";if(!i||!a.CertDomains?.includes(i))throw new Error("HTTPS isn't on for this tailnet; turn on HTTPS Certificates on the DNS page of the Tailscale admin console");return`https://${i}/${e?e+"/":""}`}y(lt,"tailnetUrl");async function ut({skipped:e=[],run:s=_,platform:t=process.platform,uid:c=process.getuid(),username:o=v.userInfo().username,port:a=Number(process.env.KICKFLIP_HUB_PORT||4500),tailscale:i=B({platform:t})}={}){const S=y(async $=>{try{return await s(i,$)}catch(d){return{status:1,error:d.message}}},"execute"),l=y($=>{try{return $.status===0?JSON.parse($.stdout):null}catch{return null}},"json"),w=i?await S(["version"]):null,k=w?.status===0,u=k?l(await S(["status","--json"])):null,p=u?.BackendState==="Running",f=u?.Self?.DNSName?.replace(/\.$/,"")||"",h=k&&t==="linux"&&c!==0,m=h?l(await S(["debug","prefs"]))?.OperatorUser:null,j=k?l(await S(["serve","status","--json"])):null,g=W(j);let b=!1;try{const $=new URL(g.root);b=$.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes($.hostname)&&Number($.port)===a&&$.pathname==="/"&&!$.search&&!$.hash}catch{}const E=y(($,d,x,T,A="yours")=>({item:$,state:d?"ok":A,detail:x,fix:d?null:T}),"entry"),N=[E("Tailscale",k,k?`${(w.stdout||"installed").trim().split(`
2
- `)[0]} (${i})${e.length?`; skipped ${e.join(", ")}, whose daemon${e.length===1?" isn\u2019t":"s aren\u2019t"} running`:""}`:`not on this session\u2019s PATH${t==="darwin"?" or in Applications":""}`,H(t)),E("Tailscale signed in",p,p?`signed in${f?" as "+f:""}`:k?"not connected":"needs Tailscale","tailscale up")];h&&N.push(E("Tailscale operator",m===o,m===o?o:`${m||"none"} (expected ${o})`,"sudo tailscale set --operator=$USER"));const C=g.paths.filter($=>$!=="/"),L=E("tailscale /",b,`${g.root||"nothing"}${b?"":` (expected the hub on ${a})`}${C.length?"; other mounts: "+C.join(", "):""}`,p?"kickflip doctor --fix":k?"tailscale up":H(t),p?"fixable":"yours");return{installed:k,signedIn:p,dns:f,operatorChecked:h,operator:m,username:o,pointsAtHub:b,prereqs:N,root:L,serveConfig:j}}y(ut,"tailscaleState");async function dt({home:e=v.homedir(),cloneRoot:s=O(),port:t=Number(process.env.KICKFLIP_HUB_PORT||4500),uid:c=process.getuid(),env:o=process.env,run:a=_,platform:i=process.platform,tailscale:S=B({env:o,platform:i}),wait:l=y(p=>new Promise(f=>setTimeout(f,p)),"wait"),fetch:w=globalThis.fetch,dryRun:k=!1,log:u=console.log}={}){const p=n.join(e,".claude","kickflip"),f=q({platform:i,home:e,uid:c,env:o,run:a});if(k){try{for(const{link:x,target:T,created:A,replaced:F}of R({home:e,cloneRoot:s,dryRun:k}))u(`would ${A||F?"link":"check"} ${x} -> ${T}`)}catch(x){u(`would refuse: ${x.message}`)}u(`would merge statusLine and the watcher Stop hook, turn on autoCompactEnabled and remove stale hooks in ${n.join(e,".claude","settings.json")}`);const d=K(e);d.length&&u(`would add ${d.join(", ")} from ${I} with ${M(d)}`);for(const x of await f.install(null,{wait:l,dryRun:k}))u(x);u(`would map tailscale / to the hub on ${t} and remove old site mounts`);return}for(const{link:d,target:x,created:T,replaced:A}of R({home:e,cloneRoot:s}))u(`${T||A?"linked":"checked"} ${d} -> ${x}`);for(const d of Z({home:e}))u(d);const h=K(e);if(h.length){const d=a("npx",D(h),{env:o,timeout:3e5});u(d.status===0?`added ${h.join(", ")} from ${I}`:`could not add ${h.join(", ")} from ${I}: ${d.error}; run ${M(h)}`)}const m=P(),j=G(n.join(s,"hub","hub.mjs"),{home:e,cloneRoot:s});r.mkdirSync(p,{recursive:!0});const g=n.join(p,"hub.log"),b=f.definition({node:m,entry:j,state:p,port:t,log:g});for(const d of await f.install(b,{wait:l}))u(d);let E=!1;for(let d=0;d<30&&!E;d++)await l(300),E=!!await Y({port:t,fetch:w});if(!E)throw new Error("hub did not start; see "+g);if(!S)return u(`skipped mapping tailscale / to the hub: Tailscale isn't installed on this host; ${H(i)}`);const N=a(S,["serve","--bg",String(t)],{env:o});if(N.status!==0)throw new Error(N.error||"tailscale serve failed");const C=a(S,["serve","status","--json"],{env:o});let L;try{L=JSON.parse(C.stdout)}catch{return}let $={};try{$=JSON.parse(r.readFileSync(n.join(p,"manifest.json"),"utf8")).sites||{}}catch(d){if(d.code!=="ENOENT")throw d}for(const d of W(L).paths)d!=="/"&&Object.hasOwn($,d.replace(/^\//,"").replace(/\/$/,""))&&a(S,["serve","--https=443","--set-path="+d,"off"],{env:o})}y(dt,"runInstall");function Z({home:e=v.homedir()}={}){const s=n.join(e,".claude","settings.json");let t={},c=384;try{t=JSON.parse(r.readFileSync(s,"utf8")),c=r.statSync(s).mode}catch(l){if(l.code!=="ENOENT")throw l}if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`not a settings object: ${s}`);const o=[];let a=!1;const i=n.join(e,".claude","statusline.sh");if(Object.hasOwn(t,"statusLine"))V(t.statusLine,e)||o.push(`kept existing statusLine in ${s}; it points elsewhere`);else{const l=/^[\w/.-]+$/.test(i)?i:`'${i.replaceAll("'","'\\''")}'`;t.statusLine={type:"command",command:l},a=!0,o.push(`set statusLine in ${s} -> ${l}`)}if(!X(t)){const l=t.hooks&&typeof t.hooks=="object"?t.hooks:{};t.hooks={...l,Stop:[...Array.isArray(l.Stop)?l.Stop:[],{hooks:[{type:"command",command:U}]}]},a=!0,o.push(`added the watcher Stop hook to ${s} -> ${U}`)}t.autoCompactEnabled!==!0&&(t.autoCompactEnabled=!0,a=!0,o.push(`turned on autoCompactEnabled in ${s}`));const S=n.join(e,".claude","hooks","no-paths.py");if(!r.existsSync(S)&&t.hooks&&typeof t.hooks=="object"){const l=y(u=>u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escape"),w=[S,"~/.claude/hooks/no-paths.py","$HOME/.claude/hooks/no-paths.py","${HOME}/.claude/hooks/no-paths.py"].map(l).join("|"),k=new RegExp(`^\\s*(?:exec\\s+)?(?:(?:/usr/bin/env\\s+)?(?:[^\\s]+/)?python(?:\\d+(?:\\.\\d+)*)?(?:\\s+-[^\\s]+)*\\s+)?(?:"(?:${w})"|'(?:${w})'|(?:${w}))(?=$|\\s)`);for(const[u,p]of Object.entries(t.hooks))Array.isArray(p)&&(t.hooks[u]=p.flatMap(f=>{if(!Array.isArray(f?.hooks))return[f];const h=f.hooks.filter(m=>m?.type!=="command"||typeof m.command!="string"||!k.test(m.command)?!0:(o.push(`removed stale hook ${u}: ${m.command}`),a=!0,!1));return h.length===f.hooks.length?[f]:h.length?[{...f,hooks:h}]:[]}))}if(a){r.mkdirSync(n.dirname(s),{recursive:!0});const l=`${s}.${process.pid}.${Date.now()}.tmp`;try{r.writeFileSync(l,JSON.stringify(t,null,2)+`
3
- `,{mode:c,flag:"wx"}),r.renameSync(l,s)}finally{try{r.unlinkSync(l)}catch{}}}return o}y(Z,"installClaudeSettings");function pt({home:e=v.homedir(),skillsDir:s=n.join(e,".claude","skills"),cloneRoot:t=O()}={}){const c=n.join(e,".claude","statusline.sh");if(!r.lstatSync(c,{throwIfNoEntry:!1})?.isSymbolicLink())return!1;let a=n.resolve(n.dirname(c),r.readlinkSync(c))===n.resolve(s,"kickflip","bin","statusline.mjs");try{a||=r.realpathSync(c)===r.realpathSync(n.join(t,"bin","statusline.mjs"))}catch{}return a?(r.unlinkSync(c),!0):!1}y(pt,"uninstallStatusLine");export{U as WATCHER_STOP,X as hasWatcherStop,Y as hubStatus,Q as inspectLinks,Z as installClaudeSettings,R as installLinks,P as nodeBin,V as ownsStatusLine,dt as runInstall,G as storedPath,lt as tailnetUrl,W as tailscaleRoot,ut as tailscaleState,pt as uninstallStatusLine,ct as watcherCommand};
1
+ var D=Object.defineProperty;var y=(e,s)=>D(e,"name",{value:s,configurable:!0});import r from"node:fs";import v from"node:os";import n from"node:path";import{SKILLS_SOURCE as I,addArgv as q,addCommand as M,missingSkills as R}from"../shared/skills.mjs";import{cloneRoot as O}from"../shared/repos.mjs";import{hubService as z,runCommand as _}from"../shared/service.mjs";import{tailscaleBin as B,tailscaleInstallHint as H}from"../shared/tailscale.mjs";const K="/opt/homebrew/bin/node",P=y((e=process.execPath,s=K)=>e.startsWith("/opt/homebrew/Cellar/")&&r.existsSync(s)?s:e,"nodeBin"),G=/\/opt\/homebrew\/Cellar\/node\/[^/\s"'<>:]+\/bin(\/node)?(?![^/\s"'<>:])/g,lt=y((e,s=K)=>r.existsSync(s)?e.replace(G,(t,c)=>c?s:n.dirname(s)):e,"relinkCellarNode"),ut=y((e,s,t=O())=>`${P()} ${n.join(t,"bin","wait-events.mjs")} ${e} ${s}`,"watcherCommand");function Q(e,{home:s=v.homedir(),skillsDir:t=n.join(s,".claude","skills"),cloneRoot:c=O()}={}){if(typeof e!="string"||!n.isAbsolute(e))return e;const o=n.relative(c,e);if(o===".."||o.startsWith(`..${n.sep}`)||n.isAbsolute(o))return e;const a=n.resolve(t,"kickflip");let i=!1;try{i=r.realpathSync(a)===r.realpathSync(c)}catch{}return i?n.join(a,o):e}y(Q,"storedPath");function V({home:e=v.homedir(),skillsDir:s=n.join(e,".claude","skills"),cloneRoot:t=O()}={}){const c=r.realpathSync(t),o=[["kickflip",c],["kickflip-hooks",n.join(c,"hooks-plugin")]].map(([u,p])=>{if(!r.statSync(p,{throwIfNoEntry:!1})?.isDirectory())throw new Error(`not a directory: ${p}`);const f=u==="kickflip"?p:n.resolve(s,"kickflip","hooks-plugin"),h=n.resolve(s,u),m=r.lstatSync(h,{throwIfNoEntry:!1});let j;if(m){let g;try{g=r.realpathSync(h)}catch(b){if(b.code!=="ENOENT")throw b}m.isSymbolicLink()?g!==r.realpathSync(p)&&(j=`refusing to replace link ${h} -> ${r.readlinkSync(h)}; remove that link explicitly, then rerun kickflip doctor --fix`):(!m.isDirectory()||g!==r.realpathSync(p))&&(j=`refusing to replace real path ${h}; move it aside explicitly, then rerun kickflip doctor --fix`)}return{link:h,target:f,created:!m,...j?{refusal:j}:{}}}),a=n.join(c,"bin","statusline.mjs");if(!r.statSync(a,{throwIfNoEntry:!1})?.isFile())throw new Error(`not a file: ${a}`);const i=n.join(e,".claude","statusline.sh"),S=n.resolve(s,"kickflip","bin","statusline.mjs"),l=r.lstatSync(i,{throwIfNoEntry:!1});let w=!1,k;if(l)if(!l.isSymbolicLink())k=`refusing to replace real path ${i}; move it aside explicitly, then rerun kickflip doctor --fix`;else{let u;try{u=r.realpathSync(i)}catch(m){if(m.code!=="ENOENT")throw m}const p=n.join(e,".claude","kickflip","sites");let f=p;try{f=r.realpathSync(p)}catch{}const h=!!u&&[p,f].some(m=>u.startsWith(m+n.sep));u&&u!==r.realpathSync(a)&&!h&&(k=`refusing to replace link ${i} -> ${r.readlinkSync(i)}; remove that link explicitly, then rerun kickflip doctor --fix`),w=h||n.resolve(n.dirname(i),r.readlinkSync(i))!==S||!u}return o.push({link:i,target:S,created:!l,...w?{replaced:!0}:{},...k?{refusal:k}:{}}),o}y(V,"inspectLinks");function U({home:e=v.homedir(),skillsDir:s=n.join(e,".claude","skills"),cloneRoot:t=O(),dryRun:c=!1}={}){const o=V({home:e,skillsDir:s,cloneRoot:t}),a=o.find(i=>i.refusal);if(a)throw new Error(a.refusal);if(c)return o;r.mkdirSync(s,{recursive:!0}),r.mkdirSync(n.join(e,".claude"),{recursive:!0});for(const{link:i,target:S,created:l,replaced:w}of o)w&&r.unlinkSync(i),(l||w)&&r.symlinkSync(S,i,i===n.join(e,".claude","statusline.sh")?"file":"dir");return o}y(U,"installLinks");function X(e,s=v.homedir()){const t=n.join(s,".claude","statusline.sh"),c=[t,`"${t}"`,`'${t.replaceAll("'","'\\''")}'`,"~/.claude/statusline.sh","$HOME/.claude/statusline.sh",'"$HOME/.claude/statusline.sh"',"${HOME}/.claude/statusline.sh",'"${HOME}/.claude/statusline.sh"'];return e?.type==="command"&&c.includes(e.command)}y(X,"ownsStatusLine");const W='node "$HOME/.claude/skills/kickflip/hooks-plugin/hooks/watcher-stop.mjs"',Y=y(e=>(Array.isArray(e?.hooks?.Stop)?e.hooks.Stop:[]).some(s=>Array.isArray(s?.hooks)&&s.hooks.some(t=>t?.type==="command"&&/\/hooks-plugin\/hooks\/watcher-stop\.mjs\b/.test(t.command))),"hasWatcherStop");async function Z({port:e=Number(process.env.KICKFLIP_HUB_PORT||4500),fetch:s=globalThis.fetch}={}){try{const t=await s(`http://127.0.0.1:${e}/_hub/status.json`,{signal:AbortSignal.timeout(1500)});if(!t.ok)return null;const c=await t.json();return Array.isArray(c?.sites)?c:null}catch{return null}}y(Z,"hubStatus");function F(e){const s=Object.entries(e?.Web||{}).filter(([t])=>!/:\d+$/.test(t)||t.endsWith(":443")).flatMap(([,t])=>Object.entries(t.Handlers||{}));return{root:s.find(([t])=>t==="/")?.[1]?.Proxy||null,paths:[...new Set(s.map(([t])=>t))]}}y(F,"tailscaleRoot");function dt(e,{run:s=_,platform:t=process.platform,tailscale:c=B({platform:t})}={}){if(!c)throw new Error(`Tailscale isn't installed on this host; ${H(t)}`);const o=s(c,["status","--json"]);let a=null;try{a=o.status===0?JSON.parse(o.stdout):null}catch{}if(a?.BackendState!=="Running")throw new Error("Tailscale isn't running on this host; start it, or run tailscale up");const i=a.Self?.DNSName?.replace(/\.$/,"")||"";if(!i||!a.CertDomains?.includes(i))throw new Error("HTTPS isn't on for this tailnet; turn on HTTPS Certificates on the DNS page of the Tailscale admin console");return`https://${i}/${e?e+"/":""}`}y(dt,"tailnetUrl");async function pt({skipped:e=[],run:s=_,platform:t=process.platform,uid:c=process.getuid(),username:o=v.userInfo().username,port:a=Number(process.env.KICKFLIP_HUB_PORT||4500),tailscale:i=B({platform:t})}={}){const S=y(async $=>{try{return await s(i,$)}catch(d){return{status:1,error:d.message}}},"execute"),l=y($=>{try{return $.status===0?JSON.parse($.stdout):null}catch{return null}},"json"),w=i?await S(["version"]):null,k=w?.status===0,u=k?l(await S(["status","--json"])):null,p=u?.BackendState==="Running",f=u?.Self?.DNSName?.replace(/\.$/,"")||"",h=k&&t==="linux"&&c!==0,m=h?l(await S(["debug","prefs"]))?.OperatorUser:null,j=k?l(await S(["serve","status","--json"])):null,g=F(j);let b=!1;try{const $=new URL(g.root);b=$.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes($.hostname)&&Number($.port)===a&&$.pathname==="/"&&!$.search&&!$.hash}catch{}const E=y(($,d,x,A,T="yours")=>({item:$,state:d?"ok":T,detail:x,fix:d?null:A}),"entry"),N=[E("Tailscale",k,k?`${(w.stdout||"installed").trim().split(`
2
+ `)[0]} (${i})${e.length?`; skipped ${e.join(", ")}, whose daemon${e.length===1?" isn\u2019t":"s aren\u2019t"} running`:""}`:`not on this session\u2019s PATH${t==="darwin"?" or in Applications":""}`,H(t)),E("Tailscale signed in",p,p?`signed in${f?" as "+f:""}`:k?"not connected":"needs Tailscale","tailscale up")];h&&N.push(E("Tailscale operator",m===o,m===o?o:`${m||"none"} (expected ${o})`,"sudo tailscale set --operator=$USER"));const C=g.paths.filter($=>$!=="/"),L=E("tailscale /",b,`${g.root||"nothing"}${b?"":` (expected the hub on ${a})`}${C.length?"; other mounts: "+C.join(", "):""}`,p?"kickflip doctor --fix":k?"tailscale up":H(t),p?"fixable":"yours");return{installed:k,signedIn:p,dns:f,operatorChecked:h,operator:m,username:o,pointsAtHub:b,prereqs:N,root:L,serveConfig:j}}y(pt,"tailscaleState");async function ht({home:e=v.homedir(),cloneRoot:s=O(),port:t=Number(process.env.KICKFLIP_HUB_PORT||4500),uid:c=process.getuid(),env:o=process.env,run:a=_,platform:i=process.platform,tailscale:S=B({env:o,platform:i}),wait:l=y(p=>new Promise(f=>setTimeout(f,p)),"wait"),fetch:w=globalThis.fetch,dryRun:k=!1,log:u=console.log}={}){const p=n.join(e,".claude","kickflip"),f=z({platform:i,home:e,uid:c,env:o,run:a});if(k){try{for(const{link:x,target:A,created:T,replaced:J}of U({home:e,cloneRoot:s,dryRun:k}))u(`would ${T||J?"link":"check"} ${x} -> ${A}`)}catch(x){u(`would refuse: ${x.message}`)}u(`would merge statusLine and the watcher Stop hook, turn on autoCompactEnabled and remove stale hooks in ${n.join(e,".claude","settings.json")}`);const d=R(e);d.length&&u(`would add ${d.join(", ")} from ${I} with ${M(d)}`);for(const x of await f.install(null,{wait:l,dryRun:k}))u(x);u(`would map tailscale / to the hub on ${t} and remove old site mounts`);return}for(const{link:d,target:x,created:A,replaced:T}of U({home:e,cloneRoot:s}))u(`${A||T?"linked":"checked"} ${d} -> ${x}`);for(const d of tt({home:e}))u(d);const h=R(e);if(h.length){const d=a("npx",q(h),{env:o,timeout:3e5});u(d.status===0?`added ${h.join(", ")} from ${I}`:`could not add ${h.join(", ")} from ${I}: ${d.error}; run ${M(h)}`)}const m=P(),j=Q(n.join(s,"hub","hub.mjs"),{home:e,cloneRoot:s});r.mkdirSync(p,{recursive:!0});const g=n.join(p,"hub.log"),b=f.definition({node:m,entry:j,state:p,port:t,log:g});for(const d of await f.install(b,{wait:l}))u(d);let E=!1;for(let d=0;d<30&&!E;d++)await l(300),E=!!await Z({port:t,fetch:w});if(!E)throw new Error("hub did not start; see "+g);if(!S)return u(`skipped mapping tailscale / to the hub: Tailscale isn't installed on this host; ${H(i)}`);const N=a(S,["serve","--bg",String(t)],{env:o});if(N.status!==0)throw new Error(N.error||"tailscale serve failed");const C=a(S,["serve","status","--json"],{env:o});let L;try{L=JSON.parse(C.stdout)}catch{return}let $={};try{$=JSON.parse(r.readFileSync(n.join(p,"manifest.json"),"utf8")).sites||{}}catch(d){if(d.code!=="ENOENT")throw d}for(const d of F(L).paths)d!=="/"&&Object.hasOwn($,d.replace(/^\//,"").replace(/\/$/,""))&&a(S,["serve","--https=443","--set-path="+d,"off"],{env:o})}y(ht,"runInstall");function tt({home:e=v.homedir()}={}){const s=n.join(e,".claude","settings.json");let t={},c=384;try{t=JSON.parse(r.readFileSync(s,"utf8")),c=r.statSync(s).mode}catch(l){if(l.code!=="ENOENT")throw l}if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`not a settings object: ${s}`);const o=[];let a=!1;const i=n.join(e,".claude","statusline.sh");if(Object.hasOwn(t,"statusLine"))X(t.statusLine,e)||o.push(`kept existing statusLine in ${s}; it points elsewhere`);else{const l=/^[\w/.-]+$/.test(i)?i:`'${i.replaceAll("'","'\\''")}'`;t.statusLine={type:"command",command:l},a=!0,o.push(`set statusLine in ${s} -> ${l}`)}if(!Y(t)){const l=t.hooks&&typeof t.hooks=="object"?t.hooks:{};t.hooks={...l,Stop:[...Array.isArray(l.Stop)?l.Stop:[],{hooks:[{type:"command",command:W}]}]},a=!0,o.push(`added the watcher Stop hook to ${s} -> ${W}`)}t.autoCompactEnabled!==!0&&(t.autoCompactEnabled=!0,a=!0,o.push(`turned on autoCompactEnabled in ${s}`));const S=n.join(e,".claude","hooks","no-paths.py");if(!r.existsSync(S)&&t.hooks&&typeof t.hooks=="object"){const l=y(u=>u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escape"),w=[S,"~/.claude/hooks/no-paths.py","$HOME/.claude/hooks/no-paths.py","${HOME}/.claude/hooks/no-paths.py"].map(l).join("|"),k=new RegExp(`^\\s*(?:exec\\s+)?(?:(?:/usr/bin/env\\s+)?(?:[^\\s]+/)?python(?:\\d+(?:\\.\\d+)*)?(?:\\s+-[^\\s]+)*\\s+)?(?:"(?:${w})"|'(?:${w})'|(?:${w}))(?=$|\\s)`);for(const[u,p]of Object.entries(t.hooks))Array.isArray(p)&&(t.hooks[u]=p.flatMap(f=>{if(!Array.isArray(f?.hooks))return[f];const h=f.hooks.filter(m=>m?.type!=="command"||typeof m.command!="string"||!k.test(m.command)?!0:(o.push(`removed stale hook ${u}: ${m.command}`),a=!0,!1));return h.length===f.hooks.length?[f]:h.length?[{...f,hooks:h}]:[]}))}if(a){r.mkdirSync(n.dirname(s),{recursive:!0});const l=`${s}.${process.pid}.${Date.now()}.tmp`;try{r.writeFileSync(l,JSON.stringify(t,null,2)+`
3
+ `,{mode:c,flag:"wx"}),r.renameSync(l,s)}finally{try{r.unlinkSync(l)}catch{}}}return o}y(tt,"installClaudeSettings");function ft({home:e=v.homedir(),skillsDir:s=n.join(e,".claude","skills"),cloneRoot:t=O()}={}){const c=n.join(e,".claude","statusline.sh");if(!r.lstatSync(c,{throwIfNoEntry:!1})?.isSymbolicLink())return!1;let a=n.resolve(n.dirname(c),r.readlinkSync(c))===n.resolve(s,"kickflip","bin","statusline.mjs");try{a||=r.realpathSync(c)===r.realpathSync(n.join(t,"bin","statusline.mjs"))}catch{}return a?(r.unlinkSync(c),!0):!1}y(ft,"uninstallStatusLine");export{W as WATCHER_STOP,Y as hasWatcherStop,Z as hubStatus,V as inspectLinks,tt as installClaudeSettings,U as installLinks,P as nodeBin,X as ownsStatusLine,lt as relinkCellarNode,ht as runInstall,Q as storedPath,dt as tailnetUrl,F as tailscaleRoot,pt as tailscaleState,ft as uninstallStatusLine,ut as watcherCommand};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- var W=Object.defineProperty;var l=(e,r)=>W(e,"name",{value:r,configurable:!0});import d from"node:fs";import g from"node:path";import _ from"node:os";import{routeRecord as m}from"../hub/routes.mjs";import{readHubRules as K,rulesOf as Q,ruleLines as B}from"../hub/rules.mjs";import{boardAt as C,linksOf as M,hubLink as z,stopPreviousWatcher as V}from"../hub/boards.mjs";import{parentOf as I,sessionGone as X}from"../hub/live.mjs";import{ackPing as Y,cardName as Z,markWorking as ee,settingsLines as te,settingsOf as ne,WORKING_KINDS as ie}from"../board/store.mjs";import{readUsageGate as L,heldUsageEvent as se,pausedLine as re}from"../shared/usage-gate.mjs";import{recordOnly as $,PLAIN as T,ON_CARD as q}from"./event-lines.mjs";const[j,O]=process.argv.slice(2);(!j||!O)&&(console.error("usage: wait-events.mjs <route> <session-id>"),process.exit(2));const oe=g.join(_.homedir(),".claude","kickflip","manifest.json");function P(){try{return m(JSON.parse(d.readFileSync(oe,"utf8")).sites,j)||null}catch{return}}l(P,"site");function v(e){const r=e.filter?new RegExp(e.filter):null,t=Object.create(null);for(const c of e.watch||["data/events.jsonl"]){let f=[];try{f=d.readFileSync(g.resolve(e.dir,c),"utf8").split(`
3
- `).filter(Boolean)}catch{}t[c]=r?f.filter(h=>r.test(h)):f}return t}l(v,"matching");const ce=`quiet The owner doesn't read this session's terminal. Answer a prompt typed in it in full. A wake, a task notification or a builder's result is not one: write no text of your own, since board.mjs and this watcher print one line for each thing done. Talk and questions go on the board, never AskUserQuestion; only a failure the board can't show, such as the hub being down, gets one line here. Each message to the owner stands alone in its card's thread: name cards by label (#96), and a pointer such as "above" or "here" must make sense in that thread, never point into this session.`,ae=l(e=>{try{return JSON.parse(e)}catch{return null}},"parsed");function R(e){try{return JSON.parse(d.readFileSync(g.resolve(e.dir,"board.json"),"utf8"))}catch(r){return r.code==="ENOENT"?null:{}}}l(R,"boardOf");async function D(e,r){for(const t of r){let c;try{c=JSON.parse(t)}catch{continue}(c.kind==="ping"||c.kind==="hello")&&typeof c.id=="string"&&await Y(e,c.id).catch(f=>console.log(`ping ${c.id} not answered (${f.message})`))}}l(D,"ackPings");async function le(e,r){let t;try{t=JSON.parse(r)}catch{return null}if(typeof t?.kind!="string")return null;const c=typeof t.data?.key=="string"?t.data.key:t.kind.startsWith("ask-")&&typeof t.data?.id=="string"?`ask:${t.data.id}`:t.kind==="ask"?`ask:${t.id}`:null,f=c&&await Z(e,c).catch(()=>c);return m(T,t.kind)?T[t.kind](t):f&&m(q,t.kind)?q[t.kind](f,t):f?`${t.kind} on ${f}`:`${t.kind} received`}l(le,"plainLine");function de(e){let r=[];try{r=JSON.parse(d.readFileSync(g.resolve(e,"data","orchestrator-waits.json"),"utf8")).waits||[]}catch{}return r.map(t=>`waits ${t.kind} ${t.ref} ${t.key}${t.bumpedAt?" bumped":""} since ${t.since}${t.picked?`, picked up ${t.picked}`:""}: ${t.next}`)}l(de,"waitLines");const b=P();b||(console.log("site-removed"),process.exit(0));const k=g.resolve(b.dir,"data",`.watch-cursor-${O}.json`),N=g.resolve(b.dir,"data","watcher.json"),E=[process.ppid,I(process.ppid)],G=l(()=>{E[1]??=I(E[0]),X(O,E)&&process.exit(0)},"orphaned");V(b.dir,j,O);try{d.mkdirSync(g.dirname(k),{recursive:!0}),d.writeFileSync(N,JSON.stringify({pid:process.pid,since:new Date().toISOString()}))}catch{}process.on("exit",()=>{try{const e=JSON.parse(d.readFileSync(N,"utf8"));e.pid===process.pid&&d.writeFileSync(N,JSON.stringify({...e,exited_at:new Date().toISOString()}))}catch{}});let a;try{a=JSON.parse(d.readFileSync(k,"utf8"))}catch{}for(a||(a=Object.fromEntries(Object.entries(v(b)).map(([e,r])=>[e,r.length])),d.mkdirSync(g.dirname(k),{recursive:!0}),d.writeFileSync(k,JSON.stringify(a)));;){await new Promise(n=>setTimeout(n,2e3));const e=P();if(e===void 0)continue;e===null&&(console.log("site-removed"),process.exit(0)),e.owner?.session&&e.owner.session!==O&&(console.log("handed-over "+JSON.stringify(e.owner)),process.exit(0)),G();const r=l(n=>Object.fromEntries(Object.entries(n).map(([s,i])=>[s,[...m(a.$quietHeld,s)||[],...m(a.$usageHeld,s)||[],...i.slice(m(a,s)||0)]])),"pending"),t=l((n,s)=>s.state!=="paused"||!se(n),"eligible"),c=l((n,s)=>Object.values(n).some(i=>i.some(o=>t(o,s)&&!$(o))),"wakes"),f=L({dir:e.dir}),h=v(e);if(!c(r(h),f)){const n=Object.fromEntries(Object.entries(h).map(([i,o])=>[i,o.slice(m(a,i)||0).filter($)])),s=Object.fromEntries(Object.entries(h).map(([i,o])=>[i,o.slice(m(a,i)||0).filter(u=>!$(u))]));if(Object.values(n).some(i=>i.length)){R(e)&&await D(e.dir,Object.values(n).flat());const i=l((o,u)=>Object.fromEntries(Object.keys(h).map(S=>[S,[...m(o,S)||[],...u[S]]])),"append");a={...Object.fromEntries(Object.entries(h).map(([o,u])=>[o,u.length])),$quietHeld:i(a.$quietHeld,n),$usageHeld:i(a.$usageHeld,s)},Object.values(a.$usageHeld).some(o=>o.length)||delete a.$usageHeld,d.writeFileSync(k,JSON.stringify(a))}continue}await new Promise(n=>setTimeout(n,2e3)),G();const F=v(e),y=L({dir:e.dir}),J=r(F);if(!c(J,y))continue;const w=Object.create(null),x=[],U=new Set(Object.values(a.$quietHeld||{}).flat()),H=[];for(const[n,s]of Object.entries(J)){w[n]=s.filter(i=>!t(i,y));for(const i of s.filter(o=>t(o,y))){U.has(i)||H.push(i),console.log(`event ${n} ${i}`);const o=await le(e.dir,i);o&&console.log(o);const u=ae(i);u&&ie.includes(u.kind)&&typeof u.id=="string"&&x.push(u.id)}}const p=R(e);if(p&&await ee(e.dir,x).catch(n=>console.log(`working marks not written (${n.message})`)),p&&await D(e.dir,H),p)for(const n of de(e.dir))console.log(n);if(p)for(const n of B(K(),Q(p)))console.log(`rule ${n}`);if(p)for(const n of te(ne(p)))console.log(n);p&&console.log(ce),y.state==="paused"&&console.log(re(y));try{const n=p&&C(e.dir);if(n)for(const s of[...M(n,{listen:"listening"}),z()])s.ok||console.log(`link ${s.link} ${s.detail}`)}catch(n){console.log(`link registry could not check the links (${n.message})`)}const A=Object.fromEntries(Object.entries(F).map(([n,s])=>[n,s.length]));Object.values(w).some(n=>n.length)&&(A.$usageHeld=w),d.writeFileSync(k,JSON.stringify(A)),process.exit(0)}
2
+ var D=Object.defineProperty;var d=(e,r)=>D(e,"name",{value:r,configurable:!0});import a from"node:fs";import p from"node:path";import W from"node:os";import{routeRecord as h}from"../hub/routes.mjs";import{readHubRules as K,rulesOf as Q,ruleLines as _}from"../hub/rules.mjs";import{boardAt as B,linksOf as M,hubLink as z,stopPreviousWatcher as C}from"../hub/boards.mjs";import{parentOf as A,sessionGone as V}from"../hub/live.mjs";import{ackPing as X,markWorking as Y,settingsLines as Z,settingsOf as ee,WORKING_KINDS as te}from"../board/store.mjs";import{readUsageGate as I,heldUsageEvent as se,pausedLine as ne}from"../shared/usage-gate.mjs";import{recordOnly as j,plainLine as ie,shownFile as oe}from"./event-lines.mjs";const[$,O]=process.argv.slice(2);(!$||!O)&&(console.error("usage: wait-events.mjs <route> <session-id>"),process.exit(2));const re=p.join(W.homedir(),".claude","kickflip","manifest.json");function L(){try{return h(JSON.parse(a.readFileSync(re,"utf8")).sites,$)||null}catch{return}}d(L,"site");function v(e){const r=e.filter?new RegExp(e.filter):null,o=Object.create(null);for(const l of e.watch||["data/events.jsonl"]){let m=[];try{m=a.readFileSync(p.resolve(e.dir,l),"utf8").split(`
3
+ `).filter(Boolean)}catch{}o[l]=r?m.filter(g=>r.test(g)):m}return o}d(v,"matching");const ce=`quiet The owner doesn't read this session's terminal. Answer a prompt typed in it in full. A wake, a task notification or a builder's result is not one: write no text of your own, since board.mjs and this watcher print one line for each thing done. Talk and questions go on the board, never AskUserQuestion; only a failure the board can't show, such as the hub being down, gets one line here. Each message to the owner stands alone in its card's thread: name cards by label (#96), and a pointer such as "above" or "here" must make sense in that thread, never point into this session.`,ae=d(e=>{try{return JSON.parse(e)}catch{return null}},"parsed");function P(e){try{return JSON.parse(a.readFileSync(p.resolve(e.dir,"board.json"),"utf8"))}catch(r){return r.code==="ENOENT"?null:{}}}d(P,"boardOf");async function G(e,r){for(const o of r){let l;try{l=JSON.parse(o)}catch{continue}(l.kind==="ping"||l.kind==="hello")&&typeof l.id=="string"&&await X(e,l.id).catch(m=>console.log(`ping ${l.id} not answered (${m.message})`))}}d(G,"ackPings");function le(e){let r=[];try{r=JSON.parse(a.readFileSync(p.resolve(e,"data","orchestrator-waits.json"),"utf8")).waits||[]}catch{}return r.map(o=>`waits ${o.kind} ${o.ref} ${o.key}${o.bumpedAt?" bumped":""} since ${o.since}${o.picked?`, picked up ${o.picked}`:""}: ${o.next}`)}d(le,"waitLines");const b=L();b||(console.log("site-removed"),process.exit(0));const w=p.resolve(b.dir,"data",`.watch-cursor-${O}.json`),N=p.resolve(b.dir,"data","watcher.json"),F=[process.ppid,A(process.ppid)],R=d(()=>{F[1]??=A(F[0]),V(O,F)&&process.exit(0)},"orphaned");C(b.dir,$,O);try{a.mkdirSync(p.dirname(w),{recursive:!0}),a.writeFileSync(N,JSON.stringify({pid:process.pid,since:new Date().toISOString()}))}catch{}process.on("exit",()=>{try{const e=JSON.parse(a.readFileSync(N,"utf8"));e.pid===process.pid&&a.writeFileSync(N,JSON.stringify({...e,exited_at:new Date().toISOString()}))}catch{}});let c;try{c=JSON.parse(a.readFileSync(w,"utf8"))}catch{}for(c||(c=Object.fromEntries(Object.entries(v(b)).map(([e,r])=>[e,r.length])),a.mkdirSync(p.dirname(w),{recursive:!0}),a.writeFileSync(w,JSON.stringify(c)));;){await new Promise(t=>setTimeout(t,2e3));const e=L();if(e===void 0)continue;e===null&&(console.log("site-removed"),process.exit(0)),e.owner?.session&&e.owner.session!==O&&(console.log("handed-over "+JSON.stringify(e.owner)),process.exit(0)),R();const r=d(t=>Object.fromEntries(Object.entries(t).map(([n,s])=>[n,[...h(c.$quietHeld,n)||[],...h(c.$usageHeld,n)||[],...s.slice(h(c,n)||0)]])),"pending"),o=d((t,n)=>n.state!=="paused"||!se(t),"eligible"),l=d((t,n)=>Object.values(t).some(s=>s.some(i=>o(i,n)&&!j(i))),"wakes"),m=I({dir:e.dir}),g=v(e);if(!l(r(g),m)){const t=Object.fromEntries(Object.entries(g).map(([s,i])=>[s,i.slice(h(c,s)||0).filter(j)])),n=Object.fromEntries(Object.entries(g).map(([s,i])=>[s,i.slice(h(c,s)||0).filter(f=>!j(f))]));if(Object.values(t).some(s=>s.length)){P(e)&&await G(e.dir,Object.values(t).flat());const s=d((i,f)=>Object.fromEntries(Object.keys(g).map(k=>[k,[...h(i,k)||[],...f[k]]])),"append");c={...Object.fromEntries(Object.entries(g).map(([i,f])=>[i,f.length])),$quietHeld:s(c.$quietHeld,t),$usageHeld:s(c.$usageHeld,n)},Object.values(c.$usageHeld).some(i=>i.length)||delete c.$usageHeld,a.writeFileSync(w,JSON.stringify(c))}continue}await new Promise(t=>setTimeout(t,2e3)),R();const E=v(e),y=I({dir:e.dir}),J=r(E);if(!l(J,y))continue;const S=Object.create(null),x=[],U=new Set(Object.values(c.$quietHeld||{}).flat()),H=[];let T=[];try{T=JSON.parse(a.readFileSync(oe(e.dir,O),"utf8")).ids||[]}catch{}for(const[t,n]of Object.entries(J)){S[t]=n.filter(s=>!o(s,y));for(const s of n.filter(i=>o(i,y))){U.has(s)||H.push(s),console.log(`event ${t} ${s}`);const i=await ie(e.dir,s),f=ae(s);i&&console.log(T.includes(f?.id)?`already shown: ${i}`:i),f&&te.includes(f.kind)&&typeof f.id=="string"&&x.push(f.id)}}const u=P(e);if(u&&await Y(e.dir,x).catch(t=>console.log(`working marks not written (${t.message})`)),u&&await G(e.dir,H),u)for(const t of le(e.dir))console.log(t);if(u)for(const t of _(K(),Q(u)))console.log(`rule ${t}`);if(u)for(const t of Z(ee(u)))console.log(t);u&&console.log(ce),y.state==="paused"&&console.log(ne(y));try{const t=u&&B(e.dir);if(t)for(const n of[...M(t,{listen:"listening"}),z()])n.ok||console.log(`link ${n.link} ${n.detail}`)}catch(t){console.log(`link registry could not check the links (${t.message})`)}const q=Object.fromEntries(Object.entries(E).map(([t,n])=>[t,n.length]));Object.values(S).some(t=>t.length)&&(q.$usageHeld=S),a.writeFileSync(w,JSON.stringify(q)),process.exit(0)}
@@ -681,4 +681,4 @@ moves every Linear board to no ticket source. If the source can't make a ticket,
681
681
  (overnight, snoozed or the weekend). --urgent: a
682
682
  production fault only; it beats those holds. While
683
683
  notifications are off every push is dropped, urgent too
684
- KICKFLIP_PUSH_CMD='["<cmd>","<arg>"]' replaces \`node ../../bin/kickflip.mjs push\`; the flags follow it`;class d extends Error{static{i(this,"UsageError")}}const re=new Set(["new-ticket","done","clear-status","clear-next","urgent","now","clear-eta","held","unheld","idle","wait","hub","clear-install","force","worktree","dispatch","writes"]);function oe(e){const a=Object.create(null),t=[];for(let s=0;s<e.length;s++){const r=e[s];if(!r.startsWith("--")){t.push(r);continue}const o=r.slice(2);if(re.has(o)){if(Object.hasOwn(a,o))throw new d(`--${o} is given twice`);a[o]=!0}else if(s+1<e.length)(a[o]||=[]).push(e[++s]);else throw new d(`--${o} needs a value`)}return{flags:a,rest:t}}i(oe,"parse");function de(e,a,t){const s=new Set(a.filter(l=>l.startsWith("...")).map(l=>l.slice(3))),r=new Set(a.map(l=>l.replace(/^\.\.\./,""))),o=Object.keys(t).filter(l=>!r.has(l));if(o.length)throw new d(`${e} does not take ${o.map(l=>"--"+l).join(", ")}`);return Object.fromEntries(Object.entries(t).map(([l,c])=>{if(c===!0||s.has(l))return[l,c];if(c.length>1)throw new d(`--${l} is given twice`);return[l,c[0]]}))}i(de,"flagsOf");const le=["text","note","notes","heading","summary","title","body","next","progress","install-label","confirmed","asked","task","reason"],he=/^(?:\/|~\/|\.{1,2}\/)\S*\.(?:html?|md|json|txt)$/;function ce(e){const a=e.trim();if(!a||/\s/.test(a))return!1;if(he.test(a))return!0;try{return g.statSync(a).isFile()}catch{return!1}}i(ce,"looksLikePath");function ue(e,a){for(const t of le){if(typeof a[t]!="string"||!ce(a[t]))continue;const s=e.includes("file")?`; for a file use --file ${a[t].trim()}`:"";throw new d(`--${t} takes text, not a file path (${a[t].trim()})${s}`)}if(typeof a.file=="string"&&a.file!=="-"&&!g.existsSync(a.file))throw new d(`--file ${a.file}: no such file`)}i(ue,"checkInputs");const w=i(e=>g.readFileSync(e==="-"?0:e,"utf8"),"readInput");function q(e){if(!e)throw new d("--file <path> is required");try{return JSON.parse(w(e))}catch(a){throw new n.BoardError(`${e}: ${a.message}`)}}i(q,"readJSONInput");function C(e,a){const t=["notes-file","plan"].find(s=>e[s]!==void 0);if(t)throw new d(`--${t} is gone: the board names a card's notes file, <id>-notes.md, and writes it itself; ${a}`)}i(C,"refuseNotesFile");function N(e){if(e.note!==void 0&&e.file!==void 0)throw new d("pass --note or --file, not both");return e.file===void 0?e.note:w(e.file)}i(N,"noteOf");async function pe(e,a,{"owner-step":t,check:s,text:r,...o}){if(t!==void 0&&(!e||o.dir))throw new d("--owner-step goes on a board card: pass --site, not --dir");if(s!==void 0&&t===void 0)throw new d("--check goes with --owner-step: it is the code check that closes the card once the step is done");t!==void 0&&await n.setItem(e,a,{ownerStep:t,check:s});const l=e&&!o.dir,c=l&&await n.handBackCalls(e,a,o);if(c)return c;if(l&&o.next===void 0&&await n.finishesCard(e,a,o)){if(r===void 0)throw new n.BoardError(`builder done finishes ${a}: pass --text "<what you checked>", or --next "<what happens next>" to stop without finishing`);return $(e,a,{text:r,ownerStep:t})}if(l&&await n.isHelper(e,a,o.agent)){if(r===void 0)throw new d('a helper hands back its result: pass --text "<what you did or found>"');return n.stopBuilder(e,a,{...o,note:r})}if(l&&r!==void 0&&await n.isPlanner(e,a,o.agent))return n.stopBuilder(e,a,{...o,note:r,requireNext:!0});if(r!==void 0)throw new d("--text goes on a builder done that finishes the card, the main build with a worktree and no --next, or on a helper's or a planner's");return n.stopBuilder(e,a,{...o,requireNext:!0})}i(pe,"builderDone");const b={pr:[["file/id"],[],async(e,[a])=>({lines:(await n.prReport(e,a)).map(t=>JSON.stringify(t))})],"pr comment":[["pr"],["body"],(e,[a],t)=>{if(t.body===void 0)throw new d('pr comment needs --body "<what Claude says>"');return n.postPR(e,a,{body:t.body})}],"pr reply":[["pr","comment-id"],["body"],(e,[a,t],s)=>{if(s.body===void 0)throw new d('pr reply needs --body "<what Claude says>"');return n.postPR(e,a,{replyTo:t,body:s.body})}],reply:[["eventId"],["text","file","title"],(e,[a],t)=>{if(t.text===void 0==(t.file===void 0))throw new d("reply takes --text or --file");const s=t.text??w(t.file);return a.includes("/")?n.answerCard(e,a,s,t.title):n.writeReply(e,a,s,t.title)}],thread:[["file/id"],["text","link","who","via"],(e,[a],t)=>n.appendMessage(e,a,t)],"visual add":[["file/id"],["file","title"],(e,[a],t)=>n.addVisual(e,a,t)],"topic add":[["id"],["title","summary"],(e,[a],t)=>n.addTopic(e,{id:a,...t})],"question add":[[],["file"],async(e,a,t)=>{const s=q(t.file);return{...await n.addQuestions(e,s,process.env.KICKFLIP_RENDER_CHECK==="off"?void 0:se),asked:[s].flat()}}],"question resolve":[["id"],["note"],(e,[a],t)=>n.resolveQuestion(e,a,t.note)],"question settle":[["id"],["note"],(e,[a],t)=>n.settleQuestion(e,a,t.note)],"question publish":[["key"],[],async(e,[a])=>({ids:await n.publishScreened(e,a)})],"question move":[["ids"],["to","block"],(e,[a],t)=>n.moveQuestions(e,a.split(",").filter(Boolean),t.to,(t.block||"").split(",").filter(Boolean))],"prototype add":[["topic"],["title","...take","card","served","...state"],(e,[a],t)=>n.addPrototype(e,{topic:a,title:t.title,card:t.card,takes:t.take,served:t.served,states:t.state})],"prototype base":[[],[],e=>ne(e)],"prototype list":[[],[],e=>n.listPrototypes(e)],"prototype rm":[["topic"],[],(e,[a])=>n.removePrototype(e,a)],"item set":[["file/id"],["done","split-into","status","clear-status","next","clear-next","...pr","pushed","gh-since","from-ask","phase","state","held","unheld","pick-up-at","notes-file","plan","deps","blocked-until","block-reason","parent","related","relate","unrelate","install","install-sha","install-label","clear-install","title","size","model","force","ticket","new-ticket","text","check"],async(e,[a],t,s)=>(C(t,`add to its notes with item notes ${a} --heading "<heading>" --file <draft.md>`),t.done&&e&&await n.checkNotReopened(e,a),n.setItem(e,a,{done:t.done,splitInto:t["split-into"],status:t.status,clearStatus:t["clear-status"],next:t.next,clearNext:t["clear-next"],pr:t.pr,pushed:t.pushed,ghSince:t["gh-since"],fromAsk:t["from-ask"],phase:t.phase,state:t.state,held:t.held,unheld:t.unheld,pickUpAt:t["pick-up-at"],deps:t.deps,blockedUntil:t["blocked-until"],blockReason:t["block-reason"],parent:t.parent,related:t.related,relate:t.relate,unrelate:t.unrelate,install:t.install,installSha:t["install-sha"],installLabel:t["install-label"],clearInstall:t["clear-install"],title:t.title,size:t.size,model:t.model,force:t.force,ticket:t.ticket,newTicket:t["new-ticket"],text:t.text,check:t.check},s))],"item add":[["file[/id]"],["title","notes","notes-from","deps","notes-file","plan","ticket","new-ticket","pick-up-at","held","parent","size","model","phase","state","relate","from-ask","text"],(e,[a],t,s)=>{if(C(t,"seed a new card's notes with item add --notes-from <draft.md>"),t.notes!==void 0&&t["notes-from"]!==void 0)throw new d("pass --notes or --notes-from, not both");return n.addItem(e,a,{title:t.title,notes:t.notes,notesFrom:t["notes-from"],deps:t.deps,ticket:t.ticket,newTicket:t["new-ticket"],pickUpAt:t["pick-up-at"],held:t.held,parent:t.parent,size:t.size,model:t.model,phase:t.phase,state:t.state,relate:t.relate,fromAsk:t["from-ask"],text:t.text,intake:!0},s)}],"item notes":[["file/id"],["heading","file","from"],(e,[a],t)=>{if(t.heading===void 0&&t.from===void 0)throw new d(`item notes needs --heading "<the section's title>"`);if(t.file===void 0==(t.from===void 0))throw new d("item notes takes --file <draft.md> or --from <file>/<id>");return n.addNotes(e,a,t)}],"item relate-ask":[["eventId","file/id"],["summary","title"],(e,[a,t],s)=>n.relateAsk(e,a,t,s.summary,s.title)],"ask unfold":[["eventId"],[],(e,[a])=>n.unfoldAsk(e,a)],"ask move":[["eventId"],["to"],(e,[a],t)=>n.moveAsk(e,a,t.to)],"wave create":[["slug"],["title","goal","...card","note","file"],(e,[a],t)=>n.createWave(e,a,{title:t.title,goal:t.goal,cards:t.card,note:N(t)})],"wave add":[["slug","file/id"],["after"],(e,[a,t],s)=>n.changeWave(e,a,{add:t,after:s.after})],"wave remove":[["slug","file/id"],[],(e,[a,t])=>n.changeWave(e,a,{remove:t})],"wave set":[["slug","...file/id?"],["after","title","goal","note","file"],(e,[a,...t],s)=>{if(t.length>1)throw new d("wave set takes <slug> [<file/id>]");return n.changeWave(e,a,{card:t[0],after:s.after,title:s.title,goal:s.goal,note:N(s)})}],"wave finish":[["slug"],[],(e,[a])=>n.finishWave(e,a)],slack:[[],[],()=>({lines:[JSON.stringify(D())]})],"slack set":[[],["self-dm","user","domain","timezone"],async(e,a,t)=>{const s={"self-dm":"self_dm",user:"owner_slack_user",domain:"slack_domain",timezone:"timezone"};try{return{lines:[JSON.stringify(await M(Object.fromEntries(Object.entries(t).map(([r,o])=>[s[r],o]))))]}}catch(r){throw new n.BoardError(r.message)}}],integrations:[[],[],async()=>({lines:[JSON.stringify(await H.rows())]})],"review updated":[["file/id"],["text"],(e,[a],t)=>n.reviewUpdated(e,a,t.text)],"review record":[["pr"],["state","text","file"],(e,[a],t)=>{if(t.text===void 0==(t.file===void 0))throw new d("review record takes --text or --file");return n.recordReview(e,a,{state:t.state,text:t.text??w(t.file)})}],"review post":[["pr"],["file","read-at"],(e,[a],t)=>{if(t.file===void 0)throw new d("review post needs --file <review.md>");if(t["read-at"]===void 0)throw new d("review post needs --read-at <time>, when you read the PR, so a review that landed since is caught");return n.postIncomingReview(e,a,{words:w(t.file),readAt:t["read-at"]})}],"review digest":[[],[],async(e,a,t,s)=>({lines:[JSON.stringify(await n.reviewDigest(e,s))]})],"review due":[[],[],async(e,a,t,s)=>({lines:[JSON.stringify(await n.reviewDue(e,s))]})],"reviewers set":[[],["file"],(e,a,t)=>n.setReviewers(e,q(t.file))],"reviewers add":[[],["file"],(e,a,t)=>n.addReviewers(e,q(t.file))],"reviewers remove":[["...name"],[],(e,a)=>n.removeReviewers(e,a)],"rules list":[[],[],e=>n.listRules(e)],"rules add":[[],["text","hub","by"],(e,a,t)=>n.addRuleTo(e,t)],"rules edit":[["id"],["text","hub"],(e,[a],t)=>n.editRuleIn(e,a,t)],"rules remove":[["id"],["hub"],(e,[a],t)=>n.removeRuleFrom(e,a,t)],settings:[[],[],async e=>({lines:[JSON.stringify(await n.readBoardSettings(e))]})],build:[["file/id"],["asked"],async(e,[a],t)=>{if(!e)throw new n.BoardError("build needs --site <route>");n.parseKey(a);const s=await n.askedGate(e,a,t.asked);try{const r=await fetch(`http://127.0.0.1:${process.env.KICKFLIP_HUB_PORT||4500}/_hub/build`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:x.basename(e),key:a}),signal:AbortSignal.timeout(1e4)}),o=await r.json();if(!r.ok)throw new n.BoardError(o.error||"The hub refused the build.");return{lines:["started",...(await n.appendMessage(e,a,{text:s})).lines]}}catch(r){throw r instanceof n.BoardError?r:new n.BoardError(`Could not start the build: ${r.message}`)}}],"main set":[[],["install","install-sha"],(e,a,t)=>n.setMainInstall(e,{install:t.install,installSha:t["install-sha"]})],"settings set":[["name","value"],[],(e,[a,t])=>n.setBoardSetting(e,a,t)],"builder start":[["file/id"],["label","phase","progress","dir","agent","kind","model","eta","worktree","repo","dispatch"],(e,[a],{worktree:t,repo:s,dispatch:r,...o})=>{if(s!==void 0&&!t)throw new d("--repo goes with --worktree");const l=i(p=>z(e,a.split("/")[1],{repo:s,...p}),"make"),c=e&&o.dir===void 0&&ae(e);return n.startBuilder(e,a,{...o,dispatch:r?"session":void 0,worktree:t?l:void 0,ownWorktree:c?l:void 0})}],"builder progress":[["file/id","...text?"],["phase","text","dir","agent","eta","clear-eta"],(e,[a,...t],s)=>{if(t.length&&s.text!==void 0)throw new d("builder progress takes its text once: as words or as --text");if(!t.length&&s.text===void 0)throw new d("builder progress needs its text, as words or as --text");return n.builderProgress(e,a,s.text??t.join(" "),{...s,clearEta:s["clear-eta"]})}],"builder done":[["file/id"],["dir","agent","next","owner-step","check","text","updated"],async(e,[a],{updated:t,...s})=>{const r=e&&!s.dir;if(r&&t===void 0&&await n.cardLinked(e,a))throw new n.BoardError(`a reviewer has ${a}'s PR link: pass --updated "<what changed>" for its thread, or --updated none for a change only to comments, names, docs or tests`);const o=await pe(e,a,s);return r&&t!==void 0&&t.trim().toLowerCase()!=="none"&&await n.reviewUpdated(e,a,t),o}],"builder pick":[["file/id"],[],(e,[a])=>n.pickBuilder(e,a)],"agent launch":[["file/id"],["name","task","writes","model"],(e,[a],t)=>n.requestHelper(e,a,t)],"agent wait":[["file/id"],["name","agent","timeout"],(e,[a],t)=>n.waitHelper(e,a,{...t,alive:Q})],"agent merge":[["file/id"],["name"],async(e,[a],t)=>{const{record:s,card:r}=await n.helperOf(e,a,t.name);if(!s.done)throw new n.BoardError(`helper ${t.name} is still open; run agent wait ${a} --name ${t.name} first`);if(!s.writes||!s.worktree)throw new n.BoardError(`helper ${t.name} writes no code, so there is nothing to merge`);if(!r)throw new n.BoardError(`${a} has no worktree to merge helper ${t.name} into`);return G(r,s.worktree)}],audit:[["...file/id?"],[],(e,[a,...t])=>{if(t.length)throw new d("audit takes one <file/id> at most");return n.auditLog(e,a)}],"builder call":[["file/id","...text"],["dir","agent"],(e,[a,...t],s)=>n.recordCall(e,a,t.join(" "),s)],"builder calls":[["file/id"],["dir","agent"],(e,[a],t)=>n.listCalls(e,a,t)],"builder ask":[["file/id","...text"],["agent"],(e,[a,...t],s)=>n.askOrchestrator(e,a,t.join(" "),s)],"builder answer":[["file/id","ask"],["text"],(e,[a,t],s)=>n.answerBuilder(e,a,t,s.text)],"builder defer":[["file/id","ask"],["text"],(e,[a,t],s)=>n.answerBuilder(e,a,t,s.text,{deferred:!0})],"builder asks":[["file/id"],["wait","timeout"],(e,[a],t)=>n.listAsks(e,a,t)],"builder verified":[["file/id"],["dir","agent","note"],async(e,[a],t)=>{await n.verifyCalls(e,a,t);const s=e&&!t.dir?await n.verifiedFinish(e,a):null;if(!s)return{};if(s.waits.length)return{lines:[`${await n.cardName(e,a)} finishes once the owner answers ${s.waits.join(", ")}`]};try{return await $(e,a,{text:t.note??"Judgment calls verified."})}catch(r){throw r instanceof n.BoardError?Object.assign(new n.BoardError(`judgment calls verified, but ${await n.cardName(e,a)} didn't finish: ${r.message}`),{exitCode:r.exitCode}):r}}],land:[["file/id"],["repo","dir","text","owner-step","check"],async(e,[a],t)=>{const s=a.split("/")[1];if(e&&t.text===void 0)throw new d(`land needs --text "<what was checked>", which closes ${a} as done once it lands`);if(!e&&t.text!==void 0)throw new d("--text closes the card, which needs --site");if(!e&&t["owner-step"]!==void 0)throw new d("--owner-step keeps a board card open, which needs --site");if(t.check!==void 0&&t["owner-step"]===void 0)throw new d("--check goes with --owner-step: it is the code check that closes the card once the step is done");if(e&&t.dir===void 0)return $(e,a,{text:t.text,ownerStep:t["owner-step"],check:t.check,repo:t.repo});const r=e?await n.cardName(e,a):void 0,o=await U(r??a,async()=>{e&&await n.checkClose(e,a,t.text,t["owner-step"],t.check),await n.checkCallsVerified(e,a,{dir:t.dir});const l=await n.recordedWorktree(e,a,{dir:t.dir}),{repo:c,base:p}=J(e,{repo:t.repo??l?.repo});return await F({path:l?.path??x.join(K(),s),branch:l?.branch??s,repo:x.resolve(c),base:p,ref:r}),e?n.setItem(e,a,{done:!0,text:t.text,ownerStep:t["owner-step"],check:t.check}):{lines:[]}});return o.joined?{lines:[`joined the land already running for ${r??a}`]}:o}],"builder stop":[["file/id"],[],(e,[a])=>ee(m(e,"builder stop"),a)],"item stall":[["file/id"],["reason"],(e,[a],t)=>Y(m(e,"item stall"),a,t.reason)],"land stop":[["file/id"],[],(e,[a])=>te(m(e,"land stop"),a)],"land queue":[[],[],()=>Z()],"item bump":[["file/id"],[],(e,[a])=>S(m(e,"item bump"),a,!0)],"item unbump":[["file/id"],[],(e,[a])=>S(m(e,"item unbump"),a,!1)],lander:[["file/id"],[],async(e,[a])=>{if(!e)throw new d("lander needs --site <route>");return await n.relaunchLander(e,a),{lines:[`${await n.cardName(e,a)} is handed back again; the server launches a lander for it within a minute`]}}],merge:[["file/id"],["after-approval","confirmed"],async(e,[a],t)=>e&&await n.heldMerge(e,a)?X(e,a):n.mergeCard(e,a,{afterApproval:t["after-approval"],confirmed:t.confirmed})],"arch file":[["file/id"],[],(e,[a])=>e?V(e,a):Promise.reject(new n.BoardError("arch file needs --site <route>"))],push:[[],["kind","title","body","url","tag","urgent","now"],(e,a,t)=>{if(t.kind!=="fault"&&t.kind!=="reminder")throw new d(`a session pushes only --kind fault or reminder${t.kind===void 0||t.kind===!0?"":`, not "${t.kind}"`}: the board server pushes Action needed, and news goes on the board`);if(t.title===void 0)throw new d("push needs --title");return n.sendPush(e,t)}]};b.install=b.build;function m(e,a){if(!e)throw new d(`${a} needs --site <route>`);return e}i(m,"needSite");const h=i((e,a)=>n.cardName(e,a),"card"),R=i((e,a)=>`${a}${e.length===1?"":"s"} ${e.join(", ")}`,"plural"),T=i(e=>e.agent===void 0||e.agent==="main"?"builder":`builder ${e.agent}`,"builderOf");function we(e){const a=e["pick-up-at"];return[e.done&&(e["split-into"]?`done, split into ${e["split-into"].split(",").join(", ")}`:"done"),e.next!==void 0&&(e.next.trim()?"next line set":"next line cleared"),e["clear-next"]&&"next line cleared",e.pr!==void 0&&`PR #${e.pr}`,e.pushed!==void 0&&`pushed ${e.pushed}`,e["gh-since"]&&`GitHub read to ${e["gh-since"]}`,e["from-ask"]&&`from task ${e["from-ask"]}`,e.phase,e.held&&"held",e.unheld&&"resumed",a!==void 0&&(a?`held until ${a}`:"resumed"),e.deps!==void 0&&(e.deps?`blocked by ${e.deps}`:"deps cleared"),e.parent!==void 0&&(e.parent?`parent ${e.parent}`:"parent cleared"),e.related!==void 0&&(e.related?`related to ${e.related.split(",").join(", ")}`:"related cleared"),e.relate!==void 0&&`related to ${e.relate.split(",").join(", ")} added`,e.unrelate!==void 0&&`unrelated from ${e.unrelate.split(",").join(", ")}`,e.install!==void 0&&"install published",e["clear-install"]&&"install cleared",e.title!==void 0&&"renamed",e.ticket!==void 0&&`ticket ${e.ticket}`,e["new-ticket"]&&"ticket made",e.check!==void 0&&(e.check.trim()?`check ${e.check.trim().split(/\s+/).join(" ")}`:"check removed")].filter(Boolean).join(", ")}i(we,"itemChanges");const me={reply:i(async(e,[a])=>a.includes("/")?`answered ${await h(e,a)}: it waits in In Review for the owner's Done`:`reply written to ${await n.eventCard(e,a)}`,"reply"),thread:i(async(e,[a])=>`thread line on ${await h(e,a)}`,"thread"),"topic add":i((e,[a])=>`topic ${a} added`,"topic add"),"question add":i(async(e,a,t,{asked:s,staged:r})=>{const o=[...new Set(s.map(c=>c.topic))],l=o.length!==1?"":o[0].startsWith("item:")?` on ${await h(e,o[0].slice(5))}`:` on topic ${o[0]}`;return`${R(s.map(c=>c.id),"question")} ${r===s.length?"staged":"added"}${l}`},"question add"),"question resolve":i((e,[a])=>`question ${a} resolved`,"question resolve"),"question settle":i((e,[a])=>`question ${a} settled`,"question settle"),"question publish":i(async(e,[a],t,{ids:s})=>`${R(s,"question")} on ${await h(e,a)} passed to the owner`,"question publish"),"question move":i((e,[a],t)=>`questions ${a} merged onto ${t.to}`,"question move"),"prototype add":i(async(e,[a],t)=>`prototype ${a} recorded${t.card?` for ${await h(e,t.card)}`:""}`,"prototype add"),"prototype rm":i((e,[a])=>`prototype ${a} removed`,"prototype rm"),"item set":i(async(e,[a],t)=>`${await h(e,a)}: ${we(t)}`,"item set"),"item add":i(async(e,a,t,{key:s})=>`${await h(e,s)} added as ${s}`,"item add"),"item notes":i(async(e,[a],t,{file:s,heading:r})=>`${await h(e,a)}: notes section "${r}" added to ${s}`,"item notes"),"item relate-ask":i(async(e,[a,t])=>`task ${a} folded into ${await h(e,t)}`,"item relate-ask"),"ask unfold":i((e,[a])=>`task ${a} back on a card of its own`,"ask unfold"),"ask move":i((e,[a],t)=>`task ${a} moved to /${t.to}`,"ask move"),"wave create":i((e,[a])=>`wave ${a} created`,"wave create"),"wave add":i(async(e,[a,t])=>`${await h(e,t)} added to wave ${a}`,"wave add"),"wave remove":i(async(e,[a,t])=>`${await h(e,t)} taken out of wave ${a}`,"wave remove"),"wave set":i((e,[a])=>`wave ${a} updated`,"wave set"),"wave finish":i((e,[a])=>`wave ${a} finished`,"wave finish"),"review record":i((e,[a],t)=>`review of PR #${a} recorded: ${t.state==="needs"?"needs you":"posted"}`,"review record"),"reviewers set":i(()=>"reviewers replaced","reviewers set"),"reviewers add":i(()=>"reviewers added","reviewers add"),"reviewers remove":i((e,a)=>`${R(a,"reviewer")} removed`,"reviewers remove"),"rules add":i((e,a,t)=>`${t.hub?"hub":"board"} rule added`,"rules add"),"rules edit":i((e,[a],t)=>`${t.hub?"hub":"board"} rule ${a} reworded`,"rules edit"),"rules remove":i((e,[a],t)=>`${t.hub?"hub":"board"} rule ${a} removed`,"rules remove"),"builder start":i(async(e,[a],t,s)=>`${await h(e,a)}: ${s.alreadyOpen?"already open: the Implement tap opened its record; launch the agent, whose own builder start takes it up":`${T(t)} started`}`,"builder start"),"builder progress":i(async(e,[a])=>`progress line on ${await h(e,a)}`,"builder progress"),"builder done":i(async(e,[a],t,s)=>`${await h(e,a)}: ${s?.said??`${T(t)} done${t["owner-step"]===void 0?"":`; owner step "${t["owner-step"].trim()}"`}`}`,"builder done"),"builder call":i(async(e,[a])=>`judgment call recorded on ${await h(e,a)}`,"builder call"),"builder ask":i(async(e,[a],t,{id:s})=>`${await h(e,a)}: asked the orchestrator, ${s}`,"builder ask"),"builder answer":i(async(e,[a,t])=>`${await h(e,a)}: ${t} answered`,"builder answer"),"builder defer":i(async(e,[a,t])=>`${await h(e,a)}: ${t} deferred to the owner`,"builder defer"),"builder verified":i(async(e,[a],t,s)=>`${await h(e,a)}: judgment calls verified${s?.said?`; ${s.said}`:""}`,"builder verified"),land:i(async(e,[a],t,s)=>e?s?.said?`${await h(e,a)}: ${s.said}`:t["owner-step"]===void 0?`${await h(e,a)}: landed and done`:`${await h(e,a)}: landed; waits on the owner step "${t["owner-step"].trim()}"`:null,"land"),merge:i(async(e,[a],t,s)=>`${await h(e,a)}: ${s?.said??"merged"}`,"merge"),"arch file":i(async(e,[a])=>`findings of ${await h(e,a)} filed`,"arch file")};async function fe(e,a={}){try{const{flags:t,rest:s}=oe(e),r=[3,2,1].map(u=>s.slice(0,u).join(" ")).find(u=>y(b,u)),o=y(b,r);if(!o)throw new d(s.length?`unknown command "${s.slice(0,2).join(" ")}"`:"no command given");const[l,c,p]=o,f=s.slice(r.split(" ").length),_=l.at(-1)?.startsWith("..."),B=l.at(-1)?.endsWith("?")?l.length-1:l.length;if(_?f.length<B:f.length!==l.length)throw new d(`${r} takes ${l.map(u=>`<${u.replace(/^\.\.\.|\?$/g,"")}>`).join(" ")||"no arguments"}`);const{site:A,...E}=t;if(A?.length>1)throw new d("--site is given twice");const I=A?.[0],k=de(r,c,E);ue(c,k);const P=I===void 0?null:await n.siteDir(I),v=await p(P,f,k,a),O=y(me,r),j=O&&await O(P,f,k,v);j&&console.log(j);for(const u of typeof v=="object"&&v?.lines||[])console.log(u);return 0}catch(t){if(t instanceof d)return console.error(`${t.message} (node board.mjs --help lists the commands)`),2;if(t instanceof n.BoardError)return console.error(t.message),t.exitCode??1;throw t}}if(i(fe,"main"),process.argv[1]&&import.meta.url===L(g.realpathSync(process.argv[1])).href){const e=process.argv.slice(2);!e.length||e.includes("--help")||e[0]==="help"?console.log(ie):process.exitCode=await fe(e)}export{ie as USAGE,fe as main};
684
+ KICKFLIP_PUSH_CMD='["<cmd>","<arg>"]' replaces \`node ../../bin/kickflip.mjs push\`; the flags follow it`;class d extends Error{static{i(this,"UsageError")}}const re=new Set(["new-ticket","done","clear-status","clear-next","urgent","now","clear-eta","held","unheld","idle","wait","hub","clear-install","force","worktree","dispatch","writes"]);function oe(e){const a=Object.create(null),t=[];for(let s=0;s<e.length;s++){const r=e[s];if(!r.startsWith("--")){t.push(r);continue}const o=r.slice(2);if(re.has(o)){if(Object.hasOwn(a,o))throw new d(`--${o} is given twice`);a[o]=!0}else if(s+1<e.length)(a[o]||=[]).push(e[++s]);else throw new d(`--${o} needs a value`)}return{flags:a,rest:t}}i(oe,"parse");function de(e,a,t){const s=new Set(a.filter(l=>l.startsWith("...")).map(l=>l.slice(3))),r=new Set(a.map(l=>l.replace(/^\.\.\./,""))),o=Object.keys(t).filter(l=>!r.has(l));if(o.length)throw new d(`${e} does not take ${o.map(l=>"--"+l).join(", ")}`);return Object.fromEntries(Object.entries(t).map(([l,c])=>{if(c===!0||s.has(l))return[l,c];if(c.length>1)throw new d(`--${l} is given twice`);return[l,c[0]]}))}i(de,"flagsOf");const le=["text","note","notes","heading","summary","title","body","next","progress","install-label","confirmed","asked","task","reason"],he=/^(?:\/|~\/|\.{1,2}\/)\S*\.(?:html?|md|json|txt)$/;function ce(e){const a=e.trim();if(!a||/\s/.test(a))return!1;if(he.test(a))return!0;try{return g.statSync(a).isFile()}catch{return!1}}i(ce,"looksLikePath");function ue(e,a){for(const t of le){if(typeof a[t]!="string"||!ce(a[t]))continue;const s=e.includes("file")?`; for a file use --file ${a[t].trim()}`:"";throw new d(`--${t} takes text, not a file path (${a[t].trim()})${s}`)}if(typeof a.file=="string"&&a.file!=="-"&&!g.existsSync(a.file))throw new d(`--file ${a.file}: no such file`)}i(ue,"checkInputs");const w=i(e=>g.readFileSync(e==="-"?0:e,"utf8"),"readInput");function q(e){if(!e)throw new d("--file <path> is required");try{return JSON.parse(w(e))}catch(a){throw new n.BoardError(`${e}: ${a.message}`)}}i(q,"readJSONInput");function C(e,a){const t=["notes-file","plan"].find(s=>e[s]!==void 0);if(t)throw new d(`--${t} is gone: the board names a card's notes file, <id>-notes.md, and writes it itself; ${a}`)}i(C,"refuseNotesFile");function N(e){if(e.note!==void 0&&e.file!==void 0)throw new d("pass --note or --file, not both");return e.file===void 0?e.note:w(e.file)}i(N,"noteOf");async function pe(e,a,{"owner-step":t,check:s,text:r,...o}){if(t!==void 0&&(!e||o.dir))throw new d("--owner-step goes on a board card: pass --site, not --dir");if(s!==void 0&&t===void 0)throw new d("--check goes with --owner-step: it is the code check that closes the card once the step is done");t!==void 0&&await n.setItem(e,a,{ownerStep:t,check:s});const l=e&&!o.dir,c=l&&await n.handBackCalls(e,a,o);if(c)return c;if(l&&o.next===void 0&&await n.finishesCard(e,a,o)){if(r===void 0)throw new n.BoardError(`builder done finishes ${a}: pass --text "<what you checked>", or --next "<what happens next>" to stop without finishing`);return $(e,a,{text:r,ownerStep:t})}if(l&&await n.isHelper(e,a,o.agent)){if(r===void 0)throw new d('a helper hands back its result: pass --text "<what you did or found>"');return n.stopBuilder(e,a,{...o,note:r})}if(l&&r!==void 0&&await n.isPlanner(e,a,o.agent))return n.stopBuilder(e,a,{...o,note:r,requireNext:!0});if(r!==void 0)throw new d("--text goes on a builder done that finishes the card, the main build with a worktree and no --next, or on a helper's or a planner's");return n.stopBuilder(e,a,{...o,requireNext:!0})}i(pe,"builderDone");const b={pr:[["file/id"],[],async(e,[a])=>({lines:(await n.prReport(e,a)).map(t=>JSON.stringify(t))})],"pr comment":[["pr"],["body"],(e,[a],t)=>{if(t.body===void 0)throw new d('pr comment needs --body "<what Claude says>"');return n.postPR(e,a,{body:t.body})}],"pr reply":[["pr","comment-id"],["body"],(e,[a,t],s)=>{if(s.body===void 0)throw new d('pr reply needs --body "<what Claude says>"');return n.postPR(e,a,{replyTo:t,body:s.body})}],reply:[["eventId"],["text","file","title"],(e,[a],t)=>{if(t.text===void 0==(t.file===void 0))throw new d("reply takes --text or --file");const s=t.text??w(t.file);return a.includes("/")?n.answerCard(e,a,s,t.title):n.writeReply(e,a,s,t.title)}],thread:[["file/id"],["text","link","who","via"],(e,[a],t)=>n.appendMessage(e,a,t)],"visual add":[["file/id"],["file","title"],(e,[a],t)=>n.addVisual(e,a,t)],"topic add":[["id"],["title","summary"],(e,[a],t)=>n.addTopic(e,{id:a,...t})],"question add":[[],["file"],async(e,a,t)=>{const s=q(t.file);return{...await n.addQuestions(e,s,process.env.KICKFLIP_RENDER_CHECK==="off"?void 0:se),asked:[s].flat()}}],"question resolve":[["id"],["note"],(e,[a],t)=>n.resolveQuestion(e,a,t.note)],"question settle":[["id"],["note"],(e,[a],t)=>n.settleQuestion(e,a,t.note)],"question publish":[["key"],[],async(e,[a])=>({ids:await n.publishScreened(e,a)})],"question move":[["ids"],["to","block"],(e,[a],t)=>n.moveQuestions(e,a.split(",").filter(Boolean),t.to,(t.block||"").split(",").filter(Boolean))],"prototype add":[["topic"],["title","...take","card","served","...state"],(e,[a],t)=>n.addPrototype(e,{topic:a,title:t.title,card:t.card,takes:t.take,served:t.served,states:t.state})],"prototype base":[[],[],e=>ne(e)],"prototype list":[[],[],e=>n.listPrototypes(e)],"prototype rm":[["topic"],[],(e,[a])=>n.removePrototype(e,a)],"item set":[["file/id"],["done","split-into","status","clear-status","next","clear-next","...pr","pushed","gh-since","from-ask","phase","state","held","unheld","pick-up-at","notes-file","plan","deps","blocked-until","block-reason","parent","related","relate","unrelate","install","install-sha","install-label","clear-install","title","size","model","force","ticket","new-ticket","text","check"],async(e,[a],t,s)=>(C(t,`add to its notes with item notes ${a} --heading "<heading>" --file <draft.md>`),t.done&&e&&await n.checkNotReopened(e,a),n.setItem(e,a,{done:t.done,splitInto:t["split-into"],status:t.status,clearStatus:t["clear-status"],next:t.next,clearNext:t["clear-next"],pr:t.pr,pushed:t.pushed,ghSince:t["gh-since"],fromAsk:t["from-ask"],phase:t.phase,state:t.state,held:t.held,unheld:t.unheld,pickUpAt:t["pick-up-at"],deps:t.deps,blockedUntil:t["blocked-until"],blockReason:t["block-reason"],parent:t.parent,related:t.related,relate:t.relate,unrelate:t.unrelate,install:t.install,installSha:t["install-sha"],installLabel:t["install-label"],clearInstall:t["clear-install"],title:t.title,size:t.size,model:t.model,force:t.force,ticket:t.ticket,newTicket:t["new-ticket"],text:t.text,check:t.check},s))],"item add":[["file[/id]"],["title","notes","notes-from","deps","notes-file","plan","ticket","new-ticket","pick-up-at","held","parent","size","model","phase","state","relate","from-ask","text"],(e,[a],t,s)=>{if(C(t,"seed a new card's notes with item add --notes-from <draft.md>"),t.notes!==void 0&&t["notes-from"]!==void 0)throw new d("pass --notes or --notes-from, not both");return n.addItem(e,a,{title:t.title,notes:t.notes,notesFrom:t["notes-from"],deps:t.deps,ticket:t.ticket,newTicket:t["new-ticket"],pickUpAt:t["pick-up-at"],held:t.held,parent:t.parent,size:t.size,model:t.model,phase:t.phase,state:t.state,relate:t.relate,fromAsk:t["from-ask"],text:t.text,intake:!0},s)}],"item notes":[["file/id"],["heading","file","from"],(e,[a],t)=>{if(t.heading===void 0&&t.from===void 0)throw new d(`item notes needs --heading "<the section's title>"`);if(t.file===void 0==(t.from===void 0))throw new d("item notes takes --file <draft.md> or --from <file>/<id>");return n.addNotes(e,a,t)}],"item relate-ask":[["eventId","file/id"],["summary","title"],(e,[a,t],s)=>n.relateAsk(e,a,t,s.summary,s.title)],"ask unfold":[["eventId"],[],(e,[a])=>n.unfoldAsk(e,a)],"ask move":[["eventId"],["to"],(e,[a],t)=>n.moveAsk(e,a,t.to)],"wave create":[["slug"],["title","goal","...card","note","file"],(e,[a],t)=>n.createWave(e,a,{title:t.title,goal:t.goal,cards:t.card,note:N(t)})],"wave add":[["slug","file/id"],["after"],(e,[a,t],s)=>n.changeWave(e,a,{add:t,after:s.after})],"wave remove":[["slug","file/id"],[],(e,[a,t])=>n.changeWave(e,a,{remove:t})],"wave set":[["slug","...file/id?"],["after","title","goal","note","file"],(e,[a,...t],s)=>{if(t.length>1)throw new d("wave set takes <slug> [<file/id>]");return n.changeWave(e,a,{card:t[0],after:s.after,title:s.title,goal:s.goal,note:N(s)})}],"wave finish":[["slug"],[],(e,[a])=>n.finishWave(e,a)],slack:[[],[],()=>({lines:[JSON.stringify(D())]})],"slack set":[[],["self-dm","user","domain","timezone"],async(e,a,t)=>{const s={"self-dm":"self_dm",user:"owner_slack_user",domain:"slack_domain",timezone:"timezone"};try{return{lines:[JSON.stringify(await M(Object.fromEntries(Object.entries(t).map(([r,o])=>[s[r],o]))))]}}catch(r){throw new n.BoardError(r.message)}}],integrations:[[],[],async()=>({lines:[JSON.stringify(await H.rows())]})],"review updated":[["file/id"],["text"],(e,[a],t)=>n.reviewUpdated(e,a,t.text)],"review record":[["pr"],["state","text","file"],(e,[a],t)=>{if(t.text===void 0==(t.file===void 0))throw new d("review record takes --text or --file");return n.recordReview(e,a,{state:t.state,text:t.text??w(t.file)})}],"review post":[["pr"],["file","read-at"],(e,[a],t)=>{if(t.file===void 0)throw new d("review post needs --file <review.md>");if(t["read-at"]===void 0)throw new d("review post needs --read-at <time>, when you read the PR, so a review that landed since is caught");return n.postIncomingReview(e,a,{words:w(t.file),readAt:t["read-at"]})}],"review digest":[[],[],async(e,a,t,s)=>({lines:[JSON.stringify(await n.reviewDigest(e,s))]})],"review due":[[],[],async(e,a,t,s)=>({lines:[JSON.stringify(await n.reviewDue(e,s))]})],"reviewers set":[[],["file"],(e,a,t)=>n.setReviewers(e,q(t.file))],"reviewers add":[[],["file"],(e,a,t)=>n.addReviewers(e,q(t.file))],"reviewers remove":[["...name"],[],(e,a)=>n.removeReviewers(e,a)],"rules list":[[],[],e=>n.listRules(e)],"rules add":[[],["text","hub","by"],(e,a,t)=>n.addRuleTo(e,t)],"rules edit":[["id"],["text","hub"],(e,[a],t)=>n.editRuleIn(e,a,t)],"rules remove":[["id"],["hub"],(e,[a],t)=>n.removeRuleFrom(e,a,t)],settings:[[],[],async e=>({lines:[JSON.stringify(await n.readBoardSettings(e))]})],build:[["file/id"],["asked"],async(e,[a],t)=>{if(!e)throw new n.BoardError("build needs --site <route>");n.parseKey(a);const s=await n.askedGate(e,a,t.asked);try{const r=await fetch(`http://127.0.0.1:${process.env.KICKFLIP_HUB_PORT||4500}/_hub/build`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:x.basename(e),key:a}),signal:AbortSignal.timeout(1e4)}),o=await r.json();if(!r.ok)throw new n.BoardError(o.error||"The hub refused the build.");return{lines:["started",...(await n.appendMessage(e,a,{text:s})).lines]}}catch(r){throw r instanceof n.BoardError?r:new n.BoardError(`Could not start the build: ${r.message}`)}}],"main set":[[],["install","install-sha"],(e,a,t)=>n.setMainInstall(e,{install:t.install,installSha:t["install-sha"]})],"settings set":[["name","value"],[],(e,[a,t])=>n.setBoardSetting(e,a,t)],"builder start":[["file/id"],["label","phase","progress","dir","agent","kind","model","eta","worktree","repo","dispatch"],(e,[a],{worktree:t,repo:s,dispatch:r,...o})=>{if(s!==void 0&&!t)throw new d("--repo goes with --worktree");const l=i(p=>z(e,a.split("/")[1],{repo:s,...p}),"make"),c=e&&o.dir===void 0&&ae(e);return n.startBuilder(e,a,{...o,dispatch:r?"session":void 0,worktree:t?l:void 0,ownWorktree:c?l:void 0})}],"builder progress":[["file/id","...text?"],["phase","text","dir","agent","eta","clear-eta"],(e,[a,...t],s)=>{if(t.length&&s.text!==void 0)throw new d("builder progress takes its text once: as words or as --text");if(!t.length&&s.text===void 0)throw new d("builder progress needs its text, as words or as --text");return n.builderProgress(e,a,s.text??t.join(" "),{...s,clearEta:s["clear-eta"]})}],"builder done":[["file/id"],["dir","agent","next","owner-step","check","text","updated"],async(e,[a],{updated:t,...s})=>{const r=e&&!s.dir;if(r&&t===void 0&&await n.cardLinked(e,a))throw new n.BoardError(`a reviewer has ${a}'s PR link: pass --updated "<what changed>" for its thread, or --updated none for a change only to comments, names, docs or tests`);const o=await pe(e,a,s);return r&&t!==void 0&&t.trim().toLowerCase()!=="none"&&await n.reviewUpdated(e,a,t),o}],"builder pick":[["file/id"],[],(e,[a])=>n.pickBuilder(e,a)],"agent launch":[["file/id"],["name","task","writes","model"],(e,[a],t)=>n.requestHelper(e,a,t)],"agent wait":[["file/id"],["name","agent","timeout"],(e,[a],t)=>n.waitHelper(e,a,{...t,alive:Q})],"agent merge":[["file/id"],["name"],async(e,[a],t)=>{const{record:s,card:r}=await n.helperOf(e,a,t.name);if(!s.done)throw new n.BoardError(`helper ${t.name} is still open; run agent wait ${a} --name ${t.name} first`);if(!s.writes||!s.worktree)throw new n.BoardError(`helper ${t.name} writes no code, so there is nothing to merge`);if(!r)throw new n.BoardError(`${a} has no worktree to merge helper ${t.name} into`);return G(r,s.worktree)}],audit:[["...file/id?"],[],(e,[a,...t])=>{if(t.length)throw new d("audit takes one <file/id> at most");return n.auditLog(e,a)}],"builder call":[["file/id","...text"],["dir","agent"],(e,[a,...t],s)=>n.recordCall(e,a,t.join(" "),s)],"builder calls":[["file/id"],["dir","agent"],(e,[a],t)=>n.listCalls(e,a,t)],"builder ask":[["file/id","...text"],["agent"],(e,[a,...t],s)=>n.askOrchestrator(e,a,t.join(" "),s)],"builder answer":[["file/id","ask"],["text"],(e,[a,t],s)=>n.answerBuilder(e,a,t,s.text)],"builder defer":[["file/id","ask"],["text"],(e,[a,t],s)=>n.answerBuilder(e,a,t,s.text,{deferred:!0})],"builder asks":[["file/id"],["wait","timeout"],(e,[a],t)=>n.listAsks(e,a,t)],"builder verified":[["file/id"],["dir","agent","note"],async(e,[a],t)=>{await n.verifyCalls(e,a,t);const s=e&&!t.dir?await n.verifiedFinish(e,a):null;if(!s)return{};if(s.held)return{said:`${await n.cardName(e,a)} didn't land: ${s.held}`};if(s.waits.length)return{lines:[`${await n.cardName(e,a)} finishes once the owner answers ${s.waits.join(", ")}`]};try{return await $(e,a,{text:t.note??"Judgment calls verified."})}catch(r){throw r instanceof n.BoardError?Object.assign(new n.BoardError(`judgment calls verified, but ${await n.cardName(e,a)} didn't finish: ${r.message}`),{exitCode:r.exitCode}):r}}],land:[["file/id"],["repo","dir","text","owner-step","check"],async(e,[a],t)=>{const s=a.split("/")[1];if(e&&t.text===void 0)throw new d(`land needs --text "<what was checked>", which closes ${a} as done once it lands`);if(!e&&t.text!==void 0)throw new d("--text closes the card, which needs --site");if(!e&&t["owner-step"]!==void 0)throw new d("--owner-step keeps a board card open, which needs --site");if(t.check!==void 0&&t["owner-step"]===void 0)throw new d("--check goes with --owner-step: it is the code check that closes the card once the step is done");if(e&&t.dir===void 0)return $(e,a,{text:t.text,ownerStep:t["owner-step"],check:t.check,repo:t.repo});const r=e?await n.cardName(e,a):void 0,o=await U(r??a,async()=>{e&&await n.checkClose(e,a,t.text,t["owner-step"],t.check),await n.checkCallsVerified(e,a,{dir:t.dir});const l=await n.recordedWorktree(e,a,{dir:t.dir}),{repo:c,base:p}=J(e,{repo:t.repo??l?.repo});return await F({path:l?.path??x.join(K(),s),branch:l?.branch??s,repo:x.resolve(c),base:p,ref:r}),e?n.setItem(e,a,{done:!0,text:t.text,ownerStep:t["owner-step"],check:t.check}):{lines:[]}});return o.joined?{lines:[`joined the land already running for ${r??a}`]}:o}],"builder stop":[["file/id"],[],(e,[a])=>ee(m(e,"builder stop"),a)],"item stall":[["file/id"],["reason"],(e,[a],t)=>Y(m(e,"item stall"),a,t.reason)],"land stop":[["file/id"],[],(e,[a])=>te(m(e,"land stop"),a)],"land queue":[[],[],()=>Z()],"item bump":[["file/id"],[],(e,[a])=>S(m(e,"item bump"),a,!0)],"item unbump":[["file/id"],[],(e,[a])=>S(m(e,"item unbump"),a,!1)],lander:[["file/id"],[],async(e,[a])=>{if(!e)throw new d("lander needs --site <route>");return await n.relaunchLander(e,a),{lines:[`${await n.cardName(e,a)} is handed back again; the server launches a lander for it within a minute`]}}],merge:[["file/id"],["after-approval","confirmed"],async(e,[a],t)=>e&&await n.heldMerge(e,a)?X(e,a):n.mergeCard(e,a,{afterApproval:t["after-approval"],confirmed:t.confirmed})],"arch file":[["file/id"],[],(e,[a])=>e?V(e,a):Promise.reject(new n.BoardError("arch file needs --site <route>"))],push:[[],["kind","title","body","url","tag","urgent","now"],(e,a,t)=>{if(t.kind!=="fault"&&t.kind!=="reminder")throw new d(`a session pushes only --kind fault or reminder${t.kind===void 0||t.kind===!0?"":`, not "${t.kind}"`}: the board server pushes Action needed, and news goes on the board`);if(t.title===void 0)throw new d("push needs --title");return n.sendPush(e,t)}]};b.install=b.build;function m(e,a){if(!e)throw new d(`${a} needs --site <route>`);return e}i(m,"needSite");const h=i((e,a)=>n.cardName(e,a),"card"),R=i((e,a)=>`${a}${e.length===1?"":"s"} ${e.join(", ")}`,"plural"),T=i(e=>e.agent===void 0||e.agent==="main"?"builder":`builder ${e.agent}`,"builderOf");function we(e){const a=e["pick-up-at"];return[e.done&&(e["split-into"]?`done, split into ${e["split-into"].split(",").join(", ")}`:"done"),e.next!==void 0&&(e.next.trim()?"next line set":"next line cleared"),e["clear-next"]&&"next line cleared",e.pr!==void 0&&`PR #${e.pr}`,e.pushed!==void 0&&`pushed ${e.pushed}`,e["gh-since"]&&`GitHub read to ${e["gh-since"]}`,e["from-ask"]&&`from task ${e["from-ask"]}`,e.phase,e.held&&"held",e.unheld&&"resumed",a!==void 0&&(a?`held until ${a}`:"resumed"),e.deps!==void 0&&(e.deps?`blocked by ${e.deps}`:"deps cleared"),e.parent!==void 0&&(e.parent?`parent ${e.parent}`:"parent cleared"),e.related!==void 0&&(e.related?`related to ${e.related.split(",").join(", ")}`:"related cleared"),e.relate!==void 0&&`related to ${e.relate.split(",").join(", ")} added`,e.unrelate!==void 0&&`unrelated from ${e.unrelate.split(",").join(", ")}`,e.install!==void 0&&"install published",e["clear-install"]&&"install cleared",e.title!==void 0&&"renamed",e.ticket!==void 0&&`ticket ${e.ticket}`,e["new-ticket"]&&"ticket made",e.check!==void 0&&(e.check.trim()?`check ${e.check.trim().split(/\s+/).join(" ")}`:"check removed")].filter(Boolean).join(", ")}i(we,"itemChanges");const me={reply:i(async(e,[a])=>a.includes("/")?`answered ${await h(e,a)}: it waits in In Review for the owner's Done`:`reply written to ${await n.eventCard(e,a)}`,"reply"),thread:i(async(e,[a])=>`thread line on ${await h(e,a)}`,"thread"),"topic add":i((e,[a])=>`topic ${a} added`,"topic add"),"question add":i(async(e,a,t,{asked:s,staged:r})=>{const o=[...new Set(s.map(c=>c.topic))],l=o.length!==1?"":o[0].startsWith("item:")?` on ${await h(e,o[0].slice(5))}`:` on topic ${o[0]}`;return`${R(s.map(c=>c.id),"question")} ${r===s.length?"staged":"added"}${l}`},"question add"),"question resolve":i((e,[a])=>`question ${a} resolved`,"question resolve"),"question settle":i((e,[a])=>`question ${a} settled`,"question settle"),"question publish":i(async(e,[a],t,{ids:s})=>`${R(s,"question")} on ${await h(e,a)} passed to the owner`,"question publish"),"question move":i((e,[a],t)=>`questions ${a} merged onto ${t.to}`,"question move"),"prototype add":i(async(e,[a],t)=>`prototype ${a} recorded${t.card?` for ${await h(e,t.card)}`:""}`,"prototype add"),"prototype rm":i((e,[a])=>`prototype ${a} removed`,"prototype rm"),"item set":i(async(e,[a],t)=>`${await h(e,a)}: ${we(t)}`,"item set"),"item add":i(async(e,a,t,{key:s})=>`${await h(e,s)} added as ${s}`,"item add"),"item notes":i(async(e,[a],t,{file:s,heading:r})=>`${await h(e,a)}: notes section "${r}" added to ${s}`,"item notes"),"item relate-ask":i(async(e,[a,t])=>`task ${a} folded into ${await h(e,t)}`,"item relate-ask"),"ask unfold":i((e,[a])=>`task ${a} back on a card of its own`,"ask unfold"),"ask move":i((e,[a],t)=>`task ${a} moved to /${t.to}`,"ask move"),"wave create":i((e,[a])=>`wave ${a} created`,"wave create"),"wave add":i(async(e,[a,t])=>`${await h(e,t)} added to wave ${a}`,"wave add"),"wave remove":i(async(e,[a,t])=>`${await h(e,t)} taken out of wave ${a}`,"wave remove"),"wave set":i((e,[a])=>`wave ${a} updated`,"wave set"),"wave finish":i((e,[a])=>`wave ${a} finished`,"wave finish"),"review record":i((e,[a],t)=>`review of PR #${a} recorded: ${t.state==="needs"?"needs you":"posted"}`,"review record"),"reviewers set":i(()=>"reviewers replaced","reviewers set"),"reviewers add":i(()=>"reviewers added","reviewers add"),"reviewers remove":i((e,a)=>`${R(a,"reviewer")} removed`,"reviewers remove"),"rules add":i((e,a,t)=>`${t.hub?"hub":"board"} rule added`,"rules add"),"rules edit":i((e,[a],t)=>`${t.hub?"hub":"board"} rule ${a} reworded`,"rules edit"),"rules remove":i((e,[a],t)=>`${t.hub?"hub":"board"} rule ${a} removed`,"rules remove"),"builder start":i(async(e,[a],t,s)=>`${await h(e,a)}: ${s.alreadyOpen?"already open: the Implement tap opened its record; launch the agent, whose own builder start takes it up":`${T(t)} started`}`,"builder start"),"builder progress":i(async(e,[a])=>`progress line on ${await h(e,a)}`,"builder progress"),"builder done":i(async(e,[a],t,s)=>`${await h(e,a)}: ${s?.said??`${T(t)} done${t["owner-step"]===void 0?"":`; owner step "${t["owner-step"].trim()}"`}`}`,"builder done"),"builder call":i(async(e,[a])=>`judgment call recorded on ${await h(e,a)}`,"builder call"),"builder ask":i(async(e,[a],t,{id:s})=>`${await h(e,a)}: asked the orchestrator, ${s}`,"builder ask"),"builder answer":i(async(e,[a,t])=>`${await h(e,a)}: ${t} answered`,"builder answer"),"builder defer":i(async(e,[a,t])=>`${await h(e,a)}: ${t} deferred to the owner`,"builder defer"),"builder verified":i(async(e,[a],t,s)=>`${await h(e,a)}: judgment calls verified${s?.said?`; ${s.said}`:""}`,"builder verified"),land:i(async(e,[a],t,s)=>e?s?.said?`${await h(e,a)}: ${s.said}`:t["owner-step"]===void 0?`${await h(e,a)}: landed and done`:`${await h(e,a)}: landed; waits on the owner step "${t["owner-step"].trim()}"`:null,"land"),merge:i(async(e,[a],t,s)=>`${await h(e,a)}: ${s?.said??"merged"}`,"merge"),"arch file":i(async(e,[a])=>`findings of ${await h(e,a)} filed`,"arch file")};async function fe(e,a={}){try{const{flags:t,rest:s}=oe(e),r=[3,2,1].map(u=>s.slice(0,u).join(" ")).find(u=>y(b,u)),o=y(b,r);if(!o)throw new d(s.length?`unknown command "${s.slice(0,2).join(" ")}"`:"no command given");const[l,c,p]=o,f=s.slice(r.split(" ").length),_=l.at(-1)?.startsWith("..."),B=l.at(-1)?.endsWith("?")?l.length-1:l.length;if(_?f.length<B:f.length!==l.length)throw new d(`${r} takes ${l.map(u=>`<${u.replace(/^\.\.\.|\?$/g,"")}>`).join(" ")||"no arguments"}`);const{site:A,...E}=t;if(A?.length>1)throw new d("--site is given twice");const I=A?.[0],k=de(r,c,E);ue(c,k);const P=I===void 0?null:await n.siteDir(I),v=await p(P,f,k,a),O=y(me,r),j=O&&await O(P,f,k,v);j&&console.log(j);for(const u of typeof v=="object"&&v?.lines||[])console.log(u);return 0}catch(t){if(t instanceof d)return console.error(`${t.message} (node board.mjs --help lists the commands)`),2;if(t instanceof n.BoardError)return console.error(t.message),t.exitCode??1;throw t}}if(i(fe,"main"),process.argv[1]&&import.meta.url===L(g.realpathSync(process.argv[1])).href){const e=process.argv.slice(2);!e.length||e.includes("--help")||e[0]==="help"?console.log(ie):process.exitCode=await fe(e)}export{ie as USAGE,fe as main};