diacode 0.2.3 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 no=(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"],so=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"]}},oo=new Set(["node.add","node.set","node.remove","edge.add","edge.remove","edge.rewire","edge.reverse","edge.set","group.rename"]);function ao(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(([_])=>l().startsWith(_));if(b){o+=b[0].length;const _=l();if(_.startsWith('"')){const T=_.indexOf('"',1);if(T<0)throw new Error(`${t}: an unclosed quote in ${u}'s label`);c=_.slice(1,T),o+=T+1,a();const j=ge.find(([k,N])=>k===b[0]&&l().startsWith(N))??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=>_.indexOf(k)).filter(k=>k>=0));if(!Number.isFinite(j))throw new Error(`${t}: ${u}'s label is not closed`);c=_.slice(0,j).trim(),o+=j+(T.find(k=>_.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},Cn=/^(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?Cn.exec(t):null;return n?{kind:n[1].toLowerCase(),...n[2]?.trim()?{label:n[2].trim()}:{}}:t?{label:t}:{}}const _n=(e,t)=>e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")||`group${t}`;function io(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 ${_n(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 Nn(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 Mn(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 ro(e,t,n){const s=n instanceof Set?n:new Set(n);return Mn(e,t).reverse().find(o=>s.has(o))??t}const De="diacode.arch/0",be=["person","service","component","store","queue","group"],ye=["draft","accepted"],lt=["diacode","dcursed","mermaid","c4","markdown","cursor-plan"],te=120,dt=40,ke=60,M=(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),M(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&&!M(e.tech,1,te)&&n.push(`${s}: tech is 1-${te} characters`),e.detail!==void 0&&!M(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&&!M(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}"`),M(e.title,1,200)||t.push("architecture: needs a title of 1-200 characters"),e.goal!==void 0&&!M(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&&!M(o.label,0,120)&&t.push(`${a}: label is at most 120 characters`),o.tech!==void 0&&!M(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),M(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),M(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&&!M(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(...Ct(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 Ct(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&&!M(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&&!M(e.tech,0,te)&&n.push(`${e.op}: tech is at most ${te} characters`),e.detail!==void 0&&!M(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&&!M(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&&!M(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&&!M(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")&&!M(e.id,1,64)&&n.push(`${e.op}: needs a proposal id`),e.reason!==void 0&&!M(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)},Ce=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=Ct(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(Ce)){const i=t.filter(Ce),o=t.filter(f=>!Ce(f)),l=_e(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=_e({...r,rev:e.rev},o,n);return d.kind==="rejected"?{...d,index:t.indexOf(o[d.index])}:{...d,proposal:a}}return _e(e,t,n)}function _e(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(_t(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 _t(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=Ne(e,t.from,t.to);return e.edges.splice(e.edges.indexOf(a),1),t}case"arrow.rewire":case"arrow.reverse":{const a=Ne(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 Nt(e,r,d,a),a.from=r,a.to=d,t}case"arrow.set":{const a=Ne(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{_t(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 Ne(e,t,n){return e.edges.find(s=>s.from===t&&s.to===n)??A(`there is no arrow ${t} → ${n}`)}function Nt(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){Nt(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:"diacode"},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 lo(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 Mt(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,_]=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,N=T==="Container"||T==="Component",E=N?q:void 0,P=N?_: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 co(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",uo=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",opencode:"OpenCode",cursor:"Cursor",antigravity:"Antigravity"},C=e=>{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"||s==="build"?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]} ${C(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 fo(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",po={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}},ho=["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 $o=(e,t=12)=>ne(`/api/files?q=${encodeURIComponent(e)}&limit=${t}`);async function go(e){return e.length?(await ne(`/api/files?${e.map(t=>`check=${encodeURIComponent(t)}`).join("&")}`)).results:[]}async function mo(){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 wo=async()=>(await ne("/api/plans")).plans,bo=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 yo(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 ko(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 xo=(e,t)=>Je(`/api/plans/${encodeURIComponent(e)}/events`,{change:t.change,problem:t.problem,reconcile:t.reconcile,presence:t.presence,call:t.call},t),vo=e=>Je("/api/events",{plans:e.plans},{open:e.open,down:()=>{}}),So=()=>ne("/api/architecture"),Ao=()=>ne("/api/flow");async function Oo(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 jo=()=>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 To=e=>Je("/api/architecture/events",{change:e.change,problem:e.problem,call:e.call},e);async function Co(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 _o(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 No(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 Mo(e){const t=Nn(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 Me=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="${Me(t.href)}" target="_blank" rel="noopener noreferrer">${Me(t.text)}</a>`:Me(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 Eo(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 qo(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 diacode 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.",Ro=["planning","executing","done"],we="Carry on with the plan with the diacode tools: read it first, then take the next step.",Fe=e=>{const t=e.map(C);return t.length<2?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`};function Lo(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 Do(e){const t=e.to?C(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 diacode 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?C(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?`${C(e.actor)} asks your permission to ${e.permission.what}`:`${C(e.actor)} is waiting for you in its own window${e.detail?`: ${e.detail}`:""}`}function Pt(e){const t=C(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(C(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(C(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?C(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 Ss=`Only this exact command can be allowed here. Claude Code's own window may offer a wider "don't ask again" (for curl or node commands, say); DiaCode does not pass that on, because a rule that wide lets the agent run anything of that kind unasked.`,As=(e,t)=>`<details class="inbox-full" data-whole-command><summary>Show the whole command</summary><pre>${m(e)}</pre>${t?`<span class="inbox-detail">This command is longer than the editor shows. It cannot be allowed from here: read it in the agent's window and answer it there, or deny it.</span>`:""}</details>`,I=(e,t,n,s=!1)=>`<button${s?' class="primary"':""} data-act="${e}" data-step="${m(t)}">${n}</button>`;function Os(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?.partial?`<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>`: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>`:""}${d.kind==="asking"&&d.permission?.full?As(d.permission.full,d.permission.partial===!0):""}${d.kind==="asking"&&d.permission?.tool==="Bash"&&!d.permission.always&&!d.permission.partial?`<span class="inbox-detail" data-no-always>${m(Ss)}</span>`:""}</div>
12
+ ${a(d)?`<div class="row actions">${a(d)}</div>`:""}
13
+ ${d.kind==="review"?It(t.reconcile):""}
14
+ </li>`).join("")}const Po=(e,t,n)=>`<ul class="inbox">${Os(e,t,n)}</ul>`;function js(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(C(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 Ts(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 Cs(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 Io(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(C(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??{}))),_=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"),N=new Set(e.listening??[]),P=b.length>0&&b.every(([,h])=>h.owner&&N.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
+ ${Ts(l)}
25
+ <p class="lede">${Cs(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
+ ${js(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",_.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 _s(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 Fo(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 Bo(e){const t=_s(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 ${C(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 Wo=(e,t)=>t>0?`(${t}) ${e}`:e,Ns=e=>/[*?]/.test(e);function Wt(e){let t=String(e??"").trim().replace(/^(\.\/)+/,"");return t?(t.endsWith("/")&&!Ns(t)&&(t=`${t}**`),t):""}function Ho(e,t){const n=Wt(t);return!n||e.includes(n)||e.length>=le?e:[...e,n]}const Uo=(e,t)=>e.filter(n=>n!==t);function Ms(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 Ko(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"},Es=(e,t=150)=>e.length>t?`${e.slice(0,t-1)}…`:e;function zo(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}=Ms(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 qs=(e,t)=>e.id===t||e.from===t||e.to===t||Array.isArray(e.ids)&&e.ids.includes(t);function Rs(e,t,n=6){return[...e??[]].reverse().map(s=>({line:s,ops:(s.ops??[]).filter(i=>qs(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 Jo({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(C(p.who))}, ${x(Pe[p.from])}`),u?.length&&v.push(x(qt(u))),c&&v.push(`<span class="risk">stalled: ${x(C(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(N=>{const E=e.nodes[N],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(N)}</code> <span class="how">${x(gt[P]??P)}</span></li>`}).join("")}</ul>`:`<p class="help">${k}</p>`,q=Rs(i,t),_=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(_)}</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
+ ${Ds(a,t,d)}
68
+ ${Ls(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(C(j.actor))}${j.proposed?" (a proposal)":""}</span> ${x(Es(j.text))}</li>`).join("")}</ul>`:'<p class="help">Nothing done to it lately.</p>'}
75
+ </section>`}function Ls(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(C(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 Ds(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"},Ps={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 Yo(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 Is={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"/>'},Xo={approve:"check",ask:"question",input:"pencil"},Go={approve:"approve",ask:"ask first",input:"needs input"},Fs=e=>`<g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${Is[e]??""}</g>`,Bs=(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}"`:""}>${Fs(e)}</svg>`,w=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),Ws=(e,t=150)=>e.length>t?`${e.slice(0,t-1)}…`:e,Hs=e=>`${e.external?"an outside":"a"} ${e.kind}`;function Vo({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?Mt(e,n,t):null,u=[`<b>${w(Hs(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}">${Bs(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,N)=>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">${N}</p>`,q=e.edges.filter(k=>k.from===t),_=e.edges.filter(k=>k.to===t),T=(k,N)=>`<ul class="rel">${k.map(E=>{const P=e.nodes[E[N]];return`<li><button class="plain small" data-inspect="${w(E[N])}">${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(N=>N.id===t||N.from===t||N.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(Ps[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
+ ${_.length?T(_,"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:N})=>`<li><span class="how">rev ${w(k.rev)} · ${w(C(k.actor))}${k.proposed?" (a proposal)":""}</span> ${w(Ws(N.map(E=>Se(E)).join("; ")))}</li>`).join("")}</ul>`:'<p class="help">Nothing done to it lately.</p>'}
119
+ </section>`}function Qo({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?Mt(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 Zo({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 ea(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 ta(e,t={}){const n=[];e.phase==="draft"&&n.push({kind:"draft",title:"Approve the architecture",detail:`${t.by?`${C(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:`${C(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 Us(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 na=(e,t)=>`<ul class="inbox">${Us(e,t)}</ul>`;function sa(e,{at:t,of:n,applies:s,why:i,arch:o}){const l=a=>Ks(Se(a),o);return`
145
+ <header><b>${w(C(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 Ks(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 zs({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 oa=e=>`/app/#${zs(e)}`;function aa(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),Js=e=>Math.max(B.minHeight,e*Kt+B.padding*2),Ys=16,wt=6,bt={x:Math.ceil(B.maxWidth/2+wt),y:Math.ceil(Js(3)/2+Ys+wt/2)},ia=e=>({width:e.canvas.width+bt.x*2,height:e.canvas.height+bt.y*2}),me={left:16,right:16,top:32,bottom:14},Xs=e=>!!e&&e!==he;function Gs(e){const t=new Map;for(const n of e){if(!Xs(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 ra=(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 Vs(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 Qs={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 Zs(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=Zs(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 eo(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 to=0;function la(e,{labels:t=!1,className:n="",title:s="",margin:i=Qs,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${++to}`,$=e.depends.filter(c=>r.has(c.source)&&r.has(c.target)).map(c=>`<path d="${eo(r.get(c.source),r.get(c.target),d)}" marker-end="url(#${f})"/>`).join(""),p=Gs(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(Vs(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 _=g.step,T=c.y-(g.lines.length-1)*_/2;q+=g.lines.map((j,k)=>`<text x="${c.x}" y="${(T+k*_).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 da=()=>(document.fonts?.load('400 12.5px "Geist Variable"',"generator.js drawMaze")??Promise.resolve()).catch(()=>{});export{bt as $,jo as A,Do as B,yo as C,mo as D,Pe as E,Ie as F,Ke as G,Wo as H,xo as I,ps as J,la as K,po as L,ao as M,oo as N,en as O,tn as P,kt as Q,yt as R,D as S,so as T,no as U,xt as V,Mn as W,pe as X,ct as Y,fo as Z,he as _,ta as a,B as a0,ia as a1,uo as a2,jt as a3,me as a4,ro as a5,In as a6,Mt as a7,Gs as a8,Vs as a9,Jo as aA,Io as aB,Ao as aC,ho as aD,Fo as aE,ko as aF,Ht as aG,ws as aH,Uo as aI,No as aJ,Go as aK,Ro as aL,Po as aM,gn as aN,$o as aO,Wt as aP,Ko as aQ,Ho as aR,Fs as aa,Xo as ab,Yo as ac,mt as ad,co as ae,na as af,go as ag,Vo as ah,ms as ai,Qo as aj,Zo as ak,ea as al,To as am,us as an,Co as ao,sa as ap,io as aq,Ee as ar,ra as as,vo as at,aa as au,zo as av,Fe as aw,ds as ax,Mo as ay,_o as az,Us as b,Os as c,Lo as d,Ts as e,Cs as f,Pt as g,oa as h,Bo as i,Dt as j,lo as k,Bs as l,Oo as m,_s as n,qo as o,ks as p,Eo as q,da as r,C as s,zs as t,fs as u,cs as v,ze as w,wo as x,bo as y,So as z};
@@ -1,4 +1,4 @@
1
- // dcursed.js — the OpenCode side of DiaCode. One file with no dependencies, so `diacode init`
1
+ // diacode.js — the OpenCode side of DiaCode. One file with no dependencies, so `diacode init`
2
2
  // can copy it into a repository's .opencode/plugins/.
3
3
  //
4
4
  // The MCP tools are how the agent reads and edits the plan. This plugin does what the tools
@@ -27,28 +27,28 @@ const HEARTBEAT_MS = 20_000;
27
27
  /** Tools that write a file named by one of these arguments. */
28
28
  const FILE_ARGS = ['filePath', 'path', 'file'];
29
29
  const PATCH_FILE = /^\*\*\* (?:Add|Update|Delete) File: (.+?)\s*$/gm;
30
- /** The end of every dcursed tool's reply: which plan it was about. */
30
+ /** The end of every diacode tool's reply: which plan it was about. */
31
31
  const FOOTER = /\[plan ([^\s\]]+) · rev (\d+)\]\s*$/;
32
32
  /** How long the plan server holds the request for a call before answering with nothing (and it is asked again). */
33
33
  const HOLD_MS = 50_000;
34
34
 
35
35
  /**
36
36
  * Options, from the loader `diacode init` writes, and overridden by the environment for one run:
37
- * `server` (DCURSED_URL), the plan server; `agent` (DCURSED_AGENT), the name the MCP door uses, so a
37
+ * `server` (DIACODE_URL), the plan server; `agent` (DIACODE_AGENT), the name the MCP door uses, so a
38
38
  * step this agent starts through a tool and one the plugin observes belong to the same actor;
39
- * `plan`, to follow one plan; `wake` (DCURSED_WAKE=0 turns it off), whether what you do in the editor
39
+ * `plan`, to follow one plan; `wake` (DIACODE_WAKE=0 turns it off), whether what you do in the editor
40
40
  * may start a turn.
41
41
  * @type {import('@opencode-ai/plugin').Plugin}
42
42
  */
43
43
  export const DiaCode = async ({ directory, worktree, client }, options = {}) => {
44
- const server = String(process.env.DCURSED_URL ?? options.server ?? 'http://127.0.0.1:7300').replace(/\/$/, '');
45
- const agent = `opencode:${String(process.env.DCURSED_AGENT ?? options.agent ?? 'build')}`;
44
+ const server = String(process.env.DIACODE_URL ?? options.server ?? 'http://127.0.0.1:7300').replace(/\/$/, '');
45
+ const agent = `opencode:${String(process.env.DIACODE_AGENT ?? options.agent ?? 'build')}`;
46
46
  const only = typeof options.plan === 'string' ? options.plan : undefined;
47
47
  const root = worktree && worktree !== '/' ? worktree : directory;
48
48
 
49
- /** DCURSED_DEBUG=<file> makes the plugin say what it does there: how to tell it is loaded and what it saw. @param {string} line */
49
+ /** DIACODE_DEBUG=<file> makes the plugin say what it does there: how to tell it is loaded and what it saw. @param {string} line */
50
50
  const debug = (line) => {
51
- const file = process.env.DCURSED_DEBUG;
51
+ const file = process.env.DIACODE_DEBUG;
52
52
  if (file) { try { appendFileSync(file, `${new Date().toISOString()} ${line}\n`); } catch { /* not worth failing for */ } }
53
53
  };
54
54
  debug(`loaded: ${agent} -> ${server}, repository ${root}`);
@@ -68,7 +68,7 @@ export const DiaCode = async ({ directory, worktree, client }, options = {}) =>
68
68
  try {
69
69
  const res = await fetch(server + path, {
70
70
  ...init,
71
- headers: { 'x-dcursed-agent': agent, ...(init.body ? { 'content-type': 'application/json' } : {}) },
71
+ headers: { 'x-diacode-agent': agent, ...(init.body ? { 'content-type': 'application/json' } : {}) },
72
72
  signal: AbortSignal.timeout(TIMEOUT_MS),
73
73
  });
74
74
  return { status: res.status, text: await res.text(), headers: res.headers };
@@ -81,8 +81,8 @@ export const DiaCode = async ({ directory, worktree, client }, options = {}) =>
81
81
  async function brief(byName = only) {
82
82
  const res = await call(`/api/brief${byName ? `?plan=${encodeURIComponent(byName)}` : ''}`);
83
83
  if (!res || res.status !== 200 || !res.text) return null;
84
- const plan = res.headers.get('x-dcursed-plan');
85
- const rev = Number(res.headers.get('x-dcursed-rev'));
84
+ const plan = res.headers.get('x-diacode-plan');
85
+ const rev = Number(res.headers.get('x-diacode-rev'));
86
86
  return { text: res.text, plan: plan ?? undefined, rev: Number.isInteger(rev) ? rev : 0 };
87
87
  }
88
88
 
@@ -175,7 +175,7 @@ export const DiaCode = async ({ directory, worktree, client }, options = {}) =>
175
175
 
176
176
  // ── calls: what you did in the editor that this agent should act on now ──────────────────────
177
177
  const stopped = new AbortController();
178
- const wakeOn = options.wake !== false && process.env.DCURSED_WAKE !== '0' && Boolean(client)
178
+ const wakeOn = options.wake !== false && process.env.DIACODE_WAKE !== '0' && Boolean(client)
179
179
  // `opencode run` is one turn and then exits: there is no session to come back to.
180
180
  && !process.argv.slice(1).includes('run');
181
181
  const hold = Number(options.holdMs) > 0 ? Number(options.holdMs) : HOLD_MS;
@@ -248,7 +248,7 @@ export const DiaCode = async ({ directory, worktree, client }, options = {}) =>
248
248
  try {
249
249
  res = await fetch(`${server}/api/agent/wait?hold=${hold}`, {
250
250
  method: 'POST',
251
- headers: { 'x-dcursed-agent': agent, 'content-type': 'application/json' },
251
+ headers: { 'x-diacode-agent': agent, 'content-type': 'application/json' },
252
252
  body: JSON.stringify({ plans: [...new Set([...sessions.values()].map((s) => s.plan))] }),
253
253
  signal: AbortSignal.any([stopped.signal, AbortSignal.timeout(hold + 10_000)]),
254
254
  });
@@ -266,7 +266,7 @@ export const DiaCode = async ({ directory, worktree, client }, options = {}) =>
266
266
  return {
267
267
  dispose: async () => { stopped.abort(); if (beat) clearInterval(beat); beat = undefined; },
268
268
 
269
- // What OpenCode says about its sessions. (Logged with DCURSED_DEBUG, to learn what arrives.)
269
+ // What OpenCode says about its sessions. (Logged with DIACODE_DEBUG, to learn what arrives.)
270
270
  event: quietly(async ({ event }) => {
271
271
  const e = /** @type {any} */ (event);
272
272
  const sid = e.properties?.sessionID;
@@ -311,12 +311,12 @@ export const DiaCode = async ({ directory, worktree, client }, options = {}) =>
311
311
  }),
312
312
 
313
313
  'tool.execute.after': quietly(async (input, output) => {
314
- // A dcursed tool names the plan it is about: that is the plan this session is on, whatever
314
+ // A diacode tool names the plan it is about: that is the plan this session is on, whatever
315
315
  // else the repository holds.
316
316
  lastAt.set(input.sessionID, Date.now());
317
317
  // Its reply ends with the plan's id, which plan_create only learns when it is made.
318
- const footer = input.tool.startsWith('dcursed_') ? FOOTER.exec(String(output.output ?? '')) : null;
319
- const named = input.tool.startsWith('dcursed_') ? (typeof input.args?.plan === 'string' ? input.args.plan : footer?.[1]) : undefined;
318
+ const footer = input.tool.startsWith('diacode_') ? FOOTER.exec(String(output.output ?? '')) : null;
319
+ const named = input.tool.startsWith('diacode_') ? (typeof input.args?.plan === 'string' ? input.args.plan : footer?.[1]) : undefined;
320
320
  if (named && sessions.get(input.sessionID)?.plan !== named) {
321
321
  const b = await brief(named);
322
322
  sessions.set(input.sessionID, { plan: named, rev: b?.rev ?? 0 });
@@ -331,8 +331,8 @@ export const DiaCode = async ({ directory, worktree, client }, options = {}) =>
331
331
  if (note) notes.push(note);
332
332
  }
333
333
  const { lines, attention } = await changes(s);
334
- // The dcursed tools say what changed at the end of their own replies.
335
- if (!input.tool.startsWith('dcursed_')) {
334
+ // The diacode tools say what changed at the end of their own replies.
335
+ if (!input.tool.startsWith('diacode_')) {
336
336
  if (attention.length) notes.unshift(`HEADS UP, about your steps:\n${attention.map((a) => `- ${a}`).join('\n')}`);
337
337
  if (lines.length) {
338
338
  notes.push(`The plan changed since you last looked (the person, or another agent):\n${lines.map((l) => `- ${l}`).join('\n')}\nRead plan_read before your next step if this touches your work.`);