@lovek4d/kickflip 0.5.0 → 0.5.3

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 (76) hide show
  1. package/CONTEXT.md +47 -42
  2. package/README.md +1 -1
  3. package/SKILL.md +16 -16
  4. package/bin/kickflip.mjs +26 -17
  5. package/bin/wait-events.mjs +2 -2
  6. package/board/agents.mjs +2 -0
  7. package/board/bin/board.mjs +65 -18
  8. package/board/domain.mjs +7 -7
  9. package/board/finish.mjs +4 -4
  10. package/board/headless.mjs +5 -4
  11. package/board/on-host.mjs +1 -1
  12. package/board/public/app-asks.js +6 -6
  13. package/board/public/app-banner.js +7 -13
  14. package/board/public/app-cards.js +51 -27
  15. package/board/public/app-core.js +26 -8
  16. package/board/public/app-header.js +2 -1
  17. package/board/public/app-lanes.js +55 -23
  18. package/board/public/app-needs.js +129 -4
  19. package/board/public/app-reader.js +1 -1
  20. package/board/public/app-snapshot.js +6 -5
  21. package/board/public/app-threads.js +70 -59
  22. package/board/public/app.js +38 -8
  23. package/board/public/attach.js +2 -2
  24. package/board/public/dialogs.js +9 -39
  25. package/board/public/hub-kit.js +4 -2
  26. package/board/public/linear-key.js +46 -35
  27. package/board/public/new-task.js +17 -38
  28. package/board/public/prototype-kit.js +28 -3
  29. package/board/public/prototype-switcher.js +42 -107
  30. package/board/public/shell.js +7 -5
  31. package/board/public/sidebar.js +44 -5
  32. package/board/public/style.css +108 -37
  33. package/board/public/ui-cards.js +41 -30
  34. package/board/public/ui-header.js +2 -2
  35. package/board/public/ui-order.js +12 -10
  36. package/board/public/ui-questions.js +25 -38
  37. package/board/public/ui-sidebar.js +18 -12
  38. package/board/public/ui-threads.js +3 -3
  39. package/board/public/ui.js +40 -8
  40. package/board/public/view-hub-settings.js +11 -10
  41. package/board/public/view-hub.js +17 -3
  42. package/board/public/view-questions.js +142 -199
  43. package/board/public/view-settings.js +191 -72
  44. package/board/server.mjs +19 -20
  45. package/board/store.mjs +20 -15
  46. package/board/transcript.mjs +2 -0
  47. package/board/worktree.mjs +24 -20
  48. package/hooks-plugin/hooks/board-data-gate.mjs +50 -0
  49. package/hooks-plugin/hooks/hooks.json +9 -0
  50. package/hub/boards.mjs +4 -4
  51. package/hub/front-door.mjs +5 -5
  52. package/hub/github.mjs +3 -3
  53. package/hub/hub.mjs +11 -11
  54. package/hub/linear.mjs +1 -2
  55. package/hub/live.mjs +2 -2
  56. package/hub/locks.mjs +1 -1
  57. package/hub/pr-report.mjs +2 -2
  58. package/hub/presence.mjs +1 -1
  59. package/hub/push.mjs +2 -2
  60. package/hub/readiness.mjs +1 -2
  61. package/hub/review-send.mjs +1 -0
  62. package/hub/secrets.mjs +2 -0
  63. package/hub/self-restart.mjs +2 -0
  64. package/hub/sessions.mjs +2 -2
  65. package/hub/share.mjs +1 -0
  66. package/hub/slack.mjs +2 -2
  67. package/hub/stream.mjs +10 -13
  68. package/hub/try.mjs +6 -6
  69. package/hub/upgrade.mjs +1 -1
  70. package/hub/usage.mjs +3 -3
  71. package/hub/views.mjs +1 -1
  72. package/package.json +2 -1
  73. package/shared/audit.mjs +4 -0
  74. package/shared/fake-gh.mjs +17 -4
  75. package/shared/service.mjs +4 -4
  76. package/shared/usage-gate.mjs +1 -1
