@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/board/store.mjs CHANGED
@@ -1,18 +1,23 @@
1
- var bi=Object.defineProperty;var r=(e,t)=>bi(e,"name",{value:t,configurable:!0});import R from"node:fs/promises";import{constants as xi,existsSync as He}from"node:fs";import g from"node:path";import ht from"node:os";import{execFile as Xt}from"node:child_process";import{fileURLToPath as vi}from"node:url";import{BUILD_REFUSED as gt,BUILDER_ASK as Ke,ITEM_STATUSES as Yt,MAX_IMPLEMENTERS as _i,lineupPhases as $t,mergeBlockers as Si,modelName as Je,noTakePicked as ji,ownerQuestion as Ee,plans as ze,PLANNER_WORD as Oi,providerOf as kt,owesNext as yt,pushTag as Di,refOf as Qe,roundOf as bt,roundSettledBy as Pi}from"./domain.mjs";import{GITHUB_STATE as en,appendEvent as Se,listBoards as ge,samePath as je}from"../hub/boards.mjs";import{readUsageGate as tn,pauseReason as nn,builderPick as an}from"../shared/usage-gate.mjs";import{reviseQueued as Ai,flushQueue as Ri,queueStatus as Ni,pushKindError as Ei,readClaudeModel as Ii}from"../hub/push.mjs";import{holdLine as Ci,CHECK_MINUTES as Li}from"../hub/schedule.mjs";import{AT_RE as Bi}from"../hub/duration.mjs";import{routeRecord as U}from"../hub/routes.mjs";import{ticketSource as xt,ticketIn as vt,resolveTicket as qi,ticketTarget as Ti,moveTicket as Fi,titleTickets as Mi,cardIdOf as Ui}from"./tickets.mjs";import{LINEAR_NEEDS_KEY as Wi,linearStatus as Hi,linearWorks as Ki}from"../hub/linear.mjs";import{validateBranch as Ji}from"../hub/repos.mjs";import{withFileLock as Ge}from"../hub/locks.mjs";import{merge3 as zi}from"./merge3.mjs";import{fetchPR as sn,reportOf as on,githubLogin as Qi,postToPR as Gi,CLAUDE_PREFIX as rn,CLAUDE_MARK as Zi}from"../hub/pr-report.mjs";import{allLanded as cn,cardPRs as Ze,hasPR as Ve,leastReady as Vi,parsePRRef as ln,prKeyOf as Xi,prNames as Ie,prURL as Yi,storedPRs as dn}from"../shared/card-prs.mjs";import{reviewLinks as _t,topicItems as St,reviewersOf as Xe}from"./review.mjs";import{readiness as un}from"../hub/readiness.mjs";import{slackDay as fn}from"../hub/slack.mjs";import"../bin/install.mjs";import{readPermissions as ea}from"./permissions.mjs";import{parseCheck as ta,checkText as na}from"../shared/owner-check.mjs";import{RuleError as ia,rulesOf as wn,addRule as aa,editRule as sa,removeRule as oa,applyRules as ra,readHubRules as Ye,writeHubRules as ca}from"../hub/rules.mjs";class ne extends Error{static{r(this,"BoardError")}}const l=r(e=>{throw new ne(e)},"fail"),la=r(()=>g.join(ht.homedir(),".claude","kickflip","sites"),"sitesDir"),et=r(()=>g.join(ht.homedir(),".claude","waves"),"wavesDir"),pn=Symbol("read as"),y=r(async(e,t)=>{let i;try{i=await R.readFile(e,"utf8")}catch{return t}try{const n=JSON.parse(i);return n!==null&&typeof n=="object"&&!Array.isArray(n)?{...n,[pn]:i}:n}catch{return t}},"readJSON"),G=r(async e=>{try{return(await R.readFile(e,"utf8")).split(`
2
- `).filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}},"readLines");async function tt(e,t){await R.mkdir(g.dirname(e),{recursive:!0});const i=`${e}.${process.pid}.tmp`;await R.writeFile(i,t),await R.rename(i,e)}r(tt,"replace");const x=r((e,t)=>{const{[pn]:i,...n}=t??{};return i===void 0?tt(e,JSON.stringify(t,null,2)+`
3
- `):Ge(e,async()=>{const a=JSON.parse(i),s=JSON.parse(await R.readFile(e,"utf8").catch(()=>i));await tt(e,JSON.stringify(zi(a,n,s),null,2)+`
4
- `)})},"writeJSON");async function Z(e,t){await R.mkdir(g.dirname(e),{recursive:!0}),await R.appendFile(e,JSON.stringify(t)+`
5
- `)}r(Z,"appendLine");async function Gs(e){/^[\w-]+$/.test(e||"")||l(`--site takes a route such as ios-orchestrator, not "${e}"`);const t=g.join(la(),e);return await R.stat(t).then(i=>i.isDirectory(),()=>!1)||l(`no site at ${t}`),t}r(Gs,"siteDir");const H=r(async e=>({title:"Board",items:"waves",...e?await y(g.join(e,"board.json"),{}):{}}),"boardConfig");async function q(e){const t=await H(e);if(t.items==="waves")try{return(await R.readdir(et(),{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>({slug:n.name,dir:g.join(et(),n.name),file:g.join(et(),n.name,"wave.json")}))}catch{return[]}const i=g.resolve(e,t.items);return[{slug:t.slug||g.basename(t.items,".json"),dir:g.dirname(i),file:i}]}r(q,"itemSources");const K=r((e,t)=>g.join(e,"data","threads",t.replace(/[^\w.-]+/g,"__")+".jsonl"),"threadFile"),C=r(e=>g.join(e,"data","owner.json"),"ownerFile"),A=r(e=>e||l("this command needs --site <route>"),"needSite"),j=r((e,t)=>typeof e=="string"&&e.trim()?e.trim():l(`${t} must be non-empty text`),"text"),J=r((e,t)=>e===void 0?void 0:t(e),"optional"),da=/^prototype-[\w-]+\.html(?:[?#]\S*)?$/,mn=r((e,t)=>typeof e=="string"&&(da.test(e)||/^https?:\/\/\S+$/.test(e))?e:l(`${t} must be an http(s) URL or a site page such as prototype-<topic>.html?q=<id>`),"pageUrl"),jt=r((e,t)=>typeof e=="boolean"?e:l(`${t} must be true or false`),"bool"),le=r((e,t)=>typeof e=="string"&&/^[\w.-]+$/.test(e)?e:l(`${t} must use only letters, digits, "_", "." and "-"`),"domId"),Oe=r((e,t,i)=>{(!e||typeof e!="object"||Array.isArray(e))&&l(`${i} must be a JSON object`);const n=Object.keys(e).filter(a=>!t.includes(a));n.length&&l(`${i} has unknown field ${n.map(a=>`"${a}"`).join(", ")}; allowed: ${t.join(", ")}`)},"onlyKeys");function L(e){const t=/^([^/\s]+)\/([^/\s]+)$/.exec(e||"");return t?{wave:t[1],id:t[2]}:l(`expected <wave>/<id>, not "${e}"`)}r(L,"parseKey");async function De(e,t){const i=(await q(e)).find(a=>a.slug===t)||l(`this board has no wave "${t}"`),n=await y(i.file,null);return(!n||!Array.isArray(n.items))&&l(`${i.file} is not a wave file with items[]`),{source:i,wave:n}}r(De,"loadWave");async function O(e,t){const{wave:i,id:n}=L(t);let a=await De(e,i);!a.wave.items.some(o=>o.id===n)&&await ns(e,t)&&(a=await De(e,i));const s=a.wave.items.find(o=>o.id===n)||l(`wave "${i}" has no item "${n}"`);return{...a,item:s}}r(O,"loadItem");async function Zs(e,t,i){A(e),le(t,"the event id");const n=(await G(g.join(e,"data","events.jsonl"))).find(u=>u.id===t);n||l(`no event "${t}" in this site's data/events.jsonl`);const a=g.join(e,"data","replies",`${t}.html`);await tt(a,j(i,"the reply"));const s=n.kind==="ask"?`ask:${t}`:n.kind==="item-message"&&typeof n.data?.key=="string"?n.data.key:null,o=s?await $n(e,s,ya(i)):[],c=n.kind==="wave-triage"?["lineup","wave"].filter(u=>typeof n.data?.[u]=="string").map(u=>`${u}:${n.data[u]}`):[],d=n.kind==="ask"?`item:ask:${t}`:c[0];return d&&o.push(...await Tn(e,d,"Acted on: replied")),{file:a,lines:o}}r(Zs,"writeReply");const hn=r(e=>g.join(e,"data","working.json"),"workingFile");async function ua(e){return(await y(hn(e),{})).events||{}}r(ua,"readWorking");const Vs=["ask","item-message","wave-triage","overnight-triage"];async function Xs(e,t){if(!t.length)return;const i=new Date().toISOString(),n=await ua(e);await x(hn(e),{events:{...n,...Object.fromEntries(t.map(a=>[a,U(n,a)||i]))}})}r(Xs,"markWorking");const Ot=r(e=>g.join(e,"data","push-state.json"),"pushStateFile");async function fa(e,t){A(e);const i=Date.parse((await y(Ot(e),{})).last_push);if(Number.isNaN(i))return 0;const n=g.join(e,"data","replies"),a=(await R.readdir(n).catch(()=>[])).filter(o=>/\.(html|json)$/.test(o));return(await Promise.all(a.map(o=>R.stat(g.join(n,o)).then(c=>c.mtimeMs,()=>0)))).filter(o=>o>i&&o<=t.getTime()).length}r(fa,"repliesSincePush");async function wa(e,t){return await x(Ot(A(e)),{last_push:t.toISOString()}),Ot(e)}r(wa,"recordPush");const pa=g.join(g.dirname(vi(import.meta.url)),"..","bin","kickflip.mjs");function ma(){if(!process.env.KICKFLIP_PUSH_CMD)return[process.execPath,pa,"push"];try{const e=JSON.parse(process.env.KICKFLIP_PUSH_CMD);if(Array.isArray(e)&&e.length&&e.every(t=>typeof t=="string"))return e}catch{}throw new ne("KICKFLIP_PUSH_CMD must be a JSON array of strings")}r(ma,"pushCommand");async function Ys(e,t){const i=Ei(t.kind);i&&l(i),t.title===void 0&&l("push needs --title");const n=new Date,a=ga(t.body,await fa(e,n)),s={kind:t.kind,title:t.title,body:a||void 0,url:ba(t.url),tag:t.tag},[o,...c]=ma(),d=[...c,...Object.entries(s).flatMap(([f,p])=>p===void 0?[]:[`--${f}`,p]),...t.urgent?["--urgent"]:[],...t.now?["--now"]:[]],u=await new Promise(f=>{Xt(o,d,{encoding:"utf8"},(p,h,m)=>f({error:p,said:`${h||""}${m||""}`.split(`
6
- `).filter($=>$.trim())}))}),w=u.error?typeof u.error.code=="number"?u.error.code:1:0;if(w!==0)throw Object.assign(new ne([...u.said,`kickflip push failed (${typeof u.error.code=="number"?`exit ${w}`:u.error.message}); the push was not recorded`].join(`
7
- `)),{exitCode:w});return await wa(e,n),{lines:u.said}}r(Ys,"sendPush");const ha=/(?:^| · )(and \d+ repl(?:y|ies))$/,ga=r((e,t)=>[e,t&&`and ${t} ${t===1?"reply":"replies"}`].filter(Boolean).join(" \xB7 "),"withReplies"),gn=160;function $a(e){const t=String(e).split(`
8
- `).map(i=>i.replace(/\s+/g," ").trim()).find(Boolean)||"";return t.length>gn?`${t.slice(0,gn-1).trimEnd()}\u2026`:t}r($a,"pushLine");const ka={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};function ya(e){return e.replace(/<details[\s\S]*?<\/details>/gi,`
1
+ var Hi=Object.defineProperty;var r=(e,t)=>Hi(e,"name",{value:t,configurable:!0});import N from"node:fs/promises";import{constants as Ji,existsSync as De}from"node:fs";import h from"node:path";import Ot from"node:os";import{execFile as Pt}from"node:child_process";import{fileURLToPath as zi}from"node:url";import{BUILD_REFUSED as Dt,BUILDER_ASK as Xe,ITEM_STATUSES as fn,MAX_IMPLEMENTERS as Gi,MAX_PLANNERS as Qi,lineupPhases as At,mergeBlockers as Zi,modelName as et,noTakePicked as Vi,ownerQuestion as Ae,plans as Re,PLANNER_WORD as Yi,providerOf as Be,owesNext as Rt,pushTag as Xi,refOf as tt,roundOf as Nt,roundSettledBy as ea}from"./domain.mjs";import{GITHUB_STATE as pn,appendEvent as pe,listBoards as we,samePath as ve}from"../hub/boards.mjs";import{readUsageGate as wn,pauseReason as ta,pauseReasonFor as na,heldFor as ia,builderPick as mn}from"../shared/usage-gate.mjs";import{reviseQueued as aa,flushQueue as sa,queueStatus as oa,pushKindError as ra,readClaudeModel as ca}from"../hub/push.mjs";import{holdLine as da,CHECK_MINUTES as la}from"../hub/schedule.mjs";import{AT_RE as ua}from"../hub/duration.mjs";import{routeRecord as J}from"../hub/routes.mjs";import{ticketSource as Et,ticketIn as Lt,resolveTicket as fa,ticketTarget as pa,moveTicket as wa,titleTickets as ma,cardIdOf as ha}from"./tickets.mjs";import{LINEAR_NEEDS_KEY as ga,linearStatus as $a,linearWorks as ka}from"../hub/linear.mjs";import{validateBranch as ya}from"../hub/repos.mjs";import{withFileLock as nt}from"../hub/locks.mjs";import{audit as ba,auditLines as xa,boardAudit as hn,readAudit as va}from"../shared/audit.mjs";import{merge3 as Sa}from"./merge3.mjs";import{fetchPR as gn,reportOf as $n,githubLogin as _a,postToPR as ja,postReview as Oa,reviewsSince as Pa,CLAUDE_PREFIX as Te,CLAUDE_MARK as Ct}from"../hub/pr-report.mjs";import{allLanded as kn,cardPRs as Ne,hasPR as it,leastReady as Da,parsePRRef as yn,prKeyOf as Aa,prNames as qe,prURL as Ra,storedPRs as bn}from"../shared/card-prs.mjs";import{reviewLinks as at,topicItems as st,reviewersOf as Fe}from"./review.mjs";import{readiness as xn}from"../hub/readiness.mjs";import{slackDay as vn,savedSlack as Na,SlackError as Ea,SLACK_NEEDS_TOKEN as La}from"../hub/slack.mjs";import"../bin/install.mjs";import{readPermissions as Ca}from"./permissions.mjs";import{parseCheck as Ia,checkText as Ba}from"../shared/owner-check.mjs";import{RuleError as Ta,rulesOf as Sn,addRule as qa,editRule as Fa,removeRule as Ma,applyRules as Wa,readHubRules as ot,writeHubRules as Ua}from"../hub/rules.mjs";import{shareOf as Ka,validLogin as Ha}from"../hub/share.mjs";class Q extends Error{static{r(this,"BoardError")}}const u=r(e=>{throw new Q(e)},"fail"),Ja=r(()=>h.join(Ot.homedir(),".claude","kickflip","sites"),"sitesDir"),rt=r(()=>h.join(Ot.homedir(),".claude","waves"),"wavesDir"),_n=Symbol("read as"),$=r(async(e,t)=>{let i;try{i=await N.readFile(e,"utf8")}catch{return t}try{const n=JSON.parse(i);return n!==null&&typeof n=="object"&&!Array.isArray(n)?{...n,[_n]:i}:n}catch{return t}},"readJSON"),G=r(async e=>{try{return(await N.readFile(e,"utf8")).split(`
2
+ `).filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}},"readLines");async function ct(e,t){await N.mkdir(h.dirname(e),{recursive:!0});const i=`${e}.${process.pid}.tmp`;await N.writeFile(i,t),await N.rename(i,e)}r(ct,"replace");const y=r((e,t)=>{const{[_n]:i,...n}=t??{};return i===void 0?ct(e,JSON.stringify(t,null,2)+`
3
+ `):nt(e,async()=>{const a=JSON.parse(i),s=JSON.parse(await N.readFile(e,"utf8").catch(()=>i));await ct(e,JSON.stringify(Sa(a,n,s),null,2)+`
4
+ `)})},"writeJSON");async function Y(e,t){await N.mkdir(h.dirname(e),{recursive:!0}),await N.appendFile(e,JSON.stringify(t)+`
5
+ `)}r(Y,"appendLine");async function Bo(e){/^[\w-]+$/.test(e||"")||u(`--site takes a route such as ios-orchestrator, not "${e}"`);const t=h.join(Ja(),e);return await N.stat(t).then(i=>i.isDirectory(),()=>!1)||u(`no site at ${t}`),t}r(Bo,"siteDir");const M=r(async e=>({title:"Board",items:"waves",...e?await $(h.join(e,"board.json"),{}):{}}),"boardConfig");async function q(e){const t=await M(e);if(t.items==="waves")try{return(await N.readdir(rt(),{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>({slug:n.name,dir:h.join(rt(),n.name),file:h.join(rt(),n.name,"wave.json")}))}catch{return[]}const i=h.resolve(e,t.items);return[{slug:t.slug||h.basename(t.items,".json"),dir:h.dirname(i),file:i}]}r(q,"itemSources");const U=r((e,t)=>h.join(e,"data","threads",t.replace(/[^\w.-]+/g,"__")+".jsonl"),"threadFile"),L=r(e=>h.join(e,"data","owner.json"),"ownerFile"),Me=r(e=>h.join(e,"data","staged-questions.json"),"stagedFile"),A=r(e=>e||u("this command needs --site <route>"),"needSite"),j=r((e,t)=>typeof e=="string"&&e.trim()?e.trim():u(`${t} must be non-empty text`),"text"),z=r((e,t)=>e===void 0?void 0:t(e),"optional"),za=/^prototype-[\w-]+\.html(?:[?#]\S*)?$/,jn=r((e,t)=>typeof e=="string"&&(za.test(e)||/^https?:\/\/\S+$/.test(e))?e:u(`${t} must be an http(s) URL or a site page such as prototype-<topic>.html?q=<id>`),"pageUrl"),dt=r((e,t)=>typeof e=="boolean"?e:u(`${t} must be true or false`),"bool"),me=r((e,t)=>typeof e=="string"&&/^[\w.-]+$/.test(e)?e:u(`${t} must use only letters, digits, "_", "." and "-"`),"domId"),Ee=r((e,t,i)=>{(!e||typeof e!="object"||Array.isArray(e))&&u(`${i} must be a JSON object`);const n=Object.keys(e).filter(a=>!t.includes(a));n.length&&u(`${i} has unknown field ${n.map(a=>`"${a}"`).join(", ")}; allowed: ${t.join(", ")}`)},"onlyKeys");function C(e){const t=/^([^/\s]+)\/([^/\s]+)$/.exec(e||"");return t?{wave:t[1],id:t[2]}:u(`expected <wave>/<id>, not "${e}"`)}r(C,"parseKey");async function Le(e,t){const i=(await q(e)).find(a=>a.slug===t)||u(`this board has no wave "${t}"`),n=await $(i.file,null);return(!n||!Array.isArray(n.items))&&u(`${i.file} is not a wave file with items[]`),{source:i,wave:n}}r(Le,"loadWave");async function v(e,t){const{wave:i,id:n}=C(t);let a=await Le(e,i);!a.wave.items.some(o=>o.id===n)&&await Ms(e,t)&&(a=await Le(e,i));const s=a.wave.items.find(o=>o.id===n)||u(`wave "${i}" has no item "${n}"`);return{...a,item:s}}r(v,"loadItem");async function To(e,t,i){A(e),me(t,"the event id");const n=(await G(h.join(e,"data","events.jsonl"))).find(f=>f.id===t);n||u(`no event "${t}" in this site's data/events.jsonl`);const a=h.join(e,"data","replies",`${t}.html`);await ct(a,j(i,"the reply"));const s=n.kind==="ask"?`ask:${t}`:n.kind==="item-message"&&typeof n.data?.key=="string"?n.data.key:null,o=s?await Dn(e,s,is(i)):[],c=n.kind==="wave-triage"?["lineup","wave"].filter(f=>typeof n.data?.[f]=="string").map(f=>`${f}:${n.data[f]}`):[],d=n.kind==="ask"?`item:ask:${t}`:c[0];return d&&o.push(...await ti(e,d,"Acted on: replied")),{file:a,lines:o}}r(To,"writeReply");const On=r(e=>h.join(e,"data","working.json"),"workingFile");async function Ga(e){return(await $(On(e),{})).events||{}}r(Ga,"readWorking");const qo=["ask","item-message","wave-triage","overnight-triage"];async function Fo(e,t){if(!t.length)return;const i=new Date().toISOString(),n=await Ga(e);await y(On(e),{events:{...n,...Object.fromEntries(t.map(a=>[a,J(n,a)||i]))}})}r(Fo,"markWorking");const It=r(e=>h.join(e,"data","push-state.json"),"pushStateFile");async function Qa(e,t){A(e);const i=Date.parse((await $(It(e),{})).last_push);if(Number.isNaN(i))return 0;const n=h.join(e,"data","replies"),a=(await N.readdir(n).catch(()=>[])).filter(o=>/\.(html|json)$/.test(o));return(await Promise.all(a.map(o=>N.stat(h.join(n,o)).then(c=>c.mtimeMs,()=>0)))).filter(o=>o>i&&o<=t.getTime()).length}r(Qa,"repliesSincePush");async function Za(e,t){return await y(It(A(e)),{last_push:t.toISOString()}),It(e)}r(Za,"recordPush");const Va=h.join(h.dirname(zi(import.meta.url)),"..","bin","kickflip.mjs");function Ya(){if(!process.env.KICKFLIP_PUSH_CMD)return[process.execPath,Va,"push"];try{const e=JSON.parse(process.env.KICKFLIP_PUSH_CMD);if(Array.isArray(e)&&e.length&&e.every(t=>typeof t=="string"))return e}catch{}throw new Q("KICKFLIP_PUSH_CMD must be a JSON array of strings")}r(Ya,"pushCommand");async function Mo(e,t){const i=ra(t.kind);i&&u(i),t.title===void 0&&u("push needs --title");const n=new Date,a=es(t.body,await Qa(e,n)),s={kind:t.kind,title:t.title,body:a||void 0,url:as(t.url),tag:t.tag},[o,...c]=Ya(),d=[...c,...Object.entries(s).flatMap(([l,w])=>w===void 0?[]:[`--${l}`,w]),...t.urgent?["--urgent"]:[],...t.now?["--now"]:[]],f=await new Promise(l=>{Pt(o,d,{encoding:"utf8"},(w,m,g)=>l({error:w,said:`${m||""}${g||""}`.split(`
6
+ `).filter(b=>b.trim())}))}),p=f.error?typeof f.error.code=="number"?f.error.code:1:0;if(p!==0)throw Object.assign(new Q([...f.said,`kickflip push failed (${typeof f.error.code=="number"?`exit ${p}`:f.error.message}); the push was not recorded`].join(`
7
+ `)),{exitCode:p});return await Za(e,n),{lines:f.said}}r(Mo,"sendPush");const Xa=/(?:^| · )(and \d+ repl(?:y|ies))$/,es=r((e,t)=>[e,t&&`and ${t} ${t===1?"reply":"replies"}`].filter(Boolean).join(" \xB7 "),"withReplies"),Pn=160;function ts(e){const t=String(e).split(`
8
+ `).map(i=>i.replace(/\s+/g," ").trim()).find(Boolean)||"";return t.length>Pn?`${t.slice(0,Pn-1).trimEnd()}\u2026`:t}r(ts,"pushLine");const ns={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};function is(e){return e.replace(/<details[\s\S]*?<\/details>/gi,`
9
9
  `).replace(/<(?:br|\/?(?:p|div|li|ul|ol|h\d|blockquote|pre|tr|summary))\b[^>]*>/gi,`
10
- `).replace(/<[^>]*>/g,"").replace(/&(?:#(x[\da-f]{1,6}|\d{1,7})|(\w+));/gi,(t,i,n)=>{const a=i&&parseInt(i.replace(/^x/i,""),/^x/i.test(i)?16:10);return i?a<=1114111?String.fromCodePoint(a):t:U(ka,n.toLowerCase())??t})}r(ya,"htmlText");function ba(e){if(!e||!e.startsWith("/"))return e;const t=new URL(e,"http://board");return/^#item=[^&]+$/.test(t.hash)&&(t.hash=`${t.hash}&reply`),/\/[\w-]+\.html$/.test(t.pathname)&&!t.pathname.endsWith("/index.html")&&t.searchParams.set("from","push"),t.pathname+t.search+t.hash}r(ba,"pushUrl");const xa=r((e,t)=>`/${g.basename(e)}/#item=${encodeURIComponent(t)}&reply`,"threadUrl");async function $n(e,t,i){const n=$a(i);if(!n)return[];const a=Di(t),s=await Ai(a,o=>[n,ha.exec(o)?.[1]].filter(Boolean).join(" \xB7 "),xa(e,t));return s===null?[]:[`queued push ${a} now reads: ${s}`]}r($n,"freshenPush");const kn=r(e=>g.join(e,"data","hidden.json"),"hiddenFile"),va=r(async e=>new Set((await y(kn(e),{events:[]})).events||[]),"readHidden");let yn=Promise.resolve();function eo(e,t,i){le(t,"the event id");const n=yn.then(async()=>{const a=await va(e);i?a.add(t):a.delete(t),await x(kn(e),{events:[...a]})});return yn=n.catch(()=>{}),n}r(eo,"setHidden");const Dt=20*1024*1024,$e=r(e=>g.join(e,"data","uploads"),"uploadsDir"),Pe=r((e,t)=>g.join($e(e),".meta",`${t}.json`),"uploadMeta"),bn=/^\d+-[\w.-]+$/,xn=/^[\w.+-]+\/[\w.+-]+$/,vn=r(()=>Object.assign(new ne(`a file can be at most ${Dt/1024/1024} MB`),{status:413}),"tooLarge");async function to(e,t,{name:i,type:n,length:a}){if(A(e),a>Dt)throw vn();const s=String(i||"").trim().slice(0,200)||"file",o=g.basename(s).replace(/[^\w.-]+/g,"-").replace(/^[.-]+/,"").slice(-80)||"file",c=String(n||"").split(";")[0].trim().toLowerCase(),d=xn.test(c)?c:"application/octet-stream";await R.mkdir(g.dirname(Pe(e,"x")),{recursive:!0});let u,w;for(let h=Date.now();!w;h++)u=`${h}-${o}`,w=await R.open(g.join($e(e),u),"wx").catch(m=>m.code==="EEXIST"?null:Promise.reject(m));const f=g.join($e(e),u);let p=0;try{for await(const h of t){if(p+=h.length,p>Dt)throw vn();await w.write(h)}}catch(h){throw await w.close(),await R.rm(f,{force:!0}),h}return await w.close(),await x(Pe(e,u),{name:s,type:d,size:p,at:new Date().toISOString()}),{name:s,url:`uploads/${u}`,path:f,type:d,size:p}}r(to,"saveUpload");async function no(e,t){if(!bn.test(t||""))return null;const i=g.join($e(e),t),n=await R.stat(i).catch(()=>null);if(!n?.isFile())return null;const a=await y(Pe(e,t),{});return{path:i,name:a.name||t,type:xn.test(a.type||"")?a.type:"application/octet-stream",size:n.size}}r(no,"readUpload");const _n=["github","slack"];async function ke(e,t,{text:i,link:n,log:a,who:s="claude",via:o,kind:c}){A(e),String(t).startsWith("ask:")?await qe(e,t.slice(4),"the ask"):await O(e,t),/^[^\n]{1,40}$/.test(s.trim())||l("--who takes claude, love or a reviewer's name"),o!==void 0&&!_n.includes(o)&&l(`--via takes ${_n.join(" or ")}`);const d={ts:new Date().toISOString(),who:s.trim(),text:j(i,"--text"),link:J(n,w=>mn(w,"--link")),log:a,via:o,kind:c},u=K(e,t);return await Z(u,d),{file:u,lines:d.who==="claude"&&!o?await $n(e,t,d.text):[]}}r(ke,"appendThread");const de=r(e=>g.join(e,"data","ask-links.json"),"askLinksFile");async function ye(e){return(await y(de(e),{})).links||{}}r(ye,"readAskLinks");async function se(e,t){const{tickets:i}=be(await H(e)),n=await q(e),a=/^ask:(.+)$/.exec(t)?.[1];if(a===void 0){const o=/^([^/\s]+)\/([^/\s]+)$/.exec(t);if(!o)return t;const c=n.find(w=>w.slug===o[1]),d=c&&await y(c.file,null);if(!d)return o[2];const u=(d.items||[]).find(w=>w.id===o[2]);return Qe(d,u||{id:o[2]},i)}const s=e?U(await ye(e),a):void 0;if(s)return se(e,s);for(const o of n){const c=await y(o.file,null),d=(Array.isArray(c?.items)?c.items:[]).find(u=>u.from_ask===a);if(d)return Qe(c,d,i)}return`task ${a}`}r(se,"cardName");async function io(e,t){const i=(await G(g.join(e,"data","events.jsonl"))).find(n=>n.id===t);return i?.kind==="ask"?se(e,`ask:${t}`):typeof i?.data?.key=="string"?se(e,i.data.key):`the ${i?.kind} event`}r(io,"eventCard");async function ao(e,t,i,n){A(e),le(t,"the event id"),(await G(g.join(e,"data","events.jsonl"))).some(c=>c.id===t&&c.kind==="ask")||l(`no ask "${t}" in this site's data/events.jsonl`),await Pt(e,t),await O(e,i);const s={ts:new Date().toISOString(),who:"claude",text:j(n,"--summary")},o=await ye(e);return await x(de(e),{links:{...o,[t]:i}}),await Z(K(e,i),s),de(e)}r(ao,"relateAsk");async function so(e,t){await qe(e,t,"the ask");const i=await ye(e);return U(i,t)===void 0&&l(`ask "${t}" is not folded into a card`),delete i[t],await x(de(e),{links:i}),de(e)}r(so,"unfoldAsk");const nt=r(e=>g.join(e,"data","ask-progress.json"),"askProgressFile");async function it(e){return(await y(nt(e),{})).asks||{}}r(it,"readAskProgress");async function Pt(e,t){const i=U(await it(e),t)?.moved;i&&l(`ask "${t}" was moved to /${i.route}; it lives there now`)}r(Pt,"refuseMoved");async function oo(e,t,i,n){await qe(e,t,"the ask"),await Pt(e,t);const a=await it(e);return await x(nt(e),{asks:{...a,[t]:{state:i,at:new Date().toISOString(),...n===void 0?{}:{next:j(n,"--next")}}}}),nt(e)}r(oo,"markAsk");const _a=[void 0,"planned","waiting"];async function Sa(e,t,i){const n=`ask "${t}"`;if(i.some(w=>w.kind==="ask-withdrawn"&&w.data?.id===t&&!w.data?.key))return{why:`${n} was deleted by the owner`};const a=U(await it(e),t);if(a?.moved)return{why:`${n} was already moved to /${a.moved.route}`};const s=U(await ye(e),t);if(s)return{why:`${n} is folded into ${s}; run ask unfold ${t} first`};const o=[];for(const w of await q(e)){const f=await y(w.file,null);for(const p of Array.isArray(f?.items)?f.items:[])p.from_ask===t&&o.push({key:`${w.slug}/${p.id}`,it:p})}const c=o.find(({it:w})=>Ve(w)||!_a.includes(w.status));return c?{why:`${n} became ${c.key}, which has started`}:o.length?{items:o.map(w=>w.key)}:(await Promise.all(["html","json"].map(w=>R.stat(g.join(e,"data","replies",`${t}.${w}`)).then(()=>!0,()=>!1)))).some(Boolean)||!!a||i.some(w=>w.kind==="ask-done"&&w.data?.id===t)||(await G(K(e,`ask:${t}`))).some(w=>(w.who||"claude")==="claude"&&w.kind!=="status")?{why:`${n} is not New: Claude already answered it`}:null}r(Sa,"askNotNew");async function ja(e,t,i){const n=/^uploads\/([\w.-]+)$/.exec(i?.url||"")?.[1],a=bn.test(n||"")?g.join($e(e),n):null;if(!a||!await R.stat(a).then(d=>d.isFile(),()=>!1))return{name:String(i?.name||n||"file")};await R.mkdir(g.dirname(Pe(t,"x")),{recursive:!0});const s=n.replace(/^\d+-/,"");let o;for(let d=Date.now();o=`${d}-${s}`,!await R.copyFile(a,g.join($e(t),o),xi.COPYFILE_EXCL).then(()=>!0,w=>w.code==="EEXIST"?!1:Promise.reject(w));d++);const c=await y(Pe(e,n),null);return c&&await x(Pe(t,o),c),{...i,url:`uploads/${o}`,path:g.join($e(t),o)}}r(ja,"copyUpload");async function ro(e,t,i){A(e),le(t,"the event id"),(typeof i!="string"||!i.trim())&&l("ask move needs --to <route>, the board to move it to");const n=await G(g.join(e,"data","events.jsonl")),a=n.find(S=>S.id===t&&S.kind==="ask")||l(`no ask "${t}" in this site's data/events.jsonl`),s=ge(),o=s.find(S=>S.route===i)||l(`--to ${i}: no board at /${i} in the hub's manifest; the boards are ${s.map(S=>S.route).join(", ")||"none"}`);je(o.dir,e)&&l(`--to ${i}: that is this board`);const c=await Sa(e,t,n);c?.why&&l(c.why);const d=n.filter(S=>S.kind==="ask-edited"&&S.data?.id===t&&typeof S.data?.text=="string").sort((S,_)=>String(S.ts).localeCompare(String(_.ts))),u=d.at(-1),w=[];for(const S of[...a.data?.files||[],...d.flatMap(_=>_.data.files||[])])w.push(await ja(e,o.dir,S));const f={route:g.basename(e),title:(await H(e)).title,id:t},p=u?u.data.text:a.data?.text||"",h=await Se(o,"ask",{text:p,...w.length?{files:w}:{},from:f}),m={route:i,title:o.title,id:h},$=new Date().toISOString(),b=await it(e);await x(nt(e),{asks:{...b,[t]:{state:"done",at:$,moved:m}}});const v=`/${i}/#item=${encodeURIComponent(`ask:${h}`)}`;await Z(K(e,`ask:${t}`),{ts:$,who:"claude",text:`Moved to ${o.title}.`,link:v});for(const S of c?.items||[])await fe(e,S,{status:"dropped",force:!0,text:`Dropped: its ask moved to ${o.title}.`});return{file:g.join(o.dir,"data","events.jsonl"),lines:[`moved to ${v}`,...(c?.items||[]).map(S=>`dropped: ${S}`)]}}r(ro,"moveAsk");const Sn=r(e=>g.join(e,"data","checked.json"),"checkedFile");async function co(e,t,{idle:i}={}){A(e),i&&t!==void 0&&l("pass --every or --idle, not both"),i===void 0&&t===void 0&&(i=!await Oa(e));const n=new Date,a=i?null:t===void 0?Li.away:/^[1-9]\d{0,3}$/.test(String(t))?Number(t):l("--every takes the minutes between checks, such as 30");return await x(Sn(e),i?{at:n.toISOString(),every:null,idle:!0}:{at:n.toISOString(),every:a}),{file:Sn(e),every:a,lines:await Da()}}r(co,"writeChecked");async function lo(e,t,{state:i,text:n,url:a}={}){A(e),/^[1-9]\d{0,6}$/.test(String(t))||l(`review record takes the PR number, such as 437, not "${t}"`),["posted","needs"].includes(i)||l("review record needs --state posted or --state needs"),String(n??"").trim()||l("review record needs the review text, as --text or --file"),a!==void 0&&!/^https:\/\/github\.com\/\S+$/.test(a)&&l("--url takes the review's link on GitHub");const s=g.join(e,"data","reviews.json"),o=await y(s,{}),d=((await y(g.join(e,"data","incoming.json"),{}))?.prs||[]).find($=>$.number===Number(t))||o[t]||l(`PR #${t} is not an incoming PR on this board`),{title:u,author:w,url:f,touches:p=[],asked:h=!1,head:m}=d;return o[t]={number:Number(t),title:u,author:w,url:f,touches:p,asked:h,head:m,state:i,text:n,...a?{review_url:a}:{},at:new Date().toISOString()},await x(s,o),{file:s,lines:[]}}r(lo,"recordReview");async function Oa(e){for(const t of await q(e)){const i=await y(t.file,null);if((i?.items||[]).some(n=>!I.includes(n.status)&&Ze(n,oe(e,i)).length))return!0}return!1}r(Oa,"hasOpenPR");async function Da(){const e=Ni(new Date);if(e.hold)return e.count?[`queued pushes held: ${Ci(e.hold)}`]:[];const t=await Ri();return t?[`sent ${t.sent} of ${t.count} queued push${t.count===1?"":"es"}${t.ok?"":"; the rest stay queued"}`]:[]}r(Da,"flushAfterTick");const at=r(e=>g.join(e,"data","handshake.json"),"handshakeFile"),jn=r(e=>y(at(e),null),"readHandshake");async function uo(e,t){A(e),le(t,"the event id");const i=(await G(g.join(e,"data","events.jsonl"))).find(a=>a.id===t);i?.kind!=="hello"&&l(`no hello event "${t}" in this site's data/events.jsonl`);const n=await jn(e)||{};return n.hello?.id&&n.hello.id!==t&&l(`"${t}" is an older hello; ack the newest, "${n.hello.id}"`),await x(at(e),{...n,hello:n.hello||{id:t,at:i.ts,session:null},ack:{id:t,at:new Date().toISOString()}}),at(e)}r(uo,"ackHello");async function fo(e){const t=await jn(e);t&&!t.done_at&&await x(at(e),{...t,done_at:new Date().toISOString()})}r(fo,"finishHandshake");const At={name:/^[^\n]{1,40}$/,slack_user:/^U[A-Z0-9]+$/,dm:/^D[A-Z0-9]+$/,github:/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/},Ce=r((e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase(),"sameName");function Rt(e,t){return Array.isArray(e)||l(`${t} must be a JSON array of reviewers`),e.forEach((i,n)=>{const a=`${t}[${n}]`;Oe(i,Object.keys(At),a);for(const[s,o]of Object.entries(At))(typeof i[s]!="string"||!o.test(i[s].trim()))&&l(`${a}.${s} must match ${o}`);e.slice(0,n).some(s=>Ce(s.name,i.name))&&l(`${t} names "${i.name}" twice`)}),e.map(i=>Object.fromEntries(Object.keys(At).map(n=>[n,i[n].trim()])))}r(Rt,"checkReviewers");async function Nt(e,t){const{file:i,reviewers:n}=await Lt(e,s=>{const o=Rt(t(s.reviewers||[]),"the reviewers");return{set:{reviewers:o},reviewers:o}}),a=[];for(const s of await q(e)){const o=await y(s.file,null);(o?.items||[]).some(c=>!I.includes(c.status))&&(await x(s.file,{...o,reviewers:n}),a.push(`wave ${s.slug}: reviewers copied`))}return{file:i,lines:a}}r(Nt,"writeReviewers");const wo=r((e,t)=>Nt(e,()=>Rt(t,"the reviewer file")),"setReviewers"),On=r((e,t)=>((typeof e!="string"||!/^\d+(?:\.\d+)?$/.test(e)||Number(e)<=0)&&l("--ts must be a Slack message timestamp"),(typeof t!="string"||!/^D[A-Z0-9]+$/.test(t))&&l("--channel must be a DM channel id"),{ts:e,channel:t}),"linkMessage"),Et=r((e,t,i)=>Xe(e,t).find(n=>n.name===i)||l(`no reviewer "${i}" on this wave or board`),"reviewerOn"),po=r((e,t,i,{ts:n,channel:a})=>Ne(e,async()=>{const s=On(n,a),{source:o,wave:c,item:d}=await O(e,t);return Et(c,(await H(e)).reviewers,i),d.review_link_ts={...d.review_link_ts,[i]:s},await x(o.file,c),o.file}),"reviewSent"),mo=r((e,t,i,n)=>Ne(e,async()=>{(typeof n!="string"||!/^[\w+-]+$/.test(n))&&l("emoji must be a Slack emoji name without colons");const{source:a,wave:s,item:o}=await O(e,t),c=Et(s,(await H(e)).reviewers,i),d=_t(s,o,t,St())[i];d?.ts||l(`no review link recorded for ${i} on ${t}`);const u=U(o.review_link_ts,i),w=typeof u=="object"&&Array.isArray(u?.reactions)?u.reactions:[];return w.includes(n)||(o.review_link_ts={...o.review_link_ts,[i]:{...d,channel:d.channel||c.dm,reactions:[...w,n]}},await x(a.file,s)),a.file}),"reviewReact"),Dn=r(e=>g.join(A(e),"data","review-digests.json"),"digestFile");async function ho(e,t){A(e);const i=await un.waiting("slack");if(i)return{waiting:i,dms:[],reactions:[],digest:null};const n=await H(e),a=await y(en,{}),s=St(),o=`board.mjs --site ${g.basename(e)}`,c=r(f=>/^[\w.@-]+$/.test(f)?f:JSON.stringify(f),"arg"),d=[],u=[];for(const f of await q(e)){const p=await y(f.file,{}),h=Xe(p,n.reviewers),m=oe(e,p);for(const $ of p.items||[]){const{prs:b,pr:v}=Pn(a,$,m);if(!v||["done","dropped"].includes($.status))continue;const S=`${f.slug}/${$.id}`,_=_t(p,$,S,s);if($.status==="merged"||$.merged_at||cn(b.map(D=>D.gh)))for(const D of h){const P=U(_,D.name),E=U($.review_link_ts,D.name);!P?.ts||Array.isArray(E?.reactions)&&E.reactions.includes("git_merged")||u.push({key:S,reviewer:D.name,channel:P.channel||D.dm,ts:P.ts,emoji:"git_merged",record:`${o} review react ${S} ${c(D.name)} git_merged`})}else if(v.gh?.state==="OPEN"&&!v.gh.isDraft){const D=b.filter(P=>P.gh?.state==="OPEN").map(P=>P.url).join(`
11
- `);for(const P of h.filter(E=>!U(_,E.name)))d.push({key:S,reviewer:P.name,channel:P.dm,text:D,record:`${o} review sent ${S} ${c(P.name)} --ts <ts> --channel ${P.dm}`})}}}const w=await Pa(e,t);return{dms:d,reactions:u,digest:w.due?{...w,record:`${o} review digest sent <reviewer> --ts <ts> --channel <dm> --items <key,key>`}:null}}r(ho,"reviewDue");function Pn(e,t,i){const n=Ze(t,i).map(a=>({...a,url:Yi(a),gh:U(e.prs,Xi(a))||null}));return{prs:n,pr:n[Vi(n.map(a=>a.gh))]||null}}r(Pn,"cachedPRs");async function Pa(e,{now:t=new Date}={}){A(e);const i=await H(e),n=await y(en,{}),a=St(),s=new Map;for(const w of await q(e)){const f=await y(w.file,{}),p=Xe(f,i.reviewers);for(const m of p)s.has(m.name)||s.set(m.name,{name:m.name,slack_user:m.slack_user,dm:m.dm,items:[]});const h=oe(e,f);for(const m of f.items||[]){if(["merged","done","dropped"].includes(m.status))continue;const $=`${w.slug}/${m.id}`,{pr:b}=Pn(n,m,h),v=b?.gh;if(v?.state!=="OPEN"||v.isDraft||v.failing?.length||v.reviewDecision==="APPROVED")continue;const S=_t(f,m,$,a);for(const _ of p){const D=U(S,_.name),P=D?.ts?(t.getTime()-Number(D.ts)*1e3)/864e5:null;s.get(_.name).items.push({key:$,title:m.title,pr:b.number,url:b.url,sent_ts:D?.ts||null,...P>2?{days_old:Math.floor(P)}:{}})}}}const{date:o,morning:c}=fn(t),d=await y(Dn(e),{}),u=await un.waiting("slack");return{date:o,due:!u&&c&&d.last_date!==o,...u?{waiting:u}:{},reviewers:[...s.values()].filter(w=>w.items.length)}}r(Pa,"reviewDigest");async function go(e,t,{ts:i,channel:n,items:a},{now:s=new Date}={}){const o=On(i,n),c=[...new Set(j(a,"--items").split(",").map(w=>w.trim()))],d=await H(e);for(const w of c){const{wave:f}=await O(e,w);Et(f,d.reviewers,t)}const u=Dn(e);return Ge(u,async()=>{const w=await y(u,{});return await x(u,{last_date:fn(s).date,digests:[...w.digests||[],{reviewer:t,dm:o.channel,ts:o.ts,items:c,reactions:[]}]}),u})}r(go,"reviewDigestSent");function $o(e,t){const i=Rt(Array.isArray(t)?t:[t],"the reviewer file");return Nt(e,n=>[...n.map(a=>i.find(s=>Ce(s.name,a.name))||a),...i.filter(a=>!n.some(s=>Ce(a.name,s.name)))])}r($o,"addReviewers");function ko(e,t){return Nt(e,i=>{const n=t.filter(a=>!i.some(s=>Ce(s.name,a)));return n.length&&l(`this board has no reviewer ${n.map(a=>`"${a}"`).join(", ")}`),i.filter(a=>!t.some(s=>Ce(a.name,s)))})}r(ko,"removeReviewers");const Aa=r(()=>g.join(ht.homedir(),".claude","kickflip","settings.json"),"hubSettingsFile"),It=r(e=>{try{return e()}catch(t){throw t instanceof ia&&l(t.message),t}},"ruleCall"),Ct=r(async e=>wn(await y(g.join(e,"board.json"),{})),"readBoardRules");let An=Promise.resolve();function Lt(e,t){const i=An.then(async()=>{const n=g.join(A(e),"board.json"),a=await y(n,{}),{set:s,...o}=t(a);return await x(n,{...a,...s}),{file:n,...o}});return An=i.catch(()=>{}),i}r(Lt,"writeBoardJSON");const Rn=r((e,t)=>Lt(e,i=>{const n=It(()=>t(wn(i)));return{set:{rules:n.rules},...n}}),"writeBoardRules"),Nn=r(e=>typeof e=="string"&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(e),"validGithubLogin"),En=r(e=>{try{return e?xt(e):null}catch{return null}},"storedTickets"),In=r(e=>Number.isInteger(e)&&e>=1&&e<=99,"validMaxImplementers"),be=r(e=>{const t=En(e?.tickets);return{auto_merge:e?.auto_merge===!0,auto_build:e?.auto_build===!0,auto_pull:e?.auto_pull===!0,max_implementers:In(e?.max_implementers)?e.max_implementers:_i,auto_triage:e?.auto_triage===!0,auto_review:e?.auto_review===!0,idle_notification:e?.idle_notification===!0,skip_draft:e?.skip_draft===!0,prs:e?.prs!==!1,...t?{tickets:t}:{},...Nn(e?.github_login)?{github_login:e.github_login}:{}}},"settingsOf");async function Ra(e){return be(await y(g.join(A(e),"board.json"),{}))}r(Ra,"readBoardSettings");const yo=r((e,t)=>!!e?.github&&!e.local&&t.prs,"opensPRs");async function Le(e,t){Oe(t,["auto_merge","auto_build","auto_pull","max_implementers","auto_triage","auto_review","idle_notification","skip_draft","prs","tickets","github_login"],"the settings"),Object.keys(t).length||l("the settings name nothing to change"),t={...t};for(const[i,n]of Object.entries(t))if(i==="tickets"){try{t.tickets=xt(n)}catch(s){l(s.message)}t.tickets.source==="linear"&&!Ki()&&l(Wi);const a=t.tickets.source==="github"&&e?ge().find(s=>je(s.dir,e)):null;a&&!a.github&&l("GitHub issues need the board\u2019s repo on GitHub, and this board\u2019s repo isn\u2019t; pick internal or linear")}else i==="github_login"?n===""||n===null?t.github_login=void 0:Nn(n)||l("github_login must be a GitHub login"):i==="max_implementers"?In(n)||l("max_implementers must be a whole number from 1 to 99"):jt(n,i);if(t.prs===!1){const i=e?ge().find(n=>je(n.dir,e)):null;i?.github&&!i.local&&!(await ea(i.owner?.repo)).pushMain&&l("PRs off lands each card on main and pushes it, so turn on Push main after a land first")}return Lt(e,i=>{const n=be(i),a=be({...i,...t});return{set:t,settings:a,changed:Object.keys(t).filter(s=>JSON.stringify(n[s])!==JSON.stringify(a[s]))}})}r(Le,"saveBoardSettings");async function bo(){if(Hi().set)return[];const e=[];for(const t of ge()){if((await Ra(t.dir)).tickets?.source!=="linear")continue;const{settings:i}=await Le(t.dir,{tickets:{source:"internal"}});await Se(t,"settings",{tickets:i.tickets}),e.push(`/${t.route} fell back to internal tickets: Hub has no Linear key`)}return e}r(bo,"fallBackFromLinear");async function xo(e,t,i){const n=String(t).replace(/-/g,"_"),a=["auto_merge","auto_build","auto_pull","max_implementers","auto_triage","auto_review","idle_notification","skip_draft","prs","github_login","tickets"];if(a.includes(n)||l(`no board setting "${t}"; settings are ${a.map(c=>c.replace(/_/g,"-")).join(", ")}`),n==="tickets"){let c;try{c=JSON.parse(i)}catch{l('settings set tickets takes the source as JSON, such as {"source":"github"}')}const{file:d,settings:u}=await Le(e,{tickets:c});return{file:d,lines:Na({tickets:u.tickets})}}if(n==="github_login"){const{file:c,settings:d}=await Le(e,{github_login:i});return{file:c,lines:[`github-login ${d.github_login||"unset"}`]}}if(n==="max_implementers"){const{file:c,settings:d}=await Le(e,{max_implementers:/^\d+$/.test(i)?Number(i):i});return{file:c,lines:[`${t} ${d.max_implementers}`]}}["on","off"].includes(i)||l(`settings set ${t} takes on or off, not "${i}"`);const{file:s,settings:o}=await Le(e,{[n]:i==="on"});return{file:s,lines:[`${t} ${o[n]?"on":"off"}`]}}r(xo,"setBoardSetting");const Na=r(e=>Object.entries(e).map(([t,i])=>`setting ${t.replace(/_/g,"-")} ${t==="tickets"?JSON.stringify(i):t==="github_login"||t==="max_implementers"?i:i?"on":"off"}`),"settingsLines");async function Bt(e,t,i){const n=t?It(()=>i(Ye())):await Rn(e,i);return t&&It(()=>ca(n.rules)),{file:t?Aa():n.file,lines:[`id ${n.rule.id}`]}}r(Bt,"changeRules");async function Cn(e,t,i){const n=r(o=>o.map(c=>c.id),"ids");i||A(e);const[a,s]=i?[n(Ye()),e?n(await Ct(e)):[]]:[n(await Ct(e)),n(Ye())];a.includes(t)||l(`no ${i?"hub":"board"} rule "${t}"${s.includes(t)?`; it is a ${i?"board":"hub"} rule, so ${i?"drop":"pass"} --hub`:""}`)}r(Cn,"checkRuleId");async function vo(e){const t=r(i=>n=>`${i} ${n.id} ${n.by==="claude"?"claude":"owner"} ${n.text}`,"line");return{lines:[...Ye().map(t("hub")),...e?(await Ct(e)).map(t("board")):[]]}}r(vo,"listRules");function _o(e,{text:t,hub:i=!1,by:n}){return i||A(e),Bt(e,i,a=>aa(a,{text:t,by:n}))}r(_o,"addRuleTo");async function So(e,t,{text:i,hub:n=!1}){return await Cn(e,t,n),Bt(e,n,a=>sa(a,t,i))}r(So,"editRuleIn");async function jo(e,t,{hub:i=!1}){return await Cn(e,t,i),Bt(e,i,n=>oa(n,t))}r(jo,"removeRuleFrom");const Oo=r((e,t,i)=>Rn(e,n=>ra(n,t,i)),"saveBoardRules");async function Do(e,{id:t,title:i,summary:n}){A(e);const a=await y(C(e),{topics:[],items:[]}),s=a.topics||[];return s.some(o=>o.id===j(t,"the topic id"))&&l(`topic "${t}" already exists`),s.push({id:t.trim(),title:j(i,"--title"),...n===void 0?{}:{summary:j(n,"--summary")}}),await x(C(e),{...a,topics:s,items:a.items||[]}),C(e)}r(Do,"addTopic");const Ln=["quiet","info","notice","danger","success"];function Ea(e,t){if(e.diagram===void 0!=(e.practice===void 0)&&l(`${t} needs diagram and practice together`),e.diagram===void 0)return;const i=e.diagram;(!Array.isArray(i)||!i.length)&&l(`${t}.diagram must be a non-empty array of rows`),i.forEach((n,a)=>{(!Array.isArray(n)||!n.length||n.length>4)&&l(`${t}.diagram[${a}] must be a row of 1 to 4 boxes`),n.forEach((s,o)=>{const c=`${t}.diagram[${a}][${o}]`;Oe(s,["text","tone","to"],c),j(s.text,`${c}.text`),J(s.tone,d=>Ln.includes(d)?d:l(`${c}.tone takes ${Ln.join(", ")}`)),J(s.to,d=>Array.isArray(d)&&a+1<i.length&&d.every(u=>Number.isInteger(u)&&u>=0&&u<i[a+1].length)?d:l(`${c}.to must list boxes of the next row by index`))})}),(!Array.isArray(e.practice)||!e.practice.length)&&l(`${t}.practice must be a non-empty array of lines`),e.practice.forEach((n,a)=>j(n,`${t}.practice[${a}]`))}r(Ea,"checkDiagram");function Ia(e,t){(!Array.isArray(e)||!e.length)&&l(`${t}.options must be a non-empty array`);const i=new Set;e.forEach((n,a)=>{const s=`${t}.options[${a}]`;Oe(n,["id","label","recommended","detail","diagram","practice"],s),Ea(n,s),i.has(j(n.id,`${s}.id`))&&l(`${t} has two options with id "${n.id}"`),i.add(n.id),j(n.label,`${s}.label`).startsWith(`${n.id}. `)&&l(`${s}.label starts with "${n.id}. ", but the page adds the option letter itself`),J(n.recommended,o=>jt(o,`${s}.recommended`)),J(n.detail,o=>typeof o=="string"?o:l(`${s}.detail must be text`))}),e.filter(n=>n.recommended).length>1&&l(`${t} recommends more than one option`)}r(Ia,"checkOptions");function Ca(e,t,i){Oe(e,["option","card","answer"],i),t.some(n=>n.id===j(e.option,`${i}.option`))||l(`${i}.option names no option "${e.option}"`),j(e.card,`${i}.card`),j(e.answer,`${i}.answer`)}r(Ca,"checkSuggested");const Be=r(e=>g.join(e,"data","prototypes.json"),"prototypesFile"),qt=r((e,t,i)=>g.join(e,"public","prototypes",t,`${i}.js`),"takeFile");async function st(e){const t=e?(await y(Be(e),{})).prototypes:null;return Array.isArray(t)?t:[]}r(st,"readPrototypes");const La=r(e=>typeof e=="string"&&/^[a-z0-9-]+$/.test(e)?e:l(`a prototype topic uses only a-z, 0-9 and "-", not "${e}"`),"prototypeTopic");function Ba(e){const t=/^([^:]*):(.*)$/s.exec(e);(!t||!/^[A-Z]$/.test(t[1]))&&l(`--take takes KEY:"Label" with KEY one capital letter, not "${e}"`);const i=j(t[2],`--take ${t[1]}'s label`);return/^[A-Z]\.\s/.test(i)&&l(`--take ${t[1]}'s label starts with "${i.slice(0,3)}"; the take pill shows the label alone, so drop the letter`),{key:t[1],label:i}}r(Ba,"prototypeTake");const Ae=r(e=>/^prototype-(.+)\.html$/.exec(g.posix.basename(String(e||"").split(/[?#]/)[0]))?.[1],"pageTopic");async function Po(e,{topic:t,title:i,card:n,takes:a=[]}){A(e),La(t),j(i,"--title"),a.length||l('prototype add needs a --take KEY:"Label" for each take');const s=a.map(Ba),o=s.find((u,w)=>s.findIndex(f=>f.key===u.key)!==w);o&&l(`--take ${o.key} is given twice`),n!==void 0&&await O(e,n);const c=await st(e);c.some(u=>u.topic===t)&&l(`prototype ${t} is already recorded; run prototype rm ${t} first, or pick another topic`),await R.stat(g.join(e,"public",`prototype-${t}.html`)).then(()=>!0,()=>!1)&&l(`public/prototype-${t}.html is a hand-written page that questions may link; pick another topic`);const d={topic:t,title:i.trim(),...n===void 0?{}:{card:n},takes:s,at:new Date().toISOString()};return await x(Be(e),{prototypes:[...c,d]}),{file:Be(e),lines:[`page prototype-${t}.html`,...s.map(u=>`take ${u.key} ${qt(e,t,u.key)}`)]}}r(Po,"addPrototype");async function Ao(e){A(e);const t=await st(e);return{lines:t.length?t.map(i=>`${i.topic} \xB7 ${i.title} \xB7 ${i.takes.map(n=>`${n.key}: ${n.label}`).join(", ")}${i.card?` \xB7 ${i.card}`:""}`):["no prototypes recorded"]}}r(Ao,"listPrototypes");async function Ro(e,t){A(e);const i=await st(e);i.some(s=>s.topic===t)||l(`no prototype "${t}" is recorded`);const a=((await y(C(e),{items:[]})).items||[]).filter(s=>!s.resolved&&Ae(s.url)===t).map(s=>s.id);return a.length&&l(`prototype ${t} backs open question ${a.join(", ")}; resolve ${a.length===1?"it":"them"} first`),await x(Be(e),{prototypes:i.filter(s=>s.topic!==t)}),Be(e)}r(Ro,"removePrototype");async function qa(e,t,i){const n=t.url?.split(/[?#]/)[0];if(!n||!g.posix.basename(n).startsWith("prototype-"))return;const a=g.posix.basename(n),s=t.url.split("#")[0].split("?").slice(1).join("?"),o=`${i}.url`;new URLSearchParams(s).get("q")!==t.id&&l(`${o} must be ${a}?q=${t.id} so the pill can pick`);const c=Ae(n),d=(await st(e)).find(p=>p.topic===c);d||l(`${o} names ${a}, which is not a recorded prototype; record it with board.mjs prototype add ${c} --title "\u2026" --take A:"\u2026", then write its take files`);const u=d.takes.map(p=>p.key),w=t.options.map(p=>p.id),f=w.map(p=>u.indexOf(p));f.some((p,h)=>p<0||h>0&&p<f[h-1])&&l(`${i}.options ids ${w.join(", ")} must be a non-empty subset of ${a}'s takes, in take order: ${u.join(", ")}`);for(const p of u)await R.stat(qt(e,c,p)).then(h=>h.isFile(),()=>!1)||l(`${o} take ${p} has no file yet; write ${qt(e,c,p)}`)}r(qa,"checkPrototype");async function No(e,t){A(e);const i=Array.isArray(t)?t:[t];i.length||l("the question file is empty");const n=await y(C(e),{topics:[],items:[]}),a=n.items||[],s=new Set(a.map(h=>h.id)),o=new Set((n.topics||[]).map(h=>h.id));for(const[h,m]of i.entries()){const $=`question ${m?.id??h+1}`;Oe(m,["id","topic","source","question","context","url","urgent","options","round_of","reask_of","ask","suggested"],$),s.has(le(m.id,`${$}.id`))&&l(`question id "${m.id}" is already used`),s.add(m.id),j(m.topic,`${$}.topic`),m.topic.startsWith("item:ask:")?await qe(e,m.topic.slice(9),`${$}.topic`):m.topic.startsWith("item:")?await O(e,m.topic.slice(5)):m.topic.startsWith("lineup:")?await wt(e,m.topic.slice(7)):m.topic.startsWith("wave:")?await as(e,m.topic.slice(5)):o.has(m.topic)||l(`topic "${m.topic}" is not declared; add it with: topic add ${m.topic} --title <t>`),j(m.question,`${$}.question`);for(const b of["source","context"])J(m[b],v=>j(v,`${$}.${b}`));J(m.url,b=>mn(b,`${$}.url`)),J(m.urgent,b=>jt(b,`${$}.urgent`)),Ia(m.options,$),J(m.suggested,b=>Ca(b,m.options,`${$}.suggested`)),await qa(e,m,$),m.ask!==void 0&&await ps(e,m,$),J(m.round_of,b=>{const v=a.find(S=>S.id===b);v||l(`${$}.round_of names no question "${b}" in owner.json`),v.topic!==m.topic&&l(`${$}.round_of names ${b} on topic ${v.topic}; a round stays on its question's topic, ${m.topic}`),Ae(m.url)||l(`${$}.round_of needs a url on a recorded prototype, prototype-<topic>.html?q=${m.id}`)}),J(m.reask_of,b=>{const v=a.find(S=>S.id===b);v||l(`${$}.reask_of names no question "${b}" in owner.json`),v.topic!==m.topic&&l(`${$}.reask_of names ${b} on topic ${v.topic}; a re-ask stays on its question's topic, ${m.topic}`),v.resolved||l(`${$}.reask_of names ${b}, which is not resolved; only a resolved question is asked again`)})}const{answers:c,requests:d}=await ot(e),u=new Date().toISOString(),w=[],f=[];for(const h of i.filter(m=>m.round_of))h.round=bt(a.find(m=>m.id===h.round_of))+1,Re(n,[h.round_of],`Followed by prototype round ${h.round}`,u),f.push(h.round_of);for(const h of i.filter(m=>m.reask_of))Re(n,[h.reask_of],`Asked again as ${h.id}`,u),f.push(h.reask_of);for(const h of i){const m=Ae(h.url),$=a.filter(v=>v.topic===h.topic).map(v=>Ee(v,c,d)),b=h.topic.startsWith("item:")?Bn($):[];for(const v of $)b.includes(v.id)?(Re(n,[v.id],`Followed by ${h.id}`,u),f.push(v.id)):!v.resolved&&m&&Ae(v.url)===m&&(Re(n,[v.id],`Replaced by ${h.id}`,u),w.push(v.id))}const p={...n,topics:n.topics||[],items:[...a,...i.map(h=>({...h,asked_at:u}))]};return await x(C(e),p),{file:C(e),lines:[...w.map(h=>`replaced: ${h}`),...f.map(h=>`resolved: ${h}`)]}}r(No,"addQuestions");function Bn(e){return e.filter(t=>t.state==="answered").map(t=>t.id)}r(Bn,"answeredOnClaude");function Re(e,t,i,n=new Date().toISOString()){for(const a of e.items||[])t.includes(a.id)&&Object.assign(a,{resolved:i,resolved_at:n})}r(Re,"setResolved");async function Tt(e,t,i,n){return Re(t,i,n),await x(C(e),t),C(e)}r(Tt,"markResolved");async function Eo(e,t,i){A(e);const n=await y(C(e),{topics:[],items:[]}),a=(n.items||[]).find(w=>w.id===t);a||l(`no question "${t}" in owner.json`);const{answers:s,requests:o}=await ot(e),c=Ee(a,s,o);if(c.state==="resolved")return C(e);c.state==="requested"&&l(`${t} waits on the prototype the owner asked for; question add with round_of ${t} resolves it`);const d=j(i,"--note");Ae(a.url)&&Ta(n,a,s);const u=await Tt(e,n,[t],d);return await Un(e,a.topic),u}r(Eo,"resolveQuestion");async function Io(e,t){const i=t.filter(({choice:a,note:s})=>!a&&String(s||"").trim()).map(a=>a.id),n=i.length?await y(C(e),{topics:[],items:[]}):null;n?.items?.some(a=>i.includes(a.id))&&(Re(n,i,"Answered with a note"),await x(C(e),n))}r(Io,"resolveNoteAnswers");function Ta(e,t,i){const n=bt(t),a=e.items.filter(s=>s.topic===t.topic&&bt(s)===n).map(s=>Ee(s,i));Pi(a,n)||l(`${t.id} is in prototype round ${n}, which no pick has settled yet; a pick settles it`)}r(Ta,"roundSettled");async function ot(e){const t=await G(g.join(e,"data","events.jsonl"));return{answers:await Promise.all(t.filter(n=>n.kind==="owner-answer").map(async n=>{const a=await Promise.all(["html","json"].map(s=>R.stat(g.join(e,"data","replies",`${n.id}.${s}`)).then(o=>o.isFile(),()=>!1)));return{...n,reply:n.reply||a.some(Boolean)}})),requests:t.filter(n=>n.kind==="prototype-request")}}r(ot,"ownerEvents");async function qn(e,t){const i=await y(C(e),{topics:[],items:[]}),{answers:n,requests:a}=await ot(e),s=(i.items||[]).filter(o=>o.topic===t).map(o=>Ee(o,n,a));return{owner:i,asked:s}}r(qn,"topicQuestions");const ue=r((e,t)=>qn(e,`item:${t}`),"cardQuestions"),Ft=r((e,t,i)=>Tn(e,`item:${t}`,i),"resolveAnswered");async function Tn(e,t,i){if(!e)return[];const{owner:n,asked:a}=await qn(e,t),s=Bn(a);return s.length&&await Tt(e,n,s,i),await Un(e,t),s.map(o=>`resolved: ${o}`)}r(Tn,"resolveAnsweredOn");const Fn=r(async(e,t)=>!!e&&(await ue(e,t)).asked.some(i=>i.state==="open"),"hasOpenQuestion");function Mn(e,t,i){e.next=j(t,"--next"),i?e.next_on_questions=!0:delete e.next_on_questions}r(Mn,"setNext");async function Un(e,t){const i=t.startsWith("item:")&&!t.startsWith("item:ask:")?t.slice(5):null;if(!i)return;let n;try{n=await O(e,i)}catch(c){if(c instanceof ne)return;throw c}const{source:a,wave:s,item:o}=n;o.next_on_questions&&((await ue(e,i)).asked.some(c=>c.state!=="resolved")||(delete o.next,delete o.next_on_questions,await x(a.file,s)))}r(Un,"clearWaitedNext");async function Fa(e,t){const{source:i,wave:n,item:a}=await O(e,t);a.next===void 0&&a.next_on_questions===void 0||(delete a.next,delete a.next_on_questions,await x(i.file,n))}r(Fa,"clearNext");async function Wn(e,t,i,n){if(!e)return async()=>[];const{owner:a,asked:s}=await ue(e,t),o=s.filter(d=>d.state==="open").map(d=>d.id);o.length&&!n&&l(`${i}: ${t} has ${o.length===1?"an open question":"open questions"} ${o.join(", ")} with no answer yet; pass --force to close the card and resolve ${o.length===1?"it":"them"} too`);const c=s.filter(d=>d.state!=="resolved").map(d=>d.id);return async()=>(c.length&&await Tt(e,a,c,"Closed with the card"),c.map(d=>`resolved: ${d}`))}r(Wn,"closeQuestions");async function Co(e,t,i,n,a){await O(e,t),j(i,"--text"),J(n,s=>j(s,"--owner-step")),J(a,s=>Xn(s)),await Wn(A(e),t,"land",!1)}r(Co,"checkClose");async function Hn(e,t){const i=await y(C(e),{items:[]}),{answers:n,requests:a}=await ot(e);return ji((i.items||[]).map(s=>Ee(s,n,a)),t)}r(Hn,"unpickedPrototype");const Ma=r(e=>e.length>120?`${e.slice(0,119)}\u2026`:e,"clip"),Ua={ask:"text","ask-edited":"text","item-message":"text","owner-answer":"note"};async function Kn(e,t,i){const n=j(t,i).replace(/\s+/g," ");return(await G(g.join(e,"data","events.jsonl"))).map(s=>String(s.data?.[Ua[s.kind]]??"").replace(/\s+/g," ").toLowerCase()).some(s=>s.includes(n.toLowerCase()))||l(`${i} must quote the owner's words in an ask, card message or answer note on this board`),n}r(Kn,"ownerQuote");async function Lo(e,t,i){return A(e),i===void 0&&l(`only the owner's Serve / Build and the hub's Auto-build start a card run; pass --asked "<the owner's words>" quoting where the owner asked for ${t}'s run`),`Running at the owner's ask: "${await Kn(e,i,"--asked")}"`}r(Lo,"askedGate");async function qe(e,t,i="--from-ask"){return le(t,i),(await G(g.join(A(e),"data","events.jsonl"))).some(a=>a.id===t&&a.kind==="ask")?t:l(`no ask "${t}" in this site's data/events.jsonl`)}r(qe,"checkAsk");const I=["done","merged","dropped"],Bo=r(async(e,t)=>I.includes((await O(e,t)).item.status),"isFinished"),Wa=["ready","grilling","prototyping"];function rt(e){return["building","fixing"].includes(e?.status)?(delete e.status,e.status_at=new Date().toISOString(),!0):!1}r(rt,"clearBuildingStatus");function Ha(e,t,i){const n=[].concat(t).map(o=>ln(o)||l(`--pr takes a PR number or owner/repo#<n>, not "${o}"`)),a=r((o,c)=>o.number===c.number&&(o.repo||i||null)===(c.repo||i||null),"same"),s=dn(e);for(const o of n)s.some(c=>a(c,o))||s.push(o);delete e.pr,e.prs=s}r(Ha,"addPRs");const V=r((e,t)=>String(t).includes("/")?String(t):`${e}/${t}`,"depKey");async function ct(e,t,i){const n=(i.deps||[]).map(s=>V(t,s)),a=await Promise.all(n.map(s=>O(e,s).then(({item:o})=>o,()=>null)));return n.filter((s,o)=>a[o]&&!I.includes(a[o].status))}r(ct,"unfinishedDeps");async function Ka(e,t){const i=[];for(const n of await q(e)){const a=await y(n.file,null);for(const s of Array.isArray(a?.items)?a.items:[])![void 0,"planned","waiting","held"].includes(s.status)||!(s.deps||[]).some(o=>V(n.slug,o)===t)||(await ct(e,n.slug,s)).length||i.push({key:`${n.slug}/${s.id}`,queued:!!s.queued_at})}return i}r(Ka,"unblockedBy");async function Jn(e,t,i,n){const a=new Set(n.match(/[\w-]+(?:\.[\w-]+)*(?:\/[\w-]+(?:\.[\w-]+)*)*/g)||[]),s=new Set((i.deps||[]).map(o=>V(L(t).wave,o)));for(const o of await q(e)){const c=await y(o.file,null);for(const d of c?.items||[]){const u=`${o.slug}/${d.id}`;if(u===t||s.has(u)||I.includes(d.status))continue;[d.id,Qe(c,d)].flatMap(f=>[f,`${o.slug}/${f}`]).some(f=>a.has(f))&&l(`--next names unfinished card ${u}; add it with --deps`)}}}r(Jn,"checkNextDeps");async function Ja(e,t,i,n){const a="a builder starts from it, so pass";n.size||l(`${t} has no size; ${a} --size small or large with --state ready`),n.plan||l(`${t} has no notes file; ${a} --notes-file <file.md> with --state ready`);const s=await R.readFile(await Te(i,n.plan),"utf8"),o=(await ue(e,t)).asked.filter(c=>c.answers.length&&!s.includes(c.id)).map(c=>c.id);o.length&&l(`${t}'s notes leave out the answered question${o.length===1?"":"s"} ${o.join(", ")}; record each answer in ${n.plan}, naming its id, before it is ready`)}r(Ja,"checkNotesComplete");async function Te(e,t){const i=r(a=>l(`a notes file is a .md file inside ${e}, named relative to it: "${t}" ${a}`),"bad");(typeof t!="string"||!t.trim())&&i("is empty"),(g.isAbsolute(t)||t.split(/[\\/]/).includes(".."))&&i("leaves the folder"),g.extname(t).toLowerCase()!==".md"&&i("is not a .md file");const n=await R.realpath(g.resolve(e,t)).catch(()=>i("does not exist"));return n.startsWith(await R.realpath(e)+g.sep)||i("leaves the folder"),n}r(Te,"planPath");async function qo(e,t){const{source:i,wave:n,item:a}=await O(e,t);if(a.plan)return{wave:n,item:a,markdown:await R.readFile(await Te(i.dir,a.plan),"utf8")};if(typeof a.notes=="string"&&a.notes.trim())return{wave:n,item:a,markdown:a.notes};l(`${t} has no notes`)}r(qo,"readNotes");function zn({install:e,installSha:t,installLabel:i,clearInstall:n}){if(e===void 0)return(t!==void 0||i!==void 0)&&l("--install-sha and --install-label go with --install <url>"),n?null:void 0;n&&l("pass --install or --clear-install, not both");let a;try{a=new URL(String(e).trim())}catch{a=null}(!a||!["https:","itms-services:"].includes(a.protocol))&&l(`--install takes an https:// or itms-services:// URL, not "${e}"`),a.protocol==="itms-services:"&&!(a.searchParams.get("action")==="download-manifest"&&/^https:\/\//.test(a.searchParams.get("url")||""))&&l("--install: an itms-services:// URL needs ?action=download-manifest&url=https://\u2026/manifest.plist");const s=t===void 0?void 0:/^[0-9a-f]{7,40}$/i.test(t)?t.toLowerCase():l(`--install-sha takes a commit sha of 7 to 40 hex digits, not "${t}"`);return{url:String(e).trim(),...i===void 0?{}:{label:j(i,"--install-label")},built_at:new Date().toISOString(),...s?{sha:s}:{}}}r(zn,"installOf");async function To(e,{install:t,installSha:i}){const n=zn({install:t,installSha:i});n||l("main set needs --install <url>");const a=g.join(A(e),"data","main.json");return await x(a,{install:n}),{file:a,lines:["main install set"]}}r(To,"setMainInstall");const Qn=r((e,t)=>e.length?`Merged PR${e.length>1?"s":""} ${Ie(e,t)}.`:"Merged.","mergedLine");function za(e,t,i,n,a,s){return n==="merged"?a??(i.status==="merged"?null:Qn(dn(i),s)):(a===void 0&&e&&l(`--status ${n} needs --text "<what was done or left>", which becomes ${t}'s last thread line`),a??null)}r(za,"closingLine");async function Gn(e,t,{ticket:i,status:n,clearStatus:a,next:s,clearNext:o,pr:c,pushed:d,mergeReady:u,ghSince:w,fromAsk:f,state:p,held:h,unheld:m,pickUpAt:$,notesFile:b,deps:v,parent:S,related:_,install:D,installSha:P,installLabel:E,clearInstall:F,title:z,size:X,model:M,force:B,text:Y,who:ve,ownerStep:ae,ownerDone:we,check:ce},Ue){n!==void 0&&a&&l("pass --status or --clear-status, not both"),p!==void 0&&!Wa.includes(p)&&l("--state takes ready, grilling or prototyping"),B&&!I.includes(n)&&l(`--force goes with --status ${I.join(", ")}`),f!==void 0&&I.includes(n)&&l("--from-ask opens a card; close it in another call"),Y!==void 0&&j(Y,"--text"),ae!==void 0&&j(ae,"--owner-step");const Q=ce===void 0||ce===""?ce:Xn(ce);Y!==void 0&&f===void 0&&!I.includes(n)&&l(`--text goes with --from-ask or --status ${I.join(", ")}`),f!==void 0&&Y===void 0&&l(`--from-ask needs --text "<first line>", the item's first thread line after the ask`),s!==void 0&&o&&l("pass --next or --clear-next, not both"),typeof s=="string"&&!s.trim()&&([s,o]=[void 0,!0]);const re=Qa({held:h,unheld:m,pickUpAt:$}),_e=zn({install:D,installSha:P,installLabel:E,clearInstall:F});[n,a,s,o,c,d,u,w,f,p,re,b,v,S,_,_e,z,X,M,i,ae,ce].every(N=>N===void 0||N===!1)&&l("nothing to set: pass --status, --clear-status, --next, --clear-next, --pr, --pushed, --gh-since, --from-ask, --state, --held, --unheld, --pick-up-at, --notes-file, --deps, --parent, --related, --install, --clear-install, --title, --size, --model, --ticket or --check");const T=f===void 0?void 0:await qe(e,f);T&&await Pt(e,T);const{source:ee,wave:pe,item:k}=await O(e,t);T&&k.from_ask&&k.from_ask!==T&&l(`${t} came from ask "${k.from_ask}", so ask "${T}" can't be its from-ask; to fold it in: item relate-ask ${T} ${t} --summary "<line>"`),T&&p===void 0&&!k.state&&l("--from-ask files a card, which reads New until it has a state: pass --state ready, grilling or prototyping");const pt=k.status,te=I.includes(k.status);ae!==void 0&&te&&l(`${t} is already ${k.status}, so its ticket closed; an owner step goes on the command that finishes the card: land --owner-step, or builder done before the merge`),ae!==void 0&&(k.owner_step=j(ae,"--owner-step")),(we||n==="dropped")&&delete k.owner_step,Q!==void 0&&!k.owner_step&&l(`--check goes with an owner step, which ${t} doesn't have: pass --owner-step "<the step>" with it on builder done or land`),Q&&(k.owner_check={check:Q,since:k.owner_check?.check===Q?k.owner_check.since:new Date().toISOString()}),(Q===""||!k.owner_step)&&delete k.owner_check;const Jt=await Promise.all((await ie(ee.dir,k.id)).map(N=>y(N,null))),$i=yt(k,Jt);if(b!==void 0&&(await Te(ee.dir,b),k.plan=g.normalize(b)),z!==void 0&&(k.title=j(z,"--title")),Zn(k,{size:X,model:M}),v!==void 0){const N=await Yn(e,L(t).wave,v);N.length?k.deps=N:delete k.deps}if(S!==void 0){const N=await ei(e,L(t).wave,t,S);N?k.parent=N:delete k.parent}const zt=_===void 0?null:await Xa(e,t,k,_);if(re!==void 0&&lt(k,re),n==="building"&&(k.held||k.status==="held")&&l(k.pick_up_at?`${t} is held until ${k.pick_up_at}, when the board resumes it; start it early only with item set ${t} --unheld`:`${t} is held; start it only once the owner resumes it, with item set ${t} --unheld`),n!==void 0&&(k.status=Yt.includes(n)?n:l(`--status takes ${Yt.join(", ")}`)),(Ga.includes(n)||c!==void 0||d!==void 0||u!==void 0)&&Za(k),n==="building"){const N=await ct(e,L(t).wave,k);N.length&&l(`${t} is blocked by ${N.join(", ")}; start it once ${N.length===1?"that is":"those are"} done or merged`)}(n==="building"||I.includes(n))&&delete k.queued_at;const We=n==="building"&&e?await Hn(e,t):null;We&&l(`${t} has no take picked: the owner's answer to ${We.id} picks none${We.note?` ("${Ma(We.note)}")`:""}, so it prototypes again: draw the next round from that note, or grill when the note asks a question, and build once a take is picked`);const ki=I.includes(n)?await Wn(e,t,`--status ${n}`,B):async()=>[],Qt=I.includes(n)?za(e,t,{...k,status:pt},n,Y,oe(e,pe)):null;if(a&&delete k.status,(n!==void 0||a)&&(k.status_at=new Date().toISOString()),s!==void 0&&(Mn(k,s,await Fn(e,t)),await Jn(e,t,k,k.next)),o&&(delete k.next,delete k.next_on_questions),n==="building"&&s===void 0&&k.next_on_questions&&(delete k.next,delete k.next_on_questions),(c!==void 0||d!==void 0||u!==void 0)&&!k.review_since&&(k.review_since=new Date().toISOString()),c!==void 0&&(Ha(k,c,oe(e,pe)),rt(k)),d!==void 0){ge().find(N=>je(N.dir,A(e)))?.remote||l("--pushed is for a board whose repo is a plain git remote; on GitHub, open a PR and pass --pr"),Ve(k)&&l(`${t} has a PR; its PR says when it merges`);try{Ji(d)}catch{l("--pushed takes the name of the branch you pushed")}k.pushed={branch:d,at:new Date().toISOString()},k.branch=d,rt(k)}if(u!==void 0&&(k.merge_ready={branch:u,at:new Date().toISOString()},k.branch=u,rt(k)),I.includes(n)&&delete k.merge_ready,w!==void 0&&((typeof w!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(w)||Number.isNaN(Date.parse(w)))&&l("--gh-since takes an ISO-8601 UTC time such as 2026-10-23T11:00:00Z"),k.gh_since=w),T&&(k.from_ask=T),p==="ready"&&e){const N=(await ue(e,t)).asked.filter(he=>he.state==="open").map(he=>he.id);N.length&&l(`${t} has ${N.length===1?"an open question":"open questions"} ${N.join(", ")}; it is ready once the owner has answered ${N.length===1?"it":"them"}`),await Ja(e,t,ee.dir,k)}p!==void 0&&(k.state=p),_e&&(k.install=_e),_e===null&&delete k.install,!$i&&!["building","fixing"].includes(n)&&yt(k,Jt)&&l(`that leaves ${t} In Progress with nothing building and no Next; pass --next "<what happens next>"`),(i!==void 0||T&&!k.ticket&&!k.linear?.length)&&await Mt(e,t,pe,k,i,Ue,ee.dir),await x(ee.file,pe),zt&&await zt();const me=await ki();(b!==void 0||p==="ready"&&e)&&me.push(...await Ft(e,t,"Recorded in the card's notes")),n==="building"&&me.push(...await Ft(e,t,"Acted on: build started")),T&&me.push(...(await ke(e,t,{text:Y})).lines),Qt&&e&&me.push(...(await ke(e,t,{text:Qt,who:ve})).lines);const Gt=k.owner_step&&I.includes(n)?null:Ti({status:n,pr:c??d??u}),Zt=Gt&&await Fi(await ti(e),k,Gt,{...Ue,repo:oe(e,pe)});Zt&&me.push(Zt),(c!==void 0||d!==void 0||u!==void 0||ms.includes(n))&&await hs(ee.dir,k.id,I.includes(n));const mt=T?await ye(e):{};if(U(mt,T)!==void 0&&(delete mt[T],await x(de(e),{links:mt})),!I.includes(n)||te)return{file:ee.file,lines:me};const Vt=await Ka(e,t),yi=new Date().toISOString();for(const{key:N,queued:he}of Vt)await Z(K(e,N),{ts:yi,who:"claude",text:`Unblocked: ${await se(e,t)} is ${n}.`}),he||await Se({dir:e},"card-unblocked",{key:N});return{file:ee.file,lines:[...Vt.map(({key:N,queued:he})=>he?`queued build starts: ${N}`:`unblocked: ${N}`),...me]}}r(Gn,"changeItem");function Zn(e,{size:t,model:i}){for(const[n,a,s]of[["size",t,["small","large"]],["model",i,["opus","sonnet"]]])a!==void 0&&(a===""?delete e[n]:e[n]=s.includes(a)?a:l(`--${n} takes ${s.join(" or ")}, or "" to clear it`))}r(Zn,"setBuildChoice");function Qa({held:e,unheld:t,pickUpAt:i}){return[e,t,i!==void 0].filter(Boolean).length>1&&l("pass one of --held, --unheld and --pick-up-at"),i!==void 0?i===""?null:{until:Vn(i)}:e?{until:null}:t?null:void 0}r(Qa,"holdOf");function Vn(e){const t=typeof e=="string"&&Bi.test(e)?Date.parse(e):NaN;return Number.isNaN(t)&&l('--pick-up-at takes an ISO time such as 2026-11-04T09:00, the Mac\u2019s local time unless it names an offset, or "" to resume the card'),t<=Date.now()&&l(`--pick-up-at ${e} has passed; pass a later time, or --unheld to resume the card now`),new Date(t).toISOString()}r(Vn,"pickUpTime");const Ga=["building","fixing","checking",...I];function Za(e){delete e.held,delete e.pick_up_at}r(Za,"clearHold");function lt(e,t){t?e.held=!0:delete e.held,t?.until?e.pick_up_at=t.until:delete e.pick_up_at,!t&&e.status==="held"&&delete e.status,e.held_at=new Date().toISOString()}r(lt,"setHold");async function Fo(e,t,i,{announce:n=!0}={}){const{source:a,wave:s,item:o}=await O(e,t);if(n){const c=new Date(i).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});await Z(K(e,t),{ts:new Date().toISOString(),who:"claude",text:`Resumed: its hold until ${c} ended.`}),!o.queued_at&&!(await ct(e,L(t).wave,o)).length&&await Se({dir:e},"card-unblocked",{key:t,until:i})}lt(o,null),await x(a.file,s)}r(Fo,"pickUp");async function Va(e,t,i){const n=String(i?.key||""),{wave:a,id:s}=L(n),{source:o,wave:c}=await De(e,a),d={text:"Marked done.",who:"love"},u=c.items.find(h=>h.id===s)||l(`wave "${a}" has no item "${s}"`);if(!(t==="card-done"&&!!u.owner_step)&&["merged","dropped"].includes(u.status))return null;if(t==="card-done")return fe(e,n,{status:u.status==="merged"?"merged":"done",force:!0,ownerDone:!0,...d});const f=i.hold?typeof i.until=="string"?new Date(i.until).toISOString():null:void 0;lt(u,i.hold?{until:f}:null),await x(o.file,c);const p=f&&new Date(f).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});return ke(e,n,{text:i.hold?p?`Held until ${p}.`:"Held.":"Resumed.",who:"love"})}r(Va,"recordOwnerTap");function Xn(e){try{return na(ta(e))}catch(t){return l(t.message)}}r(Xn,"checkSpec");async function Mo(e,t,i,n){const{item:a}=await O(e,t);return!a.owner_step||a.owner_check?.check!==i?null:fe(e,t,{status:a.status==="merged"?"merged":"done",force:!0,ownerDone:!0,text:`Check passed: ${n}. Closed.`})}r(Mo,"passOwnerCheck");async function Uo(e,t,i,n){const{source:a,wave:s,item:o}=await O(e,t);return!o.owner_step||o.owner_check?.check!==i?!1:(o.owner_check.broken=n,await x(a.file,s),await ke(e,t,{text:`The check for "${o.owner_step}" can't run (${n}), so it stopped; Claude is asked to fix it. Done still closes the card.`}),await Se({dir:e},"owner-check-broken",{key:t,check:i,error:n}),!0)}r(Uo,"breakOwnerCheck");async function Yn(e,t,i){const n=[...new Set(String(i).split(",").map(a=>a.trim()).filter(Boolean))];for(const a of n)await O(e,V(t,a));return n}r(Yn,"depList");async function ei(e,t,i,n){if(!String(n).trim())return null;const a=V(t,String(n).trim());a===i&&l("--parent: a card can't be its own Parent");for(let s=a;s;){const o=s===a?await O(e,s):await O(e,s).catch(d=>{if(d instanceof ne)return null;throw d});if(!o)break;const{item:c}=o;c.parent&&V(L(s).wave,c.parent)===i&&l(`--parent: ${a} is a child of ${i}, so it can't be its Parent`),s=c.parent?V(L(s).wave,c.parent):null}return a}r(ei,"parentKey");async function Xa(e,t,i,n){const a=[...new Set(String(n).split(",").map(s=>s.trim()).filter(Boolean).map(s=>V(L(t).wave,s)))];a.includes(t)&&l("--related: a card can't be related to itself");for(const s of a)await O(e,s);return a.length?i.related=a:delete i.related,async()=>{for(const s of await q(e)){const o=await y(s.file,null);let c=!1;for(const d of Array.isArray(o?.items)?o.items:[]){const u=`${s.slug}/${d.id}`;u===t||a.includes(u)||!(d.related||[]).some(w=>V(s.slug,w)===t)||(d.related=d.related.filter(w=>V(s.slug,w)!==t),d.related.length||delete d.related,c=!0)}c&&await x(s.file,o)}}}r(Xa,"setRelated");const oe=r((e,t)=>e&&ge().find(i=>je(i.dir,e))?.github||t.repo,"boardRepoOf");async function Wo(e,t){const{wave:i,item:n}=await O(e,t);Ve(n)||l(`${t} has no PR`);const a=Ze(n,oe(e,i));a.length||l(`${t} has no repo`);const s=n.gh_since||"1970-01-01T00:00:00Z";try{const o=be(await H(e)).github_login||await Qi();return await Promise.all(a.map(async({repo:c,number:d})=>({repo:c,...on(await sn({repo:c,pr:d,since:s}),{pr:d,since:s,me:o})})))}catch(o){l(o.message)}}r(Wo,"prReport");async function Ho(e,t,{replyTo:i,body:n}){const a=i===void 0?"pr comment":"pr reply",s=ln(t)||l(`${a} takes a PR number or owner/repo#<n>`);i!==void 0&&!/^[1-9]\d*$/.test(i)&&l("pr reply takes the id of the review comment it answers");const o=j(n,"--body").trim();(o.startsWith(rn.trim())||o.includes(Zi))&&l(`${a} adds the ${rn.trim()} prefix and the claude-bridge marker itself; pass only your words`);const c=s.repo||oe(A(e),{})||l(`${a} needs a board on GitHub; this board has no repo there`);try{const d=await Gi({repo:c,pr:s.number,replyTo:i,words:o,login:be(await H(e)).github_login});return{lines:[`posted on PR ${s.repo?t:`#${t}`}: ${d}`]}}catch(d){l(d.message)}}r(Ho,"postPR");const ti=r(async e=>En((await H(e)).tickets),"boardSource");async function Ko(e,t,{afterApproval:i,confirmed:n,tapped:a}={}){A(e);const{wave:s,item:o}=await O(e,t);Ve(o)||l(`${t} has no PR`),I.includes(o.status)&&l(`${t} is ${o.status}`);const c=oe(e,s),d=Ze(o,c);d.length||l(`${t} has no repo`);const u=new Date().toISOString();let w;try{w=await Promise.all(d.map(_=>sn({repo:_.repo,pr:_.number,since:u})))}catch(_){l(_.message)}const f=w.map(({view:_})=>_);if(cn(f)){const _=d.filter((D,P)=>f[P].state==="MERGED");return fe(e,t,{status:"merged",text:`PR${_.length>1?"s":""} ${Ie(_,c)} ${_.length>1?"were":"was"} already merged.`})}const p=d.map((_,D)=>({..._,...w[D]})).filter(({view:_})=>_.state==="OPEN"),h=Xe(s,(await H(e)).reviewers||[]).length>0,m=[];let $=!1;for(const _ of p){const{view:D,reviews:P}=_,{failing:E,pending:F}=on(_,{pr:_.number,since:u,me:null}),z=Si({...D,checks:{state:E.length?"fail":F?"pending":"pass",failing:E,pending:F}},{needsApproval:h}),X=P.filter(B=>B.state==="APPROVED").sort((B,Y)=>String(B.submitted_at).localeCompare(String(Y.submitted_at))).at(-1)?.commit_id,M=!!(X&&D.headRefOid&&X!==D.headRefOid);$||=M,M&&i===void 0&&z.push('commits after the approval: pass --after-approval "<why they are trivial>" when they are, else ask the approver to look again'),m.push(...d.length>1?z.map(B=>`${Ie([_],c)} ${B}`):z)}p.length||m.push(d.length>1?"every PR is closed":"PR is closed"),i!==void 0&&!$&&l("--after-approval: no commit came after the approval; drop it");const b=o.manual_steps?.length?n===void 0?null:await Kn(e,n,"--confirmed"):void 0;if(n!==void 0&&b===void 0&&l(`--confirmed: ${t} has no manual steps; drop it`),b===null&&m.push(`manual steps: merge only on the owner's word, with --confirmed "<their words>"`),m.length){const _=`Not merged: ${m.join("; ")}.`;a&&await ke(e,t,{text:_}),l(_)}const v=[];for(const _ of p){const D=await new Promise(P=>{Xt("gh",["pr","merge",String(_.number),"--repo",_.repo,"--squash"],{encoding:"utf8",timeout:12e4},(E,F,z)=>P(E?String(z||E.message).trim().split(`
12
- `)[0]:null))});D&&l(`gh pr merge ${Ie([_],c)} failed: ${D}${v.length?` (merged ${Ie(v,c)} before it)`:""}`),v.push(_)}const S=[Qn(v,c),i!==void 0&&`After the approval: ${j(i,"--after-approval")}`,b&&`The owner's word on the manual steps: "${b}"`];return fe(e,t,{status:"merged",text:S.filter(Boolean).join(" ")})}r(Ko,"mergeCard");async function Jo(e,t){return(await O(e,t)).item.merge_ready||null}r(Jo,"heldMerge");async function zo(e,t){const{source:i,wave:n,item:a}=await O(e,t);return(!a.merge_ready||I.includes(a.status))&&l(`${t} isn't waiting for its Merge`),a.merge_ready.tapped=new Date().toISOString(),await x(i.file,n),a.merge_ready}r(zo,"tapMerge");async function Qo(e,t){const{source:i,item:n}=await O(e,t);return(await Promise.all((await ie(i.dir,n.id)).map(s=>y(s,null)))).filter(s=>s?.worktree?.path).sort((s,o)=>String(o.started).localeCompare(String(s.started)))[0]?.model}r(Qo,"builderModel");async function Mt(e,t,i,n,a,s,o){try{const c=await H(e),d=xt(c.tickets||{source:"internal"}),u=r((h,m)=>h.internal===!0?String(m.id).replace(/^S(\d+)$/,`${d.prefix}-$1`):null,"ownId");a===void 0&&d.source==="internal"&&vt(d,u(i,n))&&(a=u(i,n));let w=0;if(d.source==="internal")for(const h of await q(e)){const m=await y(h.file,{});for(const $ of m.items||[]){const b=[$.ticket,u(m,$)];if(w=Math.max(w,...b.map(v=>vt(d,v)||0)),a!==void 0&&`${h.slug}/${$.id}`!==t&&b.includes(a))throw Object.assign(new ne(`${a} is already the ticket of ${h.slug}/${$.id}`),{held:!0})}}const f=a===void 0&&d.source!=="internal"&&n.plan?await R.readFile(await Te(o,n.plan),"utf8"):n.notes||"",p=await qi(d,{ticket:a,title:n.title,body:f,repo:oe(e,i),next:w+1},s);n.ticket=p.ticket,p.created&&d.source!=="internal"?n.ticket_created=!0:delete n.ticket_created}catch(c){if(c instanceof ne)throw c;l(c.message)}}r(Mt,"assignTicket");const Ne=r((e,t)=>Ge(g.join(e||et(),"tickets"),t,{heartbeat:!0}),"ticketWrite"),fe=r((e,t,i,n)=>i.ticket!==void 0||i.fromAsk!==void 0?Ne(e,()=>Gn(e,t,i,n)):Gn(e,t,i,n),"setItem"),Go=r((e,t,i,n)=>Ne(e,()=>Ya(e,t,i,n)),"addItem");async function Ya(e,t,{title:i,notes:n,deps:a,notesFile:s,ticket:o,pickUpAt:c,parent:d,size:u,model:w},f){const{wave:p,id:h}=t.includes("/")?L(t):{wave:t};h!==void 0&&le(h,"the item id");const{source:m,wave:$}=await De(e,p);h!==void 0&&$.items.some(v=>v.id===h)&&l(`wave "${p}" already has an item "${h}"`);const b={id:h,title:j(i,"--title"),created:new Date().toISOString()};return d!==void 0&&(b.parent=await ei(e,p,null,d)||l("--parent takes a card, such as <wave>/<id>")),n!==void 0&&(b.notes=j(n,"--notes")),Zn(b,{size:u,model:w}),a!==void 0&&(b.deps=await Yn(e,p,a)),s!==void 0&&(await Te(m.dir,s),b.plan=g.normalize(s)),b.status=b.deps?.length?"waiting":"planned",c!==void 0&&lt(b,{until:Vn(c)}),await Mt(e,t,$,b,o,f,m.dir),h===void 0&&(b.id=Ui(b.ticket),$.items.some(v=>v.id===b.id)&&l(`wave "${p}" already has an item "${b.id}"; link ${b.ticket} with item add ${p}/<id> --ticket ${b.ticket}`)),$.items.push(b),await x(m.file,$),{file:m.file,key:`${p}/${b.id}`,lines:[]}}r(Ya,"createItem");const Zo=r((e,{dryRun:t=!1}={},i)=>Ne(A(e),()=>es(e,t,i)),"backfillTickets");async function es(e,t,i){const n=await ti(e)||l("this board has no ticket source yet; pick one in Board settings first"),a=new Set,s=[];for(const w of await q(e)){const f=await y(w.file,null);if(Array.isArray(f?.items)){s.push({entry:w,wave:f});for(const p of f.items)p.ticket&&a.add(p.ticket),f.internal===!0&&n.source==="internal"&&a.add(String(p.id).replace(/^S(\d+)$/,`${n.prefix}-$1`))}}const o=[],c={linked:0,created:0,failed:0},d=r((w,f)=>f.ticket&&!(n.source!=="internal"&&w.internal===!0&&f.ticket===f.id),"ticketed");for(const{entry:w,wave:f}of s)for(const p of f.items){if(d(f,p)||I.includes(p.status))continue;const h=`${w.slug}/${p.id}`,m=[...Mi(n,p.title),...(p.linear||[]).filter($=>vt(n,$))].find($=>n.source!=="internal"||!a.has($));if(t){c[m?"linked":"created"]++,o.push(`${h} would ${m?`link ${m}`:"get a new ticket"}`);continue}try{await Mt(e,h,f,p,m,i,w.dir),await x(w.file,f),a.add(p.ticket),c[m?"linked":"created"]++,o.push(`${h} ${m?"linked":"created"} ${p.ticket}`)}catch($){if(!($ instanceof ne))throw $;c.failed++,o.push(`${h} failed: ${$.message}`)}}const u=t?`would link ${c.linked}, create ${c.created}`:`linked ${c.linked}, created ${c.created}, failed ${c.failed}`;return{lines:[...o,`backfill${t?" (dry run)":""}: ${u}`]}}r(es,"backfill");const Vo=r(e=>Ne(e,async()=>{const t=[];for(const i of await q(e)){const n=await y(i.file,null);if(!Array.isArray(n?.items)||!Array.isArray(n.followups))continue;const a=n.followups.find(d=>n.items.some(u=>u.id===d.id));a&&l(`${i.slug}: follow-up ${a.id} has the id of a card; rename one, then restart the board`);const s=[];for(const{id:d,title:u,from:w,filed:f,done:p,...h}of n.followups){const m=p?e&&(await G(K(e,`${i.slug}/${d}`))).map($=>$.ts).filter(Boolean).sort().pop()||f:null;s.push({id:d,title:u,...f?{created:f}:{},...w?{parent:V(i.slug,w)}:{},status:p?"done":"planned",...m?{status_at:m}:{},...h})}const{followups:o,...c}=n;await x(i.file,{...c,items:[...n.items,...s]}),t.push(`${i.slug}: ${s.length} follow-ups moved to cards (${s.filter(d=>d.status==="done").length} done)`)}return t}),"migrateFollowups"),dt=r(e=>g.join(e,"data","done-archive.json"),"archiveFile"),Ut=r((e,t)=>Ge(g.join(e,"done-archive"),t,{heartbeat:!0}),"archiveWrite"),ut=r(async e=>(await y(dt(e),{cards:[]})).cards||[],"readArchive"),ft=r(e=>`${e.closed_at||""}|${e.key}`,"archiveRank"),ts=r((e,t)=>ft(e)<ft(t)?1:ft(e)>ft(t)?-1:0,"byClosed"),Wt=r(e=>g.join(e,"data","done-archive-count.json"),"archiveCountFile");async function Xo(e){const t=(await y(Wt(e),null))?.count;if(Number.isInteger(t))return t;const i=(await ut(e)).length;return await x(Wt(e),{count:i}),i}r(Xo,"archiveCount");async function Ht(e,t){t.length?await x(dt(e),{cards:t.sort(ts)}):await R.rm(dt(e),{force:!0}),await x(Wt(e),{count:t.length})}r(Ht,"writeArchive");const Yo=r((e,t)=>Ut(e,async()=>{const i=new Map(t.map(f=>[f.key,f])),n=new Date().toISOString(),a=[],s=[];for(const f of await q(e)){const p=await y(f.file,null);if(!Array.isArray(p?.items))continue;const h=p.items.filter(m=>i.has(`${f.slug}/${m.id}`)&&I.includes(m.status));if(h.length){for(const m of h)a.push({...i.get(`${f.slug}/${m.id}`),wave:f.slug,archived_at:n,item:m});s.push([f.file,{...p,items:p.items.filter(m=>!h.includes(m))}])}}if(!a.length)return[];const o=await y(C(e),{items:[]}),c=new Map(a.map(f=>[`item:${f.key}`,f]));for(const f of a)f.questions=(o.items||[]).filter(p=>p.topic===`item:${f.key}`&&p.resolved);const d=await ye(e);for(const f of a)f.asks=f.item.from_ask&&U(d,f.item.from_ask)===void 0?[f.item.from_ask]:[];const u=new Set(a.map(f=>f.key));await Ht(e,[...(await ut(e)).filter(f=>!u.has(f.key)),...a.map(({key:f,wave:p,archived_at:h,closed_at:m,item:$,questions:b,asks:v})=>({key:f,wave:p,archived_at:h,closed_at:m,item:$,questions:b,asks:v}))]),a.some(f=>f.asks.length)&&await x(de(e),{links:{...d,...Object.fromEntries(a.flatMap(f=>f.asks.map(p=>[p,f.key])))}});for(const[f,p]of s)await x(f,p);const w=(o.items||[]).filter(f=>!(c.has(f.topic)&&f.resolved));return w.length!==(o.items||[]).length&&await x(C(e),{...o,items:w}),[...u]}),"archiveCards");async function ns(e,t){return!e||!He(dt(e))?!1:Ut(e,async()=>{const i=await ut(e),n=i.find(f=>f.key===t);if(!n)return!1;const a=(await q(e)).find(f=>f.slug===n.wave),s=a&&await y(a.file,null);if(!Array.isArray(s?.items))return!1;s.items.some(f=>f.id===n.item.id)||await x(a.file,{...s,items:[...s.items,n.item]});const o=await y(C(e),{items:[]}),c=new Set((o.items||[]).map(f=>f.id)),d=(n.questions||[]).filter(f=>!c.has(f.id));d.length&&await x(C(e),{...o,items:[...o.items||[],...d]});const u=await ye(e),w=(n.asks||[]).filter(f=>U(u,f)===t);return w.length&&await x(de(e),{links:Object.fromEntries(Object.entries(u).filter(([f])=>!w.includes(f)))}),await Ht(e,i.filter(f=>f!==n)),!0})}r(ns,"restoreArchived");const ni=["push_tag","no_change"],ii=r(e=>Object.fromEntries(Object.entries(e).filter(([t])=>!ni.includes(t))),"stripQuestion"),ai=r(({summary:e,...t})=>t,"stripItem"),si=r(e=>ni.some(t=>t in e),"holdsDead"),er=r(e=>Ut(e,async()=>{for(const n of await q(e)){const a=await y(n.file,null);Array.isArray(a?.items)&&a.items.some(s=>"summary"in s)&&await x(n.file,{...a,items:a.items.map(ai)})}const t=await y(C(e),null);(t?.items||[]).some(si)&&await x(C(e),{...t,items:t.items.map(ii)});const i=await ut(e);i.some(n=>"card"in n||"summary"in n.item||(n.questions||[]).some(si))&&await Ht(e,i.map(({card:n,...a})=>({...a,...n?{closed_at:a.closed_at||n.sortAt}:{},item:ai(a.item),questions:(a.questions||[]).map(ii)})))}),"stripDeadFields"),oi=r(e=>`lineup-${e}.md`,"lineupNoteFile"),is=r(e=>typeof e=="string"&&/^[a-z0-9-]+$/.test(e)?e:l(`a wave's slug uses only a-z, 0-9 and "-", not "${e}"`),"lineupSlug");async function wt(e,t){for(const i of await q(e)){const n=await y(i.file,null),a=(n?.lineups||[]).find(s=>s.slug===t);if(a)return{source:i,wave:n,lineup:a}}return l(`this board has no wave "${t}"; lineup create makes one`)}r(wt,"findLineup");async function as(e,t){(await H(e)).items!=="waves"&&l(`topic wave:${t} is for a board over ~/.claude/waves; a lineup's triage uses lineup:<slug>`),await De(e,t)}r(as,"triagedWave");function Fe(e,t,i,n){return i.map(a=>{const{wave:s,id:o}=L(a);s!==e.slug&&l(`${a} is not in wave file "${e.slug}"; a wave's cards share one file`),t.items.some(d=>d.id===o)||l(`wave "${s}" has no item "${o}"`);const c=(t.lineups||[]).find(d=>d.slug!==n&&!d.finished_at&&$t(d).flat().includes(o));return c&&l(`${a} is already in the wave "${c.slug}"; lineup remove ${c.slug} ${a} first`),o})}r(Fe,"lineupCards");function ri(e){const t=[e??[]].flat().map(i=>String(i).split(",").map(n=>n.trim()).filter(Boolean));return(!t.length||t.some(i=>!i.length))&&l("--phase takes one phase's cards, as <wave>/<id>,<wave>/<id>, once per phase in build order"),t}r(ri,"phaseKeys");function ci(e,t,i,n){const a=new Set(i.map(s=>`${e.slug}/${s}`));for(const s of i){const o=t.items.find(u=>u.id===s),c=(o.deps||[]).filter(u=>!a.has(V(e.slug,u))),d=n.findIndex(u=>u.includes(s));d>0&&c.push(...n[d-1]),c.length?o.deps=c:delete o.deps}}r(ci,"chain");async function li(e,t,i,n,a){a!==void 0&&await tt(g.join(t.dir,oi(n.slug)),`${j(a,"the note").replace(/\n*$/,`
13
- `)}`),await x(t.file,i);const{tickets:s}=be(await H(e));return{file:t.file,lines:[`order: ${di(i,n.phases,s)}`]}}r(li,"writeLineup");const di=r((e,t,i)=>t.map(n=>n.map(a=>Qe(e,e.items.find(s=>s.id===a)||{id:a},i)).join(", ")).join(" \u2192 "),"orderLine");async function tr(e,t,{title:i,goal:n,phases:a,note:s}){is(t);const o=ri(a);s===void 0&&l("lineup create needs the wave note, as --note <text> or --file <path>");const c=await q(e);c.some(p=>p.slug===t)&&l(`"${t}" is a wave file on this board; pick another slug`);for(const p of c)((await y(p.file,null))?.lineups||[]).some(h=>h.slug===t)&&l(`this board already has a wave "${t}"`);const d=c.find(p=>p.slug===L(o[0][0]).wave)||l(`this board has no wave "${L(o[0][0]).wave}"`),{wave:u}=await De(e,d.slug),w=o.map(p=>Fe(d,u,p,t));new Set(w.flat()).size!==w.flat().length&&l("--phase names a card twice");const f={slug:t,title:j(i,"--title"),goal:j(n,"--goal"),phases:w,created:new Date().toISOString()};return ci(d,u,w.flat(),w),u.lineups=[...u.lineups||[],f],li(e,d,u,f,s)}r(tr,"createLineup");async function nr(e,t,{add:i,after:n,remove:a,phases:s,title:o,goal:c,note:d}){[i,a,s,o,c,d].every(h=>h===void 0)&&l("nothing to change: pass --add, --remove, --phase, --title, --goal, --note or --file"),n!==void 0&&i===void 0&&l("--after goes with --add");const{source:u,wave:w,lineup:f}=await wt(e,t);f.finished_at&&l(`the wave "${t}" is finished`),f.phases=$t(f),delete f.items;const p=f.phases.flat();if(i!==void 0){const[h]=Fe(u,w,[i],t);p.includes(h)&&l(`${i} is already in the wave "${t}"`);const m=n===void 0?f.phases.length:f.phases.findIndex($=>$.includes(Fe(u,w,[n],t)[0]))+1;m===0&&l(`--after ${n} is not in the wave "${t}"`),f.phases.splice(m,0,[h])}if(a!==void 0){const[h]=Fe(u,w,[a],t);p.includes(h)||l(`${a} is not in the wave "${t}"`),p.length===1&&l(`${a} is the wave's last card; lineup finish ${t} ends the wave`),f.phases=f.phases.map(m=>m.filter($=>$!==h)).filter(m=>m.length)}if(s!==void 0){const h=ri(s).map($=>Fe(u,w,$,t)),m=h.flat();(m.length!==p.length||new Set(m).size!==m.length||m.some($=>!p.includes($)))&&l("--phase lists each of the wave's cards once"),f.phases=h}return o!==void 0&&(f.title=j(o,"--title")),c!==void 0&&(f.goal=j(c,"--goal")),ci(u,w,[...new Set([...p,...f.phases.flat()])],f.phases),li(e,u,w,f,d)}r(nr,"changeLineup");async function ir(e,t){const{source:i,wave:n,lineup:a}=await wt(e,t);return a.finished_at=new Date().toISOString(),await x(i.file,n),{file:i.file}}r(ir,"finishLineup");async function ar(e,t,i){const{source:n,wave:a,lineup:s}=await wt(e,t),o=await R.readFile(g.join(n.dir,oi(t)),"utf8").catch(()=>"");return{title:s.title,markdown:`**Goal** ${s.goal}
10
+ `).replace(/<[^>]*>/g,"").replace(/&(?:#(x[\da-f]{1,6}|\d{1,7})|(\w+));/gi,(t,i,n)=>{const a=i&&parseInt(i.replace(/^x/i,""),/^x/i.test(i)?16:10);return i?a<=1114111?String.fromCodePoint(a):t:J(ns,n.toLowerCase())??t})}r(is,"htmlText");function as(e){if(!e||!e.startsWith("/"))return e;const t=new URL(e,"http://board");return/^#item=[^&]+$/.test(t.hash)&&(t.hash=`${t.hash}&reply`),/\/[\w-]+\.html$/.test(t.pathname)&&!t.pathname.endsWith("/index.html")&&t.searchParams.set("from","push"),t.pathname+t.search+t.hash}r(as,"pushUrl");const ss=r((e,t)=>`/${h.basename(e)}/#item=${encodeURIComponent(t)}&reply`,"threadUrl");async function Dn(e,t,i){const n=ts(i);if(!n)return[];const a=Xi(t),s=await aa(a,o=>[n,Xa.exec(o)?.[1]].filter(Boolean).join(" \xB7 "),ss(e,t));return s===null?[]:[`queued push ${a} now reads: ${s}`]}r(Dn,"freshenPush");const An=r(e=>h.join(e,"data","hidden.json"),"hiddenFile"),os=r(async e=>new Set((await $(An(e),{events:[]})).events||[]),"readHidden");let Rn=Promise.resolve();function Wo(e,t,i){me(t,"the event id");const n=Rn.then(async()=>{const a=await os(e);i?a.add(t):a.delete(t),await y(An(e),{events:[...a]})});return Rn=n.catch(()=>{}),n}r(Wo,"setHidden");const Nn=r(e=>h.join(e,"data","read.json"),"readMarksFile"),rs=r(async e=>(await $(Nn(e),{})).cards||{},"readMarks");let En=Promise.resolve();function Uo(e,t,i={}){const n=En.then(async()=>{const a=await rs(e),s=new Date().toISOString(),o=r((d,f)=>String(f||"")>d?f:d,"later"),c=Object.fromEntries([...new Set(t)].sort().map(d=>[d,o(a[d]||s,i[d])]));JSON.stringify(c)!==JSON.stringify(a)&&await y(Nn(e),{cards:c})});return En=n.catch(()=>{}),n}r(Uo,"markRead");const Bt=20*1024*1024,Se=r(e=>h.join(e,"data","uploads"),"uploadsDir"),Ce=r((e,t)=>h.join(Se(e),".meta",`${t}.json`),"uploadMeta"),Ln=/^\d+-[\w.-]+$/,Cn=/^[\w.+-]+\/[\w.+-]+$/,In=r(()=>Object.assign(new Q(`a file can be at most ${Bt/1024/1024} MB`),{status:413}),"tooLarge");async function Ko(e,t,{name:i,type:n,length:a}){if(A(e),a>Bt)throw In();const s=String(i||"").trim().slice(0,200)||"file",o=h.basename(s).replace(/[^\w.-]+/g,"-").replace(/^[.-]+/,"").slice(-80)||"file",c=String(n||"").split(";")[0].trim().toLowerCase(),d=Cn.test(c)?c:"application/octet-stream";await N.mkdir(h.dirname(Ce(e,"x")),{recursive:!0});let f,p;for(let m=Date.now();!p;m++)f=`${m}-${o}`,p=await N.open(h.join(Se(e),f),"wx").catch(g=>g.code==="EEXIST"?null:Promise.reject(g));const l=h.join(Se(e),f);let w=0;try{for await(const m of t){if(w+=m.length,w>Bt)throw In();await p.write(m)}}catch(m){throw await p.close(),await N.rm(l,{force:!0}),m}return await p.close(),await y(Ce(e,f),{name:s,type:d,size:w,at:new Date().toISOString()}),{name:s,url:`uploads/${f}`,path:l,type:d,size:w}}r(Ko,"saveUpload");async function Ho(e,t){if(!Ln.test(t||""))return null;const i=h.join(Se(e),t),n=await N.stat(i).catch(()=>null);if(!n?.isFile())return null;const a=await $(Ce(e,t),{});return{path:i,name:a.name||t,type:Cn.test(a.type||"")?a.type:"application/octet-stream",size:n.size}}r(Ho,"readUpload");const Bn=["github","slack"];async function re(e,t,{text:i,link:n,log:a,who:s="claude",via:o,kind:c}){A(e),String(t).startsWith("ask:")?await Je(e,t.slice(4),"the ask"):await v(e,t),/^[^\n]{1,40}$/.test(s.trim())||u("--who takes claude, love or a reviewer's name"),o!==void 0&&!Bn.includes(o)&&u(`--via takes ${Bn.join(" or ")}`);const d={ts:new Date().toISOString(),who:s.trim(),text:j(i,"--text"),link:z(n,p=>jn(p,"--link")),log:a,via:o,kind:c},f=U(e,t);return await Y(f,d),{file:f,lines:d.who==="claude"&&!o?await Dn(e,t,d.text):[]}}r(re,"appendThread");const he=r(e=>h.join(e,"data","ask-links.json"),"askLinksFile");async function _e(e){return(await $(he(e),{})).links||{}}r(_e,"readAskLinks");async function X(e,t){const{tickets:i}=ge(await M(e)),n=await q(e),a=/^ask:(.+)$/.exec(t)?.[1];if(a===void 0){const o=/^([^/\s]+)\/([^/\s]+)$/.exec(t);if(!o)return t;const c=n.find(p=>p.slug===o[1]),d=c&&await $(c.file,null);if(!d)return o[2];const f=(d.items||[]).find(p=>p.id===o[2]);return tt(d,f||{id:o[2]},i)}const s=e?J(await _e(e),a):void 0;if(s)return X(e,s);for(const o of n){const c=await $(o.file,null),d=(Array.isArray(c?.items)?c.items:[]).find(f=>f.from_ask===a);if(d)return tt(c,d,i)}return`task ${a}`}r(X,"cardName");async function Jo(e,t){const i=(await G(h.join(e,"data","events.jsonl"))).find(n=>n.id===t);return i?.kind==="ask"?X(e,`ask:${t}`):typeof i?.data?.key=="string"?X(e,i.data.key):`the ${i?.kind} event`}r(Jo,"eventCard");async function zo(e,t,i,n){A(e),me(t,"the event id"),(await G(h.join(e,"data","events.jsonl"))).some(c=>c.id===t&&c.kind==="ask")||u(`no ask "${t}" in this site's data/events.jsonl`),await Tt(e,t),await v(e,i);const s={ts:new Date().toISOString(),who:"claude",text:j(n,"--summary")},o=await _e(e);return await y(he(e),{links:{...o,[t]:i}}),await Y(U(e,i),s),he(e)}r(zo,"relateAsk");async function Go(e,t){await Je(e,t,"the ask");const i=await _e(e);return J(i,t)===void 0&&u(`ask "${t}" is not folded into a card`),delete i[t],await y(he(e),{links:i}),he(e)}r(Go,"unfoldAsk");const lt=r(e=>h.join(e,"data","ask-progress.json"),"askProgressFile");async function ut(e){return(await $(lt(e),{})).asks||{}}r(ut,"readAskProgress");async function Tt(e,t){const i=J(await ut(e),t)?.moved;i&&u(`ask "${t}" was moved to /${i.route}; it lives there now`)}r(Tt,"refuseMoved");async function Qo(e,t,i,n){await Je(e,t,"the ask"),await Tt(e,t);const a=await ut(e);return await y(lt(e),{asks:{...a,[t]:{state:i,at:new Date().toISOString(),...n===void 0?{}:{next:j(n,"--next")}}}}),lt(e)}r(Qo,"markAsk");const Tn=[void 0,"waiting"];async function cs(e,t,i){const n=`ask "${t}"`;if(i.some(p=>p.kind==="ask-withdrawn"&&p.data?.id===t&&!p.data?.key))return{why:`${n} was deleted by the owner`};const a=J(await ut(e),t);if(a?.moved)return{why:`${n} was already moved to /${a.moved.route}`};const s=J(await _e(e),t);if(s)return{why:`${n} is folded into ${s}; run ask unfold ${t} first`};const o=[];for(const p of await q(e)){const l=await $(p.file,null);for(const w of Array.isArray(l?.items)?l.items:[])w.from_ask===t&&o.push({key:`${p.slug}/${w.id}`,it:w})}const c=o.find(({it:p})=>it(p)||!Tn.includes(p.status));return c?{why:`${n} became ${c.key}, which has started`}:o.length?{items:o.map(p=>p.key)}:(await Promise.all(["html","json"].map(p=>N.stat(h.join(e,"data","replies",`${t}.${p}`)).then(()=>!0,()=>!1)))).some(Boolean)||!!a||i.some(p=>p.kind==="ask-done"&&p.data?.id===t)||(await G(U(e,`ask:${t}`))).some(p=>(p.who||"claude")==="claude"&&p.kind!=="status")?{why:`${n} is not New: Claude already answered it`}:null}r(cs,"askNotNew");async function ds(e,t,i){const n=/^uploads\/([\w.-]+)$/.exec(i?.url||"")?.[1],a=Ln.test(n||"")?h.join(Se(e),n):null;if(!a||!await N.stat(a).then(d=>d.isFile(),()=>!1))return{name:String(i?.name||n||"file")};await N.mkdir(h.dirname(Ce(t,"x")),{recursive:!0});const s=n.replace(/^\d+-/,"");let o;for(let d=Date.now();o=`${d}-${s}`,!await N.copyFile(a,h.join(Se(t),o),Ji.COPYFILE_EXCL).then(()=>!0,p=>p.code==="EEXIST"?!1:Promise.reject(p));d++);const c=await $(Ce(e,n),null);return c&&await y(Ce(t,o),c),{...i,url:`uploads/${o}`,path:h.join(Se(t),o)}}r(ds,"copyUpload");async function Zo(e,t,i){A(e),me(t,"the event id"),(typeof i!="string"||!i.trim())&&u("ask move needs --to <route>, the board to move it to");const n=await G(h.join(e,"data","events.jsonl")),a=n.find(S=>S.id===t&&S.kind==="ask")||u(`no ask "${t}" in this site's data/events.jsonl`),s=we(),o=s.find(S=>S.route===i)||u(`--to ${i}: no board at /${i} in the hub's manifest; the boards are ${s.map(S=>S.route).join(", ")||"none"}`);ve(o.dir,e)&&u(`--to ${i}: that is this board`);const c=await cs(e,t,n);c?.why&&u(c.why);const d=n.filter(S=>S.kind==="ask-edited"&&S.data?.id===t&&typeof S.data?.text=="string").sort((S,_)=>String(S.ts).localeCompare(String(_.ts))),f=d.at(-1),p=[];for(const S of[...a.data?.files||[],...d.flatMap(_=>_.data.files||[])])p.push(await ds(e,o.dir,S));const l={route:h.basename(e),title:(await M(e)).title,id:t},w=f?f.data.text:a.data?.text||"",m=await pe(o,"ask",{text:w,...p.length?{files:p}:{},from:l}),g={route:i,title:o.title,id:m},b=new Date().toISOString(),P=await ut(e);await y(lt(e),{asks:{...P,[t]:{state:"done",at:b,moved:g}}});const D=`/${i}/#item=${encodeURIComponent(`ask:${m}`)}`;await Y(U(e,`ask:${t}`),{ts:b,who:"claude",text:`Moved to ${o.title}.`,link:D});for(const S of c?.items||[])await se(e,S,{status:"dropped",force:!0,text:`Dropped: its ask moved to ${o.title}.`});return{file:h.join(o.dir,"data","events.jsonl"),lines:[`moved to ${D}`,...(c?.items||[]).map(S=>`dropped: ${S}`)]}}r(Zo,"moveAsk");const qn=r(e=>h.join(e,"data","checked.json"),"checkedFile");async function Vo(e,t,{idle:i}={}){A(e),i&&t!==void 0&&u("pass --every or --idle, not both"),i===void 0&&t===void 0&&(i=!await ls(e));const n=new Date,a=i?null:t===void 0?la.away:/^[1-9]\d{0,3}$/.test(String(t))?Number(t):u("--every takes the minutes between checks, such as 30");return await y(qn(e),i?{at:n.toISOString(),every:null,idle:!0}:{at:n.toISOString(),every:a}),{file:qn(e),every:a,lines:await us()}}r(Vo,"writeChecked");async function Yo(e,t,{state:i,text:n}={}){return A(e),["posted","needs"].includes(i)||u("review record needs --state posted or --state needs"),String(n??"").trim()||u("review record needs the review text, as --text or --file"),Mn(e,await Fn(e,t,"review record"),{state:i,text:n})}r(Yo,"recordReview");async function Fn(e,t,i){/^[1-9]\d{0,6}$/.test(String(t))||u(`${i} takes the PR number, such as 437, not "${t}"`);const n=await $(h.join(e,"data","incoming.json"),{});return{...(n?.prs||[]).find(o=>o.number===Number(t))||(await $(h.join(e,"data","reviews.json"),{}))[t]||u(`PR #${t} is not an incoming PR on this board`),repo:n?.repo||ee(e,{})}}r(Fn,"incomingPR");async function Mn(e,{number:t,title:i,author:n,url:a,touches:s=[],asked:o=!1,head:c},{state:d,text:f,review_url:p}){const l=h.join(e,"data","reviews.json"),w=await $(l,{});return w[t]={number:Number(t),title:i,author:n,url:a,touches:s,asked:o,head:c,state:d,text:f,...p?{review_url:p}:{},at:new Date().toISOString()},await y(l,w),{file:l,lines:[]}}r(Mn,"saveReview");async function Xo(e,t,{words:i,readAt:n}){A(e);const a=await Fn(e,t,"review post"),s=String(i??"").trim()||u("review post needs the review text, as --file"),o=`${Te}Claude review from the ${(await M(e)).title} board`;(s.startsWith(Te.trim())||s.includes("Claude review from")||s.includes(Ct))&&u(`review post adds the ${Te.trim()} header and the claude-bridge marker itself; pass only your words`);const c=a.repo||u("review post needs a board on GitHub; this board has no repo there");Number.isNaN(Date.parse(n))&&u("--read-at takes the time you read the PR, such as 2026-11-05T09:30:00Z");const d=ge(await M(e)).github_login;try{const f=await Pa({repo:c,pr:a.number,since:n});f.length&&u(`PR #${t} got ${f.length===1?"a review":`${f.length} reviews`} after ${n} (${f.map(l=>`${l.login} at ${l.at}`).join(", ")}); reread the PR and review again`);const p=await Oa({repo:c,pr:a.number,head:a.head,body:`${o}
14
11
 
15
- **Order** ${di(a,$t(s),i)}
12
+ ${s}
16
13
 
17
- ${o}`}}r(ar,"readLineupNotes");async function W(e,t,i,n="main"){const{id:a}=L(t);/^[\w-]{1,40}$/.test(n)||l(`--agent takes a name of letters, digits, "_" and "-", not "${n}"`);const s=n==="main"?`${a}.json`:`${a}@${n}.json`;if(i)return g.join(g.resolve(i),"agents",s);const{source:o}=await O(e,t);return g.join(o.dir,"agents",s)}r(W,"builderFile");const ui=r((e,t)=>typeof e=="string"&&/^\d{4}-\d\d-\d\dT/.test(e)&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():l(`${t} takes an ISO time such as 2026-10-23T16:30:00-07:00`),"isoTime"),ss=["reading","building","testing","checking","landing"],fi=80,wi="reading, building, testing, checking or landing";function pi(e,t,i,n){e||l(`${n} needs --site, since the line goes to the item's thread`),t!==void 0&&!ss.includes(t)&&l(`--phase takes ${wi}, not "${t}"`);const a=j(i,n);return a.length>fi&&l(`${n} is ${a.length} characters; the cap is ${fi}. Say it shorter.`),{phase:t,detail:a}}r(pi,"progressLine");const mi=r((e,t,i)=>t?{detail:e.detail}:(e.phase===void 0&&l(`${i} needs --phase ${wi}`),e),"forAgent");async function Kt(e,t,i="main",n,{phase:a,detail:s},o){const c=ze(n),d=c||i==="main"?"":Je(n)||n.kind||i,u=c?Oi[n.kind]:[d,a].filter(Boolean).join(" "),w=u?`${u[0].toUpperCase()}${u.slice(1)}: ${s}`:s,f=K(e,t);(await G(f)).filter(p=>p.kind==="status").pop()?.text!==w&&await Z(f,{ts:o,who:"claude",kind:"status",...a?{phase:a}:{},...c?{planner:!0}:{},text:w})}r(Kt,"statusToThread");const os={prototype:"sonnet",grill:"opus"};async function hi(e,t,{label:i,phase:n,progress:a,dir:s,agent:o="main",kind:c,model:d,eta:u,worktree:w,ownWorktree:f,dispatch:p}){const h=tn();if(h.state==="paused")throw new ne(nn(h));n!==void 0&&a===void 0&&l('--phase goes with --progress "<detail>"');const m=J(a,k=>pi(e,n,k,"--progress")),$=await W(e,t,s,o),b=new Date().toISOString(),v=J(c,k=>/^[\w.-]{1,30}$/.test(k)?k:l("--kind takes a short word such as claude or codex")),S=kt(v),_=d??(v==="opus"||v==="sonnet"?v:void 0),D=["build",...fs].includes(S),P=await y($,null),E=r(k=>["tap","hub"].includes(k?.dispatched)&&!k.done,"tapOpen");if(p==="session"&&E(P))return{file:$,alreadyOpen:!0,lines:[]};o!=="main"&&E(await y(await W(e,t,s),null))&&l(`the Implement tap opened ${t}'s main builder record and no agent has taken it up; run builder start ${t} without --agent first`);const F=P?.dispatched&&!P.done?P:null,z=D&&!s?(await O(e,t)).item:void 0,X=P&&xe(P).length?P:null,M=F&&S==="build"?{kind:kt(F.kind),model:F.model,reason:{tap:"The owner's Build tap picked it.",hub:"The board's pull picked it."}[F.dispatched]??"The session's dispatch picked it."}:D?an({card:z??{}}):null;M&&S!=="build"&&S!==M.kind&&l(`--kind ${S}: ${M.kind} builds now. ${M.reason} Pass --kind ${M.kind}, or --kind build.`);const B=M?M.kind:S,Y=m&&mi(m,ze({kind:B}),"--progress");d!==void 0&&!["opus","sonnet"].includes(d)&&l("--model takes opus or sonnet"),_!==void 0&&B==="codex"&&l("--model is for kind claude; codex needs none");const ve=B==="claude"?Ii():"auto";_!==void 0&&ve!=="auto"&&_!==ve&&l(`--model ${_}: the hub's Claude model is ${ve==="opus"?"Opus":"Sonnet"}. Pass --model ${ve}, or no --model.`);const ae=B==="claude"?_??M?.model??(F&&kt(F.kind)==="claude"?F.model:void 0)??"opus":ze({kind:B})?_??(F?.kind===B?F.model:void 0)??os[B]:void 0,we={label:i===void 0?"Builder":j(i,"--label"),...B?{kind:B}:{},...ae?{model:ae}:{},started:b,...u===void 0?{}:{eta:ui(u,"--eta")},...p?{dispatched:p}:{},...X?{calls:X.calls,...X.verified?{verified:X.verified}:{}}:{}},ce=D&&!s&&![...I,"building","fixing"].includes(z.status),Ue=ce?await fe(e,t,{status:"building"}):{lines:[]};let Q,re=null;const _e=f&&D&&o==="main"&&P?.worktree?.path&&He(P.worktree.path)?P.worktree:null,T=(F??X)?.worktree??_e,ee=w??(D&&o==="main"&&!T?f:void 0);try{if(ee){const k=await ie(g.dirname(g.dirname($)),L(t).id),pt=(await Promise.all(k.filter(te=>te!==$).map(te=>y(te,null)))).filter(te=>te?.worktree?.path&&!te.done).map(te=>te.worktree.path);({remade:re,...Q}=await ee({busy:pt}))}else Q=T}catch(k){throw ce&&await us(e,t,z),k}await x($,Q?{...we,worktree:Q}:we),re&&e&&await ke(e,t,{text:re}),Y&&await Kt(e,t,o,we,Y,b);const pe=await Ft(e,t,"Acted on: builder started");return e&&D&&await Fa(e,t),{file:$,kind:B??null,model:ae??null,reason:M?.reason??null,worktree:Q?.path??null,lines:[...S==="build"?[`kind: ${B}. ${M.reason}`]:[],...Je(we)?[`model: ${Je(we)}`]:[],...e?[`ref: ${await se(e,t)}`]:[],...Q?[`worktree: ${Q.path}`]:[],...re?[re]:[],...Ue.lines,...pe]}}r(hi,"startBuilder");async function rs(e,t,i,n="tap"){try{const{held:a,blockers:s}=await cs(e,t);if(a&&await Va(e,"card-hold",{key:t,hold:!1}),s.length)return await ls(e,t,s);try{const o=await hi(e,t,{kind:"build",worktree:i,dispatch:n});return{key:t,ref:await se(e,t),kind:o.kind,...o.model?{model:o.model}:{},reason:o.reason,worktree:o.worktree}}catch(o){throw a&&await ds(e,t,a),o}}catch(a){if(!(a instanceof ne))throw a;return await Z(K(e,t),{ts:new Date().toISOString(),who:"claude",kind:gt,text:`Couldn't start implementing: ${a.message}`}),null}}r(rs,"startTappedBuild");async function cs(e,t){const i=tn();i.state==="paused"&&l(nn(i));const{item:n}=await O(e,t),a=n.held||n.status==="held"?{held:n.held,status:n.status,pick_up_at:n.pick_up_at,held_at:n.held_at}:null;a&&n.status&&n.status!=="held"&&l("it's held. Unhold it, then tap Implement."),await Hn(e,t)&&l("no take is picked on its prototypes, so it prototypes again. Pick a take from the next round, then tap Implement.");const s=await Promise.all((await ct(e,L(t).wave,n)).map(o=>se(e,o)));return{held:a,blockers:s}}r(cs,"tapRefusals");async function ls(e,t,i){const{source:n,wave:a,item:s}=await O(e,t);return s.queued_at||(s.queued_at=new Date().toISOString(),await x(n.file,a),await Z(K(e,t),{ts:s.queued_at,who:"claude",text:`Implement queued: it starts once ${i.join(", ")} ${i.length===1?"is":"are"} done.`})),{key:t,ref:await se(e,t),queued:i}}r(ls,"queueBuild");async function sr(e,t,i){let n;try{n=await rs(e,t,i)}catch(a){await Z(K(e,t),{ts:new Date().toISOString(),who:"claude",kind:gt,text:`Couldn't start implementing: ${a.message}`}),n=null}if(!n){const{source:a,wave:s,item:o}=await O(e,t);delete o.queued_at,await x(a.file,s)}return n}r(sr,"startQueuedBuild");async function or(e,t,i){const n=await W(e,t),a=await y(n,null),s=new Date().toISOString();a&&!a.done&&await x(n,{...a,done:s});const{source:o,wave:c,item:d}=await O(e,t);d.status==="building"&&(delete d.status,d.status_at=s),await x(o.file,c),await Z(K(e,t),{ts:s,who:"claude",kind:gt,text:`Couldn't start implementing: ${i}`})}r(or,"abandonLaunch");async function rr(e,t,i){const n=await W(e,t),a=await y(n,null);a&&!a.done&&await x(n,{...a,done:new Date().toISOString()}),await ke(e,t,{text:i})}r(rr,"abandonPlanner");async function cr(e,t,i){const n=await y(await W(e,t),null);if(n&&!n.done)return null;const a=await hi(e,t,{kind:i,dispatch:"hub"});return{key:t,kind:i,model:a.model}}r(cr,"startPlanner");async function ds(e,t,i){const{source:n,wave:a,item:s}=await O(e,t);for(const o of Object.keys(i))i[o]===void 0?delete s[o]:s[o]=i[o];await x(n.file,a)}r(ds,"restoreHold");async function us(e,t,i){const{source:n,wave:a,item:s}=await O(e,t);for(const o of["status","status_at"])i[o]===void 0?delete s[o]:s[o]=i[o];await x(n.file,a)}r(us,"restoreStatus");const fs=["codex","claude"];async function lr(e,t){const{item:i}=await O(e,t),{kind:n,model:a,reason:s}=an({card:i});return{lines:[`${[n,a].filter(Boolean).join(" ")}: ${s}`]}}r(lr,"pickBuilder");async function gi(e,t,{dir:i}={}){const{id:n}=L(t),a=g.dirname(await W(e,t,i)),s=await ie(g.dirname(a),n);return(await Promise.all(s.map(c=>y(c,null)))).filter(c=>c?.worktree?.path).sort((c,d)=>String(d.started).localeCompare(String(c.started)))[0]?.worktree??null}r(gi,"recordedWorktree");async function dr(e,t,i,{phase:n,dir:a,agent:s="main",eta:o,clearEta:c}){o!==void 0&&c&&l("pass --eta or --clear-eta, not both");const d=pi(e,n,i,"builder progress"),u=await W(e,t,a,s),w=await y(u,null);(!w?.started||w.done)&&l(`builder progress needs an open builder record on ${t}; run builder start first`);const f=mi(d,ze(w),"builder progress");return o!==void 0&&(w.eta=ui(o,"--eta")),c&&delete w.eta,(o!==void 0||c)&&await x(u,w),await Kt(e,t,s,w,f,new Date().toISOString()),u}r(dr,"builderProgress");const xe=r(e=>(e?.calls||[]).filter(t=>!e.verified||t.at>e.verified.at),"unverifiedCalls");async function ur(e,t,i,{dir:n,agent:a="main"}){const s=j(i,"builder call");/\n/.test(s)&&l("builder call takes one line; record each call on its own");const o=await W(e,t,n,a),c=await y(o,null);return(!c?.started||c.done)&&l(`builder call needs an open builder record on ${t}; run builder start first`),await x(o,{...c,calls:[...c.calls||[],{at:new Date().toISOString(),text:s}]}),o}r(ur,"recordCall");async function Me(e,t){const i=await G(K(e,t)),n=new Map(i.filter(a=>a.kind===Ke.answer).map(a=>[a.ask,a]));return i.filter(a=>a.kind===Ke.ask).map(a=>{const s=n.get(a.ask);return{id:a.ask,agent:a.agent||"main",text:a.text,at:a.ts,answer:s?{text:s.text,at:s.ts}:null,deferred:!!s?.deferred}})}r(Me,"builderAsks");const ws=r(e=>ge().find(t=>je(t.dir,e))??{dir:e},"boardTarget");async function fr(e,t,i,{agent:n="main"}){A(e);const a=j(i,"builder ask");/\n/.test(a)&&l("builder ask takes one line; ask each question on its own");const s=await y(await W(e,t,void 0,n),null);(!s?.started||s.done)&&l(`builder ask needs an open builder record on ${t}; run builder start first`);const o=`ask${(await Me(e,t)).length+1}`;return await Z(K(e,t),{ts:new Date().toISOString(),who:`${Je(s)||s.kind||"Claude"} builder`,kind:Ke.ask,ask:o,agent:n,text:a}),await Se(ws(e),"builder-ask",{key:t,ask:o,agent:n,text:a}),{id:o,lines:[]}}r(fr,"askOrchestrator");async function wr(e,t,i,n,{deferred:a=!1}={}){A(e);const s=j(n,"--text"),o=(await Me(e,t)).find(d=>d.id===i)||l(`no ask "${i}" on ${t}; builder asks ${t} lists them`);o.answer&&l(`${i} on ${t} is already ${o.deferred?"deferred":"answered"}`);const c=new Date().toISOString();if(await Z(K(e,t),{ts:c,who:"claude",kind:Ke.answer,ask:i,...a?{deferred:!0}:{},text:s}),a){const d=await W(e,t,void 0,o.agent),u=await y(d,null);u&&await x(d,{...u,calls:[...u.calls||[],{at:c,text:`Question: ${o.text} (deferred to the owner)`}]})}return{lines:[]}}r(wr,"answerBuilder");async function pr(e,t){A(e);const i=await Me(e,t);return i.length?{lines:i.flatMap(n=>[`${n.id}. ${n.text}`,` ${n.answer?`${n.deferred?"deferred":"answered"}: ${n.answer.text}`:"waiting on the orchestrator"}`])}:{lines:["no asks yet"]}}r(pr,"listAsks");async function ps(e,t,i){const n=t.topic.startsWith("item:")&&!t.topic.startsWith("item:ask:")?t.topic.slice(5):l(`${i}.ask goes on a card's question, topic item:<wave>/<id>`),a=(await Me(e,n)).find(s=>s.id===t.ask)||l(`${i}.ask names no ask "${t.ask}" on ${n}; builder asks ${n} lists them`);a.deferred||l(`${i}.ask names ${a.id}, which the orchestrator ${a.answer?"answered":"has not deferred"}; only a deferred ask goes to the owner`)}r(ps,"checkAskQuestion");async function mr(e,t,{dir:i,agent:n="main"}){const a=await y(await W(e,t,i,n),null),s=a?.calls||[];if(!s.length)return{lines:["no judgment calls recorded"]};const{verified:o}=a,c=xe(a).length?"not verified yet":`verified ${o.at}${o.note?`: ${o.note}`:""}`;return{lines:[...s.map((d,u)=>`${u+1}. ${d.text}`),c]}}r(mr,"listCalls");async function hr(e,t,{dir:i,agent:n="main",note:a}){const s=await W(e,t,i,n),o=await y(s,null);if(xe(o).length||l(`${t} has no unverified judgment calls${n==="main"?"":` from agent ${n}`}; builder calls ${t} lists them`),e){const c=new Set((await y(C(e),{items:[]})).items?.filter(u=>u.topic===`item:${t}`&&u.ask).map(u=>u.ask)),d=(await Me(e,t)).find(u=>u.deferred&&u.agent===n&&!c.has(u.id));d&&l(`${d.id} on ${t} was deferred to the owner; add its question with "ask": "${d.id}" first`)}return await x(s,{...o,verified:{at:new Date().toISOString(),...a===void 0?{}:{note:j(a,"--note")}}}),s}r(hr,"verifyCalls");async function gr(e,t){const{source:i,item:n}=await O(e,t),a=r((o,c)=>[(o.options||[]).find(d=>d.id===c.choice)?.label,c.note].filter(Boolean).join(": ")||"answered","said"),s=(await ue(e,t)).asked.filter(o=>o.ask&&o.answers.length).map(o=>({ask:o.ask,question:o.question,answer:a(o,o.answers.at(-1))}));return{key:t,ref:await se(e,t),title:n.title||t,notes:n.plan?g.join(i.dir,n.plan):null,worktree:(await gi(e,t))?.path??null,answers:s}}r(gr,"briefFacts");async function $r(e){const t=[];for(const i of await q(e)){const n=await y(i.file,null);for(const a of n?.items||[]){if(a.status!=="checking")continue;const s=(await Promise.all((await ie(i.dir,a.id)).map(u=>y(u,null)))).filter(Boolean),o=s.map(u=>u.verified?.at).filter(Boolean).sort().at(-1);if(!o||s.some(u=>xe(u).length))continue;const c=`${i.slug}/${a.id}`;if((await ue(e,c)).asked.some(u=>u.state==="open"))continue;const d=s.filter(u=>u.worktree?.path).sort((u,w)=>String(w.started).localeCompare(String(u.started)))[0];d&&He(d.worktree.path)&&t.push({key:c,verified:o,model:d.model})}}return t}r($r,"landable");async function kr(e,t){const{item:i}=await O(e,t);i.status!=="building"&&l(`${t} is ${i.status||"not started"}; only a card at building has a stopped lander to relaunch`),await fe(e,t,{status:"checking",next:"A lander relaunches to land the verified build"});const n=g.join(e,"data","landers.json"),a=await y(n,{});delete a[t],await R.writeFile(n+".tmp",JSON.stringify(a)+`
18
- `),await R.rename(n+".tmp",n)}r(kr,"relaunchLander");async function yr(e,t,{dir:i}={}){const{id:n}=L(t),a=await ie(g.dirname(g.dirname(await W(e,t,i))),n),s=[];for(const o of a){if(!xe(await y(o,null)).length)continue;const c=g.basename(o,".json").slice(String(n).length+1)||"main";s.push(c==="main"?"":` --agent ${c}`)}s.length&&l(`land: ${t} has judgment calls nobody verified yet; check them with ${s.map(o=>`builder calls ${t}${o}`).join(", ")}, then run ${s.map(o=>`builder verified ${t}${o}`).join(", ")}`)}r(yr,"checkCallsVerified");async function br(e,t,{dir:i,agent:n="main",next:a}){const s=await y(await W(e,t,i,n),null),o=s&&!s.done?xe(s):[];if(!o.length)return null;a!==void 0&&l(`builder done sets ${t}'s Next itself while its record has judgment calls; run it without --next`);const c=o.some(u=>u.text.startsWith("Question:"))?"Answer the builder's questions":"Verify the builder's judgment calls",d=await fe(e,t,{status:"checking",next:c});return{lines:[`handed back: checking, Next "${c}"`,...d.lines]}}r(br,"handBackCalls");async function xr(e,t,{agent:i="main"}){if(i!=="main")return!1;const n=await W(e,t,void 0,i),a=await y(n,null);if(!a?.started||a.done||!a.worktree?.path)return!1;const{id:s}=L(t);for(const o of await ie(g.dirname(g.dirname(n)),s)){const c=o===n?null:await y(o,null);if(!c?.started||c.done||c.kind==="install")continue;const d=g.basename(o,".json").slice(String(s).length+1);l(`builder done would finish ${t} while agent ${d} is still open; run builder done ${t} --agent ${d} first`)}return!0}r(xr,"finishesCard");async function vr(e,t){const{source:i,item:n}=await O(e,t);if(n.status!=="checking"||(await Promise.all((await ie(i.dir,n.id)).map(o=>y(o,null)))).filter(Boolean).some(o=>xe(o).length||o.started&&!o.done&&o.kind!=="install"))return null;const s=await gi(e,t);return!s||!He(s.path)?null:{waits:(await ue(e,t)).asked.filter(o=>o.state==="open").map(o=>o.id)}}r(vr,"verifiedFinish");async function _r(e,t){const{item:i}=await O(e,t);if(i.status!=="done"||i.merged_at)return;const n=String(i.status_at||"");(await G(g.join(e,"data","events.jsonl"))).some(s=>s.kind==="item-message"&&s.data?.key===t&&String(s.ts)>n)&&l(`the owner reopened ${await se(e,t)} with a message; it closes on the owner's Done`)}r(_r,"checkNotReopened");const ms=["checking","done","merged","dropped"];async function ie(e,t){const i=g.join(e,"agents");return(await R.readdir(i).catch(()=>[])).filter(n=>n===`${t}.json`||n.startsWith(`${t}@`)&&n.endsWith(".json")).map(n=>g.join(i,n))}r(ie,"builderFiles");async function hs(e,t,i){const n=new Date().toISOString();for(const a of await ie(e,t)){const s=await y(a,null);if(!s||s.done||s.kind==="install"&&!i)continue;const{eta:o,...c}=s;await x(a,{...c,done:n})}}r(hs,"closeBuilders");async function gs(e,t,{dir:i,agent:n,startedBetween:a,note:s,next:o,requireNext:c=!1}){const d=await W(e,t,i,n),u=await y(d,null);if(!u||u.done)return d;if(a){const E=Date.parse(u.started);if(!(E>=a[0]&&E<=a[1]))return d}const{eta:w,...f}=u,p=new Date().toISOString(),h={...f,done:p,...s?{note:s}:{}},{id:m}=L(t),$=g.dirname(g.dirname(d)),b=await Promise.all((await ie($,m)).map(E=>E===d?h:y(E,null))),v=!b.some(E=>E?.started&&!E.done),S=i?{file:g.join($,"wave.json")}:(await O(e,t)).source,_=await y(S.file,null),D=_?.items?.find(E=>E.id===m);o!==void 0&&(Mn(D||l(`${t} has no item to set --next on`),o,await Fn(e,t)),e&&await Jn(e,t,D,D.next));const P=v&&rt(D);return c&&D&&yt(D,b)&&l(`builder done closes ${t}'s last open builder, which leaves it In Progress with no Next; pass --next "<what happens next>", or hand it back with item set ${t} --status checking or land`),await x(d,h),s&&await Kt(e,t,n,u,{detail:s},p),(P||o!==void 0)&&await x(S.file,_),d}r(gs,"stopBuilder");async function $s(e){const t=[];for(const i of await q(e)){const n=await y(i.file,null);for(const a of n?.items||[])for(const s of await ie(i.dir,a.id)){const o=await y(s,null);if(!o?.started||o.done)continue;const c=g.basename(s,".json");t.push({key:`${i.slug}/${a.id}`,agent:c.slice(String(a.id).length+1)||"main",label:o.label||"Builder",started:o.started})}}return t}r($s,"openBoardBuilders");async function Sr(e){const t=await $s(e);for(const i of t)await gs(e,i.key,{agent:i.agent,note:"Board closed. Builder record stopped; work is kept for reopening."});return t}r(Sr,"closeBoardBuilders");export{ne as BoardError,gn as PUSH_LINE_MAX,Dt as UPLOAD_LIMIT,Vs as WORKING_KINDS,or as abandonLaunch,rr as abandonPlanner,uo as ackHello,Go as addItem,Po as addPrototype,No as addQuestions,$o as addReviewers,_o as addRuleTo,Do as addTopic,wr as answerBuilder,ke as appendThread,Yo as archiveCards,Xo as archiveCount,dt as archiveFile,ft as archiveRank,fr as askOrchestrator,Lo as askedGate,Zo as backfillTickets,H as boardConfig,oe as boardRepoOf,Uo as breakOwnerCheck,gr as briefFacts,Qo as builderModel,dr as builderProgress,se as cardName,nr as changeLineup,yr as checkCallsVerified,Co as checkClose,_r as checkNotReopened,Sr as closeBoardBuilders,tr as createLineup,So as editRuleIn,io as eventCard,bo as fallBackFromLinear,fo as finishHandshake,ir as finishLineup,xr as finishesCard,br as handBackCalls,Jo as heldMerge,kn as hiddenFile,Bo as isFinished,q as itemSources,$r as landable,oi as lineupNoteFile,pr as listAsks,mr as listCalls,Ao as listPrototypes,vo as listRules,oo as markAsk,Xs as markWorking,Ko as mergeCard,Qn as mergedLine,Vo as migrateFollowups,ro as moveAsk,$s as openBoardBuilders,yo as opensPRs,L as parseKey,Mo as passOwnerCheck,lr as pickBuilder,Fo as pickUp,Ho as postPR,Wo as prReport,$a as pushLine,ba as pushUrl,ut as readArchive,ye as readAskLinks,it as readAskProgress,Ct as readBoardRules,Ra as readBoardSettings,jn as readHandshake,va as readHidden,y as readJSON,ar as readLineupNotes,qo as readNotes,st as readPrototypes,no as readUpload,ua as readWorking,ur as recordCall,Va as recordOwnerTap,wa as recordPush,lo as recordReview,gi as recordedWorktree,ao as relateAsk,kr as relaunchLander,Ro as removePrototype,ko as removeReviewers,jo as removeRuleFrom,fa as repliesSincePush,Io as resolveNoteAnswers,Eo as resolveQuestion,Pa as reviewDigest,go as reviewDigestSent,ho as reviewDue,mo as reviewReact,po as reviewSent,Oo as saveBoardRules,Le as saveBoardSettings,to as saveUpload,Ys as sendPush,xo as setBoardSetting,eo as setHidden,fe as setItem,To as setMainInstall,wo as setReviewers,Na as settingsLines,be as settingsOf,Gs as siteDir,la as sitesDir,hi as startBuilder,cr as startPlanner,sr as startQueuedBuild,rs as startTappedBuild,gs as stopBuilder,er as stripDeadFields,qt as takeFile,zo as tapMerge,K as threadFile,qn as topicQuestions,so as unfoldAsk,vr as verifiedFinish,hr as verifyCalls,et as wavesDir,ga as withReplies,co as writeChecked,Zs as writeReply};
14
+ ${Ct}`,login:d});return await Mn(e,a,{state:"posted",text:s,review_url:p}),{lines:[`posted review on PR #${t}: ${p}`]}}catch(f){if(f instanceof Q)throw f;u(f.message)}}r(Xo,"postIncomingReview");async function ls(e){for(const t of await q(e)){const i=await $(t.file,null);if((i?.items||[]).some(n=>!I.includes(n.status)&&Ne(n,ee(e,i)).length))return!0}return!1}r(ls,"hasOpenPR");async function us(){const e=oa(new Date);if(e.hold)return e.count?[`queued pushes held: ${da(e.hold)}`]:[];const t=await sa();return t?[`sent ${t.sent} of ${t.count} queued push${t.count===1?"":"es"}${t.ok?"":"; the rest stay queued"}`]:[]}r(us,"flushAfterTick");const ft=r(e=>h.join(e,"data","handshake.json"),"handshakeFile");async function Wn(e){const t=await $(ft(e),null);if(!t?.hello)return t;const{hello:i,...n}=t;return{...n,ping:n.ping||i}}r(Wn,"readHandshake");async function er(e,t){A(e),me(t,"the event id");const i=(await G(h.join(e,"data","events.jsonl"))).find(a=>a.id===t);i?.kind!=="ping"&&i?.kind!=="hello"&&u(`no ping event "${t}" in this site's data/events.jsonl`);const n=await Wn(e)||{};return n.ping?.id&&n.ping.id!==t&&u(`"${t}" is an older ping; ack the newest, "${n.ping.id}"`),await y(ft(e),{...n,ping:n.ping||{id:t,at:i.ts,session:null},ack:{id:t,at:new Date().toISOString()}}),ft(e)}r(er,"ackPing");async function tr(e){const t=await Wn(e);t&&!t.done_at&&await y(ft(e),{...t,done_at:new Date().toISOString()})}r(tr,"finishHandshake");const qt={name:/^[^\n]{1,40}$/,slack_user:/^U[A-Z0-9]+$/,dm:/^D[A-Z0-9]+$/,github:/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/},We=r((e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase(),"sameName");function Ft(e,t){return Array.isArray(e)||u(`${t} must be a JSON array of reviewers`),e.forEach((i,n)=>{const a=`${t}[${n}]`;Ee(i,Object.keys(qt),a);for(const[s,o]of Object.entries(qt))(typeof i[s]!="string"||!o.test(i[s].trim()))&&u(`${a}.${s} must match ${o}`);e.slice(0,n).some(s=>We(s.name,i.name))&&u(`${t} names "${i.name}" twice`)}),e.map(i=>Object.fromEntries(Object.keys(qt).map(n=>[n,i[n].trim()])))}r(Ft,"checkReviewers");async function Mt(e,t){const{file:i,reviewers:n}=await pt(e,s=>{const o=Ft(t(s.reviewers||[]),"the reviewers");return{set:{reviewers:o},reviewers:o}}),a=[];for(const s of await q(e)){const o=await $(s.file,null);(o?.items||[]).some(c=>!I.includes(c.status))&&(await y(s.file,{...o,reviewers:n}),a.push(`wave ${s.slug}: reviewers copied`))}return{file:i,lines:a}}r(Mt,"writeReviewers");const nr=r((e,t)=>Mt(e,()=>Ft(t,"the reviewer file")),"setReviewers"),Un=r((e,t)=>((typeof e!="string"||!/^\d+(?:\.\d+)?$/.test(e)||Number(e)<=0)&&u("--ts must be a Slack message timestamp"),(typeof t!="string"||!/^D[A-Z0-9]+$/.test(t))&&u("--channel must be a DM channel id"),{ts:e,channel:t}),"linkMessage"),Wt=r((e,t,i)=>Fe(e,t).find(n=>n.name===i)||u(`no reviewer "${i}" on this wave or board`),"reviewerOn"),ir=r((e,t,i,{ts:n,channel:a})=>je(e,async()=>{const s=Un(n,a),{source:o,wave:c,item:d}=await v(e,t);return Wt(c,(await M(e)).reviewers,i),d.review_link_ts={...d.review_link_ts,[i]:s},await y(o.file,c),o.file}),"reviewSent"),ar=r((e,t,i,n)=>je(e,async()=>{(typeof n!="string"||!/^[\w+-]+$/.test(n))&&u("emoji must be a Slack emoji name without colons");const{source:a,wave:s,item:o}=await v(e,t),c=Wt(s,(await M(e)).reviewers,i),d=at(s,o,t,st())[i];d?.ts||u(`no review link recorded for ${i} on ${t}`);const f=J(o.review_link_ts,i),p=typeof f=="object"&&Array.isArray(f?.reactions)?f.reactions:[];return p.includes(n)||(o.review_link_ts={...o.review_link_ts,[i]:{...d,channel:d.channel||c.dm,reactions:[...p,n]}},await y(a.file,s)),a.file}),"reviewReact"),Kn=r(e=>h.join(A(e),"data","review-digests.json"),"digestFile");async function sr(e,t){A(e);const i=await xn.waiting("slack");if(i)return{waiting:i,dms:[],reactions:[],digest:null};const n=await M(e),a=await $(pn,{}),s=st(),o=`board.mjs --site ${h.basename(e)}`,c=r(l=>/^[\w.@-]+$/.test(l)?l:JSON.stringify(l),"arg"),d=[],f=[];for(const l of await q(e)){const w=await $(l.file,{}),m=Fe(w,n.reviewers),g=ee(e,w);for(const b of w.items||[]){const{prs:P,pr:D}=Hn(a,b,g);if(!D||["done","dropped"].includes(b.status))continue;const S=`${l.slug}/${b.id}`,_=at(w,b,S,s);if(b.status==="merged"||b.merged_at||kn(P.map(x=>x.gh)))for(const x of m){const O=J(_,x.name),R=J(b.review_link_ts,x.name);!O?.ts||Array.isArray(R?.reactions)&&R.reactions.includes("git_merged")||f.push({key:S,reviewer:x.name,channel:O.channel||x.dm,ts:O.ts,emoji:"git_merged",record:`${o} review react ${S} ${c(x.name)} git_merged`})}else if(D.gh?.state==="OPEN"&&!D.gh.isDraft){const x=P.filter(O=>O.gh?.state==="OPEN").map(O=>O.url).join(`
15
+ `);for(const O of m.filter(R=>!J(_,R.name)))d.push({key:S,reviewer:O.name,slack_user:O.slack_user,channel:O.dm,text:x,record:`${o} review sent ${S} ${c(O.name)} --ts <ts> --channel ${O.dm}`})}}}const p=await ps(e,t);return{dms:d,reactions:f,digest:p.due?{...p,record:`${o} review digest sent <reviewer> --ts <ts> --channel <dm> --items <key,key>`}:null}}r(sr,"reviewDue");function fs(e,t){return new Promise((i,n)=>{Pt("gh",["pr","view",String(t),"--repo",e,"--json","latestReviews"],{encoding:"utf8",timeout:2e4},(a,s,o)=>{if(a)return n(new Q(`gh could not read ${e}#${t}'s reviews: ${String(o||a.message).trim().split(`
16
+ `)[0]}`));i(Object.fromEntries((JSON.parse(s).latestReviews||[]).map(c=>[c.author?.login,c.state])))})})}r(fs,"ghLatestReviews");async function or(e,t,i,{fetch:n,reviews:a=fs}={}){A(e);const s=Na({fetch:n})||u(La),o=j(i,"what changed"),{wave:c,item:d}=await v(e,t),f=at(c,d,t,st()),p=Fe(c,(await M(e)).reviewers).filter(m=>f[m.name]?.ts);if(!p.length)return{lines:[`no reviewer waiting on a sent link for ${t}`]};const l=await Promise.all(Ne(d,ee(e,c)).map(m=>a(m.repo,m.number))),w=p.filter(m=>!l.length||l.some(g=>g[m.github]!=="APPROVED"));for(const m of w)try{await s.post({channel:f[m.name].channel||m.dm,thread_ts:f[m.name].ts,text:`\u{1F916} Updated: ${o}`})}catch(g){throw g instanceof Ea&&u(`Updated to ${m.name} on ${t} not sent: ${g.message}`),g}return{lines:[w.length?`\u{1F916} Updated sent to ${w.map(m=>m.name).join(", ")} on ${t}`:`every reviewer on ${t} has approved; nothing sent`]}}r(or,"reviewUpdated");function Hn(e,t,i){const n=Ne(t,i).map(a=>({...a,url:Ra(a),gh:J(e.prs,Aa(a))||null}));return{prs:n,pr:n[Da(n.map(a=>a.gh))]||null}}r(Hn,"cachedPRs");async function ps(e,{now:t=new Date}={}){A(e);const i=await M(e),n=await $(pn,{}),a=st(),s=new Map;for(const p of await q(e)){const l=await $(p.file,{}),w=Fe(l,i.reviewers);for(const g of w)s.has(g.name)||s.set(g.name,{name:g.name,slack_user:g.slack_user,dm:g.dm,items:[]});const m=ee(e,l);for(const g of l.items||[]){if(["merged","done","dropped"].includes(g.status))continue;const b=`${p.slug}/${g.id}`,{pr:P}=Hn(n,g,m),D=P?.gh;if(D?.state!=="OPEN"||D.isDraft||D.failing?.length||D.reviewDecision==="APPROVED")continue;const S=at(l,g,b,a);for(const _ of w){const x=J(S,_.name),O=x?.ts?(t.getTime()-Number(x.ts)*1e3)/864e5:null;s.get(_.name).items.push({key:b,title:g.title,pr:P.number,url:P.url,sent_ts:x?.ts||null,...O>2?{days_old:Math.floor(O)}:{}})}}}const{date:o,morning:c}=vn(t),d=await $(Kn(e),{}),f=await xn.waiting("slack");return{date:o,due:!f&&c&&d.last_date!==o,...f?{waiting:f}:{},reviewers:[...s.values()].filter(p=>p.items.length)}}r(ps,"reviewDigest");async function rr(e,t,{ts:i,channel:n,items:a},{now:s=new Date}={}){const o=Un(i,n),c=[...new Set(j(a,"--items").split(",").map(p=>p.trim()))],d=await M(e);for(const p of c){const{wave:l}=await v(e,p);Wt(l,d.reviewers,t)}const f=Kn(e);return nt(f,async()=>{const p=await $(f,{});return await y(f,{last_date:vn(s).date,digests:[...p.digests||[],{reviewer:t,dm:o.channel,ts:o.ts,items:c,reactions:[]}]}),f})}r(rr,"reviewDigestSent");function cr(e,t){const i=Ft(Array.isArray(t)?t:[t],"the reviewer file");return Mt(e,n=>[...n.map(a=>i.find(s=>We(s.name,a.name))||a),...i.filter(a=>!n.some(s=>We(a.name,s.name)))])}r(cr,"addReviewers");function dr(e,t){return Mt(e,i=>{const n=t.filter(a=>!i.some(s=>We(s.name,a)));return n.length&&u(`this board has no reviewer ${n.map(a=>`"${a}"`).join(", ")}`),i.filter(a=>!t.some(s=>We(a.name,s)))})}r(dr,"removeReviewers");const ws=r(()=>h.join(Ot.homedir(),".claude","kickflip","settings.json"),"hubSettingsFile"),Ut=r(e=>{try{return e()}catch(t){throw t instanceof Ta&&u(t.message),t}},"ruleCall"),Kt=r(async e=>Sn(await $(h.join(e,"board.json"),{})),"readBoardRules");let Jn=Promise.resolve();function pt(e,t){const i=Jn.then(async()=>{const n=h.join(A(e),"board.json"),a=await $(n,{}),{set:s,...o}=t(a);return await y(n,{...a,...s}),{file:n,...o}});return Jn=i.catch(()=>{}),i}r(pt,"writeBoardJSON");const zn=r((e,t)=>pt(e,i=>{const n=Ut(()=>t(Sn(i)));return{set:{rules:n.rules},...n}}),"writeBoardRules");function lr(e,t){const i=Object.keys(t||{}),[n]=i,a=typeof t?.[n]=="string"?t[n].trim():null;return(i.length!==1||!["add","remove"].includes(n)||!Ha(a))&&u("Send add or remove with one login, like name@github."),pt(e,s=>{const o=Ka(s),c=n==="remove"?o.filter(d=>d!==a):o.includes(a)?o:[...o,a];return{set:{share:c},share:c}}).then(({share:s})=>({share:s}))}r(lr,"saveBoardShare");const Gn=r(e=>typeof e=="string"&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(e),"validGithubLogin"),Qn=r(e=>{try{return e?Et(e):null}catch{return null}},"storedTickets"),Ht=r(e=>Number.isInteger(e)&&e>=1&&e<=99,"validCap"),Jt=["max_implementers","max_planners"],ge=r(e=>{const t=Qn(e?.tickets);return{auto_merge:e?.auto_merge===!0,auto_build:e?.auto_build===!0,auto_pull:e?.auto_pull===!0,max_implementers:Ht(e?.max_implementers)?e.max_implementers:Gi,max_planners:Ht(e?.max_planners)?e.max_planners:Qi,auto_triage:e?.auto_triage===!0,auto_review:e?.auto_review===!0,idle_notification:e?.idle_notification===!0,skip_draft:e?.skip_draft===!0,prs:e?.prs!==!1,...t?{tickets:t}:{},...Gn(e?.github_login)?{github_login:e.github_login}:{}}},"settingsOf");async function ms(e){return ge(await $(h.join(A(e),"board.json"),{}))}r(ms,"readBoardSettings");const ur=r((e,t)=>!!e?.github&&!e.local&&t.prs,"opensPRs");async function Ue(e,t){Ee(t,["auto_merge","auto_build","auto_pull","max_implementers","max_planners","auto_triage","auto_review","idle_notification","skip_draft","prs","tickets","github_login"],"the settings"),Object.keys(t).length||u("the settings name nothing to change"),t={...t};for(const[i,n]of Object.entries(t))if(i==="tickets"){try{t.tickets=Et(n)}catch(s){u(s.message)}t.tickets.source==="linear"&&!ka()&&u(ga);const a=t.tickets.source==="github"&&e?we().find(s=>ve(s.dir,e)):null;a&&!a.github&&u("GitHub issues need the board\u2019s repo on GitHub, and this board\u2019s repo isn\u2019t; pick internal or linear")}else i==="github_login"?n===""||n===null?t.github_login=void 0:Gn(n)||u("github_login must be a GitHub login"):Jt.includes(i)?Ht(n)||u(`${i} must be a whole number from 1 to 99`):dt(n,i);if(t.prs===!1){const i=e?we().find(n=>ve(n.dir,e)):null;i?.github&&!i.local&&!(await Ca(i.owner?.repo)).pushMain&&u("Merge lands each card on main and pushes it, so turn on Push main after a land first")}return pt(e,i=>{const n=ge(i),a=ge({...i,...t});return{set:t,settings:a,changed:Object.keys(t).filter(s=>JSON.stringify(n[s])!==JSON.stringify(a[s]))}})}r(Ue,"saveBoardSettings");async function fr(){if($a().set)return[];const e=[];for(const t of we()){if((await ms(t.dir)).tickets?.source!=="linear")continue;const{settings:i}=await Ue(t.dir,{tickets:{source:"internal"}});await pe(t,"settings",{tickets:i.tickets}),e.push(`/${t.route} fell back to internal tickets: Hub has no Linear key`)}return e}r(fr,"fallBackFromLinear");async function pr(e,t,i){const n=String(t).replace(/-/g,"_"),a=["auto_merge","auto_build","auto_pull","max_implementers","max_planners","auto_triage","auto_review","idle_notification","skip_draft","prs","github_login","tickets"];if(a.includes(n)||u(`no board setting "${t}"; settings are ${a.map(c=>c.replace(/_/g,"-")).join(", ")}`),n==="tickets"){let c;try{c=JSON.parse(i)}catch{u('settings set tickets takes the source as JSON, such as {"source":"github"}')}const{file:d,settings:f}=await Ue(e,{tickets:c});return{file:d,lines:hs({tickets:f.tickets})}}if(n==="github_login"){const{file:c,settings:d}=await Ue(e,{github_login:i});return{file:c,lines:[`github-login ${d.github_login||"unset"}`]}}if(Jt.includes(n)){const{file:c,settings:d}=await Ue(e,{[n]:/^\d+$/.test(i)?Number(i):i});return{file:c,lines:[`${t} ${d[n]}`]}}["on","off"].includes(i)||u(`settings set ${t} takes on or off, not "${i}"`);const{file:s,settings:o}=await Ue(e,{[n]:i==="on"});return{file:s,lines:[`${t} ${o[n]?"on":"off"}`]}}r(pr,"setBoardSetting");const hs=r(e=>Object.entries(e).map(([t,i])=>`setting ${t.replace(/_/g,"-")} ${t==="tickets"?JSON.stringify(i):t==="github_login"||Jt.includes(t)?i:i?"on":"off"}`),"settingsLines");async function zt(e,t,i){const n=t?Ut(()=>i(ot())):await zn(e,i);return t&&Ut(()=>Ua(n.rules)),{file:t?ws():n.file,lines:[`id ${n.rule.id}`]}}r(zt,"changeRules");async function Zn(e,t,i){const n=r(o=>o.map(c=>c.id),"ids");i||A(e);const[a,s]=i?[n(ot()),e?n(await Kt(e)):[]]:[n(await Kt(e)),n(ot())];a.includes(t)||u(`no ${i?"hub":"board"} rule "${t}"${s.includes(t)?`; it is a ${i?"board":"hub"} rule, so ${i?"drop":"pass"} --hub`:""}`)}r(Zn,"checkRuleId");async function wr(e){const t=r(i=>n=>`${i} ${n.id} ${n.by==="claude"?"claude":"owner"} ${n.text}`,"line");return{lines:[...ot().map(t("hub")),...e?(await Kt(e)).map(t("board")):[]]}}r(wr,"listRules");function mr(e,{text:t,hub:i=!1,by:n}){return i||A(e),zt(e,i,a=>qa(a,{text:t,by:n}))}r(mr,"addRuleTo");async function hr(e,t,{text:i,hub:n=!1}){return await Zn(e,t,n),zt(e,n,a=>Fa(a,t,i))}r(hr,"editRuleIn");async function gr(e,t,{hub:i=!1}){return await Zn(e,t,i),zt(e,i,n=>Ma(n,t))}r(gr,"removeRuleFrom");const $r=r((e,t,i)=>zn(e,n=>Wa(n,t,i)),"saveBoardRules");async function kr(e,{id:t,title:i,summary:n}){A(e);const a=await $(L(e),{topics:[],items:[]}),s=a.topics||[];return s.some(o=>o.id===j(t,"the topic id"))&&u(`topic "${t}" already exists`),s.push({id:t.trim(),title:j(i,"--title"),...n===void 0?{}:{summary:j(n,"--summary")}}),await y(L(e),{...a,topics:s,items:a.items||[]}),L(e)}r(kr,"addTopic");const Vn=["quiet","info","notice","danger","success"];function gs(e,t){if(e.diagram===void 0!=(e.practice===void 0)&&u(`${t} needs diagram and practice together`),e.diagram===void 0)return;const i=e.diagram;(!Array.isArray(i)||!i.length)&&u(`${t}.diagram must be a non-empty array of rows`),i.forEach((n,a)=>{(!Array.isArray(n)||!n.length||n.length>4)&&u(`${t}.diagram[${a}] must be a row of 1 to 4 boxes`),n.forEach((s,o)=>{const c=`${t}.diagram[${a}][${o}]`;Ee(s,["text","tone","to"],c),j(s.text,`${c}.text`),z(s.tone,d=>Vn.includes(d)?d:u(`${c}.tone takes ${Vn.join(", ")}`)),z(s.to,d=>Array.isArray(d)&&a+1<i.length&&d.every(f=>Number.isInteger(f)&&f>=0&&f<i[a+1].length)?d:u(`${c}.to must list boxes of the next row by index`))})}),(!Array.isArray(e.practice)||!e.practice.length)&&u(`${t}.practice must be a non-empty array of lines`),e.practice.forEach((n,a)=>j(n,`${t}.practice[${a}]`))}r(gs,"checkDiagram");function $s(e,t){(!Array.isArray(e)||!e.length)&&u(`${t}.options must be a non-empty array`);const i=new Set;e.forEach((n,a)=>{const s=`${t}.options[${a}]`;Ee(n,["id","label","recommended","detail","diagram","practice"],s),gs(n,s),i.has(j(n.id,`${s}.id`))&&u(`${t} has two options with id "${n.id}"`),i.add(n.id),j(n.label,`${s}.label`).startsWith(`${n.id}. `)&&u(`${s}.label starts with "${n.id}. ", but the page adds the option letter itself`),z(n.recommended,o=>dt(o,`${s}.recommended`)),z(n.detail,o=>typeof o=="string"?o:u(`${s}.detail must be text`))}),e.filter(n=>n.recommended).length>1&&u(`${t} recommends more than one option`)}r($s,"checkOptions");function ks(e,t,i){Ee(e,["option","card","answer"],i),t.some(n=>n.id===j(e.option,`${i}.option`))||u(`${i}.option names no option "${e.option}"`),j(e.card,`${i}.card`),j(e.answer,`${i}.answer`)}r(ks,"checkSuggested");const Ke=r(e=>h.join(e,"data","prototypes.json"),"prototypesFile"),Gt=r((e,t,i)=>h.join(e,"public","prototypes",t,`${i}.js`),"takeFile");async function wt(e){const t=e?(await $(Ke(e),{})).prototypes:null;return Array.isArray(t)?t:[]}r(wt,"readPrototypes");const ys=r(e=>typeof e=="string"&&/^[a-z0-9-]+$/.test(e)?e:u(`a prototype topic uses only a-z, 0-9 and "-", not "${e}"`),"prototypeTopic");function bs(e){const t=/^([^:]*):(.*)$/s.exec(e);(!t||!/^[A-Z]$/.test(t[1]))&&u(`--take takes KEY:"Label" with KEY one capital letter, not "${e}"`);const i=j(t[2],`--take ${t[1]}'s label`);return/^[A-Z]\.\s/.test(i)&&u(`--take ${t[1]}'s label starts with "${i.slice(0,3)}"; the take pill shows the label alone, so drop the letter`),{key:t[1],label:i}}r(bs,"prototypeTake");const Ie=r(e=>/^prototype-(.+)\.html$/.exec(h.posix.basename(String(e||"").split(/[?#]/)[0]))?.[1],"pageTopic");async function yr(e,{topic:t,title:i,card:n,takes:a=[]}){A(e),ys(t),j(i,"--title"),a.length||u('prototype add needs a --take KEY:"Label" for each take');const s=a.map(bs),o=s.find((f,p)=>s.findIndex(l=>l.key===f.key)!==p);o&&u(`--take ${o.key} is given twice`),n!==void 0&&await v(e,n);const c=await wt(e);c.some(f=>f.topic===t)&&u(`prototype ${t} is already recorded; run prototype rm ${t} first, or pick another topic`),await N.stat(h.join(e,"public",`prototype-${t}.html`)).then(()=>!0,()=>!1)&&u(`public/prototype-${t}.html is a hand-written page that questions may link; pick another topic`);const d={topic:t,title:i.trim(),...n===void 0?{}:{card:n},takes:s,at:new Date().toISOString()};return await y(Ke(e),{prototypes:[...c,d]}),{file:Ke(e),lines:[`page prototype-${t}.html`,...s.map(f=>`take ${f.key} ${Gt(e,t,f.key)}`)]}}r(yr,"addPrototype");async function br(e){A(e);const t=await wt(e);return{lines:t.length?t.map(i=>`${i.topic} \xB7 ${i.title} \xB7 ${i.takes.map(n=>`${n.key}: ${n.label}`).join(", ")}${i.card?` \xB7 ${i.card}`:""}`):["no prototypes recorded"]}}r(br,"listPrototypes");async function xr(e,t){A(e);const i=await wt(e);i.some(s=>s.topic===t)||u(`no prototype "${t}" is recorded`);const a=((await $(L(e),{items:[]})).items||[]).filter(s=>!s.resolved&&Ie(s.url)===t).map(s=>s.id);return a.length&&u(`prototype ${t} backs open question ${a.join(", ")}; resolve ${a.length===1?"it":"them"} first`),await y(Ke(e),{prototypes:i.filter(s=>s.topic!==t)}),Ke(e)}r(xr,"removePrototype");async function xs(e,t,i){const n=t.url?.split(/[?#]/)[0];if(!n||!h.posix.basename(n).startsWith("prototype-"))return;const a=h.posix.basename(n),s=t.url.split("#")[0].split("?").slice(1).join("?"),o=`${i}.url`;new URLSearchParams(s).get("q")!==t.id&&u(`${o} must be ${a}?q=${t.id} so the pill can pick`);const c=Ie(n),d=(await wt(e)).find(w=>w.topic===c);d||u(`${o} names ${a}, which is not a recorded prototype; record it with board.mjs prototype add ${c} --title "\u2026" --take A:"\u2026", then write its take files`);const f=d.takes.map(w=>w.key),p=t.options.map(w=>w.id),l=p.map(w=>f.indexOf(w));l.some((w,m)=>w<0||m>0&&w<l[m-1])&&u(`${i}.options ids ${p.join(", ")} must be a non-empty subset of ${a}'s takes, in take order: ${f.join(", ")}`);for(const w of f)await N.stat(Gt(e,c,w)).then(m=>m.isFile(),()=>!1)||u(`${o} take ${w} has no file yet; write ${Gt(e,c,w)}`)}r(xs,"checkPrototype");async function vr(e,t){A(e);const i=Array.isArray(t)?t:[t];i.length||u("the question file is empty");const n=await $(L(e),{topics:[],items:[]}),a=n.items||[],s=await $(Me(e),{}),o=new Set([...a,...Object.values(s).flat()].map(p=>p.id)),c=new Set((n.topics||[]).map(p=>p.id));for(const[p,l]of i.entries()){const w=`question ${l?.id??p+1}`;Ee(l,["id","topic","source","question","context","url","urgent","options","round_of","reask_of","ask","suggested","prototype_gate"],w),o.has(me(l.id,`${w}.id`))&&u(`question id "${l.id}" is already used`),o.add(l.id),j(l.topic,`${w}.topic`),l.topic.startsWith("item:ask:")?await Je(e,l.topic.slice(9),`${w}.topic`):l.topic.startsWith("item:")?await v(e,l.topic.slice(5)):l.topic.startsWith("lineup:")?await xt(e,l.topic.slice(7)):l.topic.startsWith("wave:")?await Us(e,l.topic.slice(5)):c.has(l.topic)||u(`topic "${l.topic}" is not declared; add it with: topic add ${l.topic} --title <t>`),j(l.question,`${w}.question`);for(const m of["source","context"])z(l[m],g=>j(g,`${w}.${m}`));z(l.url,m=>jn(m,`${w}.url`)),z(l.urgent,m=>dt(m,`${w}.urgent`)),$s(l.options,w),z(l.prototype_gate,m=>vs(m,l,w)),z(l.suggested,m=>ks(m,l.options,`${w}.suggested`)),await xs(e,l,w),l.ask!==void 0&&await eo(e,l,w),z(l.round_of,m=>{const g=a.find(b=>b.id===m);g||u(`${w}.round_of names no question "${m}" in owner.json`),g.topic!==l.topic&&u(`${w}.round_of names ${m} on topic ${g.topic}; a round stays on its question's topic, ${l.topic}`),Ie(l.url)||u(`${w}.round_of needs a url on a recorded prototype, prototype-<topic>.html?q=${l.id}`)}),z(l.reask_of,m=>{const g=a.find(b=>b.id===m);g||u(`${w}.reask_of names no question "${m}" in owner.json`),g.topic!==l.topic&&u(`${w}.reask_of names ${m} on topic ${g.topic}; a re-ask stays on its question's topic, ${l.topic}`),g.resolved||u(`${w}.reask_of names ${m}, which is not resolved; only a resolved question is asked again`)})}const d=[],f=[];for(const p of i){const l=p.topic.startsWith("item:")&&!p.topic.startsWith("item:ask:")?p.topic.slice(5):null,w=l&&await Yn(e,l);w&&((s[l]||=[]).push(p),f.push(p),d.push(`staged: ${p.id} waits for ${l}'s ${w} to finish; the card's staged questions then publish together`))}return f.length&&await y(Me(e),s),f.length===i.length?{file:Me(e),lines:d,staged:f.length}:Xn(e,n,a,i.filter(p=>!f.includes(p)),d)}r(vr,"addQuestions");async function Yn(e,t){const{source:i}=await v(e,t);for(const n of await te(i.dir,C(t).id)){const a=await $(n,null);if(a?.started&&!a.done&&Re(a))return a.kind}return null}r(Yn,"runningPlanner");async function mt(e,t){if(!e||await Yn(e,t))return;const i=await $(Me(e),{});if(!i[t])return;const{[t]:n,...a}=i,s=await $(L(e),{topics:[],items:[]});await Xn(e,s,s.items||[],n,[]),await y(Me(e),a)}r(mt,"publishStaged");async function Xn(e,t,i,n,a){const{answers:s,requests:o}=await He(e),c=new Date().toISOString(),d=[],f=[];for(const l of n.filter(w=>w.round_of))l.round=Nt(i.find(w=>w.id===l.round_of))+1,$e(t,[l.round_of],`Followed by prototype round ${l.round}`,c),f.push(l.round_of);for(const l of n.filter(w=>w.reask_of))$e(t,[l.reask_of],`Asked again as ${l.id}`,c),f.push(l.reask_of);for(const l of n){const w=Ie(l.url),m=i.filter(b=>b.topic===l.topic).map(b=>Ae(b,s,o)),g=l.topic.startsWith("item:")?ei(m):[];for(const b of m)g.includes(b.id)?($e(t,[b.id],`Followed by ${l.id}`,c),f.push(b.id)):!b.resolved&&w&&Ie(b.url)===w&&($e(t,[b.id],`Replaced by ${l.id}`,c),d.push(b.id))}const p={...t,topics:t.topics||[],items:[...i,...n.map(l=>({...l,asked_at:c}))]};return await y(L(e),p),{file:L(e),lines:[...a,...d.map(l=>`replaced: ${l}`),...f.map(l=>`resolved: ${l}`)]}}r(Xn,"publishQuestions");function vs(e,t,i){dt(e,`${i}.prototype_gate`),e&&((!t.topic.startsWith("item:")||t.topic.startsWith("item:ask:"))&&u(`${i}.prototype_gate goes on a card's topic, item:<wave>/<id>`),t.options?.map(n=>n.id).join()!=="yes,no"&&u(`${i}.prototype_gate takes exactly the options yes and no, in that order`))}r(vs,"checkGate");async function Sr(e,t){const i=await $(L(e),{topics:[],items:[]}),n=new Map((i.items||[]).map(o=>[o.id,o])),a=new Set(t.map(o=>n.get(String(o.id))?.topic).filter(o=>o?.startsWith("item:"))),s=[];for(const o of t){const c=n.get(String(o.id));if(!c?.prototype_gate||!["yes","no"].includes(o.choice)||($e(i,[c.id],`Prototype round: ${o.choice}. The board moved the card on.`),await y(L(e),i),o.choice==="no"))continue;a.delete(c.topic);const d=c.topic.slice(5);(await v(e,d)).item.state==="grilling"&&(await se(e,d,{state:"prototyping"}),await re(e,d,{text:"You asked for a prototype round, so the board moved the card to prototyping."}),s.push(d))}for(const o of a){const{asked:c}=await Zt(e,o),d=c.find(p=>p.prototype_gate&&p.answers.at(-1)?.choice==="no"),f=o.slice(5);if(!(!d||c.some(p=>p.state==="open")||(await v(e,f)).item.state!=="grilling"))try{await se(e,f,{state:"ready"}),await re(e,f,{text:"No prototype round, and nothing left to answer, so the board moved the card to ready."})}catch(p){if(!(p instanceof Q))throw p;await re(e,f,{text:`No prototype round, but the card isn't ready yet: ${p.message}`})}}return{prototype:s}}r(Sr,"settleGates");function ei(e){return e.filter(t=>t.state==="answered").map(t=>t.id)}r(ei,"answeredOnClaude");function $e(e,t,i,n=new Date().toISOString()){for(const a of e.items||[])t.includes(a.id)&&Object.assign(a,{resolved:i,resolved_at:n})}r($e,"setResolved");async function Qt(e,t,i,n){return $e(t,i,n),await y(L(e),t),L(e)}r(Qt,"markResolved");async function _r(e,t,i){A(e);const n=await $(L(e),{topics:[],items:[]}),a=(n.items||[]).find(p=>p.id===t);a||u(`no question "${t}" in owner.json`);const{answers:s,requests:o}=await He(e),c=Ae(a,s,o);if(c.state==="resolved")return L(e);c.state==="requested"&&u(`${t} waits on the prototype the owner asked for; question add with round_of ${t} resolves it`);const d=j(i,"--note");Ie(a.url)&&Ss(n,a,s);const f=await Qt(e,n,[t],d);return await ai(e,a.topic),f}r(_r,"resolveQuestion");async function jr(e,t,i,n=[]){A(e);const[a,...s]=[...new Set(t)];a||u("question move takes the ids of the questions to merge"),await v(e,i);const o=[i,...n];new Set(o).size!==o.length&&u("question move names a card twice");for(const l of n)await v(e,l);const c=await $(L(e),{topics:[],items:[]}),{answers:d,requests:f}=await He(e);for(const l of[a,...s]){const w=(c.items||[]).find(g=>g.id===l)||u(`no question "${l}" in owner.json`),{state:m}=Ae(w,d,f);m!=="open"&&u(`${l} is ${m}; question move takes open questions`)}for(const[l,w]of n.entries()){const{item:m}=await v(e,w),g=[...m.deps||[],o[l]].join(",");await se(e,w,{deps:g,relate:i})}const p=await X(e,i);return Object.assign(c.items.find(l=>l.id===a),{topic:`item:${i}`}),$e(c,s,`Duplicate of ${p}'s question ${a}`),await y(L(e),c),L(e)}r(jr,"moveQuestions");async function Or(e,t){const i=t.filter(({choice:a,note:s})=>!a&&String(s||"").trim()).map(a=>a.id),n=i.length?await $(L(e),{topics:[],items:[]}):null;n?.items?.some(a=>i.includes(a.id))&&($e(n,i,"Answered with a note"),await y(L(e),n))}r(Or,"resolveNoteAnswers");function Ss(e,t,i){const n=Nt(t),a=e.items.filter(s=>s.topic===t.topic&&Nt(s)===n).map(s=>Ae(s,i));ea(a,n)||u(`${t.id} is in prototype round ${n}, which no pick has settled yet; a pick settles it`)}r(Ss,"roundSettled");async function He(e){const t=await G(h.join(e,"data","events.jsonl"));return{answers:await Promise.all(t.filter(n=>n.kind==="owner-answer").map(async n=>{const a=await Promise.all(["html","json"].map(s=>N.stat(h.join(e,"data","replies",`${n.id}.${s}`)).then(o=>o.isFile(),()=>!1)));return{...n,reply:n.reply||a.some(Boolean)}})),requests:t.filter(n=>n.kind==="prototype-request")}}r(He,"ownerEvents");async function Zt(e,t){const i=await $(L(e),{topics:[],items:[]}),{answers:n,requests:a}=await He(e),s=(i.items||[]).filter(o=>o.topic===t).map(o=>Ae(o,n,a));return{owner:i,asked:s}}r(Zt,"topicQuestions");const ke=r((e,t)=>Zt(e,`item:${t}`),"cardQuestions"),Vt=r((e,t,i)=>ti(e,`item:${t}`,i),"resolveAnswered");async function ti(e,t,i){if(!e)return[];const{owner:n,asked:a}=await Zt(e,t),s=ei(a);return s.length&&await Qt(e,n,s,i),await ai(e,t),s.map(o=>`resolved: ${o}`)}r(ti,"resolveAnsweredOn");const ni=r(async(e,t)=>!!e&&(await ke(e,t)).asked.some(i=>i.state==="open"),"hasOpenQuestion");function ii(e,t,i){e.next=j(t,"--next"),i?e.next_on_questions=!0:delete e.next_on_questions}r(ii,"setNext");async function ai(e,t){const i=t.startsWith("item:")&&!t.startsWith("item:ask:")?t.slice(5):null;if(!i)return;let n;try{n=await v(e,i)}catch(c){if(c instanceof Q)return;throw c}const{source:a,wave:s,item:o}=n;o.next_on_questions&&((await ke(e,i)).asked.some(c=>c.state!=="resolved")||(delete o.next,delete o.next_on_questions,await y(a.file,s)))}r(ai,"clearWaitedNext");async function _s(e,t){const{source:i,wave:n,item:a}=await v(e,t);a.next===void 0&&a.next_on_questions===void 0||(delete a.next,delete a.next_on_questions,await y(i.file,n))}r(_s,"clearNext");async function si(e,t,i,n){if(!e)return async()=>[];const{owner:a,asked:s}=await ke(e,t),o=s.filter(d=>d.state==="open").map(d=>d.id);o.length&&!n&&u(`${i}: ${t} has ${o.length===1?"an open question":"open questions"} ${o.join(", ")} with no answer yet; pass --force to close the card and resolve ${o.length===1?"it":"them"} too`);const c=s.filter(d=>d.state!=="resolved").map(d=>d.id);return async()=>(c.length&&await Qt(e,a,c,"Closed with the card"),c.map(d=>`resolved: ${d}`))}r(si,"closeQuestions");async function Pr(e,t,i,n,a){await v(e,t),j(i,"--text"),z(n,s=>j(s,"--owner-step")),z(a,s=>gi(s)),await si(A(e),t,"land",!1)}r(Pr,"checkClose");async function oi(e,t){const i=await $(L(e),{items:[]}),{answers:n,requests:a}=await He(e);return Vi((i.items||[]).map(s=>Ae(s,n,a)),t)}r(oi,"unpickedPrototype");const js=r(e=>e.length>120?`${e.slice(0,119)}\u2026`:e,"clip"),Os={ask:"text","ask-edited":"text","item-message":"text","owner-answer":"note"};async function ri(e,t,i){const n=j(t,i).replace(/\s+/g," ");return(await G(h.join(e,"data","events.jsonl"))).map(s=>String(s.data?.[Os[s.kind]]??"").replace(/\s+/g," ").toLowerCase()).some(s=>s.includes(n.toLowerCase()))||u(`${i} must quote the owner's words in an ask, card message or answer note on this board`),n}r(ri,"ownerQuote");async function Dr(e,t,i){return A(e),i===void 0&&u(`only the owner's Serve / Build and the hub's Auto-build start a card run; pass --asked "<the owner's words>" quoting where the owner asked for ${t}'s run`),`Running at the owner's ask: "${await ri(e,i,"--asked")}"`}r(Dr,"askedGate");async function Je(e,t,i="--from-ask"){return me(t,i),(await G(h.join(A(e),"data","events.jsonl"))).some(a=>a.id===t&&a.kind==="ask")?t:u(`no ask "${t}" in this site's data/events.jsonl`)}r(Je,"checkAsk");const I=["done","merged","dropped"],Ar=r(async(e,t)=>I.includes((await v(e,t)).item.status),"isFinished"),ci=["ready","grilling","prototyping"],Ps=/^mark (?:it |this |the card )?ready\b/i;function ht(e){return["building","fixing"].includes(e?.status)?(delete e.status,e.status_at=new Date().toISOString(),!0):!1}r(ht,"clearBuildingStatus");function Ds(e,t,i){const n=[].concat(t).map(o=>yn(o)||u(`--pr takes a PR number or owner/repo#<n>, not "${o}"`)),a=r((o,c)=>o.number===c.number&&(o.repo||i||null)===(c.repo||i||null),"same"),s=bn(e);for(const o of n)s.some(c=>a(c,o))||s.push(o);delete e.pr,e.prs=s}r(Ds,"addPRs");const W=r((e,t)=>String(t).includes("/")?String(t):`${e}/${t}`,"depKey");async function ze(e,t,i){const n=(i.deps||[]).map(s=>W(t,s)),a=await Promise.all(n.map(s=>v(e,s).then(({item:o})=>o,()=>null)));return n.filter((s,o)=>a[o]&&!I.includes(a[o].status))}r(ze,"unfinishedDeps");async function As(e,t){const i=[];for(const n of await q(e)){const a=await $(n.file,null);for(const s of Array.isArray(a?.items)?a.items:[])![void 0,"waiting","held"].includes(s.status)||!(s.deps||[]).some(o=>W(n.slug,o)===t)||(await ze(e,n.slug,s)).length||i.push(`${n.slug}/${s.id}`)}return i}r(As,"unblockedBy");async function di(e,t,i,n){const a=new Set(n.match(/[\w-]+(?:\.[\w-]+)*(?:\/[\w-]+(?:\.[\w-]+)*)*/g)||[]),s=new Set((i.deps||[]).map(o=>W(C(t).wave,o)));for(const o of await q(e)){const c=await $(o.file,null);for(const d of c?.items||[]){const f=`${o.slug}/${d.id}`;if(f===t||s.has(f)||I.includes(d.status))continue;[d.id,tt(c,d)].flatMap(l=>[l,`${o.slug}/${l}`]).some(l=>a.has(l))&&u(`--next names unfinished card ${f}; add it with --deps`)}}}r(di,"checkNextDeps");function li(e,t){const i="a builder starts from it, so pass";t.size||u(`${e} has no size; ${i} --size small or large with --state ready`),t.plan||u(`${e} has no notes file; ${i} --notes-file <file.md> with --state ready`)}r(li,"checkSizeAndNotes");async function Rs(e,t,i,n){li(t,n);const a=await N.readFile(await Ge(i,n.plan),"utf8"),s=(await ke(e,t)).asked.filter(o=>o.answers.length&&!a.includes(o.id)&&!(o.prototype_gate&&!o.answers.at(-1).note)).map(o=>o.id);s.length&&u(`${t}'s notes leave out the answered question${s.length===1?"":"s"} ${s.join(", ")}; record each answer in ${n.plan}, naming its id, before it is ready`)}r(Rs,"checkNotesComplete");async function Ge(e,t){const i=r(a=>u(`a notes file is a .md file inside ${e}, named relative to it: "${t}" ${a}`),"bad");(typeof t!="string"||!t.trim())&&i("is empty"),(h.isAbsolute(t)||t.split(/[\\/]/).includes(".."))&&i("leaves the folder"),h.extname(t).toLowerCase()!==".md"&&i("is not a .md file");const n=await N.realpath(h.resolve(e,t)).catch(()=>i("does not exist"));return n.startsWith(await N.realpath(e)+h.sep)||i("leaves the folder"),n}r(Ge,"planPath");async function Rr(e,t){const{source:i,wave:n,item:a}=await v(e,t);if(a.plan)return{wave:n,item:a,markdown:await N.readFile(await Ge(i.dir,a.plan),"utf8")};if(typeof a.notes=="string"&&a.notes.trim())return{wave:n,item:a,markdown:a.notes};u(`${t} has no notes`)}r(Rr,"readNotes");function ui({install:e,installSha:t,installLabel:i,clearInstall:n}){if(e===void 0)return(t!==void 0||i!==void 0)&&u("--install-sha and --install-label go with --install <url>"),n?null:void 0;n&&u("pass --install or --clear-install, not both");let a;try{a=new URL(String(e).trim())}catch{a=null}(!a||!["https:","itms-services:"].includes(a.protocol))&&u(`--install takes an https:// or itms-services:// URL, not "${e}"`),a.protocol==="itms-services:"&&!(a.searchParams.get("action")==="download-manifest"&&/^https:\/\//.test(a.searchParams.get("url")||""))&&u("--install: an itms-services:// URL needs ?action=download-manifest&url=https://\u2026/manifest.plist");const s=t===void 0?void 0:/^[0-9a-f]{7,40}$/i.test(t)?t.toLowerCase():u(`--install-sha takes a commit sha of 7 to 40 hex digits, not "${t}"`);return{url:String(e).trim(),...i===void 0?{}:{label:j(i,"--install-label")},built_at:new Date().toISOString(),...s?{sha:s}:{}}}r(ui,"installOf");async function Nr(e,{install:t,installSha:i}){const n=ui({install:t,installSha:i});n||u("main set needs --install <url>");const a=h.join(A(e),"data","main.json");return await y(a,{install:n}),{file:a,lines:["main install set"]}}r(Nr,"setMainInstall");const fi=r((e,t)=>e.length?`Merged PR${e.length>1?"s":""} ${qe(e,t)}.`:"Merged.","mergedLine");function Ns(e,t,i,n,a,s){return n==="merged"?a??(i.status==="merged"?null:fi(bn(i),s)):(a===void 0&&e&&u(`--status ${n} needs --text "<what was done or left>", which becomes ${t}'s last thread line`),a??null)}r(Ns,"closingLine");async function pi(e,t,{ticket:i,status:n,clearStatus:a,next:s,clearNext:o,pr:c,pushed:d,mergeReady:f,ghSince:p,fromAsk:l,state:w,held:m,unheld:g,pickUpAt:b,notesFile:P,deps:D,parent:S,related:_,relate:x,unrelate:O,install:R,installSha:Z,installLabel:ne,clearInstall:F,title:B,size:oe,model:ie,force:ce,text:ae,who:le,ownerStep:de,ownerDone:vt,check:V},ue){n!==void 0&&a&&u("pass --status or --clear-status, not both"),_!==void 0&&(x!==void 0||O!==void 0)&&u("pass --related, or --relate and --unrelate, not both"),w!==void 0&&!ci.includes(w)&&u("--state takes ready, grilling or prototyping"),ce&&!I.includes(n)&&u(`--force goes with --status ${I.join(", ")}`),l!==void 0&&I.includes(n)&&u("--from-ask opens a card; close it in another call"),ae!==void 0&&j(ae,"--text"),de!==void 0&&j(de,"--owner-step");const ye=V===void 0||V===""?V:gi(V);ae!==void 0&&l===void 0&&!I.includes(n)&&u(`--text goes with --from-ask or --status ${I.join(", ")}`),l!==void 0&&ae===void 0&&u(`--from-ask needs --text "<first line>", the item's first thread line after the ask`),s!==void 0&&o&&u("pass --next or --clear-next, not both"),typeof s=="string"&&!s.trim()&&([s,o]=[void 0,!0]);const Pe=Es({held:m,unheld:g,pickUpAt:b}),be=ui({install:R,installSha:Z,installLabel:ne,clearInstall:F});[n,a,s,o,c,d,f,p,l,w,Pe,P,D,S,_,x,O,be,B,oe,ie,i,de,V].every(E=>E===void 0||E===!1)&&u("nothing to set: pass --status, --clear-status, --next, --clear-next, --pr, --pushed, --gh-since, --from-ask, --state, --held, --unheld, --pick-up-at, --notes-file, --deps, --parent, --related, --relate, --unrelate, --install, --clear-install, --title, --size, --model, --ticket or --check");const H=l===void 0?void 0:await Je(e,l);H&&await Tt(e,H);const{source:T,wave:xe,item:k}=await v(e,t);H&&k.from_ask&&k.from_ask!==H&&u(`${t} came from ask "${k.from_ask}", so ask "${H}" can't be its from-ask; to fold it in: item relate-ask ${H} ${t} --summary "<line>"`),H&&w===void 0&&!k.state&&u("--from-ask files a card, which reads New until it has a state: pass --state ready, grilling or prototyping");const Mi=k.status,on=I.includes(k.status);de!==void 0&&on&&u(`${t} is already ${k.status}, so its ticket closed; an owner step goes on the command that finishes the card: land --owner-step, or builder done before the merge`),de!==void 0&&(k.owner_step=j(de,"--owner-step")),(vt||n==="dropped")&&delete k.owner_step,ye!==void 0&&!k.owner_step&&u(`--check goes with an owner step, which ${t} doesn't have: pass --owner-step "<the step>" with it on builder done or land`),ye&&(k.owner_check={check:ye,since:k.owner_check?.check===ye?k.owner_check.since:new Date().toISOString()}),(ye===""||!k.owner_step)&&delete k.owner_check;const rn=await Promise.all((await te(T.dir,k.id)).map(E=>$(E,null))),Wi=Rt(k,rn);if(P!==void 0&&(await Ge(T.dir,P),k.plan=h.normalize(P)),B!==void 0&&(k.title=j(B,"--title")),wi(k,{size:oe,model:ie}),D!==void 0){const E=await $i(e,C(t).wave,D);E.length?k.deps=E:delete k.deps}if(S!==void 0){const E=await ki(e,C(t).wave,t,S);E?k.parent=E:delete k.parent}let St=_===void 0?null:await Is(e,t,k,_);if(x!==void 0&&(k.related=[...new Set([...(k.related||[]).map(E=>W(C(t).wave,E)),...await $t(e,t,x,"--relate")])]),O!==void 0&&(St=await Bs(e,t,k,await $t(e,t,O,"--unrelate"))),Pe!==void 0&&gt(k,Pe),n==="building"&&(k.held||k.status==="held")&&u(k.pick_up_at?`${t} is held until ${k.pick_up_at}, when the board resumes it; start it early only with item set ${t} --unheld`:`${t} is held; start it only once the owner resumes it, with item set ${t} --unheld`),n==="planned"&&u("--status planned is gone: an unstarted card has no status. Clear it with --clear-status"),n!==void 0&&(k.status=fn.includes(n)?n:u(`--status takes ${fn.join(", ")}`)),(Ls.includes(n)||c!==void 0||d!==void 0||f!==void 0)&&Cs(k),n==="building"){const E=await ze(e,C(t).wave,k);E.length&&u(`${t} is blocked by ${E.join(", ")}; start it once ${E.length===1?"that is":"those are"} done or merged`)}(n==="building"||I.includes(n))&&delete k.implement_at;const Ve=n==="building"&&e?await oi(e,t):null;Ve&&u(`${t} has no take picked: the owner's answer to ${Ve.id} picks none${Ve.note?` ("${js(Ve.note)}")`:""}, so it prototypes again: draw the next round from that note, or grill when the note asks a question, and build once a take is picked`);const Ui=I.includes(n)?await si(e,t,`--status ${n}`,ce):async()=>[],cn=I.includes(n)?Ns(e,t,{...k,status:Mi},n,ae,ee(e,xe)):null;if(a&&delete k.status,(n!==void 0||a)&&(k.status_at=new Date().toISOString()),s!==void 0&&(ii(k,s,await ni(e,t)),await di(e,t,k,k.next)),o&&(delete k.next,delete k.next_on_questions),n==="building"&&s===void 0&&k.next_on_questions&&(delete k.next,delete k.next_on_questions),(c!==void 0||d!==void 0||f!==void 0)&&!k.review_since&&(k.review_since=new Date().toISOString()),c!==void 0&&(Ds(k,c,ee(e,xe)),ht(k)),d!==void 0){we().find(E=>ve(E.dir,A(e)))?.remote||u("--pushed is for a board whose repo is a plain git remote; on GitHub, open a PR and pass --pr"),it(k)&&u(`${t} has a PR; its PR says when it merges`);try{ya(d)}catch{u("--pushed takes the name of the branch you pushed")}k.pushed={branch:d,at:new Date().toISOString()},k.branch=d,ht(k)}if(f!==void 0&&(k.merge_ready={branch:f,at:new Date().toISOString()},k.branch=f,ht(k)),I.includes(n)&&delete k.merge_ready,p!==void 0&&((typeof p!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(p)||Number.isNaN(Date.parse(p)))&&u("--gh-since takes an ISO-8601 UTC time such as 2026-10-23T11:00:00Z"),k.gh_since=p),H&&(k.from_ask=H),w==="ready"&&e){const E=(await ke(e,t)).asked.filter(jt=>jt.state==="open").map(jt=>jt.id);E.length&&u(`${t} has ${E.length===1?"an open question":"open questions"} ${E.join(", ")}; it is ready once the owner has answered ${E.length===1?"it":"them"}`),await Rs(e,t,T.dir,k)}w!==void 0&&(k.state=w,delete k.unfiled),k.state==="ready"&&Ps.test(k.next??"")&&u(`${t} would read ready with Next "${k.next}", which asks for the state it is already in; pass --next with what happens next, or --clear-next`);const Ye=w==="ready"&&e&&k.implement_at?await Promise.all((await ze(e,C(t).wave,k)).map(E=>X(e,E))):null;Ye?.length&&delete k.implement_at,be&&(k.install=be),be===null&&delete k.install,!Wi&&!["building","fixing"].includes(n)&&Rt(k,rn)&&u(`that leaves ${t} In Progress with nothing building and no Next; pass --next "<what happens next>"`),(i!==void 0||H&&!k.ticket&&!k.linear?.length)&&await Yt(e,t,xe,k,i,ue,T.dir),await y(T.file,xe),St&&await St();const fe=await Ui();(P!==void 0||w==="ready"&&e)&&fe.push(...await Vt(e,t,"Recorded in the card's notes")),n==="building"&&fe.push(...await Vt(e,t,"Acted on: build started")),Ye&&fe.push(Ye.length?(await Ti(e,t,Ye)).line:`released: ${t} starts building now`),H&&fe.push(...(await re(e,t,{text:ae})).lines),cn&&e&&fe.push(...(await re(e,t,{text:cn,who:le})).lines);const dn=k.owner_step&&I.includes(n)?null:pa({status:n,pr:c??d??f}),ln=dn&&await wa(await bi(e),k,dn,{...ue,repo:ee(e,xe)});ln&&fe.push(ln),(c!==void 0||d!==void 0||f!==void 0||qi.includes(n))&&await Fi(T.dir,k.id,I.includes(n)),(c!==void 0||d!==void 0||f!==void 0||qi.includes(n))&&await mt(e,t);const _t=H?await _e(e):{};if(J(_t,H)!==void 0&&(delete _t[H],await y(he(e),{links:_t})),!I.includes(n)||on)return{file:T.file,lines:fe};const un=await As(e,t),Ki=new Date().toISOString();for(const E of un)await Y(U(e,E),{ts:Ki,who:"claude",text:`Unblocked: ${await X(e,t)} is ${n}.`}),await pe({dir:e},"card-unblocked",{key:E});return{file:T.file,lines:[...un.map(E=>`unblocked: ${E}`),...fe]}}r(pi,"changeItem");function wi(e,{size:t,model:i}){for(const[n,a,s]of[["size",t,["small","large"]],["model",i,["opus","sonnet"]]])a!==void 0&&(a===""?delete e[n]:e[n]=s.includes(a)?a:u(`--${n} takes ${s.join(" or ")}, or "" to clear it`))}r(wi,"setBuildChoice");function Es({held:e,unheld:t,pickUpAt:i}){return[e,t,i!==void 0].filter(Boolean).length>1&&u("pass one of --held, --unheld and --pick-up-at"),i!==void 0?i===""?null:{until:mi(i)}:e?{until:null}:t?null:void 0}r(Es,"holdOf");function mi(e){const t=typeof e=="string"&&ua.test(e)?Date.parse(e):NaN;return Number.isNaN(t)&&u('--pick-up-at takes an ISO time such as 2026-11-04T09:00, the Mac\u2019s local time unless it names an offset, or "" to resume the card'),t<=Date.now()&&u(`--pick-up-at ${e} has passed; pass a later time, or --unheld to resume the card now`),new Date(t).toISOString()}r(mi,"pickUpTime");const Ls=["building","fixing","checking",...I];function Cs(e){delete e.held,delete e.pick_up_at}r(Cs,"clearHold");function gt(e,t){t?e.held=!0:delete e.held,t?.until?e.pick_up_at=t.until:delete e.pick_up_at,!t&&e.status==="held"&&delete e.status,e.held_at=new Date().toISOString()}r(gt,"setHold");async function Er(e,t,i,{announce:n=!0}={}){const{source:a,wave:s,item:o}=await v(e,t);if(n){const c=new Date(i).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});await Y(U(e,t),{ts:new Date().toISOString(),who:"claude",text:`Resumed: its hold until ${c} ended.`}),(await ze(e,C(t).wave,o)).length||await pe({dir:e},"card-unblocked",{key:t,until:i})}gt(o,null),await y(a.file,s)}r(Er,"pickUp");async function hi(e,t,i){const n=String(i?.key||""),{wave:a,id:s}=C(n),{source:o,wave:c}=await Le(e,a),d={text:"Marked done.",who:"love"},f=c.items.find(m=>m.id===s)||u(`wave "${a}" has no item "${s}"`);if(!(t==="card-done"&&!!f.owner_step)&&["merged","dropped"].includes(f.status))return null;if(t==="card-done")return se(e,n,{status:f.status==="merged"?"merged":"done",force:!0,ownerDone:!0,...d});const l=i.hold?typeof i.until=="string"?new Date(i.until).toISOString():null:void 0;gt(f,i.hold?{until:l}:null),await y(o.file,c),i.hold&&(await Fi(o.dir,s,!1),await mt(e,n));const w=l&&new Date(l).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});return re(e,n,{text:i.hold?w?`Held until ${w}.`:"Held.":"Resumed.",who:"love"})}r(hi,"recordOwnerTap");function gi(e){try{return Ba(Ia(e))}catch(t){return u(t.message)}}r(gi,"checkSpec");async function Lr(e,t,i,n){const{item:a}=await v(e,t);return!a.owner_step||a.owner_check?.check!==i?null:se(e,t,{status:a.status==="merged"?"merged":"done",force:!0,ownerDone:!0,text:`Check passed: ${n}. Closed.`})}r(Lr,"passOwnerCheck");async function Cr(e,t,i,n){const{source:a,wave:s,item:o}=await v(e,t);return!o.owner_step||o.owner_check?.check!==i?!1:(o.owner_check.broken=n,await y(a.file,s),await re(e,t,{text:`The check for "${o.owner_step}" can't run (${n}), so it stopped; Claude is asked to fix it. Done still closes the card.`}),await pe({dir:e},"owner-check-broken",{key:t,check:i,error:n}),!0)}r(Cr,"breakOwnerCheck");async function $i(e,t,i){const n=[...new Set(String(i).split(",").map(a=>a.trim()).filter(Boolean))];for(const a of n)await v(e,W(t,a));return n}r($i,"depList");async function ki(e,t,i,n){if(!String(n).trim())return null;const a=W(t,String(n).trim());a===i&&u("--parent: a card can't be its own Parent");for(let s=a;s;){const o=s===a?await v(e,s):await v(e,s).catch(d=>{if(d instanceof Q)return null;throw d});if(!o)break;const{item:c}=o;c.parent&&W(C(s).wave,c.parent)===i&&u(`--parent: ${a} is a child of ${i}, so it can't be its Parent`),s=c.parent?W(C(s).wave,c.parent):null}return a}r(ki,"parentKey");async function $t(e,t,i,n){const a=t.split("/")[0],s=[...new Set(String(i).split(",").map(o=>o.trim()).filter(Boolean).map(o=>W(a,o)))];s.includes(t)&&u(`${n}: a card can't be related to itself`);for(const o of s)await v(e,o);return s}r($t,"relatedKeys");const yi=r((e,t,i)=>async()=>{for(const n of await q(e)){const a=await $(n.file,null);let s=!1;for(const o of Array.isArray(a?.items)?a.items:[]){const c=`${n.slug}/${o.id}`;c===t||!i(c)||!(o.related||[]).some(d=>W(n.slug,d)===t)||(o.related=o.related.filter(d=>W(n.slug,d)!==t),o.related.length||delete o.related,s=!0)}s&&await y(n.file,a)}},"dropLinksTo");async function Is(e,t,i,n){const a=await $t(e,t,n,"--related");return a.length?i.related=a:delete i.related,yi(e,t,s=>!a.includes(s))}r(Is,"setRelated");function Bs(e,t,i,n){const a=(i.related||[]).filter(s=>!n.includes(W(C(t).wave,s)));return a.length?i.related=a:delete i.related,yi(e,t,s=>n.includes(s))}r(Bs,"unrelateCards");const ee=r((e,t)=>e&&we().find(i=>ve(i.dir,e))?.github||t.repo,"boardRepoOf");async function Ir(e,t){const{wave:i,item:n}=await v(e,t);it(n)||u(`${t} has no PR`);const a=Ne(n,ee(e,i));a.length||u(`${t} has no repo`);const s=n.gh_since||"1970-01-01T00:00:00Z";try{const o=ge(await M(e)).github_login||await _a();return await Promise.all(a.map(async({repo:c,number:d})=>({repo:c,...$n(await gn({repo:c,pr:d,since:s}),{pr:d,since:s,me:o})})))}catch(o){u(o.message)}}r(Ir,"prReport");async function Br(e,t,{replyTo:i,body:n}){const a=i===void 0?"pr comment":"pr reply",s=yn(t)||u(`${a} takes a PR number or owner/repo#<n>`);i!==void 0&&!/^[1-9]\d*$/.test(i)&&u("pr reply takes the id of the review comment it answers");const o=j(n,"--body").trim();(o.startsWith(Te.trim())||o.includes(Ct))&&u(`${a} adds the ${Te.trim()} prefix and the claude-bridge marker itself; pass only your words`);const c=s.repo||ee(A(e),{})||u(`${a} needs a board on GitHub; this board has no repo there`);try{const d=await ja({repo:c,pr:s.number,replyTo:i,words:o,login:ge(await M(e)).github_login});return{lines:[`posted on PR ${s.repo?t:`#${t}`}: ${d}`]}}catch(d){u(d.message)}}r(Br,"postPR");const bi=r(async e=>Qn((await M(e)).tickets),"boardSource");async function Tr(e,t,{afterApproval:i,confirmed:n,tapped:a}={}){A(e);const{wave:s,item:o}=await v(e,t);it(o)||u(`${t} has no PR`),I.includes(o.status)&&u(`${t} is ${o.status}`);const c=ee(e,s),d=Ne(o,c);d.length||u(`${t} has no repo`);const f=new Date().toISOString();let p;try{p=await Promise.all(d.map(x=>gn({repo:x.repo,pr:x.number,since:f})))}catch(x){u(x.message)}const l=p.map(({view:x})=>x);if(kn(l)){const x=d.filter((O,R)=>l[R].state==="MERGED");return se(e,t,{status:"merged",text:`PR${x.length>1?"s":""} ${qe(x,c)} ${x.length>1?"were":"was"} already merged.`})}const w=d.map((x,O)=>({...x,...p[O]})).filter(({view:x})=>x.state==="OPEN"),m=Fe(s,(await M(e)).reviewers||[]).length>0,g=[];let b=!1,P=!1;for(const x of w){const{view:O,reviews:R}=x,{failing:Z,pending:ne}=$n(x,{pr:x.number,since:f,me:null}),F=Zi({...O,checks:{state:Z.length?"fail":ne?"pending":"pass",failing:Z,pending:ne}},{needsApproval:m}),B=R.filter(ie=>ie.state==="APPROVED").sort((ie,ce)=>String(ie.submitted_at).localeCompare(String(ce.submitted_at))).at(-1)?.commit_id;let oe=!!(B&&O.headRefOid&&B!==O.headRefOid);oe&&i===void 0&&zs(o,B,O.headRefOid)&&(oe=!1,P=!0),b||=oe,oe&&i===void 0&&F.push('commits after the approval: pass --after-approval "<why they are trivial>" when they are, else ask the approver to look again'),g.push(...d.length>1?F.map(ie=>`${qe([x],c)} ${ie}`):F)}w.length||g.push(d.length>1?"every PR is closed":"PR is closed"),i!==void 0&&!b&&u("--after-approval: no commit came after the approval; drop it");const D=o.manual_steps?.length?n===void 0?null:await ri(e,n,"--confirmed"):void 0;if(n!==void 0&&D===void 0&&u(`--confirmed: ${t} has no manual steps; drop it`),D===null&&g.push(`manual steps: merge only on the owner's word, with --confirmed "<their words>"`),g.length){const x=`Not merged: ${g.join("; ")}.`;a&&await re(e,t,{text:x}),u(x)}const S=[];for(const x of w){const O=await new Promise(R=>{Pt("gh",["pr","merge",String(x.number),"--repo",x.repo,"--squash"],{encoding:"utf8",timeout:12e4},(Z,ne,F)=>R(Z?String(F||Z.message).trim().split(`
17
+ `)[0]:null))});O&&u(`gh pr merge ${qe([x],c)} failed: ${O}${S.length?` (merged ${qe(S,c)} before it)`:""}`),S.push(x)}const _=[fi(S,c),i!==void 0&&`After the approval: ${j(i,"--after-approval")}`,P&&`After the approval: only the board's rebase onto ${o.rebased.at(-1).base}.`,D&&`The owner's word on the manual steps: "${D}"`];return se(e,t,{status:"merged",text:_.filter(Boolean).join(" ")})}r(Tr,"mergeCard");async function qr(e,t){return(await v(e,t)).item.merge_ready||null}r(qr,"heldMerge");async function Fr(e,t){const{source:i,wave:n,item:a}=await v(e,t);return(!a.merge_ready||I.includes(a.status))&&u(`${t} isn't waiting for its Merge`),a.merge_ready.tapped=new Date().toISOString(),await y(i.file,n),a.merge_ready}r(Fr,"tapMerge");async function Mr(e,t){const{source:i,item:n}=await v(e,t);return(await Promise.all((await te(i.dir,n.id)).map(s=>$(s,null)))).filter(s=>s?.worktree?.path).sort((s,o)=>String(o.started).localeCompare(String(s.started)))[0]?.model}r(Mr,"builderModel");async function Yt(e,t,i,n,a,s,o){try{const c=await M(e),d=Et(c.tickets||{source:"internal"}),f=r((m,g)=>m.internal===!0?String(g.id).replace(/^S(\d+)$/,`${d.prefix}-$1`):null,"ownId");a===void 0&&d.source==="internal"&&Lt(d,f(i,n))&&(a=f(i,n));let p=0;if(d.source==="internal")for(const m of await q(e)){const g=await $(m.file,{});for(const b of g.items||[]){const P=[b.ticket,f(g,b)];if(p=Math.max(p,...P.map(D=>Lt(d,D)||0)),a!==void 0&&`${m.slug}/${b.id}`!==t&&P.includes(a))throw Object.assign(new Q(`${a} is already the ticket of ${m.slug}/${b.id}`),{held:!0})}}const l=a===void 0&&d.source!=="internal"&&n.plan?await N.readFile(await Ge(o,n.plan),"utf8"):n.notes||"",w=await fa(d,{ticket:a,title:n.title,body:l,repo:ee(e,i),next:p+1},s);n.ticket=w.ticket,w.created&&d.source!=="internal"?n.ticket_created=!0:delete n.ticket_created}catch(c){if(c instanceof Q)throw c;u(c.message)}}r(Yt,"assignTicket");const je=r((e,t)=>nt(h.join(e||rt(),"tickets"),t,{heartbeat:!0}),"ticketWrite"),se=r((e,t,i,n)=>i.ticket!==void 0||i.fromAsk!==void 0?je(e,()=>pi(e,t,i,n)):pi(e,t,i,n),"setItem"),Wr=r((e,t,i,n)=>je(e,()=>Ts(e,t,i,n)),"addItem");async function Ts(e,t,{title:i,notes:n,deps:a,notesFile:s,ticket:o,pickUpAt:c,parent:d,size:f,model:p,state:l,relate:w,intake:m=!1},g){const{wave:b,id:P}=t.includes("/")?C(t):{wave:t};P!==void 0&&me(P,"the item id"),l!==void 0&&!ci.includes(l)&&u("--state takes ready, grilling or prototyping");const{source:D,wave:S}=await Le(e,b);P!==void 0&&S.items.some(O=>O.id===P)&&u(`wave "${b}" already has an item "${P}"`);const _={id:P,title:j(i,"--title"),created:new Date().toISOString()};d!==void 0&&(_.parent=await ki(e,b,null,d)||u("--parent takes a card, such as <wave>/<id>")),n!==void 0&&(_.notes=j(n,"--notes")),wi(_,{size:f,model:p}),a!==void 0&&(_.deps=await $i(e,b,a)),s!==void 0&&(await Ge(D.dir,s),_.plan=h.normalize(s)),_.deps?.length&&(_.status="waiting"),c!==void 0&&gt(_,{until:mi(c)}),w!==void 0&&(_.related=await $t(e,t,w,"--relate")),l==="ready"&&li(P===void 0?"the card":t,_),l!==void 0?_.state=l:m&&e&&(_.unfiled=!0),await Yt(e,t,S,_,o,g,D.dir),P===void 0&&(_.id=ha(_.ticket),S.items.some(O=>O.id===_.id)&&u(`wave "${b}" already has an item "${_.id}"; link ${_.ticket} with item add ${b}/<id> --ticket ${_.ticket}`));const x=`${b}/${_.id}`;return S.items.push(_),await y(D.file,S),_.unfiled&&await pe(we().find(O=>ve(O.dir,e))||{dir:e},"card-added",{key:x,title:_.title}),{file:D.file,key:x,lines:[]}}r(Ts,"createItem");const Ur=r((e,{dryRun:t=!1}={},i)=>je(A(e),()=>qs(e,t,i)),"backfillTickets");async function qs(e,t,i){const n=await bi(e)||u("this board has no ticket source yet; pick one in Board settings first"),a=new Set,s=[];for(const p of await q(e)){const l=await $(p.file,null);if(Array.isArray(l?.items)){s.push({entry:p,wave:l});for(const w of l.items)w.ticket&&a.add(w.ticket),l.internal===!0&&n.source==="internal"&&a.add(String(w.id).replace(/^S(\d+)$/,`${n.prefix}-$1`))}}const o=[],c={linked:0,created:0,failed:0},d=r((p,l)=>l.ticket&&!(n.source!=="internal"&&p.internal===!0&&l.ticket===l.id),"ticketed");for(const{entry:p,wave:l}of s)for(const w of l.items){if(d(l,w)||I.includes(w.status))continue;const m=`${p.slug}/${w.id}`,g=[...ma(n,w.title),...(w.linear||[]).filter(b=>Lt(n,b))].find(b=>n.source!=="internal"||!a.has(b));if(t){c[g?"linked":"created"]++,o.push(`${m} would ${g?`link ${g}`:"get a new ticket"}`);continue}try{await Yt(e,m,l,w,g,i,p.dir),await y(p.file,l),a.add(w.ticket),c[g?"linked":"created"]++,o.push(`${m} ${g?"linked":"created"} ${w.ticket}`)}catch(b){if(!(b instanceof Q))throw b;c.failed++,o.push(`${m} failed: ${b.message}`)}}const f=t?`would link ${c.linked}, create ${c.created}`:`linked ${c.linked}, created ${c.created}, failed ${c.failed}`;return{lines:[...o,`backfill${t?" (dry run)":""}: ${f}`]}}r(qs,"backfill");const Kr=r(e=>je(e,async()=>{const t=[];for(const i of await q(e)){const n=await $(i.file,null);if(!Array.isArray(n?.items)||!Array.isArray(n.followups))continue;const a=n.followups.find(d=>n.items.some(f=>f.id===d.id));a&&u(`${i.slug}: follow-up ${a.id} has the id of a card; rename one, then restart the board`);const s=[];for(const{id:d,title:f,from:p,filed:l,done:w,...m}of n.followups){const g=w?e&&(await G(U(e,`${i.slug}/${d}`))).map(b=>b.ts).filter(Boolean).sort().pop()||l:null;s.push({id:d,title:f,...l?{created:l}:{},...p?{parent:W(i.slug,p)}:{},...w?{status:"done"}:{},...g?{status_at:g}:{},...m})}const{followups:o,...c}=n;await y(i.file,{...c,items:[...n.items,...s]}),t.push(`${i.slug}: ${s.length} follow-ups moved to cards (${s.filter(d=>d.status==="done").length} done)`)}return t}),"migrateFollowups"),Hr=r(e=>je(e,async()=>{const t=[];for(const i of await q(e)){const n=await $(i.file,null),a=(Array.isArray(n?.items)?n.items:[]).filter(s=>s.status==="planned");if(a.length){for(const s of a)delete s.status;await y(i.file,n),t.push(`${i.slug}: ${a.length} planned cards now have no status`)}}return t}),"dropPlannedStatus"),kt=r(e=>h.join(e,"data","done-archive.json"),"archiveFile"),Xt=r((e,t)=>nt(h.join(e,"done-archive"),t,{heartbeat:!0}),"archiveWrite"),yt=r(async e=>(await $(kt(e),{cards:[]})).cards||[],"readArchive"),bt=r(e=>`${e.closed_at||""}|${e.key}`,"archiveRank"),Fs=r((e,t)=>bt(e)<bt(t)?1:bt(e)>bt(t)?-1:0,"byClosed"),en=r(e=>h.join(e,"data","done-archive-count.json"),"archiveCountFile");async function Jr(e){const t=(await $(en(e),null))?.count;if(Number.isInteger(t))return t;const i=(await yt(e)).length;return await y(en(e),{count:i}),i}r(Jr,"archiveCount");async function tn(e,t){t.length?await y(kt(e),{cards:t.sort(Fs)}):await N.rm(kt(e),{force:!0}),await y(en(e),{count:t.length})}r(tn,"writeArchive");const zr=r((e,t)=>Xt(e,async()=>{const i=new Map(t.map(l=>[l.key,l])),n=new Date().toISOString(),a=[],s=[];for(const l of await q(e)){const w=await $(l.file,null);if(!Array.isArray(w?.items))continue;const m=w.items.filter(g=>i.has(`${l.slug}/${g.id}`)&&I.includes(g.status));if(m.length){for(const g of m)a.push({...i.get(`${l.slug}/${g.id}`),wave:l.slug,archived_at:n,item:g});s.push([l.file,{...w,items:w.items.filter(g=>!m.includes(g))}])}}if(!a.length)return[];const o=await $(L(e),{items:[]}),c=new Map(a.map(l=>[`item:${l.key}`,l]));for(const l of a)l.questions=(o.items||[]).filter(w=>w.topic===`item:${l.key}`&&w.resolved);const d=await _e(e);for(const l of a)l.asks=l.item.from_ask&&J(d,l.item.from_ask)===void 0?[l.item.from_ask]:[];const f=new Set(a.map(l=>l.key));await tn(e,[...(await yt(e)).filter(l=>!f.has(l.key)),...a.map(({key:l,wave:w,archived_at:m,closed_at:g,item:b,questions:P,asks:D})=>({key:l,wave:w,archived_at:m,closed_at:g,item:b,questions:P,asks:D}))]),a.some(l=>l.asks.length)&&await y(he(e),{links:{...d,...Object.fromEntries(a.flatMap(l=>l.asks.map(w=>[w,l.key])))}});for(const[l,w]of s)await y(l,w);const p=(o.items||[]).filter(l=>!(c.has(l.topic)&&l.resolved));return p.length!==(o.items||[]).length&&await y(L(e),{...o,items:p}),[...f]}),"archiveCards");async function Ms(e,t){return!e||!De(kt(e))?!1:Xt(e,async()=>{const i=await yt(e),n=i.find(l=>l.key===t);if(!n)return!1;const a=(await q(e)).find(l=>l.slug===n.wave),s=a&&await $(a.file,null);if(!Array.isArray(s?.items))return!1;s.items.some(l=>l.id===n.item.id)||await y(a.file,{...s,items:[...s.items,n.item]});const o=await $(L(e),{items:[]}),c=new Set((o.items||[]).map(l=>l.id)),d=(n.questions||[]).filter(l=>!c.has(l.id));d.length&&await y(L(e),{...o,items:[...o.items||[],...d]});const f=await _e(e),p=(n.asks||[]).filter(l=>J(f,l)===t);return p.length&&await y(he(e),{links:Object.fromEntries(Object.entries(f).filter(([l])=>!p.includes(l)))}),await tn(e,i.filter(l=>l!==n)),!0})}r(Ms,"restoreArchived");const xi=["push_tag","no_change"],vi=r(e=>Object.fromEntries(Object.entries(e).filter(([t])=>!xi.includes(t))),"stripQuestion"),Si=r(({summary:e,...t})=>t,"stripItem"),_i=r(e=>xi.some(t=>t in e),"holdsDead"),Gr=r(e=>Xt(e,async()=>{for(const n of await q(e)){const a=await $(n.file,null);Array.isArray(a?.items)&&a.items.some(s=>"summary"in s)&&await y(n.file,{...a,items:a.items.map(Si)})}const t=await $(L(e),null);(t?.items||[]).some(_i)&&await y(L(e),{...t,items:t.items.map(vi)});const i=await yt(e);i.some(n=>"card"in n||"summary"in n.item||(n.questions||[]).some(_i))&&await tn(e,i.map(({card:n,...a})=>({...a,...n?{closed_at:a.closed_at||n.sortAt}:{},item:Si(a.item),questions:(a.questions||[]).map(vi)})))}),"stripDeadFields"),ji=r(e=>`lineup-${e}.md`,"lineupNoteFile"),Ws=r(e=>typeof e=="string"&&/^[a-z0-9-]+$/.test(e)?e:u(`a wave's slug uses only a-z, 0-9 and "-", not "${e}"`),"lineupSlug");async function xt(e,t){for(const i of await q(e)){const n=await $(i.file,null),a=(n?.lineups||[]).find(s=>s.slug===t);if(a)return{source:i,wave:n,lineup:a}}return u(`this board has no wave "${t}"; lineup create makes one`)}r(xt,"findLineup");async function Us(e,t){(await M(e)).items!=="waves"&&u(`topic wave:${t} is for a board over ~/.claude/waves; a lineup's triage uses lineup:<slug>`),await Le(e,t)}r(Us,"triagedWave");function Qe(e,t,i,n){return i.map(a=>{const{wave:s,id:o}=C(a);s!==e.slug&&u(`${a} is not in wave file "${e.slug}"; a wave's cards share one file`),t.items.some(d=>d.id===o)||u(`wave "${s}" has no item "${o}"`);const c=(t.lineups||[]).find(d=>d.slug!==n&&!d.finished_at&&At(d).flat().includes(o));return c&&u(`${a} is already in the wave "${c.slug}"; lineup remove ${c.slug} ${a} first`),o})}r(Qe,"lineupCards");function Oi(e){const t=[e??[]].flat().map(i=>String(i).split(",").map(n=>n.trim()).filter(Boolean));return(!t.length||t.some(i=>!i.length))&&u("--phase takes one phase's cards, as <wave>/<id>,<wave>/<id>, once per phase in build order"),t}r(Oi,"phaseKeys");function Pi(e,t,i,n){const a=new Set(i.map(s=>`${e.slug}/${s}`));for(const s of i){const o=t.items.find(f=>f.id===s),c=(o.deps||[]).filter(f=>!a.has(W(e.slug,f))),d=n.findIndex(f=>f.includes(s));d>0&&c.push(...n[d-1]),c.length?o.deps=c:delete o.deps}}r(Pi,"chain");async function Di(e,t,i,n,a){a!==void 0&&await ct(h.join(t.dir,ji(n.slug)),`${j(a,"the note").replace(/\n*$/,`
18
+ `)}`),await y(t.file,i);const{tickets:s}=ge(await M(e));return{file:t.file,lines:[`order: ${Ai(i,n.phases,s)}`]}}r(Di,"writeLineup");const Ai=r((e,t,i)=>t.map(n=>n.map(a=>tt(e,e.items.find(s=>s.id===a)||{id:a},i)).join(", ")).join(" \u2192 "),"orderLine");async function Qr(e,t,{title:i,goal:n,phases:a,note:s}){Ws(t);const o=Oi(a);s===void 0&&u("lineup create needs the wave note, as --note <text> or --file <path>");const c=await q(e);c.some(w=>w.slug===t)&&u(`"${t}" is a wave file on this board; pick another slug`);for(const w of c)((await $(w.file,null))?.lineups||[]).some(m=>m.slug===t)&&u(`this board already has a wave "${t}"`);const d=c.find(w=>w.slug===C(o[0][0]).wave)||u(`this board has no wave "${C(o[0][0]).wave}"`),{wave:f}=await Le(e,d.slug),p=o.map(w=>Qe(d,f,w,t));new Set(p.flat()).size!==p.flat().length&&u("--phase names a card twice");const l={slug:t,title:j(i,"--title"),goal:j(n,"--goal"),phases:p,created:new Date().toISOString()};return Pi(d,f,p.flat(),p),f.lineups=[...f.lineups||[],l],Di(e,d,f,l,s)}r(Qr,"createLineup");async function Zr(e,t,{add:i,after:n,remove:a,phases:s,title:o,goal:c,note:d}){[i,a,s,o,c,d].every(m=>m===void 0)&&u("nothing to change: pass --add, --remove, --phase, --title, --goal, --note or --file"),n!==void 0&&i===void 0&&u("--after goes with --add");const{source:f,wave:p,lineup:l}=await xt(e,t);l.finished_at&&u(`the wave "${t}" is finished`),l.phases=At(l),delete l.items;const w=l.phases.flat();if(i!==void 0){const[m]=Qe(f,p,[i],t);w.includes(m)&&u(`${i} is already in the wave "${t}"`);const g=n===void 0?l.phases.length:l.phases.findIndex(b=>b.includes(Qe(f,p,[n],t)[0]))+1;g===0&&u(`--after ${n} is not in the wave "${t}"`),l.phases.splice(g,0,[m])}if(a!==void 0){const[m]=Qe(f,p,[a],t);w.includes(m)||u(`${a} is not in the wave "${t}"`),w.length===1&&u(`${a} is the wave's last card; lineup finish ${t} ends the wave`),l.phases=l.phases.map(g=>g.filter(b=>b!==m)).filter(g=>g.length)}if(s!==void 0){const m=Oi(s).map(b=>Qe(f,p,b,t)),g=m.flat();(g.length!==w.length||new Set(g).size!==g.length||g.some(b=>!w.includes(b)))&&u("--phase lists each of the wave's cards once"),l.phases=m}return o!==void 0&&(l.title=j(o,"--title")),c!==void 0&&(l.goal=j(c,"--goal")),Pi(f,p,[...new Set([...w,...l.phases.flat()])],l.phases),Di(e,f,p,l,d)}r(Zr,"changeLineup");async function Vr(e,t){const{source:i,wave:n,lineup:a}=await xt(e,t);return a.finished_at=new Date().toISOString(),await y(i.file,n),{file:i.file}}r(Vr,"finishLineup");async function Yr(e,t,i){const{source:n,wave:a,lineup:s}=await xt(e,t),o=await N.readFile(h.join(n.dir,ji(t)),"utf8").catch(()=>"");return{title:s.title,markdown:`**Goal** ${s.goal}
19
+
20
+ **Order** ${Ai(a,At(s),i)}
21
+
22
+ ${o}`}}r(Yr,"readLineupNotes");async function K(e,t,i,n="main"){const{id:a}=C(t);/^[\w-]{1,40}$/.test(n)||u(`--agent takes a name of letters, digits, "_" and "-", not "${n}"`);const s=n==="main"?`${a}.json`:`${a}@${n}.json`;if(i)return h.join(h.resolve(i),"agents",s);const{source:o}=await v(e,t);return h.join(o.dir,"agents",s)}r(K,"builderFile");const Ri=r((e,t)=>typeof e=="string"&&/^\d{4}-\d\d-\d\dT/.test(e)&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():u(`${t} takes an ISO time such as 2026-10-23T16:30:00-07:00`),"isoTime"),Ks=["reading","building","testing","checking","landing"],Ni=80,Ei="reading, building, testing, checking or landing";function Li(e,t,i,n){e||u(`${n} needs --site, since the line goes to the item's thread`),t!==void 0&&!Ks.includes(t)&&u(`--phase takes ${Ei}, not "${t}"`);const a=j(i,n);return a.length>Ni&&u(`${n} is ${a.length} characters; the cap is ${Ni}. Say it shorter.`),{phase:t,detail:a}}r(Li,"progressLine");const Ci=r((e,t,i)=>t?{detail:e.detail}:(e.phase===void 0&&u(`${i} needs --phase ${Ei}`),e),"forAgent");async function nn(e,t,i="main",n,{phase:a,detail:s},o){const c=Re(n),d=c||i==="main"?"":et(n)||n.kind||i,f=c?Yi[n.kind]:[d,a].filter(Boolean).join(" "),p=new RegExp(`^(?:${f}|${a??f})\\s*:?\\s+`,"i"),l=f?`${f[0].toUpperCase()}${f.slice(1)}: ${s.replace(p,"")}`:s,w=U(e,t);(await G(w)).filter(m=>m.kind==="status").pop()?.text!==l&&await Y(w,{ts:o,who:"claude",kind:"status",...a?{phase:a}:{},...c?{planner:!0}:{},text:l})}r(nn,"statusToThread");const Hs={prototype:"sonnet",grill:"opus"};async function an(e,t,{label:i,phase:n,progress:a,dir:s,agent:o="main",kind:c,model:d,eta:f,worktree:p,ownWorktree:l,dispatch:w}){n!==void 0&&a===void 0&&u('--phase goes with --progress "<detail>"');const m=z(a,T=>Li(e,n,T,"--progress")),g=await K(e,t,s,o),b=new Date().toISOString(),P=z(c,T=>/^[\w.-]{1,30}$/.test(T)?T:u("--kind takes a short word such as claude or codex")),D=Be(P),S=d??(P==="opus"||P==="sonnet"?P:void 0),_=["build",...Ys].includes(D),x=await $(g,null),O=r(T=>["tap","hub"].includes(T?.dispatched)&&!T.done,"tapOpen");if(w==="session"&&O(x))return{file:g,alreadyOpen:!0,lines:[]};o!=="main"&&O(await $(await K(e,t,s),null))&&u(`the Implement tap opened ${t}'s main builder record and no agent has taken it up; run builder start ${t} without --agent first`);const R=x?.dispatched&&!x.done?x:null,Z=_&&!s?(await v(e,t)).item:void 0,ne=x&&Oe(x).length?x:null,F=R&&D==="build"?{kind:Be(R.kind),model:R.model,reason:{tap:"The owner's Build tap picked it.",hub:"The board's pull picked it."}[R.dispatched]??"The session's dispatch picked it."}:_?mn({card:Z??{}}):null;F&&D!=="build"&&D!==F.kind&&u(`--kind ${D}: ${F.kind} builds now. ${F.reason} Pass --kind ${F.kind}, or --kind build.`);const B=F?F.kind:D,oe=wn();if(ia(oe,B))throw new Q(na(oe,B));const ie=m&&Ci(m,Re({kind:B}),"--progress");d!==void 0&&!["opus","sonnet"].includes(d)&&u("--model takes opus or sonnet"),S!==void 0&&B==="codex"&&u("--model is for kind claude; codex needs none");const ce=B==="claude"?ca():"auto";S!==void 0&&ce!=="auto"&&S!==ce&&u(`--model ${S}: the hub's Claude model is ${ce==="opus"?"Opus":"Sonnet"}. Pass --model ${ce}, or no --model.`);const ae=B==="claude"?S??F?.model??(R&&Be(R.kind)==="claude"?R.model:void 0)??"opus":Re({kind:B})?S??(R?.kind===B?R.model:void 0)??Hs[B]:void 0,le={label:i===void 0?"Builder":j(i,"--label"),...B?{kind:B}:{},...ae?{model:ae}:{},started:b,...f===void 0?{}:{eta:Ri(f,"--eta")},...w?{dispatched:w}:{},...ne?{calls:ne.calls,...ne.verified?{verified:ne.verified}:{}}:{},...Qs(x)?{session:x.session}:{}},de=_&&!s&&![...I,"building","fixing"].includes(Z.status),vt=de?await se(e,t,{status:"building"}):{lines:[]};let V,ue=null;const ye=l&&_&&o==="main"?[x?.worktree,Z?.worktree].find(T=>T?.path&&De(T.path))??null:null,Pe=(R??ne)?.worktree??ye,be=p??(_&&o==="main"&&!Pe?l:void 0);try{if(be){const T=await te(h.dirname(h.dirname(g)),C(t).id),xe=(await Promise.all(T.filter(k=>k!==g).map(k=>$(k,null)))).filter(k=>k?.worktree?.path&&!k.done).map(k=>k.worktree.path);({remade:ue,...V}=await be({busy:xe}))}else V=Pe}catch(T){throw de&&await Vs(e,t,Z),T}await y(g,V?{...le,worktree:V}:le),Z?.rebase_run&&o==="main"&&![Ii,"Lander"].includes(le.label)&&await Bi(e,t),F?.inputs&&e&&ba(hn(e),{call:"builder-pick",key:t,result:[B,B==="claude"?ae:null].filter(Boolean).join(" "),reason:F.reason,inputs:{...F.inputs,...S?{askedModel:S}:{},...w?{dispatch:w}:{}}}),ue&&e&&await re(e,t,{text:ue}),ie&&await nn(e,t,o,le,ie,b);const H=await Vt(e,t,"Acted on: builder started");return e&&_&&await _s(e,t),{file:g,kind:B??null,model:ae??null,reason:F?.reason??null,worktree:V?.path??null,lines:[...D==="build"?[`kind: ${B}. ${F.reason}`]:[],...et(le)?[`model: ${et(le)}`]:[],...e?[`ref: ${await X(e,t)}`]:[],...V?[`worktree: ${V.path}`]:[],...ue?[ue]:[],...vt.lines,...H]}}r(an,"startBuilder");async function Js(e,t,i,n="tap"){try{const{held:a,blockers:s}=await Gs(e,t);if(a&&await hi(e,"card-hold",{key:t,hold:!1}),s.length)return await Ti(e,t,s);try{const o=await an(e,t,{kind:"build",worktree:i,dispatch:n});return{key:t,ref:await X(e,t),kind:o.kind,...o.model?{model:o.model}:{},reason:o.reason,worktree:o.worktree}}catch(o){throw a&&await Zs(e,t,a),o}}catch(a){if(!(a instanceof Q))throw a;return await Y(U(e,t),{ts:new Date().toISOString(),who:"claude",kind:Dt,text:`Couldn't start implementing: ${a.message}`}),null}}r(Js,"startTappedBuild");async function Xr(e,t,{pr:i,conflict:n,base:a},s){const{source:o,wave:c,item:d}=await v(e,t);d.rebase_run={pr:i,base:a,conflict:n,at:new Date().toISOString()},await y(o.file,c);try{const f=await an(e,t,{kind:"build",label:Ii,dispatch:"hub",ownWorktree:s});return{key:t,kind:f.kind,...f.model?{model:f.model}:{},worktree:f.worktree}}catch(f){throw await Bi(e,t),f}}r(Xr,"startRebase");const Ii="Rebase";async function Bi(e,t){const{source:i,wave:n,item:a}=await v(e,t);delete a.rebase_run,await y(i.file,n)}r(Bi,"endRebaseRun");async function ec(e,t){const{wave:i,item:n}=await v(e,t),a=ee(e,i);return Ne(n,a).find(s=>s.repo===a)?.number??null}r(ec,"cardPR");async function tc(e,t,{from:i,to:n,replayed:a}){const{source:s,wave:o,item:c}=await v(e,t);return c.rebase_run?(c.rebased=[...c.rebased||[],{from:i,to:n,base:c.rebase_run.base,replayed:a,at:new Date().toISOString()}],delete c.rebase_run,await y(s.file,o),!0):!1}r(tc,"recordRebase");const zs=r((e,t,i)=>{const n=new Map((e.rebased||[]).filter(a=>a.replayed).map(a=>[a.to,a.from]));for(let a=i,s=0;a&&s<=n.size;a=n.get(a),s++)if(a===t)return!0;return!1},"onlyRebased");async function Gs(e,t){const i=wn();i.state==="paused"&&u(ta(i));const{item:n}=await v(e,t),a=n.held||n.status==="held"?{held:n.held,status:n.status,pick_up_at:n.pick_up_at,held_at:n.held_at}:null;a&&![...Tn,"held"].includes(n.status)&&u("it's held. Unhold it, then tap Implement."),await oi(e,t)&&u("no take is picked on its prototypes, so it prototypes again. Pick a take from the next round, then tap Implement.");const s=await Promise.all((await ze(e,C(t).wave,n)).map(o=>X(e,o)));return{held:a,blockers:s}}r(Gs,"tapRefusals");async function nc(e,t){const{item:i}=await v(e,t);if(i.implement_at)return;(i.held||i.status==="held")&&await hi(e,"card-hold",{key:t,hold:!1});const{source:n,wave:a,item:s}=await v(e,t);s.implement_at=new Date().toISOString(),await y(n.file,a)}r(nc,"askImplement");async function Ti(e,t,i){const n=i.join(", ");return await pe({dir:e},"card-bump",{key:t}),await Y(U(e,t),{ts:new Date().toISOString(),who:"claude",text:`Can\u2019t start yet: waits on ${n}. Bumped to the top of Todo.`}),{key:t,ref:await X(e,t),bumped:i,line:`bumped: ${t} waits on ${n}, so it stays in Todo, bumped to the top`}}r(Ti,"bumpBlocked");async function ic(e,t,i){let n;try{n=await Js(e,t,i)}catch(a){await Y(U(e,t),{ts:new Date().toISOString(),who:"claude",kind:Dt,text:`Couldn't start implementing: ${a.message}`}),n=null}if(!n){const{source:a,wave:s,item:o}=await v(e,t);delete o.implement_at,await y(a.file,s)}return n}r(ic,"startReleasedBuild");async function ac(e,t,i){const n=await K(e,t),a=await $(n,null),s=new Date().toISOString();a&&!a.done&&await y(n,{...a,done:s});const{source:o,wave:c,item:d}=await v(e,t);d.status==="building"&&(delete d.status,d.status_at=s),await y(o.file,c),await Y(U(e,t),{ts:s,who:"claude",kind:Dt,text:`Couldn't start implementing: ${i}`})}r(ac,"abandonLaunch");async function sc(e,t,i){const n=await K(e,t),a=await $(n,null);a&&!a.done&&await y(n,{...a,done:new Date().toISOString()}),await mt(e,t),await re(e,t,{text:i})}r(sc,"abandonPlanner");async function oc(e,t,i,n){const a=await K(e,t),s=await $(a,null);await y(a,{...s,session:{id:i,pid:n,at:new Date().toISOString()}})}r(oc,"recordSession");async function rc(e,t){const{source:i}=await v(e,t);return(await Promise.all((await te(i.dir,C(t).id)).map(a=>$(a,null)))).filter(a=>a&&a.started&&!a.done).map(a=>({pid:a.session?.pid??null,at:a.session?.at??null}))}r(rc,"openAgents");async function cc(e,t){return(await G(U(e,t))).filter(i=>i.kind==="status").pop()?.phase==="landing"}r(cc,"isLanding");const Qs=r(e=>!!e?.session&&e.session.at>(e.done??e.started),"launchedSession");async function dc(e,t,i){const n=await $(await K(e,t),null);if(n&&!n.done)return null;const a=await an(e,t,{kind:i,dispatch:"hub"});return{key:t,kind:i,model:a.model}}r(dc,"startPlanner");async function lc(e){const t=[];for(const i of await q(e)){const n=await $(i.file,null);for(const a of n?.items||[]){if(a.status!=="building")continue;const s=await $(h.join(i.dir,"agents",`${a.id}.json`),null);!s?.started||s.done||!s.dispatched||Re(s)||t.push({key:`${i.slug}/${a.id}`,kind:Be(s.kind),model:s.model})}}return t}r(lc,"cutOffBuilds");async function Zs(e,t,i){const{source:n,wave:a,item:s}=await v(e,t);for(const o of Object.keys(i))i[o]===void 0?delete s[o]:s[o]=i[o];await y(n.file,a)}r(Zs,"restoreHold");async function Vs(e,t,i){const{source:n,wave:a,item:s}=await v(e,t);for(const o of["status","status_at"])i[o]===void 0?delete s[o]:s[o]=i[o];await y(n.file,a)}r(Vs,"restoreStatus");async function uc(e,t){return e||u("audit reads a board: pass --site <route>"),t!==void 0&&C(t),{lines:xa(va(hn(e),{key:t}))}}r(uc,"auditLog");const Ys=["codex","claude"];async function fc(e,t){const{item:i}=await v(e,t),{kind:n,model:a,reason:s}=mn({card:i});return{lines:[`${[n,a].filter(Boolean).join(" ")}: ${s}`]}}r(fc,"pickBuilder");async function pc(e,t,i){const{source:n,wave:a,item:s}=await v(e,t);if(s.worktree?.path&&De(s.worktree.path))return null;const o=await sn(e,t);if(o?.path&&De(o.path))return null;const{remade:c,...d}=await i({busy:[]});return s.worktree=d,await y(n.file,a),d}r(pc,"ensureWorktree");async function sn(e,t,{dir:i}={}){const{id:n}=C(t),a=h.dirname(await K(e,t,i)),s=await te(h.dirname(a),n);return(await Promise.all(s.map(c=>$(c,null)))).filter(c=>c?.worktree?.path).sort((c,d)=>String(d.started).localeCompare(String(c.started)))[0]?.worktree??null}r(sn,"recordedWorktree");async function wc(e,t,i,{phase:n,dir:a,agent:s="main",eta:o,clearEta:c}){o!==void 0&&c&&u("pass --eta or --clear-eta, not both");const d=Li(e,n,i,"builder progress"),f=await K(e,t,a,s),p=await $(f,null);(!p?.started||p.done)&&u(`builder progress needs an open builder record on ${t}; run builder start first`);const l=Ci(d,Re(p),"builder progress");return o!==void 0&&(p.eta=Ri(o,"--eta")),c&&delete p.eta,(o!==void 0||c)&&await y(f,p),await nn(e,t,s,p,l,new Date().toISOString()),f}r(wc,"builderProgress");async function mc(e,t){await v(e,t);const i=U(e,t);(await G(i)).filter(n=>n.kind==="status").pop()?.phase!=="landing"&&await Y(i,{ts:new Date().toISOString(),who:"claude",kind:"status",phase:"landing",text:"Landing: rebasing onto main and landing"})}r(mc,"landingLine");const Oe=r(e=>(e?.calls||[]).filter(t=>!e.verified||t.at>e.verified.at),"unverifiedCalls");async function hc(e,t,i,{dir:n,agent:a="main"}){const s=j(i,"builder call");/\n/.test(s)&&u("builder call takes one line; record each call on its own");const o=await K(e,t,n,a),c=await $(o,null);return(!c?.started||c.done)&&u(`builder call needs an open builder record on ${t}; run builder start first`),await y(o,{...c,calls:[...c.calls||[],{at:new Date().toISOString(),text:s}]}),o}r(hc,"recordCall");async function Ze(e,t){const i=await G(U(e,t)),n=new Map(i.filter(a=>a.kind===Xe.answer).map(a=>[a.ask,a]));return i.filter(a=>a.kind===Xe.ask).map(a=>{const s=n.get(a.ask);return{id:a.ask,agent:a.agent||"main",text:a.text,at:a.ts,answer:s?{text:s.text,at:s.ts}:null,deferred:!!s?.deferred}})}r(Ze,"builderAsks");const Xs=r(e=>we().find(t=>ve(t.dir,e))??{dir:e},"boardTarget");async function gc(e,t,i,{agent:n="main"}){A(e);const a=j(i,"builder ask");/\n/.test(a)&&u("builder ask takes one line; ask each question on its own");const s=await $(await K(e,t,void 0,n),null);(!s?.started||s.done)&&u(`builder ask needs an open builder record on ${t}; run builder start first`);const o=`ask${(await Ze(e,t)).length+1}`;return await Y(U(e,t),{ts:new Date().toISOString(),who:`${et(s)||s.kind||"Claude"} builder`,kind:Xe.ask,ask:o,agent:n,text:a}),await pe(Xs(e),"builder-ask",{key:t,ask:o,agent:n,text:a}),{id:o,lines:[]}}r(gc,"askOrchestrator");async function $c(e,t,i,n,{deferred:a=!1}={}){A(e);const s=j(n,"--text"),o=(await Ze(e,t)).find(d=>d.id===i)||u(`no ask "${i}" on ${t}; builder asks ${t} lists them`);o.answer&&u(`${i} on ${t} is already ${o.deferred?"deferred":"answered"}`);const c=new Date().toISOString();if(await Y(U(e,t),{ts:c,who:"claude",kind:Xe.answer,ask:i,...a?{deferred:!0}:{},text:s}),a){const d=await K(e,t,void 0,o.agent),f=await $(d,null);f&&await y(d,{...f,calls:[...f.calls||[],{at:c,text:`Question: ${o.text} (deferred to the owner)`}]})}return{lines:[]}}r($c,"answerBuilder");async function kc(e,t){A(e);const i=await Ze(e,t);return i.length?{lines:i.flatMap(n=>[`${n.id}. ${n.text}`,` ${n.answer?`${n.deferred?"deferred":"answered"}: ${n.answer.text}`:"waiting on the orchestrator"}`])}:{lines:["no asks yet"]}}r(kc,"listAsks");async function eo(e,t,i){const n=t.topic.startsWith("item:")&&!t.topic.startsWith("item:ask:")?t.topic.slice(5):u(`${i}.ask goes on a card's question, topic item:<wave>/<id>`),a=(await Ze(e,n)).find(s=>s.id===t.ask)||u(`${i}.ask names no ask "${t.ask}" on ${n}; builder asks ${n} lists them`);a.deferred||u(`${i}.ask names ${a.id}, which the orchestrator ${a.answer?"answered":"has not deferred"}; only a deferred ask goes to the owner`)}r(eo,"checkAskQuestion");async function yc(e,t,{dir:i,agent:n="main"}){const a=await $(await K(e,t,i,n),null),s=a?.calls||[];if(!s.length)return{lines:["no judgment calls recorded"]};const{verified:o}=a,c=Oe(a).length?"not verified yet":`verified ${o.at}${o.note?`: ${o.note}`:""}`;return{lines:[...s.map((d,f)=>`${f+1}. ${d.text}`),c]}}r(yc,"listCalls");async function bc(e,t,{dir:i,agent:n="main",note:a}){const s=await K(e,t,i,n),o=await $(s,null);if(Oe(o).length||u(`${t} has no unverified judgment calls${n==="main"?"":` from agent ${n}`}; builder calls ${t} lists them`),e){const c=new Set((await $(L(e),{items:[]})).items?.filter(f=>f.topic===`item:${t}`&&f.ask).map(f=>f.ask)),d=(await Ze(e,t)).find(f=>f.deferred&&f.agent===n&&!c.has(f.id));d&&u(`${d.id} on ${t} was deferred to the owner; add its question with "ask": "${d.id}" first`)}return await y(s,{...o,verified:{at:new Date().toISOString(),...a===void 0?{}:{note:j(a,"--note")}}}),s}r(bc,"verifyCalls");async function xc(e,t){const{source:i,item:n}=await v(e,t),a=r((o,c)=>[(o.options||[]).find(d=>d.id===c.choice)?.label,c.note].filter(Boolean).join(": ")||"answered","said"),s=(await ke(e,t)).asked.filter(o=>o.ask&&o.answers.length).map(o=>({ask:o.ask,question:o.question,answer:a(o,o.answers.at(-1))}));return{key:t,ref:await X(e,t),title:n.title||t,notes:n.plan?h.join(i.dir,n.plan):null,worktree:(await sn(e,t))?.path??null,answers:s,links:await to(e,t),rebasePR:n.rebase_run?.pr??null}}r(xc,"briefFacts");async function to(e,t){const i=new Map;for(const c of await q(e))for(const d of(await $(c.file,null))?.items||[])i.set(`${c.slug}/${d.id}`,{entry:c,it:d});const n=C(t).wave,{it:a}=i.get(t),s=[...i].filter(([,c])=>(c.it.related||[]).some(d=>W(c.entry.slug,d)===t)).map(([c])=>c),o=[...a.parent?[["parent",W(n,a.parent)]]:[],...(a.deps||[]).map(c=>["depends on",W(n,c)]),...[...new Set([...(a.related||[]).map(c=>W(n,c)),...s])].map(c=>["related",c])].filter(([,c])=>i.has(c));return Promise.all(o.map(async([c,d])=>{const{entry:f,it:p}=i.get(d);return{relation:c,ref:await X(e,d),title:p.title||d,status:p.status||"not started",notes:p.plan?h.join(f.dir,p.plan):null}}))}r(to,"cardLinks");async function vc(e){const t=[];for(const i of await q(e)){const n=await $(i.file,null);for(const a of n?.items||[]){if(a.status!=="checking")continue;const s=(await Promise.all((await te(i.dir,a.id)).map(f=>$(f,null)))).filter(Boolean),o=s.map(f=>f.verified?.at).filter(Boolean).sort().at(-1);if(!o||s.some(f=>Oe(f).length))continue;const c=`${i.slug}/${a.id}`;if((await ke(e,c)).asked.some(f=>f.state==="open"))continue;const d=s.filter(f=>f.worktree?.path).sort((f,p)=>String(p.started).localeCompare(String(f.started)))[0];d&&De(d.worktree.path)&&t.push({key:c,verified:o,kind:Be(d.kind),model:d.model})}}return t}r(vc,"landable");async function Sc(e,t){const{item:i}=await v(e,t);i.status!=="building"&&u(`${t} is ${i.status||"not started"}; only a card at building has a stopped lander to relaunch`),await se(e,t,{status:"checking",next:"A lander relaunches to land the verified build"});const n=h.join(e,"data","landers.json"),a=await $(n,{});delete a[t],await N.writeFile(n+".tmp",JSON.stringify(a)+`
23
+ `),await N.rename(n+".tmp",n)}r(Sc,"relaunchLander");async function _c(e,t,{dir:i}={}){const{id:n}=C(t),a=await te(h.dirname(h.dirname(await K(e,t,i))),n),s=[];for(const o of a){if(!Oe(await $(o,null)).length)continue;const c=h.basename(o,".json").slice(String(n).length+1)||"main";s.push(c==="main"?"":` --agent ${c}`)}s.length&&u(`land: ${t} has judgment calls nobody verified yet; check them with ${s.map(o=>`builder calls ${t}${o}`).join(", ")}, then run ${s.map(o=>`builder verified ${t}${o}`).join(", ")}`)}r(_c,"checkCallsVerified");async function jc(e,t,{dir:i,agent:n="main",next:a}){const s=await $(await K(e,t,i,n),null),o=s&&!s.done?Oe(s):[];if(!o.length)return null;a!==void 0&&u(`builder done sets ${t}'s Next itself while its record has judgment calls; run it without --next`);const c=o.some(f=>f.text.startsWith("Question:"))?"Answer the builder's questions":"Verify the builder's judgment calls",d=await se(e,t,{status:"checking",next:c});return{lines:[`handed back: checking, Next "${c}"`,...d.lines]}}r(jc,"handBackCalls");async function Oc(e,t,{agent:i="main"}){if(i!=="main")return!1;const n=await K(e,t,void 0,i),a=await $(n,null);if(!a?.started||a.done||!a.worktree?.path)return!1;const{id:s}=C(t);for(const o of await te(h.dirname(h.dirname(n)),s)){const c=o===n?null:await $(o,null);if(!c?.started||c.done||c.kind==="install")continue;const d=h.basename(o,".json").slice(String(s).length+1);u(`builder done would finish ${t} while agent ${d} is still open; run builder done ${t} --agent ${d} first`)}return!0}r(Oc,"finishesCard");async function Pc(e,t){const{source:i,item:n}=await v(e,t);if(n.status!=="checking"||(await Promise.all((await te(i.dir,n.id)).map(o=>$(o,null)))).filter(Boolean).some(o=>Oe(o).length||o.started&&!o.done&&o.kind!=="install"))return null;const s=await sn(e,t);return!s||!De(s.path)?null:{waits:(await ke(e,t)).asked.filter(o=>o.state==="open").map(o=>o.id)}}r(Pc,"verifiedFinish");async function Dc(e,t){const{item:i}=await v(e,t);if(i.status!=="done"||i.merged_at)return;const n=String(i.status_at||"");(await G(h.join(e,"data","events.jsonl"))).some(s=>s.kind==="item-message"&&s.data?.key===t&&String(s.ts)>n)&&u(`the owner reopened ${await X(e,t)} with a message; it closes on the owner's Done`)}r(Dc,"checkNotReopened");const qi=["checking","done","merged","dropped"];async function te(e,t){const i=h.join(e,"agents");return(await N.readdir(i).catch(()=>[])).filter(n=>n===`${t}.json`||n.startsWith(`${t}@`)&&n.endsWith(".json")).map(n=>h.join(i,n))}r(te,"builderFiles");async function Fi(e,t,i){const n=new Date().toISOString();for(const a of await te(e,t)){const s=await $(a,null);if(!s||s.done||s.kind==="install"&&!i)continue;const{eta:o,...c}=s;await y(a,{...c,done:n})}}r(Fi,"closeBuilders");async function no(e,t,{dir:i,agent:n,startedBetween:a,note:s,next:o,requireNext:c=!1}){const d=await K(e,t,i,n),f=await $(d,null);if(!f||f.done)return d;if(a){const R=Date.parse(f.started);if(!(R>=a[0]&&R<=a[1]))return d}const{eta:p,...l}=f,w=new Date().toISOString(),m={...l,done:w,...s?{note:s}:{}},{id:g}=C(t),b=h.dirname(h.dirname(d)),P=await Promise.all((await te(b,g)).map(R=>R===d?m:$(R,null))),D=!P.some(R=>R?.started&&!R.done),S=i?{file:h.join(b,"wave.json")}:(await v(e,t)).source,_=await $(S.file,null),x=_?.items?.find(R=>R.id===g);o!==void 0&&(ii(x||u(`${t} has no item to set --next on`),o,await ni(e,t)),e&&await di(e,t,x,x.next));const O=D&&ht(x);return c&&x&&Rt(x,P)&&u(`builder done closes ${t}'s last open builder, which leaves it In Progress with no Next; pass --next "<what happens next>", or hand it back with item set ${t} --status checking or land`),await y(d,m),await mt(e,t),s&&await nn(e,t,n,f,{detail:s},w),(O||o!==void 0)&&await y(S.file,_),d}r(no,"stopBuilder");async function io(e){const t=[];for(const i of await q(e)){const n=await $(i.file,null);for(const a of n?.items||[])for(const s of await te(i.dir,a.id)){const o=await $(s,null);if(!o?.started||o.done)continue;const c=h.basename(s,".json");t.push({key:`${i.slug}/${a.id}`,agent:c.slice(String(a.id).length+1)||"main",label:o.label||"Builder",started:o.started})}}return t}r(io,"openBoardBuilders");async function Ac(e){const t=await io(e);for(const i of t)await no(e,i.key,{agent:i.agent,note:"Board closed. Builder record stopped; work is kept for reopening."});return t}r(Ac,"closeBoardBuilders");export{Q as BoardError,Pn as PUSH_LINE_MAX,Bt as UPLOAD_LIMIT,qo as WORKING_KINDS,ac as abandonLaunch,sc as abandonPlanner,er as ackPing,Wr as addItem,yr as addPrototype,vr as addQuestions,cr as addReviewers,mr as addRuleTo,kr as addTopic,$c as answerBuilder,re as appendThread,zr as archiveCards,Jr as archiveCount,kt as archiveFile,bt as archiveRank,nc as askImplement,gc as askOrchestrator,Dr as askedGate,uc as auditLog,Ur as backfillTickets,M as boardConfig,ee as boardRepoOf,Cr as breakOwnerCheck,xc as briefFacts,Mr as builderModel,wc as builderProgress,X as cardName,ec as cardPR,Zr as changeLineup,_c as checkCallsVerified,Pr as checkClose,Dc as checkNotReopened,Ac as closeBoardBuilders,Qr as createLineup,lc as cutOffBuilds,Hr as dropPlannedStatus,hr as editRuleIn,pc as ensureWorktree,Jo as eventCard,fr as fallBackFromLinear,tr as finishHandshake,Vr as finishLineup,Oc as finishesCard,jc as handBackCalls,qr as heldMerge,An as hiddenFile,Ar as isFinished,cc as isLanding,q as itemSources,vc as landable,mc as landingLine,ji as lineupNoteFile,kc as listAsks,yc as listCalls,br as listPrototypes,wr as listRules,Qo as markAsk,Uo as markRead,Fo as markWorking,Tr as mergeCard,fi as mergedLine,Kr as migrateFollowups,Zo as moveAsk,jr as moveQuestions,rc as openAgents,io as openBoardBuilders,ur as opensPRs,C as parseKey,Lr as passOwnerCheck,fc as pickBuilder,Er as pickUp,Xo as postIncomingReview,Br as postPR,Ir as prReport,ts as pushLine,as as pushUrl,yt as readArchive,_e as readAskLinks,ut as readAskProgress,Kt as readBoardRules,ms as readBoardSettings,Wn as readHandshake,os as readHidden,$ as readJSON,Yr as readLineupNotes,rs as readMarks,Nn as readMarksFile,Rr as readNotes,wt as readPrototypes,Ho as readUpload,Ga as readWorking,hc as recordCall,hi as recordOwnerTap,Za as recordPush,tc as recordRebase,Yo as recordReview,oc as recordSession,sn as recordedWorktree,zo as relateAsk,Sc as relaunchLander,xr as removePrototype,dr as removeReviewers,gr as removeRuleFrom,Qa as repliesSincePush,Or as resolveNoteAnswers,_r as resolveQuestion,ps as reviewDigest,rr as reviewDigestSent,sr as reviewDue,ar as reviewReact,ir as reviewSent,or as reviewUpdated,$r as saveBoardRules,Ue as saveBoardSettings,lr as saveBoardShare,Ko as saveUpload,Mo as sendPush,pr as setBoardSetting,Wo as setHidden,se as setItem,Nr as setMainInstall,nr as setReviewers,hs as settingsLines,ge as settingsOf,Sr as settleGates,Bo as siteDir,Ja as sitesDir,an as startBuilder,dc as startPlanner,Xr as startRebase,ic as startReleasedBuild,Js as startTappedBuild,no as stopBuilder,Gr as stripDeadFields,Gt as takeFile,Fr as tapMerge,U as threadFile,Zt as topicQuestions,Go as unfoldAsk,Pc as verifiedFinish,bc as verifyCalls,rt as wavesDir,es as withReplies,Vo as writeChecked,To as writeReply};