@lovek4d/kickflip 0.7.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CONTEXT.md +10 -6
  2. package/SKILL.md +19 -13
  3. package/bin/event-lines.mjs +1 -1
  4. package/bin/install.mjs +3 -3
  5. package/board/bin/board.mjs +35 -13
  6. package/board/commit-message.mjs +6 -0
  7. package/board/domain.mjs +7 -7
  8. package/board/finish.mjs +5 -4
  9. package/board/headless.mjs +8 -8
  10. package/board/hub-lines.mjs +1 -1
  11. package/board/public/app-header.js +23 -0
  12. package/board/public/app-needs.js +1 -1
  13. package/board/public/app-reader.js +6 -2
  14. package/board/public/app.html +2 -0
  15. package/board/public/app.js +2 -0
  16. package/board/public/attach.js +12 -0
  17. package/board/public/col-resize.js +73 -0
  18. package/board/public/dialogs.js +3 -0
  19. package/board/public/prototype-kit.js +1 -1
  20. package/board/public/prototype.html +1 -0
  21. package/board/public/sidebar.css +8 -2
  22. package/board/public/style.css +33 -11
  23. package/board/public/ui-header.js +2 -2
  24. package/board/public/ui-sidebar.js +11 -3
  25. package/board/public/ui-threads.js +1 -0
  26. package/board/public/view-hub.js +2 -2
  27. package/board/public/view-questions.js +2 -1
  28. package/board/render-check.mjs +8 -8
  29. package/board/server.mjs +18 -18
  30. package/board/store.mjs +32 -31
  31. package/board/tickets.mjs +3 -3
  32. package/board/worktree.mjs +21 -19
  33. package/hooks-plugin/hooks/usage-gate.mjs +1 -3
  34. package/hub/boards.mjs +4 -4
  35. package/hub/home.mjs +1 -1
  36. package/hub/hub.mjs +11 -11
  37. package/hub/pr-report.mjs +2 -2
  38. package/hub/readiness.mjs +1 -1
  39. package/hub/review-send.mjs +1 -1
  40. package/hub/schedule.mjs +1 -1
  41. package/hub/slack.mjs +2 -2
  42. package/hub/views.mjs +1 -1
  43. package/package.json +1 -1
  44. package/shared/fake-gh.mjs +9 -4
package/board/store.mjs CHANGED
@@ -1,38 +1,39 @@
1
- var No=Object.defineProperty;var r=(e,t)=>No(e,"name",{value:t,configurable:!0});import j from"node:fs/promises";import{constants as Ro,existsSync as de,readFileSync as Eo}from"node:fs";import g from"node:path";import xn from"node:os";import{execFile as Lo}from"node:child_process";import{nodeBin as Bo}from"../bin/install.mjs";import{gh as Co,limitWords as Io}from"../shared/gh.mjs";import{fileURLToPath as To}from"node:url";import{BUILD_REFUSED as Oa,BUILDER_ASK as Tt,COMMANDS as qt,LANDER as Aa,LANES as Ce,MOVE as Pa,PAUSE_CLEARS as Da,PHASES as _n,handedBackAt as Sn,MAX_IMPLEMENTERS as qo,MAX_PLANNERS as Mo,builds as et,waveItems as Ie,mergeBlockers as Wo,modelName as Mt,noTakePicked as Uo,ownerQuestion as Te,plans as qe,QUESTION_REOPEN as Ho,PLANNER_WORD as Jo,providerOf as _t,owesNext as vn,pushTag as zo,refOf as tt,roundOf as jn,roundSettledBy as Ko,HELPER as re,VISUAL as me,visualAgent as Qo}from"./domain.mjs";import{GITHUB_STATE as On,appendEvent as he,listBoards as ge,readManifest as Go,samePath as Pe,withManifestLock as Vo,writeManifest as Zo}from"../hub/boards.mjs";import{readUsageGate as Fa,pauseReason as Yo,pauseReasonFor as Xo,heldFor as es,holdsWork as ts,builderPick as An,pauseEnd as ns}from"../shared/usage-gate.mjs";import{reviseQueued as as,pushKindError as is,readClaudeModel as Pn}from"../hub/push.mjs";import{AT_RE as os}from"../hub/duration.mjs";import{routeRecord as ae}from"../hub/routes.mjs";import{ticketSource as Na,resolveTicket as ss,ticketTarget as rs,moveTicket as cs,cardIdOf as ls}from"./tickets.mjs";import{LINEAR_NEEDS_KEY as ds,linearStatus as us,linearWorks as fs}from"../hub/linear.mjs";import{validateBranch as ws}from"../hub/repos.mjs";import{withFileLock as nt}from"../hub/locks.mjs";import{audit as ps,auditLines as ms,boardAudit as Ra,readAudit as hs}from"../shared/audit.mjs";import{merge3 as gs}from"./merge3.mjs";import{HUB as Ea,MESSAGE_LIMIT as La,BRIEF_LINE_LIMIT as Ba,hubLineOf as $s,hubText as Ca}from"./hub-lines.mjs";import{fetchPR as Ia,reportOf as Ta,githubLogin as ks,postToPR as bs,postReview as ys,reviewsSince as xs,CLAUDE_PREFIX as St,CLAUDE_MARK as Dn}from"../hub/pr-report.mjs";import{allLanded as _s,cardPRs as Me,hasPR as be,parsePRRef as Fn,prKeyOf as vt,prNames as at,prURL as Nn,storedPRs as De}from"../shared/card-prs.mjs";import{reviewLinks as Ss,topicItems as vs,reviewersOf as Rn}from"./review.mjs";import{readiness as qa}from"../hub/readiness.mjs";import{slackDay as js}from"../hub/slack.mjs";import"../bin/install.mjs";import{readPermissions as Os}from"./permissions.mjs";import{validBuildTarget as Ma}from"./build-script.mjs";import{parseCheck as As,checkText as Ps}from"../shared/owner-check.mjs";import{RuleError as Ds,rulesOf as Wa,addRule as Fs,editRule as Ns,removeRule as Rs,applyRules as Es,readHubRules as Wt,writeHubRules as Ls}from"../hub/rules.mjs";import{shareEntries as Bs,validLogin as Cs}from"../hub/share.mjs";class ue extends Error{static{r(this,"BoardError")}}const d=r(e=>{throw new ue(e)},"fail"),Is=r(()=>g.join(xn.homedir(),".claude","kickflip","sites"),"sitesDir"),Ut=r(()=>g.join(xn.homedir(),".claude","waves"),"wavesDir"),Ua=Symbol("read as"),$=r(async(e,t)=>{let n;try{n=await j.readFile(e,"utf8")}catch{return t}try{const a=JSON.parse(n);return a!==null&&typeof a=="object"&&!Array.isArray(a)?{...a,[Ua]:n}:a}catch{return t}},"readJSON"),z=r(async e=>{try{return(await j.readFile(e,"utf8")).split(`
2
- `).filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}},"readLines");async function We(e,t){await j.mkdir(g.dirname(e),{recursive:!0});const n=`${e}.${process.pid}.tmp`;await j.writeFile(n,t),await j.rename(n,e)}r(We,"replace");const y=r((e,t)=>{const{[Ua]:n,...a}=t??{};return n===void 0?We(e,JSON.stringify(t,null,2)+`
3
- `):nt(e,async()=>{const i=JSON.parse(n),o=JSON.parse(await j.readFile(e,"utf8").catch(()=>n));await We(e,JSON.stringify(gs(i,a,o),null,2)+`
4
- `)})},"writeJSON");async function le(e,t){await j.mkdir(g.dirname(e),{recursive:!0}),await j.appendFile(e,JSON.stringify(t)+`
5
- `)}r(le,"appendLine");async function Xc(e){/^[\w-]+$/.test(e||"")||d(`--site takes a route such as ios-orchestrator, not "${e}"`);const t=g.join(Is(),e);return await j.stat(t).then(n=>n.isDirectory(),()=>!1)||d(`no site at ${t}`),t}r(Xc,"siteDir");const oe=r(async e=>({title:"Board",items:"waves",...e?await $(g.join(e,"board.json"),{}):{}}),"boardConfig");async function q(e){const t=await oe(e);if(t.items==="waves")try{return(await j.readdir(Ut(),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>({slug:a.name,dir:g.join(Ut(),a.name),file:g.join(Ut(),a.name,"wave.json")}))}catch{return[]}const n=g.resolve(e,t.items);return[{slug:t.slug||g.basename(t.items,".json"),dir:g.dirname(n),file:n}]}r(q,"itemSources");const Z=r((e,t)=>g.join(e,"data","threads",t.replace(/[^\w.-]+/g,"__")+".jsonl"),"threadFile"),E=r(e=>g.join(e,"data","owner.json"),"ownerFile"),ye=r(e=>g.join(e,"data","staged-questions.json"),"stagedFile"),it=r(e=>g.join(e,"data","screening.json"),"screeningFile"),Ts=900*1e3,D=r(e=>e||d("this command needs --site <route>"),"needSite"),S=r((e,t)=>typeof e=="string"&&e.trim()?e.trim():d(`${t} must be non-empty text`),"text"),ee=r((e,t)=>e===void 0?void 0:t(e),"optional"),qs=/^prototype-[\w-]+\.html(?:[?#]\S*)?$/,Ms=/^visuals\/[\w-]+\/[\w-]+\.html$/,En=r((e,t)=>typeof e=="string"&&(qs.test(e)||Ms.test(e)||/^https?:\/\/\S+$/.test(e))?e:d(`${t} must be an http(s) URL or a site page such as prototype-<topic>.html?q=<id>`),"pageUrl"),Ht=r((e,t)=>typeof e=="boolean"?e:d(`${t} must be true or false`),"bool"),Fe=r((e,t)=>typeof e=="string"&&/^[\w.-]+$/.test(e)?e:d(`${t} must use only letters, digits, "_", "." and "-"`),"domId"),ot=r((e,t,n)=>{(!e||typeof e!="object"||Array.isArray(e))&&d(`${n} must be a JSON object`);const a=Object.keys(e).filter(i=>!t.includes(i));a.length&&d(`${n} has unknown field ${a.map(i=>`"${i}"`).join(", ")}; allowed: ${t.join(", ")}`)},"onlyKeys");function F(e){const t=/^([^/\s]+)\/([^/\s]+)$/.exec(e||"");return t?{file:t[1],id:t[2]}:d(`expected <file>/<id>, not "${e}"`)}r(F,"parseKey");async function Ue(e,t){const n=(await q(e)).find(i=>i.slug===t)||d(`this board has no item file "${t}"`),a=await $(n.file,null);return(!a||!Array.isArray(a.items))&&d(`${n.file} is not an item file with items[]`),{source:n,itemFile:a}}r(Ue,"loadItemFile");async function x(e,t){const{file:n,id:a}=F(t);let i=await Ue(e,n);!i.itemFile.items.some(s=>s.id===a)&&await Vr(e,t)&&(i=await Ue(e,n));const o=i.itemFile.items.find(s=>s.id===a)||d(`item file "${n}" has no item "${a}"`);return{...i,item:o}}r(x,"loadItem");const Jt=["md","html","json"];async function Ln(e,t){const n=new RegExp(`^${t.replace(/[.]/g,"\\.")}(?:~(\\d+))?\\.(${Jt.join("|")})$`);return(await j.readdir(e).catch(()=>[])).flatMap(a=>{const i=n.exec(a);return i?[{name:a,ext:i[2],n:Number(i[1]||1)}]:[]}).sort((a,i)=>a.n-i.n||Jt.indexOf(a.ext)-Jt.indexOf(i.ext)).filter((a,i,o)=>a.n!==o[i-1]?.n)}r(Ln,"replyFilesOf");async function el(e,t,n,a){D(e),Fe(t,"the event id");const i=(await z(g.join(e,"data","events.jsonl"))).find(h=>h.id===t);i||d(`no event "${t}" in this site's data/events.jsonl`);const o=i.kind==="ask"?await ze(e,t):null,s=o?o.key:i.kind==="ask"?`ask:${t}`:i.kind==="item-message"&&typeof i.data?.key=="string"?i.data.key:null;o&&ai(o.item)?(S(n,"the reply"),await ii(e,o,a)):a!==void 0&&d(`reply --title titles the New or answered card an ask became; "${t}" is not one`);const c=g.join(e,"data","replies"),l=await Ln(c,t),u=g.join(c,l.length?`${t}~${l.at(-1).n+1}.md`:`${t}.md`);await We(u,S(n,"the reply"));const p=s?await Cn(e,s,n):[],w=i.kind==="wave-triage"?["wave","file"].filter(h=>typeof i.data?.[h]=="string").map(h=>`${h}:${i.data[h]}`):[],f=o?`item:${o.key}`:w[0];return f&&p.push(...await Ei(e,f,"Acted on: replied")),{file:u,lines:p}}r(el,"writeReply");const Ha=r(e=>g.join(e,"data","working.json"),"workingFile");async function Ws(e){return(await $(Ha(e),{})).events||{}}r(Ws,"readWorking");const tl=["ask","item-message","wave-triage","overnight-triage"];async function nl(e,t){if(!t.length)return;const n=new Date().toISOString(),a=await Ws(e);await y(Ha(e),{events:{...a,...Object.fromEntries(t.map(i=>[i,ae(a,i)||n]))}})}r(nl,"markWorking");const Bn=r(e=>g.join(e,"data","push-state.json"),"pushStateFile");async function Us(e,t){D(e);const n=Date.parse((await $(Bn(e),{})).last_push);if(Number.isNaN(n))return 0;const a=g.join(e,"data","replies"),i=(await j.readdir(a).catch(()=>[])).filter(s=>Jt.includes(g.extname(s).slice(1)));return(await Promise.all(i.map(s=>j.stat(g.join(a,s)).then(c=>c.mtimeMs,()=>0)))).filter(s=>s>n&&s<=t.getTime()).length}r(Us,"repliesSincePush");async function Hs(e,t){return await y(Bn(D(e)),{last_push:t.toISOString()}),Bn(e)}r(Hs,"recordPush");const Js=g.join(g.dirname(To(import.meta.url)),"..","bin","kickflip.mjs");function zs(){if(!process.env.KICKFLIP_PUSH_CMD)return[Bo(),Js,"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 ue("KICKFLIP_PUSH_CMD must be a JSON array of strings")}r(zs,"pushCommand");async function al(e,t){const n=is(t.kind);n&&d(n),t.title===void 0&&d("push needs --title");const a=new Date,i=Qs(t.body,await Us(e,a)),o={kind:t.kind,title:t.title,body:i||void 0,url:Vs(t.url),tag:t.tag},[s,...c]=zs(),l=[...c,...Object.entries(o).flatMap(([w,f])=>f===void 0?[]:[`--${w}`,f]),...t.urgent?["--urgent"]:[],...t.now?["--now"]:[]],u=await new Promise(w=>{Lo(s,l,{encoding:"utf8"},(f,h,m)=>w({error:f,said:`${h||""}${m||""}`.split(`
6
- `).filter(k=>k.trim())}))}),p=u.error?typeof u.error.code=="number"?u.error.code:1:0;if(p!==0)throw Object.assign(new ue([...u.said,`kickflip push failed (${typeof u.error.code=="number"?`exit ${p}`:u.error.message}); the push was not recorded`].join(`
7
- `)),{exitCode:p});return await Hs(e,a),{lines:u.said}}r(al,"sendPush");const Ks=/(?:^| · )(and \d+ repl(?:y|ies))$/,Qs=r((e,t)=>[e,t&&`and ${t} ${t===1?"reply":"replies"}`].filter(Boolean).join(" \xB7 "),"withReplies"),Ja=160;function Gs(e){const t=String(e).split(`
8
- `).map(n=>n.replace(/\s+/g," ").trim()).find(Boolean)||"";return t.length>Ja?`${t.slice(0,Ja-1).trimEnd()}\u2026`:t}r(Gs,"pushLine");function Vs(e){if(!e||!e.startsWith("/"))return e;const t=new URL(e,"http://board");return/^#(?:selectedCard|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(Vs,"pushUrl");const Zs=r((e,t)=>`/${g.basename(e)}/#selectedCard=${encodeURIComponent(t)}&reply`,"threadUrl");async function Cn(e,t,n){const a=Gs(n);if(!a)return[];const i=zo(t),o=await as(i,s=>[a,Ks.exec(s)?.[1]].filter(Boolean).join(" \xB7 "),Zs(e,t));return o===null?[]:[`queued push ${i} now reads: ${o}`]}r(Cn,"freshenPush");const za=r(e=>g.join(e,"data","hidden.json"),"hiddenFile"),Ys=r(async e=>new Set((await $(za(e),{events:[]})).events||[]),"readHidden");let Ka=Promise.resolve();function il(e,t,n){Fe(t,"the event id");const a=Ka.then(async()=>{const i=await Ys(e);n?i.add(t):i.delete(t),await y(za(e),{events:[...i]})});return Ka=a.catch(()=>{}),a}r(il,"setHidden");const Qa=r(e=>g.join(e,"data","read.json"),"readMarksFile"),Xs=r(async e=>(await $(Qa(e),{})).cards||{},"readMarks");let Ga=Promise.resolve();function ol(e,t,n={}){const a=Ga.then(async()=>{const i=await Xs(e),o=new Date().toISOString(),s=r((l,u)=>String(u||"")>l?u:l,"later"),c=Object.fromEntries([...new Set(t)].sort().map(l=>[l,s(i[l]||o,n[l])]));JSON.stringify(c)!==JSON.stringify(i)&&await y(Qa(e),{cards:c})});return Ga=a.catch(()=>{}),a}r(ol,"markRead");const In=20*1024*1024,He=r(e=>g.join(e,"data","uploads"),"uploadsDir"),st=r((e,t)=>g.join(He(e),".meta",`${t}.json`),"uploadMeta"),Va=/^\d+-[\w.-]+$/,Za=/^[\w.+-]+\/[\w.+-]+$/,Ya=r(()=>Object.assign(new ue(`a file can be at most ${In/1024/1024} MB`),{status:413}),"tooLarge");async function sl(e,t,{name:n,type:a,length:i}){if(D(e),i>In)throw Ya();const o=String(n||"").trim().slice(0,200)||"file",s=g.basename(o).replace(/[^\w.-]+/g,"-").replace(/^[.-]+/,"").slice(-80)||"file",c=String(a||"").split(";")[0].trim().toLowerCase(),l=Za.test(c)?c:"application/octet-stream";await j.mkdir(g.dirname(st(e,"x")),{recursive:!0});let u,p;for(let h=Date.now();!p;h++)u=`${h}-${s}`,p=await j.open(g.join(He(e),u),"wx").catch(m=>m.code==="EEXIST"?null:Promise.reject(m));const w=g.join(He(e),u);let f=0;try{for await(const h of t){if(f+=h.length,f>In)throw Ya();await p.write(h)}}catch(h){throw await p.close(),await j.rm(w,{force:!0}),h}return await p.close(),await y(st(e,u),{name:o,type:l,size:f,at:new Date().toISOString()}),{name:o,url:`uploads/${u}`,path:w,type:l,size:f}}r(sl,"saveUpload");async function rl(e,t){if(!Va.test(t||""))return null;const n=g.join(He(e),t),a=await j.stat(n).catch(()=>null);if(!a?.isFile())return null;const i=await $(st(e,t),{});return{path:n,name:i.name||t,type:Za.test(i.type||"")?i.type:"application/octet-stream",size:a.size}}r(rl,"readUpload");const Xa=["github","slack"],ei=r(async(e,t)=>String(t).startsWith("ask:")?Dt(e,t.slice(4),"the ask"):x(e,t),"checkThreadKey");async function W(e,t,n,a={},{link:i}={}){D(e),await ei(e,t);const o={ts:new Date().toISOString(),who:"claude",kind:Ea,line:n,text:Ca(n,a),...i?{link:i}:{}};return await le(Z(e,t),o),{line:o,lines:$s(o).fault?await Cn(e,t,o.text):[]}}r(W,"appendStatus");async function rt(e,t,{text:n,link:a,log:i,who:o="claude",via:s,by:c}){D(e),await ei(e,t),/^[^\n]{1,40}$/.test(o.trim())||d("--who takes claude, love or a reviewer's name"),s!==void 0&&!Xa.includes(s)&&d(`--via takes ${Xa.join(" or ")}`);const l=s===void 0?zt(n):S(n,"--text"),u={ts:new Date().toISOString(),who:o.trim(),text:l,link:ee(a,w=>En(w,"--link")),log:i,via:s,by:c},p=Z(e,t);return await le(p,u),{file:p,lines:u.who==="claude"&&!s?await Cn(e,t,u.text):[]}}r(rt,"appendMessage");function zt(e){const t=S(e,"--text");return t.length>La&&d(`--text runs to ${t.length} characters, past a message's ${La}: rewrite it shorter, or put the detail in an HTML page (board.mjs visual add, or --link to a page) and link it`),t}r(zt,"messageText");async function Je(e,t,{command:n,text:a=qt[n],who:i="claude",by:o,card:s}){const c={ts:new Date().toISOString(),who:i,command:n,text:a,...o?{by:o}:{},...s?{card:s}:{}};return await le(Z(e,t),c),{lines:[]}}r(Je,"appendCommand");const xe=r(e=>g.join(e,"data","ask-links.json"),"askLinksFile");async function _e(e){return(await $(xe(e),{})).links||{}}r(_e,"readAskLinks");async function H(e,t){const{tickets:n}=Se(await oe(e)),a=await q(e),i=/^ask:(.+)$/.exec(t)?.[1];if(i===void 0){const s=/^([^/\s]+)\/([^/\s]+)$/.exec(t);if(!s)return t;const c=a.find(p=>p.slug===s[1]),l=c&&await $(c.file,null);if(!l)return s[2];const u=(l.items||[]).find(p=>p.id===s[2]);return tt(l,u||{id:s[2]},n)}const o=e?ae(await _e(e),i):void 0;if(o)return H(e,o);for(const s of a){const c=await $(s.file,null),l=(Array.isArray(c?.items)?c.items:[]).find(u=>u.from_ask===i);if(l)return tt(c,l,n)}return`task ${i}`}r(H,"cardName");async function cl(e,t){const n=(await z(g.join(e,"data","events.jsonl"))).find(a=>a.id===t);return n?.kind==="ask"?H(e,`ask:${t}`):typeof n?.data?.key=="string"?H(e,n.data.key):`the ${n?.kind} event`}r(cl,"eventCard");async function ze(e,t){for(const n of await q(e)){const a=await $(n.file,null),i=(Array.isArray(a?.items)?a.items:[]).find(o=>o.from_ask===t);if(i)return{source:n,itemFile:a,item:i,key:`${n.slug}/${i.id}`}}return null}r(ze,"askCardOf");const Tn=r(e=>!e.phase&&!e.answered_at&&!we(e)&&!be(e)&&!e.filed_held,"stillNew");function qn(e,t){const n=t.filter(i=>i.kind==="ask-edited"&&i.data?.id===e.id&&typeof i.data?.text=="string").sort((i,o)=>String(i.ts).localeCompare(String(o.ts))).at(-1);return String(n?n.data.text:e.data?.text||"").trim().split(`
9
- `)[0].trim()||(e.data?.files||[]).map(i=>i?.name).filter(Boolean).join(", ")||"Ask"}r(qn,"askTitle");const ll=r((e,t,n)=>ce(e,async()=>{D(e);const a=await z(g.join(e,"data","events.jsonl")),i=n||a.find(l=>l.id===t&&l.kind==="ask")||d(`no ask "${t}" in this site's data/events.jsonl`);if(await ze(e,t)||await ri(e,t,a))return null;const{source:o,itemFile:s}=await ti(e),c=await ni(e,o,i,qn(i,a));return s.items.push(c),await y(o.file,s),`${o.slug}/${c.id}`}),"fileAsk");async function ti(e){const t=await q(e);for(const n of t){const a=await $(n.file,null);if(a)return Array.isArray(a.items)||d(`${n.file} is not an item file with items[]`),{source:n,itemFile:a}}return(await oe(e)).items==="waves"&&d("this board has no wave yet to file a new task in; start a wave first"),await j.mkdir(t[0].dir,{recursive:!0}),{source:t[0],itemFile:{items:[]}}}r(ti,"askFile");async function ni(e,t,n,a){const i=new Date().toISOString(),o={id:await no(e),title:a,created:i,lane:"todo",lane_at:i,from_ask:n.id};return o.plan=Zt(t.dir,o.id),await Yt(g.join(t.dir,o.plan),`# ${o.title}
10
- `),o}r(ni,"newAskCard");const dl=r(e=>ce(e,async()=>{D(e);const t=r((...m)=>g.join(e,"data",...m),"data"),n=await z(t("events.jsonl")),a=await _e(e),i=new Map(Object.entries(a));for(const m of await q(e))for(const k of(await $(m.file,{})).items||[])k.from_ask&&i.set(k.from_ask,`${m.slug}/${k.id}`);const o=new Set(n.filter(m=>m.kind==="ask-withdrawn").map(m=>m.data?.id)),s=n.filter(m=>m.kind==="ask"&&!o.has(m.id)&&!i.has(m.id)).sort((m,k)=>String(m.ts).localeCompare(String(k.ts))),c=(await $(t("ask-progress.json"),{})).asks||{},l=(await $(t("ask-titles.json"),{})).titles||{},u=new Map(n.filter(m=>m.kind==="ask-done").map(m=>[m.data?.id,String(m.ts)])),p=[];let w;for(const m of s){const k=await z(Z(e,`ask:${m.id}`));if(k.some(A=>A.line==="ask-moved"))continue;const _=await Promise.all((await Ln(t("replies"),m.id)).map(A=>j.stat(t("replies",A.name)).then(I=>I.mtime.toISOString()))),N=k.filter(A=>(A.who||"claude")==="claude"&&A.kind!=="status").map(A=>String(A.ts)),v=[..._,...N].sort().pop()||[ae(c,m.id)?.at,u.get(m.id)].filter(Boolean).sort().pop();w||=await ti(e);const O=await ni(e,w.source,m,ae(l,m.id)||qn(m,n));O.created=m.ts,v&&Ft(O,"done",v),w.itemFile.items.push(O),await y(w.source.file,w.itemFile),i.set(m.id,`${w.source.slug}/${O.id}`),p.push(i.get(m.id))}const f=r(m=>i.get(/^item:ask:(.+)$/.exec(m||"")?.[1]),"cardOf"),h=await $(E(e),null);if(h?.items?.some(m=>f(m.topic))){for(const m of h.items)f(m.topic)&&(m.topic=`item:${f(m.topic)}`);await y(E(e),h)}for(const m of["ask-progress.json","ask-titles.json"])await j.rm(t(m),{force:!0});return p}),"fileAsks"),ul=r((e,t)=>ce(e,async()=>{const n=await ze(D(e),t);if(!n||!Tn(n.item))return null;const a=await z(g.join(e,"data","events.jsonl"));return n.item.title=qn(a.find(i=>i.id===t&&i.kind==="ask"),a),await y(n.source.file,n.itemFile),n.key}),"retitleAskCard");async function Mn(e,{source:t,itemFile:n,item:a,key:i}){n.items=n.items.filter(l=>l!==a);const o=Number(/^T-([1-9]\d*)$/.exec(a.id)?.[1]||0);o>(Number(n.last_task)||0)&&(n.last_task=o),await y(t.file,n),a.plan&&await j.rm(g.join(t.dir,a.plan),{force:!0});const s=Z(e,i),c=await z(s);return await j.rm(s,{force:!0}),c}r(Mn,"dropCard");const fl=r((e,t)=>ce(e,async()=>{const n=await ze(D(e),t);return!n||!Tn(n.item)?null:(await Mn(e,n),n.key)}),"dropAskCard"),ai=r(e=>!e.phase&&!e.closed_at&&!be(e)&&(!we(e)||!!e.answered_at),"answerable");async function ii(e,t,n){const{item:a,key:i}=t;a.from_ask||d(`${i} is not a card an ask became; write in its thread with thread ${i} --text`),ai(a)||d(`${i} is sorted (${a.phase||Ce[a.lane]}), so it is work: write in its thread with thread ${i} --text`),n!==void 0&&(a.title=S(n,"--title")),a.answered_at||=new Date().toISOString(),await y(t.source.file,t.itemFile)}r(ii,"markAnswered");async function oi(e,t,n){const a=await ze(e,t);a&&a.key!==n&&d(`ask "${t}" is already card ${a.key}: sort it with item set ${a.key} --phase, or merge it with item relate-ask ${t} <card>`)}r(oi,"refuseFiled");async function wl(e,t,n,a){D(e);const{source:i,itemFile:o,item:s}=await x(e,t),c={source:i,itemFile:o,item:s,key:t};return zt(n),a!==void 0&&S(a,"--title"),await ii(e,c,a),rt(e,t,{text:n})}r(wl,"answerCard");async function pl(e,t,n,a,i){D(e),Fe(t,"the event id"),(await z(g.join(e,"data","events.jsonl"))).some(l=>l.id===t&&l.kind==="ask")||d(`no ask "${t}" in this site's data/events.jsonl`),await Wn(e,t),await x(e,n),S(a,"--summary"),i!==void 0&&S(i,"--title");const s=await ze(e,t);if(s&&s.key===n&&d(`ask "${t}" is ${n} already`),s&&!Tn(s.item)&&d(`ask "${t}" became ${s.key}, which is sorted; to fold that card's notes into ${n}, use item notes ${n} --from ${s.key}, then close it`),s){const l=await ce(e,()=>Mn(e,s)),u=Z(e,`ask:${t}`);for(const p of l)await le(u,p);await le(u,{ts:new Date().toISOString(),who:"claude",kind:Ea,line:"card-merged",text:Ca("card-merged",{card:await H(e,n)}),into:n,title:i??s.item.title,link:`#selectedCard=${encodeURIComponent(n)}`})}const c=await _e(e);return await y(xe(e),{links:{...c,[t]:n}}),await rt(e,n,{text:a}),xe(e)}r(pl,"relateAsk");async function ml(e,t){await Dt(e,t,"the ask");const n=await _e(e);return ae(n,t)===void 0&&d(`ask "${t}" is not folded into a card`),delete n[t],await y(xe(e),{links:n}),xe(e)}r(ml,"unfoldAsk");const si=r(async(e,t)=>(await z(Z(e,`ask:${t}`))).find(n=>n.line==="ask-moved"),"movedLine");async function Wn(e,t){const n=await si(e,t);n&&d(`ask "${t}" was moved to ${n.link}; it lives there now`)}r(Wn,"refuseMoved");async function ri(e,t,n){const a=`ask "${t}"`;if(n.some(l=>l.kind==="ask-withdrawn"&&l.data?.id===t))return{why:`${a} was deleted by the owner`};const i=await si(e,t);if(i)return{why:`${a} was already moved to ${i.link}`};const o=ae(await _e(e),t);if(o)return{why:`${a} is folded into ${o}; run ask unfold ${t} first`};const s=[];for(const l of await q(e)){const u=await $(l.file,null);for(const p of Array.isArray(u?.items)?u.items:[])p.from_ask===t&&s.push({key:`${l.slug}/${p.id}`,it:p})}const c=s.find(({it:l})=>be(l)||we(l)||l.answered_at);return c?{why:`${a} became ${c.key}, which has started or been answered`}:s.length?{items:s.map(l=>l.key)}:null}r(ri,"askNotNew");async function er(e,t,n){const a=/^uploads\/([\w.-]+)$/.exec(n?.url||"")?.[1],i=Va.test(a||"")?g.join(He(e),a):null;if(!i||!await j.stat(i).then(l=>l.isFile(),()=>!1))return{name:String(n?.name||a||"file")};await j.mkdir(g.dirname(st(t,"x")),{recursive:!0});const o=a.replace(/^\d+-/,"");let s;for(let l=Date.now();s=`${l}-${o}`,!await j.copyFile(i,g.join(He(t),s),Ro.COPYFILE_EXCL).then(()=>!0,p=>p.code==="EEXIST"?!1:Promise.reject(p));l++);const c=await $(st(e,a),null);return c&&await y(st(t,s),c),{...n,url:`uploads/${s}`,path:g.join(He(t),s)}}r(er,"copyUpload");async function hl(e,t,n){D(e),Fe(t,"the event id"),(typeof n!="string"||!n.trim())&&d("ask move needs --to <route>, the board to move it to");const a=await z(g.join(e,"data","events.jsonl")),i=a.find(k=>k.id===t&&k.kind==="ask")||d(`no ask "${t}" in this site's data/events.jsonl`),o=ge(),s=o.find(k=>k.route===n)||d(`--to ${n}: no board at /${n} in the hub's manifest; the boards are ${o.map(k=>k.route).join(", ")||"none"}`);Pe(s.dir,e)&&d(`--to ${n}: that is this board`);const c=await ri(e,t,a);c?.why&&d(c.why);const l=a.filter(k=>k.kind==="ask-edited"&&k.data?.id===t&&typeof k.data?.text=="string").sort((k,_)=>String(k.ts).localeCompare(String(_.ts))),u=l.at(-1),p=[];for(const k of[...i.data?.files||[],...l.flatMap(_=>_.data.files||[])])p.push(await er(e,s.dir,k));const w={route:g.basename(e),title:(await oe(e)).title,id:t},f=u?u.data.text:i.data?.text||"",h=await he(s,"ask",{text:f,...p.length?{files:p}:{},from:w}),m=`/${n}/#selectedCard=${encodeURIComponent(`ask:${h}`)}`;await W(e,`ask:${t}`,"ask-moved",{board:s.title},{link:m});for(const k of c?.items||[]){const{source:_,itemFile:N,item:v}=await x(e,k);await ce(e,()=>Mn(e,{source:_,itemFile:N,item:v,key:k}))}return{file:g.join(s.dir,"data","events.jsonl"),lines:[`moved to ${m}`,...(c?.items||[]).map(k=>`dropped: ${k}`)]}}r(hl,"moveAsk");async function gl(e,t,{state:n,text:a}={}){return D(e),["posted","needs"].includes(n)||d("review record needs --state posted or --state needs"),String(a??"").trim()||d("review record needs the review text, as --text or --file"),li(e,await ci(e,t,"review record"),{state:n,text:a})}r(gl,"recordReview");async function ci(e,t,n){/^[1-9]\d{0,6}$/.test(String(t))||d(`${n} takes the PR number, such as 437, not "${t}"`);const a=await $(g.join(e,"data","incoming.json"),{});return{...(a?.prs||[]).find(s=>s.number===Number(t))||(await $(g.join(e,"data","reviews.json"),{}))[t]||d(`PR #${t} is not an incoming PR on this board`),repo:a?.repo||se(e,{})}}r(ci,"incomingPR");async function li(e,{number:t,title:n,author:a,url:i,touches:o=[],asked:s=!1,head:c},{state:l,text:u,review_url:p}){const w=g.join(e,"data","reviews.json"),f=await $(w,{});return f[t]={number:Number(t),title:n,author:a,url:i,touches:o,asked:s,head:c,state:l,text:u,...p?{review_url:p}:{},at:new Date().toISOString()},await y(w,f),{file:w,lines:[]}}r(li,"saveReview");async function $l(e,t,{words:n,readAt:a}){D(e);const i=await ci(e,t,"review post"),o=String(n??"").trim()||d("review post needs the review text, as --file"),s=`${St}Claude review from the ${(await oe(e)).title} board`;(o.startsWith(St.trim())||o.includes("Claude review from")||o.includes(Dn))&&d(`review post adds the ${St.trim()} header and the claude-bridge marker itself; pass only your words`);const c=i.repo||d("review post needs a board on GitHub; this board has no repo there");Number.isNaN(Date.parse(a))&&d("--read-at takes the time you read the PR, such as 2026-11-05T09:30:00Z");const l=Se(await oe(e)).github_login;try{const u=await xs({repo:c,pr:i.number,since:a});u.length&&d(`PR #${t} got ${u.length===1?"a review":`${u.length} reviews`} after ${a} (${u.map(w=>`${w.login} at ${w.at}`).join(", ")}); reread the PR and review again`);const p=await ys({repo:c,pr:i.number,head:i.head,body:`${s}
1
+ var Zo=Object.defineProperty;var c=(t,e)=>Zo(t,"name",{value:e,configurable:!0});import A from"node:fs/promises";import{constants as Yo,existsSync as wt,readFileSync as Xo}from"node:fs";import $ from"node:path";import An from"node:os";import{execFile as ts}from"node:child_process";import{nodeBin as es}from"../bin/install.mjs";import{gh as Ta,limitWords as ns}from"../shared/gh.mjs";import{squashBody as as}from"./commit-message.mjs";import{fileURLToPath as is}from"node:url";import{BUILD_REFUSED as qa,BUILDER_ASK as Ke,COMMANDS as ze,LANDER as Ma,LANES as qt,MOVE as Wa,PAUSE_CLEARS as Ua,PHASES as Pn,handedBackAt as Dn,MAX_IMPLEMENTERS as os,MAX_PLANNERS as ss,builds as oe,waveItems as Mt,mergeBlockers as rs,modelName as Ge,noTakePicked as cs,ownerQuestion as Wt,plans as Ut,QUESTION_REOPEN as ls,PLANNER_WORD as ds,providerOf as Oe,owesNext as Fn,pushTag as us,refOf as se,roundOf as Rn,roundSettledBy as fs,HELPER as X,VISUAL as gt,visualAgent as ws}from"./domain.mjs";import{GITHUB_STATE as Nn,appendEvent as $t,listBoards as kt,readManifest as ps,samePath as Rt,withManifestLock as ms,writeManifest as hs}from"../hub/boards.mjs";import{readUsageGate as Ha,pauseReason as gs,pauseReasonFor as $s,heldFor as ks,holdsWork as ys,builderPick as En,pauseEnd as bs}from"../shared/usage-gate.mjs";import{reviseQueued as xs,pushKindError as _s,readClaudeModel as Ln}from"../hub/push.mjs";import{AT_RE as Ss}from"../hub/duration.mjs";import{routeRecord as at}from"../hub/routes.mjs";import{ticketSource as Ja,resolveTicket as vs,ticketNamed as Ka,ticketTarget as js,moveTicket as Os,cardIdOf as As}from"./tickets.mjs";import{LINEAR_NEEDS_KEY as Ps,linearStatus as Ds,linearWorks as Fs}from"../hub/linear.mjs";import{validateBranch as Rs}from"../hub/repos.mjs";import{withFileLock as re}from"../hub/locks.mjs";import{audit as Ns,auditLines as Es,boardAudit as za,readAudit as Ls}from"../shared/audit.mjs";import{merge3 as Bs}from"./merge3.mjs";import{HUB as Ga,MESSAGE_LIMIT as Qa,BRIEF_LINE_LIMIT as Va,hubLineOf as Cs,hubText as Za,detailOf as Ya}from"./hub-lines.mjs";import{fetchPR as Xa,reportOf as ti,githubLogin as Is,postToPR as Ts,postReview as qs,reviewsSince as Ms,CLAUDE_PREFIX as Ae,CLAUDE_MARK as Bn}from"../hub/pr-report.mjs";import{allLanded as Ws,cardPRs as Ht,hasPR as St,parsePRRef as Cn,prKeyOf as Pe,prNames as Nt,prURL as In,storedPRs as Et}from"../shared/card-prs.mjs";import{reviewLinks as Us,topicItems as Hs,reviewersOf as Tn}from"./review.mjs";import{readiness as ei}from"../hub/readiness.mjs";import{SlackError as Js,SLACK_NEEDS_TOKEN as Ks,readSlack as zs,savedSlack as qn,slackDay as Mn,slackUserId as Gs}from"../hub/slack.mjs";import"../bin/install.mjs";import{readPermissions as Qs}from"./permissions.mjs";import{validBuildTarget as ni}from"./build-script.mjs";import{parseCheck as Vs,checkText as Zs}from"../shared/owner-check.mjs";import{RuleError as Ys,rulesOf as ai,addRule as Xs,editRule as tr,removeRule as er,applyRules as nr,readHubRules as Qe,writeHubRules as ar}from"../hub/rules.mjs";import{shareEntries as ir,validLogin as or}from"../hub/share.mjs";class pt extends Error{static{c(this,"BoardError")}}const d=c(t=>{throw new pt(t)},"fail"),sr=c(()=>$.join(An.homedir(),".claude","kickflip","sites"),"sitesDir"),Ve=c(()=>$.join(An.homedir(),".claude","waves"),"wavesDir"),ii=Symbol("read as"),g=c(async(t,e)=>{let n;try{n=await A.readFile(t,"utf8")}catch{return e}try{const a=JSON.parse(n);return a!==null&&typeof a=="object"&&!Array.isArray(a)?{...a,[ii]:n}:a}catch{return e}},"readJSON"),J=c(async t=>{try{return(await A.readFile(t,"utf8")).split(`
2
+ `).filter(Boolean).map(e=>JSON.parse(e))}catch{return[]}},"readLines");async function Jt(t,e){await A.mkdir($.dirname(t),{recursive:!0});const n=`${t}.${process.pid}.tmp`;await A.writeFile(n,e),await A.rename(n,t)}c(Jt,"replace");const b=c((t,e)=>{const{[ii]:n,...a}=e??{};return n===void 0?Jt(t,JSON.stringify(e,null,2)+`
3
+ `):re(t,async()=>{const i=JSON.parse(n),o=JSON.parse(await A.readFile(t,"utf8").catch(()=>n));await Jt(t,JSON.stringify(Bs(i,a,o),null,2)+`
4
+ `)})},"writeJSON");async function dt(t,e){await A.mkdir($.dirname(t),{recursive:!0}),await A.appendFile(t,JSON.stringify(e)+`
5
+ `)}c(dt,"appendLine");async function jl(t){/^[\w-]+$/.test(t||"")||d(`--site takes a route such as ios-orchestrator, not "${t}"`);const e=$.join(sr(),t);return await A.stat(e).then(n=>n.isDirectory(),()=>!1)||d(`no site at ${e}`),e}c(jl,"siteDir");const rt=c(async t=>({title:"Board",items:"waves",...t?await g($.join(t,"board.json"),{}):{}}),"boardConfig");async function q(t){const e=await rt(t);if(e.items==="waves")try{return(await A.readdir(Ve(),{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>({slug:a.name,dir:$.join(Ve(),a.name),file:$.join(Ve(),a.name,"wave.json")}))}catch{return[]}const n=$.resolve(t,e.items);return[{slug:e.slug||$.basename(e.items,".json"),dir:$.dirname(n),file:n}]}c(q,"itemSources");const Z=c((t,e)=>$.join(t,"data","threads",e.replace(/[^\w.-]+/g,"__")+".jsonl"),"threadFile"),B=c(t=>$.join(t,"data","owner.json"),"ownerFile"),ut=c(t=>$.join(t,"data","staged-questions.json"),"stagedFile"),ce=c(t=>$.join(t,"data","screening.json"),"screeningFile"),rr=900*1e3,D=c(t=>t||d("this command needs --site <route>"),"needSite"),j=c((t,e)=>typeof t=="string"&&t.trim()?t.trim():d(`${e} must be non-empty text`),"text"),it=c((t,e)=>t===void 0?void 0:e(t),"optional"),cr=/^prototype-[\w-]+\.html(?:[?#]\S*)?$/,lr=/^visuals\/[\w-]+\/[\w-]+\.html$/,Wn=c((t,e)=>typeof t=="string"&&(cr.test(t)||lr.test(t)||/^https?:\/\/\S+$/.test(t))?t:d(`${e} must be an http(s) URL or a site page such as prototype-<topic>.html?q=<id>`),"pageUrl"),Ze=c((t,e)=>typeof t=="boolean"?t:d(`${e} must be true or false`),"bool"),vt=c((t,e)=>typeof t=="string"&&/^[\w.-]+$/.test(t)?t:d(`${e} must use only letters, digits, "_", "." and "-"`),"domId"),le=c((t,e,n)=>{(!t||typeof t!="object"||Array.isArray(t))&&d(`${n} must be a JSON object`);const a=Object.keys(t).filter(i=>!e.includes(i));a.length&&d(`${n} has unknown field ${a.map(i=>`"${i}"`).join(", ")}; allowed: ${e.join(", ")}`)},"onlyKeys");function R(t){const e=/^([^/\s]+)\/([^/\s]+)$/.exec(t||"");return e?{file:e[1],id:e[2]}:d(`expected <file>/<id>, not "${t}"`)}c(R,"parseKey");async function Kt(t,e){const n=(await q(t)).find(i=>i.slug===e)||d(`this board has no item file "${e}"`),a=await g(n.file,null);return(!a||!Array.isArray(a.items))&&d(`${n.file} is not an item file with items[]`),{source:n,itemFile:a}}c(Kt,"loadItemFile");async function x(t,e){const{file:n,id:a}=R(e);let i=await Kt(t,n);!i.itemFile.items.some(s=>s.id===a)&&await _c(t,e)&&(i=await Kt(t,n));const o=i.itemFile.items.find(s=>s.id===a)||d(`item file "${n}" has no item "${a}"`);return{...i,item:o}}c(x,"loadItem");const Ye=["md","html","json"];async function Un(t,e){const n=new RegExp(`^${e.replace(/[.]/g,"\\.")}(?:~(\\d+))?\\.(${Ye.join("|")})$`);return(await A.readdir(t).catch(()=>[])).flatMap(a=>{const i=n.exec(a);return i?[{name:a,ext:i[2],n:Number(i[1]||1)}]:[]}).sort((a,i)=>a.n-i.n||Ye.indexOf(a.ext)-Ye.indexOf(i.ext)).filter((a,i,o)=>a.n!==o[i-1]?.n)}c(Un,"replyFilesOf");async function Ol(t,e,n,a){D(t),vt(e,"the event id");const i=(await J($.join(t,"data","events.jsonl"))).find(h=>h.id===e);i||d(`no event "${e}" in this site's data/events.jsonl`);const o=i.kind==="ask"?await Vt(t,e):null,s=o?o.key:i.kind==="ask"?`ask:${e}`:i.kind==="item-message"&&typeof i.data?.key=="string"?i.data.key:null;o&&$i(o.item)?(j(n,"the reply"),await ki(t,o,a)):a!==void 0&&d(`reply --title titles the New or answered card an ask became; "${e}" is not one`);const r=$.join(t,"data","replies"),l=await Un(r,e),u=$.join(r,l.length?`${e}~${l.at(-1).n+1}.md`:`${e}.md`);await Jt(u,j(n,"the reply"));const p=s?await Jn(t,s,n):[],w=i.kind==="wave-triage"?["wave","file"].filter(h=>typeof i.data?.[h]=="string").map(h=>`${h}:${i.data[h]}`):[],f=o?`item:${o.key}`:w[0];return f&&p.push(...await Xi(t,f,"Acted on: replied")),{file:u,lines:p}}c(Ol,"writeReply");const oi=c(t=>$.join(t,"data","working.json"),"workingFile");async function dr(t){return(await g(oi(t),{})).events||{}}c(dr,"readWorking");const Al=["ask","item-message","wave-triage","overnight-triage"];async function Pl(t,e){if(!e.length)return;const n=new Date().toISOString(),a=await dr(t);await b(oi(t),{events:{...a,...Object.fromEntries(e.map(i=>[i,at(a,i)||n]))}})}c(Pl,"markWorking");const Hn=c(t=>$.join(t,"data","push-state.json"),"pushStateFile");async function ur(t,e){D(t);const n=Date.parse((await g(Hn(t),{})).last_push);if(Number.isNaN(n))return 0;const a=$.join(t,"data","replies"),i=(await A.readdir(a).catch(()=>[])).filter(s=>Ye.includes($.extname(s).slice(1)));return(await Promise.all(i.map(s=>A.stat($.join(a,s)).then(r=>r.mtimeMs,()=>0)))).filter(s=>s>n&&s<=e.getTime()).length}c(ur,"repliesSincePush");async function fr(t,e){return await b(Hn(D(t)),{last_push:e.toISOString()}),Hn(t)}c(fr,"recordPush");const wr=$.join($.dirname(is(import.meta.url)),"..","bin","kickflip.mjs");function pr(){if(!process.env.KICKFLIP_PUSH_CMD)return[es(),wr,"push"];try{const t=JSON.parse(process.env.KICKFLIP_PUSH_CMD);if(Array.isArray(t)&&t.length&&t.every(e=>typeof e=="string"))return t}catch{}throw new pt("KICKFLIP_PUSH_CMD must be a JSON array of strings")}c(pr,"pushCommand");async function Dl(t,e){const n=_s(e.kind);n&&d(n),e.title===void 0&&d("push needs --title");const a=new Date,i=hr(e.body,await ur(t,a)),o={kind:e.kind,title:e.title,body:i||void 0,url:$r(e.url),tag:e.tag},[s,...r]=pr(),l=[...r,...Object.entries(o).flatMap(([w,f])=>f===void 0?[]:[`--${w}`,f]),...e.urgent?["--urgent"]:[],...e.now?["--now"]:[]],u=await new Promise(w=>{ts(s,l,{encoding:"utf8"},(f,h,m)=>w({error:f,said:`${h||""}${m||""}`.split(`
6
+ `).filter(y=>y.trim())}))}),p=u.error?typeof u.error.code=="number"?u.error.code:1:0;if(p!==0)throw Object.assign(new pt([...u.said,`kickflip push failed (${typeof u.error.code=="number"?`exit ${p}`:u.error.message}); the push was not recorded`].join(`
7
+ `)),{exitCode:p});return await fr(t,a),{lines:u.said}}c(Dl,"sendPush");const mr=/(?:^| · )(and \d+ repl(?:y|ies))$/,hr=c((t,e)=>[t,e&&`and ${e} ${e===1?"reply":"replies"}`].filter(Boolean).join(" \xB7 "),"withReplies"),si=160;function gr(t){const e=String(t).split(`
8
+ `).map(n=>n.replace(/\s+/g," ").trim()).find(Boolean)||"";return e.length>si?`${e.slice(0,si-1).trimEnd()}\u2026`:e}c(gr,"pushLine");function $r(t){if(!t||!t.startsWith("/"))return t;const e=new URL(t,"http://board");return/^#(?:selectedCard|item)=[^&]+$/.test(e.hash)&&(e.hash=`${e.hash}&reply`),/\/[\w-]+\.html$/.test(e.pathname)&&!e.pathname.endsWith("/index.html")&&e.searchParams.set("from","push"),e.pathname+e.search+e.hash}c($r,"pushUrl");const kr=c((t,e)=>`/${$.basename(t)}/#selectedCard=${encodeURIComponent(e)}&reply`,"threadUrl");async function Jn(t,e,n){const a=gr(n);if(!a)return[];const i=us(e),o=await xs(i,s=>[a,mr.exec(s)?.[1]].filter(Boolean).join(" \xB7 "),kr(t,e));return o===null?[]:[`queued push ${i} now reads: ${o}`]}c(Jn,"freshenPush");const ri=c(t=>$.join(t,"data","hidden.json"),"hiddenFile"),yr=c(async t=>new Set((await g(ri(t),{events:[]})).events||[]),"readHidden");let ci=Promise.resolve();function Fl(t,e,n){vt(e,"the event id");const a=ci.then(async()=>{const i=await yr(t);n?i.add(e):i.delete(e),await b(ri(t),{events:[...i]})});return ci=a.catch(()=>{}),a}c(Fl,"setHidden");const li=c(t=>$.join(t,"data","read.json"),"readMarksFile"),br=c(async t=>(await g(li(t),{})).cards||{},"readMarks");let di=Promise.resolve();function Rl(t,e,n={}){const a=di.then(async()=>{const i=await br(t),o=new Date().toISOString(),s=c((l,u)=>String(u||"")>l?u:l,"later"),r=Object.fromEntries([...new Set(e)].sort().map(l=>[l,s(i[l]||o,n[l])]));JSON.stringify(r)!==JSON.stringify(i)&&await b(li(t),{cards:r})});return di=a.catch(()=>{}),a}c(Rl,"markRead");const Kn=20*1024*1024,zt=c(t=>$.join(t,"data","uploads"),"uploadsDir"),de=c((t,e)=>$.join(zt(t),".meta",`${e}.json`),"uploadMeta"),ui=/^\d+-[\w.-]+$/,fi=/^[\w.+-]+\/[\w.+-]+$/,wi=c(()=>Object.assign(new pt(`a file can be at most ${Kn/1024/1024} MB`),{status:413}),"tooLarge");async function Nl(t,e,{name:n,type:a,length:i}){if(D(t),i>Kn)throw wi();const o=String(n||"").trim().slice(0,200)||"file",s=$.basename(o).replace(/[^\w.-]+/g,"-").replace(/^[.-]+/,"").slice(-80)||"file",r=String(a||"").split(";")[0].trim().toLowerCase(),l=fi.test(r)?r:"application/octet-stream";await A.mkdir($.dirname(de(t,"x")),{recursive:!0});let u,p;for(let h=Date.now();!p;h++)u=`${h}-${s}`,p=await A.open($.join(zt(t),u),"wx").catch(m=>m.code==="EEXIST"?null:Promise.reject(m));const w=$.join(zt(t),u);let f=0;try{for await(const h of e){if(f+=h.length,f>Kn)throw wi();await p.write(h)}}catch(h){throw await p.close(),await A.rm(w,{force:!0}),h}return await p.close(),await b(de(t,u),{name:o,type:l,size:f,at:new Date().toISOString()}),{name:o,url:`uploads/${u}`,path:w,type:l,size:f}}c(Nl,"saveUpload");async function El(t,e){if(!ui.test(e||""))return null;const n=$.join(zt(t),e),a=await A.stat(n).catch(()=>null);if(!a?.isFile())return null;const i=await g(de(t,e),{});return{path:n,name:i.name||e,type:fi.test(i.type||"")?i.type:"application/octet-stream",size:a.size}}c(El,"readUpload");const pi=["github","slack"],mi=c(async(t,e)=>String(e).startsWith("ask:")?Ce(t,e.slice(4),"the ask"):x(t,e),"checkThreadKey");async function W(t,e,n,a={},{link:i}={}){D(t),await mi(t,e);const o={ts:new Date().toISOString(),who:"claude",kind:Ga,line:n,text:Za(n,a),...Ya(n,a)?{detail:Ya(n,a)}:{},...i?{link:i}:{}};return await dt(Z(t,e),o),{line:o,lines:Cs(o).fault?await Jn(t,e,o.text):[]}}c(W,"appendStatus");async function Gt(t,e,{text:n,link:a,log:i,who:o="claude",via:s,by:r}){D(t),await mi(t,e),/^[^\n]{1,40}$/.test(o.trim())||d("--who takes claude, love or a reviewer's name"),s!==void 0&&!pi.includes(s)&&d(`--via takes ${pi.join(" or ")}`);const l=s===void 0?Xe(n):j(n,"--text"),u={ts:new Date().toISOString(),who:o.trim(),text:l,link:it(a,w=>Wn(w,"--link")),log:i,via:s,by:r},p=Z(t,e);return await dt(p,u),{file:p,lines:u.who==="claude"&&!s?await Jn(t,e,u.text):[]}}c(Gt,"appendMessage");function Xe(t){const e=j(t,"--text");return e.length>Qa&&d(`--text runs to ${e.length} characters, past a message's ${Qa}: rewrite it shorter, or put the detail in an HTML page (board.mjs visual add, or --link to a page) and link it`),e}c(Xe,"messageText");async function Qt(t,e,{command:n,text:a=ze[n],who:i="claude",by:o,card:s}){const r={ts:new Date().toISOString(),who:i,command:n,text:a,...o?{by:o}:{},...s?{card:s}:{}};return await dt(Z(t,e),r),{lines:[]}}c(Qt,"appendCommand");const jt=c(t=>$.join(t,"data","ask-links.json"),"askLinksFile");async function Ot(t){return(await g(jt(t),{})).links||{}}c(Ot,"readAskLinks");async function K(t,e){const{tickets:n}=At(await rt(t)),a=await q(t),i=/^ask:(.+)$/.exec(e)?.[1];if(i===void 0){const s=/^([^/\s]+)\/([^/\s]+)$/.exec(e);if(!s)return e;const r=a.find(p=>p.slug===s[1]),l=r&&await g(r.file,null);if(!l)return s[2];const u=(l.items||[]).find(p=>p.id===s[2]);return se(l,u||{id:s[2]},n)}const o=t?at(await Ot(t),i):void 0;if(o)return K(t,o);for(const s of a){const r=await g(s.file,null),l=(Array.isArray(r?.items)?r.items:[]).find(u=>u.from_ask===i);if(l)return se(r,l,n)}return`task ${i}`}c(K,"cardName");async function Ll(t,e){const n=(await J($.join(t,"data","events.jsonl"))).find(a=>a.id===e);return n?.kind==="ask"?K(t,`ask:${e}`):typeof n?.data?.key=="string"?K(t,n.data.key):`the ${n?.kind} event`}c(Ll,"eventCard");async function Vt(t,e){for(const n of await q(t)){const a=await g(n.file,null),i=(Array.isArray(a?.items)?a.items:[]).find(o=>o.from_ask===e);if(i)return{source:n,itemFile:a,item:i,key:`${n.slug}/${i.id}`}}return null}c(Vt,"askCardOf");const zn=c(t=>!t.phase&&!t.answered_at&&!mt(t)&&!St(t)&&!t.filed_held,"stillNew");function Gn(t,e){const n=e.filter(i=>i.kind==="ask-edited"&&i.data?.id===t.id&&typeof i.data?.text=="string").sort((i,o)=>String(i.ts).localeCompare(String(o.ts))).at(-1);return String(n?n.data.text:t.data?.text||"").trim().split(`
9
+ `)[0].trim()||(t.data?.files||[]).map(i=>i?.name).filter(Boolean).join(", ")||"Ask"}c(Gn,"askTitle");const Bl=c((t,e,n)=>lt(t,async()=>{D(t);const a=await J($.join(t,"data","events.jsonl")),i=n||a.find(l=>l.id===e&&l.kind==="ask")||d(`no ask "${e}" in this site's data/events.jsonl`);if(await Vt(t,e)||await xi(t,e,a))return null;const{source:o,itemFile:s}=await hi(t),r=await gi(t,o,i,Gn(i,a));return s.items.push(r),await b(o.file,s),`${o.slug}/${r.id}`}),"fileAsk");async function hi(t){const e=await q(t);for(const n of e){const a=await g(n.file,null);if(a)return Array.isArray(a.items)||d(`${n.file} is not an item file with items[]`),{source:n,itemFile:a}}return(await rt(t)).items==="waves"&&d("this board has no wave yet to file a new task in; start a wave first"),await A.mkdir(e[0].dir,{recursive:!0}),{source:e[0],itemFile:{items:[]}}}c(hi,"askFile");async function gi(t,e,n,a){const i=new Date().toISOString(),o={id:await bo(t),title:a,created:i,lane:"todo",lane_at:i,from_ask:n.id};return o.plan=sn(e.dir,o.id),await rn($.join(e.dir,o.plan),`# ${o.title}
10
+ `),o}c(gi,"newAskCard");const Cl=c(t=>lt(t,async()=>{D(t);const e=c((...m)=>$.join(t,"data",...m),"data"),n=await J(e("events.jsonl")),a=await Ot(t),i=new Map(Object.entries(a));for(const m of await q(t))for(const y of(await g(m.file,{})).items||[])y.from_ask&&i.set(y.from_ask,`${m.slug}/${y.id}`);const o=new Set(n.filter(m=>m.kind==="ask-withdrawn").map(m=>m.data?.id)),s=n.filter(m=>m.kind==="ask"&&!o.has(m.id)&&!i.has(m.id)).sort((m,y)=>String(m.ts).localeCompare(String(y.ts))),r=(await g(e("ask-progress.json"),{})).asks||{},l=(await g(e("ask-titles.json"),{})).titles||{},u=new Map(n.filter(m=>m.kind==="ask-done").map(m=>[m.data?.id,String(m.ts)])),p=[];let w;for(const m of s){const y=await J(Z(t,`ask:${m.id}`));if(y.some(F=>F.line==="ask-moved"))continue;const _=await Promise.all((await Un(e("replies"),m.id)).map(F=>A.stat(e("replies",F.name)).then(I=>I.mtime.toISOString()))),P=y.filter(F=>(F.who||"claude")==="claude"&&F.kind!=="status").map(F=>String(F.ts)),S=[..._,...P].sort().pop()||[at(r,m.id)?.at,u.get(m.id)].filter(Boolean).sort().pop();w||=await hi(t);const v=await gi(t,w.source,m,at(l,m.id)||Gn(m,n));v.created=m.ts,S&&Ie(v,"done",S),w.itemFile.items.push(v),await b(w.source.file,w.itemFile),i.set(m.id,`${w.source.slug}/${v.id}`),p.push(i.get(m.id))}const f=c(m=>i.get(/^item:ask:(.+)$/.exec(m||"")?.[1]),"cardOf"),h=await g(B(t),null);if(h?.items?.some(m=>f(m.topic))){for(const m of h.items)f(m.topic)&&(m.topic=`item:${f(m.topic)}`);await b(B(t),h)}for(const m of["ask-progress.json","ask-titles.json"])await A.rm(e(m),{force:!0});return p}),"fileAsks"),Il=c((t,e)=>lt(t,async()=>{const n=await Vt(D(t),e);if(!n||!zn(n.item))return null;const a=await J($.join(t,"data","events.jsonl"));return n.item.title=Gn(a.find(i=>i.id===e&&i.kind==="ask"),a),await b(n.source.file,n.itemFile),n.key}),"retitleAskCard");async function Qn(t,{source:e,itemFile:n,item:a,key:i}){n.items=n.items.filter(l=>l!==a);const o=Number(/^T-([1-9]\d*)$/.exec(a.id)?.[1]||0);o>(Number(n.last_task)||0)&&(n.last_task=o),await b(e.file,n),a.plan&&await A.rm($.join(e.dir,a.plan),{force:!0});const s=Z(t,i),r=await J(s);return await A.rm(s,{force:!0}),r}c(Qn,"dropCard");const Tl=c((t,e)=>lt(t,async()=>{const n=await Vt(D(t),e);return!n||!zn(n.item)?null:(await Qn(t,n),n.key)}),"dropAskCard"),$i=c(t=>!t.phase&&!t.closed_at&&!St(t)&&(!mt(t)||!!t.answered_at),"answerable");async function ki(t,e,n){const{item:a,key:i}=e;a.from_ask||d(`${i} is not a card an ask became; write in its thread with thread ${i} --text`),$i(a)||d(`${i} is sorted (${a.phase||qt[a.lane]}), so it is work: write in its thread with thread ${i} --text`),n!==void 0&&(a.title=j(n,"--title")),a.answered_at||=new Date().toISOString(),await b(e.source.file,e.itemFile)}c(ki,"markAnswered");async function yi(t,e,n){const a=await Vt(t,e);a&&a.key!==n&&d(`ask "${e}" is already card ${a.key}: sort it with item set ${a.key} --phase, or merge it with item relate-ask ${e} <card>`)}c(yi,"refuseFiled");async function ql(t,e,n,a){D(t);const{source:i,itemFile:o,item:s}=await x(t,e),r={source:i,itemFile:o,item:s,key:e};return Xe(n),a!==void 0&&j(a,"--title"),await ki(t,r,a),Gt(t,e,{text:n})}c(ql,"answerCard");async function Ml(t,e,n,a,i){D(t),vt(e,"the event id"),(await J($.join(t,"data","events.jsonl"))).some(l=>l.id===e&&l.kind==="ask")||d(`no ask "${e}" in this site's data/events.jsonl`),await Vn(t,e),await x(t,n),j(a,"--summary"),i!==void 0&&j(i,"--title");const s=await Vt(t,e);if(s&&s.key===n&&d(`ask "${e}" is ${n} already`),s&&!zn(s.item)&&d(`ask "${e}" became ${s.key}, which is sorted; to fold that card's notes into ${n}, use item notes ${n} --from ${s.key}, then close it`),s){const l=await lt(t,()=>Qn(t,s)),u=Z(t,`ask:${e}`);for(const p of l)await dt(u,p);await dt(u,{ts:new Date().toISOString(),who:"claude",kind:Ga,line:"card-merged",text:Za("card-merged",{card:await K(t,n)}),into:n,title:i??s.item.title,link:`#selectedCard=${encodeURIComponent(n)}`})}const r=await Ot(t);return await b(jt(t),{links:{...r,[e]:n}}),await Gt(t,n,{text:a}),jt(t)}c(Ml,"relateAsk");async function Wl(t,e){await Ce(t,e,"the ask");const n=await Ot(t);return at(n,e)===void 0&&d(`ask "${e}" is not folded into a card`),delete n[e],await b(jt(t),{links:n}),jt(t)}c(Wl,"unfoldAsk");const bi=c(async(t,e)=>(await J(Z(t,`ask:${e}`))).find(n=>n.line==="ask-moved"),"movedLine");async function Vn(t,e){const n=await bi(t,e);n&&d(`ask "${e}" was moved to ${n.link}; it lives there now`)}c(Vn,"refuseMoved");async function xi(t,e,n){const a=`ask "${e}"`;if(n.some(l=>l.kind==="ask-withdrawn"&&l.data?.id===e))return{why:`${a} was deleted by the owner`};const i=await bi(t,e);if(i)return{why:`${a} was already moved to ${i.link}`};const o=at(await Ot(t),e);if(o)return{why:`${a} is folded into ${o}; run ask unfold ${e} first`};const s=[];for(const l of await q(t)){const u=await g(l.file,null);for(const p of Array.isArray(u?.items)?u.items:[])p.from_ask===e&&s.push({key:`${l.slug}/${p.id}`,it:p})}const r=s.find(({it:l})=>St(l)||mt(l)||l.answered_at);return r?{why:`${a} became ${r.key}, which has started or been answered`}:s.length?{items:s.map(l=>l.key)}:null}c(xi,"askNotNew");async function xr(t,e,n){const a=/^uploads\/([\w.-]+)$/.exec(n?.url||"")?.[1],i=ui.test(a||"")?$.join(zt(t),a):null;if(!i||!await A.stat(i).then(l=>l.isFile(),()=>!1))return{name:String(n?.name||a||"file")};await A.mkdir($.dirname(de(e,"x")),{recursive:!0});const o=a.replace(/^\d+-/,"");let s;for(let l=Date.now();s=`${l}-${o}`,!await A.copyFile(i,$.join(zt(e),s),Yo.COPYFILE_EXCL).then(()=>!0,p=>p.code==="EEXIST"?!1:Promise.reject(p));l++);const r=await g(de(t,a),null);return r&&await b(de(e,s),r),{...n,url:`uploads/${s}`,path:$.join(zt(e),s)}}c(xr,"copyUpload");async function Ul(t,e,n){D(t),vt(e,"the event id"),(typeof n!="string"||!n.trim())&&d("ask move needs --to <route>, the board to move it to");const a=await J($.join(t,"data","events.jsonl")),i=a.find(y=>y.id===e&&y.kind==="ask")||d(`no ask "${e}" in this site's data/events.jsonl`),o=kt(),s=o.find(y=>y.route===n)||d(`--to ${n}: no board at /${n} in the hub's manifest; the boards are ${o.map(y=>y.route).join(", ")||"none"}`);Rt(s.dir,t)&&d(`--to ${n}: that is this board`);const r=await xi(t,e,a);r?.why&&d(r.why);const l=a.filter(y=>y.kind==="ask-edited"&&y.data?.id===e&&typeof y.data?.text=="string").sort((y,_)=>String(y.ts).localeCompare(String(_.ts))),u=l.at(-1),p=[];for(const y of[...i.data?.files||[],...l.flatMap(_=>_.data.files||[])])p.push(await xr(t,s.dir,y));const w={route:$.basename(t),title:(await rt(t)).title,id:e},f=u?u.data.text:i.data?.text||"",h=await $t(s,"ask",{text:f,...p.length?{files:p}:{},from:w}),m=`/${n}/#selectedCard=${encodeURIComponent(`ask:${h}`)}`;await W(t,`ask:${e}`,"ask-moved",{board:s.title},{link:m});for(const y of r?.items||[]){const{source:_,itemFile:P,item:S}=await x(t,y);await lt(t,()=>Qn(t,{source:_,itemFile:P,item:S,key:y}))}return{file:$.join(s.dir,"data","events.jsonl"),lines:[`moved to ${m}`,...(r?.items||[]).map(y=>`dropped: ${y}`)]}}c(Ul,"moveAsk");async function Hl(t,e,{state:n,text:a}={}){return D(t),["posted","needs"].includes(n)||d("review record needs --state posted or --state needs"),String(a??"").trim()||d("review record needs the review text, as --text or --file"),Si(t,await _i(t,e,"review record"),{state:n,text:a})}c(Hl,"recordReview");async function _i(t,e,n){/^[1-9]\d{0,6}$/.test(String(e))||d(`${n} takes the PR number, such as 437, not "${e}"`);const a=await g($.join(t,"data","incoming.json"),{});return{...(a?.prs||[]).find(s=>s.number===Number(e))||(await g($.join(t,"data","reviews.json"),{}))[e]||d(`PR #${e} is not an incoming PR on this board`),repo:a?.repo||ct(t,{})}}c(_i,"incomingPR");async function Si(t,{number:e,title:n,author:a,url:i,touches:o=[],asked:s=!1,head:r},{state:l,text:u,review_url:p}){const w=$.join(t,"data","reviews.json"),f=await g(w,{});return f[e]={number:Number(e),title:n,author:a,url:i,touches:o,asked:s,head:r,state:l,text:u,...p?{review_url:p}:{},at:new Date().toISOString()},await b(w,f),{file:w,lines:[]}}c(Si,"saveReview");async function Jl(t,e,{words:n,readAt:a}){D(t);const i=await _i(t,e,"review post"),o=String(n??"").trim()||d("review post needs the review text, as --file"),s=`${Ae}Claude review from the ${(await rt(t)).title} board`;(o.startsWith(Ae.trim())||o.includes("Claude review from")||o.includes(Bn))&&d(`review post adds the ${Ae.trim()} header and the claude-bridge marker itself; pass only your words`);const r=i.repo||d("review post needs a board on GitHub; this board has no repo there");Number.isNaN(Date.parse(a))&&d("--read-at takes the time you read the PR, such as 2026-11-05T09:30:00Z");const l=At(await rt(t)).github_login;try{const u=await Ms({repo:r,pr:i.number,since:a});u.length&&d(`PR #${e} got ${u.length===1?"a review":`${u.length} reviews`} after ${a} (${u.map(w=>`${w.login} at ${w.at}`).join(", ")}); reread the PR and review again`);const p=await qs({repo:r,pr:i.number,head:i.head,body:`${s}
11
11
 
12
12
  ${o}
13
13
 
14
- ${Dn}`,login:l});return await li(e,i,{state:"posted",text:o,review_url:p}),{lines:[`posted review on PR #${t}: ${p}`]}}catch(u){if(u instanceof ue)throw u;d(u.message)}}r($l,"postIncomingReview");const Kt=r(e=>g.join(e,"data","handshake.json"),"handshakeFile");async function di(e){const t=await $(Kt(e),null);if(!t?.hello)return t;const{hello:n,...a}=t;return{...a,ping:a.ping||n}}r(di,"readHandshake");async function kl(e,t){D(e),Fe(t,"the event id");const n=(await z(g.join(e,"data","events.jsonl"))).find(i=>i.id===t);n?.kind!=="ping"&&n?.kind!=="hello"&&d(`no ping event "${t}" in this site's data/events.jsonl`);const a=await di(e)||{};return a.ping?.id&&a.ping.id!==t&&d(`"${t}" is an older ping; ack the newest, "${a.ping.id}"`),await y(Kt(e),{...a,ping:a.ping||{id:t,at:n.ts,session:null},ack:{id:t,at:new Date().toISOString()}}),Kt(e)}r(kl,"ackPing");async function bl(e){const t=await di(e);t&&!t.done_at&&await y(Kt(e),{...t,done_at:new Date().toISOString()})}r(bl,"finishHandshake");const Un={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})$/},jt=r((e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase(),"sameName");function Hn(e,t){return Array.isArray(e)||d(`${t} must be a JSON array of reviewers`),e.forEach((n,a)=>{const i=`${t}[${a}]`;ot(n,Object.keys(Un),i);for(const[o,s]of Object.entries(Un))(typeof n[o]!="string"||!s.test(n[o].trim()))&&d(`${i}.${o} must match ${s}`);e.slice(0,a).some(o=>jt(o.name,n.name))&&d(`${t} names "${n.name}" twice`)}),e.map(n=>Object.fromEntries(Object.keys(Un).map(a=>[a,n[a].trim()])))}r(Hn,"checkReviewers");async function Jn(e,t){const{file:n,reviewers:a}=await At(e,o=>{const s=Hn(t(o.reviewers||[]),"the reviewers");return{set:{reviewers:s},reviewers:s}}),i=[];for(const o of await q(e)){const s=await $(o.file,null);(s?.items||[]).some(c=>!K(c))&&(await y(o.file,{...s,reviewers:a}),i.push(`item file ${o.slug}: reviewers copied`))}return{file:n,lines:i}}r(Jn,"writeReviewers");const yl=r((e,t)=>Jn(e,()=>Hn(t,"the reviewer file")),"setReviewers"),ct=r(e=>g.join(D(e),"data","pr-slack.json"),"prSlackFile"),Qt=r(e=>$(ct(e),{}),"readPRSlack"),Ot=r(e=>!!(e?.ts||e?.posting_at),"held");async function Ke(e,t){return nt(e,async()=>{const n=JSON.parse(await j.readFile(e,"utf8").catch(()=>"{}")),a=t(n);return await We(e,JSON.stringify(n,null,2)+`
15
- `),a})}r(Ke,"editJSON");async function Gt(e,t,n){await Ke(e,i=>{const o=t(i);Ot(o)&&d("that Slack message has already gone out"),o.posting_at=new Date().toISOString()});let a;try{a=await n()}catch(i){throw await Ke(e,o=>{delete t(o).posting_at}),i}try{await Ke(e,i=>{const o=t(i);o.ts=a,delete o.posting_at})}catch(i){d(`posted, but its record failed, so it won't go again: ${i.message}`)}return a}r(Gt,"postOnce");const xl=r((e,t,n,a)=>Gt(ct(e),i=>{const o=i[t.pr]||={head:t.head,links:{},replies:[]};return o.head??=t.head,Object.assign(o.links[t.reviewer]||={reactions:[]},{channel:n})},()=>a(n)),"postLink"),_l=r((e,t,n)=>Gt(ct(e),a=>a[t.pr].replies.find(i=>i.id===t.id).to[t.reviewer],n),"postReply"),Sl=r((e,t)=>Ke(ct(e),n=>{const a=n[t.pr].links[t.reviewer];a.reactions.includes(t.emoji)||a.reactions.push(t.emoji)}),"recordReaction"),ui=r((e,t,n,a)=>Ke(ct(e),i=>{const o=i[t],s=Object.keys(o?.links||{}).filter(c=>o.links[c].ts);return s.length?(o.replies.push({id:`${n}-${o.replies.length+1}`,text:a,to:Object.fromEntries(s.map(c=>[c,{}]))}),s):[]}),"queueReply");function tr(e,t,n){const a=e.commits||[],i=a.findIndex(o=>o.oid===n);return[`New push to #${t}`,a.slice(i+1).map(o=>o.subject).join(" \xB7 ")].filter(Boolean).join(`
16
- `)}r(tr,"pushText");async function vl(e){const t=await $(On,{}),n=r((a,i)=>{const o=ae(t.prs,a)?.head;return!!o&&o!==i.head&&Object.values(i.links).some(s=>s.ts)},"moved");return Object.entries(await Qt(e)).some(([a,i])=>n(a,i))?Ke(ct(e),a=>{const i=[];for(const[o,s]of Object.entries(a)){if(!n(o,s))continue;const c=ae(t.prs,o),l=Object.keys(s.links).filter(u=>s.links[u].ts);s.head&&(s.replies.push({id:`push-${s.replies.length+1}`,text:tr(c,o.split("#")[1],s.head),to:Object.fromEntries(l.map(u=>[u,{}]))}),i.push(o)),s.head=c.head}return i}):[]}r(vl,"queuePushes");function nr(e,t,n){const a=Number.isInteger(e.additions)?`+${e.additions}/-${e.deletions}, ${e.files} file${e.files===1?"":"s"}`:null;return[e.title||n.title,Nn(t),a].filter(Boolean).join(`
17
- `)}r(nr,"linkText");const fi=r(e=>!!e?.approved||e?.reviewDecision==="APPROVED","approved");async function jl(e,t){D(e);const n=await qa.waiting("slack");if(n)return{waiting:n,links:[],replies:[],reactions:[],digest:null};const a=await oe(e),i=await $(On,{}),o=await Qt(e),s=[];for(const p of await q(e)){const w=await $(p.file,{}),f=Rn(w,a.reviewers);for(const h of w.items||[])if(h.lane!=="done")for(const m of Me(h,se(e,w))){const k=vt(m),_=ae(i.prs,k);if(!(_?.state!=="OPEN"||_.isDraft))for(const N of f)Ot(o[k]?.links?.[N.name])||s.some(v=>v.pr===k&&v.reviewer===N.name)||s.push({pr:k,key:`${p.slug}/${h.id}`,reviewer:N.name,slack_user:N.slack_user,head:_.head||null,text:nr(_,m,h)})}}const c=[],l=[];for(const[p,w]of Object.entries(o)){const f=ae(i.prs,p),h=[fi(f)&&"git_approved",f?.state==="MERGED"?"git_merged":f?.state==="CLOSED"&&"x"].filter(Boolean);for(const[m,k]of Object.entries(w.links))if(k.ts)for(const _ of h)k.reactions.includes(_)||l.push({pr:p,reviewer:m,channel:k.channel,ts:k.ts,emoji:_});for(const m of w.replies)for(const[k,_]of Object.entries(m.to))Ot(_)||c.push({pr:p,id:m.id,reviewer:k,channel:w.links[k].channel,thread_ts:w.links[k].ts,text:m.text})}const u=await ar(e,t);return{links:s,replies:c,reactions:l,digest:u.due?u:null}}r(jl,"reviewDue");async function Ol(e,t,n){D(e);const a=S(n,"what changed"),{itemFile:i,item:o}=await x(e,t),s=[];for(const l of Me(o,se(e,i)))s.push(...await ui(e,vt(l),"updated",`Updated: ${a}`));const c=[...new Set(s)];return{lines:[c.length?`Updated queued for ${c.join(", ")} on ${t}`:`no reviewer has a link to ${t}'s PRs; nothing queued`]}}r(Ol,"reviewUpdated");async function Al(e,t){const{itemFile:n,item:a}=await x(e,t),i=await Qt(e);return Me(a,se(e,n)).some(o=>Object.values(i[vt(o)]?.links||{}).some(s=>s.ts))}r(Al,"cardLinked");const wi=r(e=>g.join(D(e),"data","review-digests.json"),"digestFile");async function ar(e,{now:t=new Date}={}){D(e);const n=await oe(e),a=await $(On,{}),i=await Qt(e),o=vs(),s=new Map;for(const f of await q(e)){const h=await $(f.file,{}),m=Rn(h,n.reviewers);for(const k of m)s.has(k.name)||s.set(k.name,{name:k.name,slack_user:k.slack_user,dm:k.dm,items:[]});for(const k of h.items||[]){if(k.lane==="done")continue;const _=`${f.slug}/${k.id}`,N=Ss(h,k,_,o);for(const v of Me(k,se(e,h))){const O=vt(v),A=ae(a.prs,O);if(!(A?.state!=="OPEN"||A.isDraft||A.failing?.length||fi(A)))for(const I of m){const B=i[O]?.links?.[I.name]?.ts||ae(N,I.name)?.ts||null,P=B?(t.getTime()-Number(B)*1e3)/864e5:null,L=P>2?Math.floor(P):null;s.get(I.name).items.push({key:_,pr:O,title:k.title,url:Nn(v),sent_ts:B,...L?{days_old:L}:{},text:`${Nn(v)} \xB7 ${k.title}${L?` (${L} days old)`:""}`})}}}}const{date:c,open:l}=js(t),u=((await $(wi(e),{})).digests||[]).filter(f=>f.date===c),p=await qa.waiting("slack");for(const f of u)s.has(f.reviewer)||s.set(f.reviewer,{name:f.reviewer,items:[]});const w=[...s.values()].map(f=>{const h=u.find(k=>k.reviewer===f.name),m=h?!h.posting_at&&(!h.ts||h.replies.some(k=>!Ot(k))):f.items.length>0;return{...f,owed:m,...h?{sent:h}:{}}}).filter(f=>f.items.length||f.sent);return{date:c,due:!p&&l&&w.some(f=>f.owed),...p?{waiting:p}:{},reviewers:w}}r(ar,"reviewDigest");async function Pl(e,t,n,{channel:a,header:i,post:o}){const s=wi(e),c=r(p=>(p.digests||[]).find(w=>w.date===t&&w.reviewer===n.name),"entry");await Ke(s,p=>{c(p)||(p.digests=[...(p.digests||[]).filter(w=>w.date===t),{date:t,reviewer:n.name,channel:a,replies:n.items.map(w=>({pr:w.pr,text:w.text}))}],delete p.last_date)});const l=c(await $(s,{})),u=l.ts||await Gt(s,c,()=>o({channel:l.channel,text:i(l.replies.length)}));for(const[p,w]of l.replies.entries())Ot(w)||await Gt(s,f=>c(f).replies[p],()=>o({channel:l.channel,thread_ts:u,text:w.text}))}r(Pl,"postDigest");function Dl(e,t){const n=Hn(Array.isArray(t)?t:[t],"the reviewer file");return Jn(e,a=>[...a.map(i=>n.find(o=>jt(o.name,i.name))||i),...n.filter(i=>!a.some(o=>jt(i.name,o.name)))])}r(Dl,"addReviewers");function Fl(e,t){return Jn(e,n=>{const a=t.filter(i=>!n.some(o=>jt(o.name,i)));return a.length&&d(`this board has no reviewer ${a.map(i=>`"${i}"`).join(", ")}`),n.filter(i=>!t.some(o=>jt(i.name,o)))})}r(Fl,"removeReviewers");const ir=r(()=>g.join(xn.homedir(),".claude","kickflip","settings.json"),"hubSettingsFile"),zn=r(e=>{try{return e()}catch(t){throw t instanceof Ds&&d(t.message),t}},"ruleCall"),Kn=r(async e=>Wa(await $(g.join(e,"board.json"),{})),"readBoardRules");let pi=Promise.resolve();function At(e,t){const n=pi.then(async()=>{const a=g.join(D(e),"board.json"),i=await $(a,{}),{set:o,...s}=t(i);return await y(a,{...i,...o}),{file:a,...s}});return pi=n.catch(()=>{}),n}r(At,"writeBoardJSON");const mi=r((e,t)=>At(e,n=>{const a=zn(()=>t(Wa(n)));return{set:{rules:a.rules},...a}}),"writeBoardRules");function Nl(e,t){const n=Object.keys(t||{}).sort().join(),a=n==="level,login",i=a?t.login:t?.[n],o=typeof i=="string"?i.trim():null;(!["add","remove","level,login"].includes(n)||!Cs(o))&&d("Send add or remove with one login, like name@github, or a listed login with its level."),a&&!["view","full"].includes(t.level)&&d("A level is view or full.");const s=r(({login:c,level:l})=>l==="full"?{login:c,level:l}:c,"stored");return At(e,c=>{const l=Bs(c);a&&!l.some(w=>w.login===o)&&d(`${o} isn't shared with yet. Add them first.`);const p=(n==="remove"?l.filter(w=>w.login!==o):a?l.map(w=>w.login===o?{login:o,level:t.level}:w):l.some(w=>w.login===o)?l:[...l,{login:o,level:"view"}]).map(s);return{set:{share:p},share:p}}).then(({share:c})=>({share:c}))}r(Nl,"saveBoardShare");const hi=r(e=>typeof e=="string"&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(e),"validGithubLogin"),gi=r(e=>{try{return e?Na(e):null}catch{return null}},"storedTickets"),Qn=r(e=>Number.isInteger(e)&&e>=1&&e<=99,"validCap"),Gn=["max_implementers","max_planners"],Se=r((e,t)=>{const n=gi(e?.tickets);return{auto_merge:e?.auto_merge===!0,auto_build:e?.auto_build===!0,auto_pull:e?.auto_pull===!0,max_implementers:Qn(e?.max_implementers)?e.max_implementers:qo,max_planners:Qn(e?.max_planners)?e.max_planners:Mo,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:t?.hub?e?.prs===!0:e?.prs!==!1,...n?{tickets:n}:{},...hi(e?.github_login)?{github_login:e.github_login}:{},...Ma(e?.build_target)?{build_target:e.build_target}:{}}},"settingsOf");async function Rl(e,t,n=new Date){let a;try{a=ns(t,n)}catch(i){d(i.message)}return await At(e,()=>({set:{paused_until:a??void 0}})),a}r(Rl,"setBoardPause");async function or(e){const t=D(e);return Se(await $(g.join(t,"board.json"),{}),ge().find(n=>Pe(n.dir,t)))}r(or,"readBoardSettings");const El=r((e,t)=>!!e?.github&&(!e.local||e.hub===!0)&&t.prs,"opensPRs");async function lt(e,t){ot(t,["auto_merge","auto_build","auto_pull","max_implementers","max_planners","auto_triage","auto_review","idle_notification","skip_draft","prs","tickets","github_login","build_target"],"the settings"),Object.keys(t).length||d("the settings name nothing to change"),t={...t};for(const[n,a]of Object.entries(t))if(n==="tickets"){try{t.tickets=Na(a)??void 0}catch(o){d(o.message)}t.tickets?.source==="linear"&&!fs()&&d(ds);const i=t.tickets?.source==="github"&&e?ge().find(o=>Pe(o.dir,e)):null;i&&!i.github&&d("GitHub issues need the board\u2019s repo on GitHub, and this board\u2019s repo isn\u2019t; pick none or linear")}else n==="github_login"?a===""||a===null?t.github_login=void 0:hi(a)||d("github_login must be a GitHub login"):n==="build_target"?a===null?t.build_target=void 0:Ma(a)||d('build_target must name .kickflip/build-<target>: letters, digits, ".", "_" or "-", or null for .kickflip/build'):Gn.includes(n)?Qn(a)||d(`${n} must be a whole number from 1 to 99`):Ht(a,n);if(t.prs===!1){const n=e?ge().find(a=>Pe(a.dir,e)):null;n?.github&&!n.local&&!(await Os(n.owner?.repo)).pushMain&&d("Merge lands each card on main and pushes it, so turn on Push main after a land first")}return At(e,n=>{const a=e?ge().find(s=>Pe(s.dir,e)):null,i=Se(n,a),o=Se({...n,...t},a);return{set:t,settings:o,changed:Object.keys(t).filter(s=>JSON.stringify(i[s])!==JSON.stringify(o[s]))}})}r(lt,"saveBoardSettings");async function Ll(){if(us().set)return[];const e=[];for(const t of ge())(await or(t.dir)).tickets?.source==="linear"&&(await lt(t.dir,{tickets:{source:"none"}}),await he(t,"settings",{tickets:null}),e.push(`/${t.route} fell back to no ticket source: Hub has no Linear key`));return e}r(Ll,"fallBackFromLinear");async function Bl(e,t,n){const a=String(t).replace(/-/g,"_"),i=["auto_merge","auto_build","auto_pull","max_implementers","max_planners","auto_triage","auto_review","idle_notification","skip_draft","prs","github_login","tickets","build_target"];if(i.includes(a)||d(`no board setting "${t}"; settings are ${i.map(c=>c.replace(/_/g,"-")).join(", ")}`),a==="tickets"){let c;try{c=JSON.parse(n)}catch{d('settings set tickets takes the source as JSON, such as {"source":"github"}')}const{file:l,settings:u}=await lt(e,{tickets:c});return{file:l,lines:sr({tickets:u.tickets})}}if(a==="github_login"){const{file:c,settings:l}=await lt(e,{github_login:n});return{file:c,lines:[`github-login ${l.github_login||"unset"}`]}}if(a==="build_target"){const{file:c,settings:l}=await lt(e,{build_target:n==="default"?null:n});return{file:c,lines:[`build-target ${l.build_target||"default"}`]}}if(Gn.includes(a)){const{file:c,settings:l}=await lt(e,{[a]:/^\d+$/.test(n)?Number(n):n});return{file:c,lines:[`${t} ${l[a]}`]}}["on","off"].includes(n)||d(`settings set ${t} takes on or off, not "${n}"`);const{file:o,settings:s}=await lt(e,{[a]:n==="on"});return{file:o,lines:[`${t} ${s[a]?"on":"off"}`]}}r(Bl,"setBoardSetting");const sr=r(e=>Object.entries(e).map(([t,n])=>`setting ${t.replace(/_/g,"-")} ${t==="tickets"?JSON.stringify(n??{source:"none"}):t==="github_login"||Gn.includes(t)?n:t==="build_target"?n||"default":n?"on":"off"}`),"settingsLines");async function Vn(e,t,n){const a=t?zn(()=>n(Wt())):await mi(e,n);return t&&zn(()=>Ls(a.rules)),{file:t?ir():a.file,lines:[`id ${a.rule.id}`]}}r(Vn,"changeRules");async function $i(e,t,n){const a=r(s=>s.map(c=>c.id),"ids");n||D(e);const[i,o]=n?[a(Wt()),e?a(await Kn(e)):[]]:[a(await Kn(e)),a(Wt())];i.includes(t)||d(`no ${n?"hub":"board"} rule "${t}"${o.includes(t)?`; it is a ${n?"board":"hub"} rule, so ${n?"drop":"pass"} --hub`:""}`)}r($i,"checkRuleId");async function Cl(e){const t=r(n=>a=>`${n} ${a.id} ${a.by==="claude"?"claude":"owner"} ${a.text}`,"line");return{lines:[...Wt().map(t("hub")),...e?(await Kn(e)).map(t("board")):[]]}}r(Cl,"listRules");function Il(e,{text:t,hub:n=!1,by:a}){return n||D(e),Vn(e,n,i=>Fs(i,{text:t,by:a}))}r(Il,"addRuleTo");async function Tl(e,t,{text:n,hub:a=!1}){return await $i(e,t,a),Vn(e,a,i=>Ns(i,t,n))}r(Tl,"editRuleIn");async function ql(e,t,{hub:n=!1}){return await $i(e,t,n),Vn(e,n,a=>Rs(a,t))}r(ql,"removeRuleFrom");const Ml=r((e,t,n)=>mi(e,a=>Es(a,t,n)),"saveBoardRules");async function Wl(e,{id:t,title:n,summary:a}){D(e);const i=await $(E(e),{topics:[],items:[]}),o=i.topics||[];return o.some(s=>s.id===S(t,"the topic id"))&&d(`topic "${t}" already exists`),o.push({id:t.trim(),title:S(n,"--title"),...a===void 0?{}:{summary:S(a,"--summary")}}),await y(E(e),{...i,topics:o,items:i.items||[]}),E(e)}r(Wl,"addTopic");const ki=["quiet","info","notice","danger","success"];function rr(e,t){if(e.diagram===void 0!=(e.practice===void 0)&&d(`${t} needs diagram and practice together`),e.diagram===void 0)return;const n=e.diagram;(!Array.isArray(n)||!n.length)&&d(`${t}.diagram must be a non-empty array of rows`),n.forEach((a,i)=>{(!Array.isArray(a)||!a.length||a.length>4)&&d(`${t}.diagram[${i}] must be a row of 1 to 4 boxes`),a.forEach((o,s)=>{const c=`${t}.diagram[${i}][${s}]`;ot(o,["text","tone","to"],c),S(o.text,`${c}.text`),ee(o.tone,l=>ki.includes(l)?l:d(`${c}.tone takes ${ki.join(", ")}`)),ee(o.to,l=>Array.isArray(l)&&i+1<n.length&&l.every(u=>Number.isInteger(u)&&u>=0&&u<n[i+1].length)?l:d(`${c}.to must list boxes of the next row by index`))})}),(!Array.isArray(e.practice)||!e.practice.length)&&d(`${t}.practice must be a non-empty array of lines`),e.practice.forEach((a,i)=>S(a,`${t}.practice[${i}]`))}r(rr,"checkDiagram");function cr(e,t){(!Array.isArray(e)||!e.length)&&d(`${t}.options must be a non-empty array`);const n=new Set;e.forEach((a,i)=>{const o=`${t}.options[${i}]`;ot(a,["id","label","recommended","detail","diagram","practice"],o),rr(a,o),n.has(S(a.id,`${o}.id`))&&d(`${t} has two options with id "${a.id}"`),n.add(a.id),S(a.label,`${o}.label`).startsWith(`${a.id}. `)&&d(`${o}.label starts with "${a.id}. ", but the page adds the option letter itself`),ee(a.recommended,s=>Ht(s,`${o}.recommended`)),ee(a.detail,s=>typeof s=="string"?s:d(`${o}.detail must be text`))}),e.filter(a=>a.recommended).length>1&&d(`${t} recommends more than one option`)}r(cr,"checkOptions");function lr(e,t,n){ot(e,["option","card","answer","reason"],n),t.some(a=>a.id===S(e.option,`${n}.option`))||d(`${n}.option names no option "${e.option}"`),S(e.card,`${n}.card`),S(e.answer,`${n}.answer`),ee(e.reason,a=>S(a,`${n}.reason`))}r(lr,"checkSuggested");const dt=r(e=>g.join(e,"data","prototypes.json"),"prototypesFile"),Zn=r((e,t,n)=>g.join(e,"public","prototypes",t,`${n}.js`),"takeFile");async function Pt(e){const t=e?(await $(dt(e),{})).prototypes:null;return Array.isArray(t)?t:[]}r(Pt,"readPrototypes");const dr=r(e=>typeof e=="string"&&/^[a-z0-9-]+$/.test(e)?e:d(`a prototype topic uses only a-z, 0-9 and "-", not "${e}"`),"prototypeTopic");function ur(e){const t=/^([^:]*):(.*)$/s.exec(e);(!t||!/^[A-Z]$/.test(t[1]))&&d(`--take takes KEY:"Label" with KEY one capital letter, not "${e}"`);const n=S(t[2],`--take ${t[1]}'s label`);return/^[A-Z]\.\s/.test(n)&&d(`--take ${t[1]}'s label starts with "${n.slice(0,3)}"; the take pill shows the label alone, so drop the letter`),{key:t[1],label:n}}r(ur,"prototypeTake");function fr(e){const t=/^([^:]*):(.*)$/s.exec(e);return(!t||!/^[a-z0-9][a-z0-9-]*$/.test(t[1]))&&d(`--state takes KEY:"Label" with KEY in a-z, 0-9 and "-", not "${e}"`),{key:t[1],label:S(t[2],`--state ${t[1]}'s label`)}}r(fr,"prototypeState");const bi=r(e=>e.find((t,n)=>e.findIndex(a=>a.key===t.key)!==n),"twiceIn"),Ne=r(e=>/^prototype-(.+)\.html$/.exec(g.posix.basename(String(e||"").split(/[?#]/)[0]))?.[1],"pageTopic");async function Ul(e,{topic:t,title:n,card:a,takes:i=[],served:o,states:s=[]}){D(e),dr(t),S(n,"--title"),i.length||d('prototype add needs a --take KEY:"Label" for each take');const c=i.map(ur),l=bi(c);l&&d(`--take ${l.key} is given twice`),o!==void 0&&!/^\/\S*$/.test(o)&&d(`--served takes the page's path on the served site, starting with "/", not "${o}"`),s.length&&o===void 0&&d("--state goes with --served: only a served round re-renders its states in place");const u=s.map(fr),p=bi(u);p&&d(`--state ${p.key} is given twice`),a!==void 0&&await x(e,a);const w=await Pt(e);w.some(m=>m.topic===t)&&d(`prototype ${t} is already recorded; run prototype rm ${t} first, or pick another topic`),await j.stat(g.join(e,"public",`prototype-${t}.html`)).then(()=>!0,()=>!1)&&d(`public/prototype-${t}.html is a hand-written page that questions may link; pick another topic`);const f={topic:t,title:n.trim(),...a===void 0?{}:{card:a},...o===void 0?{}:{served:o},takes:c,...u.length?{states:u}:{},at:new Date().toISOString()};await y(dt(e),{prototypes:[...w,f]});const h=`page prototype-${t}.html`;return o!==void 0?{file:dt(e),lines:[h,`served ${o} from the base prototype worktree (board.mjs prototype base)`,...u.length?[`states ${u.map(m=>m.key).join(", ")}`]:[]]}:{file:dt(e),lines:[h,...c.map(m=>`take ${m.key} ${Zn(e,t,m.key)}`)]}}r(Ul,"addPrototype");async function Hl(e){D(e);const t=await Pt(e);return{lines:t.length?t.map(n=>[n.topic,n.title,n.takes.map(a=>`${a.key}: ${a.label}`).join(", "),n.card,n.served&&`served ${n.served}`,n.states&&`states ${n.states.map(a=>a.key).join(", ")}`].filter(Boolean).join(" \xB7 ")):["no prototypes recorded"]}}r(Hl,"listPrototypes");async function Jl(e){const t=(await Pt(e)).filter(a=>a.served).map(a=>a.topic);if(!t.length)return[];const n=await $(E(e),{items:[]});return t.filter(a=>(n.items||[]).some(i=>!i.resolved&&Ne(i.url)===a))}r(Jl,"servedRoundsOpen");async function zl(e,t){D(e);const n=await Pt(e);n.some(o=>o.topic===t)||d(`no prototype "${t}" is recorded`);const i=((await $(E(e),{items:[]})).items||[]).filter(o=>!o.resolved&&Ne(o.url)===t).map(o=>o.id);return i.length&&d(`prototype ${t} backs open question ${i.join(", ")}; resolve ${i.length===1?"it":"them"} first`),await y(dt(e),{prototypes:n.filter(o=>o.topic!==t)}),dt(e)}r(zl,"removePrototype");async function wr(e,t,n){const a=t.url?.split(/[?#]/)[0];if(!a||!g.posix.basename(a).startsWith("prototype-"))return;const i=g.posix.basename(a),o=t.url.split("#")[0].split("?").slice(1).join("?"),s=`${n}.url`;new URLSearchParams(o).get("q")!==t.id&&d(`${s} must be ${i}?q=${t.id} so the pill can pick`);const c=Ne(a),l=(await Pt(e)).find(f=>f.topic===c);l||d(`${s} names ${i}, 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=l.takes.map(f=>f.key),p=t.options.map(f=>f.id),w=p.map(f=>u.indexOf(f));if(w.some((f,h)=>f<0||h>0&&f<w[h-1])&&d(`${n}.options ids ${p.join(", ")} must be a non-empty subset of ${i}'s takes, in take order: ${u.join(", ")}`),!l.served)for(const f of u)await j.stat(Zn(e,c,f)).then(h=>h.isFile(),()=>!1)||d(`${s} take ${f} has no file yet; write ${Zn(e,c,f)}`)}r(wr,"checkPrototype");async function Kl(e,t,n=async()=>{}){D(e);const a=Array.isArray(t)?t:[t];a.length||d("the question file is empty");const i=await $(E(e),{topics:[],items:[]}),o=i.items||[],s=await $(ye(e),{}),c=new Set([...o,...Object.values(s).flat()].map(w=>w.id)),l=new Set((i.topics||[]).map(w=>w.id));for(const[w,f]of a.entries()){const h=`question ${f?.id??w+1}`;if(ot(f,["id","topic","source","question","context","url","urgent","options","round_of","reask_of","ask","suggested","prototype_gate","ticket_gate"],h),c.has(Fe(f.id,`${h}.id`))&&d(`question id "${f.id}" is already used`),c.add(f.id),S(f.topic,`${h}.topic`),f.topic.startsWith("item:ask:")){const m=await ze(e,await Dt(e,f.topic.slice(9),`${h}.topic`));d(`${h}.topic: an ask's questions go on its card's topic${m?`, item:${m.key}`:""}`)}else f.topic.startsWith("item:")?await x(e,f.topic.slice(5)):f.topic.startsWith("wave:")?await pt(e,f.topic.slice(5)):f.topic.startsWith("file:")?await Xr(e,f.topic.slice(5)):l.has(f.topic)||d(`topic "${f.topic}" is not declared; add it with: topic add ${f.topic} --title <t>`);S(f.question,`${h}.question`),f.question.length>Ba&&d(`${h}.question runs to ${f.question.length} characters, past ${Ba}; keep the question to one line and move the detail into context or the option details, which take markdown`);for(const m of["source","context"])ee(f[m],k=>S(k,`${h}.${m}`));ee(f.url,m=>En(m,`${h}.url`)),ee(f.urgent,m=>Ht(m,`${h}.urgent`)),cr(f.options,h),ee(f.prototype_gate,m=>Si(m,f,`${h}.prototype_gate`)),f.ticket_gate!==void 0&&Si(f.ticket_gate,f,`${h}.ticket_gate`)&&await mr(e,f,h),ee(f.suggested,m=>lr(m,f.options,`${h}.suggested`)),await wr(e,f,h),f.ask!==void 0&&await mc(e,f,h),ee(f.round_of,m=>{const k=o.find(_=>_.id===m);k||d(`${h}.round_of names no question "${m}" in owner.json`),k.topic!==f.topic&&d(`${h}.round_of names ${m} on topic ${k.topic}; a round stays on its question's topic, ${f.topic}`),Ne(f.url)||d(`${h}.round_of needs a url on a recorded prototype, prototype-<topic>.html?q=${f.id}`)}),ee(f.reask_of,m=>{const k=o.find(_=>_.id===m);k||d(`${h}.reask_of names no question "${m}" in owner.json`),k.topic!==f.topic&&d(`${h}.reask_of names ${m} on topic ${k.topic}; a re-ask stays on its question's topic, ${f.topic}`),k.resolved||d(`${h}.reask_of names ${m}, which is not resolved; only a resolved question is asked again`)})}for(const w of new Set(a.map(f=>Ne(f.url)).filter(Boolean)))await n(e,w);const u=[],p=[];for(const w of a){const f=w.topic.startsWith("item:")&&!w.topic.startsWith("item:ask:")?w.topic.slice(5):null,h=f&&await yi(e,f);h&&((s[f]||=[]).push(w),p.push(w),u.push(`staged: ${w.id} waits for ${f}'s ${h} to finish; the card's staged questions then publish together`))}return p.length&&await y(ye(e),s),p.length===a.length?{file:ye(e),lines:u,staged:p.length}:_i(e,i,o,a.filter(w=>!p.includes(w)),u)}r(Kl,"addQuestions");async function yi(e,t){const{source:n}=await x(e,t);for(const a of await G(n.dir,F(t).id)){const i=await $(a,null);if(i?.started&&!i.done&&qe(i)&&i.kind!==me)return i.kind}return null}r(yi,"runningPlanner");async function ut(e,t,{screen:n=!1}={}){if(!e||await yi(e,t))return;const a=await $(ye(e),{});if(!a[t])return;const i=await $(it(e),{});if(n){i[t]||await y(it(e),{...i,[t]:new Date().toISOString()});return}const{[t]:o,...s}=a,c=await $(E(e),{topics:[],items:[]});await _i(e,c,c.items||[],o,[]),await y(ye(e),s),i[t]&&await y(it(e),Yn(i,t))}r(ut,"publishStaged");const Yn=r((e,t)=>Object.fromEntries(Object.entries(e).filter(([n])=>n!==t)),"withoutKey");async function xi(e){const t=await $(it(e),{}),n=await $(ye(e),{});return Object.fromEntries(Object.entries(t).filter(([a])=>n[a]).map(([a,i])=>[a,{since:i,ids:n[a].map(o=>o.id)}]))}r(xi,"readScreening");async function Ql(e,t,n){D(e);const a=S(n,"--note"),i=await $(ye(e),{}),o=await $(it(e),{}),s=Object.keys(i).find(w=>i[w].some(f=>f.id===t));if(!s)return pr(e,t,a);o[s]||d(`${t} waits for ${s}'s planner to finish`);const c=i[s].find(w=>w.id===t);c.prototype_gate&&d(`${t} is the card's prototype question, which is the owner's; question publish ${s} passes it on`),c.ticket_gate&&d(`${t} is the card's ticket question, which is the owner's; question publish ${s} passes it on`);const l=new Date().toISOString(),u=await $(E(e),{topics:[],items:[]});await y(E(e),{...u,topics:u.topics||[],items:[...u.items||[],{...c,asked_at:l,resolved:`Settled by the orchestrator: ${a}`,resolved_at:l}]});const p=i[s].filter(w=>w.id!==t);return await y(ye(e),p.length?{...i,[s]:p}:Yn(i,s)),p.length||await y(it(e),Yn(o,s)),await Re(e,s,`Answers (orchestrator, ${Qe()})`,`- ${t} (${c.question}): settled by the orchestrator. "${a}"`),E(e)}r(Ql,"settleQuestion");async function pr(e,t,n){const a=await $(E(e),{topics:[],items:[]}),i=(a.items||[]).find(c=>c.id===t&&c.topic?.startsWith("item:"));i||d(`no staged question "${t}"; question settle takes a question a finished grill left for you to screen, or a card's question while it waits on your re-check`);const o=i.topic.slice(5);(await x(e,o)).item.recheck_at||d(`${o} waits on no re-check, so its question ${t} stays answered as it is`);const s=new Date().toISOString();return await y(E(e),{...a,items:a.items.map(c=>c===i?{...c,resolved:`Settled by the orchestrator: ${n}`,resolved_at:s}:c)}),await Re(e,o,`Answers (orchestrator, ${Qe()})`,`- ${t} (${i.question}): settled by the orchestrator. "${n}"`),E(e)}r(pr,"settleStale");async function Gl(e,t){D(e);const n=(await xi(e))[t]?.ids||d(`${t} has no questions waiting on you to screen`);return await ut(e,t),n}r(Gl,"publishScreened");async function Vl(e,t=new Date){const n=Object.entries(await xi(e)).filter(([,a])=>t-Date.parse(a.since)>=Ts).map(([a])=>a);for(const a of n)await ut(e,a),await W(e,a,"screen-timeout");return n}r(Vl,"publishUnscreened");async function _i(e,t,n,a,i){const{answers:o,requests:s,reopens:c}=await ft(e),l=new Date().toISOString(),u=[],p=[];for(const f of a.filter(h=>h.round_of))f.round=jn(n.find(h=>h.id===f.round_of))+1,ve(t,[f.round_of],`Followed by prototype round ${f.round}`,l),p.push(f.round_of);for(const f of a.filter(h=>h.reask_of))ve(t,[f.reask_of],`Asked again as ${f.id}`,l),p.push(f.reask_of);for(const f of a){const h=Ne(f.url),m=n.filter(_=>_.topic===f.topic).map(_=>Te(_,o,s,[],c)),k=f.topic.startsWith("item:")?Ni(m):[];for(const _ of m)k.includes(_.id)?(ve(t,[_.id],`Followed by ${f.id}`,l),p.push(_.id)):!_.resolved&&h&&Ne(_.url)===h&&(ve(t,[_.id],`Replaced by ${f.id}`,l),u.push(_.id))}const w={...t,topics:t.topics||[],items:[...n,...a.map(f=>({...f,asked_at:l}))]};await y(E(e),w);for(const f of new Set(a.map(h=>Xn(h.topic)).filter(Boolean)))await xr(e,f);return{file:E(e),lines:[...i,...u.map(f=>`replaced: ${f}`),...p.map(f=>`resolved: ${f}`)]}}r(_i,"publishQuestions");function Si(e,t,n){return Ht(e,n),e?((!t.topic.startsWith("item:")||t.topic.startsWith("item:ask:"))&&d(`${n} goes on a card's topic, item:<file>/<id>`),t.options?.map(a=>a.id).join()!=="yes,no"&&d(`${n} takes exactly the options yes and no, in that order`),!0):!1}r(Si,"checkGate");async function mr(e,t,n){const a=t.topic.slice(5),{item:i}=await x(e,a);i.ticket&&d(`${n}.ticket_gate: ${a} already has ticket ${i.ticket}`),await sn(e)||d(`${n}.ticket_gate needs a board with a ticket source; with none every card stays a task`)}r(mr,"checkTicketGate");async function Zl(e,t,n){const a=await $(E(e),{topics:[],items:[]}),i=new Map((a.items||[]).map(l=>[l.id,l]));for(const l of t){const u=i.get(String(l.id));if(!u?.ticket_gate||!["yes","no"].includes(l.choice))continue;ve(a,[u.id],`Ticket: ${l.choice}.${l.choice==="yes"?" The board makes it from the card's title and notes.":""}`),await y(E(e),a);const p=u.topic.slice(5);l.choice==="yes"&&await ji(e,p,"making its ticket",async()=>{await $e(e,p,{newTicket:!0},n),await W(e,p,"ticket-made",{ticket:(await x(e,p)).item.ticket})})}for(const l of t){const u=i.get(String(l.id));if(!u?.prototype_gate||!["yes","no"].includes(l.choice))continue;ve(a,[u.id],`Prototype round: ${l.choice}. The board moves the card on once every question is answered.`),await y(E(e),a);const p=u.topic.slice(5);l.choice==="yes"&&(await x(e,p).catch(()=>null))?.item.phase==="grilling"&&await aa(e,p)&&await W(e,p,"prototype-after")}const o=new Map;for(const l of t){const u=i.get(String(l.id)),p=Xn(u?.topic);p&&o.set(p,[...o.get(p)||[],hr(u,l)])}const s=[],c=[];for(const[l,u]of o)await x(e,l).catch(()=>null)&&await ji(e,l,"writing them into its notes",async()=>{await Re(e,l,`Answers (owner, ${Qe()})`,u.join(`
18
- `));const p=await vi(e,l);p==="prototyping"&&s.push(l),p==="staging"&&c.push(l)});return{prototype:s,staged:c}}r(Zl,"settleAnswers");async function vi(e,t,{roundAt:n=!1}={}){const{item:a}=await x(e,t),{asked:i}=await fe(e,t);if(i.some(o=>o.state==="open"))return null;if(a.phase==="grilling"&&i.some(o=>o.prototype_gate&&o.answers.at(-1)?.choice==="yes")){if(await $e(e,t,{phase:"prototyping"}),n){const{source:o,itemFile:s,item:c}=await x(e,t);c.round_at=new Date().toISOString(),await y(o.file,s)}return await W(e,t,"prototype-round"),"prototyping"}return await br(e,t)?(await na(e,t),"staging"):null}r(vi,"moveOnAnswered");async function ji(e,t,n,a){try{await a()}catch(i){if(!(i instanceof ue))throw i;await W(e,t,"answers-failed",{what:n,error:i.message})}}r(ji,"followUp");const Xn=r(e=>typeof e=="string"&&e.startsWith("item:")&&!e.startsWith("item:ask:")?e.slice(5):null,"cardOfTopic"),Vt=r(e=>String(e).padStart(2,"0"),"pad2"),Qe=r((e=new Date)=>`${Vt(e.getMonth()+1)}/${Vt(e.getDate())} ${Vt(e.getHours())}:${Vt(e.getMinutes())}`,"noteStamp");function hr(e,t){const n=t.choice===null||t.choice===void 0||t.choice===""?null:(e.options||[]).find(i=>i.id===t.choice)?.label??String(t.choice),a=String(t.note||"").trim();return`- ${e.id} (${e.question}): ${n?`${n}.`:"no option picked."}${a?` Note, verbatim: "${a}"`:""}`}r(hr,"answerLine");const Oi=292,ea=r(e=>String(e).toLowerCase().replace(/[^a-z0-9-]+/g,"-"),"notesBase"),gr=r((e,t,n)=>nt(g.join(e,`.${ea(t)}-notes`),n),"notesLock");function Zt(e,t){let n=`${ea(t)}-notes.md`;for(let a=2;de(g.join(e,n));a++)n=`${ea(t)}-notes-${a}.md`;return n}r(Zt,"freeNotesName");async function Yt(e,t){const n=g.join(g.dirname(e),`.${g.basename(e)}.${process.pid}.tmp`);await j.rm(n,{force:!0}),await j.writeFile(n,t,{mode:Oi}),await j.rename(n,e)}r(Yt,"writeNotesFile");const $r=r(e=>/\n/.test(S(e,"--heading"))?d("--heading is one line, the section's title"):S(e,"--heading"),"notesHeading"),kr=r((e,t,n)=>`${e.replace(/\n*$/,`
14
+ ${Bn}`,login:l});return await Si(t,i,{state:"posted",text:o,review_url:p}),{lines:[`posted review on PR #${e}: ${p}`]}}catch(u){if(u instanceof pt)throw u;d(u.message)}}c(Jl,"postIncomingReview");const tn=c(t=>$.join(t,"data","handshake.json"),"handshakeFile");async function vi(t){const e=await g(tn(t),null);if(!e?.hello)return e;const{hello:n,...a}=e;return{...a,ping:a.ping||n}}c(vi,"readHandshake");async function Kl(t,e){D(t),vt(e,"the event id");const n=(await J($.join(t,"data","events.jsonl"))).find(i=>i.id===e);n?.kind!=="ping"&&n?.kind!=="hello"&&d(`no ping event "${e}" in this site's data/events.jsonl`);const a=await vi(t)||{};return a.ping?.id&&a.ping.id!==e&&d(`"${e}" is an older ping; ack the newest, "${a.ping.id}"`),await b(tn(t),{...a,ping:a.ping||{id:e,at:n.ts,session:null},ack:{id:e,at:new Date().toISOString()}}),tn(t)}c(Kl,"ackPing");async function zl(t){const e=await vi(t);e&&!e.done_at&&await b(tn(t),{...e,done_at:new Date().toISOString()})}c(zl,"finishHandshake");const Zn={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})$/},De=c((t,e)=>t.trim().toLowerCase()===e.trim().toLowerCase(),"sameName");function Yn(t,e){return Array.isArray(t)||d(`${e} must be a JSON array of reviewers`),t.forEach((n,a)=>{const i=`${e}[${a}]`;le(n,Object.keys(Zn),i);for(const[o,s]of Object.entries(Zn))(typeof n[o]!="string"||!s.test(n[o].trim()))&&d(`${i}.${o} must match ${s}`);t.slice(0,a).some(o=>De(o.name,n.name))&&d(`${e} names "${n.name}" twice`)}),t.map(n=>Object.fromEntries(Object.keys(Zn).map(a=>[a,n[a].trim()])))}c(Yn,"checkReviewers");async function Xn(t,e){const{file:n,reviewers:a}=await Ee(t,o=>{const s=Yn(e(o.reviewers||[]),"the reviewers");return{set:{reviewers:s},reviewers:s}}),i=[];for(const o of await q(t)){const s=await g(o.file,null);(s?.items||[]).some(r=>!G(r))&&(await b(o.file,{...s,reviewers:a}),i.push(`item file ${o.slug}: reviewers copied`))}return{file:n,lines:i}}c(Xn,"writeReviewers");const Gl=c((t,e)=>Xn(t,()=>Yn(e,"the reviewer file")),"setReviewers"),Zt=c(t=>$.join(D(t),"data","pr-slack.json"),"prSlackFile"),Fe=c(t=>g(Zt(t),{}),"readPRSlack"),Re=c(t=>!!(t?.ts||t?.posting_at),"held");async function yt(t,e){return re(t,async()=>{const n=JSON.parse(await A.readFile(t,"utf8").catch(()=>"{}")),a=e(n);return await Jt(t,JSON.stringify(n,null,2)+`
15
+ `),a})}c(yt,"editJSON");async function Ne(t,e,n){await yt(t,i=>{const o=e(i);Re(o)&&d("that Slack message has already gone out"),o.posting_at=new Date().toISOString()});let a;try{a=await n()}catch(i){throw await yt(t,o=>{delete e(o).posting_at}),i}try{await yt(t,i=>{const o=e(i);o.ts=a,delete o.posting_at})}catch(i){d(`posted, but its record failed, so it won't go again: ${i.message}`)}return a}c(Ne,"postOnce");const Ql=c((t,e,n,a)=>Ne(Zt(t),i=>{const o=i[e.pr]||={head:e.head,links:{},replies:[]};return o.head??=e.head,Object.assign(o.links[e.reviewer]||={reactions:[]},{channel:n.channel,thread_ts:n.ts})},a),"postLink"),Vl=c((t,e,n)=>Ne(Zt(t),a=>a[e.pr].replies.find(i=>i.id===e.id).to[e.reviewer],n),"postReply"),Zl=c((t,e)=>yt(Zt(t),n=>{const a=n[e.pr],i=e.reply?a.replies.find(o=>o.id===e.reply).to[e.reviewer]:a.links[e.reviewer];i.reactions=[...new Set([...i.reactions||[],e.emoji])]}),"recordReaction"),ji=c((t,e,n,a)=>yt(Zt(t),i=>{const o=i[e],s=Object.keys(o?.links||{}).filter(r=>o.links[r].ts);return s.length?(o.replies.push({id:`${n}-${o.replies.length+1}`,text:a,to:Object.fromEntries(s.map(r=>[r,{}]))}),s):[]}),"queueReply");function _r(t,e){const n=t.commits||[],a=n.length-n.findIndex(i=>i.oid===e)-1;return`${a} new commit${a===1?"":"s"}`}c(_r,"pushText");async function Yl(t){const e=await g(Nn,{}),n=c((a,i)=>{const o=at(e.prs,a)?.head;return!!o&&o!==i.head&&Object.values(i.links).some(s=>s.ts)},"moved");return Object.entries(await Fe(t)).some(([a,i])=>n(a,i))?yt(Zt(t),a=>{const i=[];for(const[o,s]of Object.entries(a)){if(!n(o,s))continue;const r=at(e.prs,o),l=Object.keys(s.links).filter(u=>s.links[u].ts);s.head&&(s.replies.push({id:`push-${s.replies.length+1}`,text:_r(r,s.head),to:Object.fromEntries(l.map(u=>[u,{}]))}),i.push(o)),s.head=r.head}return i}):[]}c(Yl,"queuePushes");function Oi(t,e,n){const[a,i]=e.split("#");return[t&&`<@${t}>`,`<${In({repo:a,number:i})}|${a.split("/").pop()}#${i}>`,n].filter(Boolean).join(" ")}c(Oi,"aboutPR");function Sr(t,e){const n=Number.isInteger(t.additions)?` (+${t.additions}/-${t.deletions}, ${t.files} file${t.files===1?"":"s"})`:"";return`ready for review: ${t.title||e.title}${n}`}c(Sr,"linkText");const Ai=c(t=>!!t?.approved||t?.reviewDecision==="APPROVED","approved");async function Xl(t,e){D(t);const n=await ei.waiting("slack");if(n)return{waiting:n,links:[],replies:[],reactions:[],digest:null};const a=await rt(t),i=await g(Nn,{}),o=await Fe(t),s=[],r=new Map;for(const w of await q(t)){const f=await g(w.file,{}),h=Tn(f,a.reviewers);for(const m of h)r.has(m.name)||r.set(m.name,m.slack_user);for(const m of f.items||[])if(m.lane!=="done")for(const y of Ht(m,ct(t,f))){const _=Pe(y),P=at(i.prs,_);if(!(P?.state!=="OPEN"||P.isDraft))for(const S of h)Re(o[_]?.links?.[S.name])||s.some(v=>v.pr===_&&v.reviewer===S.name)||s.push({pr:_,key:`${w.slug}/${m.id}`,reviewer:S.name,slack_user:S.slack_user,head:P.head||null,text:Oi(S.slack_user,_,Sr(P,m))})}}const l=[],u=[];for(const[w,f]of Object.entries(o)){const h=at(i.prs,w),m=[Ai(h)&&"git_approved",h?.state==="MERGED"?"git_merged":h?.state==="CLOSED"&&"x"].filter(Boolean),y=c((_,P,S)=>{if(P.ts)for(const v of m)P.reactions?.includes(v)||u.push({pr:w,reviewer:_,...S?{reply:S}:{},channel:P.channel||f.links[_].channel,ts:P.ts,emoji:v})},"react");for(const[_,P]of Object.entries(f.links))y(_,P);for(const _ of f.replies)for(const[P,S]of Object.entries(_.to)){y(P,S,_.id);const v=f.links[P];Re(S)||l.push({pr:w,id:_.id,reviewer:P,channel:v.channel,thread_ts:v.thread_ts?null:v.ts,text:Oi(r.get(P),w,_.text)})}}const p=await vr(t,e);return{date:Mn(e?.now).date,links:s,replies:l,reactions:u,digest:p.due?p:null}}c(Xl,"reviewDue");async function td(t,e,n){D(t);const a=j(n,"what changed"),{itemFile:i,item:o}=await x(t,e),s=[];for(const l of Ht(o,ct(t,i)))s.push(...await ji(t,Pe(l),"updated",`updated: ${a}`));const r=[...new Set(s)];return{lines:[r.length?`Updated queued for ${r.join(", ")} on ${e}`:`no reviewer has a link to ${e}'s PRs; nothing queued`]}}c(td,"reviewUpdated");async function ed(t,e){const{itemFile:n,item:a}=await x(t,e),i=await Fe(t);return Ht(a,ct(t,n)).some(o=>Object.values(i[Pe(o)]?.links||{}).some(s=>s.ts))}c(ed,"cardLinked");const ue=c(t=>$.join(D(t),"data","review-digests.json"),"digestFile");async function vr(t,{now:e=new Date}={}){D(t);const n=await rt(t),a=await g(Nn,{}),i=await Fe(t),o=Hs(),s=new Map;for(const f of await q(t)){const h=await g(f.file,{}),m=Tn(h,n.reviewers);for(const y of m)s.has(y.name)||s.set(y.name,{name:y.name,slack_user:y.slack_user,dm:y.dm,items:[]});for(const y of h.items||[]){if(y.lane==="done")continue;const _=`${f.slug}/${y.id}`,P=Us(h,y,_,o);for(const S of Ht(y,ct(t,h))){const v=Pe(S),F=at(a.prs,v);if(!(F?.state!=="OPEN"||F.isDraft||F.failing?.length||Ai(F)))for(const I of m){const M=i[v]?.links?.[I.name]?.ts||at(P,I.name)?.ts||null,O=M?(e.getTime()-Number(M)*1e3)/864e5:null,L=O>2?Math.floor(O):null;s.get(I.name).items.push({key:_,pr:v,title:y.title,url:In(S),sent_ts:M,...L?{days_old:L}:{},text:`${In(S)} \xB7 ${y.title}${L?` (${L} days old)`:""}`})}}}}const{date:r,open:l}=Mn(e),u=((await g(ue(t),{})).digests||[]).filter(f=>f.date===r),p=await ei.waiting("slack");for(const f of u)s.has(f.reviewer)||s.set(f.reviewer,{name:f.reviewer,items:[]});const w=[...s.values()].map(f=>{const h=u.find(y=>y.reviewer===f.name),m=h?.replies?!h.posting_at&&(!h.ts||h.replies.some(y=>!Re(y))):!h?.posting_at&&f.items.length>0;return{...f,owed:m,...h?{sent:h}:{}}}).filter(f=>f.items.length||f.sent);return{date:r,due:!p&&l&&w.some(f=>f.owed),...p?{waiting:p}:{},reviewers:w}}c(vr,"reviewDigest");const en=c((t,e)=>n=>(n.digests||[]).find(a=>a.date===t&&a.reviewer===e),"dayEntry"),jr=7,Pi=c((t,e)=>(Date.parse(e)-Date.parse(t.date))/864e5<jr,"heardOn");function Di(t,e,n,a){en(e,n)(t)||(t.digests=[...(t.digests||[]).filter(i=>Pi(i,e)),{date:e,reviewer:n,...a}],delete t.last_date)}c(Di,"addDayEntry");async function nd(t,e=new Date){const{date:n}=Mn(e);return((await g(ue(t),{})).digests||[]).filter(a=>a.ts&&Pi(a,n))}c(nd,"heardThreads");const ad=c((t,e,n)=>yt(ue(t),a=>{en(e.date,e.reviewer)(a).heard=n}),"markHeard");async function Or(t){const e=new Set;for(const n of Object.values(await Fe(t))){for(const a of Object.values(n.links||{}))e.add(a.ts);for(const a of n.replies||[])for(const i of Object.values(a.to))e.add(i.ts)}for(const n of(await g(ue(t),{})).digests||[])for(const a of[n,...n.replies||[]])e.add(a.ts);return e.delete(void 0),e}c(Or,"boardPosts");const Fi="\u{1F916} ",Ri=600;async function ta(t,e){return vt(e,"the event id"),(await J($.join(D(t),"data","events.jsonl"))).find(a=>a.id===e&&a.kind==="slack-question")?.data||d(`no slack-question "${e}" in this site's data/events.jsonl`)}c(ta,"slackQuestion");const ea=c(t=>t||d(Ks),"throughSlack"),na=c(t=>t.catch(e=>e instanceof Js?d(e.message):Promise.reject(e)),"slackCall");async function id(t,e,n=qn()){const a=await ta(t,e),i=await Or(t),o=Gs();return{lines:(await na(ea(n).replies({channel:a.channel,ts:a.thread_ts}))).flatMap(l=>{const u=i.has(l.ts)||l.user===o&&l.text?.startsWith(Fi)?"board":l.user===o?"you":a.reviewer,[p,...w]=String(l.text||"").split(`
16
+ `);return[`${l.ts===a.ts?"\u2192 ":""}${u}: ${p}`,...w.map(f=>` ${f}`)]})}}c(id,"slackThread");async function od(t,e,n,a=qn()){const i=await ta(t,e);i.answer||d("that message is the owner's and names no @kickflip, so it expects no reply");const o=j(n,"--text");return o.length>Ri&&d(`--text runs to ${o.length} characters, past an answer's ${Ri}: keep it brief`),await na(ea(a).post({channel:i.channel,thread_ts:i.thread_ts,text:`${Fi}${o}`})),{lines:[`answered in ${i.reviewer}'s day thread`]}}c(od,"slackAnswer");async function sd(t,e,n,{title:a,notes:i,notesFrom:o},s=qn()){const r=await ta(t,e),u=(await na(ea(s).replies({channel:r.channel,ts:r.thread_ts}))).find(h=>h.ts===r.ts)||d("that Slack message is gone from its thread"),p=await kc(t,n,{title:a,notes:i,notesFrom:o,phase:"grilling",intake:!0}),w=zs().slack_domain,f=w?`https://${w}.slack.com/archives/${r.channel}/p${r.ts.replace(".","")}?thread_ts=${r.thread_ts}&cid=${r.channel}`:void 0;return await Gt(t,p.key,{text:u.text,who:r.from==="owner"?"love":r.reviewer,via:"slack",link:f}),{...p,lines:[`filed ${p.key} grilling, for the owner's review`]}}c(sd,"slackTask");async function rd(t,e,n,{channel:a,header:i,post:o}){const s=ue(t),r=en(e,n),l=await yt(s,u=>(Di(u,e,n,{channel:a}),{...r(u)}));return{channel:l.channel,ts:l.ts||await Ne(s,r,()=>o({channel:l.channel,text:i}))}}c(rd,"openDayThread");async function cd(t,e,n,{channel:a,header:i,post:o}){const s=ue(t),r=en(e,n.name),l=`<@${n.slack_user}>`;await yt(s,f=>{Di(f,e,n.name,{channel:a});const h=r(f);h.replies||(h.replies=h.ts?[{prs:n.items.map(m=>m.pr),text:[`${l} ${i(n.items.length)}`,...n.items.map(m=>m.text)].join(`
17
+ `)}]:n.items.map(m=>({pr:m.pr,text:`${l} ${m.text}`})))});const u=r(await g(s,{})),p=u.ts||await Ne(s,r,()=>o({channel:u.channel,text:i(u.replies.length)}));for(const[f,h]of u.replies.entries())Re(h)||await Ne(s,m=>r(m).replies[f],()=>o({channel:u.channel,thread_ts:p,text:h.text}));const w=r(await g(s,{})).replies.filter(f=>f.pr&&f.ts);w.length&&await yt(Zt(t),f=>{const h=`digest-${e}`;for(const m of w){const y=f[m.pr]||={links:{},replies:[]},_=y.replies.find(P=>P.id===h)||y.replies[y.replies.push({id:h,text:m.text,to:{}})-1];_.to[n.name]||={channel:u.channel,ts:m.ts,reactions:[]}}})}c(cd,"postDigest");function ld(t,e){const n=Yn(Array.isArray(e)?e:[e],"the reviewer file");return Xn(t,a=>[...a.map(i=>n.find(o=>De(o.name,i.name))||i),...n.filter(i=>!a.some(o=>De(i.name,o.name)))])}c(ld,"addReviewers");function dd(t,e){return Xn(t,n=>{const a=e.filter(i=>!n.some(o=>De(o.name,i)));return a.length&&d(`this board has no reviewer ${a.map(i=>`"${i}"`).join(", ")}`),n.filter(i=>!e.some(o=>De(i.name,o)))})}c(dd,"removeReviewers");const Ar=c(()=>$.join(An.homedir(),".claude","kickflip","settings.json"),"hubSettingsFile"),aa=c(t=>{try{return t()}catch(e){throw e instanceof Ys&&d(e.message),e}},"ruleCall"),ia=c(async t=>ai(await g($.join(t,"board.json"),{})),"readBoardRules");let Ni=Promise.resolve();function Ee(t,e){const n=Ni.then(async()=>{const a=$.join(D(t),"board.json"),i=await g(a,{}),{set:o,...s}=e(i);return await b(a,{...i,...o}),{file:a,...s}});return Ni=n.catch(()=>{}),n}c(Ee,"writeBoardJSON");const Ei=c((t,e)=>Ee(t,n=>{const a=aa(()=>e(ai(n)));return{set:{rules:a.rules},...a}}),"writeBoardRules");function ud(t,e){const n=Object.keys(e||{}).sort().join(),a=n==="level,login",i=a?e.login:e?.[n],o=typeof i=="string"?i.trim():null;(!["add","remove","level,login"].includes(n)||!or(o))&&d("Send add or remove with one login, like name@github, or a listed login with its level."),a&&!["view","full"].includes(e.level)&&d("A level is view or full.");const s=c(({login:r,level:l})=>l==="full"?{login:r,level:l}:r,"stored");return Ee(t,r=>{const l=ir(r);a&&!l.some(w=>w.login===o)&&d(`${o} isn't shared with yet. Add them first.`);const p=(n==="remove"?l.filter(w=>w.login!==o):a?l.map(w=>w.login===o?{login:o,level:e.level}:w):l.some(w=>w.login===o)?l:[...l,{login:o,level:"view"}]).map(s);return{set:{share:p},share:p}}).then(({share:r})=>({share:r}))}c(ud,"saveBoardShare");const Li=c(t=>typeof t=="string"&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(t),"validGithubLogin"),Bi=c(t=>{try{return t?Ja(t):null}catch{return null}},"storedTickets"),oa=c(t=>Number.isInteger(t)&&t>=1&&t<=99,"validCap"),sa=["max_implementers","max_planners"],At=c((t,e)=>{const n=Bi(t?.tickets);return{auto_merge:t?.auto_merge===!0,auto_build:t?.auto_build===!0,auto_pull:t?.auto_pull===!0,max_implementers:oa(t?.max_implementers)?t.max_implementers:os,max_planners:oa(t?.max_planners)?t.max_planners:ss,auto_triage:t?.auto_triage===!0,auto_review:t?.auto_review===!0,idle_notification:t?.idle_notification===!0,skip_draft:t?.skip_draft===!0,prs:e?.hub?t?.prs===!0:t?.prs!==!1,...n?{tickets:n}:{},...Li(t?.github_login)?{github_login:t.github_login}:{},...ni(t?.build_target)?{build_target:t.build_target}:{}}},"settingsOf");async function fd(t,e,n=new Date){let a;try{a=bs(e,n)}catch(i){d(i.message)}return await Ee(t,()=>({set:{paused_until:a??void 0}})),a}c(fd,"setBoardPause");async function Pr(t){const e=D(t);return At(await g($.join(e,"board.json"),{}),kt().find(n=>Rt(n.dir,e)))}c(Pr,"readBoardSettings");const wd=c((t,e)=>!!t?.github&&(!t.local||t.hub===!0)&&e.prs,"opensPRs");async function fe(t,e){le(e,["auto_merge","auto_build","auto_pull","max_implementers","max_planners","auto_triage","auto_review","idle_notification","skip_draft","prs","tickets","github_login","build_target"],"the settings"),Object.keys(e).length||d("the settings name nothing to change"),e={...e};for(const[n,a]of Object.entries(e))if(n==="tickets"){try{e.tickets=Ja(a)??void 0}catch(o){d(o.message)}e.tickets?.source==="linear"&&!Fs()&&d(Ps);const i=e.tickets?.source==="github"&&t?kt().find(o=>Rt(o.dir,t)):null;i&&!i.github&&d("GitHub issues need the board\u2019s repo on GitHub, and this board\u2019s repo isn\u2019t; pick none or linear")}else n==="github_login"?a===""||a===null?e.github_login=void 0:Li(a)||d("github_login must be a GitHub login"):n==="build_target"?a===null?e.build_target=void 0:ni(a)||d('build_target must name .kickflip/build-<target>: letters, digits, ".", "_" or "-", or null for .kickflip/build'):sa.includes(n)?oa(a)||d(`${n} must be a whole number from 1 to 99`):Ze(a,n);if(e.prs===!1){const n=t?kt().find(a=>Rt(a.dir,t)):null;n?.github&&!n.local&&!(await Qs(n.owner?.repo)).pushMain&&d("Merge lands each card on main and pushes it, so turn on Push main after a land first")}return Ee(t,n=>{const a=t?kt().find(s=>Rt(s.dir,t)):null,i=At(n,a),o=At({...n,...e},a);return{set:e,settings:o,changed:Object.keys(e).filter(s=>JSON.stringify(i[s])!==JSON.stringify(o[s]))}})}c(fe,"saveBoardSettings");async function pd(){if(Ds().set)return[];const t=[];for(const e of kt())(await Pr(e.dir)).tickets?.source==="linear"&&(await fe(e.dir,{tickets:{source:"none"}}),await $t(e,"settings",{tickets:null}),t.push(`/${e.route} fell back to no ticket source: Hub has no Linear key`));return t}c(pd,"fallBackFromLinear");async function md(t,e,n){const a=String(e).replace(/-/g,"_"),i=["auto_merge","auto_build","auto_pull","max_implementers","max_planners","auto_triage","auto_review","idle_notification","skip_draft","prs","github_login","tickets","build_target"];if(i.includes(a)||d(`no board setting "${e}"; settings are ${i.map(r=>r.replace(/_/g,"-")).join(", ")}`),a==="tickets"){let r;try{r=JSON.parse(n)}catch{d('settings set tickets takes the source as JSON, such as {"source":"github"}')}const{file:l,settings:u}=await fe(t,{tickets:r});return{file:l,lines:Dr({tickets:u.tickets})}}if(a==="github_login"){const{file:r,settings:l}=await fe(t,{github_login:n});return{file:r,lines:[`github-login ${l.github_login||"unset"}`]}}if(a==="build_target"){const{file:r,settings:l}=await fe(t,{build_target:n==="default"?null:n});return{file:r,lines:[`build-target ${l.build_target||"default"}`]}}if(sa.includes(a)){const{file:r,settings:l}=await fe(t,{[a]:/^\d+$/.test(n)?Number(n):n});return{file:r,lines:[`${e} ${l[a]}`]}}["on","off"].includes(n)||d(`settings set ${e} takes on or off, not "${n}"`);const{file:o,settings:s}=await fe(t,{[a]:n==="on"});return{file:o,lines:[`${e} ${s[a]?"on":"off"}`]}}c(md,"setBoardSetting");const Dr=c(t=>Object.entries(t).map(([e,n])=>`setting ${e.replace(/_/g,"-")} ${e==="tickets"?JSON.stringify(n??{source:"none"}):e==="github_login"||sa.includes(e)?n:e==="build_target"?n||"default":n?"on":"off"}`),"settingsLines");async function ra(t,e,n){const a=e?aa(()=>n(Qe())):await Ei(t,n);return e&&aa(()=>ar(a.rules)),{file:e?Ar():a.file,lines:[`id ${a.rule.id}`]}}c(ra,"changeRules");async function Ci(t,e,n){const a=c(s=>s.map(r=>r.id),"ids");n||D(t);const[i,o]=n?[a(Qe()),t?a(await ia(t)):[]]:[a(await ia(t)),a(Qe())];i.includes(e)||d(`no ${n?"hub":"board"} rule "${e}"${o.includes(e)?`; it is a ${n?"board":"hub"} rule, so ${n?"drop":"pass"} --hub`:""}`)}c(Ci,"checkRuleId");async function hd(t){const e=c(n=>a=>`${n} ${a.id} ${a.by==="claude"?"claude":"owner"} ${a.text}`,"line");return{lines:[...Qe().map(e("hub")),...t?(await ia(t)).map(e("board")):[]]}}c(hd,"listRules");function gd(t,{text:e,hub:n=!1,by:a}){return n||D(t),ra(t,n,i=>Xs(i,{text:e,by:a}))}c(gd,"addRuleTo");async function $d(t,e,{text:n,hub:a=!1}){return await Ci(t,e,a),ra(t,a,i=>tr(i,e,n))}c($d,"editRuleIn");async function kd(t,e,{hub:n=!1}){return await Ci(t,e,n),ra(t,n,a=>er(a,e))}c(kd,"removeRuleFrom");const yd=c((t,e,n)=>Ei(t,a=>nr(a,e,n)),"saveBoardRules");async function bd(t,{id:e,title:n,summary:a}){D(t);const i=await g(B(t),{topics:[],items:[]}),o=i.topics||[];return o.some(s=>s.id===j(e,"the topic id"))&&d(`topic "${e}" already exists`),o.push({id:e.trim(),title:j(n,"--title"),...a===void 0?{}:{summary:j(a,"--summary")}}),await b(B(t),{...i,topics:o,items:i.items||[]}),B(t)}c(bd,"addTopic");const Ii=["quiet","info","notice","danger","success"];function Fr(t,e){if(t.diagram===void 0!=(t.practice===void 0)&&d(`${e} needs diagram and practice together`),t.diagram===void 0)return;const n=t.diagram;(!Array.isArray(n)||!n.length)&&d(`${e}.diagram must be a non-empty array of rows`),n.forEach((a,i)=>{(!Array.isArray(a)||!a.length||a.length>4)&&d(`${e}.diagram[${i}] must be a row of 1 to 4 boxes`),a.forEach((o,s)=>{const r=`${e}.diagram[${i}][${s}]`;le(o,["text","tone","to"],r),j(o.text,`${r}.text`),it(o.tone,l=>Ii.includes(l)?l:d(`${r}.tone takes ${Ii.join(", ")}`)),it(o.to,l=>Array.isArray(l)&&i+1<n.length&&l.every(u=>Number.isInteger(u)&&u>=0&&u<n[i+1].length)?l:d(`${r}.to must list boxes of the next row by index`))})}),(!Array.isArray(t.practice)||!t.practice.length)&&d(`${e}.practice must be a non-empty array of lines`),t.practice.forEach((a,i)=>j(a,`${e}.practice[${i}]`))}c(Fr,"checkDiagram");function Rr(t,e){(!Array.isArray(t)||!t.length)&&d(`${e}.options must be a non-empty array`);const n=new Set;t.forEach((a,i)=>{const o=`${e}.options[${i}]`;le(a,["id","label","recommended","detail","diagram","practice"],o),Fr(a,o),n.has(j(a.id,`${o}.id`))&&d(`${e} has two options with id "${a.id}"`),n.add(a.id),j(a.label,`${o}.label`).startsWith(`${a.id}. `)&&d(`${o}.label starts with "${a.id}. ", but the page adds the option letter itself`),it(a.recommended,s=>Ze(s,`${o}.recommended`)),it(a.detail,s=>typeof s=="string"?s:d(`${o}.detail must be text`))}),t.filter(a=>a.recommended).length>1&&d(`${e} recommends more than one option`)}c(Rr,"checkOptions");function Nr(t,e,n){le(t,["option","card","answer","reason"],n),e.some(a=>a.id===j(t.option,`${n}.option`))||d(`${n}.option names no option "${t.option}"`),j(t.card,`${n}.card`),j(t.answer,`${n}.answer`),it(t.reason,a=>j(a,`${n}.reason`))}c(Nr,"checkSuggested");const we=c(t=>$.join(t,"data","prototypes.json"),"prototypesFile"),ca=c((t,e,n)=>$.join(t,"public","prototypes",e,`${n}.js`),"takeFile");async function Le(t){const e=t?(await g(we(t),{})).prototypes:null;return Array.isArray(e)?e:[]}c(Le,"readPrototypes");const Er=c(t=>typeof t=="string"&&/^[a-z0-9-]+$/.test(t)?t:d(`a prototype topic uses only a-z, 0-9 and "-", not "${t}"`),"prototypeTopic");function Lr(t){const e=/^([^:]*):(.*)$/s.exec(t);(!e||!/^[A-Z]$/.test(e[1]))&&d(`--take takes KEY:"Label" with KEY one capital letter, not "${t}"`);const n=j(e[2],`--take ${e[1]}'s label`);return/^[A-Z]\.\s/.test(n)&&d(`--take ${e[1]}'s label starts with "${n.slice(0,3)}"; the take pill shows the label alone, so drop the letter`),{key:e[1],label:n}}c(Lr,"prototypeTake");function Br(t){const e=/^([^:]*):(.*)$/s.exec(t);return(!e||!/^[a-z0-9][a-z0-9-]*$/.test(e[1]))&&d(`--state takes KEY:"Label" with KEY in a-z, 0-9 and "-", not "${t}"`),{key:e[1],label:j(e[2],`--state ${e[1]}'s label`)}}c(Br,"prototypeState");const Ti=c(t=>t.find((e,n)=>t.findIndex(a=>a.key===e.key)!==n),"twiceIn"),Lt=c(t=>/^prototype-(.+)\.html$/.exec($.posix.basename(String(t||"").split(/[?#]/)[0]))?.[1],"pageTopic");async function xd(t,{topic:e,title:n,card:a,takes:i=[],served:o,states:s=[]}){D(t),Er(e),j(n,"--title"),i.length||d('prototype add needs a --take KEY:"Label" for each take');const r=i.map(Lr),l=Ti(r);l&&d(`--take ${l.key} is given twice`),o!==void 0&&!/^\/\S*$/.test(o)&&d(`--served takes the page's path on the served site, starting with "/", not "${o}"`),s.length&&o===void 0&&d("--state goes with --served: only a served round re-renders its states in place");const u=s.map(Br),p=Ti(u);p&&d(`--state ${p.key} is given twice`),a!==void 0&&await x(t,a);const w=await Le(t);w.some(m=>m.topic===e)&&d(`prototype ${e} is already recorded; run prototype rm ${e} first, or pick another topic`),await A.stat($.join(t,"public",`prototype-${e}.html`)).then(()=>!0,()=>!1)&&d(`public/prototype-${e}.html is a hand-written page that questions may link; pick another topic`);const f={topic:e,title:n.trim(),...a===void 0?{}:{card:a},...o===void 0?{}:{served:o},takes:r,...u.length?{states:u}:{},at:new Date().toISOString()};await b(we(t),{prototypes:[...w,f]});const h=`page prototype-${e}.html`;return o!==void 0?{file:we(t),lines:[h,`served ${o} from the base prototype worktree (board.mjs prototype base)`,...u.length?[`states ${u.map(m=>m.key).join(", ")}`]:[]]}:{file:we(t),lines:[h,...r.map(m=>`take ${m.key} ${ca(t,e,m.key)}`)]}}c(xd,"addPrototype");async function _d(t){D(t);const e=await Le(t);return{lines:e.length?e.map(n=>[n.topic,n.title,n.takes.map(a=>`${a.key}: ${a.label}`).join(", "),n.card,n.served&&`served ${n.served}`,n.states&&`states ${n.states.map(a=>a.key).join(", ")}`].filter(Boolean).join(" \xB7 ")):["no prototypes recorded"]}}c(_d,"listPrototypes");async function Sd(t){const e=(await Le(t)).filter(a=>a.served).map(a=>a.topic);if(!e.length)return[];const n=await g(B(t),{items:[]});return e.filter(a=>(n.items||[]).some(i=>!i.resolved&&Lt(i.url)===a))}c(Sd,"servedRoundsOpen");async function vd(t,e){D(t);const n=await Le(t);n.some(o=>o.topic===e)||d(`no prototype "${e}" is recorded`);const i=((await g(B(t),{items:[]})).items||[]).filter(o=>!o.resolved&&Lt(o.url)===e).map(o=>o.id);return i.length&&d(`prototype ${e} backs open question ${i.join(", ")}; resolve ${i.length===1?"it":"them"} first`),await b(we(t),{prototypes:n.filter(o=>o.topic!==e)}),we(t)}c(vd,"removePrototype");async function Cr(t,e,n){const a=e.url?.split(/[?#]/)[0];if(!a||!$.posix.basename(a).startsWith("prototype-"))return;const i=$.posix.basename(a),o=e.url.split("#")[0].split("?").slice(1).join("?"),s=`${n}.url`;new URLSearchParams(o).get("q")!==e.id&&d(`${s} must be ${i}?q=${e.id} so the pill can pick`);const r=Lt(a),l=(await Le(t)).find(f=>f.topic===r);l||d(`${s} names ${i}, which is not a recorded prototype; record it with board.mjs prototype add ${r} --title "\u2026" --take A:"\u2026", then write its take files`);const u=l.takes.map(f=>f.key),p=e.options.map(f=>f.id),w=p.map(f=>u.indexOf(f));if(w.some((f,h)=>f<0||h>0&&f<w[h-1])&&d(`${n}.options ids ${p.join(", ")} must be a non-empty subset of ${i}'s takes, in take order: ${u.join(", ")}`),!l.served)for(const f of u)await A.stat(ca(t,r,f)).then(h=>h.isFile(),()=>!1)||d(`${s} take ${f} has no file yet; write ${ca(t,r,f)}`)}c(Cr,"checkPrototype");async function jd(t,e,n=async()=>{}){D(t);const a=Array.isArray(e)?e:[e];a.length||d("the question file is empty");const i=await g(B(t),{topics:[],items:[]}),o=i.items||[],s=await g(ut(t),{}),r=new Set([...o,...Object.values(s).flat()].map(w=>w.id)),l=new Set((i.topics||[]).map(w=>w.id));for(const[w,f]of a.entries()){const h=`question ${f?.id??w+1}`;if(le(f,["id","topic","source","question","context","url","urgent","options","round_of","reask_of","ask","suggested","prototype_gate","ticket_gate"],h),r.has(vt(f.id,`${h}.id`))&&d(`question id "${f.id}" is already used`),r.add(f.id),j(f.topic,`${h}.topic`),f.topic.startsWith("item:ask:")){const m=await Vt(t,await Ce(t,f.topic.slice(9),`${h}.topic`));d(`${h}.topic: an ask's questions go on its card's topic${m?`, item:${m.key}`:""}`)}else f.topic.startsWith("item:")?await x(t,f.topic.slice(5)):f.topic.startsWith("wave:")?await $e(t,f.topic.slice(5)):f.topic.startsWith("file:")?await jc(t,f.topic.slice(5)):l.has(f.topic)||d(`topic "${f.topic}" is not declared; add it with: topic add ${f.topic} --title <t>`);j(f.question,`${h}.question`),f.question.length>Va&&d(`${h}.question runs to ${f.question.length} characters, past ${Va}; keep the question to one line and move the detail into context or the option details, which take markdown`);for(const m of["source","context"])it(f[m],y=>j(y,`${h}.${m}`));it(f.url,m=>Wn(m,`${h}.url`)),it(f.urgent,m=>Ze(m,`${h}.urgent`)),Rr(f.options,h);for(const m of Object.keys(Be))f[m]!==void 0&&Tr(f[m],f,`${h}.${m}`)&&await qr(t,f,m,h);it(f.suggested,m=>Nr(m,f.options,`${h}.suggested`)),await Cr(t,f,h),f.ask!==void 0&&await Wc(t,f,h),it(f.round_of,m=>{const y=o.find(_=>_.id===m);y||d(`${h}.round_of names no question "${m}" in owner.json`),y.topic!==f.topic&&d(`${h}.round_of names ${m} on topic ${y.topic}; a round stays on its question's topic, ${f.topic}`),Lt(f.url)||d(`${h}.round_of needs a url on a recorded prototype, prototype-<topic>.html?q=${f.id}`)}),it(f.reask_of,m=>{const y=o.find(_=>_.id===m);y||d(`${h}.reask_of names no question "${m}" in owner.json`),y.topic!==f.topic&&d(`${h}.reask_of names ${m} on topic ${y.topic}; a re-ask stays on its question's topic, ${f.topic}`),y.resolved||d(`${h}.reask_of names ${m}, which is not resolved; only a resolved question is asked again`)})}for(const w of new Set(a.map(f=>Lt(f.url)).filter(Boolean)))await n(t,w);const u=[],p=[];for(const w of a){const f=w.topic.startsWith("item:")&&!w.topic.startsWith("item:ask:")?w.topic.slice(5):null,h=f&&await qi(t,f);h&&((s[f]||=[]).push(w),p.push(w),u.push(`staged: ${w.id} waits for ${f}'s ${h} to finish; the card's staged questions then publish together`))}return p.length&&await b(ut(t),s),p.length===a.length?{file:ut(t),lines:u,staged:p.length}:Wi(t,i,o,a.filter(w=>!p.includes(w)),u)}c(jd,"addQuestions");async function qi(t,e){const{source:n}=await x(t,e);for(const a of await V(n.dir,R(e).id)){const i=await g(a,null);if(i?.started&&!i.done&&Ut(i)&&i.kind!==gt)return i.kind}return null}c(qi,"runningPlanner");async function pe(t,e,{screen:n=!1}={}){if(!t||await qi(t,e))return;const a=await g(ut(t),{});if(!a[e])return;const i=await g(ce(t),{});if(n){i[e]||await b(ce(t),{...i,[e]:new Date().toISOString()});return}const{[e]:o,...s}=a,r=await g(B(t),{topics:[],items:[]});await Wi(t,r,r.items||[],o,[]),await b(ut(t),s),i[e]&&await b(ce(t),nn(i,e))}c(pe,"publishStaged");const nn=c((t,e)=>Object.fromEntries(Object.entries(t).filter(([n])=>n!==e)),"withoutKey");async function Mi(t){const e=await g(ce(t),{}),n=await g(ut(t),{});return Object.fromEntries(Object.entries(e).filter(([a])=>n[a]).map(([a,i])=>[a,{since:i,ids:n[a].map(o=>o.id)}]))}c(Mi,"readScreening");async function Od(t,e,n){D(t);const a=j(n,"--note"),i=await g(ut(t),{}),o=await g(ce(t),{}),s=Object.keys(i).find(w=>i[w].some(f=>f.id===e));if(!s)return Ir(t,e,a);o[s]||d(`${e} waits for ${s}'s planner to finish`);const r=i[s].find(w=>w.id===e);r.prototype_gate&&d(`${e} is the card's prototype question, which is the owner's; question publish ${s} passes it on`),r.ticket_gate&&d(`${e} is the card's ticket question, which is the owner's; question publish ${s} passes it on`);const l=new Date().toISOString(),u=await g(B(t),{topics:[],items:[]});await b(B(t),{...u,topics:u.topics||[],items:[...u.items||[],{...r,asked_at:l,resolved:`Settled by the orchestrator: ${a}`,resolved_at:l}]});const p=i[s].filter(w=>w.id!==e);return await b(ut(t),p.length?{...i,[s]:p}:nn(i,s)),p.length||await b(ce(t),nn(o,s)),await Bt(t,s,`Answers (orchestrator, ${Yt()})`,`- ${e} (${r.question}): settled by the orchestrator. "${a}"`),B(t)}c(Od,"settleQuestion");async function Ir(t,e,n){const a=await g(B(t),{topics:[],items:[]}),i=(a.items||[]).find(r=>r.id===e&&r.topic?.startsWith("item:"));i||d(`no staged question "${e}"; question settle takes a question a finished grill left for you to screen, or a card's question while it waits on your re-check`);const o=i.topic.slice(5);(await x(t,o)).item.recheck_at||d(`${o} waits on no re-check, so its question ${e} stays answered as it is`);const s=new Date().toISOString();return await b(B(t),{...a,items:a.items.map(r=>r===i?{...r,resolved:`Settled by the orchestrator: ${n}`,resolved_at:s}:r)}),await Bt(t,o,`Answers (orchestrator, ${Yt()})`,`- ${e} (${i.question}): settled by the orchestrator. "${n}"`),B(t)}c(Ir,"settleStale");async function Ad(t,e){D(t);const n=(await Mi(t))[e]?.ids||d(`${e} has no questions waiting on you to screen`);return await pe(t,e),n}c(Ad,"publishScreened");async function Pd(t,e=new Date){const n=Object.entries(await Mi(t)).filter(([,a])=>e-Date.parse(a.since)>=rr).map(([a])=>a);for(const a of n)await pe(t,a),await W(t,a,"screen-timeout");return n}c(Pd,"publishUnscreened");async function Wi(t,e,n,a,i){const{answers:o,requests:s,reopens:r}=await he(t),l=new Date().toISOString(),u=[],p=[];for(const f of a.filter(h=>h.round_of))f.round=Rn(n.find(h=>h.id===f.round_of))+1,Xt(e,[f.round_of],`Followed by prototype round ${f.round}`,l),p.push(f.round_of);for(const f of a.filter(h=>h.reask_of))Xt(e,[f.reask_of],`Asked again as ${f.id}`,l),p.push(f.reask_of);for(const f of a){const h=Lt(f.url),m=n.filter(_=>_.topic===f.topic).map(_=>Wt(_,o,s,[],r)),y=f.topic.startsWith("item:")?Vi(m):[];for(const _ of m)y.includes(_.id)?(Xt(e,[_.id],`Followed by ${f.id}`,l),p.push(_.id)):!_.resolved&&h&&Lt(_.url)===h&&(Xt(e,[_.id],`Replaced by ${f.id}`,l),u.push(_.id))}const w={...e,topics:e.topics||[],items:[...n,...a.map(f=>({...f,asked_at:l}))]};await b(B(t),w);for(const f of new Set(a.map(h=>la(h.topic)).filter(Boolean)))await Gr(t,f);return{file:B(t),lines:[...i,...u.map(f=>`replaced: ${f}`),...p.map(f=>`resolved: ${f}`)]}}c(Wi,"publishQuestions");function Tr(t,e,n){return Ze(t,n),t?((!e.topic.startsWith("item:")||e.topic.startsWith("item:ask:"))&&d(`${n} goes on a card's topic, item:<file>/<id>`),e.options?.map(a=>a.id).join()!=="yes,no"&&d(`${n} takes exactly the options yes and no, in that order`),!0):!1}c(Tr,"checkGate");const Be={prototype_gate:"prototype",ticket_gate:"ticket"};async function qr(t,e,n,a){const i=e.topic.slice(5),{item:o}=await x(t,i),s=Be[n];o.gates?.[s]&&d(`${a}.${n}: ${i} already has its ${s} answer, ${o.gates[s]}`),n==="ticket_gate"&&(o.ticket&&d(`${a}.ticket_gate: ${i} already has ticket ${o.ticket}`),await ee(t)||d(`${a}.ticket_gate needs a board with a ticket source; with none every card stays a task`))}c(qr,"checkGateFact");async function Mr(t,e,n,a,i){const{source:o,itemFile:s,item:r}=await x(t,e);r.gates={...r.gates,[Be[n]]:a},await b(o.file,s),await Ui(t,e,n,i)}c(Mr,"keepGate");async function Ui(t,e,n,a){const i=await g(ut(t),{}),o=(i[e]||[]).filter(u=>!u[n]);o.length!==(i[e]||[]).length&&await b(ut(t),o.length?{...i,[e]:o}:nn(i,e));const{owner:s,asked:r}=await ft(t,e),l=r.filter(u=>u[n]&&u.state==="open").map(u=>u.id);return l.length&&await me(t,s,l,a),l.length>0}c(Ui,"resolveGate");async function Dd(t,e,n){const a=new Map(((await g(B(t),{items:[]})).items||[]).map(r=>[r.id,r]));for(const r of e){const l=a.get(String(r.id)),u=Object.keys(Be).find(h=>l?.[h]);if(!u||!["yes","no"].includes(r.choice))continue;const p=u==="ticket_gate"?`Ticket: ${r.choice}.${r.choice==="yes"?" The board makes it from the card's title and notes.":""}`:`Prototype round: ${r.choice}. The board moves the card on once every question is answered.`;await me(t,await g(B(t),{topics:[],items:[]}),[l.id],p);const w=l.topic.slice(5),f=await x(t,w).catch(()=>null);f&&(await Mr(t,w,u,r.choice,p),u==="ticket_gate"&&r.choice==="yes"&&await Hi(t,w,"making its ticket",async()=>{await bt(t,w,{newTicket:!0},n),await W(t,w,"ticket-made",{ticket:(await x(t,w)).item.ticket})}),u==="prototype_gate"&&r.choice==="yes"&&f.item.phase==="grilling"&&await ln(t,w)&&await W(t,w,"prototype-after"))}const i=new Map;for(const r of e){const l=a.get(String(r.id)),u=la(l?.topic);u&&i.set(u,[...i.get(u)||[],Wr(l,r)])}const o=[],s=[];for(const[r,l]of i)await x(t,r).catch(()=>null)&&await Hi(t,r,"writing them into its notes",async()=>{await Bt(t,r,`Answers (owner, ${Yt()})`,l.join(`
18
+ `));const u=await an(t,r);u==="prototyping"&&o.push(r),u==="staging"&&s.push(r)});return{prototype:o,staged:s}}c(Dd,"settleAnswers");async function an(t,e,{roundAt:n=!1}={}){const{item:a}=await x(t,e),{asked:i}=await ft(t,e);if(i.some(o=>o.state==="open"))return null;if(a.phase==="grilling"&&a.gates?.prototype==="yes"){await bt(t,e,{phase:"prototyping"});const{source:o,itemFile:s,item:r}=await x(t,e);return r.gates={...r.gates,prototype:"ran"},n&&(r.round_at=new Date().toISOString()),await b(o.file,s),await W(t,e,"prototype-round"),"prototyping"}return await Kr(t,e)?(await fa(t,e),"staging"):null}c(an,"moveOnAnswered");async function Hi(t,e,n,a){try{await a()}catch(i){if(!(i instanceof pt))throw i;await W(t,e,"answers-failed",{what:n,error:i.message})}}c(Hi,"followUp");const la=c(t=>typeof t=="string"&&t.startsWith("item:")&&!t.startsWith("item:ask:")?t.slice(5):null,"cardOfTopic"),on=c(t=>String(t).padStart(2,"0"),"pad2"),Yt=c((t=new Date)=>`${on(t.getMonth()+1)}/${on(t.getDate())} ${on(t.getHours())}:${on(t.getMinutes())}`,"noteStamp");function Wr(t,e){const n=e.choice===null||e.choice===void 0||e.choice===""?null:(t.options||[]).find(i=>i.id===e.choice)?.label??String(e.choice),a=String(e.note||"").trim();return`- ${t.id} (${t.question}): ${n?`${n}.`:"no option picked."}${a?` Note, verbatim: "${a}"`:""}`}c(Wr,"answerLine");const Ji=292,da=c(t=>String(t).toLowerCase().replace(/[^a-z0-9-]+/g,"-"),"notesBase"),Ur=c((t,e,n)=>re($.join(t,`.${da(e)}-notes`),n),"notesLock");function sn(t,e){let n=`${da(e)}-notes.md`;for(let a=2;wt($.join(t,n));a++)n=`${da(e)}-notes-${a}.md`;return n}c(sn,"freeNotesName");async function rn(t,e){const n=$.join($.dirname(t),`.${$.basename(t)}.${process.pid}.tmp`);await A.rm(n,{force:!0}),await A.writeFile(n,e,{mode:Ji}),await A.rename(n,t)}c(rn,"writeNotesFile");const Hr=c(t=>/\n/.test(j(t,"--heading"))?d("--heading is one line, the section's title"):j(t,"--heading"),"notesHeading"),Jr=c((t,e,n)=>`${t.replace(/\n*$/,`
19
19
  `)}
20
- ## ${t}
20
+ ## ${e}
21
21
  ${n.replace(/^\n+|\s+$/g,"")}
22
- `,"withSection");async function Re(e,t,n,a){const{source:i,item:{id:o}}=await x(e,t);return gr(i.dir,o,async()=>{const{source:s,itemFile:c,item:l}=await x(e,t);let u;l.plan?(u=await nn(s.dir,l.plan,{missingOk:!0}),de(u)||await W(e,t,"notes-missing")):(l.plan=Zt(s.dir,l.id),u=g.join(s.dir,l.plan),await y(s.file,c));const p=de(u)?await j.readFile(u,"utf8"):`# ${l.title}
23
- `;return await Yt(u,kr(p,$r(n),a)),l.plan})}r(Re,"appendNotes");async function Ai(e){const{tickets:t}=Se(await oe(e)),n=[],a=new Map;for(const i of await q(e)){const o=await $(i.file,null);a.set(i.slug,{source:i,itemFile:o||{}});for(const s of o?.items||[])s.plan&&n.push({key:`${i.slug}/${s.id}`,ref:tt(o,s,t),title:s.title,created:s.created||"",archived:!1,dir:i.dir,plan:s.plan})}for(const i of e?await Le(e):[]){if(!i.item?.plan)continue;const o=a.get(i.file);n.push({key:i.key,ref:tt(o?.itemFile||{},i.item,t),title:i.item.title,created:i.item.created||"",archived:!0,dir:o?.source.dir||g.join(e,"data"),plan:i.item.plan})}return n}r(Ai,"cardsWithNotes");const Pi=r(e=>j.realpath(g.resolve(e.dir,e.plan)).catch(()=>null),"realNotes");async function Di(e,t,n,a){if(t==="-")return Eo(0,"utf8");const i=await j.realpath(t).catch(()=>d(`${n} ${t}: no such file`));for(const o of await Ai(e))await Pi(o)===i&&d(`${n} ${t} is the notes file of ${o.ref} "${o.title}" (${o.key}), and a card's notes are its own; ${a(o)}`);return j.readFile(i,"utf8")}r(Di,"refuseCardNotes");const ta="write a draft of your own outside the board's data folder";async function Yl(e,t,{heading:n,file:a,from:i}){let o;if(i!==void 0){i===t&&d(`${t} can't fold its own notes into itself; pass --from <the other card>`);const[l,u]=await Promise.all([x(e,t),x(e,i)]),[p,w]=await Promise.all([l,u].map(({source:f,item:h})=>h.plan?j.realpath(g.resolve(f.dir,h.plan)).catch(()=>null):null));p&&p===w&&d(`${i} and ${t} name one notes file, ${l.item.plan}, from before the board named each card's own; the board splits it as it starts`),o=(await Ir(e,i)).markdown,n??=`Folded from ${await H(e,i)} "${u.item.title}"`}else o=await Di(e,a,"--file",l=>l.key===t?`${ta}, holding only the new section`:`${ta}, or fold that card's notes in with item notes ${t} --from ${l.key}`);o.trim()||d(`${i??a} is empty`);const s=await Re(e,t,n,o),c=await en(e,t,"Recorded in the card's notes");return{file:s,heading:n,lines:c}}r(Yl,"addNotes");const Xl=r(e=>ce(e,async()=>{const t=await Ai(e),n=new Map;for(const i of t){const o=await Pi(i);o&&n.set(o,[...n.get(o)||[],i])}const a=[];for(const[i,o]of n){const[s,...c]=o.sort((l,u)=>l.created<u.created?-1:l.created>u.created?1:l.key<u.key?-1:1);for(const l of c.filter(u=>!u.archived)){const{source:u,itemFile:p,item:w}=await Ue(e,F(l.key).file).then(h=>({...h,item:h.itemFile.items.find(m=>m.id===F(l.key).id)})),f=w.plan;w.plan=Zt(u.dir,w.id),await Yt(g.join(u.dir,w.plan),await j.readFile(i,"utf8")),await y(u.file,p),await W(e,l.key,"notes-shared",{card:s.ref}),a.push(`${l.key}: its own notes, ${w.plan}, copied from ${g.normalize(f)}, which ${s.key} keeps`)}await j.chmod(i,Oi)}return a}),"splitSharedNotes");async function br(e,t){const{source:n,item:a}=await x(e,t);return we(a)||be(a)||a.pushed||(await Promise.all((await G(n.dir,a.id)).map(o=>$(o,null)))).some(o=>o?.started&&!o.done&&o.kind!==me)||(await fe(e,t)).asked.some(o=>o.state==="open")||(await $(ye(e),{}))[t]?!1:!await ia(e,t)}r(br,"stageable");async function na(e,t){const{source:n,itemFile:a,item:i}=await x(e,t);i.phase!=="staging"&&(Object.assign(i,{phase:"staging",staged_at:new Date().toISOString()}),delete i.unfiled,delete i.filed_held,await y(n.file,a),await Je(e,t,{command:"staged"}))}r(na,"stage");const Fi=r(({text:e,files:t})=>[String(e||"").trim(),...(Array.isArray(t)?t:[]).map(n=>`Attached: ${n?.path||n?.name||n}`)].filter(Boolean).join(`
24
- `),"messageWords");async function yr(e,t,n){const{item:a}=await x(e,t);a.held&&await Vi(e,"card-hold",{key:t,hold:!1});const{owner:i,asked:o}=await fe(e,t),s=o.filter(l=>l.state==="open").map(l=>l.id);s.length&&await Xt(e,i,s,"Skipped: you tapped Implement");const c=Fi(n);c&&await Re(e,t,`Implement (owner, ${Qe()}), verbatim`,c),await na(e,t)}r(yr,"stageImplement");async function ed(e,t,n){const a=Fi(n);a&&await Re(e,t,`Reply (owner, ${Qe()}), verbatim`,a),await na(e,t)}r(ed,"stageReply");async function td(e,t,n){const{source:a,itemFile:i,item:o}=await x(e,t);!["ready","staging"].includes(o.phase)||we(o)||(o.phase=n==="prototype"?"prototyping":"grilling",delete o.staged_at,await y(a.file,i))}r(td,"planAgain");async function xr(e,t){const n=await x(e,t).catch(()=>null);!n||!["ready","staging"].includes(n.item.phase)||we(n.item)||(n.item.phase="grilling",delete n.item.staged_at,await y(n.source.file,n.itemFile),await W(e,t,"new-question"))}r(xr,"grillAgain");function Ni(e){return e.filter(t=>t.state==="answered").map(t=>t.id)}r(Ni,"answeredOnClaude");function ve(e,t,n,a=new Date().toISOString()){for(const i of e.items||[])t.includes(i.id)&&Object.assign(i,{resolved:n,resolved_at:a})}r(ve,"setResolved");async function Xt(e,t,n,a){return ve(t,n,a),await y(E(e),t),E(e)}r(Xt,"markResolved");async function nd(e,t,n){D(e);const a=await $(E(e),{topics:[],items:[]}),i=(a.items||[]).find(f=>f.id===t);i||d(`no question "${t}" in owner.json`);const{answers:o,requests:s,reopens:c}=await ft(e),l=Te(i,o,s,[],c);if(l.state==="resolved")return E(e);l.state==="requested"&&d(`${t} waits on the prototype the owner asked for; question add with round_of ${t} resolves it`);const u=S(n,"--note");Ne(i.url)&&_r(a,i,o);const p=await Xt(e,a,[t],u);await Bi(e,i.topic);const w=Xn(i.topic);return w&&(await x(e,w).catch(()=>null))?.item.phase==="grilling"&&await vi(e,w,{roundAt:!0}),p}r(nd,"resolveQuestion");async function ad(e,t,n,a=[]){D(e);const[i,...o]=[...new Set(t)];i||d("question move takes the ids of the questions to merge"),await x(e,n);const s=[n,...a];new Set(s).size!==s.length&&d("question move names a card twice");for(const f of a)await x(e,f);const c=await $(E(e),{topics:[],items:[]}),{answers:l,requests:u,reopens:p}=await ft(e);for(const f of[i,...o]){const h=(c.items||[]).find(k=>k.id===f)||d(`no question "${f}" in owner.json`),{state:m}=Te(h,l,u,[],p);m!=="open"&&d(`${f} is ${m}; question move takes open questions`)}for(const[f,h]of a.entries()){const{item:m}=await x(e,h),k=[...m.deps||[],s[f]].join(",");await $e(e,h,{deps:k,relate:n})}const w=await H(e,n);return Object.assign(c.items.find(f=>f.id===i),{topic:`item:${n}`}),ve(c,o,`Duplicate of ${w}'s question ${i}`),await y(E(e),c),E(e)}r(ad,"moveQuestions");async function id(e,t){const n=t.filter(({choice:i,note:o})=>!i&&String(o||"").trim()).map(i=>i.id),a=n.length?await $(E(e),{topics:[],items:[]}):null;a?.items?.some(i=>n.includes(i.id))&&(ve(a,n,"Answered with a note"),await y(E(e),a))}r(id,"resolveNoteAnswers");function _r(e,t,n){const a=jn(t),i=e.items.filter(o=>o.topic===t.topic&&jn(o)===a).map(o=>Te(o,n));Ko(i,a)||d(`${t.id} is in prototype round ${a}, which no pick has settled yet; a pick settles it`)}r(_r,"roundSettled");async function ft(e){const t=await z(g.join(e,"data","events.jsonl"));return{answers:await Promise.all(t.filter(a=>a.kind==="owner-answer").map(async a=>({...a,reply:a.reply||(await Ln(g.join(e,"data","replies"),a.id)).length>0}))),requests:t.filter(a=>a.kind==="prototype-request"),reopens:t.filter(a=>a.kind===Ho)}}r(ft,"ownerEvents");async function od(e,t){const{asked:n}=await Sr(e),a=new Map(n.map(i=>[i.id,i.state]));return t.filter(i=>!a.has(String(i.id))||["open","requested"].includes(a.get(String(i.id))))}r(od,"unrecorded");async function Sr(e){const t=await $(E(e),{topics:[],items:[]}),{answers:n,requests:a,reopens:i}=await ft(e);return{owner:t,asked:(t.items||[]).map(o=>Te(o,n,a,[],i))}}r(Sr,"topicQuestionsAll");async function Ri(e,t){const n=await $(E(e),{topics:[],items:[]}),{answers:a,requests:i,reopens:o}=await ft(e),s=(n.items||[]).filter(c=>c.topic===t).map(c=>Te(c,a,i,[],o));return{owner:n,asked:s}}r(Ri,"topicQuestions");const fe=r((e,t)=>Ri(e,`item:${t}`),"cardQuestions"),en=r((e,t,n)=>Ei(e,`item:${t}`,n),"resolveAnswered");async function Ei(e,t,n){if(!e)return[];const{owner:a,asked:i}=await Ri(e,t),o=Ni(i);return o.length&&await Xt(e,a,o,n),await Bi(e,t),o.map(s=>`resolved: ${s}`)}r(Ei,"resolveAnsweredOn");const aa=r(async(e,t)=>!!e&&(await fe(e,t)).asked.some(n=>n.state==="open"),"hasOpenQuestion");function Li(e,t,n){e.next=S(t,"--next"),e.next_at=new Date().toISOString(),n?e.next_on_questions=!0:delete e.next_on_questions}r(Li,"setNext");async function Bi(e,t){const n=t.startsWith("item:")&&!t.startsWith("item:ask:")?t.slice(5):null;if(!n)return;let a;try{a=await x(e,n)}catch(c){if(c instanceof ue)return;throw c}const{source:i,itemFile:o,item:s}=a;s.next_on_questions&&((await fe(e,n)).asked.some(c=>c.state!=="resolved")||(delete s.next,delete s.next_at,delete s.next_on_questions,await y(i.file,o)))}r(Bi,"clearWaitedNext");async function vr(e,t){const{source:n,itemFile:a,item:i}=await x(e,t);i.next===void 0&&i.next_on_questions===void 0||(delete i.next,delete i.next_at,delete i.next_on_questions,await y(n.file,a))}r(vr,"clearNext");async function Ci(e,t,n,a){if(!e)return async()=>[];const{owner:i,asked:o}=await fe(e,t),s=o.filter(l=>l.state==="open").map(l=>l.id);s.length&&!a&&d(`${n}: ${t} has ${s.length===1?"an open question":"open questions"} ${s.join(", ")} with no answer yet; pass --force to close the card and resolve ${s.length===1?"it":"them"} too`);const c=o.filter(l=>l.state!=="resolved").map(l=>l.id);return async()=>(c.length&&await Xt(e,i,c,"Closed with the card"),c.map(l=>`resolved: ${l}`))}r(Ci,"closeQuestions");async function sd(e,t,n,a,i){await x(e,t),zt(n),ee(a,o=>S(o,"--owner-step")),ee(i,o=>Zi(o)),await Ci(D(e),t,"land",!1)}r(sd,"checkClose");async function ia(e,t){const n=await $(E(e),{items:[]}),{answers:a,requests:i,reopens:o}=await ft(e);return Uo((n.items||[]).map(s=>Te(s,a,i,[],o)),t)}r(ia,"unpickedPrototype");const jr=r(e=>e.length>120?`${e.slice(0,119)}\u2026`:e,"clip"),Or={ask:"text","ask-edited":"text","item-message":"text","owner-answer":"note"};async function Ii(e,t,n){const a=S(t,n).replace(/\s+/g," ");return(await z(g.join(e,"data","events.jsonl"))).map(o=>String(o.data?.[Or[o.kind]]??"").replace(/\s+/g," ").toLowerCase()).some(o=>o.includes(a.toLowerCase()))||d(`${n} must quote the owner's words in an ask, card message or answer note on this board`),a}r(Ii,"ownerQuote");async function rd(e,t,n){return D(e),n===void 0&&d(`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 Ii(e,n,"--asked")}"`}r(rd,"askedGate");async function Dt(e,t,n="--from-ask"){return Fe(t,n),(await z(g.join(D(e),"data","events.jsonl"))).some(i=>i.id===t&&i.kind==="ask")?t:d(`no ask "${t}" in this site's data/events.jsonl`)}r(Dt,"checkAsk");function Ft(e,t,n=new Date().toISOString(),a=Ti(e,t)){if(!Ce[t])throw new Error(`no lane "${t}"`);const i=e.lane;return qi(e,t,a),e.lane=t,e.lane_at=n,t==="done"?(e.closed_at=n,delete e.reopened_at):i==="done"&&(e.reopened_at=n),i}r(Ft,"placeIn");function Ti(e,t,n=!1){return t==="todo"?we(e)?"ready":e.phase??null:t==="progress"?"reading":t==="done"?n||De(e).some(a=>a.merged_at)?"merged":"closed":null}r(Ti,"movedPhase");function qi(e,t,n){if(n!==null&&!_n[t].includes(n))throw new Error(`no ${Ce[t]} phase "${n}"`);n===null?delete e.phase:e.phase=n}r(qi,"setPhase");async function cd(e,t,n,a,i,o){const{source:s}=await x(e,t),{id:c}=F(t),l=new Date().toISOString();if(!await nt(s.file,async()=>{const w=JSON.parse(await j.readFile(s.file,"utf8")),f=w.items.find(m=>m.id===c)||d(`item file "${s.slug}" has no item "${c}"`);if(o&&((f.lane??null)!==o.lane||(f.phase??null)!==o.phase)||f.lane===n&&(i===void 0||(f.phase??null)===i))return!1;let h;return f.lane===n?qi(f,n,i):h=Ft(f,n,l,i),await We(s.file,JSON.stringify(w,null,2)+`
25
- `),h!==void 0}))return null;const p={ts:l,who:"claude",kind:Pa,text:`Moved to ${Ce[n]}: ${S(a,"why")}`};return await le(Z(e,t),p),p.text}r(cd,"moveCard");const K=r(e=>e?.lane==="done"||!!e?.reopened_at,"closed"),we=r(e=>!!e?.lane&&e.lane!=="todo","leftTodo"),ld=r(async(e,t)=>K((await x(e,t)).item),"isFinished"),Mi=["ready","grilling","prototyping"];function Wi(e,t){t!==void 0&&d(`--state is now --phase: pass --phase ${Mi.includes(t)?t:"ready, grilling or prototyping"}`),e==="staging"&&d("--phase staging is set by the board, on an owner action; pass ready, grilling or prototyping"),e!==void 0&&!Mi.includes(e)&&d("--phase takes ready, grilling or prototyping")}r(Wi,"checkPhase");const Ar="a card goes ready only from staging, which the board sets on the owner's Send, Implement or Reply";async function Ui(e,t){return(await z(g.join(D(e),"data","events.jsonl"))).some(a=>a.kind==="ask"&&a.id===t&&a.data?.quick===!0||a.kind==="item-message"&&a.data?.key===`ask:${t}`&&a.data?.intent==="build")}r(Ui,"quickAsk");const Pr=/^mark (?:it |this |the card )?ready\b/i;function Dr(e,t,n){const a=[].concat(t).map(s=>Fn(s)||d(`--pr takes a PR number or owner/repo#<n>, not "${s}"`)),i=r((s,c)=>s.number===c.number&&(s.repo||n||null)===(c.repo||n||null),"same"),o=De(e);for(const s of a)o.some(c=>i(c,s))||o.push(s);delete e.pr,e.prs=o}r(Dr,"addPRs");const J=r((e,t)=>String(t).includes("/")?String(t):`${e}/${t}`,"depKey"),Ge=/^wave:(.+)$/;async function wt(e,t,n){const a=await Promise.all((n||[]).map(async i=>{const o=String(i).match(Ge)?.[1];if(!o)return[J(t,i)];const{source:s,wave:c}=await pt(e,o);return Ie(c).map(l=>`${s.slug}/${l}`)}));return[...new Set(a.flat())]}r(wt,"depCards");async function Ee(e,t,n){const a=await wt(e,t,n.deps),i=await Promise.all(a.map(o=>x(e,o).then(({item:s})=>s,()=>null)));return a.filter((o,s)=>i[s]&&!K(i[s]))}r(Ee,"unfinishedDeps");async function Fr(e,t,n){const a=await Promise.all((await Ee(e,F(t).file,n)).map(i=>H(e,i)));return n.blocked_until?[...a,n.blocked_until]:a}r(Fr,"blockerNames");async function tn(e,t,n){n??=(await x(e,t)).item;const a=await Promise.all((await Ee(e,F(t).file,n)).map(i=>H(e,i)));return[a.length&&`by ${a.join(", ")}`,n.blocked_until&&`until ${n.blocked_until}`].filter(Boolean).join(" and ")}r(tn,"blockWords");const Nr=r((e,t)=>!be(e)&&!e.pushed&&!e.merge_ready&&!K(e)&&(!!Sn(t)||t.some(n=>n?.started&&!n.done&&et(n))),"inProgress");async function Rr(e,t){const n=[];for(const a of await q(e)){const i=await $(a.file,null);for(const o of Array.isArray(i?.items)?i.items:[])K(o)||o.blocked_until||!(await wt(e,a.slug,o.deps)).includes(t)||(await Ee(e,a.slug,o)).length||n.push(`${a.slug}/${o.id}`)}return n}r(Rr,"unblockedBy");async function Er(e,t,n){const a=F(t).file,i=(await sa(e,a,n)).map(c=>Ge.test(c)?c:J(a,c));i.length||d("--split-into takes wave:<slug> or the cards the split filed, <id>,<file>/<id>"),(await wt(e,a,i)).includes(t)&&d(`${t} can't be split into itself`);const o=await Promise.all(i.map(async c=>{const l=c.match(Ge)?.[1];if(!l)return H(e,c);const{source:u,wave:p}=await pt(e,l),w=await Promise.all(Ie(p).map(f=>H(e,`${u.slug}/${f}`)));return`the wave ${p.title} (${w.join(", ")})`})),s=[];for(const c of await q(e))for(const l of(await $(c.file,null))?.items||[]){const u=`${c.slug}/${l.id}`;if(!(K(l)||!(l.deps||[]).some(p=>J(c.slug,p)===t))){for(const p of i)(await wt(e,a,[p])).includes(u)&&d(Ge.test(p)?`${u} waits on ${t} and is in the wave "${p.match(Ge)[1]}", so it would wait on itself; split into the new cards by key`:`${u} waits on ${t} and is one of the cards it splits into, so it would wait on itself`);s.push(u)}}return{entries:i,words:o.join(", "),waiters:s}}r(Er,"splitPlan");async function Lr(e,t,{entries:n,words:a,waiters:i}){for(const s of await q(e)){const c=i.filter(u=>F(u).file===s.slug);if(!c.length)continue;const l=await $(s.file,null);for(const u of l.items.filter(p=>c.includes(`${s.slug}/${p.id}`))){const p=n.map(w=>!Ge.test(w)&&F(w).file===s.slug?F(w).id:w);u.deps=[...new Set([...u.deps.filter(w=>J(s.slug,w)!==t),...p])]}await y(s.file,l)}const o=await H(e,t);for(const s of i)await W(e,s,"split-moved",{card:o,to:a})}r(Lr,"moveWaiters");async function oa(e,t,n){const{source:a,itemFile:i,item:o}=await x(e,t);if(we(o))o.unblocked_at=n;else if(o.phase==="ready")o.recheck_at=n;else return;await y(a.file,i)}r(oa,"markUnblocked");async function Hi(e,t,n,a){const i=new Set(a.match(/#?[\w-]+(?:\.[\w-]+)*(?:\/[\w-]+(?:\.[\w-]+)*)*/g)||[]),o=new Set(await wt(e,F(t).file,n.deps));for(const s of await q(e)){const c=await $(s.file,null);for(const l of c?.items||[]){const u=`${s.slug}/${l.id}`;if(u===t||o.has(u)||K(l))continue;[l.id,tt(c,l),l.ticket].filter(Boolean).flatMap(w=>[w,`${s.slug}/${w}`]).some(w=>i.has(w))&&d(`--next names unfinished card ${u}; add it with --deps`)}}}r(Hi,"checkNextDeps");const Ji=r(e=>`item notes ${e} --heading "<heading>" --file <draft.md>`,"NOTES_COMMAND");function Br(e,t){t.size||d(`${e} has no size; a builder starts from it, so pass --size small or large with --phase ready`),t.plan||d(`${e} has no notes file; a builder starts from it, so add its notes with ${Ji(e)} before --phase ready`)}r(Br,"checkSizeAndNotes");async function Cr(e,t,n,a){Br(t,a);const i=await j.readFile(await nn(n,a.plan),"utf8"),o=(await fe(e,t)).asked.filter(s=>s.answers.length&&!i.includes(s.id)&&!((s.prototype_gate||s.ticket_gate)&&!s.answers.at(-1).note)).map(s=>s.id);o.length&&d(`${t}'s notes leave out the answered question${o.length===1?"":"s"} ${o.join(", ")}; record each answer in its notes, naming its id, with ${Ji(t)} before it is ready`)}r(Cr,"checkNotesComplete");async function nn(e,t,{missingOk:n=!1}={}){const a=r(s=>d(`a notes file is a .md file inside ${e}, named relative to it: "${t}" ${s}`),"bad");(typeof t!="string"||!t.trim())&&a("is empty"),(g.isAbsolute(t)||t.split(/[\\/]/).includes(".."))&&a("leaves the folder"),g.extname(t).toLowerCase()!==".md"&&a("is not a .md file");const i=await j.realpath(e),o=await j.realpath(g.resolve(e,t)).catch(()=>n?g.resolve(i,t):a("does not exist"));return o.startsWith(i+g.sep)||a("leaves the folder"),o}r(nn,"planPath");async function Ir(e,t){const{source:n,itemFile:a,item:i}=await x(e,t);if(i.plan)return{itemFile:a,item:i,markdown:await j.readFile(await nn(n.dir,i.plan),"utf8")};if(typeof i.notes=="string"&&i.notes.trim())return{itemFile:a,item:i,markdown:i.notes};d(`${t} has no notes`)}r(Ir,"readNotes");function zi({install:e,installSha:t,installLabel:n,clearInstall:a}){if(e===void 0)return(t!==void 0||n!==void 0)&&d("--install-sha and --install-label go with --install <url>"),a?null:void 0;a&&d("pass --install or --clear-install, not both");let i;try{i=new URL(String(e).trim())}catch{i=null}(!i||!["https:","itms-services:"].includes(i.protocol))&&d(`--install takes an https:// or itms-services:// URL, not "${e}"`),i.protocol==="itms-services:"&&!(i.searchParams.get("action")==="download-manifest"&&/^https:\/\//.test(i.searchParams.get("url")||""))&&d("--install: an itms-services:// URL needs ?action=download-manifest&url=https://\u2026/manifest.plist");const o=t===void 0?void 0:/^[0-9a-f]{7,40}$/i.test(t)?t.toLowerCase():d(`--install-sha takes a commit sha of 7 to 40 hex digits, not "${t}"`);return{url:String(e).trim(),...n===void 0?{}:{label:S(n,"--install-label")},built_at:new Date().toISOString(),...o?{sha:o}:{}}}r(zi,"installOf");async function dd(e,{install:t,installSha:n}){const a=zi({install:t,installSha:n});a||d("main set needs --install <url>");const i=g.join(D(e),"data","main.json");return await y(i,{install:a}),{file:i,lines:["main install set"]}}r(dd,"setMainInstall");const Tr=r((e,t)=>e.length?`Merged PR${e.length>1?"s":""} ${at(e,t)}.`:"Merged.","mergedLine");function qr(e,t,n,a,i,o){return o?{status:o}:n&&a===void 0?{status:["merged",{words:Tr(n,i)}]}:(a===void 0&&e&&d(`--done needs --text "<what was done, or why it closes without landing>", which becomes ${t}'s last thread line`),a===void 0?null:{text:a})}r(qr,"closingLine");function Mr(e,t,n){const a=new Date().toISOString(),i=r((o,s)=>o.number===s.number&&(o.repo||n||null)===(s.repo||n||null),"same");e.prs=De(e).map(o=>{const s=t.find(c=>i(o,c));return s&&!o.merged_at?{...o,merged_at:s.at||a}:o}),delete e.pr}r(Mr,"markMerged");async function Ki(e,t,{ticket:n,newTicket:a,status:i,clearStatus:o,done:s,splitInto:c,merged:l,landed:u,start:p,handBack:w,next:f,clearNext:h,pr:m,pushed:k,mergeReady:_,ghSince:N,fromAsk:v,phase:O,state:A,held:I,unheld:B,pickUpAt:P,deps:L,blockedUntil:T,blockReason:M,parent:C,related:Y,relate:te,unrelate:V,install:Q,installSha:Ze,installLabel:un,clearInstall:ke,title:je,size:Bt,model:mt,force:ht,text:ie,closing:ne,who:fn,by:pe,command:$a,ownerStep:Ye,ownerDone:jo,check:gt},ka){(i!==void 0||o)&&d(`--status${o?" and --clear-status are":" is"} gone: a card's lane is stored and moves itself. Close it with --done --text "<what was done, or why it closes without landing>"`),l&&(s=!0),Y!==void 0&&(te!==void 0||V!==void 0)&&d("pass --related, or --relate and --unrelate, not both"),Wi(O,A),ht&&!s&&d("--force goes with --done"),c!==void 0&&!s&&d("--split-into goes with --done"),c!==void 0&&ie!==void 0&&d("--split-into writes the closing line; drop --text");const $t=c===void 0?null:await Er(e,t,c);$t&&(ie=`Split into ${$t.words}`),v!==void 0&&s&&d("--from-ask opens a card; close it in another call"),ie!==void 0&&zt(ie),Ye!==void 0&&S(Ye,"--owner-step");const kt=gt===void 0||gt===""?gt:Zi(gt);ie!==void 0&&v===void 0&&!s&&O!=="ready"&&d("--text goes with --from-ask, --done, or --phase ready on a staging card"),v!==void 0&&ie===void 0&&d(`--from-ask needs --text "<first line>", the item's first thread line after the ask`),f!==void 0&&h&&d("pass --next or --clear-next, not both"),typeof f=="string"&&!f.trim()&&([f,h]=[void 0,!0]);const bt=Gi({held:I,unheld:B,pickUpAt:P}),Ct=zi({install:Q,installSha:Ze,installLabel:un,clearInstall:ke});[s,p,w,f,h,m,k,_,N,v,O,bt,L,T,M,C,Y,te,V,Ct,je,Bt,mt,n,a,Ye,gt].every(R=>R===void 0||R===!1)&&d("nothing to set: pass --done, --next, --clear-next, --pr, --pushed, --gh-since, --from-ask, --phase, --held, --unheld, --pick-up-at, --deps, --blocked-until, --block-reason, --parent, --related, --relate, --unrelate, --install, --clear-install, --title, --size, --model, --ticket, --new-ticket or --check");const X=v===void 0?void 0:await Dt(e,v);X&&await Wn(e,X),X&&await oi(e,X,t);const{source:Be,itemFile:Xe,item:b}=await x(e,t),ba=X??(b.phase?void 0:b.from_ask),Oo=ba!==void 0&&await Ui(e,ba);O!==void 0&&b.answered_at&&!b.closed_at&&(delete b.answered_at,we(b)&&Ft(b,"todo",void 0,null)),O!==void 0&&we(b)&&d(`--phase sets a Todo card's phase; ${t} is ${Ce[b.lane]}, where the board sets it`),O==="ready"&&!Oo&&!["staging","ready"].includes(b.phase)&&d(`${t} reads ${b.phase||"new"}, not staging; ${Ar}`),X&&b.from_ask&&b.from_ask!==X&&d(`${t} came from ask "${b.from_ask}", so ask "${X}" can't be its from-ask; to fold it in: item relate-ask ${X} ${t} --summary "<line>"`),X&&bt&&O!==void 0&&!b.phase&&d("a card filed held is filed New and takes no --phase; drop --phase, or drop --held to file it in a phase"),X&&O===void 0&&!b.phase&&!bt&&d("--from-ask files a card, which reads New until it has a phase: pass --phase grilling, prototyping, or ready for a Quick build ask, or --held to file it for later");const wn=K(b);$t&&wn&&d(`${t} is already Done, so the cards waiting on it were unblocked then; move them with item set <key> --deps`),Ye!==void 0&&wn&&d(`${t} is already Done, so its ticket closed; an owner step goes on the command that finishes the card: land --owner-step, or builder done before the merge`),Ye!==void 0&&(b.owner_step=S(Ye,"--owner-step")),jo&&delete b.owner_step,kt!==void 0&&!b.owner_step&&d(`--check goes with an owner step, which ${t} doesn't have: pass --owner-step "<the step>" with it on builder done or land`),kt&&(b.owner_check={check:kt,since:b.owner_check?.check===kt?b.owner_check.since:new Date().toISOString()}),(kt===""||!b.owner_step)&&delete b.owner_check;const pn=await Promise.all((await G(Be.dir,b.id)).map(R=>$(R,null))),Ao=vn(b,pn);if(je!==void 0&&(b.title=S(je,"--title")),Qi(b,{size:Bt,model:mt}),L!==void 0){const R=await sa(e,F(t).file,L,t);R.length?b.deps=R:delete b.deps}const ya=T===""?b.blocked_until:void 0;if(T!==void 0&&(T===""?delete b.blocked_until:b.blocked_until=S(T,"--blocked-until")),M&&(!b.deps?.length&&!b.blocked_until&&d("--block-reason goes with a block: --deps or --blocked-until"),b.block_reason=S(M,"--block-reason")),(M===""||!b.deps?.length&&!b.blocked_until)&&delete b.block_reason,C!==void 0){const R=await Yi(e,F(t).file,t,C);R?b.parent=R:delete b.parent}const xa=C!==void 0||Y!==void 0||te!==void 0||V!==void 0?await ra(e,t):null;let mn=Y===void 0?null:await Hr(e,t,b,Y);te!==void 0&&(b.related=[...new Set([...(b.related||[]).map(R=>J(F(t).file,R)),...await on(e,t,te,"--relate")])]),V!==void 0&&(mn=await Jr(e,t,b,await on(e,t,V,"--unrelate"))),bt!==void 0&&an(b,bt),p&&b.held&&d(b.pick_up_at?`${t} is held until ${b.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`);const yt=m!==void 0||k!==void 0||_!==void 0;if((p||s||w||yt)&&(Ur(b),delete b.recheck_at),p){const R=await Ee(e,F(t).file,b);R.length&&d(`${t} is blocked by ${R.join(", ")}; start it once ${R.length===1?"that is":"those are"} done`),b.blocked_until&&d(`${t} is blocked until ${b.blocked_until}; start it once that holds and the block is cleared with --blocked-until ""`)}const It=p&&e?await ia(e,t):null;It&&d(`${t} has no take picked: the owner's answer to ${It.id} picks none${It.note?` ("${jr(It.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 Po=s?await Ci(e,t,"--done",ht):async()=>[],xt=s?qr(e,t,l,ie,se(e,Xe),ne):null;if(l&&Mr(b,l,se(e,Xe)),f!==void 0&&(Li(b,f,await aa(e,t)),await Hi(e,t,b,b.next)),h&&(delete b.next,delete b.next_at,delete b.next_on_questions),p&&f===void 0&&b.next_on_questions&&(delete b.next,delete b.next_at,delete b.next_on_questions),yt&&!b.review_since&&(b.review_since=new Date().toISOString()),m!==void 0&&Dr(b,m,se(e,Xe)),k!==void 0){ge().find(R=>Pe(R.dir,D(e)))?.remote||d("--pushed is for a board whose repo is a plain git remote; on GitHub, open a PR and pass --pr"),be(b)&&d(`${t} has a PR; its PR says when it merges`);try{ws(k)}catch{d("--pushed takes the name of the branch you pushed")}b.pushed={branch:k,at:new Date().toISOString()},b.branch=k}if(_!==void 0&&(b.merge_ready={branch:_,at:new Date().toISOString()},b.branch=_),s&&delete b.merge_ready,N!==void 0&&((typeof N!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(N)||Number.isNaN(Date.parse(N)))&&d("--gh-since takes an ISO-8601 UTC time such as 2026-10-23T11:00:00Z"),b.gh_since=N),X&&(b.from_ask=X),O==="ready"&&e){const R=(await fe(e,t)).asked.filter(Ae=>Ae.state==="open").map(Ae=>Ae.id);R.length&&d(`${t} has ${R.length===1?"an open question":"open questions"} ${R.join(", ")}; it is ready once the owner has answered ${R.length===1?"it":"them"}`),await Cr(e,t,Be.dir,b)}const hn=O==="ready"&&b.phase==="staging"&&v===void 0;hn&&ie===void 0&&d(`${t} goes ready from staging on your judgment: pass --text "<what you checked it against on the board>", which goes into its notes`);const gn=O==="ready"&&b.phase==="ready"&&!!b.recheck_at&&v===void 0;gn&&ie===void 0&&d(`${t}'s block ended, so it builds once you re-check its notes against what landed: pass --text "<what you re-checked>", which goes into its notes`),O==="ready"&&!hn&&!gn&&ie!==void 0&&v===void 0&&!s&&d(`${t} reads ${b.phase||"no phase"}, not staging, so there is no judgment for --text to record`);const Do=O==="ready"&&b.phase!=="ready";O!==void 0&&(O!=="ready"&&["staging","ready"].includes(b.phase)&&(b.round_at=new Date().toISOString()),b.phase=O,delete b.recheck_at,delete b.staged_at,delete b.unfiled,delete b.filed_held),b.phase==="ready"&&Pr.test(b.next??"")&&d(`${t} would read ready with Next "${b.next}", which asks for the phase it is already in; pass --next with what happens next, or --clear-next`),Ct&&(b.install=Ct),Ct===null&&delete b.install,!Ao&&!p&&vn(b,pn)&&d(`that leaves ${t} In Progress with nothing building and no Next; pass --next "<what happens next>"`);const $n=(L!==void 0||T)&&!s&&Nr(b,pn)?await tn(e,t,b):"",_a=se(e,Xe);let kn=null;const bn=r((R,Ae)=>{b.lane!==R&&Ft(b,R,void 0,Ti(b,R,u))!==void 0&&Ae&&(kn=`Moved to ${Ce[R]}: ${Ae}`)},"moveTo");if(s?bn("done",null):yt&&b.lane!=="done"?bn("review",m!==void 0?`PR ${at([].concat(m).map(Fn),_a)} opened`:k!==void 0?`${k} pushed for its merge`:"verified, it waits for your Merge"):p&&!K(b)&&bn("progress","a build started"),a&&b.ticket&&d(`${t} already has ticket ${b.ticket}`),(n!==void 0||a)&&await to(e,Xe,b,n,ka,Be.dir),await y(Be.file,Xe),kn&&await le(Z(e,t),{ts:b.lane_at,who:"claude",kind:Pa,text:kn}),hn&&await Re(e,t,`Ready (orchestrator, ${Qe()})`,ie),gn&&await Re(e,t,`Re-checked (orchestrator, ${Qe()})`,ie),Do&&await Je(e,t,{command:"readied"}),$n){const R=e&&!await _o(e,t)&&await xo(e,t,{cause:"blocked",words:`blocked ${$n}`});await W(e,t,R?"blocked-pausing":"blocked-stays",{blocked:$n})}mn&&await mn(),xa&&await eo(e,t,xa,await ra(e,t));const Oe=await Po();if(O==="ready"&&e&&Oe.push(...await en(e,t,"Recorded in the card's notes")),p&&Oe.push(...await en(e,t,"Acted on: build started")),X&&Oe.push(...(await rt(e,t,{text:ie})).lines),xt&&e){const R=$a?await Je(e,t,{command:$a,text:xt.text,who:fn,by:pe}):xt.status?await W(e,t,...xt.status):await rt(e,t,{text:xt.text});Oe.push(...R.lines)}const Sa=b.owner_step&&s?null:rs({start:p,done:s,handover:yt}),va=Sa&&await cs(await sn(e),b,Sa,{...ka,repo:_a});va&&Oe.push(va),(yt||s||w)&&(await vo(Be.dir,b.id,s,w?{handedBack:new Date().toISOString()}:{endHandBack:!0}),await ut(e,t));const yn=X?await _e(e):{};if(ae(yn,X)!==void 0&&(delete yn[X],await y(xe(e),{links:yn})),ya&&!K(b)&&!(await Ee(e,F(t).file,b)).length){const{line:R}=await W(e,t,"unblocked",{lifted:ya});await oa(e,t,R.ts),await he({dir:e},"card-unblocked",{key:t}),Oe.unshift(`unblocked: ${t}`)}if(!s||wn)return{file:Be.file,lines:Oe};$t&&await Lr(e,t,$t);const ja=await Rr(e,t),Fo=await H(e,t);for(const R of ja){const{line:Ae}=await W(e,R,"unblocked-done",{card:Fo});await oa(e,R,Ae.ts),await he({dir:e},"card-unblocked",{key:R})}return{file:Be.file,lines:[...ja.map(R=>`unblocked: ${R}`),...Oe]}}r(Ki,"changeItem");function Qi(e,{size:t,model:n}){for(const[a,i,o]of[["size",t,["small","large"]],["model",n,["opus","sonnet"]]])i!==void 0&&(i===""?delete e[a]:e[a]=o.includes(i)?i:d(`--${a} takes ${o.join(" or ")}, or "" to clear it`))}r(Qi,"setBuildChoice");function Gi({held:e,unheld:t,pickUpAt:n}){return[e,t,n!==void 0].filter(Boolean).length>1&&d("pass one of --held, --unheld and --pick-up-at"),n!==void 0?n===""?null:{until:Wr(n)}:e?{until:null}:t?null:void 0}r(Gi,"holdOf");function Wr(e){const t=typeof e=="string"&&os.test(e)?Date.parse(e):NaN;return Number.isNaN(t)&&d('--pick-up-at takes an ISO time such as 2026-11-04T09:00, the host\u2019s local time unless it names an offset, or "" to resume the card'),t<=Date.now()&&d(`--pick-up-at ${e} has passed; pass a later time, or --unheld to resume the card now`),new Date(t).toISOString()}r(Wr,"pickUpTime");function Ur(e){delete e.held,delete e.pick_up_at}r(Ur,"clearHold");function an(e,t){t?e.held=!0:delete e.held,t?.until?e.pick_up_at=t.until:delete e.pick_up_at,e.held_at=new Date().toISOString()}r(an,"setHold");async function ud(e,t,n,{announce:a=!0}={}){const{source:i,itemFile:o,item:s}=await x(e,t);if(a){const c=new Date(n).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});await W(e,t,"hold-ended",{at:c}),!s.blocked_until&&!(await Ee(e,F(t).file,s)).length&&await he({dir:e},"card-unblocked",{key:t,until:n})}an(s,null),await y(i.file,o)}r(ud,"pickUp");async function Vi(e,t,n){const a=String(n?.key||""),{file:i,id:o}=F(a),{source:s,itemFile:c}=await Ue(e,i),l=n.shared_by?n.shared_by.name||n.shared_by.login:void 0,u={text:qt.done,who:"love",by:l,command:"done"},p=c.items.find(m=>m.id===o)||d(`item file "${i}" has no item "${o}"`);if(!(t==="card-done"&&!!p.owner_step)&&p.lane==="done")return null;if(t==="card-done")return $e(e,a,{done:!0,force:!0,ownerDone:!0,...u});const f=n.hold?typeof n.until=="string"?new Date(n.until).toISOString():null:void 0;an(p,n.hold?{until:f}:null),await y(s.file,c),n.hold&&(await _o(e,a)||await xo(e,a,{cause:"held",words:"held"}),await vo(s.dir,o,!1,{held:!0}),await ut(e,a));const h=f&&new Date(f).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});return Je(e,a,n.hold?{text:h?`${qt.hold} until ${h}`:qt.hold,who:"love",by:l,command:"hold"}:{who:"love",by:l,command:"resume"})}r(Vi,"recordOwnerTap");function Zi(e){try{return Ps(As(e))}catch(t){return d(t.message)}}r(Zi,"checkSpec");async function fd(e,t,n,a){const{item:i}=await x(e,t);return!i.owner_step||i.owner_check?.check!==n?null:$e(e,t,{done:!0,force:!0,ownerDone:!0,closing:["check-passed",{found:a}]})}r(fd,"passOwnerCheck");async function wd(e,t,n,a){const{source:i,itemFile:o,item:s}=await x(e,t);return!s.owner_step||s.owner_check?.check!==n?!1:(s.owner_check.broken=a,await y(i.file,o),await W(e,t,"check-broken",{error:a}),await he({dir:e},"owner-check-broken",{key:t,check:n,error:a}),!0)}r(wd,"breakOwnerCheck");async function sa(e,t,n,a){const i=[...new Set(String(n).split(",").map(o=>o.trim()).filter(Boolean))];for(const o of i){const s=o.match(Ge)?.[1];if(!s){await x(e,J(t,o));continue}(await wt(e,t,[o])).includes(a)&&d(`${a} is in the wave "${s}", so it would wait on itself`)}return i}r(sa,"depList");async function Yi(e,t,n,a){if(!String(a).trim())return null;const i=J(t,String(a).trim());i===n&&d("--parent: a card can't be its own Parent");for(let o=i;o;){const s=o===i?await x(e,o):await x(e,o).catch(l=>{if(l instanceof ue)return null;throw l});if(!s)break;const{item:c}=s;c.parent&&J(F(o).file,c.parent)===n&&d(`--parent: ${i} is a child of ${n}, so it can't be its Parent`),o=c.parent?J(F(o).file,c.parent):null}return i}r(Yi,"parentKey");async function on(e,t,n,a){const i=t.split("/")[0],o=[...new Set(String(n).split(",").map(s=>s.trim()).filter(Boolean).map(s=>J(i,s)))];o.includes(t)&&d(`${a}: a card can't be related to itself`);for(const s of o)await x(e,s);return o}r(on,"relatedKeys");const Xi=r((e,t,n)=>async()=>{for(const a of await q(e)){const i=await $(a.file,null);let o=!1;for(const s of Array.isArray(i?.items)?i.items:[]){const c=`${a.slug}/${s.id}`;c===t||!n(c)||!(s.related||[]).some(l=>J(a.slug,l)===t)||(s.related=s.related.filter(l=>J(a.slug,l)!==t),s.related.length||delete s.related,o=!0)}o&&await y(a.file,i)}},"dropLinksTo");async function ra(e,t){const n=new Set;let a=null;for(const i of await q(e))for(const o of(await $(i.file,null))?.items||[]){const s=`${i.slug}/${o.id}`,c=(o.related||[]).map(l=>J(i.slug,l));s===t?(c.forEach(l=>n.add(l)),o.parent&&(a=J(i.slug,o.parent))):c.includes(t)&&n.add(s)}return{related:n,parent:a}}r(ra,"linksOf");async function eo(e,t,n,a){const i=r(async(o,s,c=o,l=o)=>{await Je(e,t,{command:c,card:s}),await Je(e,s,{command:l,card:t})},"both");for(const o of a.related)n.related.has(o)||await i("related",o);for(const o of n.related)a.related.has(o)||await i("unrelated",o);a.parent&&a.parent!==n.parent&&await i("followup-of",a.parent,"followup-of","followup")}r(eo,"postLinkLines");async function Hr(e,t,n,a){const i=await on(e,t,a,"--related");return i.length?n.related=i:delete n.related,Xi(e,t,o=>!i.includes(o))}r(Hr,"setRelated");function Jr(e,t,n,a){const i=(n.related||[]).filter(o=>!a.includes(J(F(t).file,o)));return i.length?n.related=i:delete n.related,Xi(e,t,o=>a.includes(o))}r(Jr,"unrelateCards");const se=r((e,t)=>e&&ge().find(n=>Pe(n.dir,e))?.github||t.repo,"boardRepoOf");async function pd(e,t){const{itemFile:n,item:a}=await x(e,t);be(a)||d(`${t} has no PR`);const i=Me(a,se(e,n));i.length||d(`${t} has no repo`);const o=a.gh_since||"1970-01-01T00:00:00Z";try{const s=Se(await oe(e)).github_login||await ks();return await Promise.all(i.map(async({repo:c,number:l})=>({repo:c,...Ta(await Ia({repo:c,pr:l,since:o}),{pr:l,since:o,me:s})})))}catch(s){d(s.message)}}r(pd,"prReport");async function md(e,t,{replyTo:n,body:a}){const i=n===void 0?"pr comment":"pr reply",o=Fn(t)||d(`${i} takes a PR number or owner/repo#<n>`);n!==void 0&&!/^[1-9]\d*$/.test(n)&&d("pr reply takes the id of the review comment it answers");const s=S(a,"--body").trim();(s.startsWith(St.trim())||s.includes(Dn))&&d(`${i} adds the ${St.trim()} prefix and the claude-bridge marker itself; pass only your words`);const c=o.repo||se(D(e),{})||d(`${i} needs a board on GitHub; this board has no repo there`);try{const l=await bs({repo:c,pr:o.number,replyTo:n,words:s,login:Se(await oe(e)).github_login}),u=await ui(e,vt({repo:c,number:o.number}),"comment",`Comment on #${o.number}: ${s}`);return{lines:[`posted on PR ${o.repo?t:`#${t}`}: ${l}`,...u.length?[`queued for ${u.join(", ")}'s Slack thread`]:[]]}}catch(l){d(l.message)}}r(md,"postPR");const sn=r(async e=>gi((await oe(e)).tickets),"boardSource");async function hd(e,t,{afterApproval:n,confirmed:a,tapped:i}={}){D(e);const{itemFile:o,item:s}=await x(e,t);be(s)||d(`${t} has no PR`),K(s)&&d(`${t} is done`);const c=await tn(e,t,s);c&&(i&&await W(e,t,"merge-blocked",{blocked:c}),d(`Not merged: blocked ${c}.`));const l=se(e,o),u=Me(s,l);u.length||d(`${t} has no repo`);const p=new Date().toISOString(),w=r(P=>W(e,t,"gh-limited",{what:"Not merged",words:Io(P)}),"limited");let f;try{f=await Promise.all(u.map(P=>Ia({repo:P.repo,pr:P.number,since:p})))}catch(P){P.limited&&await w(P.limited),d(P.message)}const h=f.map(({view:P})=>P);if(_s(h)){const P=u.map((L,T)=>({...L,at:h[T].mergedAt})).filter((L,T)=>h[T].state==="MERGED");return $e(e,t,{merged:P,closing:["already-merged",{prs:at(P,l),many:P.length>1}]})}const m=u.map((P,L)=>({...P,...f[L]})).filter(({view:P})=>P.state==="OPEN"),k=Rn(o,(await oe(e)).reviewers||[]).length>0,_=[];let N=!1,v=!1;for(const P of m){const{view:L,reviews:T}=P,{failing:M,pending:C}=Ta(P,{pr:P.number,since:p,me:null}),Y=Wo({...L,checks:{state:M.length?"fail":C?"pending":"pass",failing:M,pending:C}},{needsApproval:k}),te=T.filter(Q=>Q.state==="APPROVED").sort((Q,Ze)=>String(Q.submitted_at).localeCompare(String(Ze.submitted_at))).at(-1)?.commit_id;let V=!!(te&&L.headRefOid&&te!==L.headRefOid);V&&n===void 0&&sc(s,te,L.headRefOid)&&(V=!1,v=!0),N||=V,V&&n===void 0&&Y.push('commits after the approval: pass --after-approval "<why they are trivial>" when they are, else ask the approver to look again'),_.push(...u.length>1?Y.map(Q=>`${at([P],l)} ${Q}`):Y)}m.length||_.push(u.length>1?"every PR is closed":"PR is closed"),n!==void 0&&!N&&d("--after-approval: no commit came after the approval; drop it");const O=s.manual_steps?.length?a===void 0?null:await Ii(e,a,"--confirmed"):void 0;if(a!==void 0&&O===void 0&&d(`--confirmed: ${t} has no manual steps; drop it`),O===null&&_.push(`manual steps: merge only on the owner's word, with --confirmed "<their words>"`),_.length){const P=`Not merged: ${_.join("; ")}.`;i&&await W(e,t,"merge-refused",{why:_.join("; ")}),d(P)}const A=[];for(const P of m){const L=await Co(["pr","merge",String(P.number),"--repo",P.repo,"--squash"],{timeout:12e4});L.limited&&await w(L.limited),L.status!==0&&d(`gh pr merge ${at([P],l)} failed: ${L.stderr.trim().split(`
26
- `)[0]||`gh exited ${L.status}`}${A.length?` (merged ${at(A,l)} before it)`:""}`),A.push(P)}const I=[n!==void 0&&`After the approval: ${S(n,"--after-approval")}`,v&&`After the approval: only the board's rebase onto ${s.rebased.at(-1).base}.`,O&&`The owner's word on the manual steps: "${O}"`].filter(Boolean),B=await $e(e,t,{merged:A});return I.length&&await rt(e,t,{text:I.join(" ")}),B}r(hd,"mergeCard");async function gd(e,t){return(await x(e,t)).item.merge_ready||null}r(gd,"heldMerge");async function $d(e,t){const{source:n,itemFile:a,item:i}=await x(e,t);(!i.merge_ready||K(i))&&d(`${t} isn't waiting for its Merge`);const o=await tn(e,t,i);return o&&d(`${t} is blocked ${o}, so its Merge waits until nothing blocks it`),i.merge_ready.tapped=new Date().toISOString(),await y(n.file,a),i.merge_ready}r($d,"tapMerge");async function kd(e,t){const{source:n,item:a}=await x(e,t);return(await Promise.all((await G(n.dir,a.id)).map(o=>$(o,null)))).filter(o=>o?.worktree?.path).sort((o,s)=>String(s.started).localeCompare(String(o.started)))[0]?.model}r(kd,"builderModel");async function to(e,t,n,a,i,o,s){const c=await sn(e)||d(zr);try{s??=a===void 0&&n.plan?await j.readFile(await nn(o,n.plan),"utf8"):n.notes||"";const l=await ss(c,{ticket:a,title:n.title,body:s,repo:se(e,t)},i);n.ticket=l.ticket,l.created?n.ticket_created=!0:delete n.ticket_created}catch(l){if(l instanceof ue)throw l;d(l.message)}}r(to,"assignTicket");const zr="this board has no ticket source, so its cards stay tasks; pick GitHub issues or Linear in Board settings first";async function no(e){const t=[],n=[];for(const a of await q(e)){const i=await $(a.file,{});t.push(...(i.items||[]).map(o=>o.id)),n.push(Number(i.last_task)||0)}return e&&t.push(...(await Le(e)).map(a=>a.item?.id)),`T-${Math.max(0,...n,...t.map(a=>Number(/^T-([1-9]\d*)$/.exec(String(a))?.[1]||0)))+1}`}r(no,"nextTaskId");const ce=r((e,t)=>nt(g.join(e||Ut(),"tickets"),t,{heartbeat:!0}),"ticketWrite"),$e=r((e,t,n,a)=>n.ticket!==void 0||n.newTicket?ce(e,()=>Ki(e,t,n,a)):Ki(e,t,n,a),"setItem"),bd=r((e,t,n,a)=>ce(e,()=>Kr(e,t,n,a)),"addItem");async function Kr(e,t,{title:n,notes:a,notesFrom:i,deps:o,ticket:s,newTicket:c,pickUpAt:l,held:u,parent:p,size:w,model:f,phase:h,state:m,relate:k,fromAsk:_,text:N,intake:v=!1},O){const{file:A,id:I}=t.includes("/")?F(t):{file:t};I!==void 0&&Fe(I,"the item id"),Wi(h,m),N!==void 0&&S(N,"--text"),N!==void 0&&_===void 0&&d("--text goes with --from-ask"),_!==void 0&&N===void 0&&d(`--from-ask needs --text "<first line>", the item's first thread line after the ask`),s!==void 0&&c&&d("pass --ticket <id> to link a ticket or --new-ticket to make one, not both");const B=_===void 0?void 0:await Dt(e,_);B&&await Wn(e,B),B&&await oi(e,B);const P=Gi({held:u,pickUpAt:l});P&&h!==void 0&&d("a card filed held is filed New and takes no --phase; drop --phase, or drop --held to file it in a phase"),B&&h===void 0&&!P&&d("--from-ask files a card, which reads New until it has a phase: pass --phase grilling, prototyping, or ready for a Quick build ask, or --held to file it for later"),h==="ready"&&!(B&&await Ui(e,B))&&d(B?`ask "${B}" is not a Quick build ask, so item add files it grilling or prototyping`:"item add files a card grilling or prototyping; ready is for a Quick build ask, filed with --from-ask"),h==="ready"&&!w&&d("a new ready card has no size; a builder starts from it, so pass --size small or large with --phase ready"),h==="ready"&&!(a??"").trim()&&i===void 0&&d("a new ready card has no notes; a builder starts from them, so pass --notes or --notes-from with --phase ready"),v&&e&&h===void 0&&!P&&d("item add files a card on a board: pass --phase grilling or prototyping, or --held to file it for later");const{source:L,itemFile:T}=await Ue(e,A);I!==void 0&&T.items.some(Q=>Q.id===I)&&d(`item file "${A}" already has an item "${I}"`);const M=new Date().toISOString(),C={id:I,title:S(n,"--title"),created:M,lane:"todo",lane_at:M};p!==void 0&&(C.parent=await Yi(e,A,null,p)||d("--parent takes a card, such as <file>/<id>")),a!==void 0&&i!==void 0&&d("pass --notes or --notes-from, not both");const Y=i!==void 0?await Di(e,i,"--notes-from",()=>`${ta}, and link that card with --relate`):a===void 0?"":S(a,"--notes");i!==void 0&&!Y.trim()&&d(`--notes-from ${i} is empty`);const te=i!==void 0?Y:`# ${C.title}
27
- ${Y&&`
28
- ${Y}
29
- `}`;Qi(C,{size:w,model:f}),o!==void 0&&(C.deps=await sa(e,A,o)),P&&an(C,P),P&&h===void 0&&(C.filed_held=!0),k!==void 0&&(C.related=await on(e,t,k,"--relate")),B&&(C.from_ask=B),h!==void 0&&(C.phase=h),(s!==void 0||c)&&await to(e,T,C,s,O,L.dir,Y),I===void 0&&C.ticket?(C.id=ls(C.ticket),T.items.some(Q=>Q.id===C.id)&&d(`item file "${A}" already has an item "${C.id}"; link ${C.ticket} with item add ${A}/<id> --ticket ${C.ticket}`)):I===void 0&&(C.id=await no(e)),C.plan=Zt(L.dir,C.id),await Yt(g.join(L.dir,C.plan),te);const V=`${A}/${C.id}`;if(T.items.push(C),await y(L.file,T),B){await rt(e,V,{text:N});const Q=await _e(e);ae(Q,B)!==void 0&&(delete Q[B],await y(xe(e),{links:Q}))}return e&&await eo(e,V,{related:new Set,parent:null},await ra(e,V)),{file:L.file,key:V,lines:[]}}r(Kr,"createItem");const yd=r(e=>ce(e,async()=>{const t=[];for(const n of await q(e)){const a=await $(n.file,null);if(!Array.isArray(a?.items)||!Array.isArray(a.followups))continue;const i=a.followups.find(l=>a.items.some(u=>u.id===l.id));i&&d(`${n.slug}: follow-up ${i.id} has the id of a card; rename one, then restart the board`);const o=[];for(const{id:l,title:u,from:p,filed:w,done:f,...h}of a.followups){const m=f?e&&(await z(Z(e,`${n.slug}/${l}`))).map(k=>k.ts).filter(Boolean).sort().pop()||w:null;o.push({id:l,title:u,...w?{created:w}:{},...p?{parent:J(n.slug,p)}:{},...f?{lane:"done",...m?{lane_at:m,closed_at:m}:{}}:{},...h})}const{followups:s,...c}=a;await y(n.file,{...c,items:[...a.items,...o]}),t.push(`${n.slug}: ${o.length} follow-ups moved to cards (${o.filter(l=>l.lane==="done").length} done)`)}return t}),"migrateFollowups");function ao(e,t=[]){if(e.status===void 0&&e.status_at===void 0&&e.merged_at===void 0)return!1;const n=e.merged_at||e.status_at||new Date().toISOString();["merged","done","dropped"].includes(e.status)&&Object.assign(e,{lane:"done",lane_at:n,closed_at:n}),(e.status==="merged"||e.merged_at)&&(e.prs=De(e).map(i=>({...i,merged_at:i.merged_at||n})),delete e.pr),e.status==="held"&&(e.held=!0);const a=t.filter(i=>i.started&&et(i)).sort((i,o)=>String(i.started).localeCompare(String(o.started))).at(-1);return e.status==="checking"&&a&&(a.handed_back=n),delete e.status,delete e.status_at,delete e.merged_at,!0}r(ao,"statusToFacts");const xd=r(e=>ce(e,async()=>{const t=[];for(const n of await q(e)){const a=await $(n.file,null);let i=0;for(const o of Array.isArray(a?.items)?a.items:[]){const s=o.status==="checking"?await G(n.dir,o.id):[],c=await Promise.all(s.map(l=>$(l,null)));if(ao(o,c.filter(Boolean))){i++;for(const[l,u]of c.entries())u?.handed_back&&await y(s[l],u)}}i&&(await y(n.file,a),t.push(`${n.slug}: ${i} cards' statuses became lanes and facts`))}return await Nt(e,async()=>{const n=await Le(e),a=n.filter(i=>i.item&&ao(i.item)).length;a&&(await Rt(e,n),t.push(`archive: ${a} cards' statuses became lanes and facts`))}),t}),"migrateStatuses");function io(e,t){const n=e.lane==="done"&&!_n.done.includes(e.phase);if(!("state"in e)&&!n)return!1;if("state"in e&&e.state!==void 0&&(e.phase=e.state),delete e.state,n){const a=De(e);e.phase=a.some(i=>i.merged_at)||!a.length&&t?"merged":"closed"}return!0}r(io,"stateToPhase");const _d=r(e=>ce(e,async()=>{const t=[],n=await q(e),a=r(async(i,o)=>!!i&&o.lane==="done"&&(await Promise.all((await G(i,o.id)).map(s=>$(s,null)))).some(s=>s?.started&&et(s)),"built");for(const i of n){const o=await $(i.file,null);let s=0;for(const c of Array.isArray(o?.items)?o.items:[])io(c,await a(i.dir,c))&&s++;s&&(await y(i.file,o),t.push(`${i.slug}: ${s} cards' states became phases`))}return await Nt(e,async()=>{const i=await Le(e);let o=0;for(const s of i)s.item&&io(s.item,await a(n.find(c=>c.slug===(s.file||F(s.key).file))?.dir,s.item))&&o++;o&&(await Rt(e,i),t.push(`archive: ${o} cards' states became phases`))}),t}),"migratePhases"),Sd=r(e=>ce(e,async()=>{const t=[];for(const n of await q(e)){const a=await $(n.file,null),i=(Array.isArray(a?.items)?a.items:[]).filter(o=>o.implement_at);if(i.length){for(const o of i)o.phase!=="ready"&&Object.assign(o,{phase:"staging",staged_at:o.implement_at}),delete o.implement_at;await y(n.file,a),t.push(`${n.slug}: ${i.length} Implement asks moved to staging or ready`)}}return t}),"stageImplementAsks"),rn=r(e=>g.join(e,"data","done-archive.json"),"archiveFile"),Nt=r((e,t)=>nt(g.join(e,"done-archive"),t,{heartbeat:!0}),"archiveWrite"),Le=r(async e=>(await $(rn(e),{cards:[]})).cards||[],"readArchive"),cn=r(e=>`${e.closed_at||""}|${e.key}`,"archiveRank"),Qr=r((e,t)=>cn(e)<cn(t)?1:cn(e)>cn(t)?-1:0,"byClosed"),ca=r(e=>g.join(e,"data","done-archive-count.json"),"archiveCountFile");async function vd(e){const t=(await $(ca(e),null))?.count;if(Number.isInteger(t))return t;const n=(await Le(e)).length;return await y(ca(e),{count:n}),n}r(vd,"archiveCount");async function Rt(e,t){t.length?await y(rn(e),{cards:t.sort(Qr)}):await j.rm(rn(e),{force:!0}),await y(ca(e),{count:t.length})}r(Rt,"writeArchive");const jd=r((e,t)=>Nt(e,async()=>{const n=new Map(t.map(w=>[w.key,w])),a=new Date().toISOString(),i=[],o=[];for(const w of await q(e)){const f=await $(w.file,null);if(!Array.isArray(f?.items))continue;const h=f.items.filter(m=>n.has(`${w.slug}/${m.id}`)&&m.lane==="done");if(h.length){for(const m of h){const k=n.get(`${w.slug}/${m.id}`);i.push({...k,file:w.slug,archived_at:a,item:k.prs?Gr(m,k.prs):m})}o.push([w.file,{...f,items:f.items.filter(m=>!h.includes(m))}])}}if(!i.length)return[];const s=await $(E(e),{items:[]}),c=new Map(i.map(w=>[`item:${w.key}`,w]));for(const w of i)w.questions=(s.items||[]).filter(f=>f.topic===`item:${w.key}`&&f.resolved);const l=await _e(e);for(const w of i)w.asks=w.item.from_ask&&ae(l,w.item.from_ask)===void 0?[w.item.from_ask]:[];const u=new Set(i.map(w=>w.key));await Rt(e,[...(await Le(e)).filter(w=>!u.has(w.key)),...i.map(({key:w,file:f,archived_at:h,closed_at:m,item:k,questions:_,asks:N})=>({key:w,file:f,archived_at:h,closed_at:m,item:k,questions:_,asks:N}))]),i.some(w=>w.asks.length)&&await y(xe(e),{links:{...l,...Object.fromEntries(i.flatMap(w=>w.asks.map(f=>[f,w.key])))}});for(const[w,f]of o)await y(w,f);const p=(s.items||[]).filter(w=>!(c.has(w.topic)&&w.resolved));return p.length!==(s.items||[]).length&&await y(E(e),{...s,items:p}),[...u]}),"archiveCards");function Gr(e,t){if(!be(e))return e;const n=De(e).map(o=>{const s=t.find(c=>c.state&&c.number===o.number&&(!o.repo||o.repo===c.repo));return s?{...o,kept:{checks:s.checks,reviews:s.reviews,codexOpen:s.codexOpen}}:o}),{pr:a,...i}=e;return{...i,prs:n}}r(Gr,"keptPRs");async function Vr(e,t){return!e||!de(rn(e))?!1:Nt(e,async()=>{const n=await Le(e),a=n.find(w=>w.key===t);if(!a)return!1;const i=(await q(e)).find(w=>w.slug===a.file),o=i&&await $(i.file,null);if(!Array.isArray(o?.items))return!1;o.items.some(w=>w.id===a.item.id)||await y(i.file,{...o,items:[...o.items,a.item]});const s=await $(E(e),{items:[]}),c=new Set((s.items||[]).map(w=>w.id)),l=(a.questions||[]).filter(w=>!c.has(w.id));l.length&&await y(E(e),{...s,items:[...s.items||[],...l]});const u=await _e(e),p=(a.asks||[]).filter(w=>ae(u,w)===t);return p.length&&await y(xe(e),{links:Object.fromEntries(Object.entries(u).filter(([w])=>!p.includes(w)))}),await Rt(e,n.filter(w=>w!==a)),!0})}r(Vr,"restoreArchived");const oo=["push_tag","no_change"],so=r(e=>Object.fromEntries(Object.entries(e).filter(([t])=>!oo.includes(t))),"stripQuestion"),ro=r(({summary:e,...t})=>t,"stripItem"),co=r(e=>oo.some(t=>t in e),"holdsDead"),Od=r(e=>Nt(e,async()=>{for(const a of await q(e)){const i=await $(a.file,null);Array.isArray(i?.items)&&i.items.some(o=>"summary"in o)&&await y(a.file,{...i,items:i.items.map(ro)})}const t=await $(E(e),null);(t?.items||[]).some(co)&&await y(E(e),{...t,items:t.items.map(so)});const n=await Le(e);n.some(a=>"card"in a||"summary"in a.item||(a.questions||[]).some(co))&&await Rt(e,n.map(({card:a,...i})=>({...i,...a?{closed_at:i.closed_at||a.sortAt}:{},item:ro(i.item),questions:(i.questions||[]).map(so)})))}),"stripDeadFields");async function Ad(){return Vo(async()=>{const e=Go(),t=Array.isArray(e.migrated)?e.migrated:[];if(t.includes("wave-names")||!Object.keys(e.sites||{}).length)return[];const n=[];for(const{route:a,dir:i}of ge(e))await Zr(i),n.push(a);return e.migrated=[...t,"wave-names"],await Zo(e),n})}r(Ad,"migrateWaveNames");const lo=r(async e=>JSON.parse(await j.readFile(e,"utf8")),"readPlain"),la=r((e,t)=>We(e,JSON.stringify(t,null,2)+`
30
- `),"writePlain"),uo=r(e=>typeof e!="string"?e:e.replace(/^wave:([a-z0-9-]+)$/,"file:$1").replace(/^lineup:([a-z0-9-]+)$/,"wave:$1"),"renamedTopic"),da=r(e=>Array.isArray(e)?e.map(da):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[uo(t),da(n)])):uo(e),"renameTopics");async function Zr(e){const t=g.join(e,"board.json"),n=await lo(t).catch(()=>null);if(n&&typeof n.items=="string"&&n.items!=="waves"&&g.basename(n.items)==="wave.json"){const i=g.join(g.dirname(n.items),"items.json");de(g.resolve(e,n.items))&&await j.rename(g.resolve(e,n.items),g.resolve(e,i)),await la(t,{...n,items:i,slug:n.slug||"wave"})}for(const i of await q(e)){const o=await lo(i.file).catch(()=>null);if(!Array.isArray(o?.lineups))continue;const{lineups:s,...c}=o;await la(i.file,{...c,waves:[...c.waves||[],...s]});for(const{slug:l}of s)await j.rename(g.join(i.dir,`lineup-${l}.md`),g.join(i.dir,ua(l))).catch(u=>{if(u.code!=="ENOENT")throw u})}const a=g.join(e,"data");for(const i of(await j.readdir(a).catch(()=>[])).filter(o=>o.endsWith(".json"))){const o=g.join(a,i),s=await j.readFile(o,"utf8");let c;try{c=JSON.parse(s)}catch{continue}c=da(c),i==="done-archive.json"&&Array.isArray(c.cards)&&(c.cards=c.cards.map(({wave:l,...u})=>l===void 0?u:{...u,file:l})),i==="arch-reviews.json"&&Array.isArray(c.reviews)&&(c.reviews=c.reviews.map(({wave:l,lineup:u,...p})=>u?{...p,wave:l}:{...p,file:l})),JSON.stringify(c)!==JSON.stringify(JSON.parse(s))&&await la(o,c)}}r(Zr,"renameWaveNames");const ua=r(e=>`wave-${e}.md`,"waveNoteFile"),Yr=r(e=>typeof e=="string"&&/^[a-z0-9-]+$/.test(e)?e:d(`a wave's slug uses only a-z, 0-9 and "-", not "${e}"`),"waveSlug");async function pt(e,t){for(const n of await q(e)){const a=await $(n.file,null),i=(a?.waves||[]).find(o=>o.slug===t);if(i)return{source:n,itemFile:a,wave:i}}return d(`this board has no wave "${t}"; wave create makes one`)}r(pt,"findWave");async function Xr(e,t){(await oe(e)).items!=="waves"&&d(`topic file:${t} is for a board over ~/.claude/waves; a wave's triage uses wave:<slug>`),await Ue(e,t)}r(Xr,"triagedFile");function fa(e,t,n,a){return n.map(i=>{const{file:o,id:s}=F(i);o!==e.slug&&d(`${i} is not in item file "${e.slug}"; a wave's cards share one file`),((t.items.find(u=>u.id===s)||d(`item file "${o}" has no item "${s}"`)).deps||[]).includes(`wave:${a}`)&&d(`${i} waits on the wave "${a}", so it can't be in it`);const l=(t.waves||[]).find(u=>u.slug!==a&&!u.finished_at&&Ie(u).includes(s));return l&&d(`${i} is already in the wave "${l.slug}"; wave remove ${l.slug} ${i} first`),s})}r(fa,"waveCards");const wa=r(e=>[...new Set(String(e??"").split(",").map(t=>t.trim()).filter(Boolean))],"cardList");function ec(e){const t=[e??[]].flat().map(n=>{const[a,i]=String(n).split(":");return[a.trim(),wa(i)]});return(!t.length||t.some(([n])=>!n))&&d("--card takes one card per flag in build order, as <file>/<id>, or <file>/<id>:<file>/<id>,\u2026 naming the earlier cards it conflicts with"),t}r(ec,"cardSpecs");function pa(e,t,n,a,i){const o=n.items.indexOf(a),s=i.map(u=>{const p=J(e.slug,u),{file:w,id:f}=F(p),h=w===e.slug?n.items.indexOf(f):-1;return(h<0||h>=o)&&d(`${p} is not an earlier card of the wave "${n.slug}"`),f}),c=t.items.find(u=>u.id===a),l=[...(c.deps||[]).filter(u=>!fo(e,n,u)),...s];l.length?c.deps=l:delete c.deps}r(pa,"relink");const fo=r((e,t,n)=>Ie(t).some(a=>J(e.slug,n)===`${e.slug}/${a}`),"inWave");async function wo(e,t,n,a,i){i!==void 0&&await We(g.join(t.dir,ua(a.slug)),`${S(i,"the note").replace(/\n*$/,`
31
- `)}`),await y(t.file,n);const{tickets:o}=Se(await oe(e));return{file:t.file,lines:[`order: ${po(t,n,a,o)}`]}}r(wo,"writeWave");function po(e,t,n,a){const i=r(o=>tt(t,t.items.find(s=>s.id===o)||{id:o},a),"label");return Ie(n).map(o=>{const s=(t.items.find(c=>c.id===o)?.deps||[]).filter(c=>fo(e,n,c));return s.length?`${i(o)} (after ${s.map(c=>i(F(J(e.slug,c)).id)).join(", ")})`:i(o)}).join(", ")}r(po,"orderLine");async function Pd(e,t,{title:n,goal:a,cards:i,note:o}){Yr(t);const s=ec(i);o===void 0&&d("wave create needs the wave note, as --note <text> or --file <path>");const c=await q(e);c.some(f=>f.slug===t)&&d(`"${t}" is an item file on this board; pick another slug`);for(const f of c)((await $(f.file,null))?.waves||[]).some(h=>h.slug===t)&&d(`this board already has a wave "${t}"`);const l=c.find(f=>f.slug===F(s[0][0]).file)||d(`this board has no item file "${F(s[0][0]).file}"`),{itemFile:u}=await Ue(e,l.slug),p=fa(l,u,s.map(([f])=>f),t);new Set(p).size!==p.length&&d("--card names a card twice");const w={slug:t,title:S(n,"--title"),goal:S(a,"--goal"),items:p,created:new Date().toISOString()};return s.forEach(([,f],h)=>pa(l,u,w,p[h],f)),u.waves=[...u.waves||[],w],wo(e,l,u,w,o)}r(Pd,"createWave");async function Dd(e,t,{add:n,remove:a,card:i,after:o,title:s,goal:c,note:l}){[n,a,i,o,s,c,l].every(m=>m===void 0)&&d("nothing to change: pass a card with --after, --title, --goal, --note or --file"),o!==void 0&&n===void 0&&i===void 0&&d(`--after goes with a card: wave set ${t} <file>/<id> --after <file>/<id>,\u2026`),i!==void 0&&o===void 0&&d(`wave set ${t} ${i} needs --after <file>/<id>,\u2026 ("" clears its links)`);const{source:u,itemFile:p,wave:w}=await pt(e,t);w.finished_at&&d(`the wave "${t}" is finished`),w.items=Ie(w),delete w.phases;const f=a===void 0?[]:await tc(e,t);if(n!==void 0){const[m]=fa(u,p,[n],t);w.items.includes(m)&&d(`${n} is already in the wave "${t}"`),w.items.push(m),pa(u,p,w,m,wa(o))}if(i!==void 0){const{file:m,id:k}=F(i);(m!==u.slug||!w.items.includes(k))&&d(`${i} is not in the wave "${t}"`),pa(u,p,w,k,wa(o))}if(a!==void 0){const[m]=fa(u,p,[a],t);w.items.includes(m)||d(`${a} is not in the wave "${t}"`),w.items.length===1&&d(`${a} is the wave's last card; wave finish ${t} ends the wave`);const k=r(v=>!K(v)&&(v.deps||[]).some(O=>J(u.slug,O)===`${u.slug}/${m}`),"waiting"),_=p.items.filter(v=>w.items.includes(v.id)&&v.id!==m&&k(v)),N=p.items.find(v=>v.id===m);if(_.length&&!(N&&K(N))){const v=await Promise.all(_.map(async O=>`${await H(e,`${u.slug}/${O.id}`)} waits on ${a}: wave set ${t} ${u.slug}/${O.id} --after <its other conflicts, or "">`));d(`${a} can't leave the wave "${t}" while open cards wait on it; relink each, then remove:
32
- ${v.join(`
33
- `)}`)}if(N&&K(N))for(const v of p.items.filter(O=>w.items.includes(O.id)&&O.deps))v.deps=v.deps.filter(O=>J(u.slug,O)!==`${u.slug}/${m}`),v.deps.length||delete v.deps;w.items=w.items.filter(v=>v!==m)}s!==void 0&&(w.title=S(s,"--title")),c!==void 0&&(w.goal=S(c,"--goal"));const h=await wo(e,u,p,w,l);return a!==void 0&&await nc(e,t,f,a),h}r(Dd,"changeWave");async function tc(e,t){const n=[];for(const a of await q(e)){const i=await $(a.file,null);for(const o of Array.isArray(i?.items)?i.items:[])K(o)||!(o.deps||[]).includes(`wave:${t}`)||(await Ee(e,a.slug,o)).length&&n.push(`${a.slug}/${o.id}`)}return n}r(tc,"waveBlocked");async function nc(e,t,n,a){const i=`${await H(e,a)} left the wave "${t}"`;for(const o of n){const{item:s}=await x(e,o);if(s.blocked_until||(await Ee(e,F(o).file,s)).length)continue;const{line:c}=await W(e,o,"unblocked",{lifted:i});await oa(e,o,c.ts),await he({dir:e},"card-unblocked",{key:o})}}r(nc,"noticeWaveUnblocked");async function Fd(e,t){const{source:n,itemFile:a,wave:i}=await pt(e,t),o=a.items.filter(s=>Ie(i).includes(s.id)&&!K(s));if(o.length){const s=await Promise.all(o.map(c=>H(e,`${n.slug}/${c.id}`)));d(`the wave "${t}" still has ${s.join(", ")} open; wave finish waits until every card in it is Done`)}return i.finished_at=new Date().toISOString(),await y(n.file,a),{file:n.file}}r(Fd,"finishWave");async function Nd(e,t,n){const{source:a,itemFile:i,wave:o}=await pt(e,t),s=await j.readFile(g.join(a.dir,ua(t)),"utf8").catch(()=>"");return{title:o.title,markdown:`**Goal** ${o.goal}
22
+ `,"withSection");async function Bt(t,e,n,a){const{source:i,item:{id:o}}=await x(t,e);return Ur(i.dir,o,async()=>{const{source:s,itemFile:r,item:l}=await x(t,e);let u;l.plan?(u=await un(s.dir,l.plan,{missingOk:!0}),wt(u)||await W(t,e,"notes-missing")):(l.plan=sn(s.dir,l.id),u=$.join(s.dir,l.plan),await b(s.file,r));const p=wt(u)?await A.readFile(u,"utf8"):`# ${l.title}
23
+ `;return await rn(u,Jr(p,Hr(n),a)),l.plan})}c(Bt,"appendNotes");async function Ki(t){const{tickets:e}=At(await rt(t)),n=[],a=new Map;for(const i of await q(t)){const o=await g(i.file,null);a.set(i.slug,{source:i,itemFile:o||{}});for(const s of o?.items||[])s.plan&&n.push({key:`${i.slug}/${s.id}`,ref:se(o,s,e),title:s.title,created:s.created||"",archived:!1,dir:i.dir,plan:s.plan})}for(const i of t?await It(t):[]){if(!i.item?.plan)continue;const o=a.get(i.file);n.push({key:i.key,ref:se(o?.itemFile||{},i.item,e),title:i.item.title,created:i.item.created||"",archived:!0,dir:o?.source.dir||$.join(t,"data"),plan:i.item.plan})}return n}c(Ki,"cardsWithNotes");const zi=c(t=>A.realpath($.resolve(t.dir,t.plan)).catch(()=>null),"realNotes");async function Gi(t,e,n,a){if(e==="-")return Xo(0,"utf8");const i=await A.realpath(e).catch(()=>d(`${n} ${e}: no such file`));for(const o of await Ki(t))await zi(o)===i&&d(`${n} ${e} is the notes file of ${o.ref} "${o.title}" (${o.key}), and a card's notes are its own; ${a(o)}`);return A.readFile(i,"utf8")}c(Gi,"refuseCardNotes");const ua="write a draft of your own outside the board's data folder";async function Fd(t,e,{heading:n,file:a,from:i}){let o;if(i!==void 0){i===e&&d(`${e} can't fold its own notes into itself; pass --from <the other card>`);const[l,u]=await Promise.all([x(t,e),x(t,i)]),[p,w]=await Promise.all([l,u].map(({source:f,item:h})=>h.plan?A.realpath($.resolve(f.dir,h.plan)).catch(()=>null):null));p&&p===w&&d(`${i} and ${e} name one notes file, ${l.item.plan}, from before the board named each card's own; the board splits it as it starts`),o=(await lc(t,i)).markdown,n??=`Folded from ${await K(t,i)} "${u.item.title}"`}else o=await Gi(t,a,"--file",l=>l.key===e?`${ua}, holding only the new section`:`${ua}, or fold that card's notes in with item notes ${e} --from ${l.key}`);o.trim()||d(`${i??a} is empty`);const s=await Bt(t,e,n,o),r=await cn(t,e,"Recorded in the card's notes");return{file:s,heading:n,lines:r}}c(Fd,"addNotes");const Rd=c(t=>lt(t,async()=>{const e=await Ki(t),n=new Map;for(const i of e){const o=await zi(i);o&&n.set(o,[...n.get(o)||[],i])}const a=[];for(const[i,o]of n){const[s,...r]=o.sort((l,u)=>l.created<u.created?-1:l.created>u.created?1:l.key<u.key?-1:1);for(const l of r.filter(u=>!u.archived)){const{source:u,itemFile:p,item:w}=await Kt(t,R(l.key).file).then(h=>({...h,item:h.itemFile.items.find(m=>m.id===R(l.key).id)})),f=w.plan;w.plan=sn(u.dir,w.id),await rn($.join(u.dir,w.plan),await A.readFile(i,"utf8")),await b(u.file,p),await W(t,l.key,"notes-shared",{card:s.ref}),a.push(`${l.key}: its own notes, ${w.plan}, copied from ${$.normalize(f)}, which ${s.key} keeps`)}await A.chmod(i,Ji)}return a}),"splitSharedNotes");async function Kr(t,e){const{source:n,item:a}=await x(t,e);return mt(a)||St(a)||a.pushed||(await Promise.all((await V(n.dir,a.id)).map(o=>g(o,null)))).some(o=>o?.started&&!o.done&&o.kind!==gt)||(await ft(t,e)).asked.some(o=>o.state==="open")||(await g(ut(t),{}))[e]?!1:!await wa(t,e)}c(Kr,"stageable");async function fa(t,e){const{source:n,itemFile:a,item:i}=await x(t,e);i.phase!=="staging"&&(Object.assign(i,{phase:"staging",staged_at:new Date().toISOString()}),delete i.unfiled,delete i.filed_held,await b(n.file,a),await Qt(t,e,{command:"staged"}))}c(fa,"stage");const Qi=c(({text:t,files:e})=>[String(t||"").trim(),...(Array.isArray(e)?e:[]).map(n=>`Attached: ${n?.path||n?.name||n}`)].filter(Boolean).join(`
24
+ `),"messageWords");async function zr(t,e,n){const{item:a}=await x(t,e);a.held&&await ho(t,"card-hold",{key:e,hold:!1});const{owner:i,asked:o}=await ft(t,e),s=o.filter(l=>l.state==="open").map(l=>l.id);s.length&&await me(t,i,s,"Skipped: you tapped Implement");const r=Qi(n);r&&await Bt(t,e,`Implement (owner, ${Yt()}), verbatim`,r),await fa(t,e)}c(zr,"stageImplement");async function Nd(t,e,n){const a=Qi(n);a&&await Bt(t,e,`Reply (owner, ${Yt()}), verbatim`,a),await fa(t,e)}c(Nd,"stageReply");async function Ed(t,e,n){const{source:a,itemFile:i,item:o}=await x(t,e);!["ready","staging"].includes(o.phase)||mt(o)||(o.phase=n==="prototype"?"prototyping":"grilling",delete o.staged_at,await b(a.file,i))}c(Ed,"planAgain");async function Gr(t,e){const n=await x(t,e).catch(()=>null);!n||!["ready","staging"].includes(n.item.phase)||mt(n.item)||(n.item.phase="grilling",delete n.item.staged_at,await b(n.source.file,n.itemFile),await W(t,e,"new-question"))}c(Gr,"grillAgain");function Vi(t){return t.filter(e=>e.state==="answered").map(e=>e.id)}c(Vi,"answeredOnClaude");function Xt(t,e,n,a=new Date().toISOString()){for(const i of t.items||[])e.includes(i.id)&&Object.assign(i,{resolved:n,resolved_at:a})}c(Xt,"setResolved");async function me(t,e,n,a){return Xt(e,n,a),await b(B(t),e),B(t)}c(me,"markResolved");async function Ld(t,e,n){D(t);const a=await g(B(t),{topics:[],items:[]}),i=(a.items||[]).find(f=>f.id===e);i||d(`no question "${e}" in owner.json`);const{answers:o,requests:s,reopens:r}=await he(t),l=Wt(i,o,s,[],r);if(l.state==="resolved")return B(t);l.state==="requested"&&d(`${e} waits on the prototype the owner asked for; question add with round_of ${e} resolves it`);const u=j(n,"--note");Lt(i.url)&&Qr(a,i,o);const p=await me(t,a,[e],u);await eo(t,i.topic);const w=la(i.topic);return w&&(await x(t,w).catch(()=>null))?.item.phase==="grilling"&&await an(t,w,{roundAt:!0}),p}c(Ld,"resolveQuestion");async function Bd(t,e,n,a=[]){D(t);const[i,...o]=[...new Set(e)];i||d("question move takes the ids of the questions to merge"),await x(t,n);const s=[n,...a];new Set(s).size!==s.length&&d("question move names a card twice");for(const f of a)await x(t,f);const r=await g(B(t),{topics:[],items:[]}),{answers:l,requests:u,reopens:p}=await he(t);for(const f of[i,...o]){const h=(r.items||[]).find(y=>y.id===f)||d(`no question "${f}" in owner.json`),{state:m}=Wt(h,l,u,[],p);m!=="open"&&d(`${f} is ${m}; question move takes open questions`)}for(const[f,h]of a.entries()){const{item:m}=await x(t,h),y=[...m.deps||[],s[f]].join(",");await bt(t,h,{deps:y,relate:n})}const w=await K(t,n);return Object.assign(r.items.find(f=>f.id===i),{topic:`item:${n}`}),Xt(r,o,`Duplicate of ${w}'s question ${i}`),await b(B(t),r),B(t)}c(Bd,"moveQuestions");async function Cd(t,e){const n=e.filter(({choice:i,note:o})=>!i&&String(o||"").trim()).map(i=>i.id),a=n.length?await g(B(t),{topics:[],items:[]}):null;a?.items?.some(i=>n.includes(i.id))&&(Xt(a,n,"Answered with a note"),await b(B(t),a))}c(Cd,"resolveNoteAnswers");function Qr(t,e,n){const a=Rn(e),i=t.items.filter(o=>o.topic===e.topic&&Rn(o)===a).map(o=>Wt(o,n));fs(i,a)||d(`${e.id} is in prototype round ${a}, which no pick has settled yet; a pick settles it`)}c(Qr,"roundSettled");async function he(t){const e=await J($.join(t,"data","events.jsonl"));return{answers:await Promise.all(e.filter(a=>a.kind==="owner-answer").map(async a=>({...a,reply:a.reply||(await Un($.join(t,"data","replies"),a.id)).length>0}))),requests:e.filter(a=>a.kind==="prototype-request"),reopens:e.filter(a=>a.kind===ls)}}c(he,"ownerEvents");async function Id(t,e){const{asked:n}=await Zi(t),a=new Map(n.map(i=>[i.id,i.state]));return e.filter(i=>!a.has(String(i.id))||["open","requested"].includes(a.get(String(i.id))))}c(Id,"unrecorded");async function Zi(t){const e=await g(B(t),{topics:[],items:[]}),{answers:n,requests:a,reopens:i}=await he(t);return{owner:e,asked:(e.items||[]).map(o=>Wt(o,n,a,[],i))}}c(Zi,"topicQuestionsAll");async function Yi(t,e){const n=await g(B(t),{topics:[],items:[]}),{answers:a,requests:i,reopens:o}=await he(t),s=(n.items||[]).filter(r=>r.topic===e).map(r=>Wt(r,a,i,[],o));return{owner:n,asked:s}}c(Yi,"topicQuestions");const ft=c((t,e)=>Yi(t,`item:${e}`),"cardQuestions"),cn=c((t,e,n)=>Xi(t,`item:${e}`,n),"resolveAnswered");async function Xi(t,e,n){if(!t)return[];const{owner:a,asked:i}=await Yi(t,e),o=Vi(i);return o.length&&await me(t,a,o,n),await eo(t,e),o.map(s=>`resolved: ${s}`)}c(Xi,"resolveAnsweredOn");const ln=c(async(t,e)=>!!t&&(await ft(t,e)).asked.some(n=>n.state==="open"),"hasOpenQuestion");function to(t,e,n){t.next=j(e,"--next"),t.next_at=new Date().toISOString(),n?t.next_on_questions=!0:delete t.next_on_questions}c(to,"setNext");async function eo(t,e){const n=e.startsWith("item:")&&!e.startsWith("item:ask:")?e.slice(5):null;if(!n)return;let a;try{a=await x(t,n)}catch(r){if(r instanceof pt)return;throw r}const{source:i,itemFile:o,item:s}=a;s.next_on_questions&&((await ft(t,n)).asked.some(r=>r.state!=="resolved")||(delete s.next,delete s.next_at,delete s.next_on_questions,await b(i.file,o)))}c(eo,"clearWaitedNext");async function Vr(t,e){const{source:n,itemFile:a,item:i}=await x(t,e);i.next===void 0&&i.next_on_questions===void 0||(delete i.next,delete i.next_at,delete i.next_on_questions,await b(n.file,a))}c(Vr,"clearNext");async function no(t,e,n,a){if(!t)return async()=>[];const{owner:i,asked:o}=await ft(t,e),s=o.filter(l=>l.state==="open").map(l=>l.id);s.length&&!a&&d(`${n}: ${e} has ${s.length===1?"an open question":"open questions"} ${s.join(", ")} with no answer yet; pass --force to close the card and resolve ${s.length===1?"it":"them"} too`);const r=o.filter(l=>l.state!=="resolved").map(l=>l.id);return async()=>(r.length&&await me(t,i,r,"Closed with the card"),r.map(l=>`resolved: ${l}`))}c(no,"closeQuestions");async function Td(t,e,n,a,i){await x(t,e),Xe(n),it(a,o=>j(o,"--owner-step")),it(i,o=>go(o)),await no(D(t),e,"land",!1)}c(Td,"checkClose");async function wa(t,e){const n=await g(B(t),{items:[]}),{answers:a,requests:i,reopens:o}=await he(t);return cs((n.items||[]).map(s=>Wt(s,a,i,[],o)),e)}c(wa,"unpickedPrototype");const Zr=c(t=>t.length>120?`${t.slice(0,119)}\u2026`:t,"clip"),Yr={ask:"text","ask-edited":"text","item-message":"text","owner-answer":"note"};async function ao(t,e,n){const a=j(e,n).replace(/\s+/g," ");return(await J($.join(t,"data","events.jsonl"))).map(o=>String(o.data?.[Yr[o.kind]]??"").replace(/\s+/g," ").toLowerCase()).some(o=>o.includes(a.toLowerCase()))||d(`${n} must quote the owner's words in an ask, card message or answer note on this board`),a}c(ao,"ownerQuote");async function qd(t,e,n){return D(t),n===void 0&&d(`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 ${e}'s run`),`Running at the owner's ask: "${await ao(t,n,"--asked")}"`}c(qd,"askedGate");async function Ce(t,e,n="--from-ask"){return vt(e,n),(await J($.join(D(t),"data","events.jsonl"))).some(i=>i.id===e&&i.kind==="ask")?e:d(`no ask "${e}" in this site's data/events.jsonl`)}c(Ce,"checkAsk");function Ie(t,e,n=new Date().toISOString(),a=io(t,e)){if(!qt[e])throw new Error(`no lane "${e}"`);const i=t.lane;return oo(t,e,a),t.lane=e,t.lane_at=n,e==="done"?(t.closed_at=n,delete t.reopened_at):i==="done"&&(t.reopened_at=n),i}c(Ie,"placeIn");function io(t,e,n=!1){return e==="todo"?mt(t)?"ready":t.phase??null:e==="progress"?"reading":e==="done"?n||Et(t).some(a=>a.merged_at)?"merged":"closed":null}c(io,"movedPhase");function oo(t,e,n){if(n!==null&&!Pn[e].includes(n))throw new Error(`no ${qt[e]} phase "${n}"`);n===null?delete t.phase:t.phase=n}c(oo,"setPhase");async function Md(t,e,n,a,i,o){const{source:s}=await x(t,e),{id:r}=R(e),l=new Date().toISOString();if(!await re(s.file,async()=>{const w=JSON.parse(await A.readFile(s.file,"utf8")),f=w.items.find(m=>m.id===r)||d(`item file "${s.slug}" has no item "${r}"`);if(o&&((f.lane??null)!==o.lane||(f.phase??null)!==o.phase)||f.lane===n&&(i===void 0||(f.phase??null)===i))return!1;let h;return f.lane===n?oo(f,n,i):h=Ie(f,n,l,i),await Jt(s.file,JSON.stringify(w,null,2)+`
25
+ `),h!==void 0}))return null;const p={ts:l,who:"claude",kind:Wa,text:`Moved to ${qt[n]}: ${j(a,"why")}`};return await dt(Z(t,e),p),p.text}c(Md,"moveCard");const G=c(t=>t?.lane==="done"||!!t?.reopened_at,"closed"),mt=c(t=>!!t?.lane&&t.lane!=="todo","leftTodo"),Wd=c(async(t,e)=>G((await x(t,e)).item),"isFinished"),so=["ready","grilling","prototyping"];function ro(t,e){e!==void 0&&d(`--state is now --phase: pass --phase ${so.includes(e)?e:"ready, grilling or prototyping"}`),t==="staging"&&d("--phase staging is set by the board, on an owner action; pass ready, grilling or prototyping"),t!==void 0&&!so.includes(t)&&d("--phase takes ready, grilling or prototyping")}c(ro,"checkPhase");const Xr="a card goes ready only from staging, which the board sets on the owner's Send, Implement or Reply";async function co(t,e){return(await J($.join(D(t),"data","events.jsonl"))).some(a=>a.kind==="ask"&&a.id===e&&a.data?.quick===!0||a.kind==="item-message"&&a.data?.key===`ask:${e}`&&a.data?.intent==="build")}c(co,"quickAsk");const tc=/^mark (?:it |this |the card )?ready\b/i;function ec(t,e,n){const a=[].concat(e).map(s=>Cn(s)||d(`--pr takes a PR number or owner/repo#<n>, not "${s}"`)),i=c((s,r)=>s.number===r.number&&(s.repo||n||null)===(r.repo||n||null),"same"),o=Et(t);for(const s of a)o.some(r=>i(r,s))||o.push(s);delete t.pr,t.prs=o}c(ec,"addPRs");const z=c((t,e)=>String(e).includes("/")?String(e):`${t}/${e}`,"depKey"),te=/^wave:(.+)$/;async function ge(t,e,n){const a=await Promise.all((n||[]).map(async i=>{const o=String(i).match(te)?.[1];if(!o)return[z(e,i)];const{source:s,wave:r}=await $e(t,o);return Mt(r).map(l=>`${s.slug}/${l}`)}));return[...new Set(a.flat())]}c(ge,"depCards");async function Ct(t,e,n){const a=await ge(t,e,n.deps),i=await Promise.all(a.map(o=>x(t,o).then(({item:s})=>s,()=>null)));return a.filter((o,s)=>i[s]&&!G(i[s]))}c(Ct,"unfinishedDeps");async function nc(t,e,n){const a=await Promise.all((await Ct(t,R(e).file,n)).map(i=>K(t,i)));return n.blocked_until?[...a,n.blocked_until]:a}c(nc,"blockerNames");async function dn(t,e,n){n??=(await x(t,e)).item;const a=await Promise.all((await Ct(t,R(e).file,n)).map(i=>K(t,i)));return[a.length&&`by ${a.join(", ")}`,n.blocked_until&&`until ${n.blocked_until}`].filter(Boolean).join(" and ")}c(dn,"blockWords");const ac=c((t,e)=>!St(t)&&!t.pushed&&!t.merge_ready&&!G(t)&&(!!Dn(e)||e.some(n=>n?.started&&!n.done&&oe(n))),"inProgress");async function ic(t,e){const n=[];for(const a of await q(t)){const i=await g(a.file,null);for(const o of Array.isArray(i?.items)?i.items:[])G(o)||o.blocked_until||!(await ge(t,a.slug,o.deps)).includes(e)||(await Ct(t,a.slug,o)).length||n.push(`${a.slug}/${o.id}`)}return n}c(ic,"unblockedBy");async function oc(t,e,n){const a=R(e).file,i=(await ma(t,a,n)).map(r=>te.test(r)?r:z(a,r));i.length||d("--split-into takes wave:<slug> or the cards the split filed, <id>,<file>/<id>"),(await ge(t,a,i)).includes(e)&&d(`${e} can't be split into itself`);const o=await Promise.all(i.map(async r=>{const l=r.match(te)?.[1];if(!l)return K(t,r);const{source:u,wave:p}=await $e(t,l),w=await Promise.all(Mt(p).map(f=>K(t,`${u.slug}/${f}`)));return`the wave ${p.title} (${w.join(", ")})`})),s=[];for(const r of await q(t))for(const l of(await g(r.file,null))?.items||[]){const u=`${r.slug}/${l.id}`;if(!(G(l)||!(l.deps||[]).some(p=>z(r.slug,p)===e))){for(const p of i)(await ge(t,a,[p])).includes(u)&&d(te.test(p)?`${u} waits on ${e} and is in the wave "${p.match(te)[1]}", so it would wait on itself; split into the new cards by key`:`${u} waits on ${e} and is one of the cards it splits into, so it would wait on itself`);s.push(u)}}return{entries:i,words:o.join(", "),waiters:s}}c(oc,"splitPlan");async function sc(t,e,{entries:n,words:a,waiters:i}){for(const s of await q(t)){const r=i.filter(u=>R(u).file===s.slug);if(!r.length)continue;const l=await g(s.file,null);for(const u of l.items.filter(p=>r.includes(`${s.slug}/${p.id}`))){const p=n.map(w=>!te.test(w)&&R(w).file===s.slug?R(w).id:w);u.deps=[...new Set([...u.deps.filter(w=>z(s.slug,w)!==e),...p])]}await b(s.file,l)}const o=await K(t,e);for(const s of i)await W(t,s,"split-moved",{card:o,to:a})}c(sc,"moveWaiters");async function pa(t,e,n){const{source:a,itemFile:i,item:o}=await x(t,e);if(mt(o))o.unblocked_at=n;else if(o.phase==="ready")o.recheck_at=n;else return;await b(a.file,i)}c(pa,"markUnblocked");async function lo(t,e,n,a){const i=new Set(a.match(/#?[\w-]+(?:\.[\w-]+)*(?:\/[\w-]+(?:\.[\w-]+)*)*/g)||[]),o=new Set(await ge(t,R(e).file,n.deps));for(const s of await q(t)){const r=await g(s.file,null);for(const l of r?.items||[]){const u=`${s.slug}/${l.id}`;if(u===e||o.has(u)||G(l))continue;[l.id,se(r,l),l.ticket].filter(Boolean).flatMap(w=>[w,`${s.slug}/${w}`]).some(w=>i.has(w))&&d(`--next names unfinished card ${u}; add it with --deps`)}}}c(lo,"checkNextDeps");const uo=c(t=>`item notes ${t} --heading "<heading>" --file <draft.md>`,"NOTES_COMMAND");function rc(t,e){e.size||d(`${t} has no size; a builder starts from it, so pass --size small or large with --phase ready`),e.plan||d(`${t} has no notes file; a builder starts from it, so add its notes with ${uo(t)} before --phase ready`)}c(rc,"checkSizeAndNotes");async function cc(t,e,n,a){rc(e,a);const i=await A.readFile(await un(n,a.plan),"utf8"),o=(await ft(t,e)).asked.filter(s=>s.answers.length&&!i.includes(s.id)&&!((s.prototype_gate||s.ticket_gate)&&!s.answers.at(-1).note)).map(s=>s.id);o.length&&d(`${e}'s notes leave out the answered question${o.length===1?"":"s"} ${o.join(", ")}; record each answer in its notes, naming its id, with ${uo(e)} before it is ready`)}c(cc,"checkNotesComplete");async function un(t,e,{missingOk:n=!1}={}){const a=c(s=>d(`a notes file is a .md file inside ${t}, named relative to it: "${e}" ${s}`),"bad");(typeof e!="string"||!e.trim())&&a("is empty"),($.isAbsolute(e)||e.split(/[\\/]/).includes(".."))&&a("leaves the folder"),$.extname(e).toLowerCase()!==".md"&&a("is not a .md file");const i=await A.realpath(t),o=await A.realpath($.resolve(t,e)).catch(()=>n?$.resolve(i,e):a("does not exist"));return o.startsWith(i+$.sep)||a("leaves the folder"),o}c(un,"planPath");async function lc(t,e){const{source:n,itemFile:a,item:i}=await x(t,e);if(i.plan)return{itemFile:a,item:i,markdown:await A.readFile(await un(n.dir,i.plan),"utf8")};if(typeof i.notes=="string"&&i.notes.trim())return{itemFile:a,item:i,markdown:i.notes};d(`${e} has no notes`)}c(lc,"readNotes");function fo({install:t,installSha:e,installLabel:n,clearInstall:a}){if(t===void 0)return(e!==void 0||n!==void 0)&&d("--install-sha and --install-label go with --install <url>"),a?null:void 0;a&&d("pass --install or --clear-install, not both");let i;try{i=new URL(String(t).trim())}catch{i=null}(!i||!["https:","itms-services:"].includes(i.protocol))&&d(`--install takes an https:// or itms-services:// URL, not "${t}"`),i.protocol==="itms-services:"&&!(i.searchParams.get("action")==="download-manifest"&&/^https:\/\//.test(i.searchParams.get("url")||""))&&d("--install: an itms-services:// URL needs ?action=download-manifest&url=https://\u2026/manifest.plist");const o=e===void 0?void 0:/^[0-9a-f]{7,40}$/i.test(e)?e.toLowerCase():d(`--install-sha takes a commit sha of 7 to 40 hex digits, not "${e}"`);return{url:String(t).trim(),...n===void 0?{}:{label:j(n,"--install-label")},built_at:new Date().toISOString(),...o?{sha:o}:{}}}c(fo,"installOf");async function Ud(t,{install:e,installSha:n}){const a=fo({install:e,installSha:n});a||d("main set needs --install <url>");const i=$.join(D(t),"data","main.json");return await b(i,{install:a}),{file:i,lines:["main install set"]}}c(Ud,"setMainInstall");const dc=c((t,e)=>t.length?`Merged PR${t.length>1?"s":""} ${Nt(t,e)}.`:"Merged.","mergedLine");function uc(t,e,n,a,i,o){return o?{status:o}:n&&a===void 0?{status:["merged",{words:dc(n,i)}]}:(a===void 0&&t&&d(`--done needs --text "<what was done, or why it closes without landing>", which becomes ${e}'s last thread line`),a===void 0?null:{text:a})}c(uc,"closingLine");function fc(t,e,n){const a=new Date().toISOString(),i=c((o,s)=>o.number===s.number&&(o.repo||n||null)===(s.repo||n||null),"same");t.prs=Et(t).map(o=>{const s=e.find(r=>i(o,r));return s&&!o.merged_at?{...o,merged_at:s.at||a}:o}),delete t.pr}c(fc,"markMerged");async function wo(t,e,{ticket:n,newTicket:a,status:i,clearStatus:o,done:s,splitInto:r,merged:l,landed:u,start:p,handBack:w,next:f,clearNext:h,pr:m,pushed:y,mergeReady:_,ghSince:P,fromAsk:S,phase:v,state:F,held:I,unheld:M,pickUpAt:O,deps:L,blockedUntil:C,blockReason:T,parent:ot,related:N,relate:H,unrelate:tt,install:Q,installSha:xt,installLabel:_t,clearInstall:Y,title:Pt,size:Ue,model:ke,force:ye,text:st,closing:nt,who:$n,by:ht,command:Aa,ownerStep:ae,ownerDone:Jo,check:be},Pa){(i!==void 0||o)&&d(`--status${o?" and --clear-status are":" is"} gone: a card's lane is stored and moves itself. Close it with --done --text "<what was done, or why it closes without landing>"`),l&&(s=!0),N!==void 0&&(H!==void 0||tt!==void 0)&&d("pass --related, or --relate and --unrelate, not both"),ro(v,F),ye&&!s&&d("--force goes with --done"),r!==void 0&&!s&&d("--split-into goes with --done"),r!==void 0&&st!==void 0&&d("--split-into writes the closing line; drop --text");const xe=r===void 0?null:await oc(t,e,r);xe&&(st=`Split into ${xe.words}`),S!==void 0&&s&&d("--from-ask opens a card; close it in another call"),st!==void 0&&Xe(st),ae!==void 0&&j(ae,"--owner-step");const _e=be===void 0||be===""?be:go(be);st!==void 0&&S===void 0&&!s&&v!=="ready"&&d("--text goes with --from-ask, --done, or --phase ready on a staging card"),S!==void 0&&st===void 0&&d(`--from-ask needs --text "<first line>", the item's first thread line after the ask`),f!==void 0&&h&&d("pass --next or --clear-next, not both"),typeof f=="string"&&!f.trim()&&([f,h]=[void 0,!0]);const Se=mo({held:I,unheld:M,pickUpAt:O}),He=fo({install:Q,installSha:xt,installLabel:_t,clearInstall:Y});[s,p,w,f,h,m,y,_,P,S,v,Se,L,C,T,ot,N,H,tt,He,Pt,Ue,ke,n,a,ae,be].every(E=>E===void 0||E===!1)&&d("nothing to set: pass --done, --next, --clear-next, --pr, --pushed, --gh-since, --from-ask, --phase, --held, --unheld, --pick-up-at, --deps, --blocked-until, --block-reason, --parent, --related, --relate, --unrelate, --install, --clear-install, --title, --size, --model, --ticket, --new-ticket or --check");const et=S===void 0?void 0:await Ce(t,S);et&&await Vn(t,et),et&&await yi(t,et,e);const{source:Tt,itemFile:ie,item:k}=await x(t,e),Da=et??(k.phase?void 0:k.from_ask),Ko=Da!==void 0&&await co(t,Da);v!==void 0&&k.answered_at&&!k.closed_at&&(delete k.answered_at,mt(k)&&Ie(k,"todo",void 0,null)),v!==void 0&&mt(k)&&d(`--phase sets a Todo card's phase; ${e} is ${qt[k.lane]}, where the board sets it`),v==="ready"&&!Ko&&!["staging","ready"].includes(k.phase)&&d(`${e} reads ${k.phase||"new"}, not staging; ${Xr}`),et&&k.from_ask&&k.from_ask!==et&&d(`${e} came from ask "${k.from_ask}", so ask "${et}" can't be its from-ask; to fold it in: item relate-ask ${et} ${e} --summary "<line>"`),et&&Se&&v!==void 0&&!k.phase&&d("a card filed held is filed New and takes no --phase; drop --phase, or drop --held to file it in a phase"),et&&v===void 0&&!k.phase&&!Se&&d("--from-ask files a card, which reads New until it has a phase: pass --phase grilling, prototyping, or ready for a Quick build ask, or --held to file it for later");const kn=G(k);xe&&kn&&d(`${e} is already Done, so the cards waiting on it were unblocked then; move them with item set <key> --deps`),ae!==void 0&&kn&&d(`${e} is already Done, 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")),Jo&&delete k.owner_step,_e!==void 0&&!k.owner_step&&d(`--check goes with an owner step, which ${e} doesn't have: pass --owner-step "<the step>" with it on builder done or land`),_e&&(k.owner_check={check:_e,since:k.owner_check?.check===_e?k.owner_check.since:new Date().toISOString()}),(_e===""||!k.owner_step)&&delete k.owner_check;const yn=await Promise.all((await V(Tt.dir,k.id)).map(E=>g(E,null))),zo=Fn(k,yn);if(Pt!==void 0&&(k.title=j(Pt,"--title")),po(k,{size:Ue,model:ke}),L!==void 0){const E=await ma(t,R(e).file,L,e);E.length?k.deps=E:delete k.deps}const Fa=C===""?k.blocked_until:void 0;if(C!==void 0&&(C===""?delete k.blocked_until:k.blocked_until=j(C,"--blocked-until")),T&&(!k.deps?.length&&!k.blocked_until&&d("--block-reason goes with a block: --deps or --blocked-until"),k.block_reason=j(T,"--block-reason")),(T===""||!k.deps?.length&&!k.blocked_until)&&delete k.block_reason,ot!==void 0){const E=await ha(t,R(e).file,e,ot);E?k.parent=E:delete k.parent}const Ra=ot!==void 0||N!==void 0||H!==void 0||tt!==void 0?await ga(t,e):null;let bn=N===void 0?null:await mc(t,e,k,N);H!==void 0&&(k.related=[...new Set([...(k.related||[]).map(E=>z(R(e).file,E)),...await wn(t,e,H,"--relate")])]),tt!==void 0&&(bn=await hc(t,e,k,await wn(t,e,tt,"--unrelate"))),Se!==void 0&&fn(k,Se),p&&k.held&&d(k.pick_up_at?`${e} is held until ${k.pick_up_at}, when the board resumes it; start it early only with item set ${e} --unheld`:`${e} is held; start it only once the owner resumes it, with item set ${e} --unheld`);const ve=m!==void 0||y!==void 0||_!==void 0;if((p||s||w||ve)&&(pc(k),delete k.recheck_at),p){const E=await Ct(t,R(e).file,k);E.length&&d(`${e} is blocked by ${E.join(", ")}; start it once ${E.length===1?"that is":"those are"} done`),k.blocked_until&&d(`${e} is blocked until ${k.blocked_until}; start it once that holds and the block is cleared with --blocked-until ""`)}const Je=p&&t?await wa(t,e):null;Je&&d(`${e} has no take picked: the owner's answer to ${Je.id} picks none${Je.note?` ("${Zr(Je.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 Go=s?await no(t,e,"--done",ye):async()=>[],je=s?uc(t,e,l,st,ct(t,ie),nt):null;if(l&&fc(k,l,ct(t,ie)),f!==void 0&&(to(k,f,await ln(t,e)),await lo(t,e,k,k.next)),h&&(delete k.next,delete k.next_at,delete k.next_on_questions),p&&f===void 0&&k.next_on_questions&&(delete k.next,delete k.next_at,delete k.next_on_questions),ve&&!k.review_since&&(k.review_since=new Date().toISOString()),m!==void 0&&ec(k,m,ct(t,ie)),y!==void 0){kt().find(E=>Rt(E.dir,D(t)))?.remote||d("--pushed is for a board whose repo is a plain git remote; on GitHub, open a PR and pass --pr"),St(k)&&d(`${e} has a PR; its PR says when it merges`);try{Rs(y)}catch{d("--pushed takes the name of the branch you pushed")}k.pushed={branch:y,at:new Date().toISOString()},k.branch=y}if(_!==void 0&&(k.merge_ready={branch:_,at:new Date().toISOString()},k.branch=_),s&&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)))&&d("--gh-since takes an ISO-8601 UTC time such as 2026-10-23T11:00:00Z"),k.gh_since=P),et&&(k.from_ask=et),v==="ready"&&t){const E=(await ft(t,e)).asked.filter(Ft=>Ft.state==="open").map(Ft=>Ft.id);E.length&&d(`${e} 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 cc(t,e,Tt.dir,k)}const xn=v==="ready"&&k.phase==="staging"&&S===void 0;xn&&st===void 0&&d(`${e} goes ready from staging on your judgment: pass --text "<what you checked it against on the board>", which goes into its notes`);const _n=v==="ready"&&k.phase==="ready"&&!!k.recheck_at&&S===void 0;_n&&st===void 0&&d(`${e}'s block ended, so it builds once you re-check its notes against what landed: pass --text "<what you re-checked>", which goes into its notes`),v==="ready"&&!xn&&!_n&&st!==void 0&&S===void 0&&!s&&d(`${e} reads ${k.phase||"no phase"}, not staging, so there is no judgment for --text to record`);const Qo=v==="ready"&&k.phase!=="ready";v!==void 0&&(v!=="ready"&&["staging","ready"].includes(k.phase)&&(k.round_at=new Date().toISOString()),k.phase=v,delete k.recheck_at,delete k.staged_at,delete k.unfiled,delete k.filed_held),k.phase==="ready"&&tc.test(k.next??"")&&d(`${e} would read ready with Next "${k.next}", which asks for the phase it is already in; pass --next with what happens next, or --clear-next`),He&&(k.install=He),He===null&&delete k.install,!zo&&!p&&Fn(k,yn)&&d(`that leaves ${e} In Progress with nothing building and no Next; pass --next "<what happens next>"`);const Sn=(L!==void 0||C)&&!s&&ac(k,yn)?await dn(t,e,k):"",Na=ct(t,ie);let vn=null;const jn=c((E,Ft)=>{k.lane!==E&&Ie(k,E,void 0,io(k,E,u))!==void 0&&Ft&&(vn=`Moved to ${qt[E]}: ${Ft}`)},"moveTo");s?jn("done",null):ve&&k.lane!=="done"?jn("review",m!==void 0?`PR ${Nt([].concat(m).map(Cn),Na)} opened`:y!==void 0?`${y} pushed for its merge`:"verified, it waits for your Merge"):p&&!G(k)&&jn("progress","a build started");const Ea=v==="ready"&&!k.ticket&&n===void 0&&!a&&!!(t&&await ee(t));Ea&&(a=!0),a&&k.ticket&&d(`${e} already has ticket ${k.ticket}`);const La=n!==void 0||a;if(La&&await yo(t,ie,k,n,Pa,Tt.dir),await b(Tt.file,ie),La&&t&&await gc(t,e,k.ticket),Ea&&await W(t,e,"ticket-made",{ticket:k.ticket}),vn&&await dt(Z(t,e),{ts:k.lane_at,who:"claude",kind:Wa,text:vn}),xn&&await Bt(t,e,`Ready (orchestrator, ${Yt()})`,st),_n&&await Bt(t,e,`Re-checked (orchestrator, ${Yt()})`,st),Qo&&await Qt(t,e,{command:"readied"}),Sn){const E=t&&!await Mo(t,e)&&await qo(t,e,{cause:"blocked",words:`blocked ${Sn}`});await W(t,e,E?"blocked-pausing":"blocked-stays",{blocked:Sn})}bn&&await bn(),Ra&&await ko(t,e,Ra,await ga(t,e));const Dt=await Go();if(v==="ready"&&t&&Dt.push(...await cn(t,e,"Recorded in the card's notes")),p&&Dt.push(...await cn(t,e,"Acted on: build started")),et&&Dt.push(...(await Gt(t,e,{text:st})).lines),je&&t){const E=Aa?await Qt(t,e,{command:Aa,text:je.text,who:$n,by:ht}):je.status?await W(t,e,...je.status):await Gt(t,e,{text:je.text});Dt.push(...E.lines)}const Ba=k.owner_step&&s?null:js({start:p,done:s,handover:ve}),Ca=Ba&&await Os(await ee(t),k,Ba,{...Pa,repo:Na});Ca&&Dt.push(Ca),(ve||s||w)&&(await Uo(Tt.dir,k.id,s,w?{handedBack:new Date().toISOString()}:{endHandBack:!0}),await pe(t,e));const On=et?await Ot(t):{};if(at(On,et)!==void 0&&(delete On[et],await b(jt(t),{links:On})),Fa&&!G(k)&&!(await Ct(t,R(e).file,k)).length){const{line:E}=await W(t,e,"unblocked",{lifted:Fa});await pa(t,e,E.ts),await $t({dir:t},"card-unblocked",{key:e}),Dt.unshift(`unblocked: ${e}`)}if(!s||kn)return{file:Tt.file,lines:Dt};xe&&await sc(t,e,xe);const Ia=await ic(t,e),Vo=await K(t,e);for(const E of Ia){const{line:Ft}=await W(t,E,"unblocked-done",{card:Vo});await pa(t,E,Ft.ts),await $t({dir:t},"card-unblocked",{key:E})}return{file:Tt.file,lines:[...Ia.map(E=>`unblocked: ${E}`),...Dt]}}c(wo,"changeItem");function po(t,{size:e,model:n}){for(const[a,i,o]of[["size",e,["small","large"]],["model",n,["opus","sonnet"]]])i!==void 0&&(i===""?delete t[a]:t[a]=o.includes(i)?i:d(`--${a} takes ${o.join(" or ")}, or "" to clear it`))}c(po,"setBuildChoice");function mo({held:t,unheld:e,pickUpAt:n}){return[t,e,n!==void 0].filter(Boolean).length>1&&d("pass one of --held, --unheld and --pick-up-at"),n!==void 0?n===""?null:{until:wc(n)}:t?{until:null}:e?null:void 0}c(mo,"holdOf");function wc(t){const e=typeof t=="string"&&Ss.test(t)?Date.parse(t):NaN;return Number.isNaN(e)&&d('--pick-up-at takes an ISO time such as 2026-11-04T09:00, the host\u2019s local time unless it names an offset, or "" to resume the card'),e<=Date.now()&&d(`--pick-up-at ${t} has passed; pass a later time, or --unheld to resume the card now`),new Date(e).toISOString()}c(wc,"pickUpTime");function pc(t){delete t.held,delete t.pick_up_at}c(pc,"clearHold");function fn(t,e){e?t.held=!0:delete t.held,e?.until?t.pick_up_at=e.until:delete t.pick_up_at,t.held_at=new Date().toISOString()}c(fn,"setHold");async function Hd(t,e,n,{announce:a=!0}={}){const{source:i,itemFile:o,item:s}=await x(t,e);if(a){const r=new Date(n).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});await W(t,e,"hold-ended",{at:r}),!s.blocked_until&&!(await Ct(t,R(e).file,s)).length&&await $t({dir:t},"card-unblocked",{key:e,until:n})}fn(s,null),await b(i.file,o)}c(Hd,"pickUp");async function ho(t,e,n){const a=String(n?.key||""),{file:i,id:o}=R(a),{source:s,itemFile:r}=await Kt(t,i),l=n.shared_by?n.shared_by.name||n.shared_by.login:void 0,u={text:ze.done,who:"love",by:l,command:"done"},p=r.items.find(m=>m.id===o)||d(`item file "${i}" has no item "${o}"`);if(!(e==="card-done"&&!!p.owner_step)&&p.lane==="done")return null;if(e==="card-done")return bt(t,a,{done:!0,force:!0,ownerDone:!0,...u});const f=n.hold?typeof n.until=="string"?new Date(n.until).toISOString():null:void 0;fn(p,n.hold?{until:f}:null),await b(s.file,r),n.hold&&(await Mo(t,a)||await qo(t,a,{cause:"held",words:"held"}),await Uo(s.dir,o,!1,{held:!0}),await pe(t,a));const h=f&&new Date(f).toLocaleString("en-US",{weekday:"short",month:"numeric",day:"numeric",hour:"numeric",minute:"2-digit"});return Qt(t,a,n.hold?{text:h?`${ze.hold} until ${h}`:ze.hold,who:"love",by:l,command:"hold"}:{who:"love",by:l,command:"resume"})}c(ho,"recordOwnerTap");function go(t){try{return Zs(Vs(t))}catch(e){return d(e.message)}}c(go,"checkSpec");async function Jd(t,e,n,a){const{item:i}=await x(t,e);return!i.owner_step||i.owner_check?.check!==n?null:bt(t,e,{done:!0,force:!0,ownerDone:!0,closing:["check-passed",{found:a}]})}c(Jd,"passOwnerCheck");async function Kd(t,e,n,a){const{source:i,itemFile:o,item:s}=await x(t,e);return!s.owner_step||s.owner_check?.check!==n?!1:(s.owner_check.broken=a,await b(i.file,o),await W(t,e,"check-broken",{error:a}),await $t({dir:t},"owner-check-broken",{key:e,check:n,error:a}),!0)}c(Kd,"breakOwnerCheck");async function ma(t,e,n,a){const i=[...new Set(String(n).split(",").map(o=>o.trim()).filter(Boolean))];for(const o of i){const s=o.match(te)?.[1];if(!s){await x(t,z(e,o));continue}(await ge(t,e,[o])).includes(a)&&d(`${a} is in the wave "${s}", so it would wait on itself`)}return i}c(ma,"depList");async function ha(t,e,n,a){if(!String(a).trim())return null;const i=z(e,String(a).trim());i===n&&d("--parent: a card can't be its own Parent");for(let o=i;o;){const s=o===i?await x(t,o):await x(t,o).catch(l=>{if(l instanceof pt)return null;throw l});if(!s)break;const{item:r}=s;r.parent&&z(R(o).file,r.parent)===n&&d(`--parent: ${i} is a child of ${n}, so it can't be its Parent`),o=r.parent?z(R(o).file,r.parent):null}return i}c(ha,"parentKey");async function wn(t,e,n,a){const i=e.split("/")[0],o=[...new Set(String(n).split(",").map(s=>s.trim()).filter(Boolean).map(s=>z(i,s)))];o.includes(e)&&d(`${a}: a card can't be related to itself`);for(const s of o)await x(t,s);return o}c(wn,"relatedKeys");const $o=c((t,e,n)=>async()=>{for(const a of await q(t)){const i=await g(a.file,null);let o=!1;for(const s of Array.isArray(i?.items)?i.items:[]){const r=`${a.slug}/${s.id}`;r===e||!n(r)||!(s.related||[]).some(l=>z(a.slug,l)===e)||(s.related=s.related.filter(l=>z(a.slug,l)!==e),s.related.length||delete s.related,o=!0)}o&&await b(a.file,i)}},"dropLinksTo");async function ga(t,e){const n=new Set;let a=null;for(const i of await q(t))for(const o of(await g(i.file,null))?.items||[]){const s=`${i.slug}/${o.id}`,r=(o.related||[]).map(l=>z(i.slug,l));s===e?(r.forEach(l=>n.add(l)),o.parent&&(a=z(i.slug,o.parent))):r.includes(e)&&n.add(s)}return{related:n,parent:a}}c(ga,"linksOf");async function ko(t,e,n,a){const i=c(async(o,s,r=o,l=o)=>{await Qt(t,e,{command:r,card:s}),await Qt(t,s,{command:l,card:e})},"both");for(const o of a.related)n.related.has(o)||await i("related",o);for(const o of n.related)a.related.has(o)||await i("unrelated",o);a.parent&&a.parent!==n.parent&&await i("followup-of",a.parent,"followup-of","followup")}c(ko,"postLinkLines");async function mc(t,e,n,a){const i=await wn(t,e,a,"--related");return i.length?n.related=i:delete n.related,$o(t,e,o=>!i.includes(o))}c(mc,"setRelated");function hc(t,e,n,a){const i=(n.related||[]).filter(o=>!a.includes(z(R(e).file,o)));return i.length?n.related=i:delete n.related,$o(t,e,o=>a.includes(o))}c(hc,"unrelateCards");const ct=c((t,e)=>t&&kt().find(n=>Rt(n.dir,t))?.github||e.repo,"boardRepoOf");async function zd(t,e){const{itemFile:n,item:a}=await x(t,e);St(a)||d(`${e} has no PR`);const i=Ht(a,ct(t,n));i.length||d(`${e} has no repo`);const o=a.gh_since||"1970-01-01T00:00:00Z";try{const s=At(await rt(t)).github_login||await Is();return await Promise.all(i.map(async({repo:r,number:l})=>({repo:r,...ti(await Xa({repo:r,pr:l,since:o}),{pr:l,since:o,me:s})})))}catch(s){d(s.message)}}c(zd,"prReport");async function Gd(t,e,{replyTo:n,body:a}){const i=n===void 0?"pr comment":"pr reply",o=Cn(e)||d(`${i} takes a PR number or owner/repo#<n>`);n!==void 0&&!/^[1-9]\d*$/.test(n)&&d("pr reply takes the id of the review comment it answers");const s=j(a,"--body").trim();(s.startsWith(Ae.trim())||s.includes(Bn))&&d(`${i} adds the ${Ae.trim()} prefix and the claude-bridge marker itself; pass only your words`);const r=o.repo||ct(D(t),{})||d(`${i} needs a board on GitHub; this board has no repo there`);try{const l=await Ts({repo:r,pr:o.number,replyTo:n,words:s,login:At(await rt(t)).github_login}),u=await ji(t,Pe({repo:r,number:o.number}),"comment",`comment: ${s}`);return{lines:[`posted on PR ${o.repo?e:`#${e}`}: ${l}`,...u.length?[`queued for ${u.join(", ")}'s Slack thread`]:[]]}}catch(l){d(l.message)}}c(Gd,"postPR");const ee=c(async t=>Bi((await rt(t)).tickets),"boardSource");async function Qd(t,e,{afterApproval:n,confirmed:a,tapped:i}={}){D(t);const{itemFile:o,item:s}=await x(t,e);St(s)||d(`${e} has no PR`),G(s)&&d(`${e} is done`);const r=await dn(t,e,s);r&&(i&&await W(t,e,"merge-blocked",{blocked:r}),d(`Not merged: blocked ${r}.`));const l=ct(t,o),u=Ht(s,l);u.length||d(`${e} has no repo`);const p=new Date().toISOString(),w=c(O=>W(t,e,"gh-limited",{what:"Not merged",words:ns(O)}),"limited");let f;try{f=await Promise.all(u.map(O=>Xa({repo:O.repo,pr:O.number,comments:!1})))}catch(O){O.limited&&await w(O.limited),d(O.message)}const h=f.map(({view:O})=>O);if(Ws(h)){const O=u.map((L,C)=>({...L,at:h[C].mergedAt})).filter((L,C)=>h[C].state==="MERGED");return bt(t,e,{merged:O,closing:["already-merged",{prs:Nt(O,l),many:O.length>1}]})}const m=u.map((O,L)=>({...O,...f[L]})).filter(({view:O})=>O.state==="OPEN"),y=Tn(o,(await rt(t)).reviewers||[]).length>0,_=[];let P=!1,S=!1;for(const O of m){const{view:L,reviews:C}=O,{failing:T,pending:ot}=ti(O,{pr:O.number,since:p,me:null}),N=rs({...L,checks:{state:T.length?"fail":ot?"pending":"pass",failing:T,pending:ot}},{needsApproval:y}),H=C.filter(Q=>Q.state==="APPROVED").sort((Q,xt)=>String(Q.submitted_at).localeCompare(String(xt.submitted_at))).at(-1)?.commit_id;let tt=!!(H&&L.headRefOid&&H!==L.headRefOid);tt&&n===void 0&&Nc(s,H,L.headRefOid)&&(tt=!1,S=!0),P||=tt,tt&&n===void 0&&N.push('commits after the approval: pass --after-approval "<why they are trivial>" when they are, else ask the approver to look again'),_.push(...u.length>1?N.map(Q=>`${Nt([O],l)} ${Q}`):N)}m.length||_.push(u.length>1?"every PR is closed":"PR is closed"),n!==void 0&&!P&&d("--after-approval: no commit came after the approval; drop it");const v=s.manual_steps?.length?a===void 0?null:await ao(t,a,"--confirmed"):void 0;if(a!==void 0&&v===void 0&&d(`--confirmed: ${e} has no manual steps; drop it`),v===null&&_.push(`manual steps: merge only on the owner's word, with --confirmed "<their words>"`),_.length){const O=`Not merged: ${_.join("; ")}.`;i&&await W(t,e,"merge-refused",{why:_.join("; ")}),d(O)}const F=[];for(const O of m){const L=await Ta(["pr","view",String(O.number),"--repo",O.repo,"--json","title,body,commits"]);L.limited&&await w(L.limited),L.status!==0&&d(`gh pr view ${Nt([O],l)} failed: ${L.stderr.trim().split(`
26
+ `)[0]||`gh exited ${L.status}`}${F.length?` (merged ${Nt(F,l)} before it)`:""}`);const{title:C,body:T,commits:ot}=JSON.parse(L.stdout),N=["--subject",C,"--body",as(await K(t,e),T,ot)],H=await Ta(["pr","merge",String(O.number),"--repo",O.repo,"--squash",...N],{timeout:12e4});H.limited&&await w(H.limited),H.status!==0&&d(`gh pr merge ${Nt([O],l)} failed: ${H.stderr.trim().split(`
27
+ `)[0]||`gh exited ${H.status}`}${F.length?` (merged ${Nt(F,l)} before it)`:""}`),F.push(O)}const I=[n!==void 0&&`After the approval: ${j(n,"--after-approval")}`,S&&`After the approval: only the board's rebase onto ${s.rebased.at(-1).base}.`,v&&`The owner's word on the manual steps: "${v}"`].filter(Boolean),M=await bt(t,e,{merged:F});return I.length&&await Gt(t,e,{text:I.join(" ")}),M}c(Qd,"mergeCard");async function Vd(t,e){return(await x(t,e)).item.merge_ready||null}c(Vd,"heldMerge");async function Zd(t,e){const{source:n,itemFile:a,item:i}=await x(t,e);(!i.merge_ready||G(i))&&d(`${e} isn't waiting for its Merge`);const o=await dn(t,e,i);return o&&d(`${e} is blocked ${o}, so its Merge waits until nothing blocks it`),i.merge_ready.tapped=new Date().toISOString(),await b(n.file,a),i.merge_ready}c(Zd,"tapMerge");async function Yd(t,e){const{source:n,item:a}=await x(t,e);return(await Promise.all((await V(n.dir,a.id)).map(o=>g(o,null)))).filter(o=>o?.worktree?.path&&o.kind!==X).sort((o,s)=>String(s.started).localeCompare(String(o.started)))[0]?.model}c(Yd,"builderModel");async function yo(t,e,n,a,i,o,s){const r=await ee(t)||d($c);try{s??=a===void 0&&n.plan?await A.readFile(await un(o,n.plan),"utf8"):n.notes||"";const l=await vs(r,{ticket:a,title:n.title,body:s,repo:ct(t,e)},i);n.ticket=l.ticket,l.created?n.ticket_created=!0:delete n.ticket_created}catch(l){if(l instanceof pt)throw l;d(l.message)}}c(yo,"assignTicket");async function gc(t,e,n){await Ui(t,e,"ticket_gate",`Ticket linked: ${n}`)&&(await x(t,e)).item.phase==="grilling"&&await an(t,e,{roundAt:!0})}c(gc,"dropTicketQuestion");const $c="this board has no ticket source, so its cards stay tasks; pick GitHub issues or Linear in Board settings first";async function bo(t){const e=[],n=[];for(const a of await q(t)){const i=await g(a.file,{});e.push(...(i.items||[]).map(o=>o.id)),n.push(Number(i.last_task)||0)}return t&&e.push(...(await It(t)).map(a=>a.item?.id)),`T-${Math.max(0,...n,...e.map(a=>Number(/^T-([1-9]\d*)$/.exec(String(a))?.[1]||0)))+1}`}c(bo,"nextTaskId");const lt=c((t,e)=>re($.join(t||Ve(),"tickets"),e,{heartbeat:!0}),"ticketWrite"),bt=c((t,e,n,a)=>n.ticket!==void 0||n.newTicket||n.phase==="ready"?lt(t,()=>wo(t,e,n,a)):wo(t,e,n,a),"setItem"),kc=c((t,e,n,a)=>lt(t,()=>yc(t,e,n,a)),"addItem");async function yc(t,e,{title:n,notes:a,notesFrom:i,deps:o,ticket:s,newTicket:r,pickUpAt:l,held:u,parent:p,splitOf:w,size:f,model:h,phase:m,state:y,relate:_,fromAsk:P,text:S,intake:v=!1},F){const{file:I,id:M}=e.includes("/")?R(e):{file:e};M!==void 0&&vt(M,"the item id"),ro(m,y),S!==void 0&&j(S,"--text"),S!==void 0&&P===void 0&&d("--text goes with --from-ask"),P!==void 0&&S===void 0&&d(`--from-ask needs --text "<first line>", the item's first thread line after the ask`),s!==void 0&&r&&d("pass --ticket <id> to link a ticket or --new-ticket to make one, not both");const O=P===void 0?void 0:await Ce(t,P);O&&await Vn(t,O),O&&await yi(t,O);const L=mo({held:u,pickUpAt:l});L&&m!==void 0&&d("a card filed held is filed New and takes no --phase; drop --phase, or drop --held to file it in a phase"),O&&m===void 0&&!L&&d("--from-ask files a card, which reads New until it has a phase: pass --phase grilling, prototyping, or ready for a Quick build ask, or --held to file it for later"),m==="ready"&&!(O&&await co(t,O))&&d(O?`ask "${O}" is not a Quick build ask, so item add files it grilling or prototyping`:"item add files a card grilling or prototyping; ready is for a Quick build ask, filed with --from-ask"),m==="ready"&&!f&&d("a new ready card has no size; a builder starts from it, so pass --size small or large with --phase ready"),m==="ready"&&!(a??"").trim()&&i===void 0&&d("a new ready card has no notes; a builder starts from them, so pass --notes or --notes-from with --phase ready"),v&&t&&m===void 0&&!L&&d("item add files a card on a board: pass --phase grilling or prototyping, or --held to file it for later");const{source:C,itemFile:T}=await Kt(t,I);M!==void 0&&T.items.some(Y=>Y.id===M)&&d(`item file "${I}" already has an item "${M}"`);const ot=new Date().toISOString(),N={id:M,title:j(n,"--title"),created:ot,lane:"todo",lane_at:ot};if(p!==void 0&&(N.parent=await ha(t,I,null,p)||d("--parent takes a card, such as <file>/<id>")),w!==void 0&&p!==void 0&&d("--split-of sets the Parent; drop --parent"),w!==void 0){N.parent=await ha(t,I,null,w)||d("--split-of takes a card, such as <file>/<id>");const{gates:Y}=(await x(t,N.parent)).item;Y&&(N.gates={...Y})}a!==void 0&&i!==void 0&&d("pass --notes or --notes-from, not both");const H=i!==void 0?await Gi(t,i,"--notes-from",()=>`${ua}, and link that card with --relate`):a===void 0?"":j(a,"--notes");i!==void 0&&!H.trim()&&d(`--notes-from ${i} is empty`);const tt=i!==void 0?H:`# ${N.title}
28
+ ${H&&`
29
+ ${H}
30
+ `}`;po(N,{size:f,model:h}),o!==void 0&&(N.deps=await ma(t,I,o)),L&&fn(N,L),L&&m===void 0&&(N.filed_held=!0),_!==void 0&&(N.related=await wn(t,e,_,"--relate")),O&&(N.from_ask=O),m!==void 0&&(N.phase=m);const Q=M===void 0?null:Ka(await ee(t),M);Q&&s!==void 0&&Ka(await ee(t),s)!==Q&&d(`--ticket ${s} is not the ticket ${M} names`);const xt=m==="ready"&&!Q&&s===void 0&&!r&&!!await ee(t);xt&&(r=!0),Q&&r&&d(`${M} names ticket ${Q}, so --new-ticket would make another; drop --new-ticket`),(s!==void 0||r||Q)&&await yo(t,T,N,s??Q??void 0,F,C.dir,H),M===void 0&&N.ticket?(N.id=As(N.ticket),T.items.some(Y=>Y.id===N.id)&&d(`item file "${I}" already has an item "${N.id}"; link ${N.ticket} with item add ${I}/<id> --ticket ${N.ticket}`)):M===void 0&&(N.id=await bo(t)),N.plan=sn(C.dir,N.id),await rn($.join(C.dir,N.plan),tt);const _t=`${I}/${N.id}`;if(T.items.push(N),await b(C.file,T),O){await Gt(t,_t,{text:S});const Y=await Ot(t);at(Y,O)!==void 0&&(delete Y[O],await b(jt(t),{links:Y}))}return xt&&t&&await W(t,_t,"ticket-made",{ticket:N.ticket}),t&&await ko(t,_t,{related:new Set,parent:null},await ga(t,_t)),{file:C.file,key:_t,lines:[]}}c(yc,"createItem");const Xd=c(t=>lt(t,async()=>{const e=[];for(const n of await q(t)){const a=await g(n.file,null);if(!Array.isArray(a?.items)||!Array.isArray(a.followups))continue;const i=a.followups.find(l=>a.items.some(u=>u.id===l.id));i&&d(`${n.slug}: follow-up ${i.id} has the id of a card; rename one, then restart the board`);const o=[];for(const{id:l,title:u,from:p,filed:w,done:f,...h}of a.followups){const m=f?t&&(await J(Z(t,`${n.slug}/${l}`))).map(y=>y.ts).filter(Boolean).sort().pop()||w:null;o.push({id:l,title:u,...w?{created:w}:{},...p?{parent:z(n.slug,p)}:{},...f?{lane:"done",...m?{lane_at:m,closed_at:m}:{}}:{},...h})}const{followups:s,...r}=a;await b(n.file,{...r,items:[...a.items,...o]}),e.push(`${n.slug}: ${o.length} follow-ups moved to cards (${o.filter(l=>l.lane==="done").length} done)`)}return e}),"migrateFollowups");function xo(t,e=[]){if(t.status===void 0&&t.status_at===void 0&&t.merged_at===void 0)return!1;const n=t.merged_at||t.status_at||new Date().toISOString();["merged","done","dropped"].includes(t.status)&&Object.assign(t,{lane:"done",lane_at:n,closed_at:n}),(t.status==="merged"||t.merged_at)&&(t.prs=Et(t).map(i=>({...i,merged_at:i.merged_at||n})),delete t.pr),t.status==="held"&&(t.held=!0);const a=e.filter(i=>i.started&&oe(i)&&i.kind!==X).sort((i,o)=>String(i.started).localeCompare(String(o.started))).at(-1);return t.status==="checking"&&a&&(a.handed_back=n),delete t.status,delete t.status_at,delete t.merged_at,!0}c(xo,"statusToFacts");const tu=c(t=>lt(t,async()=>{const e=[];for(const n of await q(t)){const a=await g(n.file,null);let i=0;for(const o of Array.isArray(a?.items)?a.items:[]){const s=o.status==="checking"?await V(n.dir,o.id):[],r=await Promise.all(s.map(l=>g(l,null)));if(xo(o,r.filter(Boolean))){i++;for(const[l,u]of r.entries())u?.handed_back&&await b(s[l],u)}}i&&(await b(n.file,a),e.push(`${n.slug}: ${i} cards' statuses became lanes and facts`))}return await Te(t,async()=>{const n=await It(t),a=n.filter(i=>i.item&&xo(i.item)).length;a&&(await qe(t,n),e.push(`archive: ${a} cards' statuses became lanes and facts`))}),e}),"migrateStatuses"),eu=c(t=>lt(t,async()=>{const{asked:e}=await Zi(t),n=[];for(const a of await q(t)){const i=await g(a.file,null);let o=0;for(const s of Array.isArray(i?.items)?i.items:[]){if(s.gates||s.lane==="done")continue;const r=`${a.slug}/${s.id}`,l={};for(const[u,p]of Object.entries(Be)){const w=e.filter(h=>h.topic===`item:${r}`&&h[u]).flatMap(h=>h.answers).filter(h=>["yes","no"].includes(h.choice)).sort((h,m)=>String(h.ts).localeCompare(String(m.ts))).at(-1);if(!w)continue;const f=p==="prototype"&&w.choice==="yes"&&(s.phase!=="grilling"||(await J(Z(t,r))).some(h=>h.line==="prototype-round"&&String(h.ts)>String(w.ts)));l[p]=f?"ran":w.choice}Object.keys(l).length&&(s.gates=l,o++)}o&&(await b(a.file,i),n.push(`${a.slug}: ${o} cards keep their gate answers`))}return n}),"migrateGates");function _o(t,e){const n=t.lane==="done"&&!Pn.done.includes(t.phase);if(!("state"in t)&&!n)return!1;if("state"in t&&t.state!==void 0&&(t.phase=t.state),delete t.state,n){const a=Et(t);t.phase=a.some(i=>i.merged_at)||!a.length&&e?"merged":"closed"}return!0}c(_o,"stateToPhase");const nu=c(t=>lt(t,async()=>{const e=[],n=await q(t),a=c(async(i,o)=>!!i&&o.lane==="done"&&(await Promise.all((await V(i,o.id)).map(s=>g(s,null)))).some(s=>s?.started&&oe(s)),"built");for(const i of n){const o=await g(i.file,null);let s=0;for(const r of Array.isArray(o?.items)?o.items:[])_o(r,await a(i.dir,r))&&s++;s&&(await b(i.file,o),e.push(`${i.slug}: ${s} cards' states became phases`))}return await Te(t,async()=>{const i=await It(t);let o=0;for(const s of i)s.item&&_o(s.item,await a(n.find(r=>r.slug===(s.file||R(s.key).file))?.dir,s.item))&&o++;o&&(await qe(t,i),e.push(`archive: ${o} cards' states became phases`))}),e}),"migratePhases"),au=c(t=>lt(t,async()=>{const e=[];for(const n of await q(t)){const a=await g(n.file,null),i=(Array.isArray(a?.items)?a.items:[]).filter(o=>o.implement_at);if(i.length){for(const o of i)o.phase!=="ready"&&Object.assign(o,{phase:"staging",staged_at:o.implement_at}),delete o.implement_at;await b(n.file,a),e.push(`${n.slug}: ${i.length} Implement asks moved to staging or ready`)}}return e}),"stageImplementAsks"),pn=c(t=>$.join(t,"data","done-archive.json"),"archiveFile"),Te=c((t,e)=>re($.join(t,"done-archive"),e,{heartbeat:!0}),"archiveWrite"),It=c(async t=>(await g(pn(t),{cards:[]})).cards||[],"readArchive"),mn=c(t=>`${t.closed_at||""}|${t.key}`,"archiveRank"),bc=c((t,e)=>mn(t)<mn(e)?1:mn(t)>mn(e)?-1:0,"byClosed"),$a=c(t=>$.join(t,"data","done-archive-count.json"),"archiveCountFile");async function iu(t){const e=(await g($a(t),null))?.count;if(Number.isInteger(e))return e;const n=(await It(t)).length;return await b($a(t),{count:n}),n}c(iu,"archiveCount");async function qe(t,e){e.length?await b(pn(t),{cards:e.sort(bc)}):await A.rm(pn(t),{force:!0}),await b($a(t),{count:e.length})}c(qe,"writeArchive");const ou=c((t,e)=>Te(t,async()=>{const n=new Map(e.map(w=>[w.key,w])),a=new Date().toISOString(),i=[],o=[];for(const w of await q(t)){const f=await g(w.file,null);if(!Array.isArray(f?.items))continue;const h=f.items.filter(m=>n.has(`${w.slug}/${m.id}`)&&m.lane==="done");if(h.length){for(const m of h){const y=n.get(`${w.slug}/${m.id}`);i.push({...y,file:w.slug,archived_at:a,item:y.prs?xc(m,y.prs):m})}o.push([w.file,{...f,items:f.items.filter(m=>!h.includes(m))}])}}if(!i.length)return[];const s=await g(B(t),{items:[]}),r=new Map(i.map(w=>[`item:${w.key}`,w]));for(const w of i)w.questions=(s.items||[]).filter(f=>f.topic===`item:${w.key}`&&f.resolved);const l=await Ot(t);for(const w of i)w.asks=w.item.from_ask&&at(l,w.item.from_ask)===void 0?[w.item.from_ask]:[];const u=new Set(i.map(w=>w.key));await qe(t,[...(await It(t)).filter(w=>!u.has(w.key)),...i.map(({key:w,file:f,archived_at:h,closed_at:m,item:y,questions:_,asks:P})=>({key:w,file:f,archived_at:h,closed_at:m,item:y,questions:_,asks:P}))]),i.some(w=>w.asks.length)&&await b(jt(t),{links:{...l,...Object.fromEntries(i.flatMap(w=>w.asks.map(f=>[f,w.key])))}});for(const[w,f]of o)await b(w,f);const p=(s.items||[]).filter(w=>!(r.has(w.topic)&&w.resolved));return p.length!==(s.items||[]).length&&await b(B(t),{...s,items:p}),[...u]}),"archiveCards");function xc(t,e){if(!St(t))return t;const n=Et(t).map(o=>{const s=e.find(r=>r.state&&r.number===o.number&&(!o.repo||o.repo===r.repo));return s?{...o,kept:{checks:s.checks,reviews:s.reviews,codexOpen:s.codexOpen}}:o}),{pr:a,...i}=t;return{...i,prs:n}}c(xc,"keptPRs");async function _c(t,e){return!t||!wt(pn(t))?!1:Te(t,async()=>{const n=await It(t),a=n.find(w=>w.key===e);if(!a)return!1;const i=(await q(t)).find(w=>w.slug===a.file),o=i&&await g(i.file,null);if(!Array.isArray(o?.items))return!1;o.items.some(w=>w.id===a.item.id)||await b(i.file,{...o,items:[...o.items,a.item]});const s=await g(B(t),{items:[]}),r=new Set((s.items||[]).map(w=>w.id)),l=(a.questions||[]).filter(w=>!r.has(w.id));l.length&&await b(B(t),{...s,items:[...s.items||[],...l]});const u=await Ot(t),p=(a.asks||[]).filter(w=>at(u,w)===e);return p.length&&await b(jt(t),{links:Object.fromEntries(Object.entries(u).filter(([w])=>!p.includes(w)))}),await qe(t,n.filter(w=>w!==a)),!0})}c(_c,"restoreArchived");const So=["push_tag","no_change"],vo=c(t=>Object.fromEntries(Object.entries(t).filter(([e])=>!So.includes(e))),"stripQuestion"),jo=c(({summary:t,...e})=>e,"stripItem"),Oo=c(t=>So.some(e=>e in t),"holdsDead"),su=c(t=>Te(t,async()=>{for(const a of await q(t)){const i=await g(a.file,null);Array.isArray(i?.items)&&i.items.some(o=>"summary"in o)&&await b(a.file,{...i,items:i.items.map(jo)})}const e=await g(B(t),null);(e?.items||[]).some(Oo)&&await b(B(t),{...e,items:e.items.map(vo)});const n=await It(t);n.some(a=>"card"in a||"summary"in a.item||(a.questions||[]).some(Oo))&&await qe(t,n.map(({card:a,...i})=>({...i,...a?{closed_at:i.closed_at||a.sortAt}:{},item:jo(i.item),questions:(i.questions||[]).map(vo)})))}),"stripDeadFields");async function ru(){return ms(async()=>{const t=ps(),e=Array.isArray(t.migrated)?t.migrated:[];if(e.includes("wave-names")||!Object.keys(t.sites||{}).length)return[];const n=[];for(const{route:a,dir:i}of kt(t))await Sc(i),n.push(a);return t.migrated=[...e,"wave-names"],await hs(t),n})}c(ru,"migrateWaveNames");const Ao=c(async t=>JSON.parse(await A.readFile(t,"utf8")),"readPlain"),ka=c((t,e)=>Jt(t,JSON.stringify(e,null,2)+`
31
+ `),"writePlain"),Po=c(t=>typeof t!="string"?t:t.replace(/^wave:([a-z0-9-]+)$/,"file:$1").replace(/^lineup:([a-z0-9-]+)$/,"wave:$1"),"renamedTopic"),ya=c(t=>Array.isArray(t)?t.map(ya):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[Po(e),ya(n)])):Po(t),"renameTopics");async function Sc(t){const e=$.join(t,"board.json"),n=await Ao(e).catch(()=>null);if(n&&typeof n.items=="string"&&n.items!=="waves"&&$.basename(n.items)==="wave.json"){const i=$.join($.dirname(n.items),"items.json");wt($.resolve(t,n.items))&&await A.rename($.resolve(t,n.items),$.resolve(t,i)),await ka(e,{...n,items:i,slug:n.slug||"wave"})}for(const i of await q(t)){const o=await Ao(i.file).catch(()=>null);if(!Array.isArray(o?.lineups))continue;const{lineups:s,...r}=o;await ka(i.file,{...r,waves:[...r.waves||[],...s]});for(const{slug:l}of s)await A.rename($.join(i.dir,`lineup-${l}.md`),$.join(i.dir,ba(l))).catch(u=>{if(u.code!=="ENOENT")throw u})}const a=$.join(t,"data");for(const i of(await A.readdir(a).catch(()=>[])).filter(o=>o.endsWith(".json"))){const o=$.join(a,i),s=await A.readFile(o,"utf8");let r;try{r=JSON.parse(s)}catch{continue}r=ya(r),i==="done-archive.json"&&Array.isArray(r.cards)&&(r.cards=r.cards.map(({wave:l,...u})=>l===void 0?u:{...u,file:l})),i==="arch-reviews.json"&&Array.isArray(r.reviews)&&(r.reviews=r.reviews.map(({wave:l,lineup:u,...p})=>u?{...p,wave:l}:{...p,file:l})),JSON.stringify(r)!==JSON.stringify(JSON.parse(s))&&await ka(o,r)}}c(Sc,"renameWaveNames");const ba=c(t=>`wave-${t}.md`,"waveNoteFile"),vc=c(t=>typeof t=="string"&&/^[a-z0-9-]+$/.test(t)?t:d(`a wave's slug uses only a-z, 0-9 and "-", not "${t}"`),"waveSlug");async function $e(t,e){for(const n of await q(t)){const a=await g(n.file,null),i=(a?.waves||[]).find(o=>o.slug===e);if(i)return{source:n,itemFile:a,wave:i}}return d(`this board has no wave "${e}"; wave create makes one`)}c($e,"findWave");async function jc(t,e){(await rt(t)).items!=="waves"&&d(`topic file:${e} is for a board over ~/.claude/waves; a wave's triage uses wave:<slug>`),await Kt(t,e)}c(jc,"triagedFile");function xa(t,e,n,a){return n.map(i=>{const{file:o,id:s}=R(i);o!==t.slug&&d(`${i} is not in item file "${t.slug}"; a wave's cards share one file`),((e.items.find(u=>u.id===s)||d(`item file "${o}" has no item "${s}"`)).deps||[]).includes(`wave:${a}`)&&d(`${i} waits on the wave "${a}", so it can't be in it`);const l=(e.waves||[]).find(u=>u.slug!==a&&!u.finished_at&&Mt(u).includes(s));return l&&d(`${i} is already in the wave "${l.slug}"; wave remove ${l.slug} ${i} first`),s})}c(xa,"waveCards");const _a=c(t=>[...new Set(String(t??"").split(",").map(e=>e.trim()).filter(Boolean))],"cardList");function Oc(t){const e=[t??[]].flat().map(n=>{const[a,i]=String(n).split(":");return[a.trim(),_a(i)]});return(!e.length||e.some(([n])=>!n))&&d("--card takes one card per flag in build order, as <file>/<id>, or <file>/<id>:<file>/<id>,\u2026 naming the earlier cards it conflicts with"),e}c(Oc,"cardSpecs");function Sa(t,e,n,a,i){const o=n.items.indexOf(a),s=i.map(u=>{const p=z(t.slug,u),{file:w,id:f}=R(p),h=w===t.slug?n.items.indexOf(f):-1;return(h<0||h>=o)&&d(`${p} is not an earlier card of the wave "${n.slug}"`),f}),r=e.items.find(u=>u.id===a),l=[...(r.deps||[]).filter(u=>!Do(t,n,u)),...s];l.length?r.deps=l:delete r.deps}c(Sa,"relink");const Do=c((t,e,n)=>Mt(e).some(a=>z(t.slug,n)===`${t.slug}/${a}`),"inWave");async function Fo(t,e,n,a,i){i!==void 0&&await Jt($.join(e.dir,ba(a.slug)),`${j(i,"the note").replace(/\n*$/,`
32
+ `)}`),await b(e.file,n);const{tickets:o}=At(await rt(t));return{file:e.file,lines:[`order: ${Ro(e,n,a,o)}`]}}c(Fo,"writeWave");function Ro(t,e,n,a){const i=c(o=>se(e,e.items.find(s=>s.id===o)||{id:o},a),"label");return Mt(n).map(o=>{const s=(e.items.find(r=>r.id===o)?.deps||[]).filter(r=>Do(t,n,r));return s.length?`${i(o)} (after ${s.map(r=>i(R(z(t.slug,r)).id)).join(", ")})`:i(o)}).join(", ")}c(Ro,"orderLine");async function cu(t,e,{title:n,goal:a,cards:i,note:o}){vc(e);const s=Oc(i);o===void 0&&d("wave create needs the wave note, as --note <text> or --file <path>");const r=await q(t);r.some(f=>f.slug===e)&&d(`"${e}" is an item file on this board; pick another slug`);for(const f of r)((await g(f.file,null))?.waves||[]).some(h=>h.slug===e)&&d(`this board already has a wave "${e}"`);const l=r.find(f=>f.slug===R(s[0][0]).file)||d(`this board has no item file "${R(s[0][0]).file}"`),{itemFile:u}=await Kt(t,l.slug),p=xa(l,u,s.map(([f])=>f),e);new Set(p).size!==p.length&&d("--card names a card twice");const w={slug:e,title:j(n,"--title"),goal:j(a,"--goal"),items:p,created:new Date().toISOString()};return s.forEach(([,f],h)=>Sa(l,u,w,p[h],f)),u.waves=[...u.waves||[],w],Fo(t,l,u,w,o)}c(cu,"createWave");async function lu(t,e,{add:n,remove:a,card:i,after:o,title:s,goal:r,note:l}){[n,a,i,o,s,r,l].every(m=>m===void 0)&&d("nothing to change: pass a card with --after, --title, --goal, --note or --file"),o!==void 0&&n===void 0&&i===void 0&&d(`--after goes with a card: wave set ${e} <file>/<id> --after <file>/<id>,\u2026`),i!==void 0&&o===void 0&&d(`wave set ${e} ${i} needs --after <file>/<id>,\u2026 ("" clears its links)`);const{source:u,itemFile:p,wave:w}=await $e(t,e);w.finished_at&&d(`the wave "${e}" is finished`),w.items=Mt(w),delete w.phases;const f=a===void 0?[]:await Ac(t,e);if(n!==void 0){const[m]=xa(u,p,[n],e);w.items.includes(m)&&d(`${n} is already in the wave "${e}"`),w.items.push(m),Sa(u,p,w,m,_a(o))}if(i!==void 0){const{file:m,id:y}=R(i);(m!==u.slug||!w.items.includes(y))&&d(`${i} is not in the wave "${e}"`),Sa(u,p,w,y,_a(o))}if(a!==void 0){const[m]=xa(u,p,[a],e);w.items.includes(m)||d(`${a} is not in the wave "${e}"`),w.items.length===1&&d(`${a} is the wave's last card; wave finish ${e} ends the wave`);const y=c(S=>!G(S)&&(S.deps||[]).some(v=>z(u.slug,v)===`${u.slug}/${m}`),"waiting"),_=p.items.filter(S=>w.items.includes(S.id)&&S.id!==m&&y(S)),P=p.items.find(S=>S.id===m);if(_.length&&!(P&&G(P))){const S=await Promise.all(_.map(async v=>`${await K(t,`${u.slug}/${v.id}`)} waits on ${a}: wave set ${e} ${u.slug}/${v.id} --after <its other conflicts, or "">`));d(`${a} can't leave the wave "${e}" while open cards wait on it; relink each, then remove:
33
+ ${S.join(`
34
+ `)}`)}if(P&&G(P))for(const S of p.items.filter(v=>w.items.includes(v.id)&&v.deps))S.deps=S.deps.filter(v=>z(u.slug,v)!==`${u.slug}/${m}`),S.deps.length||delete S.deps;w.items=w.items.filter(S=>S!==m)}s!==void 0&&(w.title=j(s,"--title")),r!==void 0&&(w.goal=j(r,"--goal"));const h=await Fo(t,u,p,w,l);return a!==void 0&&await Pc(t,e,f,a),h}c(lu,"changeWave");async function Ac(t,e){const n=[];for(const a of await q(t)){const i=await g(a.file,null);for(const o of Array.isArray(i?.items)?i.items:[])G(o)||!(o.deps||[]).includes(`wave:${e}`)||(await Ct(t,a.slug,o)).length&&n.push(`${a.slug}/${o.id}`)}return n}c(Ac,"waveBlocked");async function Pc(t,e,n,a){const i=`${await K(t,a)} left the wave "${e}"`;for(const o of n){const{item:s}=await x(t,o);if(s.blocked_until||(await Ct(t,R(o).file,s)).length)continue;const{line:r}=await W(t,o,"unblocked",{lifted:i});await pa(t,o,r.ts),await $t({dir:t},"card-unblocked",{key:o})}}c(Pc,"noticeWaveUnblocked");async function du(t,e){const{source:n,itemFile:a,wave:i}=await $e(t,e),o=a.items.filter(s=>Mt(i).includes(s.id)&&!G(s));if(o.length){const s=await Promise.all(o.map(r=>K(t,`${n.slug}/${r.id}`)));d(`the wave "${e}" still has ${s.join(", ")} open; wave finish waits until every card in it is Done`)}return i.finished_at=new Date().toISOString(),await b(n.file,a),{file:n.file}}c(du,"finishWave");async function uu(t,e,n){const{source:a,itemFile:i,wave:o}=await $e(t,e),s=await A.readFile($.join(a.dir,ba(e)),"utf8").catch(()=>"");return{title:o.title,markdown:`**Goal** ${o.goal}
34
35
 
35
- **Order** ${po(a,i,o,n)}
36
+ **Order** ${Ro(a,i,o,n)}
36
37
 
37
- ${s}`}}r(Nd,"readWaveNotes");async function U(e,t,n,a="main"){const{id:i}=F(t);/^[\w-]{1,40}$/.test(a)||d(`--agent takes a name of letters, digits, "_" and "-", not "${a}"`);const o=a==="main"?`${i}.json`:`${i}@${a}.json`;if(n)return g.join(g.resolve(n),"agents",o);const{source:s}=await x(e,t);return g.join(s.dir,"agents",o)}r(U,"builderFile");const mo=r((e,t)=>typeof e=="string"&&/^\d{4}-\d\d-\d\dT/.test(e)&&!Number.isNaN(Date.parse(e))?new Date(e).toISOString():d(`${t} takes an ISO time such as 2026-10-23T16:30:00-07:00`),"isoTime"),ac=_n.progress,ho=80,go="reading, building, testing, checking or landing";function $o(e,t,n,a){e||d(`${a} needs --site, since the line goes to the item's thread`),t!==void 0&&!ac.includes(t)&&d(`--phase takes ${go}, not "${t}"`);const i=S(n,a);return i.length>ho&&d(`${a} is ${i.length} characters; the cap is ${ho}. Say it shorter.`),{phase:t,detail:i}}r($o,"progressLine");const ko=r((e,t,n)=>t?{detail:e.detail}:(e.phase===void 0&&d(`${n} needs --phase ${go}`),e),"forAgent");async function ma(e,t,n="main",a,{phase:i,detail:o},s){const c=qe(a),l=c||n==="main"?"":a.kind===re?n:Mt(a)||a.kind||n,u=c?Jo[a.kind]:[l,i].filter(Boolean).join(" "),p=new RegExp(`^(?:${u}|${i??u})\\s*:?\\s+`,"i"),w=u?`${u[0].toUpperCase()}${u.slice(1)}: ${o.replace(p,"")}`:o,f=Z(e,t);(await z(f)).filter(h=>h.kind==="status").pop()?.text!==w&&await le(f,{ts:s,who:"claude",kind:"status",run:a.started,...i?{phase:i}:{},...c?{planner:!0}:{},text:w})}r(ma,"statusToThread");const ic={prototype:"sonnet",grill:"opus",[me]:"sonnet"};async function Et(e,t,{label:n,phase:a,progress:i,dir:o,agent:s="main",kind:c,model:l,eta:u,worktree:p,ownWorktree:w,dispatch:f}){a!==void 0&&i===void 0&&d('--phase goes with --progress "<detail>"');const h=ee(i,ne=>$o(e,a,ne,"--progress")),m=await U(e,t,o,s),k=new Date().toISOString(),_=ee(c,ne=>/^[\w.-]{1,30}$/.test(ne)?ne:d("--kind takes a short word such as claude or codex")),N=_t(_),v=l??(_==="opus"||_==="sonnet"?_:void 0),O=["build",...wc].includes(N),A=await $(m,null),I=r(ne=>["tap","hub"].includes(ne?.dispatched)&&!ne.done,"tapOpen");if(f==="session"&&I(A))return{file:m,alreadyOpen:!0,lines:[]};s!=="main"&&_!==me&&_!==re&&I(await $(await U(e,t,o),null))&&d(`the Implement tap opened ${t}'s main builder record and no agent has taken it up; run builder start ${t} without --agent first`);const B=A?.dispatched&&!A.done?A:null,P=O&&!o?(await x(e,t)).item:void 0,L=A&&Ve(A).length?A:null,T=B&&N==="build"?{kind:_t(B.kind),model:B.model,reason:{tap:"The owner's Build tap picked it.",hub:"The board's pull picked it."}[B.dispatched]??"The session's dispatch picked it."}:O?An({card:P??{}}):null;T&&N!=="build"&&N!==T.kind&&d(`--kind ${N}: ${T.kind} builds now. ${T.reason} Pass --kind ${T.kind}, or --kind build.`);const M=T?T.kind:N,C=Fa({dir:e});if(!(B&&!f)&&es(C,M))throw new ue(Xo(C,M));const Y=h&&ko(h,qe({kind:M}),"--progress");l!==void 0&&!["opus","sonnet"].includes(l)&&d("--model takes opus or sonnet"),v!==void 0&&M==="codex"&&d("--model is for kind claude; codex needs none");const te=M==="claude"?Pn():"auto";v!==void 0&&te!=="auto"&&v!==te&&d(`--model ${v}: the hub's Claude model is ${te==="opus"?"Opus":"Sonnet"}. Pass --model ${te}, or no --model.`);const V=M==="claude"?v??T?.model??(B&&_t(B.kind)==="claude"?B.model:void 0)??"opus":qe({kind:M})?v??(B?.kind===M?B.model:void 0)??ic[M]:M===re?v??A?.model:void 0,Q={label:n===void 0?"Builder":S(n,"--label"),...M?{kind:M}:{},...V?{model:V}:{},started:k,...u===void 0?{}:{eta:mo(u,"--eta")},...f?{dispatched:f}:{},...L?{calls:L.calls,...L.verified?{verified:L.verified}:{}}:{},...dc(A)?{session:A.session}:{},...M===re&&A?.kind===re?{label:A.label,task:A.task,writes:A.writes,requested:A.requested}:{}},Ze=O&&!o&&!K(P)&&P.lane!=="progress",un=Ze?await $e(e,t,{start:!0}):{lines:[]};let ke,je=null;const Bt=w&&O&&s==="main"?[A?.worktree,P?.worktree].find(ne=>ne?.path&&de(ne.path))??null:null,mt=(B??L)?.worktree??Bt,ht=p??(O&&s==="main"&&!mt?w:void 0);try{if(ht){const ne=await G(g.dirname(g.dirname(m)),F(t).id),fn=(await Promise.all(ne.filter(pe=>pe!==m).map(pe=>$(pe,null)))).filter(pe=>pe?.worktree?.path&&!pe.done).map(pe=>pe.worktree.path);({remade:je,...ke}=await ht({busy:fn}))}else ke=mt}catch(ne){throw Ze&&await fc(e,t,P),ne}await oc(m,A),await y(m,ke?{...Q,worktree:ke}:Q),P?.rebase_run&&s==="main"&&![bo,Aa].includes(Q.label)&&await yo(e,t),T?.inputs&&e&&ps(Ra(e),{call:"builder-pick",key:t,result:[M,M==="claude"?V:null].filter(Boolean).join(" "),reason:T.reason,inputs:{...T.inputs,...v?{askedModel:v}:{},...f?{dispatch:f}:{}}}),je&&e&&await W(e,t,"worktree-remade"),Y&&await ma(e,t,s,Q,Y,k);const ie=_===me||_===re?[]:await en(e,t,"Acted on: builder started");return e&&O&&await vr(e,t),{file:m,kind:M??null,model:V??null,reason:T?.reason??null,worktree:ke?.path??null,lines:[...N==="build"?[`kind: ${M}. ${T.reason}`]:[],...Mt(Q)?[`model: ${Mt(Q)}`]:[],...e?[`ref: ${await H(e,t)}`]:[],...ke?[`worktree: ${ke.path}`]:[],...je?[je]:[],...un.lines,...ie]}}r(Et,"startBuilder");async function oc(e,t){if(!t?.started||!t.done||!e.endsWith(".json")||g.basename(e).includes("@"))return;const{label:n,kind:a,model:i,started:o,done:s,session:c}=t,l=g.join(g.dirname(e),`${g.basename(e,".json")}@past-${Date.parse(o)}.json`);await y(l,{label:n,...a?{kind:a}:{},...i?{model:i}:{},started:o,done:s,...c?.log?{session:{log:c.log}}:{}})}r(oc,"keepPastRun");async function Rd(e,t,n,a="tap"){try{const{held:i,blockers:o}=await rc(e,t);if(i&&await Vi(e,"card-hold",{key:t,hold:!1}),o.length)return await cc(e,t,o);try{const s=await Et(e,t,{kind:"build",worktree:n,dispatch:a});return{key:t,ref:await H(e,t),kind:s.kind,...s.model?{model:s.model}:{},reason:s.reason,worktree:s.worktree}}catch(s){throw i&&await uc(e,t,i),s}}catch(i){if(!(i instanceof ue))throw i;return await W(e,t,Oa,{why:i.message}),null}}r(Rd,"startTappedBuild");async function Ed(e,t,{pr:n,conflict:a,base:i},o){const{source:s,itemFile:c,item:l}=await x(e,t);l.rebase_run={pr:n,base:i,conflict:a,at:new Date().toISOString()},await y(s.file,c);try{const u=await Et(e,t,{kind:"build",label:bo,dispatch:"hub",ownWorktree:o});return{key:t,kind:u.kind,...u.model?{model:u.model}:{},worktree:u.worktree}}catch(u){throw await yo(e,t),u}}r(Ed,"startRebase");const bo="Rebase";async function yo(e,t){const{source:n,itemFile:a,item:i}=await x(e,t);delete i.rebase_run,await y(n.file,a)}r(yo,"endRebaseRun");async function Ld(e,t){const{itemFile:n,item:a}=await x(e,t),i=se(e,n);return Me(a,i).find(o=>o.repo===i)?.number??null}r(Ld,"cardPR");async function Bd(e,t,{from:n,to:a,replayed:i}){const{source:o,itemFile:s,item:c}=await x(e,t);return c.rebase_run?(c.rebased=[...c.rebased||[],{from:n,to:a,base:c.rebase_run.base,replayed:i,at:new Date().toISOString()}],delete c.rebase_run,await y(o.file,s),!0):!1}r(Bd,"recordRebase");const sc=r((e,t,n)=>{const a=new Map((e.rebased||[]).filter(i=>i.replayed).map(i=>[i.to,i.from]));for(let i=n,o=0;i&&o<=a.size;i=a.get(i),o++)if(i===t)return!0;return!1},"onlyRebased");async function rc(e,t){const n=Fa({dir:e});ts(n)&&d(Yo(n));const{item:a}=await x(e,t),i=a.held?{held:a.held,pick_up_at:a.pick_up_at,held_at:a.held_at}:null;return i&&we(a)&&d("it's held. Unhold it, then tap Implement."),await ia(e,t)&&d("no take is picked on its prototypes, so it prototypes again. Pick a take from the next round, then tap Implement."),{held:i,blockers:await Fr(e,t,a)}}r(rc,"tapRefusals");async function Cd(e,t,n){await Je(e,t,{who:"love",by:n,command:"implement"}),await yr(e,t,{})}r(Cd,"implementAsIs");async function cc(e,t,n){const a=n.join(", ");return await he({dir:e},"card-bump",{key:t}),await W(e,t,"cant-start-yet",{names:a}),{key:t,ref:await H(e,t),bumped:n,line:`bumped: ${t} waits on ${a}, so it stays in Todo, bumped to the top`}}r(cc,"bumpBlocked");async function ln(e,t){const n=await U(e,t),a=await $(n,null);return a?.started&&!a.done&&et(a)?{file:n,record:a}:null}r(ln,"openBuild");async function xo(e,t,{cause:n,words:a,by:i,until:o}){const s=await ln(e,t);return!s||s.record.pause?!1:(await y(s.file,{...s.record,pause:{cause:n,words:a,at:new Date().toISOString(),...i?{by:i}:{},...o?{until:o}:{}}}),!0)}r(xo,"requestPause");async function lc(e,t){const n=await ln(e,t),a=n?.record.pause;if(!a||a.paused)return a??null;const i=new Date().toISOString(),o=(await z(Z(e,t))).filter(c=>c.kind==="status"&&c.phase&&!c.planner&&String(c.ts)>=String(n.record.started)).pop()?.phase,s={...a,paused:i,...o?{phase:o}:{}};return await y(n.file,{...n.record,pause:s}),await W(e,t,"paused",{phase:o,words:a.words,clear:Da[a.cause][0]}),s}r(lc,"markPaused");async function dn(e,t,{dir:n,agent:a="main"}){if(!e||n||a!=="main")return[];const i=await lc(e,t);return i?[`Paused: ${i.words}. Commit what you have now with \`git -c core.commentChar=';' commit -F <file>\`, then stop: end your turn and run nothing else. The board resumes this session, telling it so, once the pause clears.`]:[]}r(dn,"pauseReply");async function Id(e,t){const n=await ln(e,t),a=n?.record.pause;if(!a?.paused)return null;const{pause:i,...o}=n.record;return await y(n.file,o),await W(e,t,"resumed",{clear:Da[a.cause][1]}),{pause:a,record:o}}r(Id,"resumePaused");async function Td(e,t){const n=await ln(e,t);if(!n?.record.pause||n.record.pause.paused)return;const{pause:a,...i}=n.record;await y(n.file,i)}r(Td,"dropPause");async function qd(e,t,n){const a=await U(e,t),i=await $(a,null),o=new Date().toISOString();i&&!i.done&&await y(a,{...i,done:o});const{source:s,itemFile:c,item:l}=await x(e,t);l.lane==="progress"&&Ft(l,"todo",o),await y(s.file,c),await W(e,t,Oa,{why:n})}r(qd,"abandonLaunch");async function Md(e,t,[n,a],i="main"){const o=await U(e,t,void 0,i),s=await $(o,null);s&&!s.done&&await y(o,{...s,done:new Date().toISOString()}),await ut(e,t),await W(e,t,n,a)}r(Md,"abandonPlanner");async function Wd(e,t,n,a,i="main",o=null){const s=await U(e,t,void 0,i),c=await $(s,null);await y(s,{...c,session:{id:n,pid:a,log:o,at:new Date().toISOString()}})}r(Wd,"recordSession");async function Ud(e,t){const{source:n}=await x(e,t);return(await Promise.all((await G(n.dir,F(t).id)).map(i=>$(i,null)))).filter(i=>i&&i.started&&!i.done).map(i=>({pid:i.session?.pid??null,at:i.session?.at??null}))}r(Ud,"openAgents");async function Hd(e,t){const{source:n}=await x(e,t);return(await Promise.all((await G(n.dir,F(t).id)).map(i=>$(i,null)))).filter(i=>i&&i.started&&!i.done).map(i=>({kind:i.kind??null,pid:i.session?.pid??null,at:i.session?.at??null}))}r(Hd,"openRuns");async function Jd(e,t,n){const{source:a}=await x(e,t),i=new Date().toISOString();for(const o of await G(a.dir,F(t).id)){const s=await $(o,null);s?.started&&!s.done&&et(s)&&await y(o,{...s,stopped:{run:n,at:i}})}}r(Jd,"markStopped");async function zd(e,t){const{source:n,itemFile:a,item:i}=await x(e,t);i.merge_ready&&(i.merge_ready.stopped=new Date().toISOString(),await y(n.file,a))}r(zd,"stopHeldMerge");async function Kd(e,t,n){const a=S(n,"item stall --reason"),{source:i,itemFile:o,item:s}=await x(e,t);return s.lane==="done"&&d(`${await H(e,t)} is done; there is nothing to stall`),s.stalled={reason:a,at:new Date().toISOString()},await y(i.file,o),a}r(Kd,"markStalled");async function Qd(e,t){const{source:n,itemFile:a,item:i}=await x(e,t);i.stalled&&(delete i.stalled,await y(n.file,a))}r(Qd,"clearStall");async function Gd(e,t){const{item:n}=await x(e,t),a=await z(g.join(e,"data","events.jsonl")),i=r(c=>a.filter(l=>l.kind===c&&l.data?.key===t).map(l=>String(l.ts)).sort().pop()||"","latest"),o=i("card-bump");if(!o||i("card-unbump")>o)return null;const s=[n.closed_at,...De(n).map(c=>c.merged_at)].filter(Boolean).map(String).sort().pop()||"";return o>s?o:null}r(Gd,"landFirst");async function Vd(e,t,n){const{item:a}=await x(e,t);K(a)&&d(`${await H(e,t)} is done; there is nothing to bump`);const i=await he({dir:e},n?"card-bump":"card-unbump",{key:t});return(await z(g.join(e,"data","events.jsonl"))).find(o=>o.id===i).ts}r(Vd,"bumpCard");async function _o(e,t){return(await z(Z(e,t))).filter(n=>n.kind==="status").pop()?.phase==="landing"}r(_o,"isLanding");const dc=r(e=>!!e?.session&&e.session.at>(e.done??e.started),"launchedSession");async function Zd(e,t,n){const a=await $(await U(e,t),null);if(a&&!a.done)return null;const i=await Et(e,t,{kind:n,dispatch:"hub"});return{key:t,kind:n,model:i.model}}r(Zd,"startPlanner");async function Yd(e,t,n){const{source:a}=await x(e,t);if((await Promise.all((await G(a.dir,F(t).id)).map(c=>$(c,null)))).some(c=>c?.kind===me&&c.started&&!c.done))return null;const o=Qo(n);if(await $(await U(e,t,void 0,o),null))return null;const s=await Et(e,t,{kind:me,agent:o,dispatch:"hub"});return{key:t,kind:me,model:s.model,agent:o}}r(Yd,"startVisual");const ha=r(e=>typeof e=="string"&&/^[a-z][a-z0-9-]{0,29}$/.test(e)&&e!=="main"&&!e.startsWith(`${me}-`)?e:d('--name takes a short lowercase name such as tests or docs-pass: letters, digits and "-", not main or visual-\u2026'),"helperName");async function ga(e,t){const{item:n}=await x(e,t);return[(await $(await U(e,t),null))?.worktree,n.worktree].find(i=>i?.path&&de(i.path))??null}r(ga,"cardWorktree");async function Xd(e,t,{name:n,task:a,writes:i,model:o}){D(e);const s=ha(n),c=S(a,"--task");o!==void 0&&!["opus","sonnet"].includes(o)&&d("--model takes opus or sonnet");const l=Pn();o!==void 0&&l!=="auto"&&o!==l&&d(`--model ${o}: the hub's Claude model is ${l==="opus"?"Opus":"Sonnet"}. Pass --model ${l}, or no --model.`);const{item:u}=await x(e,t);K(u)&&d(`${await H(e,t)} is Done; a helper needs an open card`);const p=await U(e,t,void 0,s);return de(p)&&d(`${t} already has an agent named ${s}; pick another --name`),i&&!await ga(e,t)&&d(`a helper that writes branches from ${t}'s worktree, and the card has none; start its build first, or drop --writes`),await y(p,{label:s,kind:re,task:c,writes:!!i,...o?{model:o}:{},requested:new Date().toISOString()}),await W(e,t,"helper-asked",{agent:s,writes:i}),{lines:[`helper ${s} requested: the board launches it ${i?"once an implementer slot is free":"now"}`,`wait for it with agent wait ${t} --name ${s}`]}}r(Xd,"requestHelper");async function eu(e,t,n,a){const i=await U(e,t,void 0,n),o=await $(i,null);if(o?.kind!==re||o.started||o.done)return null;const{item:s}=await x(e,t),c=An({card:s}),l=Pn(),u=o.model??(l!=="auto"?l:c.kind==="claude"?c.model:"opus"),p=o.writes?await ga(e,t):null;o.writes&&!p&&d(`${t} has no worktree for helper ${n} to branch from`),await y(i,{...o,model:u});const w=await Et(e,t,{agent:n,kind:re,dispatch:"hub",worktree:p?({busy:f})=>a({repo:p.repo,base:p.branch,busy:f}):void 0});return{key:t,kind:re,model:u,agent:n,task:o.task,writes:o.writes,worktree:w.worktree}}r(eu,"startHelper");async function tu(e,t,n){const a=await $(await U(e,t,void 0,ha(n)),null);return a?.kind!==re&&d(`${t} has no helper named ${n}`),{record:a,card:await ga(e,t)}}r(tu,"helperOf");async function nu(e,t,{name:n,agent:a="main",timeout:i=9,every:o=2e3,alive:s}){D(e);const c=Number(i);c>0||d("--timeout takes minutes, a number above 0");const l=await U(e,t,void 0,ha(n)),u=await U(e,t,void 0,a),p=r(async f=>{const h=await $(u,null);if(!h?.started||h.done)return;const{waits:m,...k}=h;await y(u,f?{...k,waits:f}:k)},"mark"),w=Date.now()+c*6e4;await p(n);try{for(;;){const f=await $(l,null);if(f?.kind!==re&&d(`${t} has no helper named ${n}`),f.done){const m=f.writes&&f.worktree?[`branch ${f.worktree.branch} in ${f.worktree.path}: merge it with agent merge ${t} --name ${n}`]:[];return{lines:[`helper ${n} done: ${f.note??"no hand-back"}`,...m]}}const h=f.session?.pid??null;h&&!s(h)&&d(`helper ${n}'s process exited without builder done; do its task yourself`),Date.now()>=w&&d(`helper ${n} is still ${f.started?"running":f.writes?"waiting for an implementer slot":"waiting to launch"} after ${c} minutes; run agent wait again`),await new Promise(m=>setTimeout(m,o))}}finally{await p(null)}}r(nu,"waitHelper");async function au(e,t,n="main"){return n==="main"?!1:(await $(await U(e,t,void 0,n),null))?.kind===re}r(au,"isHelper");async function iu(e,t,n="main"){const a=await $(await U(e,t,void 0,n),null);return!!(a?.started&&!a.done&&qe(a))}r(iu,"isPlanner");async function ou(e,t,{file:n,title:a}){D(e);const i=S(a,"--title");(typeof n!="string"||!n.endsWith(".html"))&&d("--file takes the page, an .html file");const o=await j.readFile(g.resolve(n),"utf8").catch(()=>d(`--file ${n} can't be read`));o.trim()||d(`--file ${n} is empty`),await x(e,t);const{id:s}=F(t),c=g.join(e,"public","visuals",s);await j.mkdir(c,{recursive:!0});const l=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,60).replace(/^-+|-+$/g,"")||"visual";let u=`${l}.html`;for(let w=2;de(g.join(c,u));w++)u=`${l}-${w}.html`;await j.writeFile(g.join(c,u),o,{flag:"wx"});const p=`visuals/${s}/${u}`;return await le(Z(e,t),{ts:new Date().toISOString(),who:"claude",kind:me,text:S(i,"--name"),link:En(p,"--link")}),{lines:[p]}}r(ou,"addVisual");async function su(e){const t=[];for(const n of await q(e)){const a=await $(n.file,null);for(const i of a?.items||[]){if(K(i))continue;const o=await $(g.join(n.dir,"agents",`${i.id}.json`),null);!o?.started||o.done||!o.dispatched||qe(o)||t.push({key:`${n.slug}/${i.id}`,kind:_t(o.kind),model:o.model})}}return t}r(su,"cutOffBuilds");async function uc(e,t,n){const{source:a,itemFile:i,item:o}=await x(e,t);for(const s of Object.keys(n))n[s]===void 0?delete o[s]:o[s]=n[s];await y(a.file,i)}r(uc,"restoreHold");async function fc(e,t,n){const{source:a,itemFile:i,item:o}=await x(e,t);for(const s of["lane","lane_at","closed_at","reopened_at"])n[s]===void 0?delete o[s]:o[s]=n[s];await y(a.file,i)}r(fc,"restoreLane");async function ru(e,t){return e||d("audit reads a board: pass --site <route>"),t!==void 0&&F(t),{lines:ms(hs(Ra(e),{key:t}))}}r(ru,"auditLog");const wc=["codex","claude"];async function cu(e,t){const{item:n}=await x(e,t),{kind:a,model:i,reason:o}=An({card:n});return{lines:[`${[a,i].filter(Boolean).join(" ")}: ${o}`]}}r(cu,"pickBuilder");async function So(e,t,{dir:n}={}){const{id:a}=F(t),i=g.dirname(await U(e,t,n)),o=await G(g.dirname(i),a);return(await Promise.all(o.map(c=>$(c,null)))).filter(c=>c?.worktree?.path).sort((c,l)=>String(l.started).localeCompare(String(c.started)))[0]?.worktree??null}r(So,"recordedWorktree");async function lu(e,t){const{source:n}=await x(e,t),i=(await Promise.all((await G(n.dir,F(t).id)).map(o=>$(o,null)))).filter(o=>o?.session?.id&&o.worktree?.path).sort((o,s)=>String(s.started).localeCompare(String(o.started)))[0];return i?{id:i.session.id,worktree:i.worktree.path}:null}r(lu,"recordedSession");async function du(e,t,n,{phase:a,dir:i,agent:o="main",eta:s,clearEta:c}){s!==void 0&&c&&d("pass --eta or --clear-eta, not both");const l=$o(e,a,n,"builder progress"),u=await U(e,t,i,o),p=await $(u,null);(!p?.started||p.done)&&d(`builder progress needs an open builder record on ${t}; run builder start first`);const w=ko(l,qe(p),"builder progress");return s!==void 0&&(p.eta=mo(s,"--eta")),c&&delete p.eta,(s!==void 0||c)&&await y(u,p),await ma(e,t,o,p,w,new Date().toISOString()),{file:u,lines:await dn(e,t,{dir:i,agent:o})}}r(du,"builderProgress");async function uu(e,t){const{source:n}=await x(e,t),a=Z(e,t);if((await z(a)).filter(s=>s.kind==="status").pop()?.phase==="landing")return;const o=(await Promise.all((await G(n.dir,F(t).id)).map(s=>$(s,null)))).filter(s=>s?.started&&et(s)&&s.label!==Aa).map(s=>s.started).sort().pop();await le(a,{ts:new Date().toISOString(),who:"claude",kind:"status",phase:"landing",text:"Landing: rebasing onto main and landing",...o?{run:o}:{}})}r(uu,"landingLine");const Ve=r(e=>(e?.calls||[]).filter(t=>!e.verified||t.at>e.verified.at),"unverifiedCalls");async function fu(e,t,n,{dir:a,agent:i="main"}){const o=S(n,"builder call");/\n/.test(o)&&d("builder call takes one line; record each call on its own");const s=await U(e,t,a,i),c=await $(s,null);return(!c?.started||c.done)&&d(`builder call needs an open builder record on ${t}; run builder start first`),await y(s,{...c,calls:[...c.calls||[],{at:new Date().toISOString(),text:o}]}),{file:s,lines:await dn(e,t,{dir:a,agent:i})}}r(fu,"recordCall");async function Lt(e,t){const n=await z(Z(e,t)),a=new Map(n.filter(i=>i.kind===Tt.answer).map(i=>[i.ask,i]));return n.filter(i=>i.kind===Tt.ask).map(i=>{const o=a.get(i.ask);return{id:i.ask,agent:i.agent||"main",text:i.text,at:i.ts,answer:o?{text:o.text,at:o.ts}:null,deferred:!!o?.deferred}})}r(Lt,"builderAsks");const pc=r(e=>ge().find(t=>Pe(t.dir,e))??{dir:e},"boardTarget");async function wu(e,t,n,{agent:a="main"}){D(e);const i=S(n,"builder ask");/\n/.test(i)&&d("builder ask takes one line; ask each question on its own");const o=await $(await U(e,t,void 0,a),null);(!o?.started||o.done)&&d(`builder ask needs an open builder record on ${t}; run builder start first`);const s=`ask${(await Lt(e,t)).length+1}`;return await le(Z(e,t),{ts:new Date().toISOString(),who:`${Mt(o)||o.kind||"Claude"} builder`,kind:Tt.ask,ask:s,agent:a,text:i}),await he(pc(e),"builder-ask",{key:t,ask:s,agent:a,text:i}),{id:s,lines:await dn(e,t,{agent:a})}}r(wu,"askOrchestrator");async function pu(e,t,n,a,{deferred:i=!1}={}){D(e);const o=S(a,"--text"),s=(await Lt(e,t)).find(l=>l.id===n)||d(`no ask "${n}" on ${t}; builder asks ${t} lists them`);s.answer&&d(`${n} on ${t} is already ${s.deferred?"deferred":"answered"}`);const c=new Date().toISOString();if(await le(Z(e,t),{ts:c,who:"claude",kind:Tt.answer,ask:n,...i?{deferred:!0}:{},text:o}),i){const l=await U(e,t,void 0,s.agent),u=await $(l,null);u&&await y(l,{...u,calls:[...u.calls||[],{at:c,text:`Question: ${s.text} (deferred to the owner)`}]})}return{lines:[]}}r(pu,"answerBuilder");async function mu(e,t,{wait:n=!1,timeout:a=9,every:i=2e3}={}){D(e);const o=Number(a);o>0||d("--timeout takes minutes, a number above 0");const s=Date.now()+o*6e4;for(;;){const c=await Lt(e,t);if(!c.length)return{lines:["no asks yet"]};const l=c.filter(w=>!w.answer),u=c.flatMap(w=>[`${w.id}. ${w.text}`,` ${w.answer?`${w.deferred?"deferred":"answered"}: ${w.answer.text}`:"waiting on the orchestrator"}`]);if(!n||!l.length)return{lines:u};const p=await dn(e,t,{});if(p.length)return{lines:[...u,...p]};Date.now()>=s&&d(`${l.map(w=>w.id).join(", ")} still waiting on the orchestrator after ${o} minutes; run builder asks ${t} --wait again`),await new Promise(w=>setTimeout(w,i))}}r(mu,"listAsks");async function mc(e,t,n){const a=t.topic.startsWith("item:")&&!t.topic.startsWith("item:ask:")?t.topic.slice(5):d(`${n}.ask goes on a card's question, topic item:<file>/<id>`),i=(await Lt(e,a)).find(o=>o.id===t.ask)||d(`${n}.ask names no ask "${t.ask}" on ${a}; builder asks ${a} lists them`);i.deferred||d(`${n}.ask names ${i.id}, which the orchestrator ${i.answer?"answered":"has not deferred"}; only a deferred ask goes to the owner`)}r(mc,"checkAskQuestion");async function hu(e,t,{dir:n,agent:a="main"}){const i=await $(await U(e,t,n,a),null),o=i?.calls||[];if(!o.length)return{lines:["no judgment calls recorded"]};const{verified:s}=i,c=Ve(i).length?"not verified yet":`verified ${s.at}${s.note?`: ${s.note}`:""}`;return{lines:[...o.map((l,u)=>`${u+1}. ${l.text}`),c]}}r(hu,"listCalls");async function gu(e,t,{dir:n,agent:a="main",note:i}){const o=await U(e,t,n,a),s=await $(o,null);if(Ve(s).length||d(`${t} has no unverified judgment calls${a==="main"?"":` from agent ${a}`}; builder calls ${t} lists them`),e){const c=new Set((await $(E(e),{items:[]})).items?.filter(u=>u.topic===`item:${t}`&&u.ask).map(u=>u.ask)),l=(await Lt(e,t)).find(u=>u.deferred&&u.agent===a&&!c.has(u.id));l&&d(`${l.id} on ${t} was deferred to the owner; add its question with "ask": "${l.id}" first`)}return await y(o,{...s,verified:{at:new Date().toISOString(),...i===void 0?{}:{note:S(i,"--note")}}}),o}r(gu,"verifyCalls");async function $u(e,t){const{source:n,item:a}=await x(e,t),i=r((s,c)=>[(s.options||[]).find(l=>l.id===c.choice)?.label,c.note].filter(Boolean).join(": ")||"answered","said"),o=(await fe(e,t)).asked.filter(s=>s.ask&&s.answers.length).map(s=>({ask:s.ask,question:s.question,answer:i(s,s.answers.at(-1))}));return{key:t,ref:await H(e,t),title:a.title||t,notes:a.plan?g.join(n.dir,a.plan):null,thread:Z(e,t),worktree:(await So(e,t))?.path??null,answers:o,links:await hc(e,t),rebasePR:a.rebase_run?.pr??null,ticketQuestion:!a.ticket&&!!await sn(e)}}r($u,"briefFacts");async function hc(e,t){const n=new Map;for(const c of await q(e))for(const l of(await $(c.file,null))?.items||[])n.set(`${c.slug}/${l.id}`,{entry:c,it:l});const a=F(t).file,{it:i}=n.get(t),o=[...n].filter(([,c])=>(c.it.related||[]).some(l=>J(c.entry.slug,l)===t)).map(([c])=>c),s=[...i.parent?[["parent",J(a,i.parent)]]:[],...(i.deps||[]).map(c=>["depends on",J(a,c)]),...[...new Set([...(i.related||[]).map(c=>J(a,c)),...o])].map(c=>["related",c])].filter(([,c])=>n.has(c));return Promise.all(s.map(async([c,l])=>{const{entry:u,it:p}=n.get(l);return{relation:c,ref:await H(e,l),title:p.title||l,lane:Ce[p.lane||"todo"],notes:p.plan?g.join(u.dir,p.plan):null,thread:Z(e,l)}}))}r(hc,"cardLinks");async function ku(e){const t=[];for(const n of await q(e)){const a=await $(n.file,null);for(const i of a?.items||[]){if(K(i))continue;const o=(await Promise.all((await G(n.dir,i.id)).map(u=>$(u,null)))).filter(Boolean);if(!Sn(o))continue;const s=o.map(u=>u.verified?.at).filter(Boolean).sort().at(-1);if(!s||o.some(u=>Ve(u).length))continue;const c=`${n.slug}/${i.id}`;if((await fe(e,c)).asked.some(u=>u.state==="open")||await tn(e,c,i))continue;const l=o.filter(u=>u.worktree?.path).sort((u,p)=>String(p.started).localeCompare(String(u.started)))[0];l&&de(l.worktree.path)&&t.push({key:c,verified:s,kind:_t(l.kind),model:l.model})}}return t}r(ku,"landable");async function bu(e,t){const{source:n,item:a}=await x(e,t);(await Promise.all((await G(n.dir,a.id)).map(c=>$(c,null)))).some(c=>c?.started&&!c.done)||d(`${t} has no open builder; only a card whose lander stopped has one to relaunch`),await $e(e,t,{handBack:!0,next:"A lander relaunches to land the verified build"});const o=g.join(e,"data","landers.json"),s=await $(o,{});delete s[t],await j.writeFile(o+".tmp",JSON.stringify(s)+`
38
- `),await j.rename(o+".tmp",o)}r(bu,"relaunchLander");async function yu(e,t,{dir:n}={}){const{id:a}=F(t),i=await G(g.dirname(g.dirname(await U(e,t,n))),a),o=[];for(const s of i){if(!Ve(await $(s,null)).length)continue;const c=g.basename(s,".json").slice(String(a).length+1)||"main";o.push(c==="main"?"":` --agent ${c}`)}o.length&&d(`land: ${t} has judgment calls nobody verified yet; check them with ${o.map(s=>`builder calls ${t}${s}`).join(", ")}, then run ${o.map(s=>`builder verified ${t}${s}`).join(", ")}`)}r(yu,"checkCallsVerified");async function xu(e,t,{dir:n,agent:a="main",next:i}){const o=await $(await U(e,t,n,a),null),s=o&&!o.done?Ve(o):[];if(!s.length)return null;i!==void 0&&d(`builder done sets ${t}'s Next itself while its record has judgment calls; run it without --next`);const c=s.some(u=>u.text.startsWith("Question:"))?"Answer the builder's questions":"Verify the builder's judgment calls",l=await $e(e,t,{handBack:!0,next:c});return{lines:[`handed back: Next "${c}"`,...l.lines]}}r(xu,"handBackCalls");async function _u(e,t,{agent:n="main"}){if(n!=="main")return!1;const a=await U(e,t,void 0,n),i=await $(a,null);if(!i?.started||i.done||!i.worktree?.path)return!1;const{id:o}=F(t);for(const s of await G(g.dirname(g.dirname(a)),o)){const c=s===a?null:await $(s,null);if(!c?.started||c.done||c.kind==="install")continue;const l=g.basename(s,".json").slice(String(o).length+1);d(`builder done would finish ${t} while agent ${l} is still open; run builder done ${t} --agent ${l} first`)}return!0}r(_u,"finishesCard");async function Su(e,t){const{source:n,item:a}=await x(e,t);if(K(a))return null;const i=(await Promise.all((await G(n.dir,a.id)).map(s=>$(s,null)))).filter(Boolean);if(!Sn(i)||i.some(s=>Ve(s).length||s.started&&!s.done&&s.kind!=="install"))return null;const o=await So(e,t);return!o||!de(o.path)?null:{waits:(await fe(e,t)).asked.filter(s=>s.state==="open").map(s=>s.id)}}r(Su,"verifiedFinish");async function vu(e,t){const{item:n}=await x(e,t);if(n.reopened_at&&d(`the owner reopened ${await H(e,t)}; it closes on the owner's Done`),n.lane!=="done"||De(n).some(o=>o.merged_at))return;const a=String(n.closed_at||"");(await z(g.join(e,"data","events.jsonl"))).some(o=>o.kind==="item-message"&&o.data?.key===t&&String(o.ts)>a)&&d(`the owner reopened ${await H(e,t)} with a message; it closes on the owner's Done`)}r(vu,"checkNotReopened");async function G(e,t){const n=g.join(e,"agents");return(await j.readdir(n).catch(()=>[])).filter(a=>a===`${t}.json`||a.startsWith(`${t}@`)&&!a.startsWith(`${t}@past-`)&&a.endsWith(".json")).map(a=>g.join(n,a))}r(G,"builderFiles");async function vo(e,t,n,{handedBack:a,endHandBack:i=!1,held:o=!1}={}){const s=new Date().toISOString();for(const c of await G(e,t)){const l=await $(c,null);if(!l)continue;if(l.done||l.kind==="install"&&!n){if(i&&l.handed_back){const{handed_back:f,...h}=l;await y(c,h)}continue}if(o&&l.pause)continue;const{eta:u,handed_back:p,...w}=l;await y(c,{...w,done:s,...a?{handed_back:a}:{},...o&&l.started?{hold_stopped:!0}:{}})}}r(vo,"closeBuilders");async function ju(e,t){const n=await U(e,t),a=await $(n,null);if(!a?.hold_stopped)return null;const{hold_stopped:i,...o}=a;return await y(n,o),{kind:a.kind??null,label:a.label??null}}r(ju,"takeHoldStopped");async function gc(e,t,{dir:n,agent:a,startedBetween:i,note:o,next:s,requireNext:c=!1}){const l=await U(e,t,n,a),u=await $(l,null);if(!u||u.done)return l;if(i){const I=Date.parse(u.started);if(!(I>=i[0]&&I<=i[1]))return l}const{eta:p,...w}=u,f=new Date().toISOString(),h={...w,done:f,...o?{note:o}:{}},{id:m}=F(t),k=g.dirname(g.dirname(l)),_=await Promise.all((await G(k,m)).map(I=>I===l?h:$(I,null))),N=!_.some(I=>I?.started&&!I.done),v=n?{file:g.join(k,"wave.json")}:(await x(e,t)).source,O=await $(v.file,null),A=O?.items?.find(I=>I.id===m);return s!==void 0&&(Li(A||d(`${t} has no item to set --next on`),s,await aa(e,t)),e&&await Hi(e,t,A,A.next)),c&&A&&vn(A,_)&&d(`builder done closes ${t}'s last open builder, which leaves it In Progress with no Next; pass --next "<what happens next>", or record a judgment call with builder call ${t} or land`),await y(l,h),await ut(e,t,{screen:u.kind==="grill"}),o&&await ma(e,t,a,u,{detail:o},f),s!==void 0&&await y(v.file,O),l}r(gc,"stopBuilder");async function $c(e){const t=[];for(const n of await q(e)){const a=await $(n.file,null);for(const i of a?.items||[])for(const o of await G(n.dir,i.id)){const s=await $(o,null);if(!s?.started||s.done)continue;const c=g.basename(o,".json");t.push({key:`${n.slug}/${i.id}`,agent:c.slice(String(i.id).length+1)||"main",label:s.label||"Builder",started:s.started})}}return t}r($c,"openBoardBuilders");async function Ou(e){const t=await $c(e);for(const n of t)await gc(e,n.key,{agent:n.agent,note:"Board closed. Builder record stopped; work is kept for reopening."});return t}r(Ou,"closeBoardBuilders");export{ue as BoardError,Ja as PUSH_LINE_MAX,Jt as REPLY_EXTS,Ts as SCREEN_AFTER,In as UPLOAD_LIMIT,tl as WORKING_KINDS,qd as abandonLaunch,Md as abandonPlanner,kl as ackPing,bd as addItem,Yl as addNotes,Ul as addPrototype,Kl as addQuestions,Dl as addReviewers,Il as addRuleTo,Wl as addTopic,ou as addVisual,pu as answerBuilder,wl as answerCard,rt as appendMessage,W as appendStatus,jd as archiveCards,vd as archiveCount,rn as archiveFile,cn as archiveRank,wu as askOrchestrator,rd as askedGate,ru as auditLog,tn as blockWords,oe as boardConfig,se as boardRepoOf,wd as breakOwnerCheck,$u as briefFacts,kd as builderModel,du as builderProgress,Vd as bumpCard,Al as cardLinked,H as cardName,Ld as cardPR,Dd as changeWave,yu as checkCallsVerified,sd as checkClose,vu as checkNotReopened,Qd as clearStall,Ou as closeBoardBuilders,Pd as createWave,su as cutOffBuilds,fl as dropAskCard,Td as dropPause,Tl as editRuleIn,cl as eventCard,Ll as fallBackFromLinear,ll as fileAsk,dl as fileAsks,bl as finishHandshake,Fd as finishWave,_u as finishesCard,xu as handBackCalls,gd as heldMerge,tu as helperOf,za as hiddenFile,Cd as implementAsIs,ld as isFinished,au as isHelper,_o as isLanding,iu as isPlanner,q as itemSources,Gd as landFirst,ku as landable,uu as landingLine,mu as listAsks,hu as listCalls,Hl as listPrototypes,Cl as listRules,lc as markPaused,ol as markRead,Kd as markStalled,Jd as markStopped,nl as markWorking,hd as mergeCard,Tr as mergedLine,zt as messageText,yd as migrateFollowups,_d as migratePhases,xd as migrateStatuses,Ad as migrateWaveNames,hl as moveAsk,cd as moveCard,ad as moveQuestions,Ud as openAgents,$c as openBoardBuilders,Hd as openRuns,El as opensPRs,F as parseKey,fd as passOwnerCheck,cu as pickBuilder,ud as pickUp,td as planAgain,Pl as postDigest,$l as postIncomingReview,xl as postLink,md as postPR,_l as postReply,pd as prReport,Gl as publishScreened,Vl as publishUnscreened,Gs as pushLine,Vs as pushUrl,vl as queuePushes,Le as readArchive,_e as readAskLinks,Kn as readBoardRules,or as readBoardSettings,di as readHandshake,Ys as readHidden,$ as readJSON,Xs as readMarks,Qa as readMarksFile,Ir as readNotes,Qt as readPRSlack,Pt as readPrototypes,xi as readScreening,rl as readUpload,Nd as readWaveNotes,Ws as readWorking,fu as recordCall,Vi as recordOwnerTap,Hs as recordPush,Sl as recordReaction,Bd as recordRebase,gl as recordReview,Wd as recordSession,lu as recordedSession,So as recordedWorktree,pl as relateAsk,bu as relaunchLander,zl as removePrototype,Fl as removeReviewers,ql as removeRuleFrom,Us as repliesSincePush,Ln as replyFilesOf,Xd as requestHelper,xo as requestPause,id as resolveNoteAnswers,nd as resolveQuestion,Id as resumePaused,ul as retitleAskCard,ar as reviewDigest,jl as reviewDue,Ol as reviewUpdated,Ml as saveBoardRules,lt as saveBoardSettings,Nl as saveBoardShare,sl as saveUpload,al as sendPush,Jl as servedRoundsOpen,Rl as setBoardPause,Bl as setBoardSetting,il as setHidden,$e as setItem,dd as setMainInstall,yl as setReviewers,sr as settingsLines,Se as settingsOf,Zl as settleAnswers,Ql as settleQuestion,Xc as siteDir,Is as sitesDir,Xl as splitSharedNotes,yr as stageImplement,Sd as stageImplementAsks,ed as stageReply,Et as startBuilder,eu as startHelper,Zd as startPlanner,Ed as startRebase,Rd as startTappedBuild,Yd as startVisual,gc as stopBuilder,zd as stopHeldMerge,Od as stripDeadFields,Zn as takeFile,ju as takeHoldStopped,$d as tapMerge,Z as threadFile,Ri as topicQuestions,ml as unfoldAsk,od as unrecorded,Su as verifiedFinish,gu as verifyCalls,nu as waitHelper,ua as waveNoteFile,Ut as wavesDir,Qs as withReplies,el as writeReply};
38
+ ${s}`}}c(uu,"readWaveNotes");async function U(t,e,n,a="main"){const{id:i}=R(e);/^[\w-]{1,40}$/.test(a)||d(`--agent takes a name of letters, digits, "_" and "-", not "${a}"`);const o=a==="main"?`${i}.json`:`${i}@${a}.json`;if(n)return $.join($.resolve(n),"agents",o);const{source:s}=await x(t,e);return $.join(s.dir,"agents",o)}c(U,"builderFile");const No=c((t,e)=>typeof t=="string"&&/^\d{4}-\d\d-\d\dT/.test(t)&&!Number.isNaN(Date.parse(t))?new Date(t).toISOString():d(`${e} takes an ISO time such as 2026-10-23T16:30:00-07:00`),"isoTime"),Dc=Pn.progress,Eo=80,Lo="reading, building, testing, checking or landing";function Bo(t,e,n,a){t||d(`${a} needs --site, since the line goes to the item's thread`),e!==void 0&&!Dc.includes(e)&&d(`--phase takes ${Lo}, not "${e}"`);const i=j(n,a);return i.length>Eo&&d(`${a} is ${i.length} characters; the cap is ${Eo}. Say it shorter.`),{phase:e,detail:i}}c(Bo,"progressLine");const Co=c((t,e,n)=>e?{detail:t.detail}:(t.phase===void 0&&d(`${n} needs --phase ${Lo}`),t),"forAgent");async function va(t,e,n="main",a,{phase:i,detail:o},s){const r=Ut(a),l=r||n==="main"?"":a.kind===X?n:Ge(a)||a.kind||n,u=r?ds[a.kind]:[l,i].filter(Boolean).join(" "),p=new RegExp(`^(?:${u}|${i??u})\\s*:?\\s+`,"i"),w=u?`${u[0].toUpperCase()}${u.slice(1)}: ${o.replace(p,"")}`:o,f=Z(t,e);(await J(f)).filter(h=>h.kind==="status").pop()?.text!==w&&await dt(f,{ts:s,who:"claude",kind:"status",run:a.started,...i?{phase:i}:{},...r?{planner:!0}:{},text:w})}c(va,"statusToThread");const Fc={prototype:"sonnet",grill:"opus",[gt]:"sonnet"};async function Me(t,e,{label:n,phase:a,progress:i,dir:o,agent:s="main",kind:r,model:l,eta:u,worktree:p,ownWorktree:w,dispatch:f}){a!==void 0&&i===void 0&&d('--phase goes with --progress "<detail>"');const h=it(i,nt=>Bo(t,a,nt,"--progress")),m=await U(t,e,o,s),y=new Date().toISOString(),_=it(r,nt=>/^[\w.-]{1,30}$/.test(nt)?nt:d("--kind takes a short word such as claude or codex")),P=Oe(_),S=l??(_==="opus"||_==="sonnet"?_:void 0),v=["build",...qc].includes(P),F=await g(m,null),I=c(nt=>["tap","hub"].includes(nt?.dispatched)&&!nt.done,"tapOpen");if(f==="session"&&I(F))return{file:m,alreadyOpen:!0,lines:[]};s!=="main"&&_!==gt&&_!==X&&I(await g(await U(t,e,o),null))&&d(`the Implement tap opened ${e}'s main builder record and no agent has taken it up; run builder start ${e} without --agent first`);const M=F?.dispatched&&!F.done?F:null,O=v&&!o?(await x(t,e)).item:void 0,L=F&&ne(F).length?F:null,C=M&&P==="build"?{kind:Oe(M.kind),model:M.model,reason:{tap:"The owner's Build tap picked it.",hub:"The board's pull picked it."}[M.dispatched]??"The session's dispatch picked it."}:v?En({card:O??{}}):null;C&&P!=="build"&&P!==C.kind&&d(`--kind ${P}: ${C.kind} builds now. ${C.reason} Pass --kind ${C.kind}, or --kind build.`);const T=C?C.kind:P,ot=Ha({dir:t});if(!(M&&!f)&&ks(ot,T))throw new pt($s(ot,T));const N=h&&Co(h,Ut({kind:T}),"--progress");l!==void 0&&!["opus","sonnet"].includes(l)&&d("--model takes opus or sonnet"),S!==void 0&&T==="codex"&&d("--model is for kind claude; codex needs none");const H=T==="claude"?Ln():"auto";S!==void 0&&H!=="auto"&&S!==H&&d(`--model ${S}: the hub's Claude model is ${H==="opus"?"Opus":"Sonnet"}. Pass --model ${H}, or no --model.`);const tt=T==="claude"?S??C?.model??(M&&Oe(M.kind)==="claude"?M.model:void 0)??"opus":Ut({kind:T})?S??(M?.kind===T?M.model:void 0)??Fc[T]:T===X?S??F?.model:void 0,Q={label:n===void 0?"Builder":j(n,"--label"),...T?{kind:T}:{},...tt?{model:tt}:{},started:y,...u===void 0?{}:{eta:No(u,"--eta")},...f?{dispatched:f}:{},...L?{calls:L.calls,...L.verified?{verified:L.verified}:{}}:{},...Cc(F)?{session:F.session}:{},...T===X&&F?.kind===X?{label:F.label,task:F.task,writes:F.writes,requested:F.requested}:{}},xt=v&&!o&&!G(O)&&O.lane!=="progress",_t=xt?await bt(t,e,{start:!0}):{lines:[]};let Y,Pt=null;const Ue=w&&v&&s==="main"?[F?.worktree,O?.worktree].find(nt=>nt?.path&&wt(nt.path))??null:null,ke=(M??L)?.worktree??Ue,ye=p??(v&&s==="main"&&!ke?w:void 0);try{if(ye){const nt=await V($.dirname($.dirname(m)),R(e).id),$n=(await Promise.all(nt.filter(ht=>ht!==m).map(ht=>g(ht,null)))).filter(ht=>ht?.worktree?.path&&!ht.done).map(ht=>ht.worktree.path);({remade:Pt,...Y}=await ye({busy:$n}))}else Y=ke}catch(nt){throw xt&&await Tc(t,e,O),nt}await Rc(m,F),await b(m,Y?{...Q,worktree:Y}:Q),O?.rebase_run&&s==="main"&&![Io,Ma].includes(Q.label)&&await To(t,e),C?.inputs&&t&&Ns(za(t),{call:"builder-pick",key:e,result:[T,T==="claude"?tt:null].filter(Boolean).join(" "),reason:C.reason,inputs:{...C.inputs,...S?{askedModel:S}:{},...f?{dispatch:f}:{}}}),Pt&&t&&await W(t,e,"worktree-remade"),N&&await va(t,e,s,Q,N,y);const st=_===gt||_===X?[]:await cn(t,e,"Acted on: builder started");return t&&v&&await Vr(t,e),{file:m,kind:T??null,model:tt??null,reason:C?.reason??null,worktree:Y?.path??null,lines:[...P==="build"?[`kind: ${T}. ${C.reason}`]:[],...Ge(Q)?[`model: ${Ge(Q)}`]:[],...t?[`ref: ${await K(t,e)}`]:[],...Y?[`worktree: ${Y.path}`]:[],...Pt?[Pt]:[],..._t.lines,...st]}}c(Me,"startBuilder");async function Rc(t,e){if(!e?.started||!e.done||!t.endsWith(".json")||$.basename(t).includes("@"))return;const{label:n,kind:a,model:i,started:o,done:s,session:r}=e,l=$.join($.dirname(t),`${$.basename(t,".json")}@past-${Date.parse(o)}.json`);await b(l,{label:n,...a?{kind:a}:{},...i?{model:i}:{},started:o,done:s,...r?.log?{session:{log:r.log}}:{}})}c(Rc,"keepPastRun");async function fu(t,e,n,a="tap"){try{const{held:i,blockers:o}=await Ec(t,e);if(i&&await ho(t,"card-hold",{key:e,hold:!1}),o.length)return await Lc(t,e,o);try{const s=await Me(t,e,{kind:"build",worktree:n,dispatch:a});return{key:e,ref:await K(t,e),kind:s.kind,...s.model?{model:s.model}:{},reason:s.reason,worktree:s.worktree}}catch(s){throw i&&await Ic(t,e,i),s}}catch(i){if(!(i instanceof pt))throw i;return await W(t,e,qa,{why:i.message}),null}}c(fu,"startTappedBuild");async function wu(t,e,{pr:n,conflict:a,base:i},o){const{source:s,itemFile:r,item:l}=await x(t,e);l.rebase_run={pr:n,base:i,conflict:a,at:new Date().toISOString()},await b(s.file,r);try{const u=await Me(t,e,{kind:"build",label:Io,dispatch:"hub",ownWorktree:o});return{key:e,kind:u.kind,...u.model?{model:u.model}:{},worktree:u.worktree}}catch(u){throw await To(t,e),u}}c(wu,"startRebase");const Io="Rebase";async function To(t,e){const{source:n,itemFile:a,item:i}=await x(t,e);delete i.rebase_run,await b(n.file,a)}c(To,"endRebaseRun");async function pu(t,e){const{itemFile:n,item:a}=await x(t,e),i=ct(t,n);return Ht(a,i).find(o=>o.repo===i)?.number??null}c(pu,"cardPR");async function mu(t,e,{from:n,to:a,replayed:i}){const{source:o,itemFile:s,item:r}=await x(t,e);return r.rebase_run?(r.rebased=[...r.rebased||[],{from:n,to:a,base:r.rebase_run.base,replayed:i,at:new Date().toISOString()}],delete r.rebase_run,await b(o.file,s),!0):!1}c(mu,"recordRebase");const Nc=c((t,e,n)=>{const a=new Map((t.rebased||[]).filter(i=>i.replayed).map(i=>[i.to,i.from]));for(let i=n,o=0;i&&o<=a.size;i=a.get(i),o++)if(i===e)return!0;return!1},"onlyRebased");async function Ec(t,e){const n=Ha({dir:t});ys(n)&&d(gs(n));const{item:a}=await x(t,e),i=a.held?{held:a.held,pick_up_at:a.pick_up_at,held_at:a.held_at}:null;return i&&mt(a)&&d("it's held. Unhold it, then tap Implement."),await wa(t,e)&&d("no take is picked on its prototypes, so it prototypes again. Pick a take from the next round, then tap Implement."),{held:i,blockers:await nc(t,e,a)}}c(Ec,"tapRefusals");async function hu(t,e,n){await Qt(t,e,{who:"love",by:n,command:"implement"}),await zr(t,e,{})}c(hu,"implementAsIs");async function Lc(t,e,n){const a=n.join(", ");return await $t({dir:t},"card-bump",{key:e}),await W(t,e,"cant-start-yet",{names:a}),{key:e,ref:await K(t,e),bumped:n,line:`bumped: ${e} waits on ${a}, so it stays in Todo, bumped to the top`}}c(Lc,"bumpBlocked");async function hn(t,e){const n=await U(t,e),a=await g(n,null);return a?.started&&!a.done&&oe(a)?{file:n,record:a}:null}c(hn,"openBuild");async function qo(t,e,{cause:n,words:a,by:i,until:o}){const s=await hn(t,e);return!s||s.record.pause?!1:(await b(s.file,{...s.record,pause:{cause:n,words:a,at:new Date().toISOString(),...i?{by:i}:{},...o?{until:o}:{}}}),!0)}c(qo,"requestPause");async function Bc(t,e){const n=await hn(t,e),a=n?.record.pause;if(!a||a.paused)return a??null;const i=new Date().toISOString(),o=(await J(Z(t,e))).filter(r=>r.kind==="status"&&r.phase&&!r.planner&&String(r.ts)>=String(n.record.started)).pop()?.phase,s={...a,paused:i,...o?{phase:o}:{}};return await b(n.file,{...n.record,pause:s}),await W(t,e,"paused",{phase:o,words:a.words,clear:Ua[a.cause][0]}),s}c(Bc,"markPaused");async function gn(t,e,{dir:n,agent:a="main"}){if(!t||n||a!=="main")return[];const i=await Bc(t,e);return i?[`Paused: ${i.words}. Commit what you have now with \`git -c core.commentChar=';' commit -F <file>\`, then stop: end your turn and run nothing else. The board resumes this session, telling it so, once the pause clears.`]:[]}c(gn,"pauseReply");async function gu(t,e){const n=await hn(t,e),a=n?.record.pause;if(!a?.paused)return null;const{pause:i,...o}=n.record;return await b(n.file,o),await W(t,e,"resumed",{clear:Ua[a.cause][1]}),{pause:a,record:o}}c(gu,"resumePaused");async function $u(t,e){const n=await hn(t,e);if(!n?.record.pause||n.record.pause.paused)return;const{pause:a,...i}=n.record;await b(n.file,i)}c($u,"dropPause");async function ku(t,e,n){const a=await U(t,e),i=await g(a,null),o=new Date().toISOString();i&&!i.done&&await b(a,{...i,done:o});const{source:s,itemFile:r,item:l}=await x(t,e);l.lane==="progress"&&Ie(l,"todo",o),await b(s.file,r),await W(t,e,qa,{why:n})}c(ku,"abandonLaunch");async function yu(t,e,[n,a],i="main"){const o=await U(t,e,void 0,i),s=await g(o,null);s&&!s.done&&await b(o,{...s,done:new Date().toISOString()}),await pe(t,e),await W(t,e,n,a)}c(yu,"abandonPlanner");async function bu(t,e,n,a,i="main",o=null){const s=await U(t,e,void 0,i),r=await g(s,null);await b(s,{...r,session:{id:n,pid:a,log:o,at:new Date().toISOString()}})}c(bu,"recordSession");async function xu(t,e){const{source:n}=await x(t,e);return(await Promise.all((await V(n.dir,R(e).id)).map(i=>g(i,null)))).filter(i=>i&&i.started&&!i.done).map(i=>({pid:i.session?.pid??null,at:i.session?.at??null}))}c(xu,"openAgents");async function _u(t,e){const{source:n}=await x(t,e);return(await Promise.all((await V(n.dir,R(e).id)).map(i=>g(i,null)))).filter(i=>i&&i.started&&!i.done).map(i=>({kind:i.kind??null,pid:i.session?.pid??null,at:i.session?.at??null}))}c(_u,"openRuns");async function Su(t,e,n){const{source:a}=await x(t,e),i=new Date().toISOString();for(const o of await V(a.dir,R(e).id)){const s=await g(o,null);s?.started&&!s.done&&oe(s)&&await b(o,{...s,stopped:{run:n,at:i}})}}c(Su,"markStopped");async function vu(t,e){const{source:n,itemFile:a,item:i}=await x(t,e);i.merge_ready&&(i.merge_ready.stopped=new Date().toISOString(),await b(n.file,a))}c(vu,"stopHeldMerge");async function ju(t,e,n){const a=j(n,"item stall --reason"),{source:i,itemFile:o,item:s}=await x(t,e);return s.lane==="done"&&d(`${await K(t,e)} is done; there is nothing to stall`),s.stalled={reason:a,at:new Date().toISOString()},await b(i.file,o),a}c(ju,"markStalled");async function Ou(t,e){const{source:n,itemFile:a,item:i}=await x(t,e);i.stalled&&(delete i.stalled,await b(n.file,a))}c(Ou,"clearStall");async function Au(t,e){const{item:n}=await x(t,e),a=await J($.join(t,"data","events.jsonl")),i=c(r=>a.filter(l=>l.kind===r&&l.data?.key===e).map(l=>String(l.ts)).sort().pop()||"","latest"),o=i("card-bump");if(!o||i("card-unbump")>o)return null;const s=[n.closed_at,...Et(n).map(r=>r.merged_at)].filter(Boolean).map(String).sort().pop()||"";return o>s?o:null}c(Au,"landFirst");async function Pu(t,e,n){const{item:a}=await x(t,e);G(a)&&d(`${await K(t,e)} is done; there is nothing to bump`);const i=await $t({dir:t},n?"card-bump":"card-unbump",{key:e});return(await J($.join(t,"data","events.jsonl"))).find(o=>o.id===i).ts}c(Pu,"bumpCard");async function Mo(t,e){return(await J(Z(t,e))).filter(n=>n.kind==="status").pop()?.phase==="landing"}c(Mo,"isLanding");const Cc=c(t=>!!t?.session&&t.session.at>(t.done??t.started),"launchedSession");async function Du(t,e,n){const a=await g(await U(t,e),null);if(a&&!a.done)return null;const i=await Me(t,e,{kind:n,dispatch:"hub"});return{key:e,kind:n,model:i.model}}c(Du,"startPlanner");async function Fu(t,e,n){const{source:a}=await x(t,e);if((await Promise.all((await V(a.dir,R(e).id)).map(r=>g(r,null)))).some(r=>r?.kind===gt&&r.started&&!r.done))return null;const o=ws(n);if(await g(await U(t,e,void 0,o),null))return null;const s=await Me(t,e,{kind:gt,agent:o,dispatch:"hub"});return{key:e,kind:gt,model:s.model,agent:o}}c(Fu,"startVisual");const ja=c(t=>typeof t=="string"&&/^[a-z][a-z0-9-]{0,29}$/.test(t)&&t!=="main"&&!t.startsWith(`${gt}-`)?t:d('--name takes a short lowercase name such as tests or docs-pass: letters, digits and "-", not main or visual-\u2026'),"helperName");async function Oa(t,e){const{item:n}=await x(t,e);return[(await g(await U(t,e),null))?.worktree,n.worktree].find(i=>i?.path&&wt(i.path))??null}c(Oa,"cardWorktree");async function Ru(t,e,{name:n,task:a,writes:i,model:o}){D(t);const s=ja(n),r=j(a,"--task");o!==void 0&&!["opus","sonnet"].includes(o)&&d("--model takes opus or sonnet");const l=Ln();o!==void 0&&l!=="auto"&&o!==l&&d(`--model ${o}: the hub's Claude model is ${l==="opus"?"Opus":"Sonnet"}. Pass --model ${l}, or no --model.`);const{item:u}=await x(t,e);G(u)&&d(`${await K(t,e)} is Done; a helper needs an open card`);const p=await U(t,e,void 0,s);return wt(p)&&d(`${e} already has an agent named ${s}; pick another --name`),i&&!await Oa(t,e)&&d(`a helper that writes branches from ${e}'s worktree, and the card has none; start its build first, or drop --writes`),await b(p,{label:s,kind:X,task:r,writes:!!i,...o?{model:o}:{},requested:new Date().toISOString()}),await W(t,e,"helper-asked",{agent:s,writes:i}),{lines:[`helper ${s} requested: the board launches it ${i?"once an implementer slot is free":"now"}`,`wait for it with agent wait ${e} --name ${s}`]}}c(Ru,"requestHelper");async function Nu(t,e,n,a){const i=await U(t,e,void 0,n),o=await g(i,null);if(o?.kind!==X||o.started||o.done)return null;const{item:s}=await x(t,e),r=En({card:s}),l=Ln(),u=o.model??(l!=="auto"?l:r.kind==="claude"?r.model:"opus"),p=o.writes?await Oa(t,e):null;o.writes&&!p&&d(`${e} has no worktree for helper ${n} to branch from`),await b(i,{...o,model:u});const w=await Me(t,e,{agent:n,kind:X,dispatch:"hub",worktree:p?({busy:f})=>a({repo:p.repo,base:p.branch,busy:f}):void 0});return{key:e,kind:X,model:u,agent:n,task:o.task,writes:o.writes,worktree:w.worktree}}c(Nu,"startHelper");async function Eu(t,e,n){const a=await g(await U(t,e,void 0,ja(n)),null);return a?.kind!==X&&d(`${e} has no helper named ${n}`),{record:a,card:await Oa(t,e)}}c(Eu,"helperOf");async function Lu(t,e,{name:n,agent:a="main",timeout:i=9,every:o=2e3,alive:s}){D(t);const r=Number(i);r>0||d("--timeout takes minutes, a number above 0");const l=await U(t,e,void 0,ja(n)),u=await U(t,e,void 0,a),p=c(async f=>{const h=await g(u,null);if(!h?.started||h.done)return;const{waits:m,...y}=h;await b(u,f?{...y,waits:f}:y)},"mark"),w=Date.now()+r*6e4;await p(n);try{for(;;){const f=await g(l,null);if(f?.kind!==X&&d(`${e} has no helper named ${n}`),f.done){const m=f.writes&&f.worktree?[`branch ${f.worktree.branch} in ${f.worktree.path}: merge it with agent merge ${e} --name ${n}`]:[];return{lines:[`helper ${n} done: ${f.note??"no hand-back"}`,...m]}}const h=f.session?.pid??null;h&&!s(h)&&d(`helper ${n}'s process exited without builder done; do its task yourself`),Date.now()>=w&&d(`helper ${n} is still ${f.started?"running":f.writes?"waiting for an implementer slot":"waiting to launch"} after ${r} minutes; run agent wait again`),await new Promise(m=>setTimeout(m,o))}}finally{await p(null)}}c(Lu,"waitHelper");async function Bu(t,e,n="main"){return n==="main"?!1:(await g(await U(t,e,void 0,n),null))?.kind===X}c(Bu,"isHelper");async function Cu(t,e,n="main"){const a=await g(await U(t,e,void 0,n),null);return!!(a?.started&&!a.done&&Ut(a))}c(Cu,"isPlanner");async function Iu(t,e,{file:n,title:a}){D(t);const i=j(a,"--title");(typeof n!="string"||!n.endsWith(".html"))&&d("--file takes the page, an .html file");const o=await A.readFile($.resolve(n),"utf8").catch(()=>d(`--file ${n} can't be read`));o.trim()||d(`--file ${n} is empty`),await x(t,e);const{id:s}=R(e),r=$.join(t,"public","visuals",s);await A.mkdir(r,{recursive:!0});const l=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,60).replace(/^-+|-+$/g,"")||"visual";let u=`${l}.html`;for(let w=2;wt($.join(r,u));w++)u=`${l}-${w}.html`;await A.writeFile($.join(r,u),o,{flag:"wx"});const p=`visuals/${s}/${u}`;return await dt(Z(t,e),{ts:new Date().toISOString(),who:"claude",kind:gt,text:j(i,"--name"),link:Wn(p,"--link")}),{lines:[p]}}c(Iu,"addVisual");async function Tu(t){const e=[];for(const n of await q(t)){const a=await g(n.file,null);for(const i of a?.items||[]){if(G(i))continue;const o=await g($.join(n.dir,"agents",`${i.id}.json`),null);!o?.started||o.done||!o.dispatched||Ut(o)||e.push({key:`${n.slug}/${i.id}`,kind:Oe(o.kind),model:o.model})}}return e}c(Tu,"cutOffBuilds");async function Ic(t,e,n){const{source:a,itemFile:i,item:o}=await x(t,e);for(const s of Object.keys(n))n[s]===void 0?delete o[s]:o[s]=n[s];await b(a.file,i)}c(Ic,"restoreHold");async function Tc(t,e,n){const{source:a,itemFile:i,item:o}=await x(t,e);for(const s of["lane","lane_at","closed_at","reopened_at"])n[s]===void 0?delete o[s]:o[s]=n[s];await b(a.file,i)}c(Tc,"restoreLane");async function qu(t,e){return t||d("audit reads a board: pass --site <route>"),e!==void 0&&R(e),{lines:Es(Ls(za(t),{key:e}))}}c(qu,"auditLog");const qc=["codex","claude"];async function Mu(t,e){const{item:n}=await x(t,e),{kind:a,model:i,reason:o}=En({card:n});return{lines:[`${[a,i].filter(Boolean).join(" ")}: ${o}`]}}c(Mu,"pickBuilder");async function Wo(t,e,{dir:n}={}){const{id:a}=R(e),i=$.dirname(await U(t,e,n)),o=await V($.dirname(i),a);return(await Promise.all(o.map(r=>g(r,null)))).filter(r=>r?.worktree?.path&&r.kind!==X).sort((r,l)=>String(l.started).localeCompare(String(r.started)))[0]?.worktree??null}c(Wo,"recordedWorktree");async function Wu(t,e){const{source:n}=await x(t,e),i=(await Promise.all((await V(n.dir,R(e).id)).map(o=>g(o,null)))).filter(o=>o?.session?.id&&o.worktree?.path&&o.kind!==X).sort((o,s)=>String(s.started).localeCompare(String(o.started)))[0];return i?{id:i.session.id,worktree:i.worktree.path}:null}c(Wu,"recordedSession");async function Uu(t,e,n,{phase:a,dir:i,agent:o="main",eta:s,clearEta:r}){s!==void 0&&r&&d("pass --eta or --clear-eta, not both");const l=Bo(t,a,n,"builder progress"),u=await U(t,e,i,o),p=await g(u,null);(!p?.started||p.done)&&d(`builder progress needs an open builder record on ${e}; run builder start first`);const w=Co(l,Ut(p),"builder progress");return s!==void 0&&(p.eta=No(s,"--eta")),r&&delete p.eta,(s!==void 0||r)&&await b(u,p),await va(t,e,o,p,w,new Date().toISOString()),{file:u,lines:await gn(t,e,{dir:i,agent:o})}}c(Uu,"builderProgress");async function Hu(t,e){const{source:n}=await x(t,e),a=Z(t,e);if((await J(a)).filter(s=>s.kind==="status").pop()?.phase==="landing")return;const o=(await Promise.all((await V(n.dir,R(e).id)).map(s=>g(s,null)))).filter(s=>s?.started&&oe(s)&&s.label!==Ma).map(s=>s.started).sort().pop();await dt(a,{ts:new Date().toISOString(),who:"claude",kind:"status",phase:"landing",text:"Landing: rebasing onto main and landing",...o?{run:o}:{}})}c(Hu,"landingLine");const ne=c(t=>(t?.calls||[]).filter(e=>!t.verified||e.at>t.verified.at),"unverifiedCalls");async function Ju(t,e,n,{dir:a,agent:i="main"}){const o=j(n,"builder call");/\n/.test(o)&&d("builder call takes one line; record each call on its own");const s=await U(t,e,a,i),r=await g(s,null);return(!r?.started||r.done)&&d(`builder call needs an open builder record on ${e}; run builder start first`),await b(s,{...r,calls:[...r.calls||[],{at:new Date().toISOString(),text:o}]}),{file:s,lines:await gn(t,e,{dir:a,agent:i})}}c(Ju,"recordCall");async function We(t,e){const n=await J(Z(t,e)),a=new Map(n.filter(i=>i.kind===Ke.answer).map(i=>[i.ask,i]));return n.filter(i=>i.kind===Ke.ask).map(i=>{const o=a.get(i.ask);return{id:i.ask,agent:i.agent||"main",text:i.text,at:i.ts,answer:o?{text:o.text,at:o.ts}:null,deferred:!!o?.deferred}})}c(We,"builderAsks");const Mc=c(t=>kt().find(e=>Rt(e.dir,t))??{dir:t},"boardTarget");async function Ku(t,e,n,{agent:a="main"}){D(t);const i=j(n,"builder ask");/\n/.test(i)&&d("builder ask takes one line; ask each question on its own");const o=await g(await U(t,e,void 0,a),null);(!o?.started||o.done)&&d(`builder ask needs an open builder record on ${e}; run builder start first`);const s=`ask${(await We(t,e)).length+1}`;return await dt(Z(t,e),{ts:new Date().toISOString(),who:`${Ge(o)||o.kind||"Claude"} builder`,kind:Ke.ask,ask:s,agent:a,text:i}),await $t(Mc(t),"builder-ask",{key:e,ask:s,agent:a,text:i}),{id:s,lines:await gn(t,e,{agent:a})}}c(Ku,"askOrchestrator");async function zu(t,e,n,a,{deferred:i=!1}={}){D(t);const o=j(a,"--text"),s=(await We(t,e)).find(l=>l.id===n)||d(`no ask "${n}" on ${e}; builder asks ${e} lists them`);s.answer&&d(`${n} on ${e} is already ${s.deferred?"deferred":"answered"}`);const r=new Date().toISOString();if(await dt(Z(t,e),{ts:r,who:"claude",kind:Ke.answer,ask:n,...i?{deferred:!0}:{},text:o}),i){const l=await U(t,e,void 0,s.agent),u=await g(l,null);u&&await b(l,{...u,calls:[...u.calls||[],{at:r,text:`Question: ${s.text} (deferred to the owner)`}]})}return{lines:[]}}c(zu,"answerBuilder");async function Gu(t,e,{wait:n=!1,timeout:a=9,every:i=2e3}={}){D(t);const o=Number(a);o>0||d("--timeout takes minutes, a number above 0");const s=Date.now()+o*6e4;for(;;){const r=await We(t,e);if(!r.length)return{lines:["no asks yet"]};const l=r.filter(w=>!w.answer),u=r.flatMap(w=>[`${w.id}. ${w.text}`,` ${w.answer?`${w.deferred?"deferred":"answered"}: ${w.answer.text}`:"waiting on the orchestrator"}`]);if(!n||!l.length)return{lines:u};const p=await gn(t,e,{});if(p.length)return{lines:[...u,...p]};Date.now()>=s&&d(`${l.map(w=>w.id).join(", ")} still waiting on the orchestrator after ${o} minutes; run builder asks ${e} --wait again`),await new Promise(w=>setTimeout(w,i))}}c(Gu,"listAsks");async function Wc(t,e,n){const a=e.topic.startsWith("item:")&&!e.topic.startsWith("item:ask:")?e.topic.slice(5):d(`${n}.ask goes on a card's question, topic item:<file>/<id>`),i=(await We(t,a)).find(o=>o.id===e.ask)||d(`${n}.ask names no ask "${e.ask}" on ${a}; builder asks ${a} lists them`);i.deferred||d(`${n}.ask names ${i.id}, which the orchestrator ${i.answer?"answered":"has not deferred"}; only a deferred ask goes to the owner`)}c(Wc,"checkAskQuestion");async function Qu(t,e,{dir:n,agent:a="main"}){const i=await g(await U(t,e,n,a),null),o=i?.calls||[];if(!o.length)return{lines:["no judgment calls recorded"]};const{verified:s}=i,r=ne(i).length?"not verified yet":`verified ${s.at}${s.note?`: ${s.note}`:""}`;return{lines:[...o.map((l,u)=>`${u+1}. ${l.text}`),r]}}c(Qu,"listCalls");async function Vu(t,e,{dir:n,agent:a="main",note:i}){const o=await U(t,e,n,a),s=await g(o,null);if(ne(s).length||d(`${e} has no unverified judgment calls${a==="main"?"":` from agent ${a}`}; builder calls ${e} lists them`),t){const r=new Set((await g(B(t),{items:[]})).items?.filter(u=>u.topic===`item:${e}`&&u.ask).map(u=>u.ask)),l=(await We(t,e)).find(u=>u.deferred&&u.agent===a&&!r.has(u.id));l&&d(`${l.id} on ${e} was deferred to the owner; add its question with "ask": "${l.id}" first`)}return await b(o,{...s,verified:{at:new Date().toISOString(),...i===void 0?{}:{note:j(i,"--note")}}}),o}c(Vu,"verifyCalls");async function Zu(t,e){const{source:n,item:a}=await x(t,e),i=c((s,r)=>[(s.options||[]).find(l=>l.id===r.choice)?.label,r.note].filter(Boolean).join(": ")||"answered","said"),o=(await ft(t,e)).asked.filter(s=>s.ask&&s.answers.length).map(s=>({ask:s.ask,question:s.question,answer:i(s,s.answers.at(-1))}));return{key:e,ref:await K(t,e),title:a.title||e,notes:a.plan?$.join(n.dir,a.plan):null,thread:Z(t,e),worktree:(await Wo(t,e))?.path??null,answers:o,links:await Uc(t,e),rebasePR:a.rebase_run?.pr??null,prototype:a.gates?.prototype??null}}c(Zu,"briefFacts");async function Uc(t,e){const n=new Map;for(const r of await q(t))for(const l of(await g(r.file,null))?.items||[])n.set(`${r.slug}/${l.id}`,{entry:r,it:l});const a=R(e).file,{it:i}=n.get(e),o=[...n].filter(([,r])=>(r.it.related||[]).some(l=>z(r.entry.slug,l)===e)).map(([r])=>r),s=[...i.parent?[["parent",z(a,i.parent)]]:[],...(i.deps||[]).map(r=>["depends on",z(a,r)]),...[...new Set([...(i.related||[]).map(r=>z(a,r)),...o])].map(r=>["related",r])].filter(([,r])=>n.has(r));return Promise.all(s.map(async([r,l])=>{const{entry:u,it:p}=n.get(l);return{relation:r,ref:await K(t,l),title:p.title||l,lane:qt[p.lane||"todo"],notes:p.plan?$.join(u.dir,p.plan):null,thread:Z(t,l)}}))}c(Uc,"cardLinks");async function Yu(t){const e=[];for(const n of await q(t)){const a=await g(n.file,null);for(const i of a?.items||[]){if(G(i))continue;const o=(await Promise.all((await V(n.dir,i.id)).map(u=>g(u,null)))).filter(Boolean);if(!Dn(o))continue;const s=o.map(u=>u.verified?.at).filter(Boolean).sort().at(-1);if(!s||o.some(u=>ne(u).length))continue;const r=`${n.slug}/${i.id}`;if((await ft(t,r)).asked.some(u=>u.state==="open")||await dn(t,r,i))continue;const l=o.filter(u=>u.worktree?.path&&u.kind!==X).sort((u,p)=>String(p.started).localeCompare(String(u.started)))[0];l&&wt(l.worktree.path)&&e.push({key:r,verified:s,kind:Oe(l.kind),model:l.model})}}return e}c(Yu,"landable");async function Xu(t,e){const{source:n,item:a}=await x(t,e);(await Promise.all((await V(n.dir,a.id)).map(r=>g(r,null)))).some(r=>r?.started&&!r.done)||d(`${e} has no open builder; only a card whose lander stopped has one to relaunch`),await bt(t,e,{handBack:!0,next:"A lander relaunches to land the verified build"});const o=$.join(t,"data","landers.json"),s=await g(o,{});delete s[e],await A.writeFile(o+".tmp",JSON.stringify(s)+`
39
+ `),await A.rename(o+".tmp",o)}c(Xu,"relaunchLander");async function tf(t,e,{dir:n}={}){const{id:a}=R(e),i=await V($.dirname($.dirname(await U(t,e,n))),a),o=[];for(const s of i){if(!ne(await g(s,null)).length)continue;const r=$.basename(s,".json").slice(String(a).length+1)||"main";o.push(r==="main"?"":` --agent ${r}`)}o.length&&d(`land: ${e} has judgment calls nobody verified yet; check them with ${o.map(s=>`builder calls ${e}${s}`).join(", ")}, then run ${o.map(s=>`builder verified ${e}${s}`).join(", ")}`)}c(tf,"checkCallsVerified");async function ef(t,e,{dir:n,agent:a="main",next:i}){const o=await g(await U(t,e,n,a),null),s=o&&!o.done?ne(o):[];if(!s.length)return null;i!==void 0&&d(`builder done sets ${e}'s Next itself while its record has judgment calls; run it without --next`);const r=s.some(u=>u.text.startsWith("Question:"))?"Answer the builder's questions":"Verify the builder's judgment calls",l=await bt(t,e,{handBack:!0,next:r});return{lines:[`handed back: Next "${r}"`,...l.lines]}}c(ef,"handBackCalls");async function nf(t,e,{agent:n="main"}){if(n!=="main")return!1;const a=await U(t,e,void 0,n),i=await g(a,null);if(!i?.started||i.done||!i.worktree?.path)return!1;const{id:o}=R(e);for(const s of await V($.dirname($.dirname(a)),o)){const r=s===a?null:await g(s,null);if(!r?.started||r.done||r.kind==="install")continue;const l=$.basename(s,".json").slice(String(o).length+1);d(`builder done would finish ${e} while agent ${l} is still open; run builder done ${e} --agent ${l} first`)}return!0}c(nf,"finishesCard");async function af(t,e){const{source:n,item:a}=await x(t,e);if(G(a))return null;const i=(await Promise.all((await V(n.dir,a.id)).map(s=>g(s,null)))).filter(Boolean);if(!Dn(i))return{held:"the build hasn't handed back; run builder done first"};if(i.some(s=>ne(s).length))return{held:"a builder record still has unverified judgment calls"};if(i.some(s=>s.started&&!s.done&&s.kind!=="install"))return{held:"a builder record is still open"};const o=await Wo(t,e);return!o||!wt(o.path)?{held:"the build's worktree is gone"}:{waits:(await ft(t,e)).asked.filter(s=>s.state==="open").map(s=>s.id)}}c(af,"verifiedFinish");async function of(t,e){const{item:n}=await x(t,e);if(n.reopened_at&&d(`the owner reopened ${await K(t,e)}; it closes on the owner's Done`),n.lane!=="done"||Et(n).some(o=>o.merged_at))return;const a=String(n.closed_at||"");(await J($.join(t,"data","events.jsonl"))).some(o=>o.kind==="item-message"&&o.data?.key===e&&String(o.ts)>a)&&d(`the owner reopened ${await K(t,e)} with a message; it closes on the owner's Done`)}c(of,"checkNotReopened");async function V(t,e){const n=$.join(t,"agents");return(await A.readdir(n).catch(()=>[])).filter(a=>a===`${e}.json`||a.startsWith(`${e}@`)&&!a.startsWith(`${e}@past-`)&&a.endsWith(".json")).map(a=>$.join(n,a))}c(V,"builderFiles");async function Uo(t,e,n,{handedBack:a,endHandBack:i=!1,held:o=!1}={}){const s=new Date().toISOString();for(const r of await V(t,e)){const l=await g(r,null);if(!l)continue;if(l.done||l.kind==="install"&&!n){if(i&&l.handed_back){const{handed_back:f,...h}=l;await b(r,h)}continue}if(o&&l.pause)continue;const{eta:u,handed_back:p,...w}=l;await b(r,{...w,done:s,...a?{handed_back:a}:{},...o&&l.started?{hold_stopped:!0}:{}})}}c(Uo,"closeBuilders");async function sf(t,e){const n=await U(t,e),a=await g(n,null);if(!a?.hold_stopped)return null;const{hold_stopped:i,...o}=a;return await b(n,o),{kind:a.kind??null,label:a.label??null}}c(sf,"takeHoldStopped");async function Ho(t,e,{dir:n,agent:a,startedBetween:i,note:o,next:s,requireNext:r=!1}){const l=await U(t,e,n,a),u=await g(l,null);if(!u||u.done)return l;if(i){const I=Date.parse(u.started);if(!(I>=i[0]&&I<=i[1]))return l}const{eta:p,...w}=u,f=new Date().toISOString(),h={...w,done:f,...o?{note:o}:{}},{id:m}=R(e),y=$.dirname($.dirname(l)),_=await Promise.all((await V(y,m)).map(I=>I===l?h:g(I,null))),P=!_.some(I=>I?.started&&!I.done),S=n?{file:$.join(y,"wave.json")}:(await x(t,e)).source,v=await g(S.file,null),F=v?.items?.find(I=>I.id===m);return s!==void 0&&(to(F||d(`${e} has no item to set --next on`),s,await ln(t,e)),t&&await lo(t,e,F,F.next)),r&&F&&Fn(F,_)&&d(`builder done closes ${e}'s last open builder, which leaves it In Progress with no Next; pass --next "<what happens next>", or record a judgment call with builder call ${e} or land`),await b(l,h),await pe(t,e,{screen:u.kind==="grill"}),o&&await va(t,e,a,u,{detail:o},f),s!==void 0&&await b(S.file,v),l}c(Ho,"stopBuilder");async function rf(t,e,n){const a=(await g(await U(t,e,void 0,n.agent),null))?.kind,i=await Ho(t,e,n),{phase:o,gates:s}=(await x(t,e)).item,r=await ln(t,e)||!!(await g(ut(t),{}))[e];if(o!=={grill:"grilling",prototype:"prototyping"}[a]||r)return{file:i,lines:[]};if(a==="grill"&&s?.prototype&&await an(t,e,{roundAt:!0}))return{file:i,lines:[]};const{line:l,lines:u}=await W(t,e,"planner-unasked",{kind:a});return{file:i,lines:[l.text,...u]}}c(rf,"stopPlanner");async function Hc(t){const e=[];for(const n of await q(t)){const a=await g(n.file,null);for(const i of a?.items||[])for(const o of await V(n.dir,i.id)){const s=await g(o,null);if(!s?.started||s.done)continue;const r=$.basename(o,".json");e.push({key:`${n.slug}/${i.id}`,agent:r.slice(String(i.id).length+1)||"main",label:s.label||"Builder",started:s.started})}}return e}c(Hc,"openBoardBuilders");async function cf(t){const e=await Hc(t);for(const n of e)await Ho(t,n.key,{agent:n.agent,note:"Board closed. Builder record stopped; work is kept for reopening."});return e}c(cf,"closeBoardBuilders");export{Fi as ANSWER_MARK,pt as BoardError,si as PUSH_LINE_MAX,Ye as REPLY_EXTS,rr as SCREEN_AFTER,Kn as UPLOAD_LIMIT,Al as WORKING_KINDS,ku as abandonLaunch,yu as abandonPlanner,Kl as ackPing,kc as addItem,Fd as addNotes,xd as addPrototype,jd as addQuestions,ld as addReviewers,gd as addRuleTo,bd as addTopic,Iu as addVisual,zu as answerBuilder,ql as answerCard,Gt as appendMessage,W as appendStatus,ou as archiveCards,iu as archiveCount,pn as archiveFile,mn as archiveRank,Ku as askOrchestrator,qd as askedGate,qu as auditLog,dn as blockWords,rt as boardConfig,Or as boardPosts,ct as boardRepoOf,Kd as breakOwnerCheck,Zu as briefFacts,Yd as builderModel,Uu as builderProgress,Pu as bumpCard,ed as cardLinked,K as cardName,pu as cardPR,lu as changeWave,tf as checkCallsVerified,Td as checkClose,of as checkNotReopened,Ou as clearStall,cf as closeBoardBuilders,cu as createWave,Tu as cutOffBuilds,Tl as dropAskCard,$u as dropPause,$d as editRuleIn,Ll as eventCard,pd as fallBackFromLinear,Bl as fileAsk,Cl as fileAsks,zl as finishHandshake,du as finishWave,nf as finishesCard,ef as handBackCalls,nd as heardThreads,Vd as heldMerge,Eu as helperOf,ri as hiddenFile,hu as implementAsIs,Wd as isFinished,Bu as isHelper,Mo as isLanding,Cu as isPlanner,q as itemSources,Au as landFirst,Yu as landable,Hu as landingLine,Gu as listAsks,Qu as listCalls,_d as listPrototypes,hd as listRules,ad as markHeard,Bc as markPaused,Rl as markRead,ju as markStalled,Su as markStopped,Pl as markWorking,Qd as mergeCard,dc as mergedLine,Xe as messageText,Xd as migrateFollowups,eu as migrateGates,nu as migratePhases,tu as migrateStatuses,ru as migrateWaveNames,Ul as moveAsk,Md as moveCard,Bd as moveQuestions,xu as openAgents,Hc as openBoardBuilders,rd as openDayThread,_u as openRuns,wd as opensPRs,R as parseKey,Jd as passOwnerCheck,Mu as pickBuilder,Hd as pickUp,Ed as planAgain,cd as postDigest,Jl as postIncomingReview,Ql as postLink,Gd as postPR,Vl as postReply,zd as prReport,Ad as publishScreened,Pd as publishUnscreened,gr as pushLine,$r as pushUrl,Yl as queuePushes,It as readArchive,Ot as readAskLinks,ia as readBoardRules,Pr as readBoardSettings,vi as readHandshake,yr as readHidden,g as readJSON,br as readMarks,li as readMarksFile,lc as readNotes,Fe as readPRSlack,Le as readPrototypes,Mi as readScreening,El as readUpload,uu as readWaveNotes,dr as readWorking,Ju as recordCall,ho as recordOwnerTap,fr as recordPush,Zl as recordReaction,mu as recordRebase,Hl as recordReview,bu as recordSession,Wu as recordedSession,Wo as recordedWorktree,Ml as relateAsk,Xu as relaunchLander,vd as removePrototype,dd as removeReviewers,kd as removeRuleFrom,ur as repliesSincePush,Un as replyFilesOf,Ru as requestHelper,qo as requestPause,Cd as resolveNoteAnswers,Ld as resolveQuestion,gu as resumePaused,Il as retitleAskCard,vr as reviewDigest,Xl as reviewDue,td as reviewUpdated,yd as saveBoardRules,fe as saveBoardSettings,ud as saveBoardShare,Nl as saveUpload,Dl as sendPush,Sd as servedRoundsOpen,fd as setBoardPause,md as setBoardSetting,Fl as setHidden,bt as setItem,Ud as setMainInstall,Gl as setReviewers,Dr as settingsLines,At as settingsOf,Dd as settleAnswers,Od as settleQuestion,jl as siteDir,sr as sitesDir,od as slackAnswer,sd as slackTask,id as slackThread,Rd as splitSharedNotes,zr as stageImplement,au as stageImplementAsks,Nd as stageReply,Me as startBuilder,Nu as startHelper,Du as startPlanner,wu as startRebase,fu as startTappedBuild,Fu as startVisual,Ho as stopBuilder,vu as stopHeldMerge,rf as stopPlanner,su as stripDeadFields,ca as takeFile,sf as takeHoldStopped,Zd as tapMerge,Z as threadFile,Yi as topicQuestions,Wl as unfoldAsk,Id as unrecorded,af as verifiedFinish,Vu as verifyCalls,Lu as waitHelper,ba as waveNoteFile,Ve as wavesDir,hr as withReplies,Ol as writeReply};