@lovek4d/kickflip 0.5.3 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTEXT.md +82 -46
- package/SKILL.md +21 -15
- package/bin/doctor.mjs +5 -4
- package/bin/install.mjs +3 -3
- package/bin/kickflip.mjs +12 -12
- package/bin/wait-events.mjs +2 -2
- package/board/agents.mjs +2 -2
- package/board/arch-review.mjs +4 -4
- package/board/bin/board.mjs +179 -92
- package/board/build-script.mjs +2 -1
- package/board/domain.mjs +9 -7
- package/board/finish.mjs +4 -4
- package/board/headless.mjs +9 -5
- package/board/onboarding.mjs +11 -0
- package/board/prototype-base.mjs +1 -0
- package/board/prototype-page.mjs +1 -0
- package/board/public/app-arch.js +1 -1
- package/board/public/app-cards.js +40 -47
- package/board/public/app-header.js +6 -7
- package/board/public/app-lanes.js +19 -45
- package/board/public/app-needs.js +36 -31
- package/board/public/app-snapshot.js +43 -70
- package/board/public/app-threads.js +42 -46
- package/board/public/app.html +9 -4
- package/board/public/app.js +78 -32
- package/board/public/hub-kit.js +62 -2
- package/board/public/hub.css +2 -0
- package/board/public/new-task.js +8 -6
- package/board/public/progress-review.html +46 -0
- package/board/public/progress-review.js +158 -0
- package/board/public/prototype-kit.js +109 -4
- package/board/public/prototype-switcher.js +130 -31
- package/board/public/prototype.html +57 -3
- package/board/public/router.js +7 -6
- package/board/public/shell.js +65 -24
- package/board/public/sidebar.css +6 -0
- package/board/public/sidebar.js +19 -69
- package/board/public/style.css +116 -73
- package/board/public/ui-cards.js +78 -57
- package/board/public/ui-enums.js +2 -2
- package/board/public/ui-header.js +23 -16
- package/board/public/ui-hub.js +19 -5
- package/board/public/ui-links.js +7 -7
- package/board/public/ui-order.js +1 -1
- package/board/public/ui-page-header.js +19 -7
- package/board/public/ui-patch.js +7 -33
- package/board/public/ui-progress-bar.js +28 -0
- package/board/public/ui-questions.js +25 -17
- package/board/public/ui-sidebar.js +31 -23
- package/board/public/ui-snapshot.js +44 -53
- package/board/public/ui-threads.js +57 -28
- package/board/public/ui.js +94 -18
- package/board/public/view-hub-settings.js +12 -58
- package/board/public/view-hub.js +5 -2
- package/board/public/view-notes.js +27 -7
- package/board/public/view-questions.js +90 -68
- package/board/public/view-settings.js +133 -15
- package/board/render-check.mjs +10 -0
- package/board/review.mjs +1 -1
- package/board/server.mjs +20 -19
- package/board/stop.mjs +1 -0
- package/board/store.mjs +29 -18
- package/board/sync.mjs +2 -0
- package/board/tickets.mjs +3 -3
- package/board/transcript.mjs +2 -2
- package/board/worktree.mjs +22 -21
- package/hooks-plugin/hooks/board-data-gate.mjs +9 -6
- package/hooks-plugin/hooks/usage-gate.mjs +20 -3
- package/hub/board-repo.mjs +1 -1
- package/hub/boards.mjs +4 -4
- package/hub/front-door.mjs +2 -2
- package/hub/github.mjs +3 -3
- package/hub/hub.mjs +11 -11
- package/hub/incoming.mjs +2 -2
- package/hub/owner-checks.mjs +1 -1
- package/hub/pr-report.mjs +2 -2
- package/hub/review-send.mjs +1 -1
- package/hub/sessions.mjs +2 -2
- package/hub/share.mjs +1 -1
- package/hub/slack.mjs +2 -2
- package/hub/try.mjs +6 -6
- package/hub/upgrade.mjs +1 -1
- package/hub/usage.mjs +3 -3
- package/hub/views.mjs +1 -1
- package/package.json +1 -1
- package/shared/card-prs.mjs +1 -1
- package/shared/machine-gate.mjs +2 -0
- package/shared/prototype-frame.js +1 -0
- package/shared/tailscale.mjs +1 -1
- package/shared/usage-gate.mjs +1 -1
- package/board/public/ui-phase-bars.js +0 -17
package/hub/try.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,{mode:384}),O.chmodSync(m,384),m}
|
|
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(`
|
|
1
|
+
var se=Object.defineProperty;var a=(c,f)=>se(c,"name",{value:f,configurable:!0});import O from"node:fs";import T from"node:path";import Nt from"node:os";import mt from"node:http";import{execFile as ie,spawn as ne}from"node:child_process";import{createInterface as Dt}from"node:readline";import{promisify as oe}from"node:util";import{listBoards as U,readManifest as J,readJSON as nt,saveJSON as Bt,appendEvent as ae,GITHUB_STATE as ce,REPO_FETCH as Rt}from"./boards.mjs";import{boardRepo as et,githubFromOrigin as Ft,mainRefOf as le}from"./board-repo.mjs";import{gitReachFault as Ht,remoteFromInput as de,remoteGitEnv as ue}from"./repos.mjs";import{readiness as fe}from"./readiness.mjs";import{tailscaleBin as pe}from"../shared/tailscale.mjs";import{buildScriptError as he,buildScriptOf as Wt}from"../board/build-script.mjs";import{appendThread as me,recordedWorktree as we,servedRoundsOpen as ye,setItem as ge}from"../board/store.mjs";import{BASE_KEY as z,baseWorktreeOf as $e}from"../board/prototype-base.mjs";import{cardPRs as ve,hasPR as be,prKeyOf as Se}from"../shared/card-prs.mjs";import{hubGate as ke}from"../board/on-host.mjs";import{pipeUpgrade as Oe,refuse as Te,refuseUpgrade as Ee}from"./front-door.mjs";import{shareOf as xe}from"./share.mjs";class E extends Error{static{a(this,"BuildError")}constructor(f,h=400){super(f),this.status=h}}const wt=oe(ie),C=a(async(c,...f)=>(await wt("git",["-C",c,...f],{encoding:"utf8",timeout:3e3})).stdout.trim(),"git"),je=/errSecInternalComponent|keychain[^\n]*\blocked\b|\blocked\b[^\n]*keychain/i,Y={first:8500,last:8599},yt=a(c=>/^\d+$/.test(String(c))&&Number(c)>=Y.first&&Number(c)<=Y.last,"isTryPort"),_e=30*6e4,Gt=["tailscale-user-login","tailscale-user-name","tailscale-user-profile-pic","x-forwarded-for"],ct={main:"main",[z]:"prototypes"},F=a(c=>!Object.hasOwn(ct,c),"isCard"),Lt=a((c,f)=>T.join(c,Wt(f)),"scriptAt"),gt=a(c=>O.existsSync(c),"exists"),Kt=a((c,f)=>T.join(c.dir,"data","try",`${f.split("/").at(-1)}.log`),"logFileOf");function $t(c,f,h){const m=Kt(c,f);return O.mkdirSync(T.dirname(m),{recursive:!0}),O.writeFileSync(m,h.message+`
|
|
2
|
+
`,{mode:384}),O.chmodSync(m,384),m}a($t,"failureLog");const Ie=a(c=>new Promise(f=>{const h=mt.get({host:"127.0.0.1",port:c,path:"/",timeout:1e3},m=>{m.destroy(),f(!0)});h.on("timeout",()=>h.destroy()),h.on("error",()=>f(!1))}),"probe"),Ut=a((c,f)=>{try{process.kill(-c.pid,f)}catch{}},"signalGroup");async function Jt(c,f,h){const m=await we(c.dir,f),[S,p]=f.split("/"),k=c.waves.find(b=>b.slug===S)?.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 $=(c.github||k?.repo||"").toLowerCase();if(!g&&$){const b=[c.owner?.repo,c.dir,...Object.values(h?.sites||{}).map(_=>_.owner?.repo)];for(const _ of new Set(b.filter(P=>typeof P=="string"&&T.isAbsolute(P))))try{if(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(await C(_,"remote","get-url","origin"))?.[1].toLowerCase()===$){g=await C(_,"rev-parse","--show-toplevel");break}}catch{}}if(!m?.path&&!g||m?.path&&!T.isAbsolute(u))return"";try{const b=[T.join(O.realpathSync(Nt.homedir()),".claude","kickflip","worktrees")];if(typeof g=="string"&&T.isAbsolute(g))try{b.push(T.join(O.realpathSync(g),".claude","worktrees"))}catch{}const _=T.resolve(g||"/",u),P=O.realpathSync(_);return b.some(W=>_.startsWith(W+T.sep)&&P.startsWith(W+T.sep))&&O.statSync(P).isDirectory()?P:""}catch{return""}}a(Jt,"installWorktree");function Ce({now:c=Date.now,answers:f=Ie,log:h=console.log,waiting:m=a(async()=>null,"waiting"),event:S=ae,gate:p=ke}={}){const k=new Map,u=new Map,g=new Set,$=new Set,b=new Map,_=new Map,P=new Map,W=new Map;let G=!1,H=null,Q=null,ot=null;const lt=a(()=>new Date(c()).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=nt(e,{kind:null,main:null,cards:{}}),i={...yt(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}}:{}},s={state:i,file:e,written:JSON.stringify(r)};k.set(t.dir,s),i.main_port&&_.set(t.dir,i.main_port);const n=Object.entries(i.cards).filter(([,o])=>o.state==="running");for(const[o]of n)$.add(D(t,o));return i.kind==="web"?(i.cards=Object.fromEntries(n),i.main&&i.main.state!=="failed"&&(delete i.main.state,delete i.main.port,delete i.main.https)):i.main?.state==="running"&&(delete i.main.state,delete i.main.sha),r.prototypes?.state==="failed"&&(i.prototypes=r.prototypes),M(t),s}a(N,"stateOf");function M(t){const e=k.get(t.dir),r=JSON.stringify(e.state);r!==e.written&&(Bt(e.file,e.state),e.written=r)}a(M,"persist");const D=a((t,e)=>`${t.dir}\0${e}`,"runKey"),St=a((t,e)=>F(e)?t.cards[e]:t[ct[e]],"entryOf"),zt=a((t,e,r)=>{F(e)?t.cards[e]=r:t[ct[e]]=r},"setEntry"),kt=a((t,e)=>{F(e)?delete t.cards[e]:t[ct[e]]=null},"dropEntry");function X(t,e,r){const{state:i}=N(t),s=St(i,e);if(!s)return;const n=Object.hasOwn(r,"state")&&r.state!==s.state;Object.assign(s,r,F(e)&&n?{at:lt()}:{}),M(t)}a(X,"update");function dt(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 i=nt(T.join(r.dir,"data","try.json"),{}).main_port;yt(i)&&_.set(r.dir,Number(i))}}a(dt,"reserveMains");function Yt(t){const{board:e,key:r}=t,i=D(e,r),s=r==="main"?_.get(e.dir):b.get(i);if(s)return s;const n=new Set([..._.values(),...b.values()]);let o=Y.first;for(;n.has(o)&&o<=Y.last;)o++;if(o>Y.last)throw new Error(`No try ports available (${Y.first}\u2013${Y.last}). Stop a served card and retry.`);return r==="main"?(_.set(e.dir,o),N(e).state.main_port=o,M(e)):b.set(i,o),o}a(Yt,"publicPort");const rt=a(async t=>{const e=pe();if(!e)throw new Error("Tailscale isn't installed on this host");return wt(e,t,{encoding:"utf8",timeout:1e4})},"tailscale");async function Ot(t){try{await rt(["serve",`--https=${t}`,"off"])}catch(e){h(`try port ${t}: could not close port: ${(e.stderr||e.message).trim()}`)}}a(Ot,"removePort");const Tt=a(t=>xe(nt(T.join(t.dir,"board.json"),{})),"sharedWith");async function Et(t,e){const r=await p(t),i=t.headers["tailscale-user-login"];return r!=="other"||!i||!Tt(e).includes(i)?r:t.method==="GET"||t.method==="HEAD"?"shared":"view-only"}a(Et,"relayVerdict");function Vt(){for(const t of u.values()){if(!t.shared?.size)continue;const e=Tt(t.board);for(const r of t.shared)e.includes(r.login)||(t.shared.delete(r),r.res.destroy())}}a(Vt,"endUnshared");async function Qt(t){t.https=Yt(t);const e=t.sockets=new Set,r=a(()=>{t.visited=c()},"visit"),i=a(n=>{e.add(n),n.on("data",r),n.on("close",()=>e.delete(n))},"track"),s=t.shared=new Set;if(t.relay=mt.createServer(async(n,o)=>{const w=await Et(n,t.board);if(w!=="owner"&&w!=="shared"){Te(n,o,w);return}if(w==="shared"){const y={login:n.headers["tailscale-user-login"],res:o};s.add(y),o.on("close",()=>s.delete(y))}const x=Object.fromEntries(Object.entries(n.headers).filter(([y])=>!Gt.includes(y))),d=mt.request({host:"127.0.0.1",port:t.port,method:n.method,path:n.url,headers:x},y=>{o.writeHead(y.statusCode,y.headers),y.on("data",r),y.pipe(o),y.on("close",()=>{y.complete||o.destroy()})});o.on("close",()=>{o.writableFinished||d.destroy()}),d.on("error",()=>{o.headersSent?o.destroy():o.writeHead(502).end()}),n.pipe(d)}),t.relay.on("connection",n=>{r(),i(n)}),t.relay.on("upgrade",async(n,o,w)=>{const x=await Et(n,t.board);if(x!=="owner"){Ee(o,x==="shared"?"view-only":x);return}i(Oe({req:n,socket:o,head:w,port:t.port,path:n.url,replace:Gt}))}),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 rt(["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()}`)}}}a(Qt,"openPort");async function Xt(t){if(t.closing=!0,await t.opening?.catch(()=>{}),t.exposed&&!G&&await Ot(t.https),t.relay){for(const e of t.sockets)e.destroy();await new Promise(e=>t.relay.close(e))}t.keepPort||b.delete(D(t.board,t.key))}a(Xt,"closePort");async function Zt(){const t=[...u.values()].filter(r=>r.ready&&r.relay&&!r.closing);if(!t.length)return;let e;try{e=JSON.parse((await rt(["serve","status","--json"])).stdout)}catch(r){h(`try ports check: ${(r.stderr||r.message).trim()}`);return}for(const r of t){const i=`http://127.0.0.1:${r.relay.address().port}`,s=Object.entries(e?.Web||{}).find(([n])=>n.endsWith(`:${r.https}`))?.[1];if(s?.Handlers?.["/"]?.Proxy!==i){h(`try port ${r.https}: its serve mapping was ${s?"changed":"gone"}; serving it again`);try{await rt(["serve","--bg",`--https=${r.https}`,i])}catch(n){h(`try port ${r.https}: could not serve it again: ${(n.stderr||n.message).trim()}`)}}}}a(Zt,"reserve");function st(t=J()){if(ot)return ot;dt(t);for(const e of U(t))N(e);return ot=(async()=>{try{const{stdout:e}=await rt(["serve","status","--json"]),r=JSON.parse(e);for(const i of Object.keys(r?.TCP||{}))yt(i)&&![...u.values()].some(s=>s.https===Number(i))&&await Ot(i)}catch(e){h(`try startup cleanup: ${(e.stderr||e.message).trim()}`)}})(),ot}a(st,"initialize");async function xt(t,e,r,i){const{board:s,key:n}=t;if(X(s,n,{state:"failed",port:void 0,https:void 0}),!F(n))return;const o=[];let w=!1;try{for await(const d of Dt({input:O.createReadStream(t.logFile),crlfDelay:1/0}))w||=je.test(d),o.push(d),o.length>5&&o.shift()}catch(d){o.push(`Could not read the build log: ${d.message}`)}const x=t.port||(N(s).state.kind||(s.waves.some(({wave:d})=>d.items.some(y=>y.install?.url))?"app":"web"))==="web"?"Serve":"Build";await me(s.dir,n,{text:[`${x} failed (exit ${e??1})`,i?.message,r&&`Stopped by ${r}.`,w&&"The login keychain must be unlocked on the host.",...o].filter(Boolean).join(`
|
|
3
|
+
`)})}a(xt,"failure");function at(t){return t.ending||(Ut(t.child,"SIGTERM"),t.ending=new Promise(e=>{const r=a(()=>{clearTimeout(i),clearInterval(s),e()},"finish");let i=setTimeout(()=>{Ut(t.child,"SIGKILL"),i=setTimeout(r,1e3)},4e3);const s=setInterval(()=>{try{process.kill(-t.child.pid,0)}catch{r()}},20)})),t.ending}a(at,"terminate");async function jt(t,e=!1){t.keepPort=e,t.stopped=!0,clearTimeout(t.deadline),clearInterval(t.poll),await at(t),await t.done}a(jt,"halt");async function Z(t,e=!1){await jt(t,e),X(t.board,t.key,{state:void 0,port:void 0,https:void 0,...t.ready?{}:{sha:void 0}}),t.ready||P.delete(D(t.board,t.key))}a(Z,"stopRun");async function _t(t,e,r,i={}){if(!r)throw new E("This card has no valid worktree.");const s=Lt(r,t.build_target),n=he(s);if(n)throw new E(n);if(!O.realpathSync(s).startsWith(O.realpathSync(r)+T.sep))throw new E("Build script must be inside the worktree.");const o=await C(r,"rev-parse","HEAD");if(G)throw new E("The hub is stopping. Try again after it restarts.",503);const{state:w}=N(t),x=St(w,e),d={...F(e)?x:{},...i,sha:o,script:!0,state:"running",...F(e)?{at:lt(),head:o}:{}};delete d.port,delete d.https;const y=Kt(t,e);O.mkdirSync(T.dirname(y),{recursive:!0});const j=O.openSync(y,"w",384);O.fchmodSync(j,384);const v=ne(s,[e,r],{cwd:r,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,KICKFLIP_BOARD:t.route,HOST:"127.0.0.1"}});zt(w,e,d),M(t);const B=D(t,e),l={child:v,board:t,key:e,logFile:y,visited:c(),stopped:!1,port:null,ready:!1};u.set(B,l),P.set(B,o);let R,I;const q=a(A=>{I||=new Error(A),at(l)},"fail");v.on("error",A=>{R=A}),v.stdout.on("data",A=>O.writeSync(j,A)),v.stderr.on("data",A=>O.writeSync(j,A));const L=Dt({input:v.stdout,crlfDelay:1/0});return L.on("line",A=>{const it=/^port (\d{1,5})$/.exec(A);if(!it||l.port||l.stopped)return;const K=Number(it[1]);if(K<1||K>65535){q("Build script printed an invalid port.");return}l.port=K,clearTimeout(l.deadline);const tt=c()+6e4;let pt=!1;const Mt=a(async()=>{if(!(pt||l.stopped||l.ready||v.exitCode!==null||v.signalCode!==null)){pt=!0;try{if(await f(K)){if(l.stopped||I||v.exitCode!==null||v.signalCode!==null||(l.opening=Qt(l),await l.opening,l.stopped||I||v.exitCode!==null||v.signalCode!==null))return;l.ready=!0,l.visited=c(),w.kind="web",X(t,e,{state:"ready",port:K,https:l.https}),clearInterval(l.poll)}else c()>=tt&&q("Nothing answered on the build script\u2019s port within 60 seconds.")}finally{pt=!1}}},"check");l.poll=setInterval(()=>Mt().catch(ht=>q(ht.message)),250),Mt().catch(ht=>q(ht.message))}),l.deadline=setTimeout(()=>q("No port line within 60 minutes."),60*6e4),v.once("exit",()=>{at(l)}),l.done=new Promise(A=>v.once("close",(it,K)=>{clearTimeout(l.deadline),clearInterval(l.poll),L.close(),O.closeSync(j),(async()=>{if(await at(l),await Xt(l),l.finished=!0,l.stopped)return;const tt=e===z&&!l.port?new Error('Build script exited without printing "port <n>".'):null;I||R||it!==0||l.port&&!l.ready||tt?await xt(l,it??1,K,I||R||(l.port&&!l.ready?new Error("Build script exited before its port answered."):tt)):l.ready?(e==="main"?(delete w.main.state,delete w.main.port,delete w.main.https):kt(w,e),M(t)):(w.kind="app",X(t,e,{state:"ready"}))})().catch(tt=>h(`build /${t.route} ${e}: ${tt.message}`)).finally(()=>{u.get(B)===l&&u.delete(B),A()})})),h(`build /${t.route} ${e}: started; log ${y}`),{status:"started"}}a(_t,"launch");async function It(t,e,r){const i=D(t,"main");if(g.has(i))throw new E("A build is already running for main.",409);g.add(i);try{u.has(i)&&await Z(u.get(i),!0);const s=T.join(Nt.homedir(),".claude","kickflip","try",`${t.route}-main`);return O.mkdirSync(T.dirname(s),{recursive:!0}),gt(s)?await C(s,"checkout","--detach","--force",r.sha):(await C(e,"worktree","prune"),await C(e,"worktree","add","--detach",s,r.sha)),await _t(t,"main",s,r)}catch(s){throw s.status!==503&&(N(t).state.main={...r,state:"failed"},$t(t,"main",s),M(t)),s}finally{g.delete(i)}}a(It,"launchMain");async function ut(t,{manifest:e=J()}={}){if(await st(e),dt(e),G)throw new E("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 E("Send only the board route and card key.");const{route:r,key:i}=t;if(F(i)&&(!/^[\w.-]+\/[\w.-]+$/.test(i)||i.split("/").some(d=>d==="."||d==="..")))throw new E("Card key must be <wave>/<id>.");const s=U(e).find(d=>d.route===r);if(!s)throw new E(`/${r} is not a board.`,404);if(F(i)&&!s.waves.some(({slug:d,wave:y})=>y.items.some(j=>`${d}/${j.id}`===i)))throw new E("There is no item with this card key.",404);const n=await m();if(n)throw new E(n,409);const o=D(s,i),w=u.get(o);if(g.has(o)||w&&!w.ready&&!w.finished)throw new E(`A build is already running for ${i==="main"?"main":i===z?"the prototype site":"this card"}.`,409);if(i==="main"){const d=N(s).state.main;if(d?.state==="running")throw new E("A build is already running for main.",409);if(d?.state!=="failed"||!d.sha)throw new E("Main has no failed build to retry.",409);const{sha:y,branch:j,slug:v,at:B,script:l}=d;return It(s,et(r,e).repo,{sha:y,branch:j,slug:v,at:B,script:l,...s.build_target?{target:s.build_target}:{}})}g.add(o);const x=$.delete(o);try{u.has(o)&&await Z(u.get(o),!0);const d=i===z?Ct(s):await Jt(s,i,e);return await _t(s,i,d)}catch(d){throw b.delete(o),x&&d.status!==503&&X(s,i,{state:void 0,sha:void 0}),d}finally{g.delete(o)}}a(ut,"start");const Ct=a(t=>{const e=$e(t.route);return gt(e)&&O.statSync(e).isDirectory()?O.realpathSync(e):""},"baseWorktree");async function qt(t,e){const{state:r}=N(t),i=D(t,z),s=u.get(i);if(!((await ye(t.dir)).length>0&&Ct(t))){s&&await Z(s),r.prototypes&&(r.prototypes=null,M(t));return}if(!(s||g.has(i)||r.prototypes?.state==="failed"||await m()))try{await ut({route:t.route,key:z},{manifest:e})}catch(o){if([409,503].includes(o.status))return;throw r.prototypes={state:"failed"},$t(t,z,o),M(t),o}}a(qt,"serveBase");function Pt(t,e,{manifest:r=J()}={}){const i=U(r).find(n=>n.route===t);if(!i)return null;const s=[...u.values()].find(n=>n.board.dir===i.dir&&n.key.split("/").at(-1).toLowerCase()===e.toLowerCase()&&n.ready&&!n.stopped&&n.child.exitCode===null&&n.child.signalCode===null);return s?{key:s.key,port:s.port}:null}a(Pt,"lookup");async function ft({manifest:t=J(),routes:e}={}){if(await st(t),dt(t),G)return H;if(H&&e){if(!Q){const r={routes:new Set,manifest:t};r.done=H.catch(()=>{}).then(()=>(Q=null,ft({manifest:r.manifest,routes:[...r.routes]}))),Q=r}Q.manifest=t;for(const r of e)Q.routes.add(r);return Q.done}return H||(H=(async()=>{await Zt();const r=U(t),i=nt(ce,{}).prs||{};for(const s of[...u.values()])if(!r.some(n=>n.dir===s.board.dir)||F(s.key)&&s.ready&&c()-s.visited>=_e){await Z(s);const{state:n}=N(s.board);kt(n,s.key),M(s.board)}for(const s of r){if(G)return;if(e&&!e.includes(s.route))continue;const{state:n}=N(s),o=et(s.route,t),w=o.branch||"main",x=le(o);for(const{slug:d,wave:y}of s.waves)for(const j of y.items){const v=`${d}/${j.id}`,B=ve(j,s.github||y.repo).map(l=>i[Se(l)]);if(!(j.lane==="done"||B.length&&B.every(l=>["MERGED","CLOSED"].includes(l?.state))))try{const l=D(s,v),R=await Jt(s,v,t);if(R){const L=await C(R,"rev-parse","HEAD");let A=0;try{A=Number(await C(R,"rev-list","--count",`${x}..HEAD`))}catch{}Object.assign(n.cards[v]||={},{head:L,ahead:A,script:gt(Lt(R,s.build_target))}),M(s)}else if(!$.has(l))continue;const I=n.cards[v];if(($.has(l)||s.auto_build&&I.script&&I.ahead>0&&(I.sha||P.get(l))!==I.head&&I.state!=="running")&&!g.has(l))try{await ut({route:s.route,key:v},{manifest:t})}catch(L){if([409,503].includes(L.status))continue;throw X(s,v,{sha:I.head}),await xt({board:s,key:v,logFile:$t(s,v,L)},1),L}}catch(l){h(`try /${s.route} ${v}: ${l.message}`)}}await qt(s,t).catch(d=>h(`try /${s.route} prototypes: ${d.message}`));try{if(!o.repo||await m())continue;const d=await C(o.repo,"rev-parse",x);let y=!1;try{await C(o.repo,"cat-file","-e",`${d}:${Wt(s.build_target)}`),y=!0}catch{}if(!y){const I=u.get(D(s,"main"));I&&await Z(I),n.main=null,M(s);continue}const j=n.main;if(j?.state==="running"||j?.sha===d&&(j.target||null)===(s.build_target||null)&&(j.state==="failed"||j.state==="ready"&&(n.kind!=="web"||Pt(s.route,"main",{manifest:t}))))continue;const v=D(s,"main");if(g.has(v))continue;const B=await C(o.repo,"log","-1","--format=%cI",d);let l=s.github;if(!l)try{l=Ft(await C(o.repo,"remote","get-url","origin"))}catch{}const R={sha:d,branch:w,slug:l||"",at:B,script:y,...s.build_target?{target:s.build_target}:{}};await It(s,o.repo,R)}catch(d){h(`try /${s.route} main: ${d.message}`)}}})().finally(()=>{H=null}),H)}a(ft,"tick");function At(t,e){if(W.has(t.dir))return W.get(t.dir);const r=(async()=>{const i=et(t.route,e),s=i.branch||"main",{state:n}=N(t);n.pull={...n.pull,running:!0},M(t);let o,w;try{o=await Pe(i.repo,s)}catch(x){w=x.message}if(o===null?delete n.pull:n.pull={at:lt(),...w?{error:w}:{}},M(t),o===null)return null;if(w)return h(`pull /${t.route}: ${w}`),{commits:0,error:w};if(o.commits){h(`pull /${t.route}: ${s} fast-forwarded ${o.commits} commit${o.commits===1?"":"s"} to ${o.to.slice(0,7)}`);try{await S(t,"main-pulled",{branch:s,...o})}catch(x){h(`pull /${t.route}: could not send main-pulled (${x.message})`)}}return{commits:o.commits}})().finally(()=>W.delete(t.dir));return W.set(t.dir,r),r}a(At,"pullMain");async function te({manifest:t=J(),routes:e}={}){await st(t);const r=[];for(const i of U(t)){if(G)break;if(e&&!e.includes(i.route))continue;const s=et(i.route,t);!s.local||!s.repo||(await At(i,t))?.commits&&r.push(i.route)}return r}a(te,"pullMains");async function ee(t,{manifest:e=J()}={}){if(await st(e),G)throw new E("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 E("Send only the board route.");const r=U(e).find(n=>n.route===t.route);if(!r)throw new E(`/${t.route} is not a board.`,404);const i=et(r.route,e);if(!i.local||!i.repo)throw new E("This board fetches its branch on every poll; only a local board pulls.",409);const s=await At(r,e);if(!s)throw new E("This board\u2019s folder has no origin to pull from.",409);return s.commits&&ft({manifest:e,routes:[r.route]}).catch(n=>h(`try /${r.route} main: ${n.message}`)),s}a(ee,"pull");async function re(){G=!0;const t=Promise.all([...u.values()].map(e=>e.ready?Z(e):jt(e)));await Promise.all([t,H,...W.values()])}return a(re,"stop"),{start:ut,tick:ft,stop:re,lookup:Pt,initialize:st,pull:ee,pullMains:te,endUnshared:Vt}}a(Ce,"createTryManager");const vt=1e4,bt=a(async(c,...f)=>(await wt("git",["-C",c,...f],{encoding:"utf8",timeout:vt,env:ue()})).stdout,"originGit");async function Pe(c,f,{run:h=bt}={}){const m=a(async(...p)=>(await h(...p)).trim(),"git"),S=a(p=>{throw new Error(`can\u2019t pull: ${p}`)},"refuse");try{await m(c,"config","--get","remote.origin.url")}catch{return null}try{await m(c,"fetch","--quiet","--no-tags","origin",`+refs/heads/${f}:refs/remotes/origin/${f}`)}catch(p){S(p.killed?`git fetch timed out after ${vt/1e3} s`:Ht(p.stderr,{repo:c}).error)}try{const p=await m(c,"rev-parse","--verify",`refs/heads/${f}^{commit}`),k=await m(c,"rev-parse","--verify",`refs/remotes/origin/${f}^{commit}`),u=a((b,_)=>m(c,"merge-base","--is-ancestor",b,_).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)||S(`${f} has split from origin`);const g=Number(await m(c,"rev-list","--count",`${p}..${k}`)),$=(await m(c,"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
|
|
7
|
-
`).at(-1))}}
|
|
8
|
-
`).map(u=>/^([\da-f]+)\trefs\/heads\/(.+)$/.exec(u)).filter(Boolean).map(u=>[u[2],u[1]])),k=
|
|
6
|
+
`)).find(b=>b.includes(`branch refs/heads/${f}`))?.[0].slice(9);return $?(await m($,"status","--porcelain","--untracked-files=no")&&S("local changes"),await m($,"merge","--ff-only","--quiet",k)):await m(c,"update-ref",`refs/heads/${f}`,k,p),{from:p,to:k,commits:g}}catch(p){if(p.message.startsWith("can\u2019t pull: "))throw p;S(String(p.stderr||p.message).trim().split(`
|
|
7
|
+
`).at(-1))}}a(Pe,"pullBranch");async function tr({manifest:c=J(),log:f=console.log,routes:h}={}){const m=h?nt(Rt,{}):{};for(const S of U(c)){if(h&&!h.includes(S.route))continue;const p=et(S.route,c);if(p.local||!p.repo)continue;const k=p.branch||"main",u=new Date().toISOString(),g=Date.now();try{await bt(p.repo,"fetch","--quiet","--no-tags","origin",`+refs/heads/${k}:refs/remotes/origin/${k}`),m[S.route]={at:u,ok:!0}}catch($){f(`fetch /${S.route} after ${Date.now()-g} ms: ${$.message}`);let b=S.github;if(!b&&!S.remote)try{b=Ft(await C(p.repo,"remote","get-url","origin"))}catch{}m[S.route]={at:u,ok:!1,...Ht($.killed?`git fetch timed out after ${vt/1e3} s`:$.stderr,{github:b||"",remote:S.remote,repo:p.repo})};continue}if(S.remote)try{await Ae(S,p.repo,k,f)}catch($){f(`pushed branches /${S.route}: ${$.message}`)}}Bt(Rt,m)}a(tr,"fetchTryBranches");async function Ae(c,f,h,m){const S=c.waves.flatMap(({slug:u,wave:g})=>g.items.filter($=>$.pushed?.branch&&!be($)&&$.lane!=="done").map($=>({key:`${u}/${$.id}`,branch:$.pushed.branch})));if(!S.length)return;const p=new Map((await bt(f,"ls-remote","--heads","origin")).split(`
|
|
8
|
+
`).map(u=>/^([\da-f]+)\trefs\/heads\/(.+)$/.exec(u)).filter(Boolean).map(u=>[u[2],u[1]])),k=de(c.remote)?.host||"the remote";for(const u of S){let g=p.get(u.branch);if(!g)try{g=await C(f,"rev-parse","--verify","--quiet",`refs/heads/${u.branch}^{commit}`)}catch{}let $=!1;if(g)try{await C(f,"merge-base","--is-ancestor",g,`refs/remotes/origin/${h}`),$=!0}catch{}if(!(!$&&p.has(u.branch)))try{await ge(c.dir,u.key,{done:!0,force:!0,text:$?`${u.branch} is merged into ${h} 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}`)}}}a(Ae,"settlePushed");const V=Ce({waiting:a(()=>fe.waiting("tailscale"),"waiting")}),er=a((...c)=>V.start(...c),"startBuild"),rr=a((...c)=>V.tick(...c),"tryTick"),sr=a((...c)=>V.pull(...c),"pullNow"),ir=a((...c)=>V.pullMains(...c),"pullMains"),nr=a(()=>V.stop(),"stopTries"),or=a(()=>V.endUnshared(),"endUnsharedTries"),ar=a((...c)=>V.initialize(...c),"initializeTries");export{E as BuildError,Y as TRY_PORTS,Ce as createTryManager,or as endUnsharedTries,tr as fetchTryBranches,ar as initializeTries,Jt as installWorktree,yt as isTryPort,Pe as pullBranch,ir as pullMains,sr as pullNow,er as startBuild,nr as stopTries,rr as tryTick};
|
package/hub/upgrade.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var t=(e,i)=>d(e,"name",{value:i,configurable:!0});import c from"node:fs";import f from"node:path";const h="https://registry.npmjs.org/@lovek4d%2Fkickflip/latest",j=60*6e4,p=t(e=>String(e).split("-")[0].split(".").map(Number),"parts");function y(e,i){const[a,s]=[p(e),p(i)];for(let n=0;n<3;n++)if((a[n]||0)!==(s[n]||0))return(a[n]||0)>(s[n]||0);return!1}t(y,"newer");function _({root:e,fetch:i=globalThis.fetch,run:a,log:s=t(()=>{},"log"),pulled:n=t(()=>{},"pulled")}){const u=c.existsSync(f.join(e,".git"));let l=!1;const g=t(()=>JSON.parse(c.readFileSync(f.join(e,"package.json"),"utf8")).version,"installed");async function k(){if(u)return;let r;try{const o=await i(h,{signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new Error(`npm answered ${o.status}`);r=(await o.json()).version}catch(o){s(`kickflip update check failed: ${o.message}`);return}y(r,g())&&m()}t(k,"check");function m(){l||(l=!0,a().then(({ok:r})=>{r&&n()},r=>s(`kickflip update failed: ${r.message}`)).finally(()=>{l=!1}))}return t(m,"pull"),{check:k}}t(_,"upgrader");export{j as CHECK_MS,h as LATEST_URL,y as newer,_ as upgrader};
|
package/hub/usage.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);
|
|
3
|
-
`),
|
|
1
|
+
var k=Object.defineProperty;var u=(e,t)=>k(e,"name",{value:t,configurable:!0});import d from"node:fs";import w from"node:os";import f from"node:path";import{audit as v,hubAudit as D}from"../shared/audit.mjs";import{FOREVER as M}from"./duration.mjs";const b=6,L=12,$=180,I={five_hour:5*36e5,seven_day:7*864e5},S=u(e=>{try{return JSON.parse(d.readFileSync(e,"utf8"))}catch{return null}},"readJson"),_=u(e=>e==null||e===""||!Number.isFinite(Number(e))?null:Number(e),"num"),y=u(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"),h=u((e,t)=>({used_percentage:_(e),resets_at:y(t)}),"win");function x(e,t,n){let s;try{s=d.openSync(e,"r");const r=d.fstatSync(s).size;for(const o of[256*1024,2*1024*1024]){const a=Math.max(0,r-o),c=Buffer.alloc(r-a);d.readSync(s,c,0,c.length,a);const m=c.toString("utf8").split(`
|
|
2
|
+
`);a>0&&m.shift();for(let i=m.length-1;i>=0;i--)if(m[i].includes(t))try{const l=n(JSON.parse(m[i]));if(l)return l}catch{}if(a===0)break}}catch{}finally{if(s!==void 0)try{d.closeSync(s)}catch{}}return null}u(x,"lastMatch");const z=u(e=>x(e,"rate_limits",t=>{const n=t?.payload?.rate_limits??t?.rate_limits;return n?.primary?{rl:n}:null}),"lastRateLimits"),O=u(e=>x(e,'"rate_limit_event"',t=>t?.type==="rate_limit_event"&&t.rate_limit_info?t.rate_limit_info:null),"lastRateLimitEvent");function A(e){const t=u(n=>{const s=e.unifiedWindows?.[n];if(!s||_(s.utilization)==null)return null;const r=s.status==="rejected"||e.status==="rejected"&&e.rateLimitType===n;return h(r?100:Math.round(_(s.utilization)*1e3)/10,s.resetsAt)},"window");return{five_hour:t("five_hour"),seven_day:t("seven_day")}}u(A,"eventWindows");function q(e,t=Date.now()){const n=O(e);if(n?.status!=="rejected")return null;const s=Object.values(n.unifiedWindows||{}).find(o=>o?.status==="rejected"),r=y(s?.resetsAt??n.resetsAt);return r&&Date.parse(r)>t?r:null}u(q,"runLimit");const R=/-(\d{4}-\d\d-\d\dT\d\d)-(\d\d)-(\d\d)-(\d{3})Z\.log$/;function E(e,t){let n;try{n=d.readdirSync(e)}catch{return[]}const s=[];for(const r of n){const o=r.match(R);if(o)try{const a=d.statSync(f.join(e,r));s.push({file:f.join(e,r),started:`${o[1]}:${o[2]}:${o[3]}.${o[4]}Z`,mtime:a.mtimeMs,size:a.size})}catch{}}return s.sort((r,o)=>o.mtime-r.mtime).slice(0,L).map(r=>{const o=`${r.size}:${r.mtime}`;let a=t.get(r.file);if(a?.key!==o){const c=r.size?O(r.file):null;a={key:o,claude:r.size>0&&F(r.file)==="{",windows:c?A(c):null},t.set(r.file,a)}return{...r,claude:a.claude,windows:a.windows}})}u(E,"runLogs");function F(e){let t;try{t=d.openSync(e,"r");const n=Buffer.alloc(1);return d.readSync(t,n,0,1,0),n.toString()}catch{return null}finally{if(t!==void 0)try{d.closeSync(t)}catch{}}}u(F,"firstByte");function C(e,t){const n=t.filter(o=>o.windows).map(o=>({at:new Date(o.mtime).toISOString(),...o.windows}));if(e&&typeof e=="object"&&!Array.isArray(e)&&n.push(e),!n.length)return null;const s=u(o=>{const a=n.map(i=>i[o]&&h(i[o].used_percentage,i[o].resets_at)).filter(i=>i?.used_percentage!=null),c=Math.max(...a.map(i=>i.resets_at?Date.parse(i.resets_at):-1/0));return a.filter(i=>i.resets_at?Math.abs(Date.parse(i.resets_at)-c)<=$*1e3:c===-1/0).reduce((i,l)=>!i||l.used_percentage>i.used_percentage?l:i,null)},"window");return{at:n.map(o=>y(o.at)).filter(Boolean).sort().at(-1)??null,five_hour:s("five_hour"),seven_day:s("seven_day")}}u(C,"claudeReading");function T(e,t){const n=e.filter(s=>s.claude).sort((s,r)=>r.started.localeCompare(s.started))[0];return n?{at:n.started,reported:!!n.windows||!!(t&&Date.parse(t)>Date.parse(n.started))}:null}u(T,"newestStart");function W(e){const t=[],n=u(s=>{try{return d.readdirSync(s).sort().reverse()}catch{return[]}},"kids");e:for(const s of n(e))for(const r of n(f.join(e,s)))for(const o of n(f.join(e,s,r))){const a=f.join(e,s,r,o);for(const c of n(a))if(/^rollout-.*\.jsonl$/.test(c))try{t.push({file:f.join(a,c),mtime:d.statSync(f.join(a,c)).mtimeMs})}catch{}if(t.length>=b*2)break e}return t.sort((s,r)=>r.mtime-s.mtime).slice(0,b)}u(W,"newestRollouts");function B(e){const t=[];for(const{file:i,mtime:l}of W(e)){const p=z(i);p&&t.push({...p,mtime:l,resets:_(p.rl.primary.resets_at)})}if(!t.length)return null;const n=Math.max(...t.map(i=>i.resets??-1/0)),s=t.filter(i=>i.resets!=null&&Math.abs(i.resets-n)<=$),r=u(i=>s.reduce((l,p)=>(_(p.rl[i]?.used_percent)??-1)>(_(l?.rl[i]?.used_percent)??-1)?p:l,null),"pick");if(!s.length)return null;const o=r("primary"),a=r("secondary"),c=s.reduce((i,l)=>l.mtime>i.mtime?l:i),m=u((i,l)=>i?h(i.rl[l].used_percent,i.rl[l].resets_at):null,"w");return{five_hour:m(o,"primary"),seven_day:m(a,"secondary"),at:new Date(c.mtime).toISOString()}}u(B,"scanCodex");function N(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=y(e.at),s=u(r=>{const o=e[r];if(!o)return null;const a=h(o.used_percentage,o.resets_at);if(a.used_percentage==null)return null;const c=!n||t-Date.parse(n)>I[r]?"stale":a.resets_at&&t>=Date.parse(a.resets_at)?"reset":"live";return{...a,used_percentage:c==="reset"?0:a.used_percentage,state:c}},"window");return{at:n,five_hour:s("five_hour"),seven_day:s("seven_day")}}u(N,"readingOf");function H({home:e=w.homedir(),now:t=Date.now,cacheMs:n=6e4}={}){const s=f.join(e,".codex","sessions"),r=f.join(e,".claude","kickflip","logs"),o=new Map;let a=null,c=-1/0;return({codexShare:m="off"}={})=>{const i=t(),l=S(f.join(e,".claude","kickflip","usage.json"))?.claude,p=E(r,o),g=N(C(l,p),i),j=T(p,y(l?.at));return m==="off"?{claude:g,codex:null,start:j}:(i-c>=n&&(a=B(s),c=i),{claude:g,codex:N(a||{at:null},i),start:j})}}u(H,"usageReader");const J=95,K=u((e,t)=>e==="deaf"&&t?.percent>=J,"contextFull");function Q(e,{home:t=w.homedir()}={}){if(typeof e!="string"||!/^[\w-]+$/.test(e))return null;const n=S(f.join(t,".claude","kickflip","context",`${e}.json`));return _(n?.percent)==null||!n.at?null:{percent:_(n.percent),at:n.at}}u(Q,"contextReading");async function Y({gate:e,home:t=w.homedir(),resume:n}){const s=f.join(t,".claude","kickflip","usage-gate-state.json"),r=S(s);if(e.state==="paused"&&r?.state!=="paused"){const a=e.manual?`The owner paused the hub ${e.resets_at===M?"until they resume it":`until ${e.resets_at}`}.`:`Claude's ${e.window==="five_hour"?"5-hour":"weekly"} usage reached the ${e.pause_at}% line.`;v(D(t),{call:"usage-pause",result:"paused",reason:a,inputs:{gate:e,previous:r?.state??null}})}if(r?.state==="paused"&&e.state==="normal"){const a=r.manual?"The owner's pause of the hub ended, so every board was told.":`Claude's ${r.window==="five_hour"?"5-hour":"weekly"} usage is under the line again, so every board was told.`;v(D(t),{call:"usage-resume",result:"resumed",reason:a,inputs:{gate:e,previous:r.manual?"manual":r.window}}),await n(r.manual?"manual":r.window)}d.mkdirSync(f.dirname(s),{recursive:!0});const o=`${s}.${process.pid}.tmp`;d.writeFileSync(o,JSON.stringify(e)+`
|
|
3
|
+
`),d.renameSync(o,s)}u(Y,"checkUsagePause");export{J as CONTEXT_FULL,Y as checkUsagePause,K as contextFull,Q as contextReading,q as runLimit,H as usageReader};
|
package/hub/views.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F=Object.defineProperty;var s=(e,t)=>F(e,"name",{value:t,configurable:!0});import{clock as d,holdLine as S,sendWords as V,snoozeEnd as y}from"./schedule.mjs";import{CHOICES as H,FOREVER as $,durationEnd as W,endOf as M}from"./duration.mjs";import{siteIcon as B}from"./icons.mjs";import{codexStatus as G}from"../shared/codex.mjs";const Z=s(e=>e.charAt(0).toUpperCase()+e.slice(1),"capital"),O=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"),j=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)=>`${j(t)}${e.hold?`; ${S(e.hold,n)}`:""}`,"nowLine"),C=s((e,t)=>e.hold?S(e.hold,t):"pushes go out after each check","deviceLine"),Q=s(e=>`${p(e.quiet.start)} \u2013 ${p(e.quiet.end)}${e.quiet.hold?" \xB7 pushes held":""}`,"quietSummary"),X="checks every minute while you're here, every 5 when away",Y=s((e,t)=>e.count?`${e.count} push${e.count===1?"":"es"} queued; next send ${V(e.nextFlushAt,t)}.`:"No pushes queued.","queuedLine");function ee({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?`${O(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(ee,"pollLine");function te(e,t,n){return{title:Z(J(e,t,n)),lines:[ee(t,n),Y(e,n)],count:e.count}}s(te,"pollingNow");function ne(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(ne,"siteHealth");const R=[{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")}],oe=s((e,t,n)=>({usable:t.usable,tag:t.usable?null:t.reason,share:e,choices:R.map(({value:o,label:a})=>({value:o,label:a,on:o===e})),description:t.usable?R.find(o=>o.value===e).description(_[n]):t.words,fix:t.fix}),"codexView"),_={opus:"Opus",sonnet:"Sonnet",auto:"Claude"},P=[{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."}],se=s(e=>({model:e,builder:_[e],choices:P.map(({value:t,label:n})=>({value:t,label:n,on:t===e})),description:P.find(t=>t.value===e).description}),"claudeView");function me({now:e,st:t,poll:n,sidebar:o,rows:a,links:u=new Map,code:l={},host:c="",version:r,rules:h=[],remembered:w=new Map,integrations:m=[],codexShare:g="off",claudeModel:A="auto",codex:L=G({installed:!1}),awake:q=null}){const b=new Set(o.sites.filter(i=>i.board).map(i=>i.route)),N=!!(l.running&&l.running===l.onDisk),z=N?` \xB7 runs the code in its files (${l.onDisk})`:"",D=s(i=>({route:i.route,title:i.title,icon:B(i.route,i),href:`/${encodeURIComponent(i.route)}/`,...ne(i,u.get(i.route)),remembered:w.get(i.route)||[],restart:b.has(i.route)&&i.restart===!0}),"site"),U=[["Boards",a.filter(i=>b.has(i.route))],["Pages",a.filter(i=>!b.has(i.route))]].filter(([,i])=>i.length).map(([i,K])=>({label:i,sites:K.map(D)}));return{hub:{tone:o.hub.tone,word:o.hub.word,detail:`${o.hub.detail}${z}`,restart:!N},awake:q&&f(q,e,E),groups:U,integrations:m,usage:o.usage,pause:o.pause,codex:oe(g,L,A),claude:se(A),empty:a.length===0,polling:te(t,n,e),notifications:{on:t.settings.notifications.on,text:o.notifications.text,device:C(t,e)},hold:t.hold&&t.hold.why!=="off"?{text:`Notifications ${S(t.hold,e)}`,end:t.hold.why==="snoozed"}:null,rules:h.length?O(h.length,"rule"):"None yet",sites:O(a.length,"site"),host:c,version:r,total:o.total}}s(me,"hubView");const ge="That snooze ends in the past or more than 30 days on. Pick another time.",ye="That keep awake ends in the past or more than 30 days on. Pick another time.",T="until you end it",E="until you turn it off",I="until you resume",f=s((e,t,n)=>e===$?n:`until ${d(e,t)}`,"untilWords"),v=s((e,t)=>H.map(([n,o])=>({value:n,label:o,until:f(W(e,n),e,t)})),"durationChoices"),ie=s((e,t)=>e.on?M(e.snoozed_until,t):null,"snoozedUntil");function $e({now:e,st:t,rules:n=[],linear:o={set:!1},slack:a={set:!1},awake:u={until:null,unsupported:null},pausedUntil:l=null}){const c=t.settings,r=c.notifications,h=ie(r,e),w=t.count?` The ${t.count} queued push${t.count===1?" is":"es are"} dropped now.`:"",m=h&&`Snoozed ${f(h,e,T)}`,g=l&&`Paused ${f(l,e,I)}`;return{pause:{on:l?{title:g}:null,summary:l===$?"Paused \xB7 forever":g||"Off",choices:l?null:v(e,I)},snoozed:h?{title:m,summary:h===$?"Snoozed \xB7 forever":m}:null,device:C(t,e),on:{on:r.on,sub:r.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.${w} Needs you and the badge still update.`},snooze:r.on&&!h?{choices:v(e,T)}:null,awake:{unsupported:u.unsupported,on:u.until?{title:`Keeping awake ${f(u.until,e,E)}`}:null,choices:u.unsupported||u.until?null:v(e,E),summary:u.unsupported||(u.until?u.until===$?"On \xB7 forever":`On until ${d(u.until,e)}`:"Off")},weekends:{on:r.weekends_off,sub:`Pushes wait from Friday ${p(c.quiet.start)} until Monday ${p(c.quiet.end)}. Urgent ones still go.`},quiet:le(c,e),rules:n,linear:ae(o),slack:re(a)}}s($e,"settingsView");const ue={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(ue))}`,label:"a new Slack app"};function re(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(re,"slackWords");const k={url:"https://linear.app/settings/account/security",label:"Linear \u203A Settings \u203A Security & access \u203A Personal API keys"};function ae(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(ae,"linearWords");function le(e,t){const n=e.quiet,[o,a]=[p(n.start),p(n.end)],u=y(t,"tonight",e),l=[["Snooze tonight",`Until ${d(u,t)}${n.hold?`, then quiet hours hold pushes until ${d(y(u,"morning",e),t)}`:""}.`],["Snooze morning",`Until ${d(y(t,"morning",e),t)}.`],["Snooze monday",`Until ${d(y(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:Q(e),hint:X,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(le,"quietView");function ke(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(ke,"flushView");export{ye as AWAKE_REFUSED,X as QUIET_HINT,ge as SNOOZE_REFUSED,j as cadenceLine,Z as capital,v as durationChoices,ke as flushView,me as hubView,J as nowLine,O as plural,ee as pollLine,Q as quietSummary,$e as settingsView,ne as siteHealth};
|
package/package.json
CHANGED
package/shared/card-prs.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var i=Object.defineProperty;var n=(e,r)=>i(e,"name",{value:r,configurable:!0});const s=/^(?:([\w.-]+\/[\w.-]+)#)?([1-9]\d*)$/,o=n(e=>Array.isArray(e?.prs)?e.prs:Number.isInteger(e?.pr)?[{number:e.pr}]:[],"storedPRs"),l=n((e,r)=>o(e).map(t=>({repo:t.repo||r,number:t.number,...t.merged_at?{merged_at:t.merged_at}:{},...t.kept?{kept:t.kept}:{}})).filter(t=>t.repo),"cardPRs"),m=n(e=>o(e).length>0,"hasPR"),u=n(({repo:e,number:r})=>`${e}#${r}`,"prKeyOf"),d=n(({repo:e,number:r})=>`https://github.com/${e}/pull/${r}`,"prURL"),x=n((e,r)=>e.map(t=>t.repo&&t.repo!==r?u(t):`#${t.number}`).join(", "),"prNames");function g(e){const r=s.exec(String(e).trim());return r?{...r[1]?{repo:r[1]}:{},number:Number(r[2])}:null}n(g,"parsePRRef");const a=["MERGED","CLOSED"],c=n(e=>e.checks?.state==="fail"||!!e.failing?.length,"failing");function p(e){return e?.state?a.includes(e.state)?5:e.isDraft?1:c(e)?2:e.reviewDecision==="APPROVED"?4:3:0}n(p,"readiness");function R(e){if(!e.length)return-1;const r=e.map(p);return r.every(t=>t===5)?Math.max(0,e.findIndex(t=>t.state==="MERGED")):r.indexOf(Math.min(...r))}n(R,"leastReady");const h=n(e=>e.length>0&&e.every(r=>a.includes(r?.state))&&e.some(r=>r.state==="MERGED"),"allLanded");export{h as allLanded,l as cardPRs,m as hasPR,R as leastReady,g as parsePRRef,u as prKeyOf,x as prNames,d as prURL,o as storedPRs};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var k=Object.defineProperty;var s=(e,t)=>k(e,"name",{value:t,configurable:!0});import i from"node:fs";import c from"node:os";import _ from"node:path";import{execFileSync as v}from"node:child_process";import{audit as d,hubAudit as y}from"./audit.mjs";const h=4,f=3,A=10*6e4,M=Object.freeze({state:"normal",reason:null}),D={1:"normal",2:"warn",4:"critical"},F=s(e=>D[e]??null,"pressureOf");function N(){let e=null;try{e=Number(v("sysctl",["-n","kern.memorystatus_vm_pressure_level"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim())}catch{}return{load:c.loadavg()[0],cores:c.cpus().length,pressure:F(e)}}s(N,"readMachine");function R(e,{load:t,cores:r,pressure:o}){const a=(e==="busy"?f:h)*r;return o==="critical"||t>=a?"busy":"normal"}s(R,"machineState");const b=s((e=c.homedir())=>_.join(e,".claude","kickflip","machine-state.json"),"machineFile"),g=s(e=>{try{return JSON.parse(i.readFileSync(b(e),"utf8"))}catch{return null}},"readFile");function T(e=c.homedir()){const t=g(e);return t?.state==="busy"?{state:"busy",reason:t.reason}:M}s(T,"readMachineState");function z({home:e=c.homedir(),reading:t=N(),now:r=new Date}={}){const o=g(e),a=o?.state??"normal",n=R(a,t),O=n==="busy"?t.pressure==="critical"?"memory pressure critical":"load high":null,l={reading:t,previous:o?.state??null,hold:h,release:f},u=`1-minute load ${t.load.toFixed(1)}`,p=n!==a,S=!o?.logged_at||r.getTime()-Date.parse(o.logged_at)>=A;if(p&&n==="busy"){const E=t.pressure==="critical"?"memory pressure is critical":`${u} is at least ${h}\xD7 its ${t.cores} cores`;d(y(e),{call:"machine-busy",result:n,reason:`The host is busy: ${E}, so no new work starts.`,inputs:l},{now:r})}else p?d(y(e),{call:"machine-eased",result:n,reason:`Memory pressure is ${t.pressure??"unread"} and ${u} is under ${f}\xD7 its ${t.cores} cores, so new work starts again.`,inputs:l},{now:r}):S&&d(y(e),{call:"machine-reading",result:n,reason:`Memory pressure is ${t.pressure??"unread"} and ${u} on ${t.cores} cores.`,inputs:l},{now:r});const $={state:n,reason:O,at:r.toISOString(),reading:t,logged_at:p||S?r.toISOString():o.logged_at},m=b(e);i.mkdirSync(_.dirname(m),{recursive:!0});const x=`${m}.${process.pid}.tmp`;return i.writeFileSync(x,JSON.stringify($)+`
|
|
2
|
+
`),i.renameSync(x,m),$}s(z,"checkMachine");export{h as HOLD_LOAD,M as MACHINE_NORMAL,f as RELEASE_LOAD,z as checkMachine,b as machineFile,R as machineState,F as pressureOf,N as readMachine,T as readMachineState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){const n=new URLSearchParams(location.search);let a=n.get("variant"),e=n.get("state");const r=[];addEventListener("message",t=>{if(!(t.source!==parent||t.data?.kickflip!=="prototype")){a=t.data.take??null,e=t.data.state??null;for(const s of r)s(a,e)}}),globalThis.KickflipPrototype={get take(){return a},get state(){return e},on(t){r.push(t),t(a,e)}}})();
|
package/shared/tailscale.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var p=Object.defineProperty;var
|
|
1
|
+
var p=Object.defineProperty;var a=(t,s)=>p(t,"name",{value:s,configurable:!0});import i from"node:fs";import u from"node:os";import e from"node:path";import{spawnSync as d}from"node:child_process";const f=e.join("Tailscale.app","Contents","MacOS","Tailscale"),m=a(t=>{try{return i.statSync(t).isFile()&&(i.accessSync(t,i.constants.X_OK),!0)}catch{return!1}},"isExecutable");function r({env:t=process.env,platform:s=process.platform,apps:n=["/Applications",e.join(u.homedir(),"Applications")]}={}){const l=(t.PATH||"").split(e.delimiter).filter(Boolean).map(o=>e.join(o,"tailscale"));return s==="darwin"&&l.push(...n.map(o=>e.join(o,f))),[...new Set(l)].filter(m)}a(r,"tailscaleCandidates");function h(t){const s=d(t,["status","--json"],{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});try{return JSON.parse(s.stdout).BackendState==="Running"}catch{return!1}}a(h,"daemonRunning");function y({running:t=h,...s}={}){const n=r(s);return n.length>1?n.find(t)??n[0]:n[0]??null}a(y,"tailscaleBin");function A(t,s={}){const n=r(s);return n.includes(t)?n.slice(0,n.indexOf(t)):[]}a(A,"tailscaleSkipped");const c=a((t=process.platform)=>t==="darwin"?"brew install --cask tailscale-app":"curl -fsSL https://tailscale.com/install.sh | sh","tailscaleInstallCommand"),C=a((t=process.platform)=>t==="darwin"?`install Tailscale from https://tailscale.com/download, or ${c(t)}`:c(t),"tailscaleInstallHint");export{h as daemonRunning,y as tailscaleBin,r as tailscaleCandidates,c as tailscaleInstallCommand,C as tailscaleInstallHint,A as tailscaleSkipped};
|
package/shared/usage-gate.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var v=Object.defineProperty;var n=(e,s)=>v(e,"name",{value:s,configurable:!0});import B from"node:fs";import x from"node:os";import I from"node:path";import{usageReader as U}from"../hub/usage.mjs";import{readSettingsFile as _,writeSettingsFile as $,readCodexShare as G,readClaudeModel as L}from"../hub/push.mjs";import{FOREVER as N,durationEnd as T,storedEnd as z}from"../hub/duration.mjs";import{codexStatus as J,codexStatusReader as K,effectiveCodexShare as V}from"./codex.mjs";import{MACHINE_NORMAL as q,readMachineState as Q}from"./machine-gate.mjs";const X=n(e=>Number.isInteger(e)&&e>=50&&e<=100&&e%5===0,"validPauseAt"),c=n(e=>Number(e),"timeOf"),R=["five_hour","seven_day"],b=n((e,s)=>e===N||typeof e=="string"&&Date.parse(e)>c(s)?e:null,"pausedUntil");function Y(e,s=new Date){if(e==="off")return null;const o=T(new Date(c(s)),e);if(!o)throw Object.assign(new Error("A pause ends after now and within 30 days: <n>m, <n>h, <n>d, <n>w, forever or a date and time; or off."),{status:400});return z(o)}n(Y,"pauseEnd");const Z=n(e=>e===N?"until the owner resumes it":`until ${e}`,"pauseUntilWords");function ee({claude:e,codex:s,pauseAt:o=90,keepGoing:t,hubPause:a,boardPause:r,machine:u=q,start:w=null,now:i=Date.now()}={}){const p=X(o)?o:90,D=n(l=>p===100?null:R.find(d=>{const f=l?.[d];return f?.state==="live"&&Number.isFinite(f.used_percentage)&&f.used_percentage>=p&&(!f.resets_at||Date.parse(f.resets_at)>c(i))})||null,"past"),k=n((l,d)=>({window:d,used:d?l[d].used_percentage:null,resets_at:d?l[d].resets_at:null}),"details"),m=D(e),A=k(e,m),C=n((l,d,f)=>l?.window===d&&Math.abs(Date.parse(l.until)-Date.parse(f))<=3e5&&c(i)<Date.parse(l.until),"covers"),j=m&&!t?.near&&C(t,m,A.resets_at),h=m?null:te(e,p,i);h&&(h.going=!!t?.near&&C(t,h.window,h.resets_at),h.waiting=!h.going&&!!w&&!w.reported&&c(i)-Date.parse(w.at)<se);const M=D(s),E={past:!!M,...k(s,M)},g=b(a,i)?"hub":b(r,i)?"board":null;return g?{pause_at:p,state:"paused",manual:g,window:null,used:null,resets_at:b(g==="hub"?a:r,i),near:null,codex:E,machine:u}:{pause_at:p,state:m?j?"going":"paused":"normal",manual:null,...A,near:h,codex:E,machine:u}}n(ee,"usageGate");const se=10*6e4,y=n(e=>2*e-100,"nearFrom");function te(e,s,o){if(s===100)return null;const t=R.find(a=>{const r=e?.[a];return r?.state==="live"&&Number.isFinite(r.used_percentage)&&r.used_percentage>=y(s)&&(!r.resets_at||Date.parse(r.resets_at)>c(o))});return t?{window:t,used:e[t].used_percentage,resets_at:e[t].resets_at,from:y(s)}:null}n(te,"nearOf");const ne=n(e=>{try{return JSON.parse(B.readFileSync(I.join(e,"board.json"),"utf8"))||{}}catch{return{}}},"readBoardJson"),ae=n((e,s=Date.now())=>b(ne(e).paused_until,s),"boardPausedUntil"),O=new Map;function W({home:e=x.homedir(),now:s=Date.now(),dir:o=null}={}){let t=O.get(e);t||(t={now:c(s)},t.usage=U({home:e,now:n(()=>t.now,"now")}),t.codex=K({home:e,now:n(()=>t.now,"now")}),O.set(e,t)),t.now=c(s);const a=_(e);return ee({...t.usage({codexShare:G(t.codex(),e)}),pauseAt:a.pauseAt,keepGoing:a.keepGoing,hubPause:a.paused_until,boardPause:o?ae(o,s):null,machine:Q(e),now:s})}n(W,"readUsageGate");function be(e,{home:s=x.homedir(),now:o=new Date}={}){const t=Y(e,o),{paused_until:a,...r}=_(s);return $(t?{...r,paused_until:t}:r,s),t}n(be,"setHubPause");function ge(e,{home:s=x.homedir()}={}){if(!/^(?:50|55|60|65|70|75|80|85|90|95|100)$/.test(String(e)))throw Object.assign(new Error("pause-at takes 50..100 in steps of 5"),{status:400});$({..._(s),pauseAt:Number(e)},s)}n(ge,"setPauseAt");function $e(e,{home:s=x.homedir(),now:o=Date.now()}={}){if(!["on","off"].includes(e))throw Object.assign(new Error("keep-going takes on or off"),{status:400});const t=_(s);if(e==="on"){const a=W({home:s,now:o});if(a.state==="paused")t.keepGoing={window:a.window,until:a.resets_at};else if(a.near)t.keepGoing={window:a.near.window,until:a.near.resets_at,near:!0};else throw Object.assign(new Error("Nothing is paused."),{status:409})}else delete t.keepGoing;$(t,s)}n($e,"setKeepGoing");const Se=n(e=>{try{return["github-change","check-github","card-unblocked","overnight-triage","pr-review","owner-check-broken"].includes(JSON.parse(e).kind)}catch{return!1}},"heldUsageEvent");function De({home:e=x.homedir(),now:s=Date.now(),card:o={}}={}){const t=J({home:e}),a={codex:t.reason??"usable",claudeModel:L(e),size:o.size??null,cardModel:o.model??null},r=n(w=>{const{model:i,reason:p}=oe(a.claudeModel,o);return{kind:"claude",model:i,reason:`${w} ${p}`,inputs:a}},"claude");if(!t.usable)return r(t.words);if(a.codexShare=V(_(e).codexShare,t),a.codexShare==="off")return r("Codex share is off.");const u=W({home:e,now:s});return Object.assign(a,{pauseAt:u.pause_at,codexUsage:u.codex}),u.codex.past?r(`Codex is at ${Math.round(u.codex.used)}%, past the ${u.pause_at}% line until ${u.codex.resets_at}.`):{kind:"codex",reason:`Codex share is ${a.codexShare} and Codex is under the ${u.pause_at}% line.`,inputs:a}}n(De,"builderPick");const F={opus:"Opus",sonnet:"Sonnet"};function oe(e,s){return e!=="auto"?{model:e,reason:`Claude model is ${F[e]}.`}:s.model?{model:s.model,reason:`Claude model is Auto and the card asks for Claude ${F[s.model]}.`}:s.size==="small"?{model:"sonnet",reason:"Claude model is Auto and the card is small."}:{model:"opus",reason:"Claude model is Auto and the card isn't small."}}n(oe,"claudePick");const H={hub:["the hub","Pause hub in Hub settings"],board:["this board","Pause board in Board settings"]},re=n(e=>e.manual?`Work is paused: the owner paused ${H[e.manual][0]} ${Z(e.resets_at)}. ${H[e.manual][1]} resumes it.`:e.state==="paused"?ie(e):e.machine.state==="busy"||!e.near?.waiting?P(e):ue(e),"pauseReason"),ue=n(e=>`Work is held: Claude's ${S(e.near.window)} usage is at ${Math.round(e.near.used)}%, near the ${e.pause_at}% line, so agents start one at a time, each once the last one has reported its usage. The owner can tap Keep going on the Hub page.`,"nearReason"),P=n(e=>`Work is held: the host is busy (${e.machine.reason}). It starts again when the host eases.`,"busyReason"),ke="Held: the host is busy. It starts again when the host eases.",Ae=n(e=>e.state==="paused"||e.machine.state==="busy","holdsWork"),Ce=n(e=>`usage paused ${e.resets_at} ${e.manual?`manual ${e.manual}`:`${e.window} ${e.used}%`}`,"pausedLine"),ie=n(e=>`Work is paused: Claude's ${S(e.window)} usage is at ${Math.round(e.used)}%. Resumes at ${e.resets_at}. The owner can tap Keep going on the Hub page.`,"usagePauseReason"),de=n((e,s)=>!!e.manual||e.machine.state==="busy"||(s==="codex"?e.codex.past:e.state==="paused"),"heldFor"),Me=n((e,s)=>de(e,s)||s!=="codex"&&!!e.near?.waiting,"launchHeld"),S=n(e=>e==="five_hour"?"5-hour":"weekly","windowWord"),Ee=n((e,s)=>s==="codex"&&!e.manual&&e.codex.past?`Codex is paused: its ${S(e.codex.window)} usage is at ${Math.round(e.codex.used)}%, past the ${e.pause_at}% line. Resumes at ${e.codex.resets_at}.`:s==="codex"&&!e.manual?P(e):re(e),"pauseReasonFor");export{ke as MACHINE_HELD_LINE,ae as boardPausedUntil,De as builderPick,de as heldFor,Se as heldUsageEvent,Ae as holdsWork,Me as launchHeld,Y as pauseEnd,re as pauseReason,Ee as pauseReasonFor,Z as pauseUntilWords,Ce as pausedLine,W as readUsageGate,be as setHubPause,$e as setKeepGoing,ge as setPauseAt,ee as usageGate,X as validPauseAt};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// The phase bars: one bar per phase, those reached filled, a running one pulsing. An In Progress card draws the five
|
|
2
|
-
// build phases (ui-cards.js) and a starting board's sidebar row its three start steps (ui-sidebar.js)
|
|
3
|
-
// (docs/adr/2026-11-04-1914-a-new-board-shows-its-start-steps-and-clone-progress.md). It needs nothing else, since
|
|
4
|
-
// hub/hub.mjs renders the shell's first sidebar with it in a vm context. style.css draws the bars.
|
|
5
|
-
(function () {
|
|
6
|
-
const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
7
|
-
// strip: {reached, running, dim, label, fill, plan}, or null for no bars. reached counts the phases reached, the last of
|
|
8
|
-
// them running when running is set; fill, a percent, fills the next bar that far; plan draws them in the planner blue.
|
|
9
|
-
function phaseBars(strip, phases) {
|
|
10
|
-
if (!strip) return '';
|
|
11
|
-
const { reached, running, dim, label, fill, plan } = strip;
|
|
12
|
-
const bar = (i) => (i === reached - 1 && running ? '<i class="now"></i>' : i < reached ? '<i class="done"></i>'
|
|
13
|
-
: i === reached && fill !== undefined ? `<i class="fill" style="--p:${fill}%"></i>` : '<i class=""></i>');
|
|
14
|
-
return `<span class="phase-bars${dim ? ' dim' : ''}${plan ? ' plan' : ''}" role="img" aria-label="${esc(label)}" title="${esc(label)}">${phases.map((_, i) => bar(i)).join('')}</span>`;
|
|
15
|
-
}
|
|
16
|
-
Object.assign(globalThis.BoardUI ||= {}, { phaseBars });
|
|
17
|
-
})();
|