diacode 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ import{a as oe,b as J,i as re,c as Q,p as X,d as ie,s as D,S as P,e as ke,f as Se,n as xe,h as le,w as Ae,g as Te,j as Ee,E as Oe,G as Le,k as je,l as Pe,F as Z,m as Re,o as Ce,q as Ie,r as Ne,t as He,u as Me,v as qe,x as De,y as We,z as Be,A as _e,B as ce,C as Fe,D as Ge,H as Ue,I as Ye,J as ze,K as Ve,L as Ke}from"./fonts-D2FlQA0D.js";const i=t=>String(t).replace(/[&<>"]/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[n]),R={executing:0,paused:1,approved:2,planning:3};function Je(t){const n=s=>(s.done??0)/(s.steps||1);return t.filter(s=>s.title!==void 0&&(s.phase??"")in R).sort((s,e)=>R[s.phase]-R[e.phase]||n(s)-n(e))}function Qe(t,n){const s=t.filter(e=>e.title!==void 0);return s.find(e=>e.id===n)??Je(t)[0]??s[0]}function Xe(t){const n=t?.plan;if(!n||n.phase!=="planning")return null;const s=Object.values(n.nodes??{}).filter(r=>r.kind!=="context");if(!s.length)return null;const e=(t?.recent??[]).find(r=>r.actor!=="you"&&(r.ops??[]).some(l=>l.op==="node.add"))?.actor;return e?{key:"approve",kind:"approve",title:`${D(String(e))} drafted this plan: ${s.length} step${s.length===1?"":"s"}`,detail:"Look it over, then approve it: the agent then checks the architecture against it, and nothing starts until you press Start."}:null}function de(t,n){const s=re(t),e=n?.exists?oe(n.arch,{by:[...n.recent??[]].reverse().find(l=>l.actor!=="you")?.actor}):[],r=n?.exists&&n.arch.phase==="draft"?null:Xe(t);return{approve:r,plan:s,arch:e,total:xe(t).total+e.length+(r?1:0),shown:s.length+e.length+(r?1:0)}}function Ze(t){const n=t?.plan?.nodes??{},s=new Map((t?.presence??[]).filter(e=>e?.state==="asking").map(e=>[e.actor,e]));return Object.entries(n).filter(([,e])=>e.kind!=="context"&&e.status==="in_progress").map(([e,r])=>{const l=r,c=Ae(l),k=t?.derived?.stalled?.[e],h=k?`stalled: ${Te(k)}`:l.owner&&s.has(l.owner)?Ee(s.get(l.owner)):void 0;return{id:e,label:l.label,...c?{who:D(c.who),mark:Le[c.from],how:Oe[c.from]}:{},...h?{trouble:h}:{}}})}function et(t,n){const s=je(t,n),e=r=>t.nodes[r]?.label??r;return{new:[...s.added].map(e),changed:[...s.changed.keys()].map(e),removed:[...s.removed].map(e),arrows:s.addedArrows.size+s.removedArrows.size}}function ee(t){switch(t){case"planning":return"Planning: an agent's changes land at once.";case"approved":return"Approved, not started: your agent checks the architecture against the plan. Press Start when both are final.";case"paused":return"Paused: agents finish the step they are on and start nothing new.";case"done":return"This plan is finished.";case"abandoned":return"This plan was abandoned.";default:return""}}const tt={planning:"Planning",approved:"Approved",executing:"Executing",paused:"Paused",done:"Done",abandoned:"Abandoned"},nt={executing:P.in_progress,paused:P.waiting,done:P.done},y=(t,n="Open in full view")=>`title="${i(t)}">${i(n)}`;function at({plans:t,id:n,view:s,arch:e,presence:r=[],thumb:l="",now:c=Date.now(),armed:k,notice:h=null,down:A=!1}){const L=o=>i(le(o)),B=t.filter(o=>o.title!==void 0),_=A?'<p class="notice error" role="alert">The plan server is not answering. What you see may be out of date, and a click will not land until it is back.</p>':"",F=h?`<p class="notice ${h.kind}" role="${h.kind==="error"?"alert":"status"}">${i(h.text)}</p>`:"";if(!s?.plan){const o=s?.error?`<p class="notice error">The plan file has a problem: ${i(s.error)}</p>`:"",w=e?.exists?oe(e.arch,{by:[...e.recent??[]].reverse().find(S=>S.actor!=="you")?.actor}):[],b=w.length?`
2
+ <section class="needs" aria-labelledby="h-needs">
3
+ <h2 id="h-needs">Waiting for you <span class="count">${w.length}</span></h2>
4
+ <ul class="inbox">${J(w,{show:S=>`<button class="plain small" data-open-arch="${i(S)}" ${y(S?"Opens the architecture with this proposal on the diagram":"Opens the architecture")}</button>`})}</ul>
5
+ </section>`:"",g=r.filter(S=>S.state!=="gone"),O=re({presence:g}),ye=g.length?`
6
+ <section class="working" aria-labelledby="h-working">
7
+ <h2 id="h-working">Agents</h2>
8
+ ${O.length?`<ul class="inbox">${Q(O,{})}</ul>`:X(g,c,[])}
9
+ </section>`:"";return`${_}${o}${F}${b}${ye}<section class="empty"><h1>No plan yet</h1>
10
+ <p class="lede">Give your agent the task. It draws the architecture first, then the plan, and each waits here for your approval. Or start a plan yourself in the full editor.</p>
11
+ <p><a class="open primary" href="${L({})}" data-open>Open full screen</a></p></section>`}const d=s.plan,E=s.derived?.progress??{done:0,total:0,active:0,waiting:0,failed:0,left:0},f=de(s,e),j=ie(d.phase,E,s.listening??[]),fe=!!e?.exists&&e.arch?.phase==="draft"&&d.phase==="planning",we=!!f.approve&&d.phase==="planning"||f.plan.some(o=>o.kind==="finish")||fe,G=(o,w)=>{const b=!!o.confirm&&k===o.label;return`<button class="${o.primary?"primary":""}${b?" danger":""}" data-phase="${w}" title="${i(o.hint)}">${i(b?o.confirm??o.label:o.label)}</button>`},U=[we?"":G(j,"first"),j.second?G(j.second,"second"):""].filter(Boolean).join(""),ge=s.stopping?.length?`<p class="lede"><b>Stopping ${i(s.stopping.map(D).join(", "))}:</b> at the next tool call, and the turn ends there.</p>`:"",me=`
12
+ <header class="head">
13
+ ${B.length>1?`<select class="picker" data-pick aria-label="Which plan">${B.map(o=>`<option value="${i(o.id)}"${o.id===n?" selected":""}>${i(o.title??o.id)} · ${i(o.phase??"")}${o.steps?` · ${o.done??0}/${o.steps}`:""}</option>`).join("")}</select>`:""}
14
+ <h1 class="title">${i(d.title)}</h1>
15
+ <p class="phaseline"><span class="phase-pill" data-phase-name="${i(d.phase)}"><i style="background:${nt[d.phase]??"var(--wire)"}"></i>${i(tt[d.phase]??d.phase)}</span> <span class="rev">rev ${i(s.rev)}</span></p>
16
+ ${E.total?`${ke(E)}<p class="lede counts">${i(Se(E))}</p>`:'<p class="lede">No steps yet.</p>'}
17
+ ${U?`<div class="row controls">${U}</div>`:""}
18
+ ${ee(d.phase)?`<p class="lede">${i(ee(d.phase))}</p>`:""}
19
+ ${ge}
20
+ </header>`,Y=[f.approve?`<li class="inbox-item" data-kind="approve"><div class="inbox-what"><b>${i(f.approve.title)}</b><span class="inbox-detail">${i(f.approve.detail)}</span></div><div class="row actions"><button class="primary" data-phase="first">Approve plan</button><button class="plain small" data-open ${y("Look at the plan in the full editor")}</button></div></li>`:"",Q(f.plan,s,{showStep:o=>`<button class="plain small" data-open-step="${i(o)}" ${y("Opens the full editor at this step")}</button>`,showProposal:o=>`<button class="plain small" data-open-proposal="${i(o)}" ${y("Opens the full editor with this proposal on the diagram")}</button>`}),J(f.arch,{show:o=>`<button class="plain small" data-open-arch="${i(o)}" ${y(o?"Opens the architecture with this proposal on the diagram":"Opens the architecture")}</button>`})].join(""),$e=`
21
+ <section class="needs" aria-labelledby="h-needs">
22
+ <h2 id="h-needs">Waiting for you${f.shown?` <span class="count">${f.shown}</span>`:""}</h2>
23
+ ${Y?`<ul class="inbox">${Y}</ul>`:'<p class="calm">Nothing waits on you.</p>'}
24
+ </section>`,z=Ze(s),V=(s.derived?.ready??[]).slice(0,2).map(o=>d.nodes[o]?.label??o),ve=`
25
+ <section class="working" aria-labelledby="h-working">
26
+ <h2 id="h-working">Working now</h2>
27
+ ${X(s.presence??[],c,[])}
28
+ ${z.length?`<ul class="steplist">${z.map(o=>`<li data-step="${i(o.id)}"><button class="plain link" data-open-step="${i(o.id)}" ${y("Opens the full editor at this step",o.label)}</button>${o.who?` <span class="who" title="${i(o.how??"")}">${i(o.mark??"")} ${i(o.who)}</span>`:""}${o.trouble?` <span class="risk">${i(o.trouble)}</span>`:""}</li>`).join("")}</ul>`:`<p class="calm">${d.phase==="executing"?"No step is in progress.":"Nothing is in progress."}${d.phase==="executing"&&V.length?` Ready: ${i(V.join(", "))}.`:""}</p>`}
29
+ </section>`,be=l?`<a class="thumb" href="${L({plan:d.id})}" data-open aria-label="The diagram of ${i(d.title)}: open it in the full editor">${l}</a>`:"";let K="";if(e?.exists){const o=et(e.arch,d),w=g=>o[g].length?`<li class="plan-note ${g}">${Pe(Z[g].icon,{size:12})} <span>${i(Z[g].word)}</span> ${o[g].map(O=>`<b>${i(O)}</b>`).join(", ")}</li>`:"",b=[w("new"),w("changed"),w("removed")].join("");K=`
30
+ <section class="footprint" aria-labelledby="h-arch">
31
+ <h2 id="h-arch">On the architecture</h2>
32
+ ${b?`<ul class="fp">${b}</ul>`:'<p class="calm">This plan changes no box of it yet.</p>'}
33
+ <p class="more"><button class="plain small" data-open-arch="" ${y("Opens the architecture in the full editor","Open the architecture")}</button></p>
34
+ </section>`}return`${_}${F}${me}${$e}${ve}${be}${K}
35
+ <footer class="foot"><a class="open" href="${L({plan:d.id})}" data-open>Open full screen</a></footer>`}const p=document.getElementById("root"),te=document.title,st=3e3,a={plans:[],id:void 0,pinned:null,view:null,arch:null,presence:[],notice:null,armed:void 0,down:!1,noServer:!1,unfollow:null,followed:void 0},pe="dcursed.compact.plan";try{a.pinned=new URLSearchParams(location.search).get("plan")||decodeURIComponent(location.hash.slice(1))||localStorage.getItem(pe)}catch{}function ot(t){const n=t?.plan;if(!n||!Object.keys(n.nodes).length)return"";const s=t.layout??{canvas:{width:640,height:240},direction:"LR",nodes:{}},e=ze({plan:n,layout:s});return Ve({...e,canvas:s.canvas??{width:640,height:240},direction:s.direction,title:n.title},{labels:!1,title:`The diagram of ${n.title}`,edge:r=>{const l=Ke[n.nodes[r]?.status??"not_started"];return l?.edge?l.colour:void 0}})}let M="",q=!1;const ne=t=>t.dataset.answer?`a:${t.dataset.answer}`:`g:${t.dataset.from}>${t.dataset.to}`;function m(){if(a.noServer)return;const t=at({plans:a.plans,id:a.id,view:a.view,arch:a.arch,presence:a.presence,thumb:ot(a.view),now:Date.now(),armed:a.armed,notice:a.notice,down:a.down}),n=t.replace(/ah\d+/g,"ah");if(n===M)return;const s=document.activeElement;if(p.contains(s)&&(s instanceof HTMLInputElement||s instanceof HTMLSelectElement)){q=!0;return}q=!1,M=n;const e=[...p.querySelectorAll("input[data-answer], input[data-gate-text]")].map(c=>c).filter(c=>c.value).map(c=>[ne(c),c.value]);p.innerHTML=t;for(const[c,k]of e){const h=[...p.querySelectorAll("input[data-answer], input[data-gate-text]")].map(A=>A).find(A=>ne(A)===c);h&&(h.value=k)}const r=a.view?.plan?de(a.view,a.arch).total:0;document.title=Ue(a.view?.plan?`${a.view.plan.title} · ${te}`:te,r),document.querySelector('link[rel="icon"]')?.setAttribute("href",r>0?"/favicon-needs.svg":"/favicon.svg"),window.parent!==window&&window.parent.postMessage({dcursed:"needs",total:r},"*")}p.addEventListener("focusout",()=>{q&&setTimeout(()=>{p.contains(document.activeElement)||m()},0)});let C=!1,I=!1,ae;async function u(){if(C){I=!0;return}C=!0;try{if(a.plans=await De(),a.id=Qe(a.plans,a.pinned)?.id,a.view=a.id?await We(a.id):null,a.arch=await Be().catch(()=>a.arch),a.presence=a.view?[]:await _e().catch(()=>a.presence),a.down=!1,a.noServer=!1,rt(a.id),a.notice?.call){const t=[...a.view?.calls??[],...a.arch?.calls??[]].find(s=>s.id===a.notice?.call),n=t&&ce(t);n&&(a.notice={text:n.text,kind:n.kind,call:t.id})}m()}catch{if(!a.noServer&&!a.down&&(a.down=!0,m()),!a.view&&!a.plans.length){const n=a.noServer;await he(),n&&!a.noServer&&$(0)}}finally{C=!1,I&&(I=!1,$(0))}}const $=(t=120)=>{clearTimeout(ae),ae=setTimeout(u,t)};function rt(t){t!==a.followed&&(a.unfollow?.(),a.followed=t,a.unfollow=t?Ye(t,{change:()=>$(),problem:()=>$(),reconcile:()=>$(),presence:()=>$(),call:n=>{a.notice?.call===n.id&&$(0)},open:n=>{a.down&&(a.down=!1,m()),n&&$(0)},down:()=>{a.down=!0,m()}}):null)}async function he(){if(await Ge()){a.noServer=!1;return}a.noServer=!0,M="",p.innerHTML=`<section class="empty"><h1>No plan server</h1>
36
+ <p class="lede">This view shows the plans of a repository, and needs that repository's plan server. Run <code>npx diacode serve</code> in it, or open the folder in VS Code with the DiaCode extension.</p></section>`}function v(t){a.notice=t,m();const n=t;t.call||setTimeout(()=>{a.notice===n&&(a.notice=null,m())},9e3)}function W(t){const n=t?.[0],s=n&&ce(n);n&&s&&v({text:s.text,kind:s.kind,call:n.id})}function ue(){const t=document.activeElement;p.contains(t)&&t instanceof HTMLInputElement&&t.blur()}async function x(t,n,s){if(!a.view?.plan||!a.id)return!1;const{status:e,body:r}=await qe(a.id,a.view.rev,t,s);return ue(),e===200?(v({text:n,kind:"info"}),W(r.calls)):v({text:`Not done: ${r.why??r.error}`,kind:"error"}),await u(),e===200}async function N(t,n,s){if(!a.arch?.exists)return!1;const{status:e,body:r}=await Me(a.arch.rev,t,s);return ue(),e===200?(v({text:n,kind:"info"}),W(r.calls)):v({text:`Not done: ${r.why??r.error}`,kind:"error"}),await u(),e===200}function T(t){if(window.parent!==window){window.parent.postMessage({dcursed:"open",hash:He(t)},"*");return}location.assign(le(t))}async function it(t){const n=a.view;if(!n?.plan)return;const s=ie(n.plan.phase,n.derived?.progress,n.listening??[]),e=t==="second"?s.second:s;if(!e)return;if(e.confirm&&a.armed!==e.label){a.armed=e.label,m(),setTimeout(()=>{a.armed===e.label&&(a.armed=void 0,m())},4e3);return}a.armed=void 0,await x(e.ops,e.message,e.reason)&&e.ops[0]?.op==="plan.stop"&&a.view?.stopping?.length&&!a.notice?.call&&v({text:`Stopped. ${a.view.stopping.map(l=>l.replace(/^opencode:/,"")).join(", ")} stops at the next tool call; the plan is back in planning.`,kind:"info"})}async function se(t){try{const{call:n}=await Fe(a.id??"",t);n&&W([n]),await u()}catch(n){v({text:`Not asked: ${n.message}.`,kind:"error"})}}const H=t=>p.querySelector(t);p.addEventListener("click",async t=>{const s=t.target.closest("button, a[data-open]");if(!(s instanceof HTMLElement))return;const e=s.dataset;if(s.tagName==="A"){window.parent!==window&&(t.preventDefault(),T({plan:a.id}));return}if(e.phase)return void it(e.phase);if(e.open!==void 0)return T({plan:a.id});if(e.openStep)return T({plan:a.id,step:e.openStep});if(e.openProposal)return T({plan:a.id,proposal:e.openProposal});if(e.openArch!==void 0)return T(e.openArch?{architecture:!0,proposal:e.openArch}:{architecture:!0});if(e.archAcceptDraft!==void 0)return void N([{op:"arch.set",phase:"accepted"}],"Architecture approved. Your agent draws the plan on it.","you approved the architecture");if(e.archAccept)return void N([{op:"proposal.accept",id:e.archAccept}],`Accepted ${e.archAccept}.`);if(e.archReject){const r=document.querySelector(`[data-arch-why="${CSS.escape(e.archReject)}"]`)?.value.trim();return void N([{op:"proposal.reject",id:e.archReject}],`Rejected ${e.archReject}.`,r||void 0)}if(e.accept)return void x([{op:"proposal.accept",id:e.accept}],`Accepted ${e.accept}.`);if(e.finish!==void 0)return void x([{op:"plan.set",phase:"done"}],"Plan marked done.","you marked the plan done");if(e.permit||e.deny||e.permitAlways){const r=e.permit??e.permitAlways??e.deny,l=document.querySelector(`[data-permit-why="${CSS.escape(r)}"]`)?.value.trim(),{status:c}=await Re(r,e.deny?"deny":"allow",e.deny?l:void 0,e.permitAlways!==void 0);return v({text:c===200?e.deny?"Denied: the agent is told why.":e.permitAlways!==void 0?"Allowed, and it will not ask again for this kind until its session ends.":"Allowed: the agent carries on.":c===409?"That one cannot be allowed for good: allow it once, or deny it.":"That prompt was already answered in the agent's window.",kind:c===200?"info":"error"}),void u()}if(e.reject)return void x([{op:"proposal.reject",id:e.reject}],`Rejected ${e.reject}.`);if(e.reconcile!==void 0){await se({});return}if(e.gate){const r=`[data-from="${CSS.escape(e.from??"")}"][data-to="${CSS.escape(e.to??"")}"]`,l=Ce(e.gate,e.from??"",e.to??"",e.option??H(`[data-gate-text]${r}`)?.value??"");if(!l){H(`[data-gate-text]${r}`)?.focus();return}return void x(l.ops,l.message,l.reason)}if(e.act){if(e.act==="replan"){await se({kind:"failure",step:e.step??""});return}const r=H(`[data-answer="${CSS.escape(e.step??"")}"]`),l=Ie(e.act,e.step??"",r?.value??"");l?x(l.ops,l.message,l.reason):e.act==="answer"&&r?.focus()}});p.addEventListener("keydown",t=>{const n=t.target;if(!(t.key!=="Enter"||!(n instanceof HTMLInputElement))){if(n.dataset.answer)p.querySelector(`[data-act="answer"][data-step="${CSS.escape(n.dataset.answer)}"]`)?.dispatchEvent(new MouseEvent("click",{bubbles:!0}));else if(n.dataset.gateText!==void 0){const s=`[data-from="${CSS.escape(n.dataset.from??"")}"][data-to="${CSS.escape(n.dataset.to??"")}"]`;(p.querySelector(`[data-gate="give"]:not([data-option])${s}`)??p.querySelector(`[data-gate="pass"]${s}`))?.dispatchEvent(new MouseEvent("click",{bubbles:!0}))}}});p.addEventListener("change",t=>{const n=t.target;if(!(!(n instanceof HTMLSelectElement)||n.dataset.pick===void 0)){a.pinned=n.value;try{localStorage.setItem(pe,n.value)}catch{}n.blur(),u()}});await Ne();await he();a.noServer||await u();setInterval(()=>{document.hidden||u()},st);document.addEventListener("visibilitychange",()=>{document.hidden||u()});addEventListener("focus",()=>u());Object.assign(window,{compact:a});
@@ -0,0 +1 @@
1
+ *{box-sizing:border-box}html{background:var(--paper)}body{margin:0;font:13px/1.45 var(--sans);color:var(--ink);background:var(--paper);-webkit-text-size-adjust:100%}main{padding:12px 12px 18px;max-width:520px;margin:0 auto;overflow-wrap:anywhere}h1,h2{margin:0;font-weight:600}h1{font-size:15px;line-height:1.3}h2{font-size:11.5px;letter-spacing:.04em;text-transform:uppercase;color:var(--slate);margin:0 0 6px;display:flex;align-items:center;gap:6px}section{margin:0 0 16px}b{font-weight:600}code{font:12px var(--mono)}a{color:var(--ember-deep)}button{font:inherit;font-size:12.5px;padding:5px 11px;border-radius:7px;border:1px solid var(--line);background:var(--surface);color:var(--ink);cursor:pointer;min-height:28px}button:hover:not(:disabled){border-color:var(--ink)}button:disabled{opacity:.42;cursor:default}button:focus-visible,a:focus-visible,select:focus-visible,input:focus-visible{outline:3px solid var(--ember);outline-offset:1px}button.primary{background:var(--ember);border-color:var(--ember);color:var(--ink);font-weight:560}button.primary:hover:not(:disabled){filter:brightness(1.06);border-color:var(--ember)}.row button[data-permit-always]{white-space:normal;text-align:left;max-width:100%;overflow-wrap:anywhere}a.open-link{font:inherit;font-size:12.5px;padding:6px 12px;border-radius:7px;border:1px solid var(--ink);background:var(--surface);color:var(--ink);text-decoration:none;white-space:nowrap}a.open-link:hover{background:var(--ink);color:var(--surface)}.inbox-detail a,.note a{color:inherit;text-decoration:underline;text-underline-offset:2px}button.danger,button.danger:hover{background:var(--st-failed);border-color:var(--st-failed);color:#fff}button.plain{background:transparent;border-radius:999px;font-size:12px;padding:3px 10px;min-height:0}button.plain.small{font-size:11.5px;padding:1px 9px}button.plain:hover:not(:disabled){background:var(--ground)}button.link{border:0;padding:0;text-align:left;border-radius:4px;font-weight:560;font-size:13px}button.link:hover:not(:disabled){text-decoration:underline;background:transparent}.row{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-top:8px}.row button{white-space:nowrap}.lede{margin:6px 0 0;font-size:12px;line-height:1.5;color:var(--slate)}.lede code{color:var(--ink)}.calm{margin:0;font-size:12.5px;color:var(--slate)}.count{font-size:11px;font-weight:600;letter-spacing:0;padding:0 6px;min-width:18px;text-align:center;border-radius:999px;background:var(--ember);color:var(--ink)}.notice{margin:0 0 10px;padding:7px 10px;border-radius:6px;font-size:12.5px;background:var(--surface);border:1px solid var(--line)}.notice.error{border-color:var(--ember-deep);color:var(--ember-deep)}.head{margin-bottom:14px}.picker{width:100%;margin:0 0 8px;font:inherit;font-size:12px;padding:4px 6px;border:1px solid var(--line);border-radius:6px;background:var(--surface);color:var(--ink)}.phaseline{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:4px 0 8px;font-size:12px;color:var(--slate)}.phase-pill{display:inline-flex;align-items:center;gap:6px;padding:1px 9px 1px 7px;border:1px solid var(--line);border-radius:999px;background:var(--surface);color:var(--ink);font-weight:560}.phase-pill i{width:8px;height:8px;border-radius:50%}.progress{display:flex;height:8px;border-radius:4px;overflow:hidden;background:var(--line);margin:2px 0 6px}.progress i{display:block}.counts{margin-top:0}.needs{padding:8px 10px 10px;background:var(--ember-tint);border-left:3px solid var(--ember);border-radius:0 8px 8px 0}.needs:has(>.calm){background:transparent;border-left-color:var(--line);padding-left:10px}.inbox{list-style:none;margin:0;padding:0}.inbox-item{padding:9px 0;border-top:1px solid rgb(25 18 15 / .12)}.inbox-item:first-child{border-top:0;padding-top:2px}.inbox-what{display:flex;flex-direction:column;gap:1px}.inbox-detail{font-size:12px;color:var(--slate)}.inbox-item .row input{flex:1 1 130px;min-width:0;font:inherit;font-size:12px;padding:5px 8px;border:1px solid var(--line);border-radius:6px;background:var(--surface);color:var(--ink)}.inbox-item .lede,.inbox-item .err{margin:6px 0 0;font-size:12px}.inbox-item[data-kind=failure]{border-left:3px solid var(--st-failed);padding-left:9px;margin-left:-10px}.agents{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 8px}.agent{display:inline-flex;align-items:center;gap:5px;font-size:11.5px;padding:2px 8px;border:1px solid var(--line);border-radius:999px;color:var(--slate);background:var(--surface)}.agent b{color:var(--ink);font-weight:560}.agent i{width:7px;height:7px;border-radius:50%;background:var(--wire-soft);flex:none}.agent.working i{background:var(--st-working);box-shadow:0 0 0 3px color-mix(in srgb,var(--st-working) 22%,transparent)}.agent.error{border-color:var(--ember-deep);color:var(--ember-deep)}.agent.error i,.agent.quiet i{background:var(--ember-deep)}.agent.gone{opacity:.6}.agent.asking{border-color:var(--st-waiting);color:var(--ink)}.agent.asking i{background:var(--st-waiting);box-shadow:0 0 0 3px color-mix(in srgb,var(--st-waiting) 22%,transparent)}.steplist{list-style:none;margin:0;padding:0}.steplist li{padding:5px 0;border-bottom:1px solid var(--line-soft)}.steplist li:last-child{border-bottom:0}.who{font-size:12px;color:var(--slate);white-space:nowrap}.risk{display:block;font-size:12px;color:var(--ember-deep)}.thumb{display:block;margin:0 0 16px;padding:6px;border:1px solid var(--line);border-radius:8px;background:var(--ground);line-height:0}.thumb:hover{border-color:var(--ink)}.thumb svg{width:100%;height:auto;max-height:150px}.fp{list-style:none;margin:0;padding:0;font-size:12.5px}.fp li{padding:2px 0}.plan-note{display:block;font-weight:560}.plan-note span{font-weight:560}.plan-note b{font-weight:400;color:var(--ink)}.plan-note.new{color:var(--st-done)}.plan-note.changed{color:var(--st-waiting)}.plan-note.removed{color:var(--st-failed)}.plan-note .glyph{vertical-align:-2px}.more{margin:6px 0 0}.foot{padding-top:4px;border-top:1px solid var(--line)}a.open{display:inline-block;margin-top:10px;padding:6px 12px;border:1px solid var(--ink);border-radius:7px;color:var(--ink);text-decoration:none;font-weight:560;font-size:12.5px}a.open:hover{background:var(--ground)}a.open.primary{background:var(--ember);border-color:var(--ember)}.empty h1{margin-bottom:6px}
@@ -0,0 +1,156 @@
1
+ (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();const Gt=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Vt=/^(you|[a-z0-9][a-z0-9-]*:\S{1,80})$/,L=e=>typeof e=="string"&&Gt.test(e),Qt=e=>typeof e=="string"&&Vt.test(e),Zt=e=>String(e).normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,56).replace(/-+$/,"")||"step";function yt(e,t){const n=t instanceof Set?i=>t.has(i):i=>i in t,s=Zt(e);if(!n(s))return s;for(let i=2;;i++)if(!n(`${s}-${i}`))return`${s}-${i}`}const en=(e,t)=>e.edges.filter(n=>n.to===t).map(n=>n.from),kt=(e,t,n=!1)=>e.edges.filter(s=>s.from===t&&!(n&&s.kind==="after")).map(s=>s.to);function tn(e,t,n=!1){const s=new Map;let i=[t];for(let o=1;i.length;o++){const l=[];for(const a of i)for(const r of kt(e,a,n))r===t||s.has(r)||(s.set(r,o),l.push(r));i=l}return s}const eo=(e,t,n)=>t===n||tn(e,t).has(n);function xt(e,t){return!e?.length||!t?.length?!1:e.some(n=>t.some(s=>n===s||et(n,s)||et(s,n)))}function nn(e){const t=[],n=s=>{const i=t[t.length-1];i&&(i.k==="deep"||i.k==="star")?s==="deep"&&(i.k="deep"):t.push({k:s})};for(let s=0;s<e.length;s++){const i=e[s];i==="*"&&e[s+1]==="*"?(n("deep"),s++,e[s+1]==="/"&&s++):i==="*"?n("star"):i==="?"?t.push({k:"any"}):t.push({k:"lit",ch:i})}return t}function et(e,t){if(!/[*?]/.test(e))return!1;const n=nn(e),s=t.length;let i=new Uint8Array(s+1),o=new Uint8Array(s+1);i[s]=1;for(let l=n.length-1;l>=0;l--){const a=n[l];for(let r=s;r>=0;r--)a.k==="deep"?o[r]=i[r]||r<s&&o[r+1]?1:0:a.k==="star"?o[r]=i[r]||r<s&&t[r]!=="/"&&o[r+1]?1:0:r===s?o[r]=0:o[r]=(a.k==="any"?t[r]!=="/":t[r]===a.ch)&&i[r+1]?1:0;[i,o]=[o,i]}return i[0]===1}const tt=["not_started","in_progress","waiting","done","failed","cancelled"],nt=["planning","approved","executing","paused","done","abandoned"],sn=["task","context"],st=["needs","after","approve","ask","input"],to=new Set(["approve","ask","input"]),F=(e,t=0,n=1/0)=>typeof e=="string"&&e.length>=t&&e.length<=n,le=64,Be=256,X=4e3,vt=8,St=80,on=e=>Array.isArray(e)&&e.length>=1&&e.length<=vt&&e.every(t=>F(t,1,St)&&t.trim()===t),an=`options is 1-${vt} answers, each 1-${St} characters with no space at either end`,oe=2e3,We=e=>Array.isArray(e)&&e.length<=le&&e.every(t=>F(t,1,Be)),rn=`files is a list of paths or globs (at most ${le}, each 1-${Be} characters)`,At=64,ln=e=>Array.isArray(e)&&e.length<=At&&e.every(t=>L(t)),dn=`touches is a list of box ids from the architecture (at most ${At})`,cn=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function un(e,t,n,s){for(const i of Object.keys(e))t.includes(i)||s.push(`${n}: unknown field "${i}"`)}const fn={"node.add":{required:["label"],optional:["id","kind","detail","group","files","touches","after"],ids:["id"]},"node.set":{required:["id"],optional:["label","kind","detail","group","files","touches"],ids:["id"],oneOf:["label","kind","detail","group","files","touches"]},"node.remove":{required:["id"],ids:["id"]},"edge.add":{required:["from","to"],optional:["label","kind","options"],ids:["from","to"]},"edge.remove":{required:["from","to"],ids:["from","to"]},"edge.rewire":{required:["from","to"],optional:["newFrom","newTo"],ids:["from","to","newFrom","newTo"],oneOf:["newFrom","newTo"]},"edge.reverse":{required:["from","to"],ids:["from","to"]},"edge.set":{required:["from","to"],optional:["label","kind","options"],ids:["from","to"],oneOf:["label","kind","options"]},"gate.pass":{required:["from","to"],optional:["answer"],ids:["from","to"]},"gate.ask":{required:["from","to","question"],optional:["options"],ids:["from","to"]},"gate.reject":{required:["from","to"],optional:["reason"],ids:["from","to"]},"status.set":{required:["id","status"],optional:["note"],ids:["id"]},claim:{required:["id"],ids:["id"]},release:{required:["id"],ids:["id"]},"group.rename":{required:["from","to"]},"plan.set":{optional:["title","goal","phase"],oneOf:["title","goal","phase"]},"plan.stop":{},"layout.place":{required:["id","x","y"],ids:["id"]},"proposal.accept":{required:["id"]},"proposal.reject":{required:["id"],optional:["reason"]},review:{required:["ids"]}},no=new Set(["node.add","node.set","node.remove","edge.add","edge.remove","edge.rewire","edge.reverse","edge.set","group.rename"]);function so(e){if(!cn(e)||typeof e.op!="string")return['an op is an object with an "op" name'];const t=fn[e.op];if(!t)return[`"${e.op}" is not an op`];const n=[],s=["op",...t.required??[],...t.optional??[]];un(e,s,e.op,n);for(const i of t.required??[])e[i]===void 0&&n.push(`${e.op}: needs "${i}"`);t.oneOf&&!t.oneOf.some(i=>e[i]!==void 0)&&n.push(`${e.op}: needs one of ${t.oneOf.join(", ")}`);for(const i of t.ids??[])e[i]!==void 0&&!L(e[i])&&n.push(`${e.op}: "${e[i]}" is not a valid id`);return e.label!==void 0&&!F(e.label,e.op==="edge.set"||e.op==="edge.add"?0:1,120)&&n.push(`${e.op}: label is at most 120 characters`),e.detail!==void 0&&!F(e.detail,0,X)&&n.push(`${e.op}: detail is text of at most ${X} characters`),e.kind!==void 0&&(e.op.startsWith("edge.")?st.includes(e.kind)||n.push(`${e.op}: kind is one of ${st.join(", ")}`):sn.includes(e.kind)||n.push(`${e.op}: kind is task or context`)),e.question!==void 0&&!F(e.question,1,oe)&&n.push(`${e.op}: question is 1-${oe} characters`),e.answer!==void 0&&!F(e.answer,0,oe)&&n.push(`${e.op}: answer is at most ${oe} characters`),e.options!==void 0&&!on(e.options)&&n.push(`${e.op}: ${an}`),e.files!==void 0&&!We(e.files)&&n.push(`${e.op}: ${rn}`),e.touches!==void 0&&!ln(e.touches)&&n.push(`${e.op}: ${dn}`),e.group!==void 0&&!(e.op==="node.set"&&e.group===null)&&!F(e.group,1,80)&&n.push(`${e.op}: group is 1-80 characters`),e.after!==void 0&&!(Array.isArray(e.after)&&e.after.every(L))&&n.push(`${e.op}: after is a list of step ids`),e.op==="status.set"&&!tt.includes(e.status)&&n.push(`status.set: "${e.status}" is not a status (${tt.join(", ")})`),e.note!==void 0&&!F(e.note,0,oe)&&n.push(`${e.op}: note is at most ${oe} characters`),e.op==="group.rename"&&(!F(e.from,1,80)||!F(e.to,1,80))&&n.push("group.rename: from and to are group names of 1-80 characters"),e.title!==void 0&&!F(e.title,1,200)&&n.push("plan.set: title is 1-200 characters"),e.goal!==void 0&&!F(e.goal)&&n.push("plan.set: goal is text"),e.phase!==void 0&&!nt.includes(e.phase)&&n.push(`plan.set: phase is one of ${nt.join(", ")}`),e.op==="layout.place"&&!(Number.isFinite(e.x)&&Number.isFinite(e.y))&&n.push("layout.place: x and y are numbers"),(e.op==="proposal.accept"||e.op==="proposal.reject")&&!F(e.id,1,64)&&n.push(`${e.op}: needs a proposal id`),e.reason!==void 0&&!F(e.reason,0,1e3)&&n.push(`${e.op}: reason is at most 1000 characters`),e.op==="review"&&!(Array.isArray(e.ids)&&e.ids.length&&e.ids.every(L))&&n.push("review: ids is a non-empty list of step ids"),n}const ot=(e,t)=>JSON.stringify(e)===JSON.stringify(t),je=e=>`${e.from}\0${e.to}`,ie=e=>e.kind??"needs";function Te(e,t){const n=(e.label??"")!==(t.label??"")?t.label??"":void 0,s=ie(e)!==ie(t)?ie(t):void 0;return n===void 0&&s===void 0?null:ae({op:"edge.set",from:t.from,to:t.to,label:n,kind:s})}function pn(e,t,{bridge:n=!1}={}){const s=[],i=[],o={};for(const u of["title","goal","phase"])e[u]!==t[u]&&t[u]!==void 0&&(o[u]=t[u]);Object.keys(o).length&&s.push({op:"plan.set",...o}),t.rev!==e.rev&&i.push("rev (the server counts revisions)"),ot(e.proposals??[],t.proposals??[])||i.push("proposals (accept or reject them instead)");const l=Object.keys(t.nodes).filter(u=>!(u in e.nodes)),a=Object.keys(e.nodes).filter(u=>!(u in t.nodes)),r=Object.keys(t.nodes).filter(u=>u in e.nodes);for(const u of l){const c=t.nodes[u];s.push(ae({op:"node.add",id:u,label:c.label,kind:c.kind,detail:c.detail,group:c.group,files:c.files,touches:c.touches}))}for(const u of r){const c=e.nodes[u],g=t.nodes[u],b={};for(const v of["label","kind","detail","files","touches"])!ot(c[v],g[v])&&g[v]!==void 0&&(b[v]=g[v]);c.kind==="context"&&g.kind===void 0&&(b.kind="task"),c.detail!==void 0&&g.detail===void 0&&(b.detail=""),c.files!==void 0&&g.files===void 0&&(b.files=[]),c.touches!==void 0&&g.touches===void 0&&(b.touches=[]),c.group!==g.group&&(b.group=g.group??null),Object.keys(b).length&&s.push({op:"node.set",id:u,...b})}const d=new Map(e.edges.map(u=>[je(u),u])),f=new Map(t.edges.map(u=>[je(u),u])),$=[...d].filter(([u,c])=>!f.has(u)&&c.from in t.nodes&&c.to in t.nodes).map(([,u])=>u),p=[...f].filter(([u])=>!d.has(u)).map(([,u])=>u);for(const u of[...$]){const c=p.find(b=>b.from===u.to&&b.to===u.from);if(!c)continue;s.push({op:"edge.reverse",from:u.from,to:u.to});const g=Te(u,c);g&&s.push(g),$.splice($.indexOf(u),1),p.splice(p.indexOf(c),1)}for(const u of[...$]){const c=p.find(b=>b.from===u.from||b.to===u.to);if(!c)continue;s.push(ae({op:"edge.rewire",from:u.from,to:u.to,newFrom:c.from!==u.from?c.from:void 0,newTo:c.to!==u.to?c.to:void 0}));const g=Te(u,c);g&&s.push(g),$.splice($.indexOf(u),1),p.splice(p.indexOf(c),1)}for(const u of $)s.push({op:"edge.remove",from:u.from,to:u.to});for(const u of a)s.push({op:"node.remove",id:u});if(n&&a.length){const u=new Set(a),c=(b,v)=>e.edges.filter(O=>O.to===b).flatMap(O=>u.has(O.from)?v.has(O.from)?[]:(v.add(O.from),c(O.from,v)):[O.from]),g=new Set;for(const b of e.edges)if(!(!u.has(b.from)||u.has(b.to)||!(b.to in t.nodes)||t.nodes[b.to].status==="done"))for(const v of c(b.from,new Set([b.from]))){const O=je({from:v,to:b.to});v===b.to||!(v in t.nodes)||f.has(O)||g.has(O)||(g.add(O),s.push({op:"edge.add",from:v,to:b.to}))}}for(const u of p)s.push(ae({op:"edge.add",from:u.from,to:u.to,label:u.label,kind:u.kind,options:u.kind==="ask"?u.options:void 0}));for(const[u,c]of f){const g=d.get(u),b=g&&Te(g,c);b&&s.push(b)}for(const u of[...r,...l]){const c=e.nodes[u]??{},g=t.nodes[u];if(g.kind==="context")continue;const b=c.status??"not_started",v=g.status??"not_started";(b!==v||(c.note??"")!==(g.note??""))&&s.push(ae({op:"status.set",id:u,status:v,note:g.note})),(c.statusFrom!==g.statusFrom||c.statusBy!==g.statusBy)&&b===v&&i.push(`${u}: statusFrom/statusBy (the server stamps them)`),c.owner!==g.owner&&(g.owner===void 0?s.push({op:"release",id:u}):i.push(`${u}: owner (a step is owned by claiming it)`))}for(const[u,c]of f){const g=d.get(u)??{from:c.from,to:c.to},b=ie(g)!==ie(c);c.question!==void 0&&(b||c.question!==g.question||JSON.stringify(c.options)!==JSON.stringify(g.options))&&!c.passed?s.push({op:"gate.ask",from:c.from,to:c.to,question:c.question,...c.options?{options:c.options}:{}}):c.options!==void 0&&c.question===void 0&&ie(c)==="ask"&&(b||JSON.stringify(c.options)!==JSON.stringify(g.options))&&s.push({op:"edge.set",from:c.from,to:c.to,options:c.options}),c.passed&&(b||!g.passed)?s.push(ae({op:"gate.pass",from:c.from,to:c.to,answer:c.answer})):!c.passed&&g.passed&&!b&&i.push(`${c.from} → ${c.to}: passed (a checkpoint is not taken back; change the arrow's kind to reset it)`)}return{ops:s,ignored:i}}function ae(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const R=(e,t=120)=>{const n=String(e).replace(/\s+/g," ").trim();return`"${n.length>t?`${n.slice(0,t-1)}…`:n}"`},hn={not_started:"not started",in_progress:"in progress",waiting:"waiting for you",done:"done",failed:"failed",cancelled:"cancelled"},$n=e=>hn[e]??e,at={after:"order only",approve:"checkpoint: the person approves its result first",ask:"checkpoint: ask the person first",input:"checkpoint: needs input from the person"};function gn(e){switch(e.op){case"node.add":return`add step ${e.id??""}${e.id?" ":""}${R(e.label)}${e.kind==="context"?" (context)":""}${e.group?` in ${R(e.group)}`:""}${e.after?.length?`, after ${e.after.join(", ")}`:""}`;case"node.set":{const t=[];return e.label!==void 0&&t.push(`label → ${R(e.label)}`),e.kind!==void 0&&t.push(`kind → ${e.kind}`),e.detail!==void 0&&t.push(e.detail===""?"detail cleared":"detail rewritten"),e.files!==void 0&&t.push(`files → ${e.files.length?e.files.join(", "):"none"}`),e.touches!==void 0&&t.push(`changes boxes → ${e.touches.length?e.touches.join(", "):"none named"}`),e.group!==void 0&&t.push(e.group===null?"out of its group":`group → ${R(e.group)}`),`change ${e.id}: ${t.join("; ")}`}case"node.remove":return`remove step ${e.id}`;case"edge.add":return`${e.to} now depends on ${e.from}${e.kind&&e.kind!=="needs"?`, ${at[e.kind]}`:""}${e.label?` (${R(e.label,40)})`:""}`;case"edge.remove":return`${e.to} no longer depends on ${e.from}`;case"edge.rewire":return`arrow ${e.from} → ${e.to} is now ${e.newFrom??e.from} → ${e.newTo??e.to}`;case"edge.reverse":return`arrow ${e.from} → ${e.to} flipped to ${e.to} → ${e.from}`;case"edge.set":{const t=[];return e.kind!==void 0&&t.push(e.kind==="needs"?"a plain dependency":at[e.kind]),e.label!==void 0&&t.push(`label ${R(e.label,40)}`),`arrow ${e.from} → ${e.to}: ${t.join("; ")}`}case"gate.pass":return`the checkpoint ${e.from} → ${e.to} is passed${e.answer?`: ${R(e.answer,300)}`:""}; ${e.to} may start`;case"gate.ask":return`asked the person before ${e.to}: ${R(e.question,300)}${e.options?.length?`, offering ${e.options.map(t=>R(t,60)).join(" / ")}`:""}`;case"gate.reject":return`${e.from} was sent back, not approved${e.reason?` (${R(e.reason,300)})`:""}: it is to be done again`;case"status.set":return`${e.id} is ${$n(e.status)}${e.note?` (${R(e.note,160)})`:""}`;case"claim":return`take ${e.id}`;case"release":return`let go of ${e.id}`;case"group.rename":return`rename group ${R(e.from)} to ${R(e.to)}`;case"plan.set":{const t=[];return e.title!==void 0&&t.push(`title → ${R(e.title)}`),e.goal!==void 0&&t.push(`goal → ${R(e.goal,200)}`),e.phase!==void 0&&t.push(`phase → ${e.phase}`),`set the plan's ${t.join("; ")}`}case"plan.stop":return"stop the plan: the agents stop now, it is back in planning, and the steps in progress are put back";case"layout.place":return`place ${e.id}`;case"proposal.accept":return`accept proposal ${e.id}`;case"proposal.reject":return`reject proposal ${e.id}${e.reason?` (${R(e.reason,160)})`:""}`;case"review":return`${e.ids.join(", ")} reviewed: no change needed`;default:return String(e.op)}}const mn=[/^classDef\s+\S+\s+\S/,/^class\s+[\p{L}\p{N}_,\-\s]+\s+[\w-]+\s*$/u,/^style\s+[\p{L}\p{N}_-]+\s+[^\s\-=.~<]/u,/^linkStyle\s+(default|[\d,\s]+)\s/,/^click\s+[\p{L}\p{N}_-]+\s/u,/^acc(Title|Descr)\s*[:{]/,/^direction\s+(LR|RL|TD|TB|BT)\s*$/],ge=[["(((",")))"],["((","))"],["([","])"],["[[","]]"],["[(",")]"],["[/","/]"],["[/","\\]"],["[\\","\\]"],["[\\","/]"],["{{","}}"],["(",")"],["[","]"],["{","}"],[">","]"]],wn=/^(<?)(-{2,}|={2,}|-\.+-|~{3,})([>ox]?)/,bn=/^(--|==|-\.)\s+([^|]+?)\s+(-{2,}>|={2,}>|\.-+>|-{3,}|={3,}|\.-+)/,yn=/^[\p{L}\p{N}_]+(?:-[\p{L}\p{N}_]+)*/u,fe=e=>e.replace(/#quot;/g,'"').replace(/#amp;/g,"&").replace(/#lt;/g,"<").replace(/#gt;/g,">").replace(/#(\d+);/g,(t,n)=>String.fromCodePoint(Number(n)));function Ot(e,{rich:t=!1}={}){const n={direction:"TD",nodes:new Map,edges:[],warnings:[],...t?{subgraphs:[]}:{}},s=[],i=[];let o=!1;if(e.replace(/\r\n?/g,`
2
+ `).split(`
3
+ `).forEach((a,r)=>{const d=`line ${r+1}`;for(const f of kn(a.replace(/%%.*$/,""))){const $=f.trim();if(!$)continue;if(!o){const c=/^(flowchart|graph)(?:\s+(LR|RL|TD|TB|BT))?\s*$/.exec($);if(!c)throw new Error(`${d}: a plan diagram starts with "flowchart" or "graph", not "${$.slice(0,30)}"`);n.direction=c[2]==="LR"||c[2]==="RL"?"LR":"TD",o=!0;continue}if($==="end"){if(!s.length)throw new Error(`${d}: "end" with no subgraph open`);s.pop(),i.pop();continue}const p=/^subgraph\s+(.+)$/.exec($);if(p){if(s.push(xn(p[1])),n.subgraphs){const c=/^([\p{L}\p{N}_-]+)\s*(?:\[|$)/u.exec(p[1])?.[1];i.push(n.subgraphs.push({...c?{id:c}:{},title:s.at(-1),...i.length?{parent:i.at(-1)}:{}})-1)}continue}const u=t?/^class\s+([\p{L}\p{N}_,\-\s]+?)\s+([\w-]+)\s*$/u.exec($):null;if(u){for(const c of u[1].split(",").map(g=>g.trim()).filter(Boolean)){const g=n.nodes.get(c);g&&(g.cls=u[2])}continue}mn.some(c=>c.test($))||vn($,d,s.at(-1),n,t?i.at(-1)??-1:void 0)}}),!o)throw new Error('this is not a Mermaid flowchart: it has no "flowchart" or "graph" line');return s.length&&n.warnings.push(`${s.length} subgraph${s.length===1?" was":"s were"} never closed with "end"`),n}function kn(e){const t=[];let n=0,s=!1,i=0;for(let o=0;o<e.length;o++){const l=e[o];l==='"'?s=!s:!s&&"[({".includes(l)?n++:!s&&"])}".includes(l)?n=Math.max(0,n-1):!s&&n===0&&l===";"&&(t.push(e.slice(i,o)),i=o+1)}return t.push(e.slice(i)),t}function xn(e){const t=/^[\p{L}\p{N}_-]+\s*\[\s*"?(.*?)"?\s*\]\s*$/u.exec(e);if(t)return fe(t[1]);const n=/^"(.*)"$/.exec(e.trim());return n?fe(n[1]):e.trim()}function vn(e,t,n,s,i){let o=0;const l=()=>e.slice(o),a=()=>{for(;o<e.length&&/\s/.test(e[o]);)o++},r=()=>{a();const p=yn.exec(l());if(!p)throw new Error(`${t}: expected a node id at "${l().slice(0,30)}"`);const u=p[0];o+=u.length;let c,g;const b=ge.find(([C])=>l().startsWith(C));if(b){o+=b[0].length;const C=l();if(C.startsWith('"')){const T=C.indexOf('"',1);if(T<0)throw new Error(`${t}: an unclosed quote in ${u}'s label`);c=C.slice(1,T),o+=T+1,a();const j=ge.find(([k,M])=>k===b[0]&&l().startsWith(M))??ge.find(([,k])=>l().startsWith(k));if(!j)throw new Error(`${t}: ${u}'s label is not closed`);o+=j[1].length}else{const T=ge.filter(([k])=>k===b[0]).map(([,k])=>k),j=Math.min(...T.map(k=>C.indexOf(k)).filter(k=>k>=0));if(!Number.isFinite(j))throw new Error(`${t}: ${u}'s label is not closed`);c=C.slice(0,j).trim(),o+=j+(T.find(k=>C.startsWith(k,j))??T[0]).length}g=fe(c).replace(/^`|`$/g,"").trim(),c=g.replace(/<br\s*\/?>/gi," ").trim()}const v=/^:::([\w-]+)/.exec(l());v&&(o+=v[0].length);const O=s.nodes.get(u),q=i!==void 0?{...b?{shape:b[0]}:{},...g?{raw:g}:{},...v?{cls:v[1]}:{}}:{};return O?(c&&(O.label=c),Object.assign(O,q)):s.nodes.set(u,{label:c||u,...n?{group:n}:{},...i!==void 0&&i>=0?{frame:i}:{},...q}),u},d=()=>{const p=[r()];for(a();l().startsWith("&");)o++,p.push(r()),a();return p},f=()=>{a();const p=bn.exec(l());if(p)return o+=p[0].length,{...rt(p[1],fe(p[2].trim())),twoWay:!1};const u=wn.exec(l());if(!u)return null;o+=u[0].length,a();let c;const g=/^\|([^|]*)\|/.exec(l());return g&&(o+=g[0].length,c=fe(g[1].trim().replace(/^"(.*)"$/,"$1"))),{...rt(u[2],c),twoWay:u[1]==="<"}};let $=d();for(;;){const p=f();if(!p)break;const u=d();for(const c of $)for(const g of u)s.edges.push({from:c,to:g,...p.kind?{kind:p.kind}:{},...p.label?{label:p.label}:{}}),p.twoWay&&s.warnings.push(`${t}: ${c} <--> ${g} points both ways; kept as ${c} → ${g}`);$=u}if(a(),o<e.length)throw new Error(`${t}: could not read "${l().slice(0,40)}"`)}function Sn(e){e=e.replace(/\r\n?/g,`
4
+ `);const t=/^---\n([\s\S]*?)\n---/.exec(e)?.[1]??"",n=i=>{const o=new RegExp(`^${i}:\\s*(.*)$`,"m").exec(t);return o&&o[1].trim().replace(/^(['"])(.*)\1$/,"$2")||void 0},s=/```mermaid\s*\n([\s\S]*?)```/.exec(e);return{title:n("name"),goal:n("overview"),mermaid:s?s[1]:null}}const An=/^(unchanged|existing|untouched|context)\b/i;function On(e){const t=[],n=[...e.warnings];for(const[o,l]of e.nodes)t.push({op:"node.add",id:o,label:l.label.slice(0,120),...l.group?{group:l.group.slice(0,80)}:{},...l.group&&An.test(l.group)?{kind:"context"}:{}});const s=new Map,i=(o,l)=>{const a=new Set([o]),r=[o];for(;r.length;){const d=r.pop();if(d===l)return!0;for(const f of s.get(d)??[])a.has(f)||(a.add(f),r.push(f))}return!1};for(const o of e.edges){if(o.from===o.to){n.push(`left out ${o.from} → ${o.to}: a step cannot depend on itself`);continue}if(!s.get(o.from)?.has(o.to)){if(i(o.to,o.from)){n.push(`left out ${o.from} → ${o.to}: it closes a loop, and a plan cannot loop`);continue}s.has(o.from)||s.set(o.from,new Set),s.get(o.from).add(o.to),t.push({op:"edge.add",from:o.from,to:o.to,...o.label?{label:o.label.slice(0,120)}:{},...o.kind?{kind:o.kind}:{}})}}return{ops:t,warnings:n}}const jn=/[^A-Za-z0-9 _.\-/]/,it=e=>jn.test(e)?`["${e.replace(/"/g,"#quot;")}"]`:`[${e}]`,Tn=(e,t)=>{const n=String(e??"").trim(),s=t==="approve"||t==="ask"||t==="input",i=s?n?`${t}: ${n}`:t:n,o=t==="after"?"-.->":s?"==>":"-->";return i?`${o}|"${i.replace(/"/g,"#quot;")}"|`:o},_n=/^(approve|ask|input)\s*(?::\s*([\s\S]*))?$/i;function rt(e,t){if(e.startsWith("-."))return{kind:"after",...t?{label:t}:{}};const n=e.startsWith("==")&&t?_n.exec(t):null;return n?{kind:n[1].toLowerCase(),...n[2]?.trim()?{label:n[2].trim()}:{}}:t?{label:t}:{}}const Cn=(e,t)=>e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")||`group${t}`;function oo(e,t="LR"){const n=[`flowchart ${t==="TD"?"TD":"LR"}`],s=Object.keys(e.nodes),i=[];for(const o of s){const l=e.nodes[o].group;i.includes(l)||i.push(l)}i.forEach((o,l)=>{const a=s.filter(r=>e.nodes[r].group===o);if(o===void 0){for(const r of a)n.push(` ${r}${it(e.nodes[r].label)}`);return}n.push(` subgraph ${Cn(o,l)} ["${o.replace(/"/g,"#quot;")}"]`);for(const r of a)n.push(` ${r}${it(e.nodes[r].label)}`);n.push(" end")});for(const o of e.edges)!(o.from in e.nodes)||!(o.to in e.nodes)||n.push(` ${o.from} ${Tn(o.label,o.kind)} ${o.to}`);return n.join(`
5
+ `)}function Mn(e,t=""){const n=/\.(md|markdown)$/i.test(t)||/```mermaid/.test(e);let s=e,i,o,l="mermaid";if(n){const $=Sn(e);if(!$.mermaid)throw new Error("there is no ```mermaid block in this file");({mermaid:s,title:i,goal:o}=$),l=/\.plan\.md$/i.test(t)||$.title?"cursor-plan":"markdown"}const a=Ot(s),{ops:r,warnings:d}=On(a),f=(t.split(/[\\/]/).pop()??"").replace(/\.(plan\.)?(md|markdown|mmd|mermaid|txt)$/i,"").replace(/_[0-9a-f]{8}$/i,"").replace(/[_-]+/g," ").trim();return{title:(i??(f?f[0].toUpperCase()+f.slice(1):"Imported plan")).slice(0,200),goal:o,direction:a.direction,source:{kind:l,...t?{path:t}:{}},ops:r,warnings:d}}const Le=["service","group"],ee=(e,t)=>Object.keys(e.nodes).filter(n=>e.nodes[n].in===t),pe=(e,t)=>Object.values(e.nodes).some(n=>n.in===t);function Nn(e,t){const n=[];for(let s=e.nodes[t]?.in;s&&!n.includes(s)&&s!==t;s=e.nodes[s]?.in)n.push(s);return n}function jt(e,t){const n=[],s=[t];for(;s.length;)for(const i of ee(e,s.pop()))i===t||n.includes(i)||(n.push(i),s.push(i));return n}function En(e){for(const t of Object.keys(e.nodes)){const n=[t];for(let s=e.nodes[t].in;s&&e.nodes[s];s=e.nodes[s].in){if(s===t)return[...n,t];if(n.includes(s))break;n.push(s)}}return null}const qn=(e,t)=>e.edges.filter(n=>n.to===t).map(n=>n.from);function ao(e,t,n){const s=n instanceof Set?n:new Set(n);return Nn(e,t).reverse().find(o=>s.has(o))??t}const De="dcursed.arch/0",be=["person","service","component","store","queue","group"],ye=["draft","accepted"],lt=["dcursed","mermaid","c4","markdown","cursor-plan"],te=120,dt=40,ke=60,N=(e,t=0,n=1/0)=>typeof e=="string"&&e.length>=t&&e.length<=n,H=e=>e!=null&&typeof e=="object"&&!Array.isArray(e),Tt=`files is a list of paths or globs (at most ${le}, each 1-${Be} characters)`;function z(e,t,n,s){for(const i of Object.keys(e))t.includes(i)||s.push(`${n}: unknown field "${i}"`)}const Rn=["label","kind","external","in","tech","detail","files","planned","retiring"],Ln=["from","to","label","tech","async","via","planned","retiring"];function Dn(e,t,n){const s=`box ${t}`;if(!H(e)){n.push(`${s}: not an object`);return}z(e,Rn,s,n),N(e.label,1,120)||n.push(`${s}: needs a label of 1-120 characters`),be.includes(e.kind)||n.push(`${s}: kind is one of ${be.join(", ")}`),e.external!==void 0&&e.external!==!0&&n.push(`${s}: external is true (leave it out for a box you run)`),e.in!==void 0&&!L(e.in)&&n.push(`${s}: in is the id of the service or group it sits in`),e.tech!==void 0&&!N(e.tech,1,te)&&n.push(`${s}: tech is 1-${te} characters`),e.detail!==void 0&&!N(e.detail,0,X)&&n.push(`${s}: detail is text of at most ${X} characters`),e.files!==void 0&&!We(e.files)&&n.push(`${s}: ${Tt}`),e.planned!==void 0&&!L(e.planned)&&n.push(`${s}: planned is the id of the plan that adds it`),e.retiring!==void 0&&!L(e.retiring)&&n.push(`${s}: retiring is the id of the plan that removes it`),e.planned!==void 0&&e.retiring!==void 0&&n.push(`${s}: a box is planned or retiring, not both`)}function Pn(e,t,n,s){if(!H(e)){s.push(`${t}: not an object`);return}z(e,["from","to","label"],t,s),e.label!==void 0&&!N(e.label,0,120)&&s.push(`${t}: label is at most 120 characters`);for(const i of["from","to"])e[i]in n?n[e[i]].kind==="group"&&s.push(`${t}: ${e[i]} is a group, a frame and not something that is called`):s.push(`${t}: "${e[i]}" is not a box`)}function In(e){const t=[];if(!H(e))return["an architecture is a JSON object"];if(z(e,["schema","title","goal","rev","phase","source","nodes","edges","flows","proposals"],"architecture",t),e.schema!==De&&t.push(`architecture: schema is "${De}"`),N(e.title,1,200)||t.push("architecture: needs a title of 1-200 characters"),e.goal!==void 0&&!N(e.goal)&&t.push("architecture: goal is text"),(!Number.isInteger(e.rev)||e.rev<0)&&t.push("architecture: rev is a whole number from 0"),ye.includes(e.phase)||t.push(`architecture: phase is one of ${ye.join(", ")}`),e.source!==void 0&&(!H(e.source)||!lt.includes(e.source.kind)?t.push(`architecture: source.kind is one of ${lt.join(", ")}`):z(e.source,["kind","url","path","importedAt"],"architecture.source",t)),!H(e.nodes))return[...t,"architecture: nodes is an object keyed by box id"];for(const[o,l]of Object.entries(e.nodes))L(o)||t.push(`box "${o}": not a valid id`),Dn(l,o,t);const n=e.nodes;for(const[o,l]of Object.entries(n)){if(!H(l)||l.in===void 0||!L(l.in))continue;const a=n[l.in];a?Le.includes(a.kind)||t.push(`box ${o}: sits in ${l.in}, which is a ${a.kind}; only a service or a group holds other boxes`):t.push(`box ${o}: sits in "${l.in}", which is not a box`)}if(!t.some(o=>o.includes("sits in"))){const o=En(e);o&&t.push(`boxes sit inside each other in a loop: ${o.join(" → ")}`)}if(!Array.isArray(e.edges))return[...t,"architecture: edges is a list"];const s=new Set;if(e.edges.forEach((o,l)=>{const a=`arrow ${l+1}`;if(!H(o)){t.push(`${a}: not an object`);return}z(o,Ln,a,t),o.label!==void 0&&!N(o.label,0,120)&&t.push(`${a}: label is at most 120 characters`),o.tech!==void 0&&!N(o.tech,1,te)&&t.push(`${a}: tech is 1-${te} characters`),o.async!==void 0&&o.async!==!0&&t.push(`${a}: async is true (leave it out for an arrow that waits for the answer)`),o.planned!==void 0&&!L(o.planned)&&t.push(`${a}: planned is the id of the plan that adds it`),o.retiring!==void 0&&!L(o.retiring)&&t.push(`${a}: retiring is the id of the plan that removes it`),o.planned!==void 0&&o.retiring!==void 0&&t.push(`${a}: an arrow is planned or retiring, not both`),o.from in n||t.push(`${a}: "${o.from}" is not a box`),o.to in n||t.push(`${a}: "${o.to}" is not a box`),o.from===o.to&&t.push(`${a}: ${o.from} cannot use itself`),o.via!==void 0&&(o.via in n?n[o.via].kind!=="queue"&&t.push(`${a}: via ${o.via} is a ${n[o.via].kind}; it names the queue that carries the arrow`):t.push(`${a}: via "${o.via}" is not a box`));const r=`${o.from}\0${o.to}`;s.has(r)&&t.push(`${a}: ${o.from} → ${o.to} is there twice`),s.add(r);for(const d of[o.from,o.to])d in n&&(n[d].kind==="group"?t.push(`${a}: ${d} is a group, a frame round other boxes; it takes no arrows`):pe(e,d)&&t.push(`${a}: ${d} has boxes inside it, so it is a frame and takes no arrows; the arrows belong to the boxes inside`))}),!Array.isArray(e.flows))return[...t,"architecture: flows is a list (empty if there are none)"];e.flows.length>dt&&t.push(`architecture: at most ${dt} flows`);const i=new Set;return e.flows.forEach((o,l)=>{const a=`flow ${o?.id??l+1}`;if(!H(o)){t.push(`${a}: not an object`);return}z(o,["id","title","steps"],a,t),L(o.id)?i.has(o.id)&&t.push(`${a}: two flows are called ${o.id}`):t.push(`${a}: needs an id (letters, digits, "-", "_" or ".")`),i.add(o.id),N(o.title,1,120)||t.push(`${a}: needs a title of 1-120 characters`),!Array.isArray(o.steps)||!o.steps.length||o.steps.length>ke?t.push(`${a}: steps is a list of 1-${ke} steps`):o.steps.forEach((r,d)=>Pn(r,`${a}, step ${d+1}`,n,t))}),e.proposals!==void 0&&(Array.isArray(e.proposals)?e.proposals.forEach((o,l)=>{const a=`proposal ${o?.id??l+1}`;if(!H(o)){t.push(`${a}: not an object`);return}z(o,["id","by","at","reason","ops"],a,t),N(o.id,1,64)||t.push(`${a}: needs an id`),Qt(o.by)||t.push(`${a}: by is not an actor`),o.reason!==void 0&&!N(o.reason,0,1e3)&&t.push(`${a}: reason is at most 1000 characters`),!Array.isArray(o.ops)||!o.ops.length?t.push(`${a}: needs at least one op`):o.ops.forEach((r,d)=>t.push(..._t(r).map(f=>`${a}, op ${d+1}: ${f}`)))}):t.push("architecture: proposals is a list")),t}const Fn={"box.add":{required:["label","kind"],optional:["id","in","tech","detail","files","external","planned","retiring"],ids:["id","in"]},"box.set":{required:["id"],optional:["label","kind","in","tech","detail","files","external","planned","retiring"],ids:["id","in"],oneOf:["label","kind","in","tech","detail","files","external","planned","retiring"]},"box.remove":{required:["id"],ids:["id"]},"arrow.add":{required:["from","to"],optional:["label","tech","async","via","planned","retiring"],ids:["from","to","via"]},"arrow.remove":{required:["from","to"],ids:["from","to"]},"arrow.rewire":{required:["from","to"],optional:["newFrom","newTo"],ids:["from","to","newFrom","newTo"],oneOf:["newFrom","newTo"]},"arrow.reverse":{required:["from","to"],ids:["from","to"]},"arrow.set":{required:["from","to"],optional:["label","tech","async","via","planned","retiring"],ids:["from","to","via"],oneOf:["label","tech","async","via","planned","retiring"]},"flow.add":{required:["id","title","steps"],ids:["id"]},"flow.set":{required:["id"],optional:["title","steps"],ids:["id"],oneOf:["title","steps"]},"flow.remove":{required:["id"],ids:["id"]},"arch.set":{optional:["title","goal","phase"],oneOf:["title","goal","phase"]},"layout.place":{required:["id","x","y"],ids:["id"]},"layout.fold":{required:["id","folded"],ids:["id"]},"proposal.accept":{required:["id"]},"proposal.reject":{required:["id"],optional:["reason"]}},Bn=new Set(["box.add","box.set","box.remove","arrow.add","arrow.remove","arrow.rewire","arrow.reverse","arrow.set","flow.add","flow.set","flow.remove"]),Wn={"box.set":["in","planned","retiring"],"arrow.set":["via","planned","retiring"]};function _t(e){if(!H(e)||typeof e.op!="string")return['an op is an object with an "op" name'];const t=Fn[e.op];if(!t)return[`"${e.op}" is not an op`];const n=[],s=["op",...t.required??[],...t.optional??[]];z(e,s,e.op,n);for(const l of t.required??[])e[l]===void 0&&n.push(`${e.op}: needs "${l}"`);t.oneOf&&!t.oneOf.some(l=>e[l]!==void 0)&&n.push(`${e.op}: needs one of ${t.oneOf.join(", ")}`);const i=Wn[e.op]??[];for(const l of t.ids??[])e[l]!==void 0&&!(e[l]===null&&i.includes(l))&&!L(e[l])&&n.push(`${e.op}: "${e[l]}" is not a valid id`);const o=e.op==="box.add"||e.op==="box.set";e.label!==void 0&&!N(e.label,e.op==="arrow.add"||e.op==="arrow.set"?0:1,120)&&n.push(`${e.op}: label is at most 120 characters`),e.tech!==void 0&&!N(e.tech,0,te)&&n.push(`${e.op}: tech is at most ${te} characters`),e.detail!==void 0&&!N(e.detail,0,X)&&n.push(`${e.op}: detail is text of at most ${X} characters`),e.kind!==void 0&&!be.includes(e.kind)&&n.push(`${e.op}: kind is one of ${be.join(", ")}`),e.files!==void 0&&!We(e.files)&&n.push(`${e.op}: ${Tt}`),e.external!==void 0&&typeof e.external!="boolean"&&n.push(`${e.op}: external is true or false`),e.async!==void 0&&typeof e.async!="boolean"&&n.push(`${e.op}: async is true or false`);for(const l of["planned","retiring"])e[l]!==void 0&&e[l]!==null&&!L(e[l])&&n.push(`${e.op}: ${l} is a plan id${o||e.op.startsWith("arrow")?" (null clears it)":""}`);return e.planned&&e.retiring&&n.push(`${e.op}: a box or arrow is planned or retiring, not both`),e.title!==void 0&&!N(e.title,1,e.op==="flow.add"||e.op==="flow.set"?120:200)&&n.push(`${e.op}: title is a name of 1-${e.op.startsWith("flow")?120:200} characters`),e.goal!==void 0&&!N(e.goal)&&n.push("arch.set: goal is text"),e.phase!==void 0&&!ye.includes(e.phase)&&n.push(`arch.set: phase is one of ${ye.join(", ")}`),e.steps!==void 0&&(!Array.isArray(e.steps)||!e.steps.length||e.steps.length>ke?n.push(`${e.op}: steps is a list of 1-${ke} steps`):e.steps.forEach((l,a)=>{if(!H(l)){n.push(`${e.op}: step ${a+1} is not an object`);return}z(l,["from","to","label"],`${e.op}: step ${a+1}`,n),(!L(l.from)||!L(l.to))&&n.push(`${e.op}: step ${a+1} needs from and to, box ids`),l.label!==void 0&&!N(l.label,0,120)&&n.push(`${e.op}: step ${a+1}: label is at most 120 characters`)})),e.op==="layout.place"&&!(Number.isFinite(e.x)&&Number.isFinite(e.y))&&n.push("layout.place: x and y are numbers"),e.op==="layout.fold"&&typeof e.folded!="boolean"&&n.push("layout.fold: folded is true or false"),(e.op==="proposal.accept"||e.op==="proposal.reject")&&!N(e.id,1,64)&&n.push(`${e.op}: needs a proposal id`),e.reason!==void 0&&!N(e.reason,0,1e3)&&n.push(`${e.op}: reason is at most 1000 characters`),n}class He extends Error{}const A=e=>{throw new He(e)},_e=e=>Bn.has(e.op)||e.op==="arch.set"&&(e.title!==void 0||e.goal!==void 0);function ct(e,t,n){for(let i=0;i<t.length;i++){const o=_t(t[i]);if(o.length)return{kind:"rejected",index:i,op:t[i],why:o.join("; ")}}const s=n.actor.startsWith("server:")&&!n.propose;if((e.phase==="accepted"||n.propose)&&n.actor!=="you"&&!s&&t.some(_e)){const i=t.filter(_e),o=t.filter(f=>!_e(f)),l=Ce(e,i,{...n,actor:"you"});if(l.kind==="rejected")return{...l,index:t.indexOf(i[l.index])};const a={id:n.proposalId??`p${e.rev+1}`,by:n.actor,...n.at?{at:n.at}:{},...n.reason?{reason:n.reason}:{},ops:l.ops},r={...structuredClone(e),proposals:[...e.proposals??[],a]};if(!o.length)return{kind:"proposed",arch:{...r,rev:e.rev+1},proposal:a};const d=Ce({...r,rev:e.rev},o,n);return d.kind==="rejected"?{...d,index:t.indexOf(o[d.index])}:{...d,proposal:a}}return Ce(e,t,n)}function Ce(e,t,n){const s=structuredClone(e),i={who:n,you:n.actor==="you",impact:new Map,touched:new Set,placements:[],folds:[]},o=[];for(let a=0;a<t.length;a++)try{o.push(Ct(s,t[a],i));const r=In(s);r.length&&A(r[0])}catch(r){if(r instanceof He)return{kind:"rejected",index:a,op:t[a],why:r.message};throw r}s.rev=e.rev+1,s.proposals&&!s.proposals.length&&delete s.proposals;const l=[...i.impact].filter(([a])=>s.nodes[a]&&!i.touched.has(a)).map(([a,r])=>({id:a,reasons:[...r]})).sort((a,r)=>a.id.localeCompare(r.id));return{kind:"applied",arch:s,ops:o,impact:l,touched:[...i.touched].filter(a=>s.nodes[a]),placements:i.placements,folds:i.folds}}const Q=(e,t)=>e.nodes[t]??A(`there is no box ${t}`);function J(e,t,n){n!==void 0&&(n===""||n===null?delete e[t]:e[t]=n)}function Ct(e,t,n){const{you:s}=n,i=(a,r)=>{const d=n.impact.get(a);d?d.add(r):n.impact.set(a,new Set([r]))},o=(a,r)=>{for(const d of qn(e,a))i(d,`${a} ${r}`)},l=(a,r)=>{const d=Q(e,r);Le.includes(d.kind)||A(`${r} is a ${d.kind}; only a service or a group holds other boxes`),(r===a||jt(e,a).includes(r))&&A(`${a} cannot sit inside ${r}: that would put it inside itself`),e.edges.some(f=>f.from===r||f.to===r)&&A(`${r} has arrows of its own, and a box with boxes inside it is a frame, which takes none: move them to the boxes that will be inside it first`)};switch(t.op){case"box.add":{const a=t.id??yt(t.label,e.nodes);e.nodes[a]&&A(`box ${a} exists`);const r={label:t.label,kind:t.kind};return t.external&&(r.external=!0),t.in!==void 0&&(e.nodes[a]=r,l(a,t.in),r.in=t.in),J(r,"tech",t.tech),J(r,"detail",t.detail),t.files?.length&&(r.files=t.files),t.planned&&(r.planned=t.planned),t.retiring&&(r.retiring=t.retiring),e.nodes[a]=r,n.touched.add(a),{...t,id:a}}case"box.set":{const a=Q(e,t.id),r={label:a.label,kind:a.kind,tech:a.tech,detail:a.detail,files:JSON.stringify(a.files),external:a.external};if(t.label!==void 0&&(a.label=t.label),t.kind!==void 0&&t.kind!==a.kind){const f=ee(e,t.id);f.length&&!Le.includes(t.kind)&&A(`${t.id} has ${f.join(", ")} inside it: take them out before it becomes a ${t.kind}`),t.kind==="group"&&e.edges.some($=>$.from===t.id||$.to===t.id)&&A(`${t.id} has arrows, and a group is a frame round other boxes, which takes none`),a.kind==="queue"&&e.edges.some($=>$.via===t.id)&&A(`${t.id} carries arrows (via): they name a queue`),a.kind=t.kind}return t.in===null?delete a.in:t.in!==void 0&&(l(t.id,t.in),a.in=t.in),J(a,"tech",t.tech),J(a,"detail",t.detail),Array.isArray(t.files)&&!t.files.length?delete a.files:t.files!==void 0&&(a.files=t.files),t.external===!1?delete a.external:t.external===!0&&(a.external=!0),t.planned!==void 0&&(t.planned&&a.retiring&&A(`${t.id} is retiring: clear that first (retiring: null)`),t.planned?a.planned=t.planned:delete a.planned),t.retiring!==void 0&&(t.retiring&&a.planned&&A(`${t.id} is planned: clear that first (planned: null)`),t.retiring?a.retiring=t.retiring:delete a.retiring),n.touched.add(t.id),(a.label!==r.label||a.kind!==r.kind||a.tech!==r.tech||a.detail!==r.detail||JSON.stringify(a.files)!==r.files||a.external!==r.external)&&o(t.id,"changed"),t}case"box.remove":{const a=Q(e,t.id);o(t.id,"was removed");for(const r of ee(e,t.id))a.in?e.nodes[r].in=a.in:delete e.nodes[r].in;delete e.nodes[t.id],e.edges=e.edges.filter(r=>r.from!==t.id&&r.to!==t.id);for(const r of e.edges)r.via===t.id&&delete r.via;for(const r of e.flows)r.steps=r.steps.filter(d=>d.from!==t.id&&d.to!==t.id);return e.flows=e.flows.filter(r=>r.steps.length),t}case"arrow.add":return Hn(e,t),t;case"arrow.remove":{const a=Me(e,t.from,t.to);return e.edges.splice(e.edges.indexOf(a),1),t}case"arrow.rewire":case"arrow.reverse":{const a=Me(e,t.from,t.to),r=t.op==="arrow.reverse"?a.to:t.newFrom??a.from,d=t.op==="arrow.reverse"?a.from:t.newTo??a.to;return Mt(e,r,d,a),a.from=r,a.to=d,t}case"arrow.set":{const a=Me(e,t.from,t.to);return J(a,"label",t.label),J(a,"tech",t.tech),t.async===!1?delete a.async:t.async===!0&&(a.async=!0),t.via===null?delete a.via:t.via!==void 0&&(a.via=t.via),t.planned!==void 0&&(t.planned&&a.retiring&&A(`${t.from} → ${t.to} is retiring: clear that first (retiring: null)`),t.planned?a.planned=t.planned:delete a.planned),t.retiring!==void 0&&(t.retiring&&a.planned&&A(`${t.from} → ${t.to} is planned: clear that first (planned: null)`),t.retiring?a.retiring=t.retiring:delete a.retiring),t}case"flow.add":return e.flows.some(a=>a.id===t.id)&&A(`there is already a flow ${t.id}`),e.flows.push({id:t.id,title:t.title,steps:t.steps.map(ut)}),t;case"flow.set":{const a=e.flows.find(r=>r.id===t.id)??A(`there is no flow ${t.id}`);return t.title!==void 0&&(a.title=t.title),t.steps!==void 0&&(a.steps=t.steps.map(ut)),t}case"flow.remove":return e.flows.some(a=>a.id===t.id)||A(`there is no flow ${t.id}`),e.flows=e.flows.filter(a=>a.id!==t.id),t;case"arch.set":return t.phase!==void 0&&t.phase!==e.phase&&!s&&A("only you accept the architecture, or take it back to a draft"),t.title!==void 0&&(e.title=t.title),t.goal!==void 0&&(t.goal?e.goal=t.goal:delete e.goal),t.phase!==void 0&&(e.phase=t.phase),t;case"layout.place":return s||A("only you place a box: the layout is yours"),Q(e,t.id),pe(e,t.id)&&A(`${t.id} is a frame round other boxes: place the boxes inside it`),n.placements.push({id:t.id,x:t.x,y:t.y}),t;case"layout.fold":return s||A("only you fold a frame: the layout is yours"),Q(e,t.id),t.folded&&!pe(e,t.id)&&A(`${t.id} has nothing inside it to fold`),n.folds.push({id:t.id,folded:t.folded}),t;case"proposal.accept":{s||A("only you accept a proposal");const a=(e.proposals??[]).find(r=>r.id===t.id)??A(`there is no proposal ${t.id}`);e.proposals=(e.proposals??[]).filter(r=>r!==a);for(const r of a.ops)try{Ct(e,r,n)}catch(d){throw d instanceof He&&A(`proposal ${t.id} no longer applies: ${d.message}`),d}return t}case"proposal.reject":return s||A("only you reject a proposal"),(e.proposals??[]).some(a=>a.id===t.id)||A(`there is no proposal ${t.id}`),e.proposals=(e.proposals??[]).filter(a=>a.id!==t.id),t;default:return A(`"${t.op}" is not an op`)}}const ut=e=>({from:e.from,to:e.to,...e.label?{label:e.label}:{}});function Me(e,t,n){return e.edges.find(s=>s.from===t&&s.to===n)??A(`there is no arrow ${t} → ${n}`)}function Mt(e,t,n,s){const i=Q(e,t),o=Q(e,n);t===n&&A(`${t} cannot use itself`),e.edges.some(l=>l!==s&&l.from===t&&l.to===n)&&A(`${t} → ${n} is there already`);for(const[l,a]of[[t,i],[n,o]])a.kind==="group"&&A(`${l} is a group, a frame round other boxes; it takes no arrows`),pe(e,l)&&A(`${l} has boxes inside it, so it is a frame and takes no arrows: draw the arrow to one of the boxes inside (fold it to see them as one)`)}function Hn(e,t){Mt(e,t.from,t.to);const n={from:t.from,to:t.to};J(n,"label",t.label),J(n,"tech",t.tech),t.async&&(n.async=!0),t.via&&(n.via=t.via),t.planned&&(n.planned=t.planned),t.retiring&&(n.retiring=t.retiring),e.edges.push(n)}function Un({title:e,goal:t,phase:n="accepted",source:s}){return{schema:De,title:e,...t?{goal:t}:{},rev:0,phase:n,source:s??{kind:"dcursed"},nodes:{},edges:[],flows:[]}}const K=(e,t=120)=>{const n=String(e).replace(/\s+/g," ").trim();return`"${n.length>t?`${n.slice(0,t-1)}…`:n}"`};function Se(e){switch(e.op){case"box.add":return`add ${e.external?"external ":""}${e.kind} ${e.id??""}${e.id?" ":""}${K(e.label)}${e.in?` in ${e.in}`:""}${e.tech?` (${e.tech})`:""}${e.planned?`, planned by ${e.planned}`:""}`;case"box.set":{const t=[];return e.label!==void 0&&t.push(`label → ${K(e.label)}`),e.kind!==void 0&&t.push(`kind → ${e.kind}`),e.in!==void 0&&t.push(e.in===null?"out of what it sat in":`in → ${e.in}`),e.tech!==void 0&&t.push(e.tech===""?"tech cleared":`tech → ${e.tech}`),e.detail!==void 0&&t.push(e.detail===""?"detail cleared":"detail rewritten"),e.files!==void 0&&t.push(`files → ${e.files.length?e.files.join(", "):"none"}`),e.external!==void 0&&t.push(e.external?"external":"no longer external"),e.planned!==void 0&&t.push(e.planned===null?"no longer planned":`planned by ${e.planned}`),e.retiring!==void 0&&t.push(e.retiring===null?"no longer retiring":`retiring (${e.retiring} removes it)`),`change ${e.id}: ${t.join("; ")}`}case"box.remove":return`remove box ${e.id}`;case"arrow.add":return`${e.from} now uses ${e.to}${e.label?` (${K(e.label,40)})`:""}${e.async?", async":""}`;case"arrow.remove":return`${e.from} no longer uses ${e.to}`;case"arrow.rewire":return`arrow ${e.from} → ${e.to} is now ${e.newFrom??e.from} → ${e.newTo??e.to}`;case"arrow.reverse":return`arrow ${e.from} → ${e.to} flipped to ${e.to} → ${e.from}`;case"arrow.set":{const t=[];return e.label!==void 0&&t.push(`label ${K(e.label,40)}`),e.tech!==void 0&&t.push(e.tech===""?"tech cleared":`tech ${e.tech}`),e.async!==void 0&&t.push(e.async?"async: does not wait for the answer":"waits for the answer"),e.via!==void 0&&t.push(e.via===null?"no queue":`via ${e.via}`),e.planned!==void 0&&t.push(e.planned===null?"no longer planned":`planned by ${e.planned}`),e.retiring!==void 0&&t.push(e.retiring===null?"no longer retiring":`retiring (${e.retiring} removes it)`),`arrow ${e.from} → ${e.to}: ${t.join("; ")}`}case"flow.add":return`add flow ${e.id} ${K(e.title)} (${e.steps.length} step${e.steps.length===1?"":"s"})`;case"flow.set":return`change flow ${e.id}: ${[e.title!==void 0?`title → ${K(e.title)}`:"",e.steps!==void 0?`${e.steps.length} step${e.steps.length===1?"":"s"}`:""].filter(Boolean).join("; ")}`;case"flow.remove":return`remove flow ${e.id}`;case"arch.set":{const t=[];return e.title!==void 0&&t.push(`title → ${K(e.title)}`),e.goal!==void 0&&t.push(`goal → ${K(e.goal,200)}`),e.phase!==void 0&&t.push(e.phase==="accepted"?"accepted":"back to a draft"),`the architecture: ${t.join("; ")}`}case"layout.place":return`place ${e.id}`;case"layout.fold":return`${e.folded?"fold":"unfold"} ${e.id}`;case"proposal.accept":return`accept proposal ${e.id}`;case"proposal.reject":return`reject proposal ${e.id}${e.reason?` (${K(e.reason,160)})`:""}`;default:return String(e.op)}}function Kn(e,t){return e.edges.some(n=>n.from===t.from&&n.to===t.to)?"call":e.edges.some(n=>n.from===t.to&&n.to===t.from)?"reply":"gap"}const ft=e=>`${e.from}\0${e.to}`;function io(e,t){const n={plan:t.id,added:new Set,removed:new Set,changed:new Map,addedArrows:new Set,removedArrows:new Set};for(const[s,i]of Object.entries(e.nodes))i.planned===t.id&&n.added.add(s),i.retiring===t.id&&n.removed.add(s);for(const s of e.edges)s.planned===t.id&&n.addedArrows.add(ft(s)),(s.retiring===t.id||n.removed.has(s.from)||n.removed.has(s.to))&&n.removedArrows.add(ft(s));for(const[s,i]of Object.entries(t.nodes)){if(i.kind==="context"||i.status==="cancelled")continue;const o=new Set((i.touches??[]).filter(l=>l in e.nodes));for(const[l,a]of Object.entries(e.nodes))a.files?.length&&xt(i.files,a.files)&&o.add(l);for(const l of o){if(n.added.has(l)||n.removed.has(l))continue;const a=n.changed.get(l);a?a.includes(s)||a.push(s):n.changed.set(l,[s])}}return n}function Nt(e,t,n){return t.added.has(n)?"new":t.removed.has(n)?"removed":t.changed.has(n)||pe(e,n)&&jt(e,n).some(s=>t.added.has(s)||t.removed.has(s)||t.changed.has(s))?"changed":"untouched"}function zn(e,t){const n=(t.touches??[]).map(s=>({id:s,by:"hand"}));for(const[s,i]of Object.entries(e.nodes))i.files?.length&&xt(t.files,i.files)&&!n.some(o=>o.id===s)&&n.push({id:s,by:"files"});return n}const Jn={"(((":"person","((":"person","[(":"store","([":"queue",">":"queue","(":"service","{{":"service"},Yn={person:["((","))"],service:["(",")"],component:["[","]"],store:["[(",")]"],queue:["([","])"],group:["[","]"]};function pt(e){const t=/^([\s\S]*?)\s*(?:<br\s*\/?>|\n)\s*\[([^\]]+)\]\s*$/.exec(e);return t?{label:t[1].replace(/<br\s*\/?>/gi," ").trim(),tech:t[2].trim()}:{label:e.replace(/<br\s*\/?>/gi," ").trim()}}function Xn(e){const t=Ot(e,{rich:!0}),n={direction:t.direction,boxes:new Map,arrows:[],warnings:[...t.warnings]},s=t.subgraphs??[],i=new Set([...t.nodes.keys(),...s.flatMap(l=>l.id?[l.id]:[])]),o=s.map(l=>l.id??(()=>{const a=yt(l.title,i);return i.add(a),a})());s.forEach((l,a)=>n.boxes.set(o[a],{label:l.title.slice(0,120),kind:"group",...l.parent!==void 0?{in:o[l.parent]}:{}}));for(const[l,a]of t.nodes){if(o.includes(l)&&a.shape===void 0&&a.raw===void 0)continue;const{label:r,tech:d}=pt(a.raw??a.label);n.boxes.set(l,{label:(r||l).slice(0,120),kind:a.shape&&Jn[a.shape]||"component",...a.cls==="external"?{external:!0}:{},...d?{tech:d.slice(0,120)}:{},...a.frame!==void 0?{in:o[a.frame]}:{}})}for(const l of t.edges){const a=l.kind&&l.kind!=="after"?`${l.kind}${l.label?`: ${l.label}`:""}`:l.label,{label:r,tech:d}=pt(a??"");n.arrows.push({from:l.from,to:l.to,...r?{label:r.slice(0,120)}:{},...d?{tech:d.slice(0,120)}:{},...l.kind==="after"?{async:!0}:{}})}return n}const Gn=/^(Person|System|Container|Component)(Db|Queue)?(_Ext)?$/,Vn=/^(Boundary|Enterprise_Boundary|System_Boundary|Container_Boundary|Deployment_Node|Node|Node_L|Node_R)$/,Qn=/^(Rel|BiRel|Rel_[UDLR]|Rel_Back|Rel_Neighbor|Rel_Back_Neighbor|BiRel_[UDLR])$/,Et=/^C4(Context|Container|Component|Dynamic|Deployment)\b/;function Zn(e){const t=[];let n="",s=!1;for(const i of e)i==='"'?(s=!s,n+=i):i===","&&!s?(t.push(n),n=""):n+=i;return t.push(n),t.map(i=>i.trim()).filter(i=>!i.startsWith("$")).map(i=>i.replace(/^"([\s\S]*)"$/,"$1").trim())}function es(e){const t={direction:"TD",boxes:new Map,arrows:[],warnings:[]},n=[];let s=!1;if(e.replace(/\r\n?/g,`
6
+ `).split(`
7
+ `).forEach((i,o)=>{const l=`line ${o+1}`,a=i.replace(/%%.*$/,"").trim();if(!a)return;if(!s){if(!Et.test(a))throw new Error(`${l}: a C4 diagram starts with C4Context, C4Container, C4Component, C4Dynamic or C4Deployment, not "${a.slice(0,30)}"`);s=!0;return}if(a==="}"){n.pop();return}const r=/^title\s+(.+)$/.exec(a);if(r){t.title=r[1].trim();return}const d=/^([A-Za-z_]+)\s*\(([\s\S]*?)\)\s*(\{)?\s*$/.exec(a);if(!d){if(/^(UpdateElementStyle|UpdateRelStyle|UpdateLayoutConfig|UpdateBoundaryStyle|LAYOUT_|SHOW_|HIDE_)/.test(a))return;throw new Error(`${l}: could not read "${a.slice(0,40)}"`)}const[,f,$,p]=d,u=Zn($);if(Qn.test(f)){const[se,h,S,U]=u;if(!se||!h)throw new Error(`${l}: ${f} needs two aliases`);f.startsWith("BiRel")&&t.warnings.push(`${l}: ${se} <--> ${h} points both ways; kept as ${se} → ${h}`),t.arrows.push({from:se,to:h,...S?{label:S.slice(0,120)}:{},...U?{tech:U.slice(0,120)}:{}});return}const c=n.at(-1),g=Vn.test(f),b=Gn.exec(f);if(!g&&!b){t.warnings.push(`${l}: ${f} is not drawn here, and was left out`);return}const[v,O,q,C]=u;if(!v||!O)throw new Error(`${l}: ${f} needs an alias and a label`);if(g){t.boxes.set(v,{label:O.slice(0,120),kind:"group",...c?{in:c}:{}}),p&&n.push(v);return}const[,T,j,k]=b,M=T==="Container"||T==="Component",E=M?q:void 0,P=M?C:q,Ae=j==="Db"?"store":j==="Queue"?"queue":T==="Person"?"person":T==="Component"?"component":"service";t.boxes.set(v,{label:O.slice(0,120),kind:Ae,...k?{external:!0}:{},...E?{tech:E.slice(0,120)}:{},...P?{detail:P.slice(0,4e3)}:{},...c?{in:c}:{}})}),!s)throw new Error("this is not a Mermaid C4 diagram: it has no C4Context, C4Container… line");return n.length&&t.warnings.push(`${n.length} boundar${n.length===1?"y was":"ies were"} never closed with "}"`),t}function ts(e){const t=[...e.warnings],n=[],s=[...e.boxes.keys()],i=new Set,o=r=>{if(i.has(r))return;i.add(r);const d=e.boxes.get(r);d.in&&e.boxes.has(d.in)&&o(d.in),n.push({op:"box.add",id:r,label:d.label,kind:d.kind,...d.external?{external:!0}:{},...d.tech?{tech:d.tech}:{},...d.detail?{detail:d.detail}:{},...d.in&&e.boxes.has(d.in)?{in:d.in}:{}})};for(const r of s)o(r);let l=Un({title:"import",phase:"accepted"});const a=[];for(const r of n){const d=ct(l,[r],{actor:"you",via:"file"});d.kind==="applied"?(l=d.arch,a.push(r)):d.kind==="rejected"&&t.push(`left out box ${r.id}: ${d.why}`)}for(const r of e.arrows){const d={op:"arrow.add",from:r.from,to:r.to,...r.label?{label:r.label}:{},...r.tech?{tech:r.tech}:{},...r.async?{async:!0}:{}},f=ct(l,[d],{actor:"you",via:"file"});f.kind==="applied"?(l=f.arch,a.push(d)):f.kind==="rejected"&&!/is there already/.test(f.why)&&t.push(`left out ${r.from} → ${r.to}: ${f.why}`)}return{ops:a,warnings:t}}const Ue=e=>`"${e.replace(/"/g,"#quot;")}"`,ns=e=>Ue(e.tech?`${e.label}<br/>[${e.tech}]`:e.label);function ss(e){const t=e.tech?`${e.label??""}<br/>[${e.tech}]`:e.label??"",n=e.async?"-.->":"-->";return t?`${n}|${Ue(t)}|`:n}function ro(e,t="LR"){const n=[`flowchart ${t==="TD"?"TD":"LR"}`],s=e;let i=!1;const o=(r,d)=>{const f=e.nodes[r],[$,p]=Yn[f.kind];f.external&&(i=!0),n.push(`${d}${r}${$}${ns(f)}${p}${f.external?":::external":""}`)},l=(r,d)=>{n.push(`${d}subgraph ${r} [${Ue(e.nodes[r].label)}]`);for(const f of ee(s,r))a(f,`${d} `);n.push(`${d}end`)},a=(r,d)=>{ee(s,r).length||e.nodes[r].kind==="group"?l(r,d):o(r,d)};for(const r of Object.keys(e.nodes))e.nodes[r].in||a(r," ");for(const r of e.edges)r.from in e.nodes&&r.to in e.nodes&&n.push(` ${r.from} ${ss(r)} ${r.to}`);return i&&n.push(" classDef external fill:#eeeeee,stroke:#999999,color:#333333"),n.join(`
8
+ `)}function os(e,t=""){let n=e;if(/\.(md|markdown)$/i.test(t)||/```mermaid/.test(e)){const d=/```mermaid\s*\n([\s\S]*?)```/.exec(e);if(!d)throw new Error("there is no ```mermaid block in this file");n=d[1]}const s=n.split(`
9
+ `).map(d=>d.replace(/%%.*$/,"").trim()).find(Boolean)??"",i=Et.test(s),o=i?es(n):Xn(n),{ops:l,warnings:a}=ts(o),r=(t.split(/[\\/]/).pop()??"").replace(/\.(md|markdown|mmd|mermaid|txt)$/i,"").replace(/[_-]+/g," ").trim();return{title:(o.title??(r?r[0].toUpperCase()+r.slice(1):"Imported architecture")).slice(0,200),direction:o.direction,source:{kind:i?"c4":/\.(md|markdown)$/i.test(t)?"markdown":"mermaid",...t?{path:t}:{}},ops:l,warnings:a}}const he="top level",lo=e=>{const t=[];for(const n of e.steps)n.group&&!t.includes(n.group)&&t.push(n.group);return[...t.filter(n=>n!==he),...t.filter(n=>n===he)]},Ke={observed:"●",reported:"○",you:"◆"},Pe={observed:"seen editing its files",reported:"said by the agent",you:"set by you"},as={"claude-code":"Claude Code",cursor:"Cursor",antigravity:"Antigravity"},_=e=>{if(e.startsWith("opencode:"))return e.slice(9);if(e.startsWith("server:"))return"DiaCode";const t=e.indexOf(":"),n=t>0?as[e.slice(0,t)]:void 0;if(!n)return e;const s=e.slice(t+1);return s==="main"||s==="agent"?n:`${n} (${s})`};function ze(e){if(!e||e.kind==="context")return null;const t=e.status&&e.status!=="not_started",n=e.owner??(t?e.statusBy:void 0);return n?{who:n,from:e.statusFrom??"reported"}:null}function is(e,t){const n=ze(e);return n?`${Ke[n.from]} ${_(n.who)}${t?` · ${t}`:""}`:""}const Z={in_progress:"working",waiting:"waiting",done:"done",failed:"failed",cancelled:"cancelled"},qt=e=>`waits on ${e.slice(0,2).join(", ")}${e.length>2?` +${e.length-2}`:""}`,rs=e=>`checkpoint after ${e.slice(0,2).join(", ")}${e.length>2?` +${e.length-2}`:""}`;function co(e,{stalled:t,blockedOn:n,held:s}={}){const i=[];e&&e.kind!=="context"&&(Z[e.status]?i.push(Z[e.status]):e.status==="not_started"&&!n?.length&&!s?.length&&i.push("not started"),n?.length?i.push(qt(n)):s?.length&&i.push(rs(s)));const o=is(e,t);return o&&i.push(o),i.join(" · ")}const D={in_progress:"#2F6FB0",waiting:"#9A6700",done:"#2E7D32",failed:"#B3261E",cancelled:"#69625B"},ls="#69625B",uo={not_started:{colour:ls,icon:"ring",word:"not started",edge:!1,strike:!1},in_progress:{colour:D.in_progress,icon:"half",word:Z.in_progress,edge:!0,strike:!1},waiting:{colour:D.waiting,icon:"hourglass",word:Z.waiting,edge:!0,strike:!1},done:{colour:D.done,icon:"check",word:Z.done,edge:!0,strike:!1},failed:{colour:D.failed,icon:"cross",word:Z.failed,edge:!0,strike:!1},cancelled:{colour:D.cancelled,icon:"slash",word:Z.cancelled,edge:!0,strike:!0}},fo=["not_started","in_progress","waiting","done","failed","cancelled"],Ie={new:{colour:D.done,icon:"plus",word:"new"},changed:{colour:D.waiting,icon:"pencil",word:"changed"},removed:{colour:D.failed,icon:"cross",word:"removed"}},ht={width:300,height:180};async function G(e){let t;try{t=await e.json()}catch{throw new Error(e.status>=500?"the plan server is not reachable":`the plan server answered ${e.status}`)}return t}async function ne(e){const t=await fetch(e),n=await G(t);if(!t.ok)throw new Error(n.error??`${t.status}`);return n}const po=(e,t=12)=>ne(`/api/files?q=${encodeURIComponent(e)}&limit=${t}`);async function ho(e){return e.length?(await ne(`/api/files?${e.map(t=>`check=${encodeURIComponent(t)}`).join("&")}`)).results:[]}async function $o(){try{const e=await fetch("/api/health");if(!e.ok)return null;const t=await e.json();return t.ok?t:null}catch{return null}}const go=async()=>(await ne("/api/plans")).plans,mo=e=>ne(`/api/plans/${encodeURIComponent(e)}`);async function ds(e){const t=await fetch("/api/plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await G(t);if(!t.ok)throw new Error(n.error??`${t.status}`);return n}async function cs(e,t,n,s){const i=await fetch(`/api/plans/${encodeURIComponent(e)}/batches`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({plan:e,baseRev:t,ops:n,...s?{reason:s}:{}})});return{status:i.status,body:await G(i)}}async function wo(e,t={}){const n=await fetch(`/api/plans/${encodeURIComponent(e)}/reconcile`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),s=await G(n);if(!n.ok)throw new Error(s.error??`${n.status}`);return s}async function bo(e,t){const n=await fetch(`/api/plans/${encodeURIComponent(e)}/drift`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({ignore:t})}),s=await G(n);if(!n.ok)throw new Error(s.error??`${n.status}`)}function Je(e,t,n){let s=null,i,o=!1,l=1e3,a=!1;const r=()=>{s=new EventSource(e),s.addEventListener("open",()=>{l=1e3,n.open(a),a=!0}),s.addEventListener("error",()=>{n.down(),!(o||s?.readyState!==EventSource.CLOSED)&&(s=null,i=setTimeout(r,l),l=Math.min(l*2,1e4))});for(const[d,f]of Object.entries(t))f&&s.addEventListener(d,$=>f(JSON.parse($.data)))};return r(),()=>{o=!0,clearTimeout(i),s?.close()}}const yo=(e,t)=>Je(`/api/plans/${encodeURIComponent(e)}/events`,{change:t.change,problem:t.problem,reconcile:t.reconcile,presence:t.presence,call:t.call},t),ko=e=>Je("/api/events",{plans:e.plans},{open:e.open,down:()=>{}}),xo=()=>ne("/api/architecture"),vo=()=>ne("/api/flow");async function So(e,t,n,s=!1){const i=await fetch(`/api/permissions/${encodeURIComponent(e)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({decision:t,...n?{reason:n}:{},...s?{always:!0}:{}})});return{status:i.status,body:await G(i)}}const Ao=()=>ne("/api/presence").then(e=>e.agents??[]);async function us(e){const t=await fetch("/api/architecture",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await G(t);if(!t.ok)throw new Error(n.error??`${t.status}`);return n}async function fs(e,t,n){const s=await fetch("/api/architecture/batches",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({baseRev:e,ops:t,...n?{reason:n}:{}})});return{status:s.status,body:await G(s)}}const Oo=e=>Je("/api/architecture/events",{change:e.change,problem:e.problem,call:e.call},e);async function jo(e){const t=os(await e.text(),e.name);await us({title:t.title,source:t.source,direction:t.direction});const{status:n,body:s}=await fs(0,t.ops,`imported from ${e.name}`);if(n!==200)throw new Error(s.why??s.error);return{warnings:t.warnings}}function To(e){const{plan:t,layout:n}=e,s=n.canvas??{width:640,height:240};return{id:t.id,title:t.title,plan:t.title,repo:"",source:t.source?.url??"",direction:n.direction,note:t.goal??"",canvas:{width:s.width+ht.width,height:s.height+ht.height},...ps(e)}}function ps({plan:e,layout:t}){return{steps:Object.entries(e.nodes).map(([n,s])=>({id:n,label:s.label,group:s.group??he,x:t.nodes[n]?.x??0,y:t.nodes[n]?.y??0})),depends:e.edges.map(n=>({source:n.from,target:n.to,label:n.label??"",kind:n.kind??"needs"}))}}function _o(e,t){const n={...e.plan,nodes:{},edges:[]};for(const o of t.steps){const a={...e.plan.nodes[o.id]??{},label:o.label};o.group&&o.group!==he?a.group=o.group:delete a.group,n.nodes[o.id]=a}const s=new Map(e.plan.edges.map(o=>[`${o.from}\0${o.to}`,o]));n.edges=t.depends.map(o=>{const l=o.kind&&o.kind!=="needs"?o.kind:void 0,a=s.get(`${o.source}\0${o.target}`),r=a&&a.kind===l?{question:a.question,passed:a.passed,answer:a.answer}:{};return Object.fromEntries(Object.entries({from:o.source,to:o.target,label:o.label||void 0,kind:l,...r}).filter(([,d])=>d!==void 0))});const{ops:i}=pn(e.plan,n,{bridge:!0});for(const o of t.steps){const l=e.layout.nodes[o.id],a=Math.round(o.x),r=Math.round(o.y);(!l||Math.round(l.x)!==a||Math.round(l.y)!==r)&&i.push({op:"layout.place",id:o.id,x:a,y:r})}return i}async function Co(e){const t=Mn(await e.text(),e.name),n=await ds({title:t.title,goal:t.goal,source:t.source,direction:t.direction}),{status:s,body:i}=await cs(n.id,0,t.ops,`imported from ${e.name}`);if(s!==200)throw new Error(i.why??i.error);return{id:n.id,warnings:t.warnings}}const Ne=e=>String(e).replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]),hs=/https?:\/\/[^\s<>"'`]+/gi,$t=(e,t)=>e.split(t).length-1;function $s(e){let t=e;for(;;){const n=t.at(-1)??"",s={")":"(","]":"[","}":"{"}[n];if(/[.,;:!?*_]/.test(n)||s&&$t(t,n)>$t(t,s))t=t.slice(0,-1);else return t}}function Rt(e){let t;try{t=new URL(e)}catch{return null}return t.username||t.password?null:t.protocol==="https:"?t.hostname?t.href:null:t.protocol==="http:"&&(t.hostname==="127.0.0.1"||t.hostname==="localhost")?t.href:null}function Lt(e){const t=String(e??""),n=[];let s=0;for(const i of t.matchAll(hs)){const o=i.index??0,l=$s(i[0]),a=Rt(l);a&&(o>s&&n.push({text:t.slice(s,o)}),n.push({text:l,href:a}),s=o+l.length)}return s<t.length&&n.push({text:t.slice(s)}),n}function re(e){return[...new Set(Lt(e).flatMap(t=>t.href?[t.href]:[]))]}function Y(e){return Lt(e).map(t=>t.href?`<a href="${Ne(t.href)}" target="_blank" rel="noopener noreferrer">${Ne(t.text)}</a>`:Ne(t.text)).join("")}const m=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]);function xe(e,t){const n=e?Date.parse(e):NaN;if(!Number.isFinite(n))return"";const s=Math.max(0,Math.round((t-n)/1e3));return s<45?"just now":s<3600?`${Math.max(1,Math.round(s/60))} min`:s<86400?`${Math.round(s/3600)} h`:`${Math.round(s/86400)} d`}function gs(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if((s.ops??[]).some(i=>i.id===t&&/^(status\.set|claim|release)$/.test(i.op)))return s.at}}function Mo(e,t,n=""){switch(e){case"start":return{ops:[{op:"claim",id:t},{op:"status.set",id:t,status:"in_progress",note:"started by you"}],reason:`you started ${t}`,message:`Started ${t}.`};case"done":return{ops:[{op:"status.set",id:t,status:"done",note:"marked done by you"},{op:"release",id:t}],reason:`you marked ${t} done`,message:`Marked ${t} done.`};case"failed":return{ops:[{op:"status.set",id:t,status:"failed",note:"marked failed by you"}],reason:`you marked ${t} failed`,message:`Marked ${t} failed.`};case"release":return{ops:[{op:"release",id:t}],reason:`you took ${t} off its owner`,message:`Released ${t}.`};case"reopen":return{ops:[{op:"status.set",id:t,status:"not_started"},{op:"release",id:t}],reason:`you reopened ${t}`,message:`Reopened ${t}.`};case"cancel":return{ops:[{op:"status.set",id:t,status:"cancelled",note:"cancelled by you"},{op:"release",id:t}],reason:`you cancelled ${t}`,message:`Cancelled ${t}.`};case"answer":{const s=n.trim();return s?{ops:[{op:"status.set",id:t,status:"in_progress",note:`you answered: ${s}`}],reason:`Answer to ${t}: ${s}`,message:`Answered ${t}.`}:null}default:return null}}function No(e,t,n,s=""){const i=s.trim();return e==="back"?{ops:[{op:"gate.reject",from:t,to:n,...i?{reason:i}:{}}],reason:`you sent ${t} back`,message:`Sent ${t} back to be done again.`}:e==="give"&&!i?null:{ops:[{op:"gate.pass",from:t,to:n,...i?{answer:i}:{}}],reason:`you passed the checkpoint before ${n}${i?`: ${i}`:""}`,message:`Passed the checkpoint before ${n}.`}}const ce="Carry out the plan with the dcursed tools, one step at a time: start a step, do it, mark it done. Stop and ask me if a step is unclear.",Ee="The architecture is approved. Draw the plan on it with plan_create (every step, what it waits for, the files it touches), then stop: do not start any step.",ue="The plan is approved but not started. Check the architecture against it (arch_read), propose what needs to change with arch_edit and a reason for each, then stop. Do not start any step: I press Start.",Eo=["planning","executing","done"],we="Carry on with the plan with the dcursed tools: read it first, then take the next step.",Fe=e=>{const t=e.map(_);return t.length<2?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`};function qo(e,t,n=[]){const s=o=>[{op:"plan.set",phase:o}];if(e==="planning")return{label:"Approve plan",primary:!0,ops:s("approved"),reason:"you approved the plan",message:"Plan approved. Nothing starts yet: your agent checks the architecture against it.",tell:ue,line:n.length?`Look the plan over and change what is wrong, then approve it. ${Fe(n)} then checks the architecture against it and proposes what needs to change; nothing starts until you press Start.`:"Look the plan over and change what is wrong, then approve it. No agent is listening for the editor right now, so you may have to ask yours to check the architecture against it. Nothing starts until you press Start.",hint:"Approve the plan. Your agent checks the architecture against it and proposes what needs to change; nothing starts until you press Start. From now on an agent's changes to the plan arrive as proposals for you to accept."};if(e==="approved")return{label:"Start",primary:!0,ops:s("executing"),reason:"you started the plan",message:"Started.",tell:ce,line:n.length?`The plan is approved. This starts it: ${Fe(n)} carries it out.`:"The plan is approved. This starts it. No agent is listening for the editor right now, so you may have to tell yours to begin.",hint:"Start the plan: your agent carries it out, one step at a time."};const i={label:"Stop",confirm:"Stop the agents now?",primary:!1,ops:[{op:"plan.stop"}],reason:"you stopped the plan",message:"Stopped: the agents stop now. Press Start to carry on.",line:"",hint:"Stop the agents now, even mid-step: what they were doing is put back, what they finished stays. The plan waits for you to press Start again."};return e==="executing"?t?.total&&t.done===t.total?{label:"Mark plan done",primary:!0,ops:s("done"),reason:"you marked the plan done",message:"Plan marked done.",hint:"Every step is finished.",line:"Every step is finished."}:{label:"Pause",primary:!1,ops:s("paused"),reason:"you paused the plan",message:"Paused: agents finish the step they are on and start nothing new.",line:"Agents' edits to steps and arrows arrive as proposals for you to accept or reject. Pause: they finish the step they are on and start nothing new. Stop: they stop now, and the plan goes back to planning.",hint:"Agents finish the step they are on, then start nothing new until you resume.",second:i}:e==="paused"?{label:"Resume",primary:!0,ops:s("executing"),reason:"you resumed the plan",message:"Resumed.",tell:we,line:"Paused: agents finish the step they are on and start nothing new. Resume to carry on, or Stop to halt them now and change the plan.",hint:"Carry on with the plan, and tell the agent that was at work on it.",second:i}:{label:"Reopen",primary:!1,ops:s("planning"),reason:"you reopened the plan",message:"Reopened: back to planning.",hint:"Plan again.",line:"This plan is finished. Reopen it to change it."}}function Ro(e){const t=e.to?_(e.to):"the agent";if(e.kind==="started")switch(e.state){case"sent":return{text:`Started. Telling ${t} to carry it out…`,kind:"info"};case"delivered":return{text:`Started, and ${t} was told to carry it out: the Steps panel shows it working.`,kind:"info"};case"queued":return{text:`Started. ${t} is not listening yet (in the middle of a turn, or not running): it is told when it is, or tell it yourself.`,kind:"info",copy:ce};case"failed":return{text:`Started, but ${t} could not be told${e.detail?` (${e.detail})`:""}. Tell it to carry the plan out.`,kind:"error",copy:ce};case"expired":return{text:`Started. ${t} did not come back to take it: tell it to carry the plan out.`,kind:"info",copy:ce};case"none":return{text:"Started. No agent is listening for the editor, so none was told: tell yours to carry the plan out.",kind:"info",copy:ce};default:return null}if(e.kind==="planApproved")switch(e.state){case"sent":return{text:`Plan approved. Telling ${t} to check the architecture against it…`,kind:"info"};case"delivered":return{text:`Plan approved, and ${t} is checking the architecture against it. Nothing starts until you press Start.`,kind:"info"};case"queued":return{text:`Plan approved. ${t} is not listening yet (in the middle of a turn, or not running): it is told when it is, or tell it yourself.`,kind:"info",copy:ue};case"failed":return{text:`Plan approved, but ${t} could not be told${e.detail?` (${e.detail})`:""}. Ask it to check the architecture against the plan, or press Start if it is already right.`,kind:"error",copy:ue};case"expired":return{text:`Plan approved. ${t} did not come back to take it: ask it to check the architecture against the plan, or press Start if it is already right.`,kind:"info",copy:ue};case"none":return{text:"Plan approved. No agent is listening for the editor, so none was told: ask yours to check the architecture against the plan, or press Start if it is already right.",kind:"info",copy:ue};default:return null}if(e.kind==="resumed")switch(e.state){case"sent":return{text:`Resumed. Telling ${t} to carry on…`,kind:"info"};case"delivered":return{text:`Resumed, and ${t} was told to carry on.`,kind:"info"};case"queued":return{text:`Resumed. ${t} is told when it is listening, or tell it yourself.`,kind:"info",copy:we};case"none":return{text:"Resumed. No agent is listening for the editor: tell yours to carry on.",kind:"info",copy:we};case"failed":case"expired":return{text:`Resumed, but ${t} could not be told${e.detail?` (${e.detail})`:""}: tell it to carry on.`,kind:"info",copy:we};default:return null}if(e.kind==="stopped")switch(e.state){case"sent":return{text:`Stopping ${t}…`,kind:"info"};case"delivered":return{text:`Stopped: ${t}'s turn was cut off. Press Start to carry on.`,kind:"info"};case"failed":case"expired":return{text:`${t} could not be stopped from here${e.detail?` (${e.detail})`:""}: stop it in its own window. Its next dcursed tool tells it to stop.`,kind:"error"};default:return null}if(e.kind==="passed"||e.kind==="sentBack"){const i=e.kind==="passed"?"Checkpoint passed":`Sent ${e.step??"the step"} back`,o=e.text.replace(/^\[DiaCode\] /,"");switch(e.state){case"sent":return{text:`${i}. Telling ${t}…`,kind:"info"};case"delivered":return{text:`${i}, and ${t} was told.`,kind:"info"};case"queued":return{text:`${i}. ${t} hears it when its turn ends, or at its next step.`,kind:"info"};case"failed":case"expired":return{text:`${i}. ${t} could not be woken: tell it yourself.`,kind:"info",copy:o};default:return null}}if(e.kind==="archAccepted")switch(e.state){case"sent":return{text:`Architecture approved. Telling ${t} to draw the plan on it…`,kind:"info"};case"delivered":return{text:`Architecture approved, and ${t} was told to draw the plan on it.`,kind:"info"};case"queued":return{text:`Architecture approved. ${t} hears it when its turn ends: it then draws the plan.`,kind:"info",copy:Ee};case"none":return{text:"Architecture approved. No agent is listening for the editor: ask yours to draw the plan on it.",kind:"info",copy:Ee};case"failed":case"expired":return{text:`Architecture approved. ${t} could not be told${e.detail?` (${e.detail})`:""}: ask it to draw the plan on it.`,kind:"info",copy:Ee};default:return null}if(e.kind==="archChanged")return e.state==="delivered"?{text:`${t} was told what you changed in the architecture, and will propose the matching change to the plan.`,kind:"info"}:e.state==="failed"?{text:`${t} could not be told what you changed in the architecture${e.detail?` (${e.detail})`:""}: ask it to make the plan agree.`,kind:"info"}:null;if(e.kind==="archSettled")switch(e.state){case"sent":return{text:`Decided. Telling ${t}…`,kind:"info"};case"delivered":return{text:`Decided, and ${t} was told what you did with its proposal.`,kind:"info"};case"queued":return{text:`Decided. ${t} hears it when its turn ends, or at its next architecture tool.`,kind:"info"};case"failed":case"expired":return{text:`Decided. ${t} could not be woken${e.detail?` (${e.detail})`:""}: it reads it at its next architecture tool.`,kind:"info"};default:return null}if(e.kind==="replan"){const i="Look at the files that no step lists (or the failed step) and propose the matching change to the plan with plan_edit, or say none is needed.";switch(e.state){case"sent":return{text:`Asking ${t}…`,kind:"info"};case"delivered":return{text:`${t} was asked. Its answer arrives as a proposal to accept, or as a sentence in its window if the plan needs no change.`,kind:"info"};case"queued":return{text:`${t} is in the middle of a turn: it is asked when the turn ends.`,kind:"info",copy:i};case"none":return{text:`${e.to?`${t} cannot be woken from the editor`:"No agent is listening for the editor"}, so nobody was asked. Ask your agent in its own window, or settle it by hand: add the file to a step, or ignore it.`,kind:"info",copy:i};case"failed":return{text:`${t} could not be asked${e.detail?` (${e.detail})`:""}. Ask it in its own window, or settle it by hand: add the file to a step, or ignore it.`,kind:"info",copy:i};case"expired":return{text:`${t} did not come back to take the question (it is in the middle of a long turn, or not running). Ask it in its own window, or settle it by hand: add the file to a step, or ignore it.`,kind:"info",copy:i};default:return null}}if(e.kind==="changed")return e.state==="delivered"?{text:`${t} had stopped, so it was told what you changed and will propose the matching change to the architecture.`,kind:"info"}:e.state==="failed"?{text:`${t} could not be told what you changed${e.detail?` (${e.detail})`:""}: it reads it at its next step, or tell it to carry on.`,kind:"info"}:null;const n=e.step??"the step",s=e.text.replace(/^\[DiaCode\] /,"");switch(e.state){case"sent":return{text:`Answered ${n}. Telling ${t}…`,kind:"info"};case"delivered":return{text:`Answered ${n}: ${t} has your answer and is carrying on.`,kind:"info"};case"queued":return{text:`Answered ${n}. ${t} reads it at its next step, or when its turn ends.`,kind:"info"};case"failed":case"expired":return{text:`Answered ${n}. ${t} could not be woken: it reads the answer at its next step, or tell it to carry on.`,kind:"info",copy:s};default:return null}}function ms({id:e,calls:t=[],bare:n,proposed:s=!1,now:i=Date.now(),noun:o="step",working:l}){if(!n||s)return"";const a=t.find($=>Array.isArray($.bare)&&$.bare.includes(e));if(!a)return"";const r=i-Date.parse(a.at),d=a.to?_(a.to):"the agent",f=o==="box"?"a description, technology and files":"a description, files and boxes";switch(a.state){case"sent":case"delivered":return r>18e4||l===!1&&r>2e4?"":`${d} is suggesting ${f} for it: the suggestion arrives as a card to accept.`;case"queued":return`${d} will suggest ${f} for it when its turn ends.`;case"none":case"failed":case"expired":return r>6e5?"":`Nobody can suggest it from here${a.to?` (${d} cannot be woken by the editor)`:""}: ${o==="box"?"write what it is for yourself":"write what done means yourself"}, or ask your agent.`;default:return""}}const ws=e=>(e?.presence??[]).some(t=>t.state==="working"||t.state==="asking"),bs={working:"working",idle:"idle",error:"hit an error",asking:"waiting for you",quiet:"gone quiet",gone:"gone"};function Dt(e){return e.permission?.what?`${_(e.actor)} asks your permission to ${e.permission.what}`:`${_(e.actor)} is waiting for you in its own window${e.detail?`: ${e.detail}`:""}`}function Pt(e){const t=_(e.owner);switch(e.state){case"idle":return`${t} went idle with this unfinished`;case"error":return`${t} hit an error${e.detail?`: ${e.detail}`:""}`;case"quiet":return`${t} has not been heard from for a while`;default:return`${t} is gone`}}function ys(e){return e?e.behind>0?`has not seen the last ${e.behind} change${e.behind===1?"":"s"} (read to rev ${e.rev})`:`has seen everything (rev ${e.rev})`:""}function ks(e,t,n=[]){const s=new Set((e??[]).map(a=>a.actor)),i=a=>n.find(r=>r.actor===a),o=a=>a?`<span class="receipt">${m(ys(a))}</span>`:"",l=(e??[]).map(a=>{const r=a.state==="working"?"":xe(a.state==="gone"?a.seen:a.since,t),d=(a.state==="error"||a.state==="asking")&&a.detail?`: ${m(a.detail)}`:"",f=i(a.actor);return`<span class="${`agent ${m(a.state)}${f?" has-receipt":""}${f&&f.behind>0?" behind":""}`}"><i></i><span class="who"><b>${m(_(a.actor))}</b> ${m(bs[a.state]??a.state)}${r?` · ${m(r)}${r==="just now"?"":" ago"}`:""}${d}</span>${o(f)}</span>`});for(const a of n)s.has(a.actor)||l.push(`<span class="agent has-receipt${a.behind>0?" behind":""}"><i></i><span class="who"><b>${m(_(a.actor))}</b></span>${o(a)}</span>`);return l.length?`<div class="agents">${l.join("")}</div>`:""}function Ye(e){if(e?.replanner==="opencode")return{by:"OpenCode",drift:"Ask OpenCode's re-planner: should the plan cover this?",review:"Ask OpenCode's re-planner",failure:"Re-plan from this with OpenCode"};const t=e?.replanAgent?_(e.replanAgent):"your agent";return{by:t,drift:`Ask ${t}: should the plan cover this?`,review:`Ask ${t} to review these`,failure:`Ask ${t} to re-plan from this`}}function xs(e){const t=String(e??"");return/https?:\/\/|api[ _-]?key|expired|unauthori[sz]ed|credential/i.test(t)&&!/^OpenCode is not signed in/.test(t)?"OpenCode is not signed in (its key is missing or has expired, or no provider is set up). Run `opencode auth login` in a terminal, then ask again.":t||"OpenCode could not answer."}function It(e){if(!e)return"";const t="OpenCode's re-planner",n=e.kind==="drift"?(e.files??[]).map(m).join(", "):(e.steps??[]).map(m).join(", ");return e.state==="running"?`<p class="lede">${t} is reading ${n||"the plan"}…</p>`:e.state==="failed"?`<p class="err">${m(xs(e.message))}</p>`:`<p class="lede">${t}: ${m(e.message??"done")}.</p>`}function Ft(e){const t=`data-from="${m(e.from)}" data-to="${m(e.to)}"`,n=e.open?Rt(e.open):null,s=n?`<a class="open-link" href="${m(n)}" target="_blank" rel="noopener noreferrer" title="Opens ${m(n)} in a new tab">Open</a>`:"",i=(l,a,r=!1)=>`<button${r?' class="primary"':""} data-gate="${l}" ${t}>${a}</button>`,o=l=>`<input data-gate-text ${t} placeholder="${m(l)}" aria-label="${m(l)}">`;if(e.kind==="approve")return`${s}${i("pass","Approve",!0)}${o("or why it is not right")}${i("back","Send back")}`;if(e.kind==="input")return`${o("what it needs")}${i("give","Give",!0)}`;if(e.turn==="you"){const l=(e.options??[]).map(a=>`<button data-gate="give" data-option="${m(a)}" ${t}>${m(a)}</button>`).join("");return`${l}${o(l?"or your own answer":"your answer")}${i("give","Answer",!l)}`}return i("pass","Let it start without asking")}const Bt=e=>`<input data-answer="${m(e)}" placeholder="your answer" aria-label="Answer ${m(e)}">${I("answer",e,"Answer",!0)}`;function vs(e,t){const n=l=>`<b>${m(t.nodes[l]?.label??l)}</b> <code>${m(l)}</code>`;let s;e.kind==="approve"?s=`Approve the result of ${n(e.from)} before ${n(e.to)} starts${e.label?`: ${Y(e.label)}`:""}`:e.kind==="input"?s=`${n(e.to)} needs input from you${e.label?`: ${Y(e.label)}`:""}`:e.turn==="you"?s=`Asked before ${n(e.to)}: <q>${Y(e.question??"")}</q>`:s=`Before ${n(e.to)}, the agent is to ask you something. It has not asked yet.`;const i=e.kind==="approve"?t.nodes[e.from]?.note:void 0,o=e.kind==="approve"?re(i)[0]??re(e.label)[0]:void 0;return`<li class="step gate" data-step="${m(e.to)}" tabindex="0"><div class="head"><span>${s}</span></div>${i?`<div class="note">${Y(i)}</div>`:""}<div class="row actions">${Ft({...e,...o?{open:o}:{}})}</div></li>`}const I=(e,t,n,s=!1)=>`<button${s?' class="primary"':""} data-act="${e}" data-step="${m(t)}">${n}</button>`;function Ss(e,t,{showStep:n=i=>`<button class="plain small" data-show-step="${m(i)}">Show</button>`,showProposal:s=i=>`<button class="plain small" data-show-proposal="${m(i)}">Show on the board</button>`}={}){const i=t.reconcile?.state==="running",o=Ye(t),l=(d,f,$,p=!1)=>`<button${p?' class="primary" ':" "}data-act="${d}" data-step="${m(f)}">${$}</button>`,a=d=>{const f=d.step;switch(d.kind){case"question":return`${Bt(f)}${n(f)}`;case"asking":return d.permission?`<button class="primary" data-permit="${m(d.permission.id)}">Allow</button>${d.permission.always?`<button data-permit-always="${m(d.permission.id)}" title="Allowed now, and until this agent session ends it does not ask again for ${m(d.permission.always.label)}. Nothing is written to any file.">Allow, and don't ask again for ${m(d.permission.always.label)}</button>`:""}<input data-permit-why="${m(d.permission.id)}" placeholder="why not (optional)" aria-label="Why you deny it"><button data-deny="${m(d.permission.id)}">Deny</button>`:"";case"checkpoint":{const $=d.gate,p=$?.kind==="approve"?re(d.detail)[0]??re($.label)[0]:void 0;return`${Ft({...$,turn:"you",...p?{open:p}:{}})}${n(f)}`}case"failure":return`<button class="primary" data-act="replan" data-step="${m(f)}"${i?" disabled":""}>${m(o.failure)}</button>${l("reopen",f,"Try again")}${n(f)}`;case"stalled":return`${l("release",f,"Release")}${n(f)}`;case"proposal":return`<button class="primary" data-accept="${m(d.proposal)}">Accept</button><button data-reject="${m(d.proposal)}">Reject</button>${s(d.proposal)}`;case"review":return`<button class="primary" data-reconcile ${i?"disabled":""}>${i?"Looking…":m(o.review)}</button>${n(f)}`;case"finish":return'<button class="primary" data-finish>Mark plan done</button>';default:return""}},r=(d,f)=>d.kind==="asking"?m(f??""):Y(f);return e.map(d=>`
10
+ <li class="inbox-item" data-kind="${d.kind}">
11
+ <div class="inbox-what"><b>${r(d,d.title)}</b>${d.kind==="checkpoint"&&d.gate?.kind==="approve"&&d.gate.label?`<span class="inbox-detail">${Y(d.gate.label)}</span>`:""}${d.detail?`<span class="inbox-detail">${r(d,d.detail)}</span>`:""}</div>
12
+ ${a(d)?`<div class="row actions">${a(d)}</div>`:""}
13
+ ${d.kind==="review"?It(t.reconcile):""}
14
+ </li>`).join("")}const Lo=(e,t,n)=>`<ul class="inbox">${Ss(e,t,n)}</ul>`;function As(e,t,n,s,i){if(!e?.length)return"";const o=Ye(s),l=i.filter(([,r])=>r.status!=="done"&&r.status!=="cancelled"),a=r=>`<div class="row"><select data-drift-add="${m(r)}" aria-label="Add ${m(r)} to a step"><option value="">Add it to a step…</option>${l.map(([d,f])=>`<option value="${m(d)}">${m(f.label)}</option>`).join("")}</select><button class="plain small" data-ignore-drift="${m(r)}">Ignore it</button></div>`;return`<h4>Outside the plan</h4><p class="lede">Agents edited these files, and no step lists them.</p>
15
+ <ul class="items steps">${e.map(r=>`<li class="step"><code>${m(r.file)}</code><div class="meta"><span class="who">${m(_(r.by))}</span> · ${r.count}× · ${m(xe(r.at,t))}${xe(r.at,t)==="just now"?"":" ago"}</div>${a(r.file)}</li>`).join("")}</ul>
16
+ <div class="row"><button class="primary" data-act="drift" data-step=""${n?" disabled":""}>${m(o.drift)}</button></div>`}function Os(e){const t=(n,s)=>n?`<i style="flex:${n};background:${s}"></i>`:"";return`<div class="progress" role="img" aria-label="${e.done} of ${e.total} done">${t(e.done,D.done)}${t(e.active,D.in_progress)}${t(e.waiting,D.waiting)}${t(e.failed,D.failed)}${t(e.left,"var(--line)")}</div>`}function js(e){return[`${e.done} of ${e.total} done`,e.active?`${e.active} working`:"",e.waiting?`${e.waiting} waiting for you`:"",e.failed?`${e.failed} failed`:"",e.atRisk?`${e.atRisk} at risk`:"",e.cancelled?`${e.cancelled} cancelled`:""].filter(Boolean).join(" · ")}function Do(e,{now:t=Date.now()}={}){const n=e.plan,{derived:s,review:i={},recent:o=[]}=e,l=s.progress,a=new Map((e.presence??[]).filter(h=>h.state==="asking").map(h=>[h.actor,h])),r=Object.entries(n.nodes).filter(([,h])=>h.kind!=="context"),d=new Set((s.gates??[]).filter(h=>h.turn==="agent").map(h=>h.to));if(!r.length)return'<p class="lede">No steps yet. Double-click the board to add one, or give your agent the task: it draws the architecture, then the plan. What it writes appears here as it goes.</p>';const f=(h,S,U,Jt={})=>{const de=ze(S),$e=S.status??"not_started",Xe=s.atRisk?.[h],Ge=s.stalled?.[h],Ve=s.blocked?.[h],Qe=s.held?.[h],Oe=xe(gs(o,h),t),W=[];de&&W.push(`<span class="who" title="${m(Pe[de.from])}">${Ke[de.from]} ${m(_(de.who))}</span> <span class="how">${m(Pe[de.from])}</span>`),Oe&&$e!=="not_started"&&W.push(`<span class="how">${m(Oe)}${Oe==="just now"?"":" ago"}</span>`),Ve&&$e!=="not_started"&&W.push(`<span class="how">blocked by ${Ve.map(m).join(", ")}</span>`),Qe&&W.push(d.has(h)?'<span class="how">the agent asks you something before it starts</span>':`<span class="how">waits at a checkpoint after ${Qe.map(m).join(", ")}</span>`),Ge&&W.push(`<span class="risk">stalled: ${m(Pt(Ge))}</span>`),$e==="in_progress"&&S.owner&&a.has(S.owner)&&W.push(`<span class="risk">${m(Dt(a.get(S.owner)))}</span>`),Xe&&W.push(`<span class="risk">at risk: ${Xe.map(m).join(", ")} failed</span>`),h in i&&W.push('<span class="how">needs review</span>');const Ze=ms({id:h,calls:e.calls,working:ws(e),bare:!S.detail&&!S.files?.length&&!S.touches?.length,proposed:(n.proposals??[]).some(Yt=>(Yt.ops??[]).some(Xt=>Xt.id===h)),now:t});return Ze&&W.push(`<span class="how suggesting">${m(Ze)}</span>`),`
17
+ <li class="step" data-step="${m(h)}" tabindex="0">
18
+ <div class="head"><span><i class="dot" style="background:${D[$e]??"var(--wire-soft)"}"></i><b>${m(S.label)}</b> <code>${m(h)}</code></span><button class="plain small" data-inspect="${m(h)}" aria-label="Details of ${m(S.label)}">Details</button></div>
19
+ ${W.length?`<div class="meta">${W.join(" · ")}</div>`:""}
20
+ ${S.note?`<div class="note">${Y(S.note)}</div>`:""}
21
+ ${Jt.showQuestion?`<div class="row">${Bt(h)}</div>`:""}
22
+ ${U.length?`<div class="row actions">${U.join("")}</div>`:""}
23
+ </li>`},$=(h,S,U="")=>S.length?`<h4>${h}</h4>${U?`<p class="lede">${U}</p>`:""}<ul class="items steps">${S.join("")}</ul>`:"",p=h=>r.filter(([S,U])=>h(U,S)),u=h=>h.status??"not_started",c=e.reconcile?.state==="running",g=(s.gates??[]).filter(h=>h.turn==="you"),b=p(h=>u(h)==="waiting"),v=p(h=>u(h)==="failed"),O=p((h,S)=>u(h)==="in_progress"&&S in(s.stalled??{})),q=p((h,S)=>u(h)==="in_progress"&&!(S in(s.stalled??{}))),C=p((h,S)=>u(h)==="not_started"&&s.ready.includes(S)),T=p((h,S)=>u(h)==="not_started"&&!s.ready.includes(S)),j=p(h=>u(h)==="done"),k=p(h=>u(h)==="cancelled"),M=new Set(e.listening??[]),P=b.length>0&&b.every(([,h])=>h.owner&&M.has(h.owner))?"An agent stopped to ask. Your answer is sent to it, and it carries on.":"An agent stopped to ask. An agent listening for the editor is woken with your answer; any other reads it at its next step, so tell it to carry on.",Ae=h=>h.owner==="you",se=n.phase==="planning"?"Nothing is in front of these: the agent starts here once you approve the plan.":"Nothing is in front of these: an agent takes them next. To do one yourself, open its Details.";return`
24
+ ${Os(l)}
25
+ <p class="lede">${js(l)}</p>
26
+ ${n.phase==="planning"?`<p class="lede">Planning: agents' changes land at once. When the plan looks right, press <b>Approve plan</b> in the plan header above the chart; after that, an agent's changes to steps and arrows arrive as proposals for you to accept.</p>`:""}
27
+ ${n.phase==="paused"?'<p class="lede"><b>Paused.</b> Agents finish the step they are on and start nothing new. Press <b>Resume</b> in the plan header to carry on.</p>':""}
28
+ ${e.stopping?.length?`<p class="lede"><b>Stopping ${m(Fe(e.stopping))}:</b> ${e.stopping.length===1?"it stops":"they stop"} at the next tool call, and the turn ends there.</p>`:""}
29
+ ${ks(e.presence,t,e.reads)}
30
+ ${It(e.reconcile)}
31
+ ${n.proposals?.length?`<p class="lede"><button data-show-proposal="${m(n.proposals[0].id)}">${n.proposals.length===1?"A proposal is":`${n.proposals.length} proposals are`} waiting for you: show ${n.proposals.length===1?"it":"them"} on the board</button></p>`:""}
32
+ ${$("At a checkpoint",g.map(h=>vs(h,n)),"The plan waits for you here before the next step starts. What you say goes to the agent with it.")}
33
+ ${$("Waiting for you",b.map(([h,S])=>f(h,S,[I("cancel",h,"Cancel step")],{showQuestion:!0})),P)}
34
+ ${$("Stalled",O.map(([h,S])=>f(h,S,[I("done",h,"Mark done"),I("failed",h,"Mark failed"),I("release",h,"Release")])),"The agent holding these has stopped, and the plan still says in progress.")}
35
+ ${$("Failed",v.map(([h,S])=>f(h,S,[`<button class="primary" data-act="replan" data-step="${m(h)}"${c?" disabled":""}>${m(Ye(e).failure)}</button>`,I("reopen",h,"Try again"),I("cancel",h,"Cancel step")])))}
36
+ ${As(e.drift,t,c,e,r)}
37
+ ${$("Working now",q.map(([h,S])=>f(h,S,Ae(S)?[I("done",h,"Mark done"),I("failed",h,"Mark failed"),I("release",h,"Release")]:[])))}
38
+ ${$(n.phase==="planning"?"First up":"Ready",C.map(([h,S])=>f(h,S,[I("cancel",h,"Cancel step")])),se)}
39
+ ${$("Blocked",T.map(([h,S])=>f(h,S,[I("cancel",h,"Cancel step")])))}
40
+ ${$("Done",j.map(([h,S])=>f(h,S,[I("reopen",h,"Reopen")])),"Finished steps are locked on the chart: reopen one to change it.")}
41
+ ${$("Cancelled",k.map(([h,S])=>f(h,S,[I("reopen",h,"Reopen")])))}`}function Ts(e){const t=e?.plan?.nodes??{},n=Object.entries(t).filter(([,p])=>p&&p.kind!=="context"),s=(e?.presence??[]).filter(p=>p?.state==="asking").map(p=>String(p.actor)),i=n.filter(([,p])=>p.status==="waiting").map(([p])=>p),o=n.filter(([,p])=>p.status==="failed").map(([p])=>p),l=Object.keys(e?.derived?.stalled??{}).filter(p=>t[p]?.status==="in_progress"),a=(e?.plan?.proposals??[]).length,r=(e?.derived?.gates??[]).filter(p=>p.turn==="you").map(p=>({from:p.from,to:p.to})),d=e?.derived?.proposed??{},f=Object.keys(e?.review??{}).filter(p=>t[p]&&t[p].kind!=="context"&&!(p in d)),$=e?.plan?.phase==="executing"&&n.length>0&&n.every(([,p])=>p.status==="done"||p.status==="cancelled");return{asking:s,questions:i,failures:o,stalled:l,proposals:a,gates:r,reviews:f,finish:$,total:s.length+i.length+o.length+l.length+a+r.length+($?1:0)}}const V=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;function Po(e){const t=[e.asking.length?`${V(e.asking.length,"agent")} asking you in ${e.asking.length===1?"its window":"their windows"}`:"",e.questions.length?V(e.questions.length,"question"):"",e.gates?.length?V(e.gates.length,"checkpoint"):"",e.failures.length?V(e.failures.length,"failure"):"",e.stalled.length?`${e.stalled.length} stalled`:"",e.proposals?V(e.proposals,"proposal")+" to review":"",e.reviews?.length?`${V(e.reviews.length,"step")} to review`:"",e.finish?"the finished plan to close":""].filter(Boolean);return t.length?`Waiting on you: ${t.join(", ")}.`:""}function Io(e){const t=Ts(e),n=e?.plan?.nodes??{},s=o=>n[o]?.label??o,i=[];for(const o of(e?.presence??[]).filter(l=>l?.state==="asking"))i.push({key:`asking:${o.actor}:${o.permission?.id??""}`,kind:"asking",title:Dt(o),...o.permission?{permission:o.permission}:{}});for(const o of t.questions)i.push({key:`question:${o}`,kind:"question",step:o,title:`${s(o)} asks you`,...n[o]?.note?{detail:n[o].note}:{}});for(const o of(e?.derived?.gates??[]).filter(l=>l.turn==="you")){const l=o.kind==="approve"?`Approve the result of ${s(o.from)} before ${s(o.to)} starts`:o.kind==="input"?`${s(o.to)} needs input from you${o.label?`: ${o.label}`:""}`:`Before ${s(o.to)}, the agent asks: ${o.question??""}`,a=o.kind==="approve"?n[o.from]?.note:void 0;i.push({key:`gate:${o.from}>${o.to}`,kind:"checkpoint",step:o.to,title:l,...a?{detail:a}:{},gate:{from:o.from,to:o.to,kind:o.kind,label:o.label,question:o.question,...o.options?.length?{options:o.options}:{}}})}for(const o of t.failures)i.push({key:`failure:${o}`,kind:"failure",step:o,title:`${s(o)} failed`,...n[o]?.note?{detail:n[o].note}:{}});for(const o of t.stalled)i.push({key:`stalled:${o}`,kind:"stalled",step:o,title:`${s(o)} has stalled`,detail:Pt(e?.derived?.stalled?.[o])});for(const o of e?.plan?.proposals??[])i.push({key:`proposal:${o.id}`,kind:"proposal",proposal:o.id,title:`Proposal ${o.id} from ${_(String(o.by))}`,...o.reason?{detail:o.reason}:{}});if(t.reviews.length){const o=t.reviews.slice(0,3).map(s).join(", ");i.push({key:"review",kind:"review",steps:t.reviews,step:t.reviews[0],title:`Review ${V(t.reviews.length,"step")}`,detail:`${o}${t.reviews.length>3?` and ${t.reviews.length-3} more`:""}: a change upstream of ${t.reviews.length===1?"it":"them"} may have made ${t.reviews.length===1?"it":"them"} wrong`})}return t.finish&&i.push({key:"finish",kind:"finish",title:"Every step is done",detail:"Mark the plan done to close it. What it planned in the architecture is then put to you to make real."}),i}const Fo=(e,t)=>t>0?`(${t}) ${e}`:e,_s=e=>/[*?]/.test(e);function Wt(e){let t=String(e??"").trim().replace(/^(\.\/)+/,"");return t?(t.endsWith("/")&&!_s(t)&&(t=`${t}**`),t):""}function Bo(e,t){const n=Wt(t);return!n||e.includes(n)||e.length>=le?e:[...e,n]}const Wo=(e,t)=>e.filter(n=>n!==t);function Cs(e){if(!e)return{note:"",warn:!1};switch(e.kind){case"pattern":{const t=e.matches??0;return t===0?{note:"matches no files",warn:!0}:{note:`matches ${t} file${t===1?"":"s"}`,warn:!1}}case"new":return{note:"new file",warn:!1};case"folder":return{note:"a folder: add folder/** to watch what is in it",warn:!0};case"withheld":return{note:"private or ignored by git",warn:!1};default:return{note:"",warn:!1}}}function Ho(e,t,n,s){const i=t.filter(l=>!s.includes(l)).map(l=>({kind:"file",path:l,note:""})),o=Wt(e);if(!o||!n)return i;if(n.kind==="pattern"&&!s.includes(o)){const l=n.matches??0;i.push({kind:"pattern",path:o,note:l===0?"a pattern: matches no files":`a pattern: matches ${l} file${l===1?"":"s"}`})}else if(n.kind==="folder"){const l=`${o.replace(/\/+$/,"")}/**`;s.includes(l)||i.push({kind:"folder",path:l,note:"everything in this folder"})}else n.kind==="new"&&!s.includes(o)&&/[./]/.test(o)&&i.push({kind:"new",path:o,note:"a file this step will create"});return i}const x=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),gt={not_started:"not started",in_progress:"in progress",waiting:"waiting for you",done:"done",failed:"failed",cancelled:"cancelled"},Ms=(e,t=150)=>e.length>t?`${e.slice(0,t-1)}…`:e;function Uo(e,t,n){if(t==="detail")return{op:"node.set",id:e,detail:n.replace(/\s+$/,"")};if(t==="files")return{op:"node.set",id:e,files:[...new Set(n.split(`
42
+ `).map(s=>s.trim()).filter(Boolean))]};throw new Error(`a step has no field "${t}" to edit here`)}function Ht(e,t,n={}){return t.length?t.map(s=>{const{note:i,warn:o}=Cs(n[s]);return`<li class="file-chip${o?" warn":""}" data-path="${x(s)}"><code>${x(s)}</code>${i?`<span class="chip-note">${x(i)}</span>`:""}<button type="button" class="chip-x" data-remove-file="${x(s)}" data-step="${x(e)}" aria-label="Stop listing ${x(s)}">×</button></li>`}).join(""):'<li class="chips-none">None yet.</li>'}const Ns=(e,t)=>e.id===t||e.from===t||e.to===t||Array.isArray(e.ids)&&e.ids.includes(t);function Es(e,t,n=6){return[...e??[]].reverse().map(s=>({line:s,ops:(s.ops??[]).filter(i=>Ns(i,t))})).filter(s=>s.ops.length).slice(0,n).map(({line:s,ops:i})=>({rev:s.rev,actor:s.actor,text:i.map(o=>gn(o)).join("; "),...s.proposed?{proposed:s.proposed}:{}}))}function Ko({plan:e,id:t,derived:n={},review:s={},recent:i=[],drafts:o={},fileInfo:l={},arch:a=null,suggesting:r=""}){const d=e?.nodes?.[t];if(!d)return"";const f=d.kind==="context"?"context":d.status??"not_started",$=D[f]??"var(--wire-soft)",p=ze(d),u=n.blocked?.[t],c=n.stalled?.[t],g=n.atRisk?.[t],b=n.proposed?.[t],v=[`<b>${x(d.kind==="context"?"context, not work":gt[f]??f)}</b>`];p&&v.push(`${x(Ke[p.from])} ${x(_(p.who))}, ${x(Pe[p.from])}`),u?.length&&v.push(x(qt(u))),c&&v.push(`<span class="risk">stalled: ${x(_(c.owner))} is ${x(c.state)}</span>`),g?.length&&v.push(`<span class="risk">at risk: ${g.map(x).join(", ")} failed</span>`),s[t]&&v.push(`needs review: ${s[t].because.map(x).join("; ")} <button class="plain small" data-review="${x(t)}" title="I looked: no change is needed">Looks fine</button>`),b?.length&&v.push(`${b.length===1?"a proposal waits":`${b.length} proposals wait`} to change it (${b.map(x).join(", ")}): shown on the board`);const O=(j,k)=>j.length?`<ul class="rel">${j.map(M=>{const E=e.nodes[M],P=E.kind==="context"?"context":E.status??"not_started";return`<li><i class="dot" style="background:${D[P]??"var(--wire-soft)"}"></i>${x(E.label)} <code>${x(M)}</code> <span class="how">${x(gt[P]??P)}</span></li>`}).join("")}</ul>`:`<p class="help">${k}</p>`,q=Es(i,t),C=o.detail??d.detail??"",T=j=>j?' <b class="unsaved">Not saved yet.</b>':"";return`
43
+ <section class="inspector" aria-label="Step: ${x(d.label)}">
44
+ <header>
45
+ <div><i class="dot" style="background:${$}"></i><b class="name">${x(d.label)}</b> <code>${x(t)}</code></div>
46
+ <button class="plain" data-close-inspector aria-label="Close the details of ${x(d.label)}">Close</button>
47
+ </header>
48
+ <p class="facts">${v.join(" · ")}</p>
49
+
50
+ <label for="insp-detail">What done means</label>
51
+ <textarea id="insp-detail" data-field="detail" data-step="${x(t)}" rows="5" maxlength="${X}" placeholder="Not written yet. Say what is true when this step is finished: the tests that pass, the behaviour that works.">${x(C)}</textarea>
52
+ <p class="help">An agent is given this with the step. Saved when you leave the box.${T(o.detail!==void 0&&o.detail!==(d.detail??""))}</p>
53
+ ${r?`<p class="help suggesting">${x(r)}</p>`:""}
54
+ ${re(d.detail??"").length?`<p class="help">Addresses in it: ${re(d.detail??"").map(j=>Y(j)).join(", ")}</p>`:""}
55
+ <div class="row"><button class="primary" data-save-field="detail" data-step="${x(t)}">Save</button></div>
56
+
57
+ <label for="insp-files">Files this step changes</label>
58
+ <div class="files" data-files-for="${x(t)}">
59
+ <ul class="chips" aria-label="Files this step lists">${Ht(t,d.files??[],l)}</ul>
60
+ <div class="files-add">
61
+ <input id="insp-files" type="text" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-controls="insp-files-list" autocomplete="off" spellcheck="false" data-files-input="${x(t)}" placeholder="Search the repository, or type a path or a pattern">
62
+ <ul class="files-menu" id="insp-files-list" role="listbox" aria-label="Files to add" hidden></ul>
63
+ </div>
64
+ </div>
65
+ <p class="help">At most ${le}. A pattern such as <code>src/**/*.js</code> says how many files it matches. A file this step will create can be named before it exists. When an agent edits a file only this step lists, the step is marked started: that is how a start is <em>seen</em>.</p>
66
+
67
+ ${Rs(a,t,d)}
68
+ ${qs(e,t,d,n)}
69
+ <h5>Depends on</h5>
70
+ ${O(en(e,t),"Nothing: it can start.")}
71
+ <h5>Waited on by</h5>
72
+ ${O(kt(e,t),"Nothing depends on it.")}
73
+ <h5>History</h5>
74
+ ${q.length?`<ul class="hist">${q.map(j=>`<li><span class="how">rev ${x(j.rev)} · ${x(_(j.actor))}${j.proposed?" (a proposal)":""}</span> ${x(Ms(j.text))}</li>`).join("")}</ul>`:'<p class="help">Nothing done to it lately.</p>'}
75
+ </section>`}function qs(e,t,n,s){if(n.kind==="context")return"";const i=n.status??"not_started",o=(f,$)=>`<button data-act="${f}" data-step="${x(t)}">${$}</button>`,l=[],a=Array.isArray(s.ready)&&s.ready.includes(t);i==="not_started"&&a&&l.push(o("start","Start it myself"),o("done","Mark done")),i==="in_progress"&&l.push(o("done","Mark done"),o("failed","Mark failed"),...n.owner?[o("release",n.owner==="you"?"Release":"Take it back from the agent")]:[]);const r=(s.gates??[]).filter(f=>f.to===t&&f.turn==="agent");for(const f of r)l.push(`<button data-gate="pass" data-from="${x(f.from)}" data-to="${x(f.to)}">Let it start without asking</button>`);return l.length?`<h5>Do it yourself</h5><p class="help">${n.owner&&n.owner!=="you"?`${x(_(n.owner))} has this step. `:""}These change the plan for the agent: it is told at its next step.</p><div class="row actions">${l.join("")}</div>`:""}function Rs(e,t,n){if(!e)return'<h5>Boxes it changes</h5><p class="help">This repository has no architecture yet, so there is no box to name. Draw one in the Architecture view, or ask your agent to.</p>';const s=zn(e,n),i=new Set(n.touches??[]),o=a=>{const r=e.nodes[a.id],d=r?r.label:a.id;return a.by==="hand"?`<li class="file-chip${r?"":" warn"}" data-box="${x(a.id)}"><span>${x(d)}</span>${r?"":'<span class="chip-note">not in the architecture</span>'}<button type="button" class="chip-x" data-remove-touch="${x(a.id)}" data-step="${x(t)}" aria-label="Stop saying it changes ${x(d)}">×</button></li>`:`<li class="file-chip" data-box="${x(a.id)}"><span>${x(d)}</span><span class="chip-note">from its files</span></li>`},l=Object.entries(e.nodes).filter(([a])=>!i.has(a));return`
76
+ <h5>Boxes it changes</h5>
77
+ <ul class="chips touches" aria-label="Boxes of the architecture this step changes">${s.length?s.map(o).join(""):'<li class="chips-none">None named.</li>'}</ul>
78
+ <select data-touch-add="${x(t)}" aria-label="Add a box this step changes"><option value="">Add a box…</option>${l.map(([a,r])=>`<option value="${x(a)}">${x(r.label)} (${x(r.kind)})</option>`).join("")}</select>
79
+ <p class="help">What a plan does to the architecture: the Architecture view shows these boxes as changed. The ones this step's files fall in are included without being named.</p>`}const mt={person:"Person",service:"Service",component:"Component",store:"Store",queue:"Queue",group:"Group"},Ls={person:"a user or a role",service:"something that runs: an app, an API, a worker",component:"a part inside a service: a package, a folder, a file",store:"where data lives: a database, a cache, a bucket",queue:"a message channel: a queue, a topic, an event bus",group:"a frame round other boxes"},y=e=>Math.round(e*100)/100;function zo(e,{x:t,y:n,w:s,h:i},{folded:o=!1}={}){const l=t-s/2,a=t+s/2,r=n-i/2,d=n+i/2,f=[],$=(u,c,g={})=>f.push({tag:"path",role:c,attrs:{d:u,...g}}),p=(u,c=0,g=0)=>`M${y(l+c+u)} ${y(r+g)}H${y(a+c-u)}A${u} ${u} 0 0 1 ${y(a+c)} ${y(r+g+u)}V${y(d+g-u)}A${u} ${u} 0 0 1 ${y(a+c-u)} ${y(d+g)}H${y(l+c+u)}A${u} ${u} 0 0 1 ${y(l+c)} ${y(d+g-u)}V${y(r+g+u)}A${u} ${u} 0 0 1 ${y(l+c+u)} ${y(r+g)}Z`;switch(e){case"store":{const u=s/2,c=Math.min(9,Math.max(5,i*.18));$(`M${y(l)} ${y(r+c)}A${y(u)} ${y(c)} 0 0 1 ${y(a)} ${y(r+c)}V${y(d-c)}A${y(u)} ${y(c)} 0 0 1 ${y(l)} ${y(d-c)}Z`,"fill"),$(`M${y(l)} ${y(r+c)}A${y(u)} ${y(c)} 0 0 0 ${y(a)} ${y(r+c)}`,"line");break}case"queue":{const u=Math.min(12,s/5),c=i/2;$(`M${y(l+u)} ${y(r)}H${y(a-u)}A${y(u)} ${y(c)} 0 0 1 ${y(a-u)} ${y(d)}H${y(l+u)}A${y(u)} ${y(c)} 0 0 1 ${y(l+u)} ${y(r)}Z`,"fill"),$(`M${y(l+u)} ${y(r)}A${y(u)} ${y(c)} 0 0 0 ${y(l+u)} ${y(d)}`,"line");break}case"person":{f.push({tag:"circle",role:"fill",attrs:{cx:y(t),cy:y(r-4),r:7.5}}),$(p(Math.min(i/2,13)),"fill");break}case"component":o&&$(p(3,5,-5),"back"),$(p(3),"fill");break;case"group":{o&&$(p(10,5,-5),"back",{dashed:1}),$(p(10),"fill",{dashed:1});break}default:{const u=Math.min(14,i/2);o&&$(p(u,5,-5),"back"),$(p(u),"fill")}}return f}const Ds={ring:'<circle cx="6" cy="6" r="3.2"/>',half:'<circle cx="6" cy="6" r="3.6"/><path d="M6 2.4a3.6 3.6 0 0 1 0 7.2z" fill="currentColor" stroke="none"/>',hourglass:'<path d="M3.5 2.5h5L6 6zM3.5 9.5h5L6 6z" fill="currentColor"/>',check:'<path d="M3 6.3l2.2 2.2L9 3.9"/>',cross:'<path d="M3.6 3.6l4.8 4.8M8.4 3.6L3.6 8.4"/>',slash:'<circle cx="6" cy="6" r="3.6"/><path d="M3.5 8.5l5-5"/>',question:'<path d="M4.4 4.6c0-1 .7-1.8 1.7-1.8s1.7.7 1.7 1.6c0 1.4-1.7 1.4-1.7 2.8"/><path d="M6.1 9.2v.1"/>',pencil:'<path d="M3 9l.5-2.1 4.3-4.3 1.6 1.6L5.1 8.5z"/><path d="M7 3.5l1.6 1.6"/>',exclaim:'<path d="M6 2.8v4"/><path d="M6 9.2v.1"/>',plus:'<path d="M6 3v6M3 6h6"/>',async:'<path d="M2 6h1.6M5.2 6h1.6M8.4 6h1.6"/>',fold:'<path d="M3.2 4.2L6 7l2.8-2.8"/>',unfold:'<path d="M3.2 7.8L6 5l2.8 2.8"/>'},Jo={approve:"check",ask:"question",input:"pencil"},Yo={approve:"approve",ask:"ask first",input:"needs input"},Ps=e=>`<g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${Ds[e]??""}</g>`,Is=(e,{size:t=14,colour:n}={})=>`<svg class="glyph" viewBox="0 0 12 12" width="${t}" height="${t}" aria-hidden="true"${n?` style="color:${n}"`:""}>${Ps(e)}</svg>`,w=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),Fs=(e,t=150)=>e.length>t?`${e.slice(0,t-1)}…`:e,Bs=e=>`${e.external?"an outside":"a"} ${e.kind}`;function Xo({arch:e,id:t,footprint:n=null,steps:s={},drafts:i={},fileInfo:o={},recent:l=[],editable:a=!0,suggesting:r=""}){const d=e.nodes[t];if(!d)return"";const f=ee(e,t),$=d.in?e.nodes[d.in]:void 0,p=n?Nt(e,n,t):null,u=[`<b>${w(Bs(d))}</b>`];$&&u.push(`in <button class="plain small" data-inspect="${w(d.in)}">${w($.label)}</button>`),f.length&&u.push(`a frame: it holds ${f.length} box${f.length===1?"":"es"}, and takes no arrows of its own`),d.planned&&u.push(`<span class="plan-note new">${d.planned==="next"?"planned":`planned by <code>${w(d.planned)}</code>`}: it does not exist yet</span>`),d.retiring&&u.push(`<span class="plan-note removed">retiring: <code>${w(d.retiring)}</code> removes it</span>`),p&&p!=="untouched"&&u.push(`<span class="plan-note ${p}">${Is(Ie[p].icon,{size:12})} ${w(Ie[p].word)} by ${w(n?.plan??"")}</span>`);const c=n?.changed.get(t)??[],g=i.detail??d.detail??"",b=i.tech??d.tech??"",v=a?"":" disabled",O=(k,M)=>k.length?`<ul class="rel">${k.map(E=>{const P=e.nodes[E];return`<li><button class="plain small" data-inspect="${w(E)}">${w(P.label)}</button> <span class="how">${w(P.kind)}</span></li>`}).join("")}</ul>`:`<p class="help">${M}</p>`,q=e.edges.filter(k=>k.from===t),C=e.edges.filter(k=>k.to===t),T=(k,M)=>`<ul class="rel">${k.map(E=>{const P=e.nodes[E[M]];return`<li><button class="plain small" data-inspect="${w(E[M])}">${w(P.label)}</button> <span class="how">${w([E.label,E.tech,E.async?"async":""].filter(Boolean).join(" · ")||P.kind)}</span></li>`}).join("")}</ul>`,j=[...l].reverse().map(k=>({l:k,ops:(k.ops??[]).filter(M=>M.id===t||M.from===t||M.to===t)})).filter(k=>k.ops.length).slice(0,6);return`
80
+ <section class="inspector box-card" aria-label="Box: ${w(d.label)}" data-box="${w(t)}">
81
+ <header>
82
+ <div><i class="dot kind-${w(d.kind)}"></i><b class="name">${w(d.label)}</b> <code>${w(t)}</code></div>
83
+ <button class="plain" data-close-inspector aria-label="Close the details of ${w(d.label)}">Close</button>
84
+ </header>
85
+ <p class="facts">${u.join(" · ")}</p>
86
+ ${c.length?`<p class="facts">Changed by ${c.map(k=>w(s[k]?.label??k)).join(", ")}.</p>`:""}
87
+ <p class="help">${w(Ls[d.kind]??"")}. Double-click the box to rename it.</p>
88
+
89
+ <div class="row fields">
90
+ <label>What it is <select data-box-field="kind" data-box="${w(t)}"${v} aria-label="What ${w(d.label)} is">${Object.keys(mt).map(k=>`<option value="${k}"${k===d.kind?" selected":""}${f.length&&k!=="service"&&k!=="group"?" disabled":""}>${w(mt[k])}</option>`).join("")}</select></label>
91
+ <label class="check"><input type="checkbox" data-box-field="external" data-box="${w(t)}"${d.external?" checked":""}${v}> Someone else runs it</label>
92
+ </div>
93
+
94
+ <label for="insp-tech">What it runs on</label>
95
+ <input id="insp-tech" type="text" data-box-field="tech" data-box="${w(t)}" maxlength="${te}" value="${w(b)}" placeholder="Python, FastAPI"${v}>
96
+
97
+ <label for="insp-detail">What it is for</label>
98
+ <textarea id="insp-detail" data-box-field="detail" data-box="${w(t)}" rows="4" maxlength="${X}" placeholder="Not written yet. Say what this box is for, and what it is not."${v}>${w(g)}</textarea>
99
+ <p class="help">An agent reads this with the architecture. Saved when you leave the box.${i.detail!==void 0&&i.detail!==(d.detail??"")?' <b class="unsaved">Not saved yet.</b>':""}</p>
100
+ ${r?`<p class="help suggesting">${w(r)}</p>`:""}
101
+
102
+ ${a?`<label for="insp-files">The files that are its</label>
103
+ <div class="files" data-files-for="${w(t)}">
104
+ <ul class="chips" aria-label="Files this box owns">${Ht(t,d.files??[],o)}</ul>
105
+ <div class="files-add">
106
+ <input id="insp-files" type="text" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-controls="insp-files-list" autocomplete="off" spellcheck="false" data-files-input="${w(t)}" placeholder="Search the repository, or type a path or a pattern">
107
+ <ul class="files-menu" id="insp-files-list" role="listbox" aria-label="Files to add" hidden></ul>
108
+ </div>
109
+ </div>
110
+ <p class="help">At most ${le}. A plan whose step lists a file one of these covers is shown as changing this box.</p>`:""}
111
+
112
+ <h5>Uses</h5>
113
+ ${q.length?T(q,"to"):'<p class="help">Nothing.</p>'}
114
+ <h5>Used by</h5>
115
+ ${C.length?T(C,"from"):'<p class="help">Nothing.</p>'}
116
+ ${f.length?`<h5>Holds</h5>${O(f,"")}`:""}
117
+ <h5>History</h5>
118
+ ${j.length?`<ul class="hist">${j.map(({l:k,ops:M})=>`<li><span class="how">rev ${w(k.rev)} · ${w(_(k.actor))}${k.proposed?" (a proposal)":""}</span> ${w(Fs(M.map(E=>Se(E)).join("; ")))}</li>`).join("")}</ul>`:'<p class="help">Nothing done to it lately.</p>'}
119
+ </section>`}function Go({arch:e,selected:t=null,folded:n=[],footprint:s=null,foldable:i=!0}){const o=Object.keys(e.nodes);if(!o.length)return'<p class="lede">Nothing is drawn yet. Double-click the board to add a box, or ask your agent to draw the architecture.</p>';const l=a=>{const r=e.nodes[a],d=ee(e,a),f=s?Nt(e,s,a):null,$=f&&f!=="untouched"?` <span class="plan-note ${f}">${w(Ie[f].word)}</span>`:r.planned?' <span class="plan-note new">planned</span>':r.retiring?' <span class="plan-note removed">retiring</span>':"",p=n.includes(a);return`<li class="box-item" data-box="${w(a)}">
120
+ <button class="plain box-row" data-inspect="${w(a)}"${a===t?' aria-current="true"':""}><i class="dot kind-${w(r.kind)}"></i><span class="box-name">${w(r.label)}</span> <span class="how">${w(r.external?`outside ${r.kind}`:r.kind)}${r.tech?` · ${w(r.tech)}`:""}</span>${$}</button>
121
+ ${d.length&&i?`<button class="plain small fold" data-fold="${w(a)}" aria-pressed="${p}" title="${p?"Unfold: show what is inside":"Fold: hide what is inside"}">${p?"Unfold":"Fold"}</button>`:""}
122
+ ${d.length?`<ul class="box-children">${d.map(l).join("")}</ul>`:""}
123
+ </li>`};return`<ul class="boxlist" aria-label="Boxes">${o.filter(a=>!e.nodes[a].in).map(l).join("")}</ul>`}function Vo({arch:e,flowId:t=null,at:n=null,playing:s=!1}){if(!e.flows.length)return`<p class="lede">A flow is what happens, in order, when someone does something: the steps run along the arrows the diagram already has, and you play them here.</p>
124
+ <p class="lede">None yet. Ask your agent to draw one (<code>flow.add</code>), or add one in the Data tab of the Source drawer.</p>`;const i=e.flows.find(r=>r.id===t)??null,o=`<ul class="flowlist" aria-label="Flows">${e.flows.map(r=>`
125
+ <li><button class="plain flow-row" data-flow="${w(r.id)}"${r.id===i?.id?' aria-current="true"':""}><b>${w(r.title)}</b> <span class="how">${r.steps.length} step${r.steps.length===1?"":"s"}</span></button></li>`).join("")}</ul>`;if(!i)return`${o}<p class="help">Pick one to light its steps, one at a time, on the diagram.</p>`;const l=r=>w(e.nodes[r]?.label??r),a=i.steps.map((r,d)=>{const f=Kn(e,r),$=f==="reply"?' <span class="how">a reply</span>':f==="gap"?' <span class="how gap" title="The diagram does not draw this call: either an arrow is missing, or the flow is wrong.">no arrow for it</span>':"";return`<li data-flow-step="${d}"${d===n?' aria-current="step"':""}><button class="plain" data-flow-at="${d}"><span class="n">${d+1}</span> ${l(r.from)} <span aria-hidden="true">→</span> ${l(r.to)}${r.label?` <span class="how">${w(r.label)}</span>`:""}${$}</button></li>`}).join("");return`${o}
126
+ <section class="flow-open" aria-label="${w(i.title)}">
127
+ <header><b>${w(i.title)}</b></header>
128
+ <div class="row">
129
+ <button data-flow-prev aria-label="Previous step"${n===null||n<=0?" disabled":""}>&lsaquo; Back</button>
130
+ <button class="primary" data-flow-play>${s?"Pause":n===null?"Play":n>=i.steps.length-1?"Play again":"Play"}</button>
131
+ <button data-flow-next aria-label="Next step"${n!==null&&n>=i.steps.length-1?" disabled":""}>Next &rsaquo;</button>
132
+ <button class="plain" data-flow-clear>Show everything</button>
133
+ </div>
134
+ <ol class="flow-steps">${a}</ol>
135
+ </section>`}function Qo(e){const t=[...e].reverse();return t.length?`
136
+ <p class="lede">The architecture's log, newest first. It is committed with the architecture, so a pull request shows who did what.</p>
137
+ <ul class="log">${t.map(n=>`
138
+ <li><span class="rev">rev ${n.rev}</span> <code>${w(n.actor)}</code> <span class="via">via ${w(n.via)}</span>
139
+ ${n.proposed?`<span class="via">→ proposal ${w(n.proposed)}</span>`:""}
140
+ <div>${(n.ops??[]).map(s=>w(Se(s))).join(" · ")}</div></li>`).join("")}</ul>`:'<p class="lede">No changes yet. Everything you do here is logged, with who did it.</p>'}function Zo(e,t={}){const n=[];e.phase==="draft"&&n.push({kind:"draft",title:"Approve the architecture",detail:`${t.by?`${_(t.by)} drew it. `:""}Look it over and change what is wrong, then approve it. Your agent then draws the plan on it, and its later changes to it arrive as proposals for you to accept.`});for(const s of e.proposals??[])n.push({kind:"proposal",title:`${_(s.by)} proposes ${s.ops.length} change${s.ops.length===1?"":"s"} to the architecture`,detail:s.reason??s.ops.map(i=>Se(i)).join("; "),proposal:s.id});return n}function Ws(e,{show:t=n=>`<button class="plain small" data-arch-show="${w(n)}">Show on the board</button>`}={}){return e.map(n=>`
141
+ <li class="inbox-item" data-kind="${n.kind}">
142
+ <div class="inbox-what"><b>${w(n.title)}</b>${n.detail?`<span class="inbox-detail">${w(n.detail)}</span>`:""}</div>
143
+ <div class="row actions">${n.kind==="draft"?'<button class="primary" data-arch-accept-draft>Approve architecture</button>':`<button class="primary" data-arch-accept="${w(n.proposal??"")}">Accept</button>${Ut(n.proposal??"")}<button data-arch-reject="${w(n.proposal??"")}">Reject</button>${t(n.proposal??"")}`}</div>
144
+ </li>`).join("")}const ea=(e,t)=>`<ul class="inbox">${Ws(e,t)}</ul>`;function ta(e,{at:t,of:n,applies:s,why:i,arch:o}){const l=a=>Hs(Se(a),o);return`
145
+ <header><b>${w(_(e.by))} proposes</b>${n>1?` <span class="how">${t} of ${n}</span>`:""}</header>
146
+ ${e.reason?`<p class="reason">${w(e.reason)}</p>`:""}
147
+ <ul class="ops">${e.ops.map(a=>`<li>${w(l(a))}</li>`).join("")}</ul>
148
+ ${s?"":`<p class="risk">It no longer applies: ${w(i??"the architecture changed under it")}.</p>`}
149
+ <div class="row actions"><button class="primary" data-arch-accept="${w(e.id)}"${s?"":" disabled"}>Accept</button>${Ut(e.id)}<button data-arch-reject="${w(e.id)}">Reject</button>${n>1?'<button class="plain small" data-arch-next>Next</button>':""}</div>`}const Ut=e=>`<input data-arch-why="${w(e)}" placeholder="why not (optional)" aria-label="Why you reject ${w(e)}">`;function Hs(e,t){if(!t)return e;const n=Object.keys(t.nodes).sort((i,o)=>o.length-i.length);if(!n.length)return e;const s=new RegExp(`(?<![\\w-])(${n.map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})(?![\\w-])`,"g");return e.replace(s,i=>t.nodes[i]?.label??i)}function Us({plan:e,step:t,proposal:n,architecture:s,sample:i}={}){const o=l=>encodeURIComponent(l);return s?n?`architecture/proposal/${o(n)}`:i?`architecture/${o(i)}`:"architecture":e?[o(e),...t?["step",o(t)]:n?["proposal",o(n)]:[]].join("/"):""}const na=e=>`/app/#${Us(e)}`;function sa(e){const t=e.replace(/^#/,"").split("/").filter(Boolean).map(n=>{try{return decodeURIComponent(n)}catch{return n}});return t.length?t[0]==="architecture"?t[1]==="proposal"&&t[2]?{architecture:!0,proposal:t[2]}:t[1]?{architecture:!0,sample:t[1]}:{architecture:!0}:t[1]==="step"&&t[2]?{plan:t[0],step:t[2]}:t[1]==="proposal"&&t[2]?{plan:t[0],proposal:t[2]}:{plan:t[0]}:{}}const B={padding:9,maxWidth:168,minWidth:66,minHeight:34,fontSize:12.5},Kt=Math.round(B.fontSize*1.35),Ks=e=>Math.max(B.minHeight,e*Kt+B.padding*2),zs=16,wt=6,bt={x:Math.ceil(B.maxWidth/2+wt),y:Math.ceil(Ks(3)/2+zs+wt/2)},oa=e=>({width:e.canvas.width+bt.x*2,height:e.canvas.height+bt.y*2}),me={left:16,right:16,top:32,bottom:14},Js=e=>!!e&&e!==he;function Ys(e){const t=new Map;for(const n of e){if(!Js(n.group))continue;const s=t.get(n.group);s?s.push(n):t.set(n.group,[n])}return[...t].map(([n,s])=>{const i=Math.min(...s.map(r=>r.x-r.w/2))-me.left,o=Math.max(...s.map(r=>r.x+r.w/2))+me.right,l=Math.min(...s.map(r=>r.y-r.h/2))-me.top,a=Math.max(...s.map(r=>r.y+r.h/2))+me.bottom;return{group:n,x:i,y:l,w:o-i,h:a-l,members:s.map(r=>r.id)}})}const aa=(e,t,n)=>e.filter(s=>t>=s.x&&t<=s.x+s.w&&n>=s.y&&n<=s.y+s.h).sort((s,i)=>s.w*s.h-i.w*i.h)[0];function Xs(e,t,n=6.6){const s=Math.max(3,Math.floor((t-20)/n));return e.length<=s?e:`${e.slice(0,Math.max(1,s-1))}…`}const Gs={x:14,y:14};let qe;function zt(e){qe||=document.createElement("canvas").getContext("2d");const t=getComputedStyle(document.documentElement).getPropertyValue("--sans").trim()||"sans-serif";return qe.font=`normal ${B.fontSize}px ${t}`,qe.measureText(e).width}function Vs(e){const t=B.maxWidth-B.padding*2,n=String(e??"").split(/\s+/).filter(Boolean),s=[];let i="";for(const o of n){const l=i?`${i} ${o}`:o;i&&zt(l)>t?(s.push(i),i=o):i=l}return i&&s.push(i),s.length?s:[""]}function ve(e){const t=Vs(e),n=Math.max(...t.map(zt)),s=Kt;return{width:Math.max(B.minWidth,Math.min(B.maxWidth,n+B.padding*2)),height:Math.max(B.minHeight,t.length*s+B.padding*2),lines:t,step:s}}const Re=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]);function Qs(e,t,n){const s={...e,...ve(e.label)},i={...t,...ve(t.label)};if(n==="TD"){const f=s.x,$=s.y+s.height/2,p=i.x,u=i.y-i.height/2;if(u<=$)return`M${s.x} ${s.y} L${i.x} ${i.y}`;const c=($+u)/2;return Math.abs(f-p)<1?`M${f} ${$} V${u}`:`M${f} ${$} V${c} H${p} V${u}`}const o=s.x+s.width/2,l=s.y,a=i.x-i.width/2,r=i.y;if(a<=o)return`M${s.x} ${s.y} L${i.x} ${i.y}`;const d=(o+a)/2;return Math.abs(l-r)<1?`M${o} ${l} H${a}`:`M${o} ${l} H${d} V${r} H${a}`}let Zs=0;function ia(e,{labels:t=!1,className:n="",title:s="",margin:i=Gs,edge:o}={}){const l=e.canvas.width+i.x*2,a=e.canvas.height+i.y*2,r=new Map(e.steps.map(c=>[c.id,c])),d=e.direction==="TD"?"TD":"LR",f=`ah${++Zs}`,$=e.depends.filter(c=>r.has(c.source)&&r.has(c.target)).map(c=>`<path d="${Qs(r.get(c.source),r.get(c.target),d)}" marker-end="url(#${f})"/>`).join(""),p=Ys(e.steps.map(c=>{const g=ve(c.label);return{id:c.id,group:c.group,x:c.x,y:c.y,w:g.width,h:g.height}})).map(c=>`<rect x="${c.x.toFixed(1)}" y="${c.y.toFixed(1)}" width="${c.w.toFixed(1)}" height="${c.h.toFixed(1)}" rx="10" fill="var(--frame)" stroke="var(--frame-edge)" stroke-width="1.2"/>`+(t?`<text class="frame-name" x="${(c.x+12).toFixed(1)}" y="${(c.y+19).toFixed(1)}" font-size="11.5" font-weight="600" fill="var(--slate)">${Re(Xs(c.group,c.w))}</text>`:"")).join(""),u=e.steps.map(c=>{const g=ve(c.label),b=c.x-g.width/2,v=c.y-g.height/2,O=o?.(c.id);let q=`<rect x="${b.toFixed(1)}" y="${v.toFixed(1)}" width="${g.width.toFixed(1)}" height="${g.height.toFixed(1)}" rx="7" fill="var(--surface)" stroke="${O??"var(--wire)"}" stroke-width="${O?3:1.5}"/>`;if(t){const C=g.step,T=c.y-(g.lines.length-1)*C/2;q+=g.lines.map((j,k)=>`<text x="${c.x}" y="${(T+k*C).toFixed(1)}" dy=".35em" text-anchor="middle">${Re(j)}</text>`).join("")}return q}).join("");return`<svg class="${n}" viewBox="0 0 ${l} ${a}" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="${Re(s||e.title)}" preserveAspectRatio="xMidYMid meet">
150
+ <defs><marker id="${f}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" fill="var(--wire)"/></marker></defs>
151
+ <g transform="translate(${i.x} ${i.y})">
152
+ <g class="frames">${p}</g>
153
+ <g fill="none" stroke="var(--wire)" stroke-width="1.4">${$}</g>
154
+ <g class="boxes" font-size="${B.fontSize}" fill="var(--ink)" font-family="var(--sans)">${u}</g>
155
+ </g>
156
+ </svg>`}const ra=()=>(document.fonts?.load('400 12.5px "Geist Variable"',"generator.js drawMaze")??Promise.resolve()).catch(()=>{});export{bt as $,Ao as A,Ro as B,wo as C,$o as D,Pe as E,Ie as F,Ke as G,Fo as H,yo as I,ps as J,ia as K,uo as L,so as M,no as N,en as O,tn as P,kt as Q,yt as R,D as S,to as T,eo as U,xt as V,Nn as W,pe as X,ct as Y,co as Z,he as _,Zo as a,B as a0,oa as a1,lo as a2,jt as a3,me as a4,ao as a5,In as a6,Nt as a7,Ys as a8,Xs as a9,Ko as aA,Do as aB,vo as aC,fo as aD,Po as aE,bo as aF,Ht as aG,ws as aH,Wo as aI,_o as aJ,Yo as aK,Eo as aL,Lo as aM,gn as aN,po as aO,Wt as aP,Ho as aQ,Bo as aR,Ps as aa,Jo as ab,zo as ac,mt as ad,ro as ae,ea as af,ho as ag,Xo as ah,ms as ai,Go as aj,Vo as ak,Qo as al,Oo as am,us as an,jo as ao,ta as ap,oo as aq,Ee as ar,aa as as,ko as at,sa as au,Uo as av,Fe as aw,ds as ax,Co as ay,To as az,Ws as b,Ss as c,qo as d,Os as e,js as f,Pt as g,na as h,Io as i,Dt as j,io as k,Is as l,So as m,Ts as n,No as o,ks as p,Mo as q,ra as r,_ as s,Us as t,fs as u,cs as v,ze as w,go as x,mo as y,xo as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diacode",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "A plan you and your coding agents share: a diagram in your repository that you edit by hand, with each step showing who has it and how that is known. For OpenCode, Claude Code, Cursor and Antigravity.",
5
5
  "type": "module",
6
6
  "bin": {