package/hub/sessions.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var ne=Object.defineProperty;var a=(e,s)=>ne(e,"name",{value:s,configurable:!0});import x from"node:fs";import w from"node:path";import j from"node:os";import{spawn as K,spawnSync as oe}from"node:child_process";import{fileURLToPath as ie}from"node:url";import{joinName as re,routeRecord as h,validRoute as ae}from"./routes.mjs";import{withFileLock as ce}from"./locks.mjs";import{RESUME_STATE as D,carryCursor as ue,hubBoard as W,isListening as de,listBoards as L,listenState as le,oldestUnheard as fe,readManifest as I,readJSON as P,saveJSON as J,watchedCounts as pe,watchedLines as me,watcherCursor as he,withManifestLock as we,writeManifest as ge}from"./boards.mjs";import{readUsageGate as be,heldUsageEvent as ke}from"../shared/usage-gate.mjs";import{liveSessions as _,sessionRecords as $e,processStarts as ye,verifiedProcess as Ie}from"./live.mjs";import{deliver as Se}from"./push.mjs";import{WAIT_MS as _e}from"./prompts.mjs";import{nodeBin as H,storedPath as X}from"../bin/install.mjs";import{reposDir as Te}from"../shared/repos.mjs";import{isClone as xe}from"./repos.mjs";import{trustFolder as je}from"./trust.mjs";import{contextFull as Oe,contextReading as ve}from"./usage.mjs";const O=X(w.resolve(w.dirname(ie(import.meta.url)),"..")),Ae=3*6e4,Ee=5*6e4,Ce=15*6e4,q=w.join(j.homedir(),".claude","kickflip","compact-state.json"),De=a((e,s=Date.now())=>!!e.error||s-Date.parse(e.asked_at||e.since)>=Ce,"startFailed");function Le(e){return e.joined_at?{step:"landing",stepAt:e.joined_at}:e.phase==="cloning"?{step:"cloning",stepAt:e.asked_at}:{step:"starting",stepAt:e.phase_at||e.asked_at||e.since}}a(Le,"startStep");function ps(e,s=Date.now(),t=()=>{},r=()=>!0){return Object.entries(e.starting||{}).filter(([i,n])=>h(e.sites,i)?n.joined_at&&!r(i):!0).map(([i,n])=>{const o=De(n,s);return{route:i,title:n.title||n.label||i,repo:n.repo,...Le(n),...n.phase==="cloning"&&t(i)!==void 0?{percent:t(i)}:{},...n.branch?{branch:n.branch,tickets:n.tickets}:{},askedAt:n.asked_at||n.since,failed:o,...n.joined_at?{joined:!0}:{},...n.error?{error:n.error}:o&&n.joined_at?{error:"Its session joined, but the board is not listening yet."}:{}}})}a(ps,"startingBoards");const Pe=_e/1e3+60,Ue=JSON.stringify({worktree:{bgIsolation:"none"},permissions:{deny:["Workflow"]},hooks:{PermissionRequest:[{matcher:"*",hooks:[{type:"command",command:`"${H()}" "${w.join(O,"hub","permission-hook.mjs")}"`,timeout:Pe}]}],PermissionDenied:[{matcher:"Bash",hooks:[{type:"command",command:`"${H()}" "${w.join(O,"hub","permission-denied-hook.mjs")}"`,timeout:15}]}]}});class m extends Error{static{a(this,"SessionError")}constructor(s,t){super(s),this.reason=t}}function Ne(e,s){if(!ae(e))throw new m("Choose a board route.","none");return ce(w.join(j.homedir(),".claude","kickflip","session-locks",e),()=>s({resume:a(t=>Xe(e,t),"resume")}),{staleAfter:12e4,timeout:9e4})}a(Ne,"withSessionLock");function v(){if(process.env.KICKFLIP_CLAUDE)return process.env.KICKFLIP_CLAUDE;const e=w.join(j.homedir(),".local","bin","claude");return x.existsSync(e)?e:"claude"}a(v,"claudeBin");const A=a(e=>e==="CLAUDECODE"||e==="CLAUDE_PID"||e==="CLAUDE_EFFORT"||e.startsWith("CLAUDE_CODE_"),"inherited");function Q(){return process.env.KICKFLIP_TMUX?process.env.KICKFLIP_TMUX:["/opt/homebrew/bin/tmux","/usr/local/bin/tmux","/usr/bin/tmux"].find(e=>x.existsSync(e))||"tmux"}a(Q,"tmuxBin");function U(e){const s=oe(Q(),e,{encoding:"utf8",timeout:1e4,env:Object.fromEntries(Object.entries(process.env).filter(([t])=>!A(t)))});return s.error?.code==="ENOENT"?{status:127,stdout:"",stderr:"tmux isn't installed; kickflip doctor names how to install it"}:{status:s.status??1,stdout:s.stdout||"",stderr:s.stderr||s.error?.message||""}}a(U,"runTmux");const S=a(e=>`kickflip-${e}`,"tmuxName"),N=a((e,s)=>e(["has-session","-t",`=${S(s)}`]).status===0,"hasTmux");async function ms({manifest:e=I(),now:s=new Date,running:t=_(),wakes:r=P(D,{}),tmux:i=U}={}){if(!t)return{compacted:[],failed:[]};const n=Object.assign(Object.create(null),P(q,{})),o=[],l=[];let u=!1;const c=W(e)?.route;for(const p of L(e)){const f=ve(p.owner?.session);if(!Oe(le(p,{now:s.getTime(),running:t,wakes:r}),f)){h(n,p.route)&&(delete n[p.route],u=!0);continue}if(p.route!==c||h(n,p.route)||!N(i,p.route))continue;const d=`=${S(p.route)}:`,$=i(["send-keys","-t",d,"-l","/compact"]),k=$.status===0?i(["send-keys","-t",d,"Enter"]):$,g=k.status===0?null:(k.stderr||k.stdout).trim().slice(0,300)||`tmux exited ${k.status}`;n[p.route]={session:p.owner.session,percent:f.percent,at:s.toISOString(),...g?{error:g}:{}},u=!0,g?l.push(`${p.route}: could not send /compact to tmux session ${S(p.route)} (${g})`):o.push(p.route)}return u&&J(q,n),{compacted:o,failed:l}}a(ms,"compactFullContexts");function B(e,{cwd:s,timeout:t=6e4}){const r=v(),i=Object.fromEntries(Object.entries(process.env).filter(([n])=>!A(n)));return i.CLAUDE_BG_ISOLATION="none",w.isAbsolute(r)&&(i.PATH=`${w.dirname(r)}:${i.PATH||""}`),new Promise(n=>{let o="",l="",u;try{u=K(r,e,{cwd:s,env:i,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(f){n({status:1,stdout:o,stderr:f.message});return}const c=a(f=>{clearTimeout(p),u.stdout.destroy(),u.stderr.destroy(),n({status:f,stdout:o,stderr:l})},"done"),p=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}c(1)},t);u.stdout.on("data",f=>{o+=f}),u.stderr.on("data",f=>{l+=f}),u.on("error",f=>{l+=f.message,c(1)}),u.on("close",f=>c(f??1)),u.on("exit",f=>setTimeout(()=>c(f??1),300)),u.unref()})}a(B,"runClaude");async function Be(e,{cwd:s,run:t=B,starts:r=ye,signal:i=process.kill}={}){if(e.kind==="bg"){const n=await t(["stop",e.jobId||e.sessionId.slice(0,8)],{cwd:s,timeout:8e3});if(n.status!==0)throw new m(`claude stop failed: ${(n.stderr||n.stdout).trim().slice(0,300)}`,"failed")}else{if(!Ie(e,r))throw new m(`Cannot verify session ${e.sessionId}'s process identity; refusing to signal pid ${e.pid}.`,"failed");i(e.pid,"SIGTERM")}}a(Be,"runSessionStop");async function hs(e,{live:s=_,stop:t=Be}={}){if(!e?.session)return;const r=s();if(!r)throw new m(ee(e.session),"unknown");const i=r.get(e.session);if(!i)return;await t(i,{cwd:e.repo||i.cwd||j.homedir()});const n=Date.now()+5e3;for(let o=s();!o||o.get(e.session)?.pid===i.pid;o=s()){if(Date.now()>=n)throw new m(`session ${e.session} did not stop`,"failed");await new Promise(l=>setTimeout(l,100))}}a(hs,"stopSession");function Me(e){const s=`=${S(e)}`;return Re(Q(),process.env.TMUX?["switch-client","-t",s]:["attach-session","-t",s])}a(Me,"attachTmux");function Re(e,s){const t=Object.fromEntries(Object.entries(process.env).filter(([n])=>!A(n)&&n!=="CLAUDE_BG_ISOLATION")),r=a(()=>{},"ignore");process.on("SIGINT",r).on("SIGQUIT",r);const i=a(()=>process.off("SIGINT",r).off("SIGQUIT",r),"settle");return new Promise((n,o)=>{const l=K(e,s,{env:t,stdio:"inherit"});l.on("error",u=>{i(),o(new m(u.message,"failed"))}),l.on("close",u=>{i(),n({status:u??1})})})}a(Re,"runForeground");const M=a(({name:e,model:s})=>["--name",e,"--permission-mode","auto","--settings",Ue,...s?["--model",s]:[]],"common"),Fe=a(e=>`'${e.replaceAll("'","'\\''")}'`,"quote"),E=a((e,s)=>`--name ${Fe(re(e,s))}`,"boardFlag"),Ge=a(({route:e,name:s,model:t,prompt:r})=>["--bg",...M({name:s,model:t}),`/kickflip ${E(e,s)}${r?` ${r}`:""}`],"startArgv"),Ke=a((e,s,t)=>`The hub resumed this session because /${e} had nobody listening. Rejoin the board as session ${s} (kickflip steps 3 and 5): rerun \`node ${w.join(O,"bin","kickflip.mjs")} join ${E(e,t)} --session ${s}\`, relaunch its watcher as a background task, then go on with what its events ask. If your session id (the folder above your scratchpad) isn't ${s}, rejoin with yours and --force.`,"resumePrompt"),We=a(({id:e,route:s,name:t,model:r,background:i})=>["--resume",e,"--bg",...i?[]:M({name:t,model:r}),Ke(s,e,t)],"resumeArgv"),Y=a((e,s)=>`You are the hub session. Read \`${w.join(O,"docs","hub-session.md")}\`, then rejoin /${e} (join ${E(e,s)}) and relaunch its watcher.`,"hubPrompt"),z=a(({route:e,title:s,id:t,model:r})=>[...t?["--resume",t]:[],...M({name:s,model:r}),t?`${Y(e,s)} If your session id (the folder above your scratchpad) isn't ${t}, rejoin with yours and --force.`:`/kickflip ${E(e,s)} --hub
2
- ${Y(e,s)}`],"hubArgv");function V(e,s,{cwd:t,tmux:r}){const i=v(),n=[...new Set(["CLAUDECODE","CLAUDE_BG_ISOLATION",...Object.keys(process.env).filter(A)])].flatMap(l=>["-u",l]),o=r(["new-session","-d","-s",S(e),"-c",t,"/usr/bin/env",...n,...w.isAbsolute(i)?[`PATH=${w.dirname(i)}:${process.env.PATH||""}`]:[],i,...s]);if(o.status!==0)throw new m(`tmux new-session failed (${o.status}): ${(o.stderr||o.stdout).trim().slice(0,300)}`,"failed");return[i,...s]}a(V,"startTmux");async function ws({manifest:e=I(),repo:s,tmux:t=U,attach:r=Me,live:i=_}={}){const n=W(e);if(!n)throw new m("No hub board is flagged; flag one with kickflip set <route> --hub, or run kickflip join --hub in its repo folder","hub");if(!N(t,n.route)){const o=n.owner?.session?n.owner:null;if(o&&!o.repo&&!s)throw new m(`/${n.route}'s session ${o.session} has no folder recorded; pass --repo <its folder>`,"none");F(o,i);const l=o?.repo||w.resolve(s||process.cwd());if(!x.statSync(l,{throwIfNoEntry:!1})?.isDirectory())throw new m(o?.repo?`/${n.route}'s recorded folder ${l} is gone; rejoin from its new folder with --repo`:`no folder at ${l}`,"none");V(n.route,z({route:n.route,title:n.title,id:o?.session,model:o?.model}),{cwd:l,tmux:t})}return r(n.route)}a(ws,"hubSession");function R(e,s){const t=h(e?.sites,s),r=t?.owner?.session?t.owner:h(e?.starting,s);return r?.session?{...r,title:t?.title||s}:null}a(R,"sessionOf");async function Z(e,s=null){const t=e.match(/backgrounded\s*·\s*([0-9a-f]{8})\b/)?.[1]||e.match(/\bclaude attach ([0-9a-f]{8})\b/)?.[1];if(!t)return{session:s,confirmed:!1};if(s?.startsWith(t))return{session:s,confirmed:!0};for(let r=0;r<20;r++){const i=$e().find(n=>n.jobId===t||n.sessionId.startsWith(t));if(i)return{session:i.sessionId,confirmed:!0};await new Promise(n=>setTimeout(n,500))}return{session:s,confirmed:!1}}a(Z,"startedId");async function Je(e,{run:s,cwd:t}){const r=await s(["agents","--json","--all"],{cwd:t});try{return JSON.parse(r.stdout).some(i=>i?.sessionId===e&&i.kind==="background")}catch{return!1}}a(Je,"isBackground");const ee=a(e=>`Couldn't tell whether session ${e} is live: ps gave no answer in time, as happens on a busy Mac. Try again in a moment.`,"unknownLiveness");function F(e,s){if(!e)return;const t=s();if(!t)throw new m(ee(e.session),"unknown");const r=t.get(e.session);if(r)throw new m(`session ${e.session} is live (${r.kind==="bg"?"in the background":"in a terminal"}, pid ${r.pid}); it gets no second process`,"live")}a(F,"refuseLive");async function se(e,{from:s,to:t,mark:r}){await we(async()=>{const i=I(),n=L(i).find(l=>l.route===e);if(n?.owner?.session===s&&(r||t!==s)&&ue(n,{from:s,to:t,mark:r}),t===s)return;const o=h(i.sites,e);if(o?.owner?.session===s)Object.assign(o,{owner:{...o.owner,session:t},updated:new Date().toISOString()});else if(h(i.starting,e)?.session===s)i.starting[e]={...h(i.starting,e),session:t};else return;await ge(i)})}a(se,"moveOwner");async function gs(e,{manifest:s=I(),repo:t,model:r,prompt:i,run:n=B,live:o=_,clones:l=Te()}={}){if(h(s.closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const u=R(s,e);F(u,o);const c=w.resolve(t||u?.repo||process.cwd());if(!x.statSync(c,{throwIfNoEntry:!1})?.isDirectory())throw new m(`no folder at ${c}`,"none");if(xe(c,l))try{je(c)}catch(g){throw new m(`Couldn't trust this folder for Claude Code: ${g.message}`,"failed")}const p=h(s?.sites,e)?.title||h(s?.starting,e)?.title||e,f=Ge({route:e,name:p,model:r||u?.model,prompt:i}),d=await n(f,{cwd:c});if(d.status!==0){const g=(d.stderr||"").trim()||(d.stdout||"").trim();throw new m(g?`claude --bg failed (${d.status}): ${g.slice(0,300)}`:`claude exited ${d.status} with no output; check \`claude agents\``,"failed")}const{session:$,confirmed:k}=await Z(d.stdout);if(!$)throw new m(`claude --bg started a session but no session record names it yet; find it with claude agents (${d.stdout.trim().slice(0,300)})`,"failed");return{route:e,session:$,confirmed:k,repo:X(c),model:r||u?.model||null,name:p,argv:[v(),...f],output:d.stdout.trim()}}a(gs,"startSession");function He(e,s={}){return Ne(e,({resume:t})=>t(s))}a(He,"resumeSession");async function Xe(e,{manifest:s=I(),run:t=B,tmux:r=U,live:i=_,mark:n=null}={}){if(h(I().closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const o=R(s,e);if(!o)throw new m(`/${e} has no recorded session`,"none");if(!o.repo)throw new m(`/${e}'s session ${o.session} has no folder recorded; its session records one by rejoining (kickflip join, --repo)`,"none");if(F(o,i),h(s.sites,e)?.hub===!0){if(N(r,e))throw new m(`/${e}'s tmux session ${S(e)} is still open; attach with kickflip hub`,"live");const d=V(e,z({route:e,title:o.title,id:o.session,model:o.model}),{cwd:o.repo,tmux:r});return await se(e,{from:o.session,to:o.session,mark:n}),{route:e,session:o.session,previous:o.session,confirmed:!1,repo:o.repo,argv:d,output:`in tmux session ${S(e)}`}}const l=await Je(o.session,{run:t,cwd:o.repo}),u=We({id:o.session,route:e,name:o.title,model:o.model,background:l}),c=await t(u,{cwd:o.repo});if(c.status!==0)throw new m(`claude --resume failed (${c.status}): ${(c.stderr||c.stdout).trim().slice(0,300)}`,"failed");const{session:p,confirmed:f}=await Z(c.stdout,o.session);return await se(e,{from:o.session,to:p,mark:n}),{route:e,session:p,previous:o.session,confirmed:f,repo:o.repo,argv:[v(),...u],output:c.stdout.trim()}}a(Xe,"resumeRecordedSession");function qe(e,{listening:s,live:t,recorded:r,counts:i,waiting:n,asked:o=!1,now:l}){if(s)return{action:"none",entry:null};const u=new Date(l).toISOString(),c=e?{...e}:{down_since:u};return t?delete c.mark:!c.mark&&i&&(c.mark=i),c.pushed_at?{action:"none",entry:c}:c.resumed_at?c.error||l-Date.parse(c.resumed_at)>=Ee?{action:"push",entry:{...c,pushed_at:u}}:{action:"none",entry:c}:!r||t?{action:"none",entry:c}:!!(e?.mark&&i&&Object.entries(i).some(([f,d])=>d>(h(e.mark,f)??0)))||o||n&&l-Date.parse(c.down_since)>=Ae?{action:"resume",entry:{...c,resumed_at:u}}:{action:"none",entry:c}}a(qe,"resumeStep");async function bs({manifest:e=I(),now:s=new Date,live:t=_,asked:r=new Set,listening:i=a((u,c)=>de(u,{now:s.getTime(),running:c}),"listening"),resume:n=a((u,c)=>He(u,{manifest:e,live:t,mark:c}),"resume"),push:o=Se,gate:l=be({now:s})}={}){const u=t();if(!u)return{resumed:[],pushed:[],failed:[]};const c=P(D,{}),p=Object.create(null),f={resumed:[],pushed:[],failed:[]};for(const d of L(e)){const $=R(e,d.route),k=!!($&&u.has($.session)),g=i(d,u);let{action:T,entry:b}=qe(h(c,d.route),{listening:g,live:k,recorded:!!$?.repo,now:s.getTime(),asked:r.has(d.route),counts:g?null:pe(d),waiting:!g&&!k&&fe(d)!==null});if(T==="resume"&&l.state==="paused"){const y=h(c,d.route)?.mark||he(d);Object.entries(me(d)).flatMap(([C,te])=>te.slice(h(y,C)||0)).some(C=>!ke(C))||(T="none",delete b.resumed_at)}if(T==="resume")try{await n(d.route,b.mark),f.resumed.push(d.route)}catch(y){y.reason==="unknown"?delete b.resumed_at:b={...b,error:y.message},f.failed.push(`${d.route}: could not resume its session (${y.message})`)}else if(T==="push"){const y=b.error?`The hub couldn't resume it: ${b.error}`:k?"Its session is running but hasn't relaunched its watcher.":`It still isn't listening after the hub resumed it. Try kickflip resume ${d.route}, or claude agents.`;try{await o({title:`${d.title}'s session didn't come back`,body:y,url:`/${d.route}/`,tag:`resume-${d.route}`},{kind:"fault",immediate:!0,at:s}),f.pushed.push(d.route)}catch(G){b={...b,pushed_at:void 0},f.failed.push(`${d.route}: could not push that its session didn't come back (${G.message})`)}}b&&(p[d.route]=b)}return JSON.stringify(p)!==JSON.stringify(c)&&J(D,p),f}a(bs,"checkSessions");export{Ue as BG_SETTINGS,Ee as COMEBACK_WAIT,Pe as PROMPT_HOOK_TIMEOUT_S,Ae as RESUME_AFTER,Ce as STARTING_WAIT,m as SessionError,Me as attachTmux,bs as checkSessions,v as claudeBin,ms as compactFullContexts,z as hubArgv,ws as hubSession,A as inherited,We as resumeArgv,Ke as resumePrompt,He as resumeSession,qe as resumeStep,B as runClaude,Be as runSessionStop,U as runTmux,R as sessionOf,Ge as startArgv,De as startFailed,gs as startSession,ps as startingBoards,hs as stopSession,Q as tmuxBin,S as tmuxName,Ne as withSessionLock};
1
+ var ce=Object.defineProperty;var a=(e,s)=>ce(e,"name",{value:s,configurable:!0});import O from"node:fs";import g from"node:path";import A from"node:os";import{spawn as J,spawnSync as de}from"node:child_process";import{fileURLToPath as ue}from"node:url";import{joinName as le,routeRecord as h,validRoute as fe}from"./routes.mjs";import{withFileLock as pe}from"./locks.mjs";import{RESUME_STATE as P,carryCursor as me,hubBoard as H,isListening as he,listBoards as U,listenState as we,oldestUnheard as ge,readManifest as _,readJSON as N,saveJSON as X,watchedCounts as be,watchedLines as $e,watcherCursor as ke,withManifestLock as ye,writeManifest as Ie}from"./boards.mjs";import{readUsageGate as Se,heldUsageEvent as _e}from"../shared/usage-gate.mjs";import{liveSessions as x,sessionRecords as Te,processStarts as xe,verifiedProcess as je}from"./live.mjs";import{deliver as ve}from"./push.mjs";import{WAIT_MS as Oe}from"./prompts.mjs";import{nodeBin as q,storedPath as Q}from"../bin/install.mjs";import{reposDir as Ae}from"../shared/repos.mjs";import{isClone as Ee}from"./repos.mjs";import{trustFolder as Ce}from"./trust.mjs";import{contextFull as De,contextReading as Le}from"./usage.mjs";import{audit as Y,boardAudit as z}from"../shared/audit.mjs";const E=Q(g.resolve(g.dirname(ue(import.meta.url)),"..")),Pe=3*6e4,Ue=5*6e4,Ne=15*6e4,V=g.join(A.homedir(),".claude","kickflip","compact-state.json"),Be=a((e,s=Date.now())=>!!e.error||s-Date.parse(e.asked_at||e.since)>=Ne,"startFailed");function Me(e){return e.joined_at?{step:"landing",stepAt:e.joined_at}:e.phase==="cloning"?{step:"cloning",stepAt:e.asked_at}:{step:"starting",stepAt:e.phase_at||e.asked_at||e.since}}a(Me,"startStep");function $s(e,s=Date.now(),t=()=>{},r=()=>!0){return Object.entries(e.starting||{}).filter(([i,n])=>h(e.sites,i)?n.joined_at&&!r(i):!0).map(([i,n])=>{const o=Be(n,s);return{route:i,title:n.title||n.label||i,repo:n.repo,...Me(n),...n.phase==="cloning"&&t(i)!==void 0?{percent:t(i)}:{},...n.branch?{branch:n.branch,tickets:n.tickets}:{},askedAt:n.asked_at||n.since,failed:o,...n.joined_at?{joined:!0}:{},...n.error?{error:n.error}:o&&n.joined_at?{error:"Its session joined, but the board is not listening yet."}:{}}})}a($s,"startingBoards");const Re=Oe/1e3+60,Fe=JSON.stringify({worktree:{bgIsolation:"none"},permissions:{deny:["Workflow"]},hooks:{PermissionRequest:[{matcher:"*",hooks:[{type:"command",command:`"${q()}" "${g.join(E,"hub","permission-hook.mjs")}"`,timeout:Re}]}],PermissionDenied:[{matcher:"Bash",hooks:[{type:"command",command:`"${q()}" "${g.join(E,"hub","permission-denied-hook.mjs")}"`,timeout:15}]}]}});class m extends Error{static{a(this,"SessionError")}constructor(s,t){super(s),this.reason=t}}function Ge(e,s){if(!fe(e))throw new m("Choose a board route.","none");return pe(g.join(A.homedir(),".claude","kickflip","session-locks",e),()=>s({resume:a(t=>Ve(e,t),"resume")}),{staleAfter:12e4,timeout:9e4})}a(Ge,"withSessionLock");function C(){if(process.env.KICKFLIP_CLAUDE)return process.env.KICKFLIP_CLAUDE;const e=g.join(A.homedir(),".local","bin","claude");return O.existsSync(e)?e:"claude"}a(C,"claudeBin");const D=a(e=>e==="CLAUDECODE"||e==="CLAUDE_PID"||e==="CLAUDE_EFFORT"||e.startsWith("CLAUDE_CODE_"),"inherited");function Z(){return process.env.KICKFLIP_TMUX?process.env.KICKFLIP_TMUX:["/opt/homebrew/bin/tmux","/usr/local/bin/tmux","/usr/bin/tmux"].find(e=>O.existsSync(e))||"tmux"}a(Z,"tmuxBin");function B(e){const s=de(Z(),e,{encoding:"utf8",timeout:1e4,env:Object.fromEntries(Object.entries(process.env).filter(([t])=>!D(t)))});return s.error?.code==="ENOENT"?{status:127,stdout:"",stderr:"tmux isn't installed; kickflip doctor names how to install it"}:{status:s.status??1,stdout:s.stdout||"",stderr:s.stderr||s.error?.message||""}}a(B,"runTmux");const T=a(e=>`kickflip-${e}`,"tmuxName"),M=a((e,s)=>e(["has-session","-t",`=${T(s)}`]).status===0,"hasTmux");async function ks({manifest:e=_(),now:s=new Date,running:t=x(),wakes:r=N(P,{}),tmux:i=B}={}){if(!t)return{compacted:[],failed:[]};const n=Object.assign(Object.create(null),N(V,{})),o=[],f=[];let u=!1;const c=H(e)?.route;for(const p of U(e)){const l=Le(p.owner?.session);if(!De(we(p,{now:s.getTime(),running:t,wakes:r}),l)){h(n,p.route)&&(delete n[p.route],u=!0);continue}if(p.route!==c||h(n,p.route)||!M(i,p.route))continue;const d=`=${T(p.route)}:`,y=i(["send-keys","-t",d,"-l","/compact"]),b=y.status===0?i(["send-keys","-t",d,"Enter"]):y,w=b.status===0?null:(b.stderr||b.stdout).trim().slice(0,300)||`tmux exited ${b.status}`;n[p.route]={session:p.owner.session,percent:l.percent,at:s.toISOString(),...w?{error:w}:{}},Y(z(p.dir),{call:"compact",result:w?"failed":"typed /compact",reason:`Its session's context is ${l.percent}% full and it isn't listening.${w?` ${w}`:""}`,inputs:{session:p.owner.session,context:l}},{now:s}),u=!0,w?f.push(`${p.route}: could not send /compact to tmux session ${T(p.route)} (${w})`):o.push(p.route)}return u&&X(V,n),{compacted:o,failed:f}}a(ks,"compactFullContexts");function R(e,{cwd:s,timeout:t=6e4}){const r=C(),i=Object.fromEntries(Object.entries(process.env).filter(([n])=>!D(n)));return i.CLAUDE_BG_ISOLATION="none",g.isAbsolute(r)&&(i.PATH=`${g.dirname(r)}:${i.PATH||""}`),new Promise(n=>{let o="",f="",u;try{u=J(r,e,{cwd:s,env:i,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(l){n({status:1,stdout:o,stderr:l.message});return}const c=a(l=>{clearTimeout(p),u.stdout.destroy(),u.stderr.destroy(),n({status:l,stdout:o,stderr:f})},"done"),p=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}c(1)},t);u.stdout.on("data",l=>{o+=l}),u.stderr.on("data",l=>{f+=l}),u.on("error",l=>{f+=l.message,c(1)}),u.on("close",l=>c(l??1)),u.on("exit",l=>setTimeout(()=>c(l??1),300)),u.unref()})}a(R,"runClaude");async function Ke(e,{cwd:s,run:t=R,starts:r=xe,signal:i=process.kill}={}){if(e.kind==="bg"){const n=await t(["stop",e.jobId||e.sessionId.slice(0,8)],{cwd:s,timeout:8e3});if(n.status!==0)throw new m(`claude stop failed: ${(n.stderr||n.stdout).trim().slice(0,300)}`,"failed")}else{if(!je(e,r))throw new m(`Cannot verify session ${e.sessionId}'s process identity; refusing to signal pid ${e.pid}.`,"failed");i(e.pid,"SIGTERM")}}a(Ke,"runSessionStop");async function ys(e,{live:s=x,stop:t=Ke}={}){if(!e?.session)return;const r=s();if(!r)throw new m(oe(e.session),"unknown");const i=r.get(e.session);if(!i)return;await t(i,{cwd:e.repo||i.cwd||A.homedir()});const n=Date.now()+5e3;for(let o=s();!o||o.get(e.session)?.pid===i.pid;o=s()){if(Date.now()>=n)throw new m(`session ${e.session} did not stop`,"failed");await new Promise(f=>setTimeout(f,100))}}a(ys,"stopSession");function We(e){const s=`=${T(e)}`;return Je(Z(),process.env.TMUX?["switch-client","-t",s]:["attach-session","-t",s])}a(We,"attachTmux");function Je(e,s){const t=Object.fromEntries(Object.entries(process.env).filter(([n])=>!D(n)&&n!=="CLAUDE_BG_ISOLATION")),r=a(()=>{},"ignore");process.on("SIGINT",r).on("SIGQUIT",r);const i=a(()=>process.off("SIGINT",r).off("SIGQUIT",r),"settle");return new Promise((n,o)=>{const f=J(e,s,{env:t,stdio:"inherit"});f.on("error",u=>{i(),o(new m(u.message,"failed"))}),f.on("close",u=>{i(),n({status:u??1})})})}a(Je,"runForeground");const F=a(({name:e,model:s})=>["--name",e,"--permission-mode","auto","--settings",Fe,...s?["--model",s]:[]],"common"),He=a(e=>`'${e.replaceAll("'","'\\''")}'`,"quote"),L=a((e,s)=>`--name ${He(le(e,s))}`,"boardFlag"),Xe=a(({route:e,name:s,model:t,prompt:r})=>["--bg",...F({name:s,model:t}),`/kickflip ${L(e,s)}${r?` ${r}`:""}`],"startArgv"),qe=a((e,s,t)=>`The hub resumed this session because /${e} had nobody listening. Rejoin the board as session ${s} (kickflip steps 3 and 5): rerun \`node ${g.join(E,"bin","kickflip.mjs")} join ${L(e,t)} --session ${s}\`, relaunch its watcher as a background task, then go on with what its events ask. If your session id (the folder above your scratchpad) isn't ${s}, rejoin with yours and --force.`,"resumePrompt"),Qe=a(({id:e,route:s,name:t,model:r,background:i})=>["--resume",e,"--bg",...i?[]:F({name:t,model:r}),qe(s,e,t)],"resumeArgv"),ee=a((e,s)=>`You are the hub session. Read \`${g.join(E,"docs","hub-session.md")}\`, then rejoin /${e} (join ${L(e,s)}) and relaunch its watcher.`,"hubPrompt"),se=a(({route:e,title:s,id:t,model:r})=>[...t?["--resume",t]:[],...F({name:s,model:r}),t?`${ee(e,s)} If your session id (the folder above your scratchpad) isn't ${t}, rejoin with yours and --force.`:`/kickflip ${L(e,s)} --hub
2
+ ${ee(e,s)}`],"hubArgv");function te(e,s,{cwd:t,tmux:r}){const i=C(),n=[...new Set(["CLAUDECODE","CLAUDE_BG_ISOLATION",...Object.keys(process.env).filter(D)])].flatMap(f=>["-u",f]),o=r(["new-session","-d","-s",T(e),"-c",t,"/usr/bin/env",...n,...g.isAbsolute(i)?[`PATH=${g.dirname(i)}:${process.env.PATH||""}`]:[],i,...s]);if(o.status!==0)throw new m(`tmux new-session failed (${o.status}): ${(o.stderr||o.stdout).trim().slice(0,300)}`,"failed");return[i,...s]}a(te,"startTmux");async function Is({manifest:e=_(),repo:s,tmux:t=B,attach:r=We,live:i=x}={}){const n=H(e);if(!n)throw new m("No hub board is flagged; flag one with kickflip set <route> --hub, or run kickflip join --hub in its repo folder","hub");if(!M(t,n.route)){const o=n.owner?.session?n.owner:null;if(o&&!o.repo&&!s)throw new m(`/${n.route}'s session ${o.session} has no folder recorded; pass --repo <its folder>`,"none");K(o,i);const f=o?.repo||g.resolve(s||process.cwd());if(!O.statSync(f,{throwIfNoEntry:!1})?.isDirectory())throw new m(o?.repo?`/${n.route}'s recorded folder ${f} is gone; rejoin from its new folder with --repo`:`no folder at ${f}`,"none");te(n.route,se({route:n.route,title:n.title,id:o?.session,model:o?.model}),{cwd:f,tmux:t})}return r(n.route)}a(Is,"hubSession");function G(e,s){const t=h(e?.sites,s),r=t?.owner?.session?t.owner:h(e?.starting,s);return r?.session?{...r,title:t?.title||s}:null}a(G,"sessionOf");async function ne(e,s=null){const t=e.match(/backgrounded\s*·\s*([0-9a-f]{8})\b/)?.[1]||e.match(/\bclaude attach ([0-9a-f]{8})\b/)?.[1];if(!t)return{session:s,confirmed:!1};if(s?.startsWith(t))return{session:s,confirmed:!0};for(let r=0;r<20;r++){const i=Te().find(n=>n.jobId===t||n.sessionId.startsWith(t));if(i)return{session:i.sessionId,confirmed:!0};await new Promise(n=>setTimeout(n,500))}return{session:s,confirmed:!1}}a(ne,"startedId");async function Ye(e,{run:s,cwd:t}){const r=await s(["agents","--json","--all"],{cwd:t});try{return JSON.parse(r.stdout).some(i=>i?.sessionId===e&&i.kind==="background")}catch{return!1}}a(Ye,"isBackground");const oe=a(e=>`Couldn't tell whether session ${e} is live: ps gave no answer in time, as happens on a busy Mac. Try again in a moment.`,"unknownLiveness");function K(e,s){if(!e)return;const t=s();if(!t)throw new m(oe(e.session),"unknown");const r=t.get(e.session);if(r)throw new m(`session ${e.session} is live (${r.kind==="bg"?"in the background":"in a terminal"}, pid ${r.pid}); it gets no second process`,"live")}a(K,"refuseLive");async function ie(e,{from:s,to:t,mark:r}){await ye(async()=>{const i=_(),n=U(i).find(f=>f.route===e);if(n?.owner?.session===s&&(r||t!==s)&&me(n,{from:s,to:t,mark:r}),t===s)return;const o=h(i.sites,e);if(o?.owner?.session===s)Object.assign(o,{owner:{...o.owner,session:t},updated:new Date().toISOString()});else if(h(i.starting,e)?.session===s)i.starting[e]={...h(i.starting,e),session:t};else return;await Ie(i)})}a(ie,"moveOwner");async function Ss(e,{manifest:s=_(),repo:t,model:r,prompt:i,run:n=R,live:o=x,clones:f=Ae()}={}){if(h(s.closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const u=G(s,e);K(u,o);const c=g.resolve(t||u?.repo||process.cwd());if(!O.statSync(c,{throwIfNoEntry:!1})?.isDirectory())throw new m(`no folder at ${c}`,"none");if(Ee(c,f))try{Ce(c)}catch(w){throw new m(`Couldn't trust this folder for Claude Code: ${w.message}`,"failed")}const p=h(s?.sites,e)?.title||h(s?.starting,e)?.title||e,l=Xe({route:e,name:p,model:r||u?.model,prompt:i}),d=await n(l,{cwd:c});if(d.status!==0){const w=(d.stderr||"").trim()||(d.stdout||"").trim();throw new m(w?`claude --bg failed (${d.status}): ${w.slice(0,300)}`:`claude exited ${d.status} with no output; check \`claude agents\``,"failed")}const{session:y,confirmed:b}=await ne(d.stdout);if(!y)throw new m(`claude --bg started a session but no session record names it yet; find it with claude agents (${d.stdout.trim().slice(0,300)})`,"failed");return{route:e,session:y,confirmed:b,repo:Q(c),model:r||u?.model||null,name:p,argv:[C(),...l],output:d.stdout.trim()}}a(Ss,"startSession");function ze(e,s={}){return Ge(e,({resume:t})=>t(s))}a(ze,"resumeSession");async function Ve(e,{manifest:s=_(),run:t=R,tmux:r=B,live:i=x,mark:n=null}={}){if(h(_().closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const o=G(s,e);if(!o)throw new m(`/${e} has no recorded session`,"none");if(!o.repo)throw new m(`/${e}'s session ${o.session} has no folder recorded; its session records one by rejoining (kickflip join, --repo)`,"none");if(K(o,i),h(s.sites,e)?.hub===!0){if(M(r,e))throw new m(`/${e}'s tmux session ${T(e)} is still open; attach with kickflip hub`,"live");const d=te(e,se({route:e,title:o.title,id:o.session,model:o.model}),{cwd:o.repo,tmux:r});return await ie(e,{from:o.session,to:o.session,mark:n}),{route:e,session:o.session,previous:o.session,confirmed:!1,repo:o.repo,argv:d,output:`in tmux session ${T(e)}`}}const f=await Ye(o.session,{run:t,cwd:o.repo}),u=Qe({id:o.session,route:e,name:o.title,model:o.model,background:f}),c=await t(u,{cwd:o.repo});if(c.status!==0)throw new m(`claude --resume failed (${c.status}): ${(c.stderr||c.stdout).trim().slice(0,300)}`,"failed");const{session:p,confirmed:l}=await ne(c.stdout,o.session);return await ie(e,{from:o.session,to:p,mark:n}),{route:e,session:p,previous:o.session,confirmed:l,repo:o.repo,argv:[C(),...u],output:c.stdout.trim()}}a(Ve,"resumeRecordedSession");function Ze(e,{listening:s,live:t,recorded:r,counts:i,waiting:n,asked:o=!1,now:f}){if(s)return{action:"none",entry:null};const u=new Date(f).toISOString(),c=e?{...e}:{down_since:u};return t?delete c.mark:!c.mark&&i&&(c.mark=i),c.pushed_at?{action:"none",entry:c}:c.resumed_at?c.error||f-Date.parse(c.resumed_at)>=Ue?{action:"push",entry:{...c,pushed_at:u}}:{action:"none",entry:c}:!r||t?{action:"none",entry:c}:!!(e?.mark&&i&&Object.entries(i).some(([l,d])=>d>(h(e.mark,l)??0)))||o||n&&f-Date.parse(c.down_since)>=Pe?{action:"resume",entry:{...c,resumed_at:u}}:{action:"none",entry:c}}a(Ze,"resumeStep");async function _s({manifest:e=_(),now:s=new Date,live:t=x,asked:r=new Set,listening:i=a((u,c)=>he(u,{now:s.getTime(),running:c}),"listening"),resume:n=a((u,c)=>ze(u,{manifest:e,live:t,mark:c}),"resume"),push:o=ve,gate:f=Se({now:s})}={}){const u=t();if(!u)return{resumed:[],pushed:[],failed:[]};const c=N(P,{}),p=Object.create(null),l={resumed:[],pushed:[],failed:[]};for(const d of U(e)){const y=G(e,d.route),b=!!(y&&u.has(y.session)),w=i(d,u);let{action:j,entry:$}=Ze(h(c,d.route),{listening:w,live:b,recorded:!!y?.repo,now:s.getTime(),asked:r.has(d.route),counts:w?null:be(d),waiting:!w&&!b&&ge(d)!==null});if(j==="resume"&&f.state==="paused"){const I=h(c,d.route)?.mark||ke(d);Object.entries($e(d)).flatMap(([S,ae])=>ae.slice(h(I,S)||0)).some(S=>!_e(S))||(j="none",delete $.resumed_at)}const W=h(c,d.route),re={listening:w,live:b,asked:r.has(d.route),downSince:W?.down_since??null,resumedAt:W?.resumed_at??null},v=a((I,k,S)=>Y(z(d.dir),{call:I,result:k,reason:S,inputs:re},{now:s}),"logged");if(j==="resume"){const I=r.has(d.route)?"The owner opened the board's page while its session wasn't listening.":"An event waited while the board's session wasn't listening.";try{await n(d.route,$.mark),l.resumed.push(d.route),v("session-resume","resumed",I)}catch(k){k.reason==="unknown"?delete $.resumed_at:$={...$,error:k.message},l.failed.push(`${d.route}: could not resume its session (${k.message})`),v("session-resume","failed",`${I} ${k.message}`)}}else if(j==="push"){const I=$.error?`The hub couldn't resume it: ${$.error}`:b?"Its session is running but hasn't relaunched its watcher.":`It still isn't listening after the hub resumed it. Try kickflip resume ${d.route}, or claude agents.`,k=`Its session didn't come back after the hub resumed it: ${I}`;try{await o({title:`${d.title}'s session didn't come back`,body:I,url:`/${d.route}/`,tag:`resume-${d.route}`},{kind:"fault",immediate:!0,at:s}),l.pushed.push(d.route),v("push","sent",k)}catch(S){$={...$,pushed_at:void 0},l.failed.push(`${d.route}: could not push that its session didn't come back (${S.message})`),v("push","not sent",`${k} Not sent: ${S.message}`)}}$&&(p[d.route]=$)}return JSON.stringify(p)!==JSON.stringify(c)&&X(P,p),l}a(_s,"checkSessions");export{Fe as BG_SETTINGS,Ue as COMEBACK_WAIT,Re as PROMPT_HOOK_TIMEOUT_S,Pe as RESUME_AFTER,Ne as STARTING_WAIT,m as SessionError,We as attachTmux,_s as checkSessions,C as claudeBin,ks as compactFullContexts,se as hubArgv,Is as hubSession,D as inherited,Qe as resumeArgv,qe as resumePrompt,ze as resumeSession,Ze as resumeStep,R as runClaude,Ke as runSessionStop,B as runTmux,G as sessionOf,Xe as startArgv,Be as startFailed,Ss as startSession,$s as startingBoards,ys as stopSession,Z as tmuxBin,T as tmuxName,Ge as withSessionLock};
package/hub/share.mjs ADDED
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var u=(t,e)=>m(t,"name",{value:e,configurable:!0});import E from"node:path";import{isBoardSite as _,readJSON as w,saveJSON as b}from"./boards.mjs";const g=u(t=>typeof t=="string"&&t.length<=200&&/^[^\s@]+@[^\s@]+$/.test(t),"validLogin"),y=u(t=>Array.isArray(t?.share)?[...new Set(t.share.filter(g))]:[],"shareOf");function M(t,e){const i=new Set;for(const[c,s]of Object.entries(e||{}))_(s)&&y(w(E.join(s.dir,"board.json"),{})).includes(t)&&i.add(c);return i}u(M,"sharedRoutes");const x=new Set(["/","/sw.js","/manifest.webmanifest","/favicon.ico"]),R=/^\/_hub\/(?:app\/[\w.-]+|colors\.css|kickflip\.png|hub\.css|icon-(?:180|192|512)\.png|sidebar\.json|stream)$/,j=new Set(["/_hub","/_hub/","/_hub/settings","/_hub/settings/polling"]),D=new RegExp("^/(?:"+["","questions\\.html","notes\\.html","plan\\.html","index\\.html","prototype-[a-z0-9-]+\\.html","[\\w-][\\w.-]*\\.(?:js|mjs|css|png|svg|ico|webp|jpe?g|gif|woff2?)","prototypes/[a-z0-9-]+/[\\w-][\\w.-]*\\.js","uploads/[^/]+","api/(?:board|questions|done|links|working|thread|notes|plan|try/main/log)"].join("|")+")$");function U({method:t="GET",pathname:e,routes:i}){const c=t==="GET"||t==="HEAD";if(x.has(e)||R.test(e))return c?"pass":"view-only";if(j.has(e))return c?"home":"other";const s=/^\/([^/]+)(\/.*)?$/.exec(e);if(!s||!i.has(s[1]))return"other";const l=s[2]||"/";return l===`/${s[1]}`||l.startsWith(`/${s[1]}/`)?"view-only":c&&D.test(l)?"pass":"view-only"}u(U,"shareReach");function B(t){const e=String(t||"").split("/")[1]||"";if(!e||e==="_hub"||e.includes("."))return null;try{return decodeURIComponent(e)}catch{return null}}u(B,"routeOfPath");function F(t,e,i){const c=(t?.sites||[]).filter(s=>e.has(s.route)).map(({count:s,ctx:l,...p})=>p);return{code:t?.code??null,total:0,start:c[0]?.route??null,sites:c,starting:[],shared:{by:i||null}}}u(F,"sharedSidebar");const O=60*6e4,v=20,A=6e4;function H({file:t,now:e=Date.now}={}){const i=w(t,{}),c=new Map,s=new Map,l=new Map;let p=[];const S=u(()=>{try{b(t,i)}catch{}},"save");return{visit(n,o,r){const a=i[n]||={name:null,at:{}};let f=!1;if(o&&a.name!==o&&(a.name=o,f=!0),r){l.set(n,r);const h=new Date(e()).toISOString();a.at[r]=h;const d=`${n} ${r}`;e()-(c.get(d)??-1/0)<A||(c.set(d,e()),f=!0)}f&&S()},watching(n){return s.set(n,(s.get(n)||0)+1),()=>{const o=s.get(n)-1;o>0?s.set(n,o):s.delete(n)}},refuse(n,o,r){p=[{login:n,name:o||null,route:r||null,at:new Date(e()).toISOString()},...p.filter(a=>a.login!==n)].slice(0,v)},people(n,o){return o.map(r=>({login:r,name:i[r]?.name||null,now:s.has(r)&&l.get(r)===n,at:i[r]?.at?.[n]||null}))},refusals(n,o){const r=e()-O;return p.filter(a=>Date.parse(a.at)>=r&&(a.route===n||a.route===null)&&!o.includes(a.login)).map(({login:a,name:f,at:h})=>({login:a,name:f,at:h}))}}}u(H,"shareTracker");export{B as routeOfPath,y as shareOf,U as shareReach,H as shareTracker,M as sharedRoutes,F as sharedSidebar,g as validLogin};
package/hub/slack.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var w=Object.defineProperty;var n=(r,t)=>w(r,"name",{value:t,configurable:!0});import o from"node:fs";import s from"node:path";import m from"node:os";import{withFileLock as h}from"./locks.mjs";const i=["self_dm","owner_slack_user","slack_domain","timezone"],a=n(()=>s.join(m.homedir(),".claude","kickflip","slack.json"),"fileOf"),c=n(r=>{try{return JSON.parse(o.readFileSync(r,"utf8"))||{}}catch{return{}}},"read"),d=n(r=>Object.fromEntries(i.map(t=>[t,typeof r?.[t]=="string"?r[t]:""])),"identityOf");function f(r){const t=a();o.mkdirSync(s.dirname(t),{recursive:!0});const e=`${t}.${process.pid}.tmp`;return o.writeFileSync(e,JSON.stringify(r,null,2)+`
2
- `,{mode:384}),o.chmodSync(e,384),o.renameSync(e,t),r}n(f,"save");function l(){const r=d(c(a()));if(i.some(e=>r[e]))return r;const t=d(c(s.join(m.homedir(),".claude","slack-bridge","state.json")).config);return i.some(e=>t[e])?f(t):r}n(l,"readSlack");async function $(r){for(const[t,e]of Object.entries(r)){if(!i.includes(t)||typeof e!="string")throw new Error(`Unknown Slack setting ${t}`);if(t==="self_dm"&&e&&!/^D[A-Z0-9]+$/.test(e))throw new Error("self-dm must be a DM channel id");if(t==="owner_slack_user"&&e&&!/^U[A-Z0-9]+$/.test(e))throw new Error("user must be a Slack user id");if(t==="slack_domain"&&e&&!/^[a-z0-9][a-z0-9-]*$/.test(e))throw new Error("domain must be a Slack workspace domain");if(t==="timezone"&&e)try{new Intl.DateTimeFormat("en",{timeZone:e})}catch{throw new Error("timezone must be an IANA timezone such as Area/City")}}return h(a(),()=>f({...l(),...r}))}n($,"setSlack");function z(r=new Date){const t=l().timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,e=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",hourCycle:"h23"}).formatToParts(r).map(({type:u,value:p})=>[u,p]));return{date:`${e.year}-${e.month}-${e.day}`,morning:!["Sat","Sun"].includes(e.weekday)&&Number(e.hour)>=9}}n(z,"slackDay");export{l as readSlack,$ as setSlack,z as slackDay};
1
+ var v=Object.defineProperty;var n=(r,e)=>v(r,"name",{value:e,configurable:!0});import u from"node:fs";import d from"node:path";import p from"node:os";import{withFileLock as x}from"./locks.mjs";import{readSecret as $,writeSecret as f}from"./secrets.mjs";const l=["self_dm","owner_slack_user","slack_domain","timezone"],k=n(()=>d.join(p.homedir(),".claude","kickflip","slack.json"),"fileOf"),w=n(r=>{try{return JSON.parse(u.readFileSync(r,"utf8"))||{}}catch{return{}}},"read"),S=n(r=>Object.fromEntries(l.map(e=>[e,typeof r?.[e]=="string"?r[e]:""])),"identityOf");function y(r){const e=k();u.mkdirSync(d.dirname(e),{recursive:!0});const t=`${e}.${process.pid}.tmp`;return u.writeFileSync(t,JSON.stringify(r,null,2)+`
2
+ `,{mode:384}),u.chmodSync(t,384),u.renameSync(t,e),r}n(y,"save");function _(){const r=S(w(k()));if(l.some(t=>r[t]))return r;const e=S(w(d.join(p.homedir(),".claude","slack-bridge","state.json")).config);return l.some(t=>e[t])?y(e):r}n(_,"readSlack");async function I(r){for(const[e,t]of Object.entries(r)){if(!l.includes(e)||typeof t!="string")throw new Error(`Unknown Slack setting ${e}`);if(e==="self_dm"&&t&&!/^D[A-Z0-9]+$/.test(t))throw new Error("self-dm must be a DM channel id");if(e==="owner_slack_user"&&t&&!/^U[A-Z0-9]+$/.test(t))throw new Error("user must be a Slack user id");if(e==="slack_domain"&&t&&!/^[a-z0-9][a-z0-9-]*$/.test(t))throw new Error("domain must be a Slack workspace domain");if(e==="timezone"&&t)try{new Intl.DateTimeFormat("en",{timeZone:t})}catch{throw new Error("timezone must be an IANA timezone such as Area/City")}}return x(k(),()=>y({..._(),...r}))}n(I,"setSlack");function N(r=new Date){const e=_().timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,t=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",hourCycle:"h23"}).formatToParts(r).map(({type:c,value:a})=>[c,a]));return{date:`${t.year}-${t.month}-${t.day}`,morning:!["Sat","Sun"].includes(t.weekday)&&Number(t.hour)>=9}}n(N,"slackDay");class m extends Error{static{n(this,"SlackError")}constructor(e,t=502){super(e),this.status=t}}const E=n(()=>process.env.KICKFLIP_SLACK_URL||"https://slack.com/api","api"),O=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive"];function g(r,{fetch:e=globalThis.fetch,checked:t=n(()=>{},"checked")}={}){async function c(a,i={}){let o;try{const s=await e(`${E()}/${a}`,{method:"POST",headers:{"content-type":"application/json; charset=utf-8",authorization:`Bearer ${r}`},body:JSON.stringify(i),signal:AbortSignal.timeout(15e3)});if(o=await s.json().catch(()=>null),!o)throw new Error(`Slack answered ${s.status}`)}catch(s){throw new m(`Could not reach Slack: ${s.message}`)}if(O.includes(o.error))throw t(!1),new m("Slack refused the token.",400);if(t(!0),!o.ok)throw new m(`Slack: ${o.error}`);return o}return n(c,"call"),{async who(){const{team:a,team_id:i,user:o,user_id:s}=await c("auth.test");return{team:a,team_id:i,user:o,user_id:s}},async people(){const a=[];let i="";do{const o=await c("users.list",{limit:200,...i?{cursor:i}:{}});for(const s of o.members)!s.deleted&&!s.is_bot&&s.id!=="USLACKBOT"&&a.push({id:s.id,name:s.profile?.real_name||s.real_name||s.name});i=o.response_metadata?.next_cursor||""}while(i);return a.sort((o,s)=>o.name.localeCompare(s.name))},openDM:n(async a=>(await c("conversations.open",{users:a})).channel.id,"openDM"),post:n(async({channel:a,text:i,thread_ts:o})=>(await c("chat.postMessage",{channel:a,text:i,unfurl_links:!1,...o?{thread_ts:o}:{}})).ts,"post"),async react({channel:a,ts:i,name:o}){try{await c("reactions.add",{channel:a,timestamp:i,name:o})}catch(s){if(s.message!=="Slack: already_reacted")throw s}}}}n(g,"slackClient");const h=n(r=>{const e=$("slack",r);return typeof e?.token=="string"&&e.token?e:null},"savedToken");function b(r){const e=h(r);return e?{set:!0,...e.refused_at?{refused:!0}:{},...e.team?{team:e.team,user:e.user}:{}}:{set:!1}}n(b,"slackStatus");const K="Slack needs Hub\u2019s Slack token; add it in Hub settings \u203A Slack first.";async function L(r,{fetch:e}={}){const t=typeof r=="string"?r.trim():"";if(!/^xoxp-[\w-]{10,250}$/.test(t))throw new m("Paste a Slack user token, which starts with xoxp-.",400);const c=new Date().toISOString();let a=!1;const i=await g(t,{fetch:e,checked:n(o=>{a=!o},"checked")}).who().catch(o=>{if(!a)throw o;return null});return f("slack",i?{token:t,...i,saved_at:c}:{token:t,saved_at:c,refused_at:c}),b()}n(L,"saveSlackToken");function U(){return f("slack",null),b()}n(U,"removeSlackToken");function D(r,e){const t=h();if(t?.token!==r||!!t.refused_at==!e)return;const{refused_at:c,...a}=t;f("slack",e?a:{...a,refused_at:new Date().toISOString()})}n(D,"markChecked");function Z({fetch:r}={}){const e=h();return e?g(e.token,{fetch:r,checked:n(t=>D(e.token,t),"checked")}):null}n(Z,"savedSlack");export{K as SLACK_NEEDS_TOKEN,m as SlackError,_ as readSlack,U as removeSlackToken,L as saveSlackToken,Z as savedSlack,I as setSlack,g as slackClient,N as slackDay,b as slackStatus};
package/hub/stream.mjs CHANGED
@@ -1,19 +1,16 @@
1
- var F=Object.defineProperty;var r=(w,g)=>F(w,"name",{value:g,configurable:!0});import W from"node:http";import A from"node:fs";import B from"node:path";function P({targets:w,watched:g=r(()=>[],"watched"),sidebar:I,retryMs:O=2e3,sidebarMs:j=15e3,pingMs:H=25e3,settleMs:M=300,log:v=r(()=>{},"log")}){const o=new Set,a=new Map,c=new Map,S=new Set;let l=null,y=[],u=new Set,d=null;const h=r((t,e=o)=>{for(const n of e)n.write(t)},"write"),T=r((t,e)=>`event: ${t}
2
- data: ${JSON.stringify(e)}
3
-
4
- `,"event");async function m(t=[]){let e;try{e=await I({fresh:new Set(t)})}catch(i){v(`sidebar for the stream failed: ${i.message}`);return}const n=JSON.stringify(e);n!==l&&(l=n,h(`event: sidebar
5
- data: ${n}
1
+ var W=Object.defineProperty;var r=(p,m)=>W(p,"name",{value:m,configurable:!0});import A from"node:http";import B from"node:fs";import G from"node:path";function R({targets:p,watched:m=r(()=>[],"watched"),sidebar:z,retryMs:I=2e3,sidebarMs:M=15e3,pingMs:T=25e3,settleMs:j=300,log:g=r(()=>{},"log")}){const s=new Map,a=new Map,i=new Map,v=new Set;let l=null,y=null,S=[],u=new Set,d=null;const H=r(t=>{for(const e of s.keys())e.write(t)},"write"),$=r((t,e,n)=>{const o=s.get(t);t.write(`event: sidebar
2
+ data: ${o?JSON.stringify(o.view(e)):n}
6
3
 
7
- `))}r(m,"refreshSidebar");function $(t){t&&u.add(t),!d&&(d=setTimeout(()=>{d=null;const e=[...u];u=new Set,m(e)},M))}r($,"sidebarSoon");function b(t){h(T("change",{route:t})),$(t)}r(b,"changed");function _(t,e){const n={port:e,req:null};a.set(t,n);const i=r(()=>{a.get(t)===n&&a.delete(t),n.req?.destroy()},"drop");n.req=W.get({host:"127.0.0.1",port:e,path:"/api/stream",headers:{accept:"text/event-stream"}},s=>{if(s.statusCode!==200){s.resume(),i();return}S.has(t)&&b(t),S.add(t),s.setEncoding("utf8");let f="";s.on("data",C=>{f+=C.replace(/\r\n/g,`
8
- `);for(let p=f.indexOf(`
4
+ `)},"sidebarTo"),J=r((t,e)=>`event: ${t}
5
+ data: ${JSON.stringify(e)}
9
6
 
10
- `);p>=0;p=f.indexOf(`
7
+ `,"event");async function h(t=[]){let e;try{e=await z({fresh:new Set(t)})}catch(o){g(`sidebar for the stream failed: ${o.message}`);return}const n=JSON.stringify(e);if(n!==l){l=n,y=e;for(const o of s.keys())$(o,e,n)}}r(h,"refreshSidebar");function q(t){t&&u.add(t),!d&&(d=setTimeout(()=>{d=null;const e=[...u];u=new Set,h(e)},j))}r(q,"sidebarSoon");function b(t){const e=J("change",{route:t});for(const[n,o]of s)(!o||o.routes.has(t))&&n.write(e);q(t)}r(b,"changed");function N(t,e){const n={port:e,req:null};a.set(t,n);const o=r(()=>{a.get(t)===n&&a.delete(t),n.req?.destroy()},"drop");n.req=A.get({host:"127.0.0.1",port:e,path:"/api/stream",headers:{accept:"text/event-stream"}},c=>{if(c.statusCode!==200){c.resume(),o();return}v.has(t)&&b(t),v.add(t),c.setEncoding("utf8");let f="";c.on("data",E=>{f+=E.replace(/\r\n/g,`
8
+ `);for(let w=f.indexOf(`
11
9
 
12
- `)){const E=f.slice(0,p);f=f.slice(p+2),/^event: ?change$/m.test(E)&&b(t)}}),s.on("close",i),s.on("error",i)}),n.req.on("error",i)}r(_,"connect");function q(){let t;try{t=new Map(w().map(e=>[e.route,e.port]))}catch(e){v(`stream targets failed: ${e.message}`);return}for(const[e,n]of a)t.get(e)!==n.port&&(a.delete(e),n.req?.destroy());for(const[e,n]of t)a.has(e)||_(e,n)}r(q,"reconcile");function x(){let t;try{t=new Set(g().map(e=>e.dir))}catch(e){v(`stream watched failed: ${e.message}`);return}for(const[e,n]of c)t.has(e)||(n.close(),c.delete(e));for(const e of t)if(!c.has(e))try{const n=A.watch(B.join(e,"data"),(i,s)=>{s==="watcher.json"&&$()});n.on("error",()=>{n.close(),c.delete(e)}),c.set(e,n)}catch{}}r(x,"watchWatchers");function k(){q(),x(),y=[setInterval(()=>{q(),x()},O),setInterval(()=>m(),j),setInterval(()=>h(`: ping
10
+ `);w>=0;w=f.indexOf(`
13
11
 
14
- `),H)]}r(k,"startHolding");function z(){for(const t of y)clearInterval(t);y=[],clearTimeout(d),d=null,u=new Set;for(const t of a.values())t.req?.destroy();a.clear();for(const t of c.values())t.close();c.clear(),S.clear(),l=null}r(z,"stopHolding");function J(t,e){e.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive"}),e.write(`retry: 3000
12
+ `)){const F=f.slice(0,w);f=f.slice(w+2),/^event: ?change$/m.test(F)&&b(t)}}),c.on("close",o),c.on("error",o)}),n.req.on("error",o)}r(N,"connect");function x(){let t;try{t=new Map(p().map(e=>[e.route,e.port]))}catch(e){g(`stream targets failed: ${e.message}`);return}for(const[e,n]of a)t.get(e)!==n.port&&(a.delete(e),n.req?.destroy());for(const[e,n]of t)a.has(e)||N(e,n)}r(x,"reconcile");function k(){let t;try{t=new Set(m().map(e=>e.dir))}catch(e){g(`stream watched failed: ${e.message}`);return}for(const[e,n]of i)t.has(e)||(n.close(),i.delete(e));for(const e of t)if(!i.has(e))try{const n=B.watch(G.join(e,"data"),(o,c)=>{c==="watcher.json"&&q()});n.on("error",()=>{n.close(),i.delete(e)}),i.set(e,n)}catch{}}r(k,"watchWatchers");function _(){x(),k(),S=[setInterval(()=>{x(),k()},I),setInterval(()=>h(),M),setInterval(()=>H(`: ping
15
13
 
16
- `),o.add(e),o.size===1&&k(),l?h(`event: sidebar
17
- data: ${l}
14
+ `),T)]}r(_,"startHolding");function O(){for(const t of S)clearInterval(t);S=[],clearTimeout(d),d=null,u=new Set;for(const t of a.values())t.req?.destroy();a.clear();for(const t of i.values())t.close();i.clear(),v.clear(),l=null,y=null}r(O,"stopHolding");function C(t,e,n=null){e.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive"}),e.write(`retry: 3000
18
15
 
19
- `,[e]):m(),t.on("close",()=>{o.delete(e),o.size||z()})}r(J,"handle");function N(){for(const t of o)t.end();o.clear(),z()}return r(N,"close"),{handle:J,close:N,changed:r(t=>{o.size&&b(t)},"changed"),refresh:r(()=>{o.size&&m()},"refresh")}}r(P,"hubStream");export{P as hubStream};
16
+ `),s.set(e,n),s.size===1&&_(),l?$(e,y,l):h(),t.on("close",()=>{s.delete(e),s.size||O()})}r(C,"handle");function D(){for(const t of s.keys())t.end();s.clear(),O()}return r(D,"close"),{handle:C,close:D,changed:r(t=>{s.size&&b(t)},"changed"),refresh:r(()=>{s.size&&h()},"refresh")}}r(R,"hubStream");export{R as hubStream};
package/hub/try.mjs CHANGED
@@ -1,8 +1,8 @@
1
- var Wt=Object.defineProperty;var a=(n,f)=>Wt(n,"name",{value:f,configurable:!0});import x from"node:fs";import O from"node:path";import Ot from"node:os";import ut from"node:http";import{execFile as Jt,spawn as zt}from"node:child_process";import{createInterface as Ct}from"node:readline";import{promisify as Ut}from"node:util";import{listBoards as W,readManifest as J,readJSON as rt,saveJSON as Et,appendEvent as Yt,GITHUB_STATE as qt,REPO_FETCH as It}from"./boards.mjs";import{boardRepo as Q,githubFromOrigin as jt}from"./board-repo.mjs";import{gitReachFault as Mt,remoteFromInput as Qt,remoteGitEnv as Vt}from"./repos.mjs";import{readiness as Xt}from"./readiness.mjs";import{tailscaleBin as Zt}from"../shared/tailscale.mjs";import{buildScriptError as te}from"../board/build-script.mjs";import{appendThread as ee,recordedWorktree as ie,setItem as re}from"../board/store.mjs";import{cardPRs as se,hasPR as ne,prKeyOf as oe}from"../shared/card-prs.mjs";import{hubGate as ae}from"../board/on-host.mjs";import{pipeUpgrade as ce,refuse as le,refuseUpgrade as de}from"./front-door.mjs";class T extends Error{static{a(this,"BuildError")}constructor(f,w=400){super(f),this.status=w}}const ft=Ut(Jt),M=a(async(n,...f)=>(await ft("git",["-C",n,...f],{encoding:"utf8",timeout:3e3})).stdout.trim(),"git"),ue=/errSecInternalComponent|keychain[^\n]*\blocked\b|\blocked\b[^\n]*keychain/i,z={first:8500,last:8599},pt=a(n=>/^\d+$/.test(String(n))&&Number(n)>=z.first&&Number(n)<=z.last,"isTryPort"),fe=30*6e4,Pt=a(n=>O.join(n,".kickflip","build"),"scriptAt"),_t=a(n=>x.existsSync(n),"exists"),At=a((n,f)=>O.join(n.dir,"data","try",`${f.split("/").at(-1)}.log`),"logFileOf");function Nt(n,f,w){const m=At(n,f);return x.mkdirSync(O.dirname(m),{recursive:!0}),x.writeFileSync(m,w.message+`
2
- `,{mode:384}),x.chmodSync(m,384),m}a(Nt,"failureLog");const pe=a(n=>new Promise(f=>{const w=ut.get({host:"127.0.0.1",port:n,path:"/",timeout:1e3},m=>{m.destroy(),f(!0)});w.on("timeout",()=>w.destroy()),w.on("error",()=>f(!1))}),"probe"),Dt=a((n,f)=>{try{process.kill(-n.pid,f)}catch{}},"signalGroup");async function Bt(n,f,w){const m=await ie(n.dir,f),[v,p]=f.split("/"),k=n.waves.find(b=>b.slug===v)?.wave,d=m?.path||k?.items.find(b=>b.id===p)?.worktree;if(typeof d!="string"||!d||d.split(O.sep).includes(".."))return"";let g=m?.repo;const y=(n.github||k?.repo||"").toLowerCase();if(!g&&y){const b=[n.owner?.repo,n.dir,...Object.values(w?.sites||{}).map(I=>I.owner?.repo)];for(const I of new Set(b.filter(P=>typeof P=="string"&&O.isAbsolute(P))))try{if(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(await M(I,"remote","get-url","origin"))?.[1].toLowerCase()===y){g=await M(I,"rev-parse","--show-toplevel");break}}catch{}}if(!m?.path&&!g||m?.path&&!O.isAbsolute(d))return"";try{const b=[O.join(x.realpathSync(Ot.homedir()),".claude","kickflip","worktrees")];if(typeof g=="string"&&O.isAbsolute(g))try{b.push(O.join(x.realpathSync(g),".claude","worktrees"))}catch{}const I=O.resolve(g||"/",d),P=x.realpathSync(I);return b.some(L=>I.startsWith(L+O.sep)&&P.startsWith(L+O.sep))&&x.statSync(P).isDirectory()?P:""}catch{return""}}a(Bt,"installWorktree");function he({now:n=Date.now,answers:f=pe,log:w=console.log,waiting:m=a(async()=>null,"waiting"),event:v=Yt,gate:p=ae}={}){const k=new Map,d=new Map,g=new Set,y=new Set,b=new Map,I=new Map,P=new Map,L=new Map;let G=!1,R=null,U=null,et=null;const st=a(()=>new Date(n()).toISOString(),"stamp");function D(t){if(k.has(t.dir))return k.get(t.dir);const i=O.join(t.dir,"data","try.json"),r=rt(i,{kind:null,main:null,cards:{}}),s={...pt(r.main_port)?{main_port:r.main_port}:{},kind:r.kind||null,main:r.main||null,cards:{...r.cards},...r.pull?{pull:{...r.pull,running:void 0}}:{}},e={state:s,file:i,written:JSON.stringify(r)};k.set(t.dir,e),s.main_port&&I.set(t.dir,s.main_port);const o=Object.entries(s.cards).filter(([,c])=>c.state==="running");for(const[c]of o)y.add(B(t,c));return s.kind==="web"?(s.cards=Object.fromEntries(o),s.main&&s.main.state!=="failed"&&(delete s.main.state,delete s.main.port,delete s.main.https)):s.main?.state==="running"&&(delete s.main.state,delete s.main.sha),A(t),e}a(D,"stateOf");function A(t){const i=k.get(t.dir),r=JSON.stringify(i.state);r!==i.written&&(Et(i.file,i.state),i.written=r)}a(A,"persist");const B=a((t,i)=>`${t.dir}\0${i}`,"runKey"),wt=a((t,i)=>i==="main"?t.main:t.cards[i],"entryOf");function Y(t,i,r){const{state:s}=D(t),e=wt(s,i);if(!e)return;const o=Object.hasOwn(r,"state")&&r.state!==e.state;Object.assign(e,r,i!=="main"&&o?{at:st()}:{}),A(t)}a(Y,"update");function nt(t){const i=[...Object.values(t?.sites||{}),...Object.values(t?.closed||{}).map(r=>r.site)];for(const r of i){if(!r?.dir)continue;const s=rt(O.join(r.dir,"data","try.json"),{}).main_port;pt(s)&&I.set(r.dir,Number(s))}}a(nt,"reserveMains");function Ft(t){const{board:i,key:r}=t,s=B(i,r),e=r==="main"?I.get(i.dir):b.get(s);if(e)return e;const o=new Set([...I.values(),...b.values()]);let c=z.first;for(;o.has(c)&&c<=z.last;)c++;if(c>z.last)throw new Error(`No try ports available (${z.first}\u2013${z.last}). Stop a served card and retry.`);return r==="main"?(I.set(i.dir,c),D(i).state.main_port=c,A(i)):b.set(s,c),c}a(Ft,"publicPort");const ot=a(async t=>{const i=Zt();if(!i)throw new Error("Tailscale isn't installed on this host");return ft(i,t,{encoding:"utf8",timeout:1e4})},"tailscale");async function yt(t){try{await ot(["serve",`--https=${t}`,"off"])}catch(i){w(`try port ${t}: could not close port: ${(i.stderr||i.message).trim()}`)}}a(yt,"removePort");async function Rt(t){t.https=Ft(t);const i=t.sockets=new Set,r=a(()=>{t.visited=n()},"visit"),s=a(e=>{i.add(e),e.on("data",r),e.on("close",()=>i.delete(e))},"track");if(t.relay=ut.createServer(async(e,o)=>{const c=await p(e);if(c!=="owner"){le(e,o,c);return}const h=ut.request({host:"127.0.0.1",port:t.port,method:e.method,path:e.url,headers:e.headers},S=>{o.writeHead(S.statusCode,S.headers),S.on("data",r),S.pipe(o),S.on("close",()=>{S.complete||o.destroy()})});o.on("close",()=>{o.writableFinished||h.destroy()}),h.on("error",()=>{o.headersSent?o.destroy():o.writeHead(502).end()}),e.pipe(h)}),t.relay.on("connection",e=>{r(),s(e)}),t.relay.on("upgrade",async(e,o,c)=>{const h=await p(e);if(h!=="owner"){de(o,h);return}s(ce({req:e,socket:o,head:c,port:t.port,path:e.url}))}),await new Promise((e,o)=>{t.relay.once("error",o),t.relay.listen(0,"127.0.0.1",e)}),!t.stopped){t.exposed=!0;try{await ot(["serve","--bg",`--https=${t.https}`,`http://127.0.0.1:${t.relay.address().port}`])}catch(e){throw new Error(`Couldn't open try port ${t.https}: ${(e.stderr||e.message).trim()}`)}}}a(Rt,"openPort");async function Lt(t){if(await t.opening?.catch(()=>{}),t.exposed&&await yt(t.https),t.relay){for(const i of t.sockets)i.destroy();await new Promise(i=>t.relay.close(i))}t.keepPort||b.delete(B(t.board,t.key))}a(Lt,"closePort");function X(t=J()){if(et)return et;nt(t);for(const i of W(t))D(i);return et=(async()=>{try{const{stdout:i}=await ot(["serve","status","--json"]),r=JSON.parse(i);for(const s of Object.keys(r?.TCP||{}))pt(s)&&![...d.values()].some(e=>e.https===Number(s))&&await yt(s)}catch(i){w(`try startup cleanup: ${(i.stderr||i.message).trim()}`)}})(),et}a(X,"initialize");async function gt(t,i,r,s){const{board:e,key:o}=t;if(Y(e,o,{state:"failed",port:void 0,https:void 0}),o==="main")return;const c=[];let h=!1;try{for await(const u of Ct({input:x.createReadStream(t.logFile),crlfDelay:1/0}))h||=ue.test(u),c.push(u),c.length>5&&c.shift()}catch(u){c.push(`Could not read the build log: ${u.message}`)}const S=t.port||(D(e).state.kind||(e.waves.some(({wave:u})=>u.items.some(C=>C.install?.url))?"app":"web"))==="web"?"Serve":"Build";await ee(e.dir,o,{text:[`${S} failed (exit ${i??1})`,s?.message,r&&`Stopped by ${r}.`,h&&"The login keychain must be unlocked on the Mac.",...c].filter(Boolean).join(`
3
- `)})}a(gt,"failure");function it(t){return t.ending||(Dt(t.child,"SIGTERM"),t.ending=new Promise(i=>{const r=a(()=>{clearTimeout(s),clearInterval(e),i()},"finish");let s=setTimeout(()=>{Dt(t.child,"SIGKILL"),s=setTimeout(r,1e3)},4e3);const e=setInterval(()=>{try{process.kill(-t.child.pid,0)}catch{r()}},20)})),t.ending}a(it,"terminate");async function $t(t,i=!1){t.keepPort=i,t.stopped=!0,clearTimeout(t.deadline),clearInterval(t.poll),await it(t),await t.done}a($t,"halt");async function Z(t,i=!1){await $t(t,i),Y(t.board,t.key,{state:void 0,port:void 0,https:void 0,...t.ready?{}:{sha:void 0}}),t.ready||P.delete(B(t.board,t.key))}a(Z,"stopRun");async function bt(t,i,r,s={}){if(!r)throw new T("This card has no valid worktree.");const e=Pt(r),o=te(e);if(o)throw new T(o);if(!x.realpathSync(e).startsWith(x.realpathSync(r)+O.sep))throw new T("Build script must be inside the worktree.");const c=await M(r,"rev-parse","HEAD");if(G)throw new T("The hub is stopping. Try again after it restarts.",503);const{state:h}=D(t),S=wt(h,i),u={...i==="main"?{}:S,...s,sha:c,script:!0,state:"running",...i==="main"?{}:{at:st(),head:c}};delete u.port,delete u.https;const C=At(t,i);x.mkdirSync(O.dirname(C),{recursive:!0});const E=x.openSync(C,"w",384);x.fchmodSync(E,384);const $=zt(e,[i,r],{cwd:r,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,KICKFLIP_BOARD:t.route,HOST:"127.0.0.1"}});i==="main"?h.main=u:h.cards[i]=u,A(t);const N=B(t,i),l={child:$,board:t,key:i,logFile:C,visited:n(),stopped:!1,port:null,ready:!1};d.set(N,l),P.set(N,c);let F,j;const q=a(_=>{j||=new Error(_),it(l)},"fail");$.on("error",_=>{F=_}),$.stdout.on("data",_=>x.writeSync(E,_)),$.stderr.on("data",_=>x.writeSync(E,_));const H=Ct({input:$.stdout,crlfDelay:1/0});return H.on("line",_=>{const tt=/^port (\d{1,5})$/.exec(_);if(!tt||l.port||l.stopped)return;const K=Number(tt[1]);if(K<1||K>65535){q("Build script printed an invalid port.");return}l.port=K,clearTimeout(l.deadline);const ct=n()+6e4;let lt=!1;const xt=a(async()=>{if(!(lt||l.stopped||l.ready||$.exitCode!==null||$.signalCode!==null)){lt=!0;try{if(await f(K)){if(l.stopped||j||$.exitCode!==null||$.signalCode!==null||(l.opening=Rt(l),await l.opening,l.stopped||j||$.exitCode!==null||$.signalCode!==null))return;l.ready=!0,l.visited=n(),h.kind="web",Y(t,i,{state:"ready",port:K,https:l.https}),clearInterval(l.poll)}else n()>=ct&&q("Nothing answered on the build script\u2019s port within 60 seconds.")}finally{lt=!1}}},"check");l.poll=setInterval(()=>xt().catch(dt=>q(dt.message)),250),xt().catch(dt=>q(dt.message))}),l.deadline=setTimeout(()=>q("No port line within 60 minutes."),60*6e4),$.once("exit",()=>{it(l)}),l.done=new Promise(_=>$.once("close",(tt,K)=>{clearTimeout(l.deadline),clearInterval(l.poll),H.close(),x.closeSync(E),(async()=>{await it(l),await Lt(l),l.finished=!0,!l.stopped&&(j||F||tt!==0||l.port&&!l.ready?await gt(l,tt??1,K,j||F||(l.port&&!l.ready?new Error("Build script exited before its port answered."):null)):l.ready?(i==="main"?(delete h.main.state,delete h.main.port,delete h.main.https):delete h.cards[i],A(t)):(h.kind="app",Y(t,i,{state:"ready"})))})().catch(ct=>w(`build /${t.route} ${i}: ${ct.message}`)).finally(()=>{d.get(N)===l&&d.delete(N),_()})})),w(`build /${t.route} ${i}: started; log ${C}`),{status:"started"}}a(bt,"launch");async function vt(t,i,r){const s=B(t,"main");if(g.has(s))throw new T("A build is already running for main.",409);g.add(s);try{d.has(s)&&await Z(d.get(s),!0);const e=O.join(Ot.homedir(),".claude","kickflip","try",`${t.route}-main`);return x.mkdirSync(O.dirname(e),{recursive:!0}),_t(e)?await M(e,"checkout","--detach","--force",r.sha):(await M(i,"worktree","prune"),await M(i,"worktree","add","--detach",e,r.sha)),await bt(t,"main",e,r)}catch(e){throw e.status!==503&&(D(t).state.main={...r,state:"failed"},Nt(t,"main",e),A(t)),e}finally{g.delete(s)}}a(vt,"launchMain");async function kt(t,{manifest:i=J()}={}){if(await X(i),nt(i),G)throw new T("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(u=>!["route","key"].includes(u))||typeof t.route!="string"||typeof t.key!="string")throw new T("Send only the board route and card key.");const{route:r,key:s}=t;if(s!=="main"&&(!/^[\w.-]+\/[\w.-]+$/.test(s)||s.split("/").some(u=>u==="."||u==="..")))throw new T("Card key must be <wave>/<id>.");const e=W(i).find(u=>u.route===r);if(!e)throw new T(`/${r} is not a board.`,404);if(s!=="main"&&!e.waves.some(({slug:u,wave:C})=>C.items.some(E=>`${u}/${E.id}`===s)))throw new T("There is no item with this card key.",404);const o=await m();if(o)throw new T(o,409);const c=B(e,s),h=d.get(c);if(g.has(c)||h&&!h.ready&&!h.finished)throw new T(`A build is already running for ${s==="main"?"main":"this card"}.`,409);if(s==="main"){const u=D(e).state.main;if(u?.state==="running")throw new T("A build is already running for main.",409);if(u?.state!=="failed"||!u.sha)throw new T("Main has no failed build to retry.",409);const{sha:C,branch:E,slug:$,at:N,script:l}=u;return vt(e,Q(r,i).repo,{sha:C,branch:E,slug:$,at:N,script:l})}g.add(c);const S=y.delete(c);try{d.has(c)&&await Z(d.get(c),!0);const u=await Bt(e,s,i);return await bt(e,s,u)}catch(u){throw b.delete(c),S&&u.status!==503&&Y(e,s,{state:void 0,sha:void 0}),u}finally{g.delete(c)}}a(kt,"start");function St(t,i,{manifest:r=J()}={}){const s=W(r).find(o=>o.route===t);if(!s)return null;const e=[...d.values()].find(o=>o.board.dir===s.dir&&o.key.split("/").at(-1).toLowerCase()===i.toLowerCase()&&o.ready&&!o.stopped&&o.child.exitCode===null&&o.child.signalCode===null);return e?{key:e.key,port:e.port}:null}a(St,"lookup");async function at({manifest:t=J(),routes:i}={}){if(await X(t),nt(t),G)return R;if(R&&i){if(!U){const r={routes:new Set,manifest:t};r.done=R.catch(()=>{}).then(()=>(U=null,at({manifest:r.manifest,routes:[...r.routes]}))),U=r}U.manifest=t;for(const r of i)U.routes.add(r);return U.done}return R||(R=(async()=>{const r=W(t),s=rt(qt,{}).prs||{};for(const e of[...d.values()])if(!r.some(o=>o.dir===e.board.dir)||e.key!=="main"&&e.ready&&n()-e.visited>=fe){await Z(e);const{state:o}=D(e.board);e.key==="main"?o.main=null:delete o.cards[e.key],A(e.board)}for(const e of r){if(G)return;if(i&&!i.includes(e.route))continue;const{state:o}=D(e),c=Q(e.route,t),h=c.branch||"main",S=c.local?`refs/heads/${h}`:`refs/remotes/origin/${h}`;for(const{slug:u,wave:C}of e.waves)for(const E of C.items){const $=`${u}/${E.id}`,N=se(E,e.github||C.repo).map(l=>s[oe(l)]);if(!(["done","merged","dropped"].includes(String(E.status).toLowerCase())||N.length&&N.every(l=>["MERGED","CLOSED"].includes(l?.state))))try{const l=B(e,$),F=await Bt(e,$,t);if(F){const H=await M(F,"rev-parse","HEAD");let _=0;try{_=Number(await M(F,"rev-list","--count",`${S}..HEAD`))}catch{}Object.assign(o.cards[$]||={},{head:H,ahead:_,script:_t(Pt(F))}),A(e)}else if(!y.has(l))continue;const j=o.cards[$];if((y.has(l)||e.auto_build&&j.script&&j.ahead>0&&(j.sha||P.get(l))!==j.head&&j.state!=="running")&&!g.has(l))try{await kt({route:e.route,key:$},{manifest:t})}catch(H){if([409,503].includes(H.status))continue;throw Y(e,$,{sha:j.head}),await gt({board:e,key:$,logFile:Nt(e,$,H)},1),H}}catch(l){w(`try /${e.route} ${$}: ${l.message}`)}}try{if(!c.repo||await m())continue;const u=await M(c.repo,"rev-parse",S);let C=!1;try{await M(c.repo,"cat-file","-e",`${u}:.kickflip/build`),C=!0}catch{}if(!C){const j=d.get(B(e,"main"));j&&await Z(j),o.main=null,A(e);continue}const E=o.main;if(E?.state==="running"||E?.sha===u&&(E.state==="failed"||E.state==="ready"&&(o.kind!=="web"||St(e.route,"main",{manifest:t}))))continue;const $=B(e,"main");if(g.has($))continue;const N=await M(c.repo,"log","-1","--format=%cI",u);let l=e.github;if(!l)try{l=jt(await M(c.repo,"remote","get-url","origin"))}catch{}const F={sha:u,branch:h,slug:l||"",at:N,script:C};await vt(e,c.repo,F)}catch(u){w(`try /${e.route} main: ${u.message}`)}}})().finally(()=>{R=null}),R)}a(at,"tick");function Tt(t,i){if(L.has(t.dir))return L.get(t.dir);const r=(async()=>{const s=Q(t.route,i),e=s.branch||"main",{state:o}=D(t);o.pull={...o.pull,running:!0},A(t);let c,h;try{c=await me(s.repo,e)}catch(S){h=S.message}if(c===null?delete o.pull:o.pull={at:st(),...h?{error:h}:{}},A(t),c===null)return null;if(h)return w(`pull /${t.route}: ${h}`),{commits:0,error:h};if(c.commits){w(`pull /${t.route}: ${e} fast-forwarded ${c.commits} commit${c.commits===1?"":"s"} to ${c.to.slice(0,7)}`);try{await v(t,"main-pulled",{branch:e,...c})}catch(S){w(`pull /${t.route}: could not send main-pulled (${S.message})`)}}return{commits:c.commits}})().finally(()=>L.delete(t.dir));return L.set(t.dir,r),r}a(Tt,"pullMain");async function Ht({manifest:t=J(),routes:i}={}){await X(t);const r=[];for(const s of W(t)){if(G)break;if(i&&!i.includes(s.route))continue;const e=Q(s.route,t);!e.local||!e.repo||(await Tt(s,t))?.commits&&r.push(s.route)}return r}a(Ht,"pullMains");async function Gt(t,{manifest:i=J()}={}){if(await X(i),G)throw new T("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(o=>o!=="route")||typeof t.route!="string")throw new T("Send only the board route.");const r=W(i).find(o=>o.route===t.route);if(!r)throw new T(`/${t.route} is not a board.`,404);const s=Q(r.route,i);if(!s.local||!s.repo)throw new T("This board fetches its branch on every poll; only a local board pulls.",409);const e=await Tt(r,i);if(!e)throw new T("This board\u2019s folder has no origin to pull from.",409);return e.commits&&at({manifest:i,routes:[r.route]}).catch(o=>w(`try /${r.route} main: ${o.message}`)),e}a(Gt,"pull");async function Kt(){G=!0;const t=Promise.all([...d.values()].map(i=>i.ready?Z(i):$t(i)));await Promise.all([t,R,...L.values()])}return a(Kt,"stop"),{start:kt,tick:at,stop:Kt,lookup:St,initialize:X,pull:Gt,pullMains:Ht}}a(he,"createTryManager");const ht=1e4,mt=a(async(n,...f)=>(await ft("git",["-C",n,...f],{encoding:"utf8",timeout:ht,env:Vt()})).stdout,"originGit");async function me(n,f,{run:w=mt}={}){const m=a(async(...p)=>(await w(...p)).trim(),"git"),v=a(p=>{throw new Error(`can\u2019t pull: ${p}`)},"refuse");try{await m(n,"config","--get","remote.origin.url")}catch{return null}try{await m(n,"fetch","--quiet","--no-tags","origin",`+refs/heads/${f}:refs/remotes/origin/${f}`)}catch(p){v(p.killed?`git fetch timed out after ${ht/1e3} s`:Mt(p.stderr,{repo:n}).error)}try{const p=await m(n,"rev-parse","--verify",`refs/heads/${f}^{commit}`),k=await m(n,"rev-parse","--verify",`refs/remotes/origin/${f}^{commit}`),d=a((b,I)=>m(n,"merge-base","--is-ancestor",b,I).then(()=>!0,P=>{if(P.code===1)return!1;throw P}),"isAncestor");if(p===k||await d(k,p))return{from:p,to:p,commits:0};await d(p,k)||v(`${f} has split from origin`);const g=Number(await m(n,"rev-list","--count",`${p}..${k}`)),y=(await m(n,"worktree","list","--porcelain")).split(`
1
+ var Jt=Object.defineProperty;var c=(a,f)=>Jt(a,"name",{value:f,configurable:!0});import O from"node:fs";import T from"node:path";import jt from"node:os";import ut from"node:http";import{execFile as Yt,spawn as Vt}from"node:child_process";import{createInterface as Ct}from"node:readline";import{promisify as Qt}from"node:util";import{listBoards as W,readManifest as K,readJSON as et,saveJSON as It,appendEvent as Xt,GITHUB_STATE as Zt,REPO_FETCH as Mt}from"./boards.mjs";import{boardRepo as X,githubFromOrigin as Pt}from"./board-repo.mjs";import{gitReachFault as At,remoteFromInput as qt,remoteGitEnv as te}from"./repos.mjs";import{readiness as ee}from"./readiness.mjs";import{tailscaleBin as ie}from"../shared/tailscale.mjs";import{buildScriptError as re}from"../board/build-script.mjs";import{appendThread as se,recordedWorktree as ne,setItem as oe}from"../board/store.mjs";import{cardPRs as ae,hasPR as ce,prKeyOf as le}from"../shared/card-prs.mjs";import{hubGate as de}from"../board/on-host.mjs";import{pipeUpgrade as ue,refuse as fe,refuseUpgrade as pe}from"./front-door.mjs";import{shareOf as he}from"./share.mjs";class x extends Error{static{c(this,"BuildError")}constructor(f,w=400){super(f),this.status=w}}const ft=Qt(Yt),M=c(async(a,...f)=>(await ft("git",["-C",a,...f],{encoding:"utf8",timeout:3e3})).stdout.trim(),"git"),me=/errSecInternalComponent|keychain[^\n]*\blocked\b|\blocked\b[^\n]*keychain/i,z={first:8500,last:8599},pt=c(a=>/^\d+$/.test(String(a))&&Number(a)>=z.first&&Number(a)<=z.last,"isTryPort"),we=30*6e4,_t=c(a=>T.join(a,".kickflip","build"),"scriptAt"),Dt=c(a=>O.existsSync(a),"exists"),Nt=c((a,f)=>T.join(a.dir,"data","try",`${f.split("/").at(-1)}.log`),"logFileOf");function Bt(a,f,w){const m=Nt(a,f);return O.mkdirSync(T.dirname(m),{recursive:!0}),O.writeFileSync(m,w.message+`
2
+ `,{mode:384}),O.chmodSync(m,384),m}c(Bt,"failureLog");const ye=c(a=>new Promise(f=>{const w=ut.get({host:"127.0.0.1",port:a,path:"/",timeout:1e3},m=>{m.destroy(),f(!0)});w.on("timeout",()=>w.destroy()),w.on("error",()=>f(!1))}),"probe"),Ft=c((a,f)=>{try{process.kill(-a.pid,f)}catch{}},"signalGroup");async function Rt(a,f,w){const m=await ne(a.dir,f),[v,p]=f.split("/"),k=a.waves.find(b=>b.slug===v)?.wave,u=m?.path||k?.items.find(b=>b.id===p)?.worktree;if(typeof u!="string"||!u||u.split(T.sep).includes(".."))return"";let g=m?.repo;const y=(a.github||k?.repo||"").toLowerCase();if(!g&&y){const b=[a.owner?.repo,a.dir,...Object.values(w?.sites||{}).map(C=>C.owner?.repo)];for(const C of new Set(b.filter(P=>typeof P=="string"&&T.isAbsolute(P))))try{if(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(await M(C,"remote","get-url","origin"))?.[1].toLowerCase()===y){g=await M(C,"rev-parse","--show-toplevel");break}}catch{}}if(!m?.path&&!g||m?.path&&!T.isAbsolute(u))return"";try{const b=[T.join(O.realpathSync(jt.homedir()),".claude","kickflip","worktrees")];if(typeof g=="string"&&T.isAbsolute(g))try{b.push(T.join(O.realpathSync(g),".claude","worktrees"))}catch{}const C=T.resolve(g||"/",u),P=O.realpathSync(C);return b.some(L=>C.startsWith(L+T.sep)&&P.startsWith(L+T.sep))&&O.statSync(P).isDirectory()?P:""}catch{return""}}c(Rt,"installWorktree");function ge({now:a=Date.now,answers:f=ye,log:w=console.log,waiting:m=c(async()=>null,"waiting"),event:v=Xt,gate:p=de}={}){const k=new Map,u=new Map,g=new Set,y=new Set,b=new Map,C=new Map,P=new Map,L=new Map;let G=!1,R=null,Y=null,it=null;const st=c(()=>new Date(a()).toISOString(),"stamp");function N(t){if(k.has(t.dir))return k.get(t.dir);const e=T.join(t.dir,"data","try.json"),r=et(e,{kind:null,main:null,cards:{}}),s={...pt(r.main_port)?{main_port:r.main_port}:{},kind:r.kind||null,main:r.main||null,cards:{...r.cards},...r.pull?{pull:{...r.pull,running:void 0}}:{}},i={state:s,file:e,written:JSON.stringify(r)};k.set(t.dir,i),s.main_port&&C.set(t.dir,s.main_port);const n=Object.entries(s.cards).filter(([,o])=>o.state==="running");for(const[o]of n)y.add(B(t,o));return s.kind==="web"?(s.cards=Object.fromEntries(n),s.main&&s.main.state!=="failed"&&(delete s.main.state,delete s.main.port,delete s.main.https)):s.main?.state==="running"&&(delete s.main.state,delete s.main.sha),_(t),i}c(N,"stateOf");function _(t){const e=k.get(t.dir),r=JSON.stringify(e.state);r!==e.written&&(It(e.file,e.state),e.written=r)}c(_,"persist");const B=c((t,e)=>`${t.dir}\0${e}`,"runKey"),wt=c((t,e)=>e==="main"?t.main:t.cards[e],"entryOf");function V(t,e,r){const{state:s}=N(t),i=wt(s,e);if(!i)return;const n=Object.hasOwn(r,"state")&&r.state!==i.state;Object.assign(i,r,e!=="main"&&n?{at:st()}:{}),_(t)}c(V,"update");function nt(t){const e=[...Object.values(t?.sites||{}),...Object.values(t?.closed||{}).map(r=>r.site)];for(const r of e){if(!r?.dir)continue;const s=et(T.join(r.dir,"data","try.json"),{}).main_port;pt(s)&&C.set(r.dir,Number(s))}}c(nt,"reserveMains");function Lt(t){const{board:e,key:r}=t,s=B(e,r),i=r==="main"?C.get(e.dir):b.get(s);if(i)return i;const n=new Set([...C.values(),...b.values()]);let o=z.first;for(;n.has(o)&&o<=z.last;)o++;if(o>z.last)throw new Error(`No try ports available (${z.first}\u2013${z.last}). Stop a served card and retry.`);return r==="main"?(C.set(e.dir,o),N(e).state.main_port=o,_(e)):b.set(s,o),o}c(Lt,"publicPort");const ot=c(async t=>{const e=ie();if(!e)throw new Error("Tailscale isn't installed on this host");return ft(e,t,{encoding:"utf8",timeout:1e4})},"tailscale");async function yt(t){try{await ot(["serve",`--https=${t}`,"off"])}catch(e){w(`try port ${t}: could not close port: ${(e.stderr||e.message).trim()}`)}}c(yt,"removePort");const gt=c(t=>he(et(T.join(t.dir,"board.json"),{})),"sharedWith");async function $t(t,e){const r=await p(t),s=t.headers["tailscale-user-login"];return r!=="other"||!s||!gt(e).includes(s)?r:t.method==="GET"||t.method==="HEAD"?"shared":"view-only"}c($t,"relayVerdict");function Ht(){for(const t of u.values()){if(!t.shared?.size)continue;const e=gt(t.board);for(const r of t.shared)e.includes(r.login)||(t.shared.delete(r),r.res.destroy())}}c(Ht,"endUnshared");async function Gt(t){t.https=Lt(t);const e=t.sockets=new Set,r=c(()=>{t.visited=a()},"visit"),s=c(n=>{e.add(n),n.on("data",r),n.on("close",()=>e.delete(n))},"track"),i=t.shared=new Set;if(t.relay=ut.createServer(async(n,o)=>{const h=await $t(n,t.board);if(h!=="owner"&&h!=="shared"){fe(n,o,h);return}if(h==="shared"){const d={login:n.headers["tailscale-user-login"],res:o};i.add(d),o.on("close",()=>i.delete(d))}const S=ut.request({host:"127.0.0.1",port:t.port,method:n.method,path:n.url,headers:n.headers},d=>{o.writeHead(d.statusCode,d.headers),d.on("data",r),d.pipe(o),d.on("close",()=>{d.complete||o.destroy()})});o.on("close",()=>{o.writableFinished||S.destroy()}),S.on("error",()=>{o.headersSent?o.destroy():o.writeHead(502).end()}),n.pipe(S)}),t.relay.on("connection",n=>{r(),s(n)}),t.relay.on("upgrade",async(n,o,h)=>{const S=await $t(n,t.board);if(S!=="owner"){pe(o,S==="shared"?"view-only":S);return}s(ue({req:n,socket:o,head:h,port:t.port,path:n.url}))}),await new Promise((n,o)=>{t.relay.once("error",o),t.relay.listen(0,"127.0.0.1",n)}),!t.stopped){t.exposed=!0;try{await ot(["serve","--bg",`--https=${t.https}`,`http://127.0.0.1:${t.relay.address().port}`])}catch(n){throw new Error(`Couldn't open try port ${t.https}: ${(n.stderr||n.message).trim()}`)}}}c(Gt,"openPort");async function Ut(t){if(await t.opening?.catch(()=>{}),t.exposed&&await yt(t.https),t.relay){for(const e of t.sockets)e.destroy();await new Promise(e=>t.relay.close(e))}t.keepPort||b.delete(B(t.board,t.key))}c(Ut,"closePort");function Z(t=K()){if(it)return it;nt(t);for(const e of W(t))N(e);return it=(async()=>{try{const{stdout:e}=await ot(["serve","status","--json"]),r=JSON.parse(e);for(const s of Object.keys(r?.TCP||{}))pt(s)&&![...u.values()].some(i=>i.https===Number(s))&&await yt(s)}catch(e){w(`try startup cleanup: ${(e.stderr||e.message).trim()}`)}})(),it}c(Z,"initialize");async function bt(t,e,r,s){const{board:i,key:n}=t;if(V(i,n,{state:"failed",port:void 0,https:void 0}),n==="main")return;const o=[];let h=!1;try{for await(const d of Ct({input:O.createReadStream(t.logFile),crlfDelay:1/0}))h||=me.test(d),o.push(d),o.length>5&&o.shift()}catch(d){o.push(`Could not read the build log: ${d.message}`)}const S=t.port||(N(i).state.kind||(i.waves.some(({wave:d})=>d.items.some(E=>E.install?.url))?"app":"web"))==="web"?"Serve":"Build";await se(i.dir,n,{text:[`${S} failed (exit ${e??1})`,s?.message,r&&`Stopped by ${r}.`,h&&"The login keychain must be unlocked on the Mac.",...o].filter(Boolean).join(`
3
+ `)})}c(bt,"failure");function rt(t){return t.ending||(Ft(t.child,"SIGTERM"),t.ending=new Promise(e=>{const r=c(()=>{clearTimeout(s),clearInterval(i),e()},"finish");let s=setTimeout(()=>{Ft(t.child,"SIGKILL"),s=setTimeout(r,1e3)},4e3);const i=setInterval(()=>{try{process.kill(-t.child.pid,0)}catch{r()}},20)})),t.ending}c(rt,"terminate");async function vt(t,e=!1){t.keepPort=e,t.stopped=!0,clearTimeout(t.deadline),clearInterval(t.poll),await rt(t),await t.done}c(vt,"halt");async function q(t,e=!1){await vt(t,e),V(t.board,t.key,{state:void 0,port:void 0,https:void 0,...t.ready?{}:{sha:void 0}}),t.ready||P.delete(B(t.board,t.key))}c(q,"stopRun");async function kt(t,e,r,s={}){if(!r)throw new x("This card has no valid worktree.");const i=_t(r),n=re(i);if(n)throw new x(n);if(!O.realpathSync(i).startsWith(O.realpathSync(r)+T.sep))throw new x("Build script must be inside the worktree.");const o=await M(r,"rev-parse","HEAD");if(G)throw new x("The hub is stopping. Try again after it restarts.",503);const{state:h}=N(t),S=wt(h,e),d={...e==="main"?{}:S,...s,sha:o,script:!0,state:"running",...e==="main"?{}:{at:st(),head:o}};delete d.port,delete d.https;const E=Nt(t,e);O.mkdirSync(T.dirname(E),{recursive:!0});const j=O.openSync(E,"w",384);O.fchmodSync(j,384);const $=Vt(i,[e,r],{cwd:r,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,KICKFLIP_BOARD:t.route,HOST:"127.0.0.1"}});e==="main"?h.main=d:h.cards[e]=d,_(t);const D=B(t,e),l={child:$,board:t,key:e,logFile:E,visited:a(),stopped:!1,port:null,ready:!1};u.set(D,l),P.set(D,o);let F,I;const Q=c(A=>{I||=new Error(A),rt(l)},"fail");$.on("error",A=>{F=A}),$.stdout.on("data",A=>O.writeSync(j,A)),$.stderr.on("data",A=>O.writeSync(j,A));const H=Ct({input:$.stdout,crlfDelay:1/0});return H.on("line",A=>{const tt=/^port (\d{1,5})$/.exec(A);if(!tt||l.port||l.stopped)return;const U=Number(tt[1]);if(U<1||U>65535){Q("Build script printed an invalid port.");return}l.port=U,clearTimeout(l.deadline);const ct=a()+6e4;let lt=!1;const Et=c(async()=>{if(!(lt||l.stopped||l.ready||$.exitCode!==null||$.signalCode!==null)){lt=!0;try{if(await f(U)){if(l.stopped||I||$.exitCode!==null||$.signalCode!==null||(l.opening=Gt(l),await l.opening,l.stopped||I||$.exitCode!==null||$.signalCode!==null))return;l.ready=!0,l.visited=a(),h.kind="web",V(t,e,{state:"ready",port:U,https:l.https}),clearInterval(l.poll)}else a()>=ct&&Q("Nothing answered on the build script\u2019s port within 60 seconds.")}finally{lt=!1}}},"check");l.poll=setInterval(()=>Et().catch(dt=>Q(dt.message)),250),Et().catch(dt=>Q(dt.message))}),l.deadline=setTimeout(()=>Q("No port line within 60 minutes."),60*6e4),$.once("exit",()=>{rt(l)}),l.done=new Promise(A=>$.once("close",(tt,U)=>{clearTimeout(l.deadline),clearInterval(l.poll),H.close(),O.closeSync(j),(async()=>{await rt(l),await Ut(l),l.finished=!0,!l.stopped&&(I||F||tt!==0||l.port&&!l.ready?await bt(l,tt??1,U,I||F||(l.port&&!l.ready?new Error("Build script exited before its port answered."):null)):l.ready?(e==="main"?(delete h.main.state,delete h.main.port,delete h.main.https):delete h.cards[e],_(t)):(h.kind="app",V(t,e,{state:"ready"})))})().catch(ct=>w(`build /${t.route} ${e}: ${ct.message}`)).finally(()=>{u.get(D)===l&&u.delete(D),A()})})),w(`build /${t.route} ${e}: started; log ${E}`),{status:"started"}}c(kt,"launch");async function St(t,e,r){const s=B(t,"main");if(g.has(s))throw new x("A build is already running for main.",409);g.add(s);try{u.has(s)&&await q(u.get(s),!0);const i=T.join(jt.homedir(),".claude","kickflip","try",`${t.route}-main`);return O.mkdirSync(T.dirname(i),{recursive:!0}),Dt(i)?await M(i,"checkout","--detach","--force",r.sha):(await M(e,"worktree","prune"),await M(e,"worktree","add","--detach",i,r.sha)),await kt(t,"main",i,r)}catch(i){throw i.status!==503&&(N(t).state.main={...r,state:"failed"},Bt(t,"main",i),_(t)),i}finally{g.delete(s)}}c(St,"launchMain");async function Tt(t,{manifest:e=K()}={}){if(await Z(e),nt(e),G)throw new x("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(d=>!["route","key"].includes(d))||typeof t.route!="string"||typeof t.key!="string")throw new x("Send only the board route and card key.");const{route:r,key:s}=t;if(s!=="main"&&(!/^[\w.-]+\/[\w.-]+$/.test(s)||s.split("/").some(d=>d==="."||d==="..")))throw new x("Card key must be <wave>/<id>.");const i=W(e).find(d=>d.route===r);if(!i)throw new x(`/${r} is not a board.`,404);if(s!=="main"&&!i.waves.some(({slug:d,wave:E})=>E.items.some(j=>`${d}/${j.id}`===s)))throw new x("There is no item with this card key.",404);const n=await m();if(n)throw new x(n,409);const o=B(i,s),h=u.get(o);if(g.has(o)||h&&!h.ready&&!h.finished)throw new x(`A build is already running for ${s==="main"?"main":"this card"}.`,409);if(s==="main"){const d=N(i).state.main;if(d?.state==="running")throw new x("A build is already running for main.",409);if(d?.state!=="failed"||!d.sha)throw new x("Main has no failed build to retry.",409);const{sha:E,branch:j,slug:$,at:D,script:l}=d;return St(i,X(r,e).repo,{sha:E,branch:j,slug:$,at:D,script:l})}g.add(o);const S=y.delete(o);try{u.has(o)&&await q(u.get(o),!0);const d=await Rt(i,s,e);return await kt(i,s,d)}catch(d){throw b.delete(o),S&&d.status!==503&&V(i,s,{state:void 0,sha:void 0}),d}finally{g.delete(o)}}c(Tt,"start");function xt(t,e,{manifest:r=K()}={}){const s=W(r).find(n=>n.route===t);if(!s)return null;const i=[...u.values()].find(n=>n.board.dir===s.dir&&n.key.split("/").at(-1).toLowerCase()===e.toLowerCase()&&n.ready&&!n.stopped&&n.child.exitCode===null&&n.child.signalCode===null);return i?{key:i.key,port:i.port}:null}c(xt,"lookup");async function at({manifest:t=K(),routes:e}={}){if(await Z(t),nt(t),G)return R;if(R&&e){if(!Y){const r={routes:new Set,manifest:t};r.done=R.catch(()=>{}).then(()=>(Y=null,at({manifest:r.manifest,routes:[...r.routes]}))),Y=r}Y.manifest=t;for(const r of e)Y.routes.add(r);return Y.done}return R||(R=(async()=>{const r=W(t),s=et(Zt,{}).prs||{};for(const i of[...u.values()])if(!r.some(n=>n.dir===i.board.dir)||i.key!=="main"&&i.ready&&a()-i.visited>=we){await q(i);const{state:n}=N(i.board);i.key==="main"?n.main=null:delete n.cards[i.key],_(i.board)}for(const i of r){if(G)return;if(e&&!e.includes(i.route))continue;const{state:n}=N(i),o=X(i.route,t),h=o.branch||"main",S=o.local?`refs/heads/${h}`:`refs/remotes/origin/${h}`;for(const{slug:d,wave:E}of i.waves)for(const j of E.items){const $=`${d}/${j.id}`,D=ae(j,i.github||E.repo).map(l=>s[le(l)]);if(!(["done","merged","dropped"].includes(String(j.status).toLowerCase())||D.length&&D.every(l=>["MERGED","CLOSED"].includes(l?.state))))try{const l=B(i,$),F=await Rt(i,$,t);if(F){const H=await M(F,"rev-parse","HEAD");let A=0;try{A=Number(await M(F,"rev-list","--count",`${S}..HEAD`))}catch{}Object.assign(n.cards[$]||={},{head:H,ahead:A,script:Dt(_t(F))}),_(i)}else if(!y.has(l))continue;const I=n.cards[$];if((y.has(l)||i.auto_build&&I.script&&I.ahead>0&&(I.sha||P.get(l))!==I.head&&I.state!=="running")&&!g.has(l))try{await Tt({route:i.route,key:$},{manifest:t})}catch(H){if([409,503].includes(H.status))continue;throw V(i,$,{sha:I.head}),await bt({board:i,key:$,logFile:Bt(i,$,H)},1),H}}catch(l){w(`try /${i.route} ${$}: ${l.message}`)}}try{if(!o.repo||await m())continue;const d=await M(o.repo,"rev-parse",S);let E=!1;try{await M(o.repo,"cat-file","-e",`${d}:.kickflip/build`),E=!0}catch{}if(!E){const I=u.get(B(i,"main"));I&&await q(I),n.main=null,_(i);continue}const j=n.main;if(j?.state==="running"||j?.sha===d&&(j.state==="failed"||j.state==="ready"&&(n.kind!=="web"||xt(i.route,"main",{manifest:t}))))continue;const $=B(i,"main");if(g.has($))continue;const D=await M(o.repo,"log","-1","--format=%cI",d);let l=i.github;if(!l)try{l=Pt(await M(o.repo,"remote","get-url","origin"))}catch{}const F={sha:d,branch:h,slug:l||"",at:D,script:E};await St(i,o.repo,F)}catch(d){w(`try /${i.route} main: ${d.message}`)}}})().finally(()=>{R=null}),R)}c(at,"tick");function Ot(t,e){if(L.has(t.dir))return L.get(t.dir);const r=(async()=>{const s=X(t.route,e),i=s.branch||"main",{state:n}=N(t);n.pull={...n.pull,running:!0},_(t);let o,h;try{o=await $e(s.repo,i)}catch(S){h=S.message}if(o===null?delete n.pull:n.pull={at:st(),...h?{error:h}:{}},_(t),o===null)return null;if(h)return w(`pull /${t.route}: ${h}`),{commits:0,error:h};if(o.commits){w(`pull /${t.route}: ${i} fast-forwarded ${o.commits} commit${o.commits===1?"":"s"} to ${o.to.slice(0,7)}`);try{await v(t,"main-pulled",{branch:i,...o})}catch(S){w(`pull /${t.route}: could not send main-pulled (${S.message})`)}}return{commits:o.commits}})().finally(()=>L.delete(t.dir));return L.set(t.dir,r),r}c(Ot,"pullMain");async function Wt({manifest:t=K(),routes:e}={}){await Z(t);const r=[];for(const s of W(t)){if(G)break;if(e&&!e.includes(s.route))continue;const i=X(s.route,t);!i.local||!i.repo||(await Ot(s,t))?.commits&&r.push(s.route)}return r}c(Wt,"pullMains");async function Kt(t,{manifest:e=K()}={}){if(await Z(e),G)throw new x("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(n=>n!=="route")||typeof t.route!="string")throw new x("Send only the board route.");const r=W(e).find(n=>n.route===t.route);if(!r)throw new x(`/${t.route} is not a board.`,404);const s=X(r.route,e);if(!s.local||!s.repo)throw new x("This board fetches its branch on every poll; only a local board pulls.",409);const i=await Ot(r,e);if(!i)throw new x("This board\u2019s folder has no origin to pull from.",409);return i.commits&&at({manifest:e,routes:[r.route]}).catch(n=>w(`try /${r.route} main: ${n.message}`)),i}c(Kt,"pull");async function zt(){G=!0;const t=Promise.all([...u.values()].map(e=>e.ready?q(e):vt(e)));await Promise.all([t,R,...L.values()])}return c(zt,"stop"),{start:Tt,tick:at,stop:zt,lookup:xt,initialize:Z,pull:Kt,pullMains:Wt,endUnshared:Ht}}c(ge,"createTryManager");const ht=1e4,mt=c(async(a,...f)=>(await ft("git",["-C",a,...f],{encoding:"utf8",timeout:ht,env:te()})).stdout,"originGit");async function $e(a,f,{run:w=mt}={}){const m=c(async(...p)=>(await w(...p)).trim(),"git"),v=c(p=>{throw new Error(`can\u2019t pull: ${p}`)},"refuse");try{await m(a,"config","--get","remote.origin.url")}catch{return null}try{await m(a,"fetch","--quiet","--no-tags","origin",`+refs/heads/${f}:refs/remotes/origin/${f}`)}catch(p){v(p.killed?`git fetch timed out after ${ht/1e3} s`:At(p.stderr,{repo:a}).error)}try{const p=await m(a,"rev-parse","--verify",`refs/heads/${f}^{commit}`),k=await m(a,"rev-parse","--verify",`refs/remotes/origin/${f}^{commit}`),u=c((b,C)=>m(a,"merge-base","--is-ancestor",b,C).then(()=>!0,P=>{if(P.code===1)return!1;throw P}),"isAncestor");if(p===k||await u(k,p))return{from:p,to:p,commits:0};await u(p,k)||v(`${f} has split from origin`);const g=Number(await m(a,"rev-list","--count",`${p}..${k}`)),y=(await m(a,"worktree","list","--porcelain")).split(`
4
4
 
5
5
  `).map(b=>b.split(`
6
- `)).find(b=>b.includes(`branch refs/heads/${f}`))?.[0].slice(9);return y?(await m(y,"status","--porcelain","--untracked-files=no")&&v("local changes"),await m(y,"merge","--ff-only","--quiet",k)):await m(n,"update-ref",`refs/heads/${f}`,k,p),{from:p,to:k,commits:g}}catch(p){if(p.message.startsWith("can\u2019t pull: "))throw p;v(String(p.stderr||p.message).trim().split(`
7
- `).at(-1))}}a(me,"pullBranch");async function Ne({manifest:n=J(),log:f=console.log,routes:w}={}){const m=w?rt(It,{}):{};for(const v of W(n)){if(w&&!w.includes(v.route))continue;const p=Q(v.route,n);if(p.local||!p.repo)continue;const k=p.branch||"main",d=new Date().toISOString(),g=Date.now();try{await mt(p.repo,"fetch","--quiet","--no-tags","origin",`+refs/heads/${k}:refs/remotes/origin/${k}`),m[v.route]={at:d,ok:!0}}catch(y){f(`fetch /${v.route} after ${Date.now()-g} ms: ${y.message}`);let b=v.github;if(!b&&!v.remote)try{b=jt(await M(p.repo,"remote","get-url","origin"))}catch{}m[v.route]={at:d,ok:!1,...Mt(y.killed?`git fetch timed out after ${ht/1e3} s`:y.stderr,{github:b||"",remote:v.remote,repo:p.repo})};continue}if(v.remote)try{await we(v,p.repo,k,f)}catch(y){f(`pushed branches /${v.route}: ${y.message}`)}}Et(It,m)}a(Ne,"fetchTryBranches");async function we(n,f,w,m){const v=n.waves.flatMap(({slug:d,wave:g})=>g.items.filter(y=>y.pushed?.branch&&!ne(y)&&!["done","merged","dropped"].includes(String(y.status).toLowerCase())).map(y=>({key:`${d}/${y.id}`,branch:y.pushed.branch})));if(!v.length)return;const p=new Map((await mt(f,"ls-remote","--heads","origin")).split(`
8
- `).map(d=>/^([\da-f]+)\trefs\/heads\/(.+)$/.exec(d)).filter(Boolean).map(d=>[d[2],d[1]])),k=Qt(n.remote)?.host||"the remote";for(const d of v){let g=p.get(d.branch);if(!g)try{g=await M(f,"rev-parse","--verify","--quiet",`refs/heads/${d.branch}^{commit}`)}catch{}let y=!1;if(g)try{await M(f,"merge-base","--is-ancestor",g,`refs/remotes/origin/${w}`),y=!0}catch{}if(!(!y&&p.has(d.branch)))try{await re(n.dir,d.key,{status:y?"merged":"done",force:!0,text:y?`${d.branch} is merged into ${w} on ${k}, so this card is Done.`:`${d.branch} is gone from ${k}, so this card is Done.`})}catch(b){m(`pushed ${d.key}: ${b.message}`)}}}a(we,"settlePushed");const V=he({waiting:a(()=>Xt.waiting("tailscale"),"waiting")}),De=a((...n)=>V.start(...n),"startBuild"),Be=a((...n)=>V.tick(...n),"tryTick"),Fe=a((...n)=>V.pull(...n),"pullNow"),Re=a((...n)=>V.pullMains(...n),"pullMains"),Le=a(()=>V.stop(),"stopTries"),He=a((...n)=>V.initialize(...n),"initializeTries");export{T as BuildError,z as TRY_PORTS,he as createTryManager,Ne as fetchTryBranches,He as initializeTries,Bt as installWorktree,pt as isTryPort,me as pullBranch,Re as pullMains,Fe as pullNow,De as startBuild,Le as stopTries,Be as tryTick};
6
+ `)).find(b=>b.includes(`branch refs/heads/${f}`))?.[0].slice(9);return y?(await m(y,"status","--porcelain","--untracked-files=no")&&v("local changes"),await m(y,"merge","--ff-only","--quiet",k)):await m(a,"update-ref",`refs/heads/${f}`,k,p),{from:p,to:k,commits:g}}catch(p){if(p.message.startsWith("can\u2019t pull: "))throw p;v(String(p.stderr||p.message).trim().split(`
7
+ `).at(-1))}}c($e,"pullBranch");async function Le({manifest:a=K(),log:f=console.log,routes:w}={}){const m=w?et(Mt,{}):{};for(const v of W(a)){if(w&&!w.includes(v.route))continue;const p=X(v.route,a);if(p.local||!p.repo)continue;const k=p.branch||"main",u=new Date().toISOString(),g=Date.now();try{await mt(p.repo,"fetch","--quiet","--no-tags","origin",`+refs/heads/${k}:refs/remotes/origin/${k}`),m[v.route]={at:u,ok:!0}}catch(y){f(`fetch /${v.route} after ${Date.now()-g} ms: ${y.message}`);let b=v.github;if(!b&&!v.remote)try{b=Pt(await M(p.repo,"remote","get-url","origin"))}catch{}m[v.route]={at:u,ok:!1,...At(y.killed?`git fetch timed out after ${ht/1e3} s`:y.stderr,{github:b||"",remote:v.remote,repo:p.repo})};continue}if(v.remote)try{await be(v,p.repo,k,f)}catch(y){f(`pushed branches /${v.route}: ${y.message}`)}}It(Mt,m)}c(Le,"fetchTryBranches");async function be(a,f,w,m){const v=a.waves.flatMap(({slug:u,wave:g})=>g.items.filter(y=>y.pushed?.branch&&!ce(y)&&!["done","merged","dropped"].includes(String(y.status).toLowerCase())).map(y=>({key:`${u}/${y.id}`,branch:y.pushed.branch})));if(!v.length)return;const p=new Map((await mt(f,"ls-remote","--heads","origin")).split(`
8
+ `).map(u=>/^([\da-f]+)\trefs\/heads\/(.+)$/.exec(u)).filter(Boolean).map(u=>[u[2],u[1]])),k=qt(a.remote)?.host||"the remote";for(const u of v){let g=p.get(u.branch);if(!g)try{g=await M(f,"rev-parse","--verify","--quiet",`refs/heads/${u.branch}^{commit}`)}catch{}let y=!1;if(g)try{await M(f,"merge-base","--is-ancestor",g,`refs/remotes/origin/${w}`),y=!0}catch{}if(!(!y&&p.has(u.branch)))try{await oe(a.dir,u.key,{status:y?"merged":"done",force:!0,text:y?`${u.branch} is merged into ${w} on ${k}, so this card is Done.`:`${u.branch} is gone from ${k}, so this card is Done.`})}catch(b){m(`pushed ${u.key}: ${b.message}`)}}}c(be,"settlePushed");const J=ge({waiting:c(()=>ee.waiting("tailscale"),"waiting")}),He=c((...a)=>J.start(...a),"startBuild"),Ge=c((...a)=>J.tick(...a),"tryTick"),Ue=c((...a)=>J.pull(...a),"pullNow"),We=c((...a)=>J.pullMains(...a),"pullMains"),Ke=c(()=>J.stop(),"stopTries"),ze=c(()=>J.endUnshared(),"endUnsharedTries"),Je=c((...a)=>J.initialize(...a),"initializeTries");export{x as BuildError,z as TRY_PORTS,ge as createTryManager,ze as endUnsharedTries,Le as fetchTryBranches,Je as initializeTries,Rt as installWorktree,pt as isTryPort,$e as pullBranch,We as pullMains,Ue as pullNow,He as startBuild,Ke as stopTries,Ge as tryTick};
package/hub/upgrade.mjs CHANGED
@@ -1 +1 @@
1
- var E=Object.defineProperty;var t=(r,s)=>E(r,"name",{value:s,configurable:!0});import h from"node:fs";import d from"node:path";const _="https://registry.npmjs.org/@lovek4d%2Fkickflip/latest",C=60*6e4,v=t(r=>String(r).split("-")[0].split(".").map(Number),"parts");function F(r,s){const[l,u]=[v(r),v(s)];for(let n=0;n<3;n++)if((l[n]||0)!==(u[n]||0))return(l[n]||0)>(u[n]||0);return!1}t(F,"newer");function L({root:r,fetch:s=globalThis.fetch,builders:l,run:u,log:n=t(()=>{},"log"),changed:c=t(()=>{},"changed")}){const k=h.existsSync(d.join(r,".git"));let i=null,f=!1,a=!1,p=0,o=null;const y=t(()=>JSON.parse(h.readFileSync(d.join(r,"package.json"),"utf8")).version,"installed");async function S(){if(!k){try{const e=await s(_,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw new Error(`npm answered ${e.status}`);i=(await e.json()).version}catch(e){n(`kickflip update check failed: ${e.message}`)}c()}}t(S,"check");function g(){return k||!i||!F(i,y())?null:a?{state:"updating",version:i}:f?{state:"waiting",version:i,builders:p}:o?{state:"failed",version:i,error:o}:{state:"available",version:i}}t(g,"state");let m=Promise.resolve();const w=t(()=>m=m.catch(()=>{}).then(b),"tick");async function b(){if(!(!f||a)){if(p=(await l()).length,p){c();return}f=!1,a=!0,o=null,c(),u().then(({ok:e,error:x})=>{e||(o=x)},e=>{o=e.message}).finally(()=>{a=!1,c()})}}t(b,"tickOnce");async function j(){if(!g())throw Object.assign(new Error("kickflip is up to date."),{status:409});return a||(f=!0),await w(),g()}return t(j,"request"),{check:S,state:g,request:j,tick:w}}t(L,"upgrader");export{C as CHECK_MS,_ as LATEST_URL,F as newer,L as upgrader};
1
+ var x=Object.defineProperty;var e=(n,s)=>x(n,"name",{value:s,configurable:!0});import m from"node:fs";import h from"node:path";const b="https://registry.npmjs.org/@lovek4d%2Fkickflip/latest",A=60*6e4,v=e(n=>String(n).split("-")[0].split(".").map(Number),"parts");function p(n,s){const[a,l]=[v(n),v(s)];for(let r=0;r<3;r++)if((a[r]||0)!==(l[r]||0))return(a[r]||0)>(l[r]||0);return!1}e(p,"newer");function C({root:n,running:s,fetch:a=globalThis.fetch,run:l,log:r=e(()=>{},"log"),changed:c=e(()=>{},"changed"),pulled:w=e(()=>{},"pulled")}){const g=m.existsSync(h.join(n,".git"));let i=null,u=!1,o=null;const d=e(()=>JSON.parse(m.readFileSync(h.join(n,"package.json"),"utf8")).version,"installed");async function y(){if(!g){try{const t=await a(b,{signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new Error(`npm answered ${t.status}`);i=(await t.json()).version}catch(t){r(`kickflip update check failed: ${t.message}`)}i&&p(i,d())&&k(),c()}}e(y,"check");function f(){if(g)return null;const t=d();return p(t,s)?{state:"updated",version:t}:!i||!p(i,t)?null:u?{state:"updating",version:i}:o?{state:"failed",version:i,error:o}:{state:"available",version:i}}e(f,"state");function k(){u||(u=!0,o=null,l().then(({ok:t,error:j})=>{t?w():o=j},t=>{o=t.message}).finally(()=>{u=!1,c()}))}e(k,"pull");async function S(){if(!f()||f().state==="updated")throw Object.assign(new Error("kickflip is up to date."),{status:409});return k(),c(),f()}return e(S,"request"),{check:y,state:f,request:S}}e(C,"upgrader");export{A as CHECK_MS,b as LATEST_URL,p as newer,C as upgrader};
package/hub/usage.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var x=Object.defineProperty;var a=(t,e)=>x(t,"name",{value:e,configurable:!0});import f from"node:fs";import _ from"node:os";import m from"node:path";const S=6,N=180,b={five_hour:5*36e5,seven_day:7*864e5},h=a(t=>{try{return JSON.parse(f.readFileSync(t,"utf8"))}catch{return null}},"readJson"),y=a(t=>t==null||t===""||!Number.isFinite(Number(t))?null:Number(t),"num"),g=a(t=>{if(t==null||t==="")return null;const n=typeof t=="number"||/^\d+(\.\d+)?$/.test(String(t))?Number(t)>1e12?Number(t):Number(t)*1e3:Date.parse(String(t));return Number.isFinite(new Date(n).getTime())?new Date(n).toISOString():null},"isoOf"),w=a((t,e)=>({used_percentage:y(t),resets_at:g(e)}),"win");function O(t){let e;try{e=f.openSync(t,"r");const n=f.fstatSync(e).size;for(const r of[256*1024,2*1024*1024]){const s=Math.max(0,n-r),u=Buffer.alloc(n-s);f.readSync(e,u,0,u.length,s);const c=u.toString("utf8").split(`
2
- `);s>0&&c.shift();for(let i=c.length-1;i>=0;i--)if(c[i].includes("rate_limits"))try{const d=JSON.parse(c[i]),o=d?.payload?.rate_limits??d?.rate_limits;if(o?.primary)return{rl:o}}catch{}if(s===0)break}}catch{}finally{if(e!==void 0)try{f.closeSync(e)}catch{}}return null}a(O,"lastRateLimits");function k(t){const e=[],n=a(r=>{try{return f.readdirSync(r).sort().reverse()}catch{return[]}},"kids");t:for(const r of n(t))for(const s of n(m.join(t,r)))for(const u of n(m.join(t,r,s))){const c=m.join(t,r,s,u);for(const i of n(c))if(/^rollout-.*\.jsonl$/.test(i))try{e.push({file:m.join(c,i),mtime:f.statSync(m.join(c,i)).mtimeMs})}catch{}if(e.length>=S*2)break t}return e.sort((r,s)=>s.mtime-r.mtime).slice(0,S)}a(k,"newestRollouts");function D(t){const e=[];for(const{file:o,mtime:l}of k(t)){const p=O(o);p&&e.push({...p,mtime:l,resets:y(p.rl.primary.resets_at)})}if(!e.length)return null;const n=Math.max(...e.map(o=>o.resets??-1/0)),r=e.filter(o=>o.resets!=null&&Math.abs(o.resets-n)<=N),s=a(o=>r.reduce((l,p)=>(y(p.rl[o]?.used_percent)??-1)>(y(l?.rl[o]?.used_percent)??-1)?p:l,null),"pick");if(!r.length)return null;const u=s("primary"),c=s("secondary"),i=r.reduce((o,l)=>l.mtime>o.mtime?l:o),d=a((o,l)=>o?w(o.rl[l].used_percent,o.rl[l].resets_at):null,"w");return{five_hour:d(u,"primary"),seven_day:d(c,"secondary"),at:new Date(i.mtime).toISOString()}}a(D,"scanCodex");function j(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;const n=g(t.at),r=a(s=>{const u=t[s];if(!u)return null;const c=w(u.used_percentage,u.resets_at);if(c.used_percentage==null)return null;const i=!n||e-Date.parse(n)>b[s]?"stale":c.resets_at&&e>=Date.parse(c.resets_at)?"reset":"live";return{...c,used_percentage:i==="reset"?0:c.used_percentage,state:i}},"window");return{at:n,five_hour:r("five_hour"),seven_day:r("seven_day")}}a(j,"readingOf");function J({home:t=_.homedir(),now:e=Date.now,cacheMs:n=6e4}={}){const r=m.join(t,".codex","sessions");let s=null,u=-1/0;return({codexShare:c="off"}={})=>{const i=e(),d=j(h(m.join(t,".claude","kickflip","usage.json"))?.claude,i);return c==="off"?{claude:d,codex:null}:(i-u>=n&&(s=D(r),u=i),{claude:d,codex:j(s||{at:null},i)})}}a(J,"usageReader");const F=95,L=a((t,e)=>t==="deaf"&&e?.percent>=F,"contextFull");function R(t,{home:e=_.homedir()}={}){if(typeof t!="string"||!/^[\w-]+$/.test(t))return null;const n=h(m.join(e,".claude","kickflip","context",`${t}.json`));return y(n?.percent)==null||!n.at?null:{percent:y(n.percent),at:n.at}}a(R,"contextReading");async function W({gate:t,home:e=_.homedir(),resume:n}){const r=m.join(e,".claude","kickflip","usage-gate-state.json"),s=h(r);s?.state==="paused"&&t.state==="normal"&&await n(s.window),f.mkdirSync(m.dirname(r),{recursive:!0});const u=`${r}.${process.pid}.tmp`;f.writeFileSync(u,JSON.stringify(t)+`
3
- `),f.renameSync(u,r)}a(W,"checkUsagePause");export{F as CONTEXT_FULL,W as checkUsagePause,L as contextFull,R as contextReading,J as usageReader};
1
+ var N=Object.defineProperty;var a=(e,t)=>N(e,"name",{value:t,configurable:!0});import f from"node:fs";import _ from"node:os";import d from"node:path";import{audit as w,hubAudit as S}from"../shared/audit.mjs";const g=6,k=180,O={five_hour:5*36e5,seven_day:7*864e5},h=a(e=>{try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}},"readJson"),y=a(e=>e==null||e===""||!Number.isFinite(Number(e))?null:Number(e),"num"),j=a(e=>{if(e==null||e==="")return null;const n=typeof e=="number"||/^\d+(\.\d+)?$/.test(String(e))?Number(e)>1e12?Number(e):Number(e)*1e3:Date.parse(String(e));return Number.isFinite(new Date(n).getTime())?new Date(n).toISOString():null},"isoOf"),x=a((e,t)=>({used_percentage:y(e),resets_at:j(t)}),"win");function D(e){let t;try{t=f.openSync(e,"r");const n=f.fstatSync(t).size;for(const s of[256*1024,2*1024*1024]){const r=Math.max(0,n-s),c=Buffer.alloc(n-r);f.readSync(t,c,0,c.length,r);const i=c.toString("utf8").split(`
2
+ `);r>0&&i.shift();for(let u=i.length-1;u>=0;u--)if(i[u].includes("rate_limits"))try{const p=JSON.parse(i[u]),o=p?.payload?.rate_limits??p?.rate_limits;if(o?.primary)return{rl:o}}catch{}if(r===0)break}}catch{}finally{if(t!==void 0)try{f.closeSync(t)}catch{}}return null}a(D,"lastRateLimits");function $(e){const t=[],n=a(s=>{try{return f.readdirSync(s).sort().reverse()}catch{return[]}},"kids");e:for(const s of n(e))for(const r of n(d.join(e,s)))for(const c of n(d.join(e,s,r))){const i=d.join(e,s,r,c);for(const u of n(i))if(/^rollout-.*\.jsonl$/.test(u))try{t.push({file:d.join(i,u),mtime:f.statSync(d.join(i,u)).mtimeMs})}catch{}if(t.length>=g*2)break e}return t.sort((s,r)=>r.mtime-s.mtime).slice(0,g)}a($,"newestRollouts");function v(e){const t=[];for(const{file:o,mtime:l}of $(e)){const m=D(o);m&&t.push({...m,mtime:l,resets:y(m.rl.primary.resets_at)})}if(!t.length)return null;const n=Math.max(...t.map(o=>o.resets??-1/0)),s=t.filter(o=>o.resets!=null&&Math.abs(o.resets-n)<=k),r=a(o=>s.reduce((l,m)=>(y(m.rl[o]?.used_percent)??-1)>(y(l?.rl[o]?.used_percent)??-1)?m:l,null),"pick");if(!s.length)return null;const c=r("primary"),i=r("secondary"),u=s.reduce((o,l)=>l.mtime>o.mtime?l:o),p=a((o,l)=>o?x(o.rl[l].used_percent,o.rl[l].resets_at):null,"w");return{five_hour:p(c,"primary"),seven_day:p(i,"secondary"),at:new Date(u.mtime).toISOString()}}a(v,"scanCodex");function b(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=j(e.at),s=a(r=>{const c=e[r];if(!c)return null;const i=x(c.used_percentage,c.resets_at);if(i.used_percentage==null)return null;const u=!n||t-Date.parse(n)>O[r]?"stale":i.resets_at&&t>=Date.parse(i.resets_at)?"reset":"live";return{...i,used_percentage:u==="reset"?0:i.used_percentage,state:u}},"window");return{at:n,five_hour:s("five_hour"),seven_day:s("seven_day")}}a(b,"readingOf");function J({home:e=_.homedir(),now:t=Date.now,cacheMs:n=6e4}={}){const s=d.join(e,".codex","sessions");let r=null,c=-1/0;return({codexShare:i="off"}={})=>{const u=t(),p=b(h(d.join(e,".claude","kickflip","usage.json"))?.claude,u);return i==="off"?{claude:p,codex:null}:(u-c>=n&&(r=v(s),c=u),{claude:p,codex:b(r||{at:null},u)})}}a(J,"usageReader");const F=95,L=a((e,t)=>e==="deaf"&&t?.percent>=F,"contextFull");function R(e,{home:t=_.homedir()}={}){if(typeof e!="string"||!/^[\w-]+$/.test(e))return null;const n=h(d.join(t,".claude","kickflip","context",`${e}.json`));return y(n?.percent)==null||!n.at?null:{percent:y(n.percent),at:n.at}}a(R,"contextReading");async function W({gate:e,home:t=_.homedir(),resume:n}){const s=d.join(t,".claude","kickflip","usage-gate-state.json"),r=h(s);e.state==="paused"&&r?.state!=="paused"&&w(S(t),{call:"usage-pause",result:"paused",reason:`Claude's ${e.window==="five_hour"?"5-hour":"weekly"} usage reached the ${e.pause_at}% line.`,inputs:{gate:e,previous:r?.state??null}}),r?.state==="paused"&&e.state==="normal"&&(w(S(t),{call:"usage-resume",result:"resumed",reason:`Claude's ${r.window==="five_hour"?"5-hour":"weekly"} usage is under the line again, so every board was told.`,inputs:{gate:e,previous:r.window}}),await n(r.window)),f.mkdirSync(d.dirname(s),{recursive:!0});const c=`${s}.${process.pid}.tmp`;f.writeFileSync(c,JSON.stringify(e)+`
3
+ `),f.renameSync(c,s)}a(W,"checkUsagePause");export{F as CONTEXT_FULL,W as checkUsagePause,L as contextFull,R as contextReading,J as usageReader};
package/hub/views.mjs CHANGED
@@ -1 +1 @@
1
- var _=Object.defineProperty;var s=(e,t)=>_(e,"name",{value:t,configurable:!0});import{clock as c,holdLine as w,sendWords as H,snoozeEnd as f}from"./schedule.mjs";import{CHOICES as T,FOREVER as k,durationEnd as V,endOf as F}from"./duration.mjs";import{siteIcon as K}from"./icons.mjs";import{codexStatus as M}from"../shared/codex.mjs";const W=s(e=>e.charAt(0).toUpperCase()+e.slice(1),"capital"),b=s((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),h=s(e=>{const[t,n]=e.split(":").map(Number),o=new Date;return o.setHours(t,n,0,0),c(o,o)},"timeOfDay"),B=s(e=>`checks every ${e.every===1?"minute":`${e.every} min`} while you\u2019re ${e.present?"here":"away"}${e.low?", slower while GitHub\u2019s points are low":""}`,"cadenceLine"),G=s((e,t,n)=>`${B(t)}${e.hold?`; ${w(e.hold,n)}`:""}`,"nowLine"),S=s((e,t)=>e.hold?w(e.hold,t):"pushes go out after each check","deviceLine"),Z=s(e=>`${h(e.quiet.start)} \u2013 ${h(e.quiet.end)}${e.quiet.hold?" \xB7 pushes held":""}`,"quietSummary"),Q="checks every minute while you're here, every 5 when away",X=s((e,t)=>e.count?`${e.count} push${e.count===1?"":"es"} queued; next send ${H(e.nextFlushAt,t)}.`:"No pushes queued.","queuedLine");function Y({running:e=!1,nextAt:t,last:n=null},o){if(e)return"Checking GitHub now";const l=`Next check ${c(t,o)}`;if(!n)return l;const u=n.failed.length?"could not reach GitHub for every PR":n.watched?`${b(n.watched,"PR")}, ${n.changes.length?`${n.changes.length} changed`:"no change"}`:"no PRs watched";return`${l} \xB7 last ${c(new Date(n.at),o)}, ${u}`}s(Y,"pollLine");function j(e,t,n){return{title:W(G(e,t,n)),lines:[Y(t,n),X(e,n)],count:e.count}}s(j,"pollingNow");function J(e,t){const n={port:"down \xB7 not answering",files:"down \xB7 folder missing"}[e.serves]||"down \xB7 restarting";if(e.state!=="up")return{tone:e.state==="down"?"down":"wait",word:e.state==="down"?n:e.state,lines:[]};if(!t)return{tone:"ok",word:"up",lines:[]};const o=t.filter(r=>!r.ok),l=o.filter(r=>r.state==="broken"),u=t.find(r=>r.link==="events"),a=u?.listen==="asleep"||u?.listen==="waking"?u.listen:u?.ok?"listening":"not listening",d=l.length?`degraded \xB7 ${a}`:o.length?`up \xB7 ${a} \xB7 ${o.length} settling`:`up \xB7 ${a} \xB7 every link passes`;return{tone:o.length?"wait":"ok",word:d,lines:o.map(r=>({link:r.link,detail:`${r.state==="broken"?"":"settling: "}${r.detail}`}))}}s(J,"siteHealth");const A=[{value:"always",label:"Always on",description:s(()=>"Codex implements and reviews. Work pauses when it runs out.","description")},{value:"auto",label:"Auto",description:s(e=>`Codex implements and reviews, and ${e} takes over while it's out.`,"description")},{value:"off",label:"Off",description:s(e=>`${e} implements and reviews.`,"description")}],ee=s((e,t,n)=>({usable:t.usable,tag:t.usable?null:t.reason,share:e,choices:A.map(({value:o,label:l})=>({value:o,label:l,on:o===e})),description:t.usable?A.find(o=>o.value===e).description(q[n]):t.words,fix:t.fix}),"codexView"),q={opus:"Opus",sonnet:"Sonnet",auto:"Claude"},N=[{value:"opus",label:"Opus",description:"Always Opus. Auto would give small cards to Sonnet."},{value:"auto",label:"Auto",description:"Auto: small cards get Sonnet, the rest get Opus."},{value:"sonnet",label:"Sonnet",description:"Always Sonnet. Auto would give large cards to Opus."}],te=s(e=>({model:e,builder:q[e],choices:N.map(({value:t,label:n})=>({value:t,label:n,on:t===e})),description:N.find(t=>t.value===e).description}),"claudeView");function de({now:e,st:t,poll:n,sidebar:o,rows:l,links:u=new Map,code:a={},host:d="",rules:r=[],remembered:y=new Map,integrations:p=[],codexShare:R="off",claudeModel:x="auto",codex:U=M({installed:!1}),awake:O=null}){const $=new Set(o.sites.filter(i=>i.board).map(i=>i.route)),E=!!(a.running&&a.running===a.onDisk),z=E?` \xB7 runs the code in its files (${a.onDisk})`:"",D=s(i=>({route:i.route,title:i.title,icon:K(i.route,i),href:`/${encodeURIComponent(i.route)}/`,...J(i,u.get(i.route)),remembered:y.get(i.route)||[],restart:$.has(i.route)&&i.restart===!0}),"site"),I=[["Boards",l.filter(i=>$.has(i.route))],["Pages",l.filter(i=>!$.has(i.route))]].filter(([,i])=>i.length).map(([i,L])=>({label:i,sites:L.map(D)}));return{hub:{tone:o.hub.tone,word:o.hub.word,detail:`${o.hub.detail}${z}`,restart:!E},awake:O&&g(O,e,v),groups:I,integrations:p,usage:o.usage,pause:o.pause,codex:ee(R,U,x),claude:te(x),empty:l.length===0,polling:j(t,n,e),notifications:{on:t.settings.notifications.on,text:o.notifications.text,device:S(t,e)},hold:t.hold&&t.hold.why!=="off"?{text:`Notifications ${w(t.hold,e)}`,end:t.hold.why==="snoozed"}:null,rules:r.length?b(r.length,"rule"):"None yet",sites:b(l.length,"site"),host:d,total:o.total}}s(de,"hubView");const ce="That snooze ends in the past or more than 30 days on. Pick another time.",he="That keep awake ends in the past or more than 30 days on. Pick another time.",C="until you end it",v="until you turn it off",g=s((e,t,n)=>e===k?n:`until ${c(e,t)}`,"untilWords"),P=s((e,t)=>T.map(([n,o])=>({value:n,label:o,until:g(V(e,n),e,t)})),"durationChoices"),ne=s((e,t)=>e.on?F(e.snoozed_until,t):null,"snoozedUntil");function pe({now:e,st:t,rules:n=[],route:o={atMac:!1,desktops:0},linear:l={set:!1},awake:u={until:null,unsupported:null}}){const a=t.settings,d=a.notifications,r=ne(d,e),y=t.count?` The ${t.count} queued push${t.count===1?" is":"es are"} dropped now.`:"",p=r&&`Snoozed ${g(r,e,C)}`;return{snoozed:r?{title:p,summary:r===k?"Snoozed \xB7 forever":p}:null,device:S(t,e),on:{on:d.on,sub:d.on?"On. Turn off to drop every push, urgent ones too.":"Off. Every push is dropped, urgent ones too. Needs you and the badge still update.",confirm:`Turn off notifications? Every push is dropped until you turn them back on, urgent ones too.${y} Needs you and the badge still update.`},presence:d.on?o.atMac?o.desktops?{title:"At the host",sub:"Pushes go to the host only. Prompts, faults and urgent pushes still reach the phone."}:{title:"At the host",sub:"No notifications on the host, so pushes still go to the phone."}:{title:"Away from the host",sub:"Pushes go to every device. At the host means unlocked and used in the last 3 minutes."}:null,snooze:d.on&&!r?{choices:P(e,C)}:null,awake:{unsupported:u.unsupported,on:u.until?{title:`Keeping awake ${g(u.until,e,v)}`}:null,choices:u.unsupported||u.until?null:P(e,v),summary:u.unsupported||(u.until?u.until===k?"On \xB7 forever":`On until ${c(u.until,e)}`:"Off")},weekends:{on:d.weekends_off,sub:`Pushes wait from Friday ${h(a.quiet.start)} until Monday ${h(a.quiet.end)}. Urgent ones still go.`},quiet:se(a,e),rules:n,linear:oe(l)}}s(pe,"settingsView");const m={url:"https://linear.app/settings/account/security",label:"Linear \u203A Settings \u203A Security & access \u203A Personal API keys"};function oe(e){const t=e.workspace?`${e.workspace} workspace`:"";return e.set?e.refused?{set:!0,refused:!0,title:t||"Linear key",down:"doesn\u2019t work",sub:`Linear refused the key. Make a new one in ${m.label} and paste it here.`,keys:m,summary:t?`Key doesn\u2019t work \xB7 ${t}`:"Key doesn\u2019t work"}:{set:!0,title:t,sub:"Key \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",summary:`Key set \xB7 ${t}`}:{set:!1,title:"No key",sub:`Make a personal API key in ${m.label}, then paste it here.`,keys:m,summary:"No key"}}s(oe,"linearWords");function se(e,t){const n=e.quiet,[o,l]=[h(n.start),h(n.end)],u=f(t,"tonight",e),a=[["Snooze tonight",`Until ${c(u,t)}${n.hold?`, then quiet hours hold pushes until ${c(f(u,"morning",e),t)}`:""}.`],["Snooze morning",`Until ${c(f(t,"morning",e),t)}.`],["Snooze monday",`Until ${c(f(t,"monday",e),t)}.`],["Off on weekends",e.notifications.weekends_off?`Pushes wait from Friday ${o} until Monday ${l}.`:"Off."],["Daily wake",`Every board wakes once at ${l}, when quiet hours end.`]];return{start:n.start,end:n.end,summary:Z(e),hint:Q,hold:{on:n.hold,sub:n.hold?`Pushes queued after ${o} wait until ${l}. Urgent ones still go.`:"Off. Pushes go out all night."},reads:a.map(([d,r])=>({title:d,sub:r}))}}s(se,"quietView");function fe(e){return e?e.ok?{sent:e.sent,count:e.count,ok:!0,message:`Sent ${e.count} queued push${e.count===1?"":"es"}.`}:{sent:e.sent,count:e.count,ok:!1,message:"Could not send the queue. It stays queued for the next check."}:{sent:0,count:0,ok:!0,message:"Nothing was queued."}}s(fe,"flushView");export{he as AWAKE_REFUSED,Q as QUIET_HINT,ce as SNOOZE_REFUSED,B as cadenceLine,W as capital,P as durationChoices,fe as flushView,de as hubView,G as nowLine,b as plural,Y as pollLine,Z as quietSummary,pe as settingsView,J as siteHealth};
1
+ var K=Object.defineProperty;var s=(e,t)=>K(e,"name",{value:t,configurable:!0});import{clock as d,holdLine as y,sendWords as F,snoozeEnd as m}from"./schedule.mjs";import{CHOICES as H,FOREVER as w,durationEnd as V,endOf as W}from"./duration.mjs";import{siteIcon as M}from"./icons.mjs";import{codexStatus as B}from"../shared/codex.mjs";const G=s(e=>e.charAt(0).toUpperCase()+e.slice(1),"capital"),b=s((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),p=s(e=>{const[t,n]=e.split(":").map(Number),o=new Date;return o.setHours(t,n,0,0),d(o,o)},"timeOfDay"),Z=s(e=>`checks every ${e.every===1?"minute":`${e.every} min`} while you\u2019re ${e.present?"here":"away"}${e.low?", slower while GitHub\u2019s points are low":""}`,"cadenceLine"),j=s((e,t,n)=>`${Z(t)}${e.hold?`; ${y(e.hold,n)}`:""}`,"nowLine"),A=s((e,t)=>e.hold?y(e.hold,t):"pushes go out after each check","deviceLine"),J=s(e=>`${p(e.quiet.start)} \u2013 ${p(e.quiet.end)}${e.quiet.hold?" \xB7 pushes held":""}`,"quietSummary"),Q="checks every minute while you're here, every 5 when away",X=s((e,t)=>e.count?`${e.count} push${e.count===1?"":"es"} queued; next send ${F(e.nextFlushAt,t)}.`:"No pushes queued.","queuedLine");function Y({running:e=!1,nextAt:t,last:n=null},o){if(e)return"Checking GitHub now";const a=`Next check ${d(t,o)}`;if(!n)return a;const u=n.failed.length?"could not reach GitHub for every PR":n.watched?`${b(n.watched,"PR")}, ${n.changes.length?`${n.changes.length} changed`:"no change"}`:"no PRs watched";return`${a} \xB7 last ${d(new Date(n.at),o)}, ${u}`}s(Y,"pollLine");function ee(e,t,n){return{title:G(j(e,t,n)),lines:[Y(t,n),X(e,n)],count:e.count}}s(ee,"pollingNow");function te(e,t){const n={port:"down \xB7 not answering",files:"down \xB7 folder missing"}[e.serves]||"down \xB7 restarting";if(e.state!=="up")return{tone:e.state==="down"?"down":"wait",word:e.state==="down"?n:e.state,lines:[]};if(!t)return{tone:"ok",word:"up",lines:[]};const o=t.filter(r=>!r.ok),a=o.filter(r=>r.state==="broken"),u=t.find(r=>r.link==="events"),l=u?.listen==="asleep"||u?.listen==="waking"?u.listen:u?.ok?"listening":"not listening",c=a.length?`degraded \xB7 ${l}`:o.length?`up \xB7 ${l} \xB7 ${o.length} settling`:`up \xB7 ${l} \xB7 every link passes`;return{tone:o.length?"wait":"ok",word:c,lines:o.map(r=>({link:r.link,detail:`${r.state==="broken"?"":"settling: "}${r.detail}`}))}}s(te,"siteHealth");const q=[{value:"always",label:"Always on",description:s(()=>"Codex implements and reviews. Work pauses when it runs out.","description")},{value:"auto",label:"Auto",description:s(e=>`Codex implements and reviews, and ${e} takes over while it's out.`,"description")},{value:"off",label:"Off",description:s(e=>`${e} implements and reviews.`,"description")}],ne=s((e,t,n)=>({usable:t.usable,tag:t.usable?null:t.reason,share:e,choices:q.map(({value:o,label:a})=>({value:o,label:a,on:o===e})),description:t.usable?q.find(o=>o.value===e).description(N[n]):t.words,fix:t.fix}),"codexView"),N={opus:"Opus",sonnet:"Sonnet",auto:"Claude"},C=[{value:"opus",label:"Opus",description:"Always Opus. Auto would give small cards to Sonnet."},{value:"auto",label:"Auto",description:"Auto: small cards get Sonnet, the rest get Opus."},{value:"sonnet",label:"Sonnet",description:"Always Sonnet. Auto would give large cards to Opus."}],oe=s(e=>({model:e,builder:N[e],choices:C.map(({value:t,label:n})=>({value:t,label:n,on:t===e})),description:C.find(t=>t.value===e).description}),"claudeView");function fe({now:e,st:t,poll:n,sidebar:o,rows:a,links:u=new Map,code:l={},host:c="",version:r,rules:h=[],remembered:f=new Map,integrations:U=[],codexShare:I="off",claudeModel:O="auto",codex:L=B({installed:!1}),awake:v=null}){const $=new Set(o.sites.filter(i=>i.board).map(i=>i.route)),E=!!(l.running&&l.running===l.onDisk),P=E?` \xB7 runs the code in its files (${l.onDisk})`:"",T=s(i=>({route:i.route,title:i.title,icon:M(i.route,i),href:`/${encodeURIComponent(i.route)}/`,...te(i,u.get(i.route)),remembered:f.get(i.route)||[],restart:$.has(i.route)&&i.restart===!0}),"site"),z=[["Boards",a.filter(i=>$.has(i.route))],["Pages",a.filter(i=>!$.has(i.route))]].filter(([,i])=>i.length).map(([i,D])=>({label:i,sites:D.map(T)}));return{hub:{tone:o.hub.tone,word:o.hub.word,detail:`${o.hub.detail}${P}`,restart:!E},awake:v&&g(v,e,S),groups:z,integrations:U,usage:o.usage,pause:o.pause,codex:ne(I,L,O),claude:oe(O),empty:a.length===0,polling:ee(t,n,e),notifications:{on:t.settings.notifications.on,text:o.notifications.text,device:A(t,e)},hold:t.hold&&t.hold.why!=="off"?{text:`Notifications ${y(t.hold,e)}`,end:t.hold.why==="snoozed"}:null,rules:h.length?b(h.length,"rule"):"None yet",sites:b(a.length,"site"),host:c,version:r,total:o.total}}s(fe,"hubView");const me="That snooze ends in the past or more than 30 days on. Pick another time.",ge="That keep awake ends in the past or more than 30 days on. Pick another time.",_="until you end it",S="until you turn it off",g=s((e,t,n)=>e===w?n:`until ${d(e,t)}`,"untilWords"),R=s((e,t)=>H.map(([n,o])=>({value:n,label:o,until:g(V(e,n),e,t)})),"durationChoices"),se=s((e,t)=>e.on?W(e.snoozed_until,t):null,"snoozedUntil");function ke({now:e,st:t,rules:n=[],linear:o={set:!1},slack:a={set:!1},awake:u={until:null,unsupported:null}}){const l=t.settings,c=l.notifications,r=se(c,e),h=t.count?` The ${t.count} queued push${t.count===1?" is":"es are"} dropped now.`:"",f=r&&`Snoozed ${g(r,e,_)}`;return{snoozed:r?{title:f,summary:r===w?"Snoozed \xB7 forever":f}:null,device:A(t,e),on:{on:c.on,sub:c.on?"On. Turn off to drop every push, urgent ones too.":"Off. Every push is dropped, urgent ones too. Needs you and the badge still update.",confirm:`Turn off notifications? Every push is dropped until you turn them back on, urgent ones too.${h} Needs you and the badge still update.`},snooze:c.on&&!r?{choices:R(e,_)}:null,awake:{unsupported:u.unsupported,on:u.until?{title:`Keeping awake ${g(u.until,e,S)}`}:null,choices:u.unsupported||u.until?null:R(e,S),summary:u.unsupported||(u.until?u.until===w?"On \xB7 forever":`On until ${d(u.until,e)}`:"Off")},weekends:{on:c.weekends_off,sub:`Pushes wait from Friday ${p(l.quiet.start)} until Monday ${p(l.quiet.end)}. Urgent ones still go.`},quiet:ae(l,e),rules:n,linear:re(o),slack:ue(a)}}s(ke,"settingsView");const ie={display_information:{name:"Kickflip"},oauth_config:{scopes:{user:["chat:write","im:write","reactions:write","users:read"]}}},x={url:`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(ie))}`,label:"a new Slack app"};function ue(e){const t=e.team?`${e.team} workspace`:"",n=`Make ${x.label}, install it to your workspace, then paste its User OAuth Token (xoxp-\u2026) here.`;return e.set?e.refused?{set:!0,refused:!0,title:t||"Slack token",down:"doesn\u2019t work",sub:`Slack refused the token. ${n}`,keys:x,summary:t?`Token doesn\u2019t work \xB7 ${t}`:"Token doesn\u2019t work"}:{set:!0,title:t,sub:`Token \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 \xB7 sends as ${e.user}`,summary:`Token set \xB7 ${t}`}:{set:!1,title:"No token",sub:n,keys:x,summary:"No token"}}s(ue,"slackWords");const k={url:"https://linear.app/settings/account/security",label:"Linear \u203A Settings \u203A Security & access \u203A Personal API keys"};function re(e){const t=e.workspace?`${e.workspace} workspace`:"";return e.set?e.refused?{set:!0,refused:!0,title:t||"Linear key",down:"doesn\u2019t work",sub:`Linear refused the key. Make a new one in ${k.label} and paste it here.`,keys:k,summary:t?`Key doesn\u2019t work \xB7 ${t}`:"Key doesn\u2019t work"}:{set:!0,title:t,sub:"Key \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",summary:`Key set \xB7 ${t}`}:{set:!1,title:"No key",sub:`Make a personal API key in ${k.label}, then paste it here.`,keys:k,summary:"No key"}}s(re,"linearWords");function ae(e,t){const n=e.quiet,[o,a]=[p(n.start),p(n.end)],u=m(t,"tonight",e),l=[["Snooze tonight",`Until ${d(u,t)}${n.hold?`, then quiet hours hold pushes until ${d(m(u,"morning",e),t)}`:""}.`],["Snooze morning",`Until ${d(m(t,"morning",e),t)}.`],["Snooze monday",`Until ${d(m(t,"monday",e),t)}.`],["Off on weekends",e.notifications.weekends_off?`Pushes wait from Friday ${o} until Monday ${a}.`:"Off."],["Daily wake",`Every board wakes once at ${a}, when quiet hours end.`]];return{start:n.start,end:n.end,summary:J(e),hint:Q,hold:{on:n.hold,sub:n.hold?`Pushes queued after ${o} wait until ${a}. Urgent ones still go.`:"Off. Pushes go out all night."},reads:l.map(([c,r])=>({title:c,sub:r}))}}s(ae,"quietView");function $e(e){return e?e.ok?{sent:e.sent,count:e.count,ok:!0,message:`Sent ${e.count} queued push${e.count===1?"":"es"}.`}:{sent:e.sent,count:e.count,ok:!1,message:"Could not send the queue. It stays queued for the next check."}:{sent:0,count:0,ok:!0,message:"Nothing was queued."}}s($e,"flushView");export{ge as AWAKE_REFUSED,Q as QUIET_HINT,me as SNOOZE_REFUSED,Z as cadenceLine,G as capital,R as durationChoices,$e as flushView,fe as hubView,j as nowLine,b as plural,Y as pollLine,J as quietSummary,ke as settingsView,te as siteHealth};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovek4d/kickflip",
3
- "version": "0.5.0",
3
+ "version": "0.5.3",
4
4
  "description": "Follow and steer Claude Code sessions from your phone.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -26,6 +26,7 @@
26
26
  "CONTEXT.md",
27
27
  "!**/*.test.mjs",
28
28
  "!board/mini-dom.mjs",
29
+ "!board/board-fixture.mjs",
29
30
  "!hub/fake-device.mjs",
30
31
  "!shared/test-helpers.mjs"
31
32
  ]
@@ -0,0 +1,4 @@
1
+ var $=Object.defineProperty;var i=(t,n)=>$(t,"name",{value:n,configurable:!0});import o from"node:fs";import x from"node:os";import f from"node:path";const l=30,m=864e5,E=i(t=>f.join(t,"data","audit.jsonl"),"boardAudit"),J=i((t=x.homedir())=>f.join(t,".claude","kickflip","audit.jsonl"),"hubAudit");function A(t){let n;try{n=o.openSync(t,"r")}catch(r){if(r.code==="ENOENT")return null;throw r}try{const r=Buffer.alloc(64),a=o.readSync(n,r,0,r.length,0);return Date.parse(r.toString("utf8",0,a).match(/^\{"at":"([^"]+)"/)?.[1])}finally{o.closeSync(n)}}i(A,"oldestAt");function k(t,{call:n,key:r,result:a,reason:c,inputs:e},{now:s=new Date,once:S=!1}={}){if(S){const u=y(t,{key:r,now:s}).findLast(N=>N.call===n);if(u?.result===a&&u.reason===c)return}const p=JSON.stringify({at:s.toISOString(),call:n,...r?{key:r}:{},result:a,reason:c,inputs:e})+`
2
+ `;o.mkdirSync(f.dirname(t),{recursive:!0});const h=s.getTime()-l*m;if(!(A(t)<h))return o.appendFileSync(t,p);const g=y(t,{now:s}).map(u=>JSON.stringify(u)+`
3
+ `).join(""),d=`${t}.${process.pid}.tmp`;o.writeFileSync(d,g+p),o.renameSync(d,t)}i(k,"audit");function y(t,{key:n,now:r=new Date}={}){let a;try{a=o.readFileSync(t,"utf8")}catch(e){if(e.code==="ENOENT")return[];throw e}const c=r.getTime()-l*m;return a.split(`
4
+ `).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}}).filter(e=>Date.parse(e.at)>=c&&(!n||e.key===n))}i(y,"readAudit");function F(t){return t.length?t.flatMap(n=>[`${n.at} ${[n.call,n.key].filter(Boolean).join(" ")}: ${n.result}. ${n.reason}`,` inputs: ${JSON.stringify(n.inputs??{})}`]):[`No calls in the last ${l} days.`]}i(F,"auditLines");export{l as AUDIT_DAYS,k as audit,F as auditLines,E as boardAudit,J as hubAudit,y as readAudit};
@@ -1,8 +1,8 @@
1
- var p=Object.defineProperty;var t=(e,r)=>p(e,"name",{value:r,configurable:!0});import n from"node:fs";import l from"node:path";import{PR_VIEW_FIELDS as g}from"../hub/pr-report.mjs";const o=t((e,r,s,i)=>{const a=l.join(e,r,`${String(s).replace(/[/#]/g,"__")}.json`);n.mkdirSync(l.dirname(a),{recursive:!0}),n.writeFileSync(a,JSON.stringify(i))},"write"),w=t((e,r,s)=>o(e,"pr",r,s),"writePR"),x=t((e,r,s)=>o(e,"issue-comments",r,s),"writeIssueComments"),v=t((e,r,s)=>o(e,"review-comments",r,s),"writeReviewComments"),b=t((e,r,s)=>o(e,"reviews",r,s),"writeReviews"),S=t((e,r,s)=>o(e,"merge",r,s),"writeMerge"),_=t((e,r,s)=>o(e,"ready",r,s),"writeReady"),j=t((e,r)=>o(e,"","user",r),"writeUser"),R=t((e,r)=>o(e,"","accounts",r),"writeAccounts"),c=t((e,r)=>{try{return n.readFileSync(l.join(e,r),"utf8").trim().split(`
2
- `).filter(Boolean).map(JSON.parse)}catch{return[]}},"jsonl"),f=t(e=>c(e,"calls.jsonl"),"calls"),O=t((e,r)=>o(e,"","rate",r),"writeRate"),N=t(e=>f(e).filter(r=>r[0]==="api"&&r[1]==="graphql").map(r=>[...r[3].matchAll(/repository\(owner: "([^"]+)", name: "([^"]+)"\) \{ pullRequest\(number: (\d+)\)/g)].map(([,s,i,a])=>`${s}/${i}#${a}`)),"queried"),k=t(e=>c(e,"tokens.jsonl"),"tokens");function E({head:e="abc1234567",failing:r=[],pending:s=0,...i}={}){return{state:"OPEN",isDraft:!1,reviewDecision:"REVIEW_REQUIRED",mergeable:"MERGEABLE",mergeStateStatus:"BLOCKED",headRefOid:e,statusCheckRollup:[...r.map(a=>({__typename:"CheckRun",name:a,status:"COMPLETED",conclusion:"FAILURE"})),...Array.from({length:s},(a,u)=>({__typename:"CheckRun",name:`ci-${u}`,status:"IN_PROGRESS",conclusion:""}))],...i}}t(E,"prView");function J(e){const r=l.join(e,"bin");return n.mkdirSync(r,{recursive:!0}),n.writeFileSync(l.join(r,"gh"),`#!${process.execPath}
1
+ var p=Object.defineProperty;var t=(s,e)=>p(s,"name",{value:e,configurable:!0});import n from"node:fs";import l from"node:path";import{PR_VIEW_FIELDS as g}from"../hub/pr-report.mjs";const o=t((s,e,r,i)=>{const a=l.join(s,e,`${String(r).replace(/[/#]/g,"__")}.json`);n.mkdirSync(l.dirname(a),{recursive:!0}),n.writeFileSync(a,JSON.stringify(i))},"write"),y=t((s,e,r)=>o(s,"pr",e,r),"writePR"),v=t((s,e,r)=>o(s,"issue-comments",e,r),"writeIssueComments"),x=t((s,e,r)=>o(s,"review-comments",e,r),"writeReviewComments"),b=t((s,e,r)=>o(s,"reviews",e,r),"writeReviews"),_=t((s,e,r)=>o(s,"merge",e,r),"writeMerge"),j=t((s,e,r)=>o(s,"ready",e,r),"writeReady"),S=t((s,e,r)=>o(s,"open",e,r),"writeOpen"),R=t((s,e)=>o(s,"","user",e),"writeUser"),O=t((s,e,r={login:e})=>o(s,"github-users",e,r),"writeGithubUser"),N=t((s,e,r)=>o(s,"collaborators",e.replace("/","__"),r),"writeCollaborators"),k=t((s,e)=>o(s,"","accounts",e),"writeAccounts"),c=t((s,e)=>{try{return n.readFileSync(l.join(s,e),"utf8").trim().split(`
2
+ `).filter(Boolean).map(JSON.parse)}catch{return[]}},"jsonl"),f=t(s=>c(s,"calls.jsonl"),"calls"),$=t((s,e)=>o(s,"","rate",e),"writeRate"),q=t(s=>f(s).filter(e=>e[0]==="api"&&e[1]==="graphql").map(e=>[...e[3].matchAll(/repository\(owner: "([^"]+)", name: "([^"]+)"\) \{ pullRequest\(number: (\d+)\)/g)].map(([,r,i,a])=>`${r}/${i}#${a}`)),"queried"),E=t(s=>c(s,"tokens.jsonl"),"tokens");function J({head:s="abc1234567",failing:e=[],pending:r=0,...i}={}){return{state:"OPEN",isDraft:!1,reviewDecision:"REVIEW_REQUIRED",mergeable:"MERGEABLE",mergeStateStatus:"BLOCKED",headRefOid:s,statusCheckRollup:[...e.map(a=>({__typename:"CheckRun",name:a,status:"COMPLETED",conclusion:"FAILURE"})),...Array.from({length:r},(a,u)=>({__typename:"CheckRun",name:`ci-${u}`,status:"IN_PROGRESS",conclusion:""}))],...i}}t(J,"prView");function A(s){const e=l.join(s,"bin");return n.mkdirSync(e,{recursive:!0}),n.writeFileSync(l.join(e,"gh"),`#!${process.execPath}
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
- const dir = ${JSON.stringify(e)};
5
+ const dir = ${JSON.stringify(s)};
6
6
  const args = process.argv.slice(2);
7
7
  fs.appendFileSync(path.join(dir, 'calls.jsonl'), JSON.stringify(args) + '\\n');
8
8
  fs.appendFileSync(path.join(dir, 'tokens.jsonl'), JSON.stringify({ args, token: process.env.GH_TOKEN || null }) + '\\n');
@@ -46,6 +46,11 @@ if (args.length === 4 && args[0] === 'api' && args[2] === '-f' && args[3].starts
46
46
  console.log(JSON.stringify({ html_url: 'https://github.com/' + args[1].slice('repos/'.length) }));
47
47
  process.exit(0);
48
48
  }
49
+ // A Comment review posted with gh api repos/<repo>/pulls/<n>/reviews -f body=\u2026 -f event=\u2026 -f commit_id=\u2026: answers its html_url.
50
+ if (args.length === 8 && args[0] === 'api' && args[2] === '-f' && args[4] === '-f' && args[6] === '-f' && /^repos\\/[^/]+\\/[^/]+\\/pulls\\/\\d+\\/reviews$/.test(args[1])) {
51
+ console.log(JSON.stringify({ html_url: 'https://github.com/' + args[1].slice('repos/'.length).replace('/pulls/', '/pull/').replace(/\\/reviews$/, '') + '#pullrequestreview-1' }));
52
+ process.exit(0);
53
+ }
49
54
  // The hub's one GraphQL query (hub/pr-report.mjs fetchPRs), answered from the same fixtures as the REST calls: each
50
55
  // aliased PR from its pr, issue-comments, review-comments and reviews fixtures, the viewer from user.json and the rate
51
56
  // limit from rate.json. A PR without a fixture, or {fail: true}, comes back null with an error, as GitHub answers.
@@ -58,6 +63,9 @@ if (args.length === 4 && args[0] === 'api' && args[1] === 'graphql' && args[2] =
58
63
  const list = (folder, repo, n) => { const v = read(fixture(folder, repo, n), []); return Array.isArray(v) ? v : []; };
59
64
  const data = { viewer: user ? { login: user.login } : null, rateLimit: rate };
60
65
  const errors = [];
66
+ for (const [, alias, owner, name] of args[3].matchAll(/(open\\d+): repository\\(owner: "([^"]+)", name: "([^"]+)"\\) \\{ pullRequests\\(/g)) {
67
+ data[alias] = { pullRequests: { nodes: read(path.join(dir, 'open', owner + '__' + name + '.json'), []) } };
68
+ }
61
69
  for (const [, alias, owner, name, n] of args[3].matchAll(/(\\w+): repository\\(owner: "([^"]+)", name: "([^"]+)"\\) \\{ pullRequest\\(number: (\\d+)\\)/g)) {
62
70
  const repo = owner + '/' + name;
63
71
  const view = read(fixture('pr', repo, n), null);
@@ -84,6 +92,11 @@ let file;
84
92
  let list = false;
85
93
  if (args.length === 7 && args[0] === 'pr' && args[1] === 'view' && /^\\d+$/.test(args[2]) && args[3] === '--repo' && args[5] === '--json' && args[6] === ${JSON.stringify(g)}) file = fixture('pr', args[4], args[2]);
86
94
  else if (args.length === 2 && args[0] === 'api' && args[1] === 'user') file = path.join(dir, 'user.json');
95
+ else if (args.length === 2 && args[0] === 'api' && /^users\\/[\\w-]+$/.test(args[1])) file = path.join(dir, 'github-users', args[1].slice(6) + '.json');
96
+ else if (args.length === 4 && args[0] === 'api' && args[1] === '--paginate' && args[2] === '--slurp' && /^repos\\/[^/]+\\/[^/]+\\/collaborators$/.test(args[3])) {
97
+ file = path.join(dir, 'collaborators', args[3].split('/').slice(1, 3).join('__') + '.json');
98
+ list = true;
99
+ }
87
100
  else if (args.length === 4 && args[0] === 'api' && args[1] === '--paginate' && args[2] === '--slurp') {
88
101
  const match = /^repos\\/([^/]+\\/[^/]+)\\/(issues|pulls)\\/(\\d+)\\/(comments\\?since=.+|reviews)$/.exec(args[3]);
89
102
  if (!match || (match[2] === 'issues' && match[4] === 'reviews')) process.exit(1);
@@ -102,4 +115,4 @@ if (list) {
102
115
  try { if (JSON.parse(value).fail) fail(); } catch {}
103
116
  console.log(value);
104
117
  }
105
- `,{mode:493}),r}t(J,"fakeGh");export{f as calls,J as fakeGh,E as prView,N as queried,k as tokens,R as writeAccounts,x as writeIssueComments,S as writeMerge,w as writePR,O as writeRate,_ as writeReady,v as writeReviewComments,b as writeReviews,j as writeUser};
118
+ `,{mode:493}),e}t(A,"fakeGh");export{f as calls,A as fakeGh,J as prView,q as queried,E as tokens,k as writeAccounts,N as writeCollaborators,O as writeGithubUser,v as writeIssueComments,_ as writeMerge,S as writeOpen,y as writePR,$ as writeRate,j as writeReady,x as writeReviewComments,b as writeReviews,R as writeUser};