diacode 0.2.0 → 0.2.2

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,153 @@
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 Pt=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,Ft=/^(you|[a-z0-9][a-z0-9-]*:\S{1,80})$/,R=e=>typeof e=="string"&&Pt.test(e),It=e=>typeof e=="string"&&Ft.test(e),Bt=e=>String(e).normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,56).replace(/-+$/,"")||"step";function pt(e,t){const n=t instanceof Set?i=>t.has(i):i=>i in t,s=Bt(e);if(!n(s))return s;for(let i=2;;i++)if(!n(`${s}-${i}`))return`${s}-${i}`}const Wt=(e,t)=>e.edges.filter(n=>n.to===t).map(n=>n.from),$t=(e,t,n=!1)=>e.edges.filter(s=>s.from===t&&!(n&&s.kind==="after")).map(s=>s.to);function Ht(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 $t(e,a,n))r===t||s.has(r)||(s.set(r,o),l.push(r));i=l}return s}const Ns=(e,t,n)=>t===n||Ht(e,t).has(n);function gt(e,t){return!e?.length||!t?.length?!1:e.some(n=>t.some(s=>n===s||Je(n,s)||Je(s,n)))}function Ut(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 Je(e,t){if(!/[*?]/.test(e))return!1;const n=Ut(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 Ve=["not_started","in_progress","waiting","done","failed","cancelled"],Xe=["planning","approved","executing","paused","done","abandoned"],Kt=["task","context"],Ze=["needs","after","approve","ask","input"],Ls=new Set(["approve","ask","input"]),F=(e,t=0,n=1/0)=>typeof e=="string"&&e.length>=t&&e.length<=n,oe=64,Pe=256,Y=4e3,ne=2e3,Fe=e=>Array.isArray(e)&&e.length<=oe&&e.every(t=>F(t,1,Pe)),zt=`files is a list of paths or globs (at most ${oe}, each 1-${Pe} characters)`,mt=64,Yt=e=>Array.isArray(e)&&e.length<=mt&&e.every(t=>R(t)),Gt=`touches is a list of box ids from the architecture (at most ${mt})`,Jt=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function Vt(e,t,n,s){for(const i of Object.keys(e))t.includes(i)||s.push(`${n}: unknown field "${i}"`)}const Xt={"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"],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"],ids:["from","to"],oneOf:["label","kind"]},"gate.pass":{required:["from","to"],optional:["answer"],ids:["from","to"]},"gate.ask":{required:["from","to","question"],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"]}},Ds=new Set(["node.add","node.set","node.remove","edge.add","edge.remove","edge.rewire","edge.reverse","edge.set","group.rename"]);function Ps(e){if(!Jt(e)||typeof e.op!="string")return['an op is an object with an "op" name'];const t=Xt[e.op];if(!t)return[`"${e.op}" is not an op`];const n=[],s=["op",...t.required??[],...t.optional??[]];Vt(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&&!R(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,Y)&&n.push(`${e.op}: detail is text of at most ${Y} characters`),e.kind!==void 0&&(e.op.startsWith("edge.")?Ze.includes(e.kind)||n.push(`${e.op}: kind is one of ${Ze.join(", ")}`):Kt.includes(e.kind)||n.push(`${e.op}: kind is task or context`)),e.question!==void 0&&!F(e.question,1,ne)&&n.push(`${e.op}: question is 1-${ne} characters`),e.answer!==void 0&&!F(e.answer,0,ne)&&n.push(`${e.op}: answer is at most ${ne} characters`),e.files!==void 0&&!Fe(e.files)&&n.push(`${e.op}: ${zt}`),e.touches!==void 0&&!Yt(e.touches)&&n.push(`${e.op}: ${Gt}`),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(R))&&n.push(`${e.op}: after is a list of step ids`),e.op==="status.set"&&!Ve.includes(e.status)&&n.push(`status.set: "${e.status}" is not a status (${Ve.join(", ")})`),e.note!==void 0&&!F(e.note,0,ne)&&n.push(`${e.op}: note is at most ${ne} 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&&!Xe.includes(e.phase)&&n.push(`plan.set: phase is one of ${Xe.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(R))&&n.push("review: ids is a non-empty list of step ids"),n}const Qe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ae=e=>`${e.from}\0${e.to}`,le=e=>e.kind??"needs";function je(e,t){const n=(e.label??"")!==(t.label??"")?t.label??"":void 0,s=le(e)!==le(t)?le(t):void 0;return n===void 0&&s===void 0?null:se({op:"edge.set",from:t.from,to:t.to,label:n,kind:s})}function Zt(e,t,{bridge:n=!1}={}){const s=[],i=[],o={};for(const d of["title","goal","phase"])e[d]!==t[d]&&t[d]!==void 0&&(o[d]=t[d]);Object.keys(o).length&&s.push({op:"plan.set",...o}),t.rev!==e.rev&&i.push("rev (the server counts revisions)"),Qe(e.proposals??[],t.proposals??[])||i.push("proposals (accept or reject them instead)");const l=Object.keys(t.nodes).filter(d=>!(d in e.nodes)),a=Object.keys(e.nodes).filter(d=>!(d in t.nodes)),r=Object.keys(t.nodes).filter(d=>d in e.nodes);for(const d of l){const c=t.nodes[d];s.push(se({op:"node.add",id:d,label:c.label,kind:c.kind,detail:c.detail,group:c.group,files:c.files,touches:c.touches}))}for(const d of r){const c=e.nodes[d],$=t.nodes[d],m={};for(const S of["label","kind","detail","files","touches"])!Qe(c[S],$[S])&&$[S]!==void 0&&(m[S]=$[S]);c.kind==="context"&&$.kind===void 0&&(m.kind="task"),c.detail!==void 0&&$.detail===void 0&&(m.detail=""),c.files!==void 0&&$.files===void 0&&(m.files=[]),c.touches!==void 0&&$.touches===void 0&&(m.touches=[]),c.group!==$.group&&(m.group=$.group??null),Object.keys(m).length&&s.push({op:"node.set",id:d,...m})}const u=new Map(e.edges.map(d=>[Ae(d),d])),f=new Map(t.edges.map(d=>[Ae(d),d])),g=[...u].filter(([d,c])=>!f.has(d)&&c.from in t.nodes&&c.to in t.nodes).map(([,d])=>d),h=[...f].filter(([d])=>!u.has(d)).map(([,d])=>d);for(const d of[...g]){const c=h.find(m=>m.from===d.to&&m.to===d.from);if(!c)continue;s.push({op:"edge.reverse",from:d.from,to:d.to});const $=je(d,c);$&&s.push($),g.splice(g.indexOf(d),1),h.splice(h.indexOf(c),1)}for(const d of[...g]){const c=h.find(m=>m.from===d.from||m.to===d.to);if(!c)continue;s.push(se({op:"edge.rewire",from:d.from,to:d.to,newFrom:c.from!==d.from?c.from:void 0,newTo:c.to!==d.to?c.to:void 0}));const $=je(d,c);$&&s.push($),g.splice(g.indexOf(d),1),h.splice(h.indexOf(c),1)}for(const d of g)s.push({op:"edge.remove",from:d.from,to:d.to});for(const d of a)s.push({op:"node.remove",id:d});if(n&&a.length){const d=new Set(a),c=(m,S)=>e.edges.filter(O=>O.to===m).flatMap(O=>d.has(O.from)?S.has(O.from)?[]:(S.add(O.from),c(O.from,S)):[O.from]),$=new Set;for(const m of e.edges)if(!(!d.has(m.from)||d.has(m.to)||!(m.to in t.nodes)||t.nodes[m.to].status==="done"))for(const S of c(m.from,new Set([m.from]))){const O=Ae({from:S,to:m.to});S===m.to||!(S in t.nodes)||f.has(O)||$.has(O)||($.add(O),s.push({op:"edge.add",from:S,to:m.to}))}}for(const d of h)s.push(se({op:"edge.add",from:d.from,to:d.to,label:d.label,kind:d.kind}));for(const[d,c]of f){const $=u.get(d),m=$&&je($,c);m&&s.push(m)}for(const d of[...r,...l]){const c=e.nodes[d]??{},$=t.nodes[d];if($.kind==="context")continue;const m=c.status??"not_started",S=$.status??"not_started";(m!==S||(c.note??"")!==($.note??""))&&s.push(se({op:"status.set",id:d,status:S,note:$.note})),(c.statusFrom!==$.statusFrom||c.statusBy!==$.statusBy)&&m===S&&i.push(`${d}: statusFrom/statusBy (the server stamps them)`),c.owner!==$.owner&&($.owner===void 0?s.push({op:"release",id:d}):i.push(`${d}: owner (a step is owned by claiming it)`))}for(const[d,c]of f){const $=u.get(d)??{from:c.from,to:c.to},m=le($)!==le(c);c.question!==void 0&&(m||c.question!==$.question)&&!c.passed&&s.push({op:"gate.ask",from:c.from,to:c.to,question:c.question}),c.passed&&(m||!$.passed)?s.push(se({op:"gate.pass",from:c.from,to:c.to,answer:c.answer})):!c.passed&&$.passed&&!m&&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 se(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}const N=(e,t=120)=>{const n=String(e).replace(/\s+/g," ").trim();return`"${n.length>t?`${n.slice(0,t-1)}…`:n}"`},Qt={not_started:"not started",in_progress:"in progress",waiting:"waiting for you",done:"done",failed:"failed",cancelled:"cancelled"},en=e=>Qt[e]??e,et={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 tn(e){switch(e.op){case"node.add":return`add step ${e.id??""}${e.id?" ":""}${N(e.label)}${e.kind==="context"?" (context)":""}${e.group?` in ${N(e.group)}`:""}${e.after?.length?`, after ${e.after.join(", ")}`:""}`;case"node.set":{const t=[];return e.label!==void 0&&t.push(`label → ${N(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 → ${N(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"?`, ${et[e.kind]}`:""}${e.label?` (${N(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":et[e.kind]),e.label!==void 0&&t.push(`label ${N(e.label,40)}`),`arrow ${e.from} → ${e.to}: ${t.join("; ")}`}case"gate.pass":return`the checkpoint ${e.from} → ${e.to} is passed${e.answer?`: ${N(e.answer,300)}`:""}; ${e.to} may start`;case"gate.ask":return`asked the person before ${e.to}: ${N(e.question,300)}`;case"gate.reject":return`${e.from} was sent back, not approved${e.reason?` (${N(e.reason,300)})`:""}: it is to be done again`;case"status.set":return`${e.id} is ${en(e.status)}${e.note?` (${N(e.note,160)})`:""}`;case"claim":return`take ${e.id}`;case"release":return`let go of ${e.id}`;case"group.rename":return`rename group ${N(e.from)} to ${N(e.to)}`;case"plan.set":{const t=[];return e.title!==void 0&&t.push(`title → ${N(e.title)}`),e.goal!==void 0&&t.push(`goal → ${N(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?` (${N(e.reason,160)})`:""}`;case"review":return`${e.ids.join(", ")} reviewed: no change needed`;default:return String(e.op)}}const nn=[/^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*$/],pe=[["(((",")))"],["((","))"],["([","])"],["[[","]]"],["[(",")]"],["[/","/]"],["[/","\\]"],["[\\","\\]"],["[\\","/]"],["{{","}}"],["(",")"],["[","]"],["{","}"],[">","]"]],sn=/^(<?)(-{2,}|={2,}|-\.+-|~{3,})([>ox]?)/,on=/^(--|==|-\.)\s+([^|]+?)\s+(-{2,}>|={2,}>|\.-+>|-{3,}|={3,}|\.-+)/,an=/^[\p{L}\p{N}_]+(?:-[\p{L}\p{N}_]+)*/u,de=e=>e.replace(/#quot;/g,'"').replace(/#amp;/g,"&").replace(/#lt;/g,"<").replace(/#gt;/g,">").replace(/#(\d+);/g,(t,n)=>String.fromCodePoint(Number(n)));function wt(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 u=`line ${r+1}`;for(const f of rn(a.replace(/%%.*$/,""))){const g=f.trim();if(!g)continue;if(!o){const c=/^(flowchart|graph)(?:\s+(LR|RL|TD|TB|BT))?\s*$/.exec(g);if(!c)throw new Error(`${u}: a plan diagram starts with "flowchart" or "graph", not "${g.slice(0,30)}"`);n.direction=c[2]==="LR"||c[2]==="RL"?"LR":"TD",o=!0;continue}if(g==="end"){if(!s.length)throw new Error(`${u}: "end" with no subgraph open`);s.pop(),i.pop();continue}const h=/^subgraph\s+(.+)$/.exec(g);if(h){if(s.push(ln(h[1])),n.subgraphs){const c=/^([\p{L}\p{N}_-]+)\s*(?:\[|$)/u.exec(h[1])?.[1];i.push(n.subgraphs.push({...c?{id:c}:{},title:s.at(-1),...i.length?{parent:i.at(-1)}:{}})-1)}continue}const d=t?/^class\s+([\p{L}\p{N}_,\-\s]+?)\s+([\w-]+)\s*$/u.exec(g):null;if(d){for(const c of d[1].split(",").map($=>$.trim()).filter(Boolean)){const $=n.nodes.get(c);$&&($.cls=d[2])}continue}nn.some(c=>c.test(g))||dn(g,u,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 rn(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 ln(e){const t=/^[\p{L}\p{N}_-]+\s*\[\s*"?(.*?)"?\s*\]\s*$/u.exec(e);if(t)return de(t[1]);const n=/^"(.*)"$/.exec(e.trim());return n?de(n[1]):e.trim()}function dn(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 h=an.exec(l());if(!h)throw new Error(`${t}: expected a node id at "${l().slice(0,30)}"`);const d=h[0];o+=d.length;let c,$;const m=pe.find(([E])=>l().startsWith(E));if(m){o+=m[0].length;const E=l();if(E.startsWith('"')){const T=E.indexOf('"',1);if(T<0)throw new Error(`${t}: an unclosed quote in ${d}'s label`);c=E.slice(1,T),o+=T+1,a();const x=pe.find(([A,M])=>A===m[0]&&l().startsWith(M))??pe.find(([,A])=>l().startsWith(A));if(!x)throw new Error(`${t}: ${d}'s label is not closed`);o+=x[1].length}else{const T=pe.filter(([A])=>A===m[0]).map(([,A])=>A),x=Math.min(...T.map(A=>E.indexOf(A)).filter(A=>A>=0));if(!Number.isFinite(x))throw new Error(`${t}: ${d}'s label is not closed`);c=E.slice(0,x).trim(),o+=x+(T.find(A=>E.startsWith(A,x))??T[0]).length}$=de(c).replace(/^`|`$/g,"").trim(),c=$.replace(/<br\s*\/?>/gi," ").trim()}const S=/^:::([\w-]+)/.exec(l());S&&(o+=S[0].length);const O=s.nodes.get(d),q=i!==void 0?{...m?{shape:m[0]}:{},...$?{raw:$}:{},...S?{cls:S[1]}:{}}:{};return O?(c&&(O.label=c),Object.assign(O,q)):s.nodes.set(d,{label:c||d,...n?{group:n}:{},...i!==void 0&&i>=0?{frame:i}:{},...q}),d},u=()=>{const h=[r()];for(a();l().startsWith("&");)o++,h.push(r()),a();return h},f=()=>{a();const h=on.exec(l());if(h)return o+=h[0].length,{...nt(h[1],de(h[2].trim())),twoWay:!1};const d=sn.exec(l());if(!d)return null;o+=d[0].length,a();let c;const $=/^\|([^|]*)\|/.exec(l());return $&&(o+=$[0].length,c=de($[1].trim().replace(/^"(.*)"$/,"$1"))),{...nt(d[2],c),twoWay:d[1]==="<"}};let g=u();for(;;){const h=f();if(!h)break;const d=u();for(const c of g)for(const $ of d)s.edges.push({from:c,to:$,...h.kind?{kind:h.kind}:{},...h.label?{label:h.label}:{}}),h.twoWay&&s.warnings.push(`${t}: ${c} <--> ${$} points both ways; kept as ${c} → ${$}`);g=d}if(a(),o<e.length)throw new Error(`${t}: could not read "${l().slice(0,40)}"`)}function cn(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 un=/^(unchanged|existing|untouched|context)\b/i;function fn(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&&un.test(l.group)?{kind:"context"}:{}});const s=new Map,i=(o,l)=>{const a=new Set([o]),r=[o];for(;r.length;){const u=r.pop();if(u===l)return!0;for(const f of s.get(u)??[])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 hn=/[^A-Za-z0-9 _.\-/]/,tt=e=>hn.test(e)?`["${e.replace(/"/g,"#quot;")}"]`:`[${e}]`,pn=(e,t)=>{const n=String(e??"").trim(),s=t==="approve"||t==="ask"||t==="input",i=s?n?`${t}: ${n}`:t:n,o=t==="after"?"-.->":s?"==>":"-->";return i?`${o}|"${i.replace(/"/g,"#quot;")}"|`:o},$n=/^(approve|ask|input)\s*(?::\s*([\s\S]*))?$/i;function nt(e,t){if(e.startsWith("-."))return{kind:"after",...t?{label:t}:{}};const n=e.startsWith("==")&&t?$n.exec(t):null;return n?{kind:n[1].toLowerCase(),...n[2]?.trim()?{label:n[2].trim()}:{}}:t?{label:t}:{}}const gn=(e,t)=>e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")||`group${t}`;function Fs(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}${tt(e.nodes[r].label)}`);return}n.push(` subgraph ${gn(o,l)} ["${o.replace(/"/g,"#quot;")}"]`);for(const r of a)n.push(` ${r}${tt(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} ${pn(o.label,o.kind)} ${o.to}`);return n.join(`
5
+ `)}function mn(e,t=""){const n=/\.(md|markdown)$/i.test(t)||/```mermaid/.test(e);let s=e,i,o,l="mermaid";if(n){const g=cn(e);if(!g.mermaid)throw new Error("there is no ```mermaid block in this file");({mermaid:s,title:i,goal:o}=g),l=/\.plan\.md$/i.test(t)||g.title?"cursor-plan":"markdown"}const a=wt(s),{ops:r,warnings:u}=fn(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:u}}const Re=["service","group"],X=(e,t)=>Object.keys(e.nodes).filter(n=>e.nodes[n].in===t),ce=(e,t)=>Object.values(e.nodes).some(n=>n.in===t);function wn(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 bt(e,t){const n=[],s=[t];for(;s.length;)for(const i of X(e,s.pop()))i===t||n.includes(i)||(n.push(i),s.push(i));return n}function bn(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 yn=(e,t)=>e.edges.filter(n=>n.to===t).map(n=>n.from);function Is(e,t,n){const s=n instanceof Set?n:new Set(n);return wn(e,t).reverse().find(o=>s.has(o))??t}const qe="dcursed.arch/0",me=["person","service","component","store","queue","group"],we=["draft","accepted"],st=["dcursed","mermaid","c4","markdown","cursor-plan"],Z=120,ot=40,be=60,_=(e,t=0,n=1/0)=>typeof e=="string"&&e.length>=t&&e.length<=n,B=e=>e!=null&&typeof e=="object"&&!Array.isArray(e),yt=`files is a list of paths or globs (at most ${oe}, each 1-${Pe} characters)`;function K(e,t,n,s){for(const i of Object.keys(e))t.includes(i)||s.push(`${n}: unknown field "${i}"`)}const kn=["label","kind","external","in","tech","detail","files","planned","retiring"],xn=["from","to","label","tech","async","via","planned","retiring"];function vn(e,t,n){const s=`box ${t}`;if(!B(e)){n.push(`${s}: not an object`);return}K(e,kn,s,n),_(e.label,1,120)||n.push(`${s}: needs a label of 1-120 characters`),me.includes(e.kind)||n.push(`${s}: kind is one of ${me.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&&!R(e.in)&&n.push(`${s}: in is the id of the service or group it sits in`),e.tech!==void 0&&!_(e.tech,1,Z)&&n.push(`${s}: tech is 1-${Z} characters`),e.detail!==void 0&&!_(e.detail,0,Y)&&n.push(`${s}: detail is text of at most ${Y} characters`),e.files!==void 0&&!Fe(e.files)&&n.push(`${s}: ${yt}`),e.planned!==void 0&&!R(e.planned)&&n.push(`${s}: planned is the id of the plan that adds it`),e.retiring!==void 0&&!R(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 Sn(e,t,n,s){if(!B(e)){s.push(`${t}: not an object`);return}K(e,["from","to","label"],t,s),e.label!==void 0&&!_(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 An(e){const t=[];if(!B(e))return["an architecture is a JSON object"];if(K(e,["schema","title","goal","rev","phase","source","nodes","edges","flows","proposals"],"architecture",t),e.schema!==qe&&t.push(`architecture: schema is "${qe}"`),_(e.title,1,200)||t.push("architecture: needs a title of 1-200 characters"),e.goal!==void 0&&!_(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"),we.includes(e.phase)||t.push(`architecture: phase is one of ${we.join(", ")}`),e.source!==void 0&&(!B(e.source)||!st.includes(e.source.kind)?t.push(`architecture: source.kind is one of ${st.join(", ")}`):K(e.source,["kind","url","path","importedAt"],"architecture.source",t)),!B(e.nodes))return[...t,"architecture: nodes is an object keyed by box id"];for(const[o,l]of Object.entries(e.nodes))R(o)||t.push(`box "${o}": not a valid id`),vn(l,o,t);const n=e.nodes;for(const[o,l]of Object.entries(n)){if(!B(l)||l.in===void 0||!R(l.in))continue;const a=n[l.in];a?Re.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=bn(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(!B(o)){t.push(`${a}: not an object`);return}K(o,xn,a,t),o.label!==void 0&&!_(o.label,0,120)&&t.push(`${a}: label is at most 120 characters`),o.tech!==void 0&&!_(o.tech,1,Z)&&t.push(`${a}: tech is 1-${Z} 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&&!R(o.planned)&&t.push(`${a}: planned is the id of the plan that adds it`),o.retiring!==void 0&&!R(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 u of[o.from,o.to])u in n&&(n[u].kind==="group"?t.push(`${a}: ${u} is a group, a frame round other boxes; it takes no arrows`):ce(e,u)&&t.push(`${a}: ${u} 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>ot&&t.push(`architecture: at most ${ot} flows`);const i=new Set;return e.flows.forEach((o,l)=>{const a=`flow ${o?.id??l+1}`;if(!B(o)){t.push(`${a}: not an object`);return}K(o,["id","title","steps"],a,t),R(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),_(o.title,1,120)||t.push(`${a}: needs a title of 1-120 characters`),!Array.isArray(o.steps)||!o.steps.length||o.steps.length>be?t.push(`${a}: steps is a list of 1-${be} steps`):o.steps.forEach((r,u)=>Sn(r,`${a}, step ${u+1}`,n,t))}),e.proposals!==void 0&&(Array.isArray(e.proposals)?e.proposals.forEach((o,l)=>{const a=`proposal ${o?.id??l+1}`;if(!B(o)){t.push(`${a}: not an object`);return}K(o,["id","by","at","reason","ops"],a,t),_(o.id,1,64)||t.push(`${a}: needs an id`),It(o.by)||t.push(`${a}: by is not an actor`),o.reason!==void 0&&!_(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,u)=>t.push(...kt(r).map(f=>`${a}, op ${u+1}: ${f}`)))}):t.push("architecture: proposals is a list")),t}const jn={"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"]}},On=new Set(["box.add","box.set","box.remove","arrow.add","arrow.remove","arrow.rewire","arrow.reverse","arrow.set","flow.add","flow.set","flow.remove"]),Tn={"box.set":["in","planned","retiring"],"arrow.set":["via","planned","retiring"]};function kt(e){if(!B(e)||typeof e.op!="string")return['an op is an object with an "op" name'];const t=jn[e.op];if(!t)return[`"${e.op}" is not an op`];const n=[],s=["op",...t.required??[],...t.optional??[]];K(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=Tn[e.op]??[];for(const l of t.ids??[])e[l]!==void 0&&!(e[l]===null&&i.includes(l))&&!R(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&&!_(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&&!_(e.tech,0,Z)&&n.push(`${e.op}: tech is at most ${Z} characters`),e.detail!==void 0&&!_(e.detail,0,Y)&&n.push(`${e.op}: detail is text of at most ${Y} characters`),e.kind!==void 0&&!me.includes(e.kind)&&n.push(`${e.op}: kind is one of ${me.join(", ")}`),e.files!==void 0&&!Fe(e.files)&&n.push(`${e.op}: ${yt}`),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&&!R(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&&!_(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&&!_(e.goal)&&n.push("arch.set: goal is text"),e.phase!==void 0&&!we.includes(e.phase)&&n.push(`arch.set: phase is one of ${we.join(", ")}`),e.steps!==void 0&&(!Array.isArray(e.steps)||!e.steps.length||e.steps.length>be?n.push(`${e.op}: steps is a list of 1-${be} steps`):e.steps.forEach((l,a)=>{if(!B(l)){n.push(`${e.op}: step ${a+1} is not an object`);return}K(l,["from","to","label"],`${e.op}: step ${a+1}`,n),(!R(l.from)||!R(l.to))&&n.push(`${e.op}: step ${a+1} needs from and to, box ids`),l.label!==void 0&&!_(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")&&!_(e.id,1,64)&&n.push(`${e.op}: needs a proposal id`),e.reason!==void 0&&!_(e.reason,0,1e3)&&n.push(`${e.op}: reason is at most 1000 characters`),n}class Ie extends Error{}const j=e=>{throw new Ie(e)},Oe=e=>On.has(e.op)||e.op==="arch.set"&&(e.title!==void 0||e.goal!==void 0);function at(e,t,n){for(let i=0;i<t.length;i++){const o=kt(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(Oe)){const i=t.filter(Oe),o=t.filter(f=>!Oe(f)),l=Te(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 u=Te({...r,rev:e.rev},o,n);return u.kind==="rejected"?{...u,index:t.indexOf(o[u.index])}:{...u,proposal:a}}return Te(e,t,n)}function Te(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(xt(s,t[a],i));const r=An(s);r.length&&j(r[0])}catch(r){if(r instanceof Ie)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 J=(e,t)=>e.nodes[t]??j(`there is no box ${t}`);function z(e,t,n){n!==void 0&&(n===""||n===null?delete e[t]:e[t]=n)}function xt(e,t,n){const{you:s}=n,i=(a,r)=>{const u=n.impact.get(a);u?u.add(r):n.impact.set(a,new Set([r]))},o=(a,r)=>{for(const u of yn(e,a))i(u,`${a} ${r}`)},l=(a,r)=>{const u=J(e,r);Re.includes(u.kind)||j(`${r} is a ${u.kind}; only a service or a group holds other boxes`),(r===a||bt(e,a).includes(r))&&j(`${a} cannot sit inside ${r}: that would put it inside itself`),e.edges.some(f=>f.from===r||f.to===r)&&j(`${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??pt(t.label,e.nodes);e.nodes[a]&&j(`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),z(r,"tech",t.tech),z(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=J(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=X(e,t.id);f.length&&!Re.includes(t.kind)&&j(`${t.id} has ${f.join(", ")} inside it: take them out before it becomes a ${t.kind}`),t.kind==="group"&&e.edges.some(g=>g.from===t.id||g.to===t.id)&&j(`${t.id} has arrows, and a group is a frame round other boxes, which takes none`),a.kind==="queue"&&e.edges.some(g=>g.via===t.id)&&j(`${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),z(a,"tech",t.tech),z(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&&j(`${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&&j(`${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=J(e,t.id);o(t.id,"was removed");for(const r of X(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(u=>u.from!==t.id&&u.to!==t.id);return e.flows=e.flows.filter(r=>r.steps.length),t}case"arrow.add":return Mn(e,t),t;case"arrow.remove":{const a=Me(e,t.from,t.to);return e.edges.splice(e.edges.indexOf(a),1),t}case"arrow.rewire":case"arrow.reverse":{const a=Me(e,t.from,t.to),r=t.op==="arrow.reverse"?a.to:t.newFrom??a.from,u=t.op==="arrow.reverse"?a.from:t.newTo??a.to;return vt(e,r,u,a),a.from=r,a.to=u,t}case"arrow.set":{const a=Me(e,t.from,t.to);return z(a,"label",t.label),z(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&&j(`${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&&j(`${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)&&j(`there is already a flow ${t.id}`),e.flows.push({id:t.id,title:t.title,steps:t.steps.map(it)}),t;case"flow.set":{const a=e.flows.find(r=>r.id===t.id)??j(`there is no flow ${t.id}`);return t.title!==void 0&&(a.title=t.title),t.steps!==void 0&&(a.steps=t.steps.map(it)),t}case"flow.remove":return e.flows.some(a=>a.id===t.id)||j(`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&&j("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||j("only you place a box: the layout is yours"),J(e,t.id),ce(e,t.id)&&j(`${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||j("only you fold a frame: the layout is yours"),J(e,t.id),t.folded&&!ce(e,t.id)&&j(`${t.id} has nothing inside it to fold`),n.folds.push({id:t.id,folded:t.folded}),t;case"proposal.accept":{s||j("only you accept a proposal");const a=(e.proposals??[]).find(r=>r.id===t.id)??j(`there is no proposal ${t.id}`);e.proposals=(e.proposals??[]).filter(r=>r!==a);for(const r of a.ops)try{xt(e,r,n)}catch(u){throw u instanceof Ie&&j(`proposal ${t.id} no longer applies: ${u.message}`),u}return t}case"proposal.reject":return s||j("only you reject a proposal"),(e.proposals??[]).some(a=>a.id===t.id)||j(`there is no proposal ${t.id}`),e.proposals=(e.proposals??[]).filter(a=>a.id!==t.id),t;default:return j(`"${t.op}" is not an op`)}}const it=e=>({from:e.from,to:e.to,...e.label?{label:e.label}:{}});function Me(e,t,n){return e.edges.find(s=>s.from===t&&s.to===n)??j(`there is no arrow ${t} → ${n}`)}function vt(e,t,n,s){const i=J(e,t),o=J(e,n);t===n&&j(`${t} cannot use itself`),e.edges.some(l=>l!==s&&l.from===t&&l.to===n)&&j(`${t} → ${n} is there already`);for(const[l,a]of[[t,i],[n,o]])a.kind==="group"&&j(`${l} is a group, a frame round other boxes; it takes no arrows`),ce(e,l)&&j(`${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 Mn(e,t){vt(e,t.from,t.to);const n={from:t.from,to:t.to};z(n,"label",t.label),z(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 En({title:e,goal:t,phase:n="accepted",source:s}){return{schema:qe,title:e,...t?{goal:t}:{},rev:0,phase:n,source:s??{kind:"dcursed"},nodes:{},edges:[],flows:[]}}const U=(e,t=120)=>{const n=String(e).replace(/\s+/g," ").trim();return`"${n.length>t?`${n.slice(0,t-1)}…`:n}"`};function xe(e){switch(e.op){case"box.add":return`add ${e.external?"external ":""}${e.kind} ${e.id??""}${e.id?" ":""}${U(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 → ${U(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?` (${U(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 ${U(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} ${U(e.title)} (${e.steps.length} step${e.steps.length===1?"":"s"})`;case"flow.set":return`change flow ${e.id}: ${[e.title!==void 0?`title → ${U(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 → ${U(e.title)}`),e.goal!==void 0&&t.push(`goal → ${U(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?` (${U(e.reason,160)})`:""}`;default:return String(e.op)}}function _n(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 rt=e=>`${e.from}\0${e.to}`;function Bs(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(rt(s)),(s.retiring===t.id||n.removed.has(s.from)||n.removed.has(s.to))&&n.removedArrows.add(rt(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&&gt(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 St(e,t,n){return t.added.has(n)?"new":t.removed.has(n)?"removed":t.changed.has(n)||ce(e,n)&&bt(e,n).some(s=>t.added.has(s)||t.removed.has(s)||t.changed.has(s))?"changed":"untouched"}function Cn(e,t){const n=(t.touches??[]).map(s=>({id:s,by:"hand"}));for(const[s,i]of Object.entries(e.nodes))i.files?.length&&gt(t.files,i.files)&&!n.some(o=>o.id===s)&&n.push({id:s,by:"files"});return n}const Rn={"(((":"person","((":"person","[(":"store","([":"queue",">":"queue","(":"service","{{":"service"},qn={person:["((","))"],service:["(",")"],component:["[","]"],store:["[(",")]"],queue:["([","])"],group:["[","]"]};function lt(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 Nn(e){const t=wt(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=pt(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:u}=lt(a.raw??a.label);n.boxes.set(l,{label:(r||l).slice(0,120),kind:a.shape&&Rn[a.shape]||"component",...a.cls==="external"?{external:!0}:{},...u?{tech:u.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:u}=lt(a??"");n.arrows.push({from:l.from,to:l.to,...r?{label:r.slice(0,120)}:{},...u?{tech:u.slice(0,120)}:{},...l.kind==="after"?{async:!0}:{}})}return n}const Ln=/^(Person|System|Container|Component)(Db|Queue)?(_Ext)?$/,Dn=/^(Boundary|Enterprise_Boundary|System_Boundary|Container_Boundary|Deployment_Node|Node|Node_L|Node_R)$/,Pn=/^(Rel|BiRel|Rel_[UDLR]|Rel_Back|Rel_Neighbor|Rel_Back_Neighbor|BiRel_[UDLR])$/,At=/^C4(Context|Container|Component|Dynamic|Deployment)\b/;function Fn(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 In(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(!At.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 u=/^([A-Za-z_]+)\s*\(([\s\S]*?)\)\s*(\{)?\s*$/.exec(a);if(!u){if(/^(UpdateElementStyle|UpdateRelStyle|UpdateLayoutConfig|UpdateBoundaryStyle|LAYOUT_|SHOW_|HIDE_)/.test(a))return;throw new Error(`${l}: could not read "${a.slice(0,40)}"`)}const[,f,g,h]=u,d=Fn(g);if(Pn.test(f)){const[te,p,v,W]=d;if(!te||!p)throw new Error(`${l}: ${f} needs two aliases`);f.startsWith("BiRel")&&t.warnings.push(`${l}: ${te} <--> ${p} points both ways; kept as ${te} → ${p}`),t.arrows.push({from:te,to:p,...v?{label:v.slice(0,120)}:{},...W?{tech:W.slice(0,120)}:{}});return}const c=n.at(-1),$=Dn.test(f),m=Ln.exec(f);if(!$&&!m){t.warnings.push(`${l}: ${f} is not drawn here, and was left out`);return}const[S,O,q,E]=d;if(!S||!O)throw new Error(`${l}: ${f} needs an alias and a label`);if($){t.boxes.set(S,{label:O.slice(0,120),kind:"group",...c?{in:c}:{}}),h&&n.push(S);return}const[,T,x,A]=m,M=T==="Container"||T==="Component",P=M?q:void 0,fe=M?E:q,ve=x==="Db"?"store":x==="Queue"?"queue":T==="Person"?"person":T==="Component"?"component":"service";t.boxes.set(S,{label:O.slice(0,120),kind:ve,...A?{external:!0}:{},...P?{tech:P.slice(0,120)}:{},...fe?{detail:fe.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 Bn(e){const t=[...e.warnings],n=[],s=[...e.boxes.keys()],i=new Set,o=r=>{if(i.has(r))return;i.add(r);const u=e.boxes.get(r);u.in&&e.boxes.has(u.in)&&o(u.in),n.push({op:"box.add",id:r,label:u.label,kind:u.kind,...u.external?{external:!0}:{},...u.tech?{tech:u.tech}:{},...u.detail?{detail:u.detail}:{},...u.in&&e.boxes.has(u.in)?{in:u.in}:{}})};for(const r of s)o(r);let l=En({title:"import",phase:"accepted"});const a=[];for(const r of n){const u=at(l,[r],{actor:"you",via:"file"});u.kind==="applied"?(l=u.arch,a.push(r)):u.kind==="rejected"&&t.push(`left out box ${r.id}: ${u.why}`)}for(const r of e.arrows){const u={op:"arrow.add",from:r.from,to:r.to,...r.label?{label:r.label}:{},...r.tech?{tech:r.tech}:{},...r.async?{async:!0}:{}},f=at(l,[u],{actor:"you",via:"file"});f.kind==="applied"?(l=f.arch,a.push(u)):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 Be=e=>`"${e.replace(/"/g,"#quot;")}"`,Wn=e=>Be(e.tech?`${e.label}<br/>[${e.tech}]`:e.label);function Hn(e){const t=e.tech?`${e.label??""}<br/>[${e.tech}]`:e.label??"",n=e.async?"-.->":"-->";return t?`${n}|${Be(t)}|`:n}function Ws(e,t="LR"){const n=[`flowchart ${t==="TD"?"TD":"LR"}`],s=e;let i=!1;const o=(r,u)=>{const f=e.nodes[r],[g,h]=qn[f.kind];f.external&&(i=!0),n.push(`${u}${r}${g}${Wn(f)}${h}${f.external?":::external":""}`)},l=(r,u)=>{n.push(`${u}subgraph ${r} [${Be(e.nodes[r].label)}]`);for(const f of X(s,r))a(f,`${u} `);n.push(`${u}end`)},a=(r,u)=>{X(s,r).length||e.nodes[r].kind==="group"?l(r,u):o(r,u)};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} ${Hn(r)} ${r.to}`);return i&&n.push(" classDef external fill:#eeeeee,stroke:#999999,color:#333333"),n.join(`
8
+ `)}function Un(e,t=""){let n=e;if(/\.(md|markdown)$/i.test(t)||/```mermaid/.test(e)){const u=/```mermaid\s*\n([\s\S]*?)```/.exec(e);if(!u)throw new Error("there is no ```mermaid block in this file");n=u[1]}const s=n.split(`
9
+ `).map(u=>u.replace(/%%.*$/,"").trim()).find(Boolean)??"",i=At.test(s),o=i?In(n):Nn(n),{ops:l,warnings:a}=Bn(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 ue="top level",Hs=e=>{const t=[];for(const n of e.steps)n.group&&!t.includes(n.group)&&t.push(n.group);return[...t.filter(n=>n!==ue),...t.filter(n=>n===ue)]},We={observed:"●",reported:"○",you:"◆"},Ne={observed:"seen editing its files",reported:"said by the agent",you:"set by you"},Kn={"claude-code":"Claude Code",cursor:"Cursor",antigravity:"Antigravity"},C=e=>{if(e.startsWith("opencode:"))return e.slice(9);if(e.startsWith("server:"))return"DiaCode";const t=e.indexOf(":"),n=t>0?Kn[e.slice(0,t)]:void 0;if(!n)return e;const s=e.slice(t+1);return s==="main"||s==="agent"?n:`${n} (${s})`};function He(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 zn(e,t){const n=He(e);return n?`${We[n.from]} ${C(n.who)}${t?` · ${t}`:""}`:""}const V={in_progress:"working",waiting:"waiting",done:"done",failed:"failed",cancelled:"cancelled"},jt=e=>`waits on ${e.slice(0,2).join(", ")}${e.length>2?` +${e.length-2}`:""}`,Yn=e=>`checkpoint after ${e.slice(0,2).join(", ")}${e.length>2?` +${e.length-2}`:""}`;function Us(e,{stalled:t,blockedOn:n,held:s}={}){const i=[];e&&e.kind!=="context"&&(V[e.status]?i.push(V[e.status]):e.status==="not_started"&&!n?.length&&!s?.length&&i.push("not started"),n?.length?i.push(jt(n)):s?.length&&i.push(Yn(s)));const o=zn(e,t);return o&&i.push(o),i.join(" · ")}const L={in_progress:"#2F6FB0",waiting:"#9A6700",done:"#2E7D32",failed:"#B3261E",cancelled:"#69625B"},Gn="#69625B",Ks={not_started:{colour:Gn,icon:"ring",word:"not started",edge:!1,strike:!1},in_progress:{colour:L.in_progress,icon:"half",word:V.in_progress,edge:!0,strike:!1},waiting:{colour:L.waiting,icon:"hourglass",word:V.waiting,edge:!0,strike:!1},done:{colour:L.done,icon:"check",word:V.done,edge:!0,strike:!1},failed:{colour:L.failed,icon:"cross",word:V.failed,edge:!0,strike:!1},cancelled:{colour:L.cancelled,icon:"slash",word:V.cancelled,edge:!0,strike:!0}},zs=["not_started","in_progress","waiting","done","failed","cancelled"],Le={new:{colour:L.done,icon:"plus",word:"new"},changed:{colour:L.waiting,icon:"pencil",word:"changed"},removed:{colour:L.failed,icon:"cross",word:"removed"}},dt={width:300,height:180};async function Q(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 ee(e){const t=await fetch(e),n=await Q(t);if(!t.ok)throw new Error(n.error??`${t.status}`);return n}const Ys=(e,t=12)=>ee(`/api/files?q=${encodeURIComponent(e)}&limit=${t}`);async function Gs(e){return e.length?(await ee(`/api/files?${e.map(t=>`check=${encodeURIComponent(t)}`).join("&")}`)).results:[]}async function Js(){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 Vs=async()=>(await ee("/api/plans")).plans,Xs=e=>ee(`/api/plans/${encodeURIComponent(e)}`);async function Jn(e){const t=await fetch("/api/plans",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await Q(t);if(!t.ok)throw new Error(n.error??`${t.status}`);return n}async function Vn(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 Q(i)}}async function Zs(e,t={}){const n=await fetch(`/api/plans/${encodeURIComponent(e)}/reconcile`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),s=await Q(n);if(!n.ok)throw new Error(s.error??`${n.status}`);return s.job}function Ue(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[u,f]of Object.entries(t))f&&s.addEventListener(u,g=>f(JSON.parse(g.data)))};return r(),()=>{o=!0,clearTimeout(i),s?.close()}}const Qs=(e,t)=>Ue(`/api/plans/${encodeURIComponent(e)}/events`,{change:t.change,problem:t.problem,reconcile:t.reconcile,presence:t.presence,call:t.call},t),eo=e=>Ue("/api/events",{plans:e.plans},{open:e.open,down:()=>{}}),to=()=>ee("/api/architecture"),no=()=>ee("/api/flow");async function so(e,t,n){const s=await fetch(`/api/permissions/${encodeURIComponent(e)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({decision:t,...n?{reason:n}:{}})});return{status:s.status,body:await Q(s)}}const oo=()=>ee("/api/presence").then(e=>e.agents??[]);async function Xn(e){const t=await fetch("/api/architecture",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await Q(t);if(!t.ok)throw new Error(n.error??`${t.status}`);return n}async function Zn(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 Q(s)}}const ao=e=>Ue("/api/architecture/events",{change:e.change,problem:e.problem,call:e.call},e);async function io(e){const t=Un(await e.text(),e.name);await Xn({title:t.title,source:t.source,direction:t.direction});const{status:n,body:s}=await Zn(0,t.ops,`imported from ${e.name}`);if(n!==200)throw new Error(s.why??s.error);return{warnings:t.warnings}}function ro(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+dt.width,height:s.height+dt.height},...Qn(e)}}function Qn({plan:e,layout:t}){return{steps:Object.entries(e.nodes).map(([n,s])=>({id:n,label:s.label,group:s.group??ue,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 lo(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!==ue?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(([,u])=>u!==void 0))});const{ops:i}=Zt(e.plan,n,{bridge:!0});for(const o of t.steps){const l=e.layout.nodes[o.id],a=Math.round(o.x),r=Math.round(o.y);(!l||Math.round(l.x)!==a||Math.round(l.y)!==r)&&i.push({op:"layout.place",id:o.id,x:a,y:r})}return i}async function co(e){const t=mn(await e.text(),e.name),n=await Jn({title:t.title,goal:t.goal,source:t.source,direction:t.direction}),{status:s,body:i}=await Vn(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 b=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]);function ye(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 es(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 uo(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 fo(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 ie="Carry out the plan with the dcursed tools, one step at a time: start a step, do it, mark it done. Stop and ask me if a step is unclear.",Ee="The architecture is approved. Draw the plan on it with plan_create (every step, what it waits for, the files it touches), then stop: do not start any step.",re="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.",ho=["planning","executing","done"],ge="Carry on with the plan with the dcursed tools: read it first, then take the next step.",De=e=>{const t=e.map(C);return t.length<2?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`};function po(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:re,line:n.length?`Look the plan over and change what is wrong, then approve it. ${De(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:ie,line:n.length?`The plan is approved. This starts it: ${De(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:ge,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 $o(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:ie};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:ie};case"expired":return{text:`Started. ${t} did not come back to take it: tell it to carry the plan out.`,kind:"info",copy:ie};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:ie};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:re};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:re};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:re};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:re};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:ge};case"none":return{text:"Resumed. No agent is listening for the editor: tell yours to carry on.",kind:"info",copy:ge};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:ge};default:return null}if(e.kind==="stopped")switch(e.state){case"sent":return{text:`Stopping ${t}…`,kind:"info"};case"delivered":return{text:`Stopped: ${t}'s turn was cut off. Press Start to carry on.`,kind:"info"};case"failed":case"expired":return{text:`${t} could not be stopped from here${e.detail?` (${e.detail})`:""}: stop it in its own window. Its next dcursed tool tells it to stop.`,kind:"error"};default:return null}if(e.kind==="passed"||e.kind==="sentBack"){const i=e.kind==="passed"?"Checkpoint passed":`Sent ${e.step??"the step"} back`,o=e.text.replace(/^\[DiaCode\] /,"");switch(e.state){case"sent":return{text:`${i}. Telling ${t}…`,kind:"info"};case"delivered":return{text:`${i}, and ${t} was told.`,kind:"info"};case"queued":return{text:`${i}. ${t} hears it when its turn ends, or at its next step.`,kind:"info"};case"failed":case"expired":return{text:`${i}. ${t} could not be woken: tell it yourself.`,kind:"info",copy:o};default:return null}}if(e.kind==="archAccepted")switch(e.state){case"sent":return{text:`Architecture approved. Telling ${t} to draw the plan on it…`,kind:"info"};case"delivered":return{text:`Architecture approved, and ${t} was told to draw the plan on it.`,kind:"info"};case"queued":return{text:`Architecture approved. ${t} hears it when its turn ends: it then draws the plan.`,kind:"info",copy:Ee};case"none":return{text:"Architecture approved. No agent is listening for the editor: ask yours to draw the plan on it.",kind:"info",copy:Ee};case"failed":case"expired":return{text:`Architecture approved. ${t} could not be told${e.detail?` (${e.detail})`:""}: ask it to draw the plan on it.`,kind:"info",copy:Ee};default:return null}if(e.kind==="archChanged")return e.state==="delivered"?{text:`${t} was told what you changed in the architecture, and will propose the matching change to the plan.`,kind:"info"}:e.state==="failed"?{text:`${t} could not be told what you changed in the architecture${e.detail?` (${e.detail})`:""}: ask it to make the plan agree.`,kind:"info"}:null;if(e.kind==="archSettled")switch(e.state){case"sent":return{text:`Decided. Telling ${t}…`,kind:"info"};case"delivered":return{text:`Decided, and ${t} was told what you did with its proposal.`,kind:"info"};case"queued":return{text:`Decided. ${t} hears it when its turn ends, or at its next architecture tool.`,kind:"info"};case"failed":case"expired":return{text:`Decided. ${t} could not be woken${e.detail?` (${e.detail})`:""}: it reads it at its next architecture tool.`,kind:"info"};default:return null}if(e.kind==="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}}const ts={working:"working",idle:"idle",error:"hit an error",asking:"waiting for you",quiet:"gone quiet",gone:"gone"};function Ot(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 Tt(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 ns(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 ss(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">${b(ns(a))}</span>`:"",l=(e??[]).map(a=>{const r=a.state==="working"?"":ye(a.state==="gone"?a.seen:a.since,t),u=(a.state==="error"||a.state==="asking")&&a.detail?`: ${b(a.detail)}`:"",f=i(a.actor);return`<span class="${`agent ${b(a.state)}${f?" has-receipt":""}${f&&f.behind>0?" behind":""}`}"><i></i><span class="who"><b>${b(C(a.actor))}</b> ${b(ts[a.state]??a.state)}${r?` · ${b(r)}${r==="just now"?"":" ago"}`:""}${u}</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>${b(C(a.actor))}</b></span>${o(a)}</span>`);return l.length?`<div class="agents">${l.join("")}</div>`:""}function Mt(e){if(!e)return"";const t="The re-planner",n=e.kind==="drift"?(e.files??[]).map(b).join(", "):(e.steps??[]).map(b).join(", ");return e.state==="running"?`<p class="lede">${t} is reading ${n||"the plan"}…</p>`:e.state==="failed"?`<p class="err">${t} could not answer: ${b(e.message??"no reason given")}</p>`:`<p class="lede">${t}: ${b(e.message??"done")}.</p>`}function Et(e){const t=`data-from="${b(e.from)}" data-to="${b(e.to)}"`,n=(i,o,l=!1)=>`<button${l?' class="primary"':""} data-gate="${i}" ${t}>${o}</button>`,s=i=>`<input data-gate-text ${t} placeholder="${b(i)}" aria-label="${b(i)}">`;return e.kind==="approve"?`${n("pass","Approve",!0)}${s("or why it is not right")}${n("back","Send back")}`:e.kind==="input"?`${s("what it needs")}${n("give","Give",!0)}`:e.turn==="you"?`${s("your answer")}${n("give","Answer",!0)}`:n("pass","Let it start without asking")}const _t=e=>`<input data-answer="${b(e)}" placeholder="your answer" aria-label="Answer ${b(e)}">${D("answer",e,"Answer",!0)}`;function os(e,t){const n=o=>`<b>${b(t.nodes[o]?.label??o)}</b> <code>${b(o)}</code>`;let s;e.kind==="approve"?s=`Approve the result of ${n(e.from)} before ${n(e.to)} starts`:e.kind==="input"?s=`${n(e.to)} needs input from you${e.label?`: ${b(e.label)}`:""}`:e.turn==="you"?s=`Asked before ${n(e.to)}: <q>${b(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;return`<li class="step gate" data-step="${b(e.to)}" tabindex="0"><div class="head"><span>${s}</span></div>${i?`<div class="note">${b(i)}</div>`:""}<div class="row actions">${Et(e)}</div></li>`}const D=(e,t,n,s=!1)=>`<button${s?' class="primary"':""} data-act="${e}" data-step="${b(t)}">${n}</button>`;function as(e,t,{showStep:n=i=>`<button class="plain small" data-show-step="${b(i)}">Show</button>`,showProposal:s=i=>`<button class="plain small" data-show-proposal="${b(i)}">Show on the board</button>`}={}){const i=t.reconcile?.state==="running",o=(a,r,u,f=!1)=>`<button${f?' class="primary" ':" "}data-act="${a}" data-step="${b(r)}">${u}</button>`,l=a=>{const r=a.step;switch(a.kind){case"question":return`${_t(r)}${n(r)}`;case"asking":return a.permission?`<button class="primary" data-permit="${b(a.permission.id)}">Allow</button><input data-permit-why="${b(a.permission.id)}" placeholder="why not (optional)" aria-label="Why you deny it"><button data-deny="${b(a.permission.id)}">Deny</button>`:"";case"checkpoint":return`${Et({...a.gate,turn:"you"})}${n(r)}`;case"failure":return`<button class="primary" data-act="replan" data-step="${b(r)}"${i?" disabled":""}>Re-plan from this</button>${o("reopen",r,"Try again")}${n(r)}`;case"stalled":return`${o("release",r,"Release")}${n(r)}`;case"proposal":return`<button class="primary" data-accept="${b(a.proposal)}">Accept</button><button data-reject="${b(a.proposal)}">Reject</button>${s(a.proposal)}`;case"review":return`<button class="primary" data-reconcile ${i?"disabled":""}>${i?"Looking…":"Ask the re-planner"}</button>${n(r)}`;case"finish":return'<button class="primary" data-finish>Mark plan done</button>';default:return""}};return e.map(a=>`
10
+ <li class="inbox-item" data-kind="${a.kind}">
11
+ <div class="inbox-what"><b>${b(a.title)}</b>${a.detail?`<span class="inbox-detail">${b(a.detail)}</span>`:""}</div>
12
+ ${l(a)?`<div class="row actions">${l(a)}</div>`:""}
13
+ ${a.kind==="review"?Mt(t.reconcile):""}
14
+ </li>`).join("")}const go=(e,t,n)=>`<ul class="inbox">${as(e,t,n)}</ul>`;function is(e,t,n){return e?.length?`<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(s=>`<li class="step"><code>${b(s.file)}</code><div class="meta"><span class="who">${b(C(s.by))}</span> · ${s.count}× · ${b(ye(s.at,t))}${ye(s.at,t)==="just now"?"":" ago"}</div></li>`).join("")}</ul>
16
+ <div class="row"><button class="primary" data-act="drift" data-step=""${n?" disabled":""}>Should the plan cover this?</button></div>`:""}function rs(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,L.done)}${t(e.active,L.in_progress)}${t(e.waiting,L.waiting)}${t(e.failed,L.failed)}${t(e.left,"var(--line)")}</div>`}function ls(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 mo(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(p=>p.state==="asking").map(p=>[p.actor,p])),r=Object.entries(n.nodes).filter(([,p])=>p.kind!=="context"),u=new Set((s.gates??[]).filter(p=>p.turn==="agent").map(p=>p.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=(p,v,W,Dt={})=>{const ae=He(v),he=v.status??"not_started",Ke=s.atRisk?.[p],ze=s.stalled?.[p],Ye=s.blocked?.[p],Ge=s.held?.[p],Se=ye(es(o,p),t),H=[];return ae&&H.push(`<span class="who" title="${b(Ne[ae.from])}">${We[ae.from]} ${b(C(ae.who))}</span> <span class="how">${b(Ne[ae.from])}</span>`),Se&&he!=="not_started"&&H.push(`<span class="how">${b(Se)}${Se==="just now"?"":" ago"}</span>`),Ye&&he!=="not_started"&&H.push(`<span class="how">blocked by ${Ye.map(b).join(", ")}</span>`),Ge&&H.push(u.has(p)?'<span class="how">the agent asks you something before it starts</span>':`<span class="how">waits at a checkpoint after ${Ge.map(b).join(", ")}</span>`),ze&&H.push(`<span class="risk">stalled: ${b(Tt(ze))}</span>`),he==="in_progress"&&v.owner&&a.has(v.owner)&&H.push(`<span class="risk">${b(Ot(a.get(v.owner)))}</span>`),Ke&&H.push(`<span class="risk">at risk: ${Ke.map(b).join(", ")} failed</span>`),p in i&&H.push('<span class="how">needs review</span>'),`
17
+ <li class="step" data-step="${b(p)}" tabindex="0">
18
+ <div class="head"><span><i class="dot" style="background:${L[he]??"var(--wire-soft)"}"></i><b>${b(v.label)}</b> <code>${b(p)}</code></span><button class="plain small" data-inspect="${b(p)}" aria-label="Details of ${b(v.label)}">Details</button></div>
19
+ ${H.length?`<div class="meta">${H.join(" · ")}</div>`:""}
20
+ ${v.note?`<div class="note">${b(v.note)}</div>`:""}
21
+ ${Dt.showQuestion?`<div class="row">${_t(p)}</div>`:""}
22
+ ${W.length?`<div class="row actions">${W.join("")}</div>`:""}
23
+ </li>`},g=(p,v,W="")=>v.length?`<h4>${p}</h4>${W?`<p class="lede">${W}</p>`:""}<ul class="items steps">${v.join("")}</ul>`:"",h=p=>r.filter(([v,W])=>p(W,v)),d=p=>p.status??"not_started",c=e.reconcile?.state==="running",$=(s.gates??[]).filter(p=>p.turn==="you"),m=h(p=>d(p)==="waiting"),S=h(p=>d(p)==="failed"),O=h((p,v)=>d(p)==="in_progress"&&v in(s.stalled??{})),q=h((p,v)=>d(p)==="in_progress"&&!(v in(s.stalled??{}))),E=h((p,v)=>d(p)==="not_started"&&s.ready.includes(v)),T=h((p,v)=>d(p)==="not_started"&&!s.ready.includes(v)),x=h(p=>d(p)==="done"),A=h(p=>d(p)==="cancelled"),M=new Set(e.listening??[]),fe=m.length>0&&m.every(([,p])=>p.owner&&M.has(p.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.",ve=p=>p.owner==="you",te=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
+ ${rs(l)}
25
+ <p class="lede">${ls(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 ${b(De(e.stopping))}:</b> ${e.stopping.length===1?"it stops":"they stop"} at the next tool call, and the turn ends there.</p>`:""}
29
+ ${ss(e.presence,t,e.reads)}
30
+ ${Mt(e.reconcile)}
31
+ ${n.proposals?.length?`<p class="lede"><button data-show-proposal="${b(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
+ ${g("At a checkpoint",$.map(p=>os(p,n)),"The plan waits for you here before the next step starts. What you say goes to the agent with it.")}
33
+ ${g("Waiting for you",m.map(([p,v])=>f(p,v,[D("cancel",p,"Cancel step")],{showQuestion:!0})),fe)}
34
+ ${g("Stalled",O.map(([p,v])=>f(p,v,[D("done",p,"Mark done"),D("failed",p,"Mark failed"),D("release",p,"Release")])),"The agent holding these has stopped, and the plan still says in progress.")}
35
+ ${g("Failed",S.map(([p,v])=>f(p,v,[`<button class="primary" data-act="replan" data-step="${b(p)}"${c?" disabled":""}>Re-plan from this</button>`,D("reopen",p,"Try again"),D("cancel",p,"Cancel step")])))}
36
+ ${is(e.drift,t,c)}
37
+ ${g("Working now",q.map(([p,v])=>f(p,v,ve(v)?[D("done",p,"Mark done"),D("failed",p,"Mark failed"),D("release",p,"Release")]:[])))}
38
+ ${g(n.phase==="planning"?"First up":"Ready",E.map(([p,v])=>f(p,v,[D("cancel",p,"Cancel step")])),te)}
39
+ ${g("Blocked",T.map(([p,v])=>f(p,v,[D("cancel",p,"Cancel step")])))}
40
+ ${g("Done",x.map(([p,v])=>f(p,v,[D("reopen",p,"Reopen")])),"Finished steps are locked on the chart: reopen one to change it.")}
41
+ ${g("Cancelled",A.map(([p,v])=>f(p,v,[D("reopen",p,"Reopen")])))}`}function ds(e){const t=e?.plan?.nodes??{},n=Object.entries(t).filter(([,h])=>h&&h.kind!=="context"),s=(e?.presence??[]).filter(h=>h?.state==="asking").map(h=>String(h.actor)),i=n.filter(([,h])=>h.status==="waiting").map(([h])=>h),o=n.filter(([,h])=>h.status==="failed").map(([h])=>h),l=Object.keys(e?.derived?.stalled??{}).filter(h=>t[h]?.status==="in_progress"),a=(e?.plan?.proposals??[]).length,r=(e?.derived?.gates??[]).filter(h=>h.turn==="you").map(h=>({from:h.from,to:h.to})),u=e?.derived?.proposed??{},f=Object.keys(e?.review??{}).filter(h=>t[h]&&t[h].kind!=="context"&&!(h in u)),g=e?.plan?.phase==="executing"&&n.length>0&&n.every(([,h])=>h.status==="done"||h.status==="cancelled");return{asking:s,questions:i,failures:o,stalled:l,proposals:a,gates:r,reviews:f,finish:g,total:s.length+i.length+o.length+l.length+a+r.length+(g?1:0)}}const G=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;function wo(e){const t=[e.asking.length?`${G(e.asking.length,"agent")} asking you in ${e.asking.length===1?"its window":"their windows"}`:"",e.questions.length?G(e.questions.length,"question"):"",e.gates?.length?G(e.gates.length,"checkpoint"):"",e.failures.length?G(e.failures.length,"failure"):"",e.stalled.length?`${e.stalled.length} stalled`:"",e.proposals?G(e.proposals,"proposal")+" to review":"",e.reviews?.length?`${G(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=ds(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:Ot(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}})}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:Tt(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 ${G(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 yo=(e,t)=>t>0?`(${t}) ${e}`:e,cs=e=>/[*?]/.test(e);function Ct(e){let t=String(e??"").trim().replace(/^(\.\/)+/,"");return t?(t.endsWith("/")&&!cs(t)&&(t=`${t}**`),t):""}function ko(e,t){const n=Ct(t);return!n||e.includes(n)||e.length>=oe?e:[...e,n]}const xo=(e,t)=>e.filter(n=>n!==t);function us(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 vo(e,t,n,s){const i=t.filter(l=>!s.includes(l)).map(l=>({kind:"file",path:l,note:""})),o=Ct(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 k=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),ct={not_started:"not started",in_progress:"in progress",waiting:"waiting for you",done:"done",failed:"failed",cancelled:"cancelled"},fs=(e,t=150)=>e.length>t?`${e.slice(0,t-1)}…`:e;function So(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 Rt(e,t,n={}){return t.length?t.map(s=>{const{note:i,warn:o}=us(n[s]);return`<li class="file-chip${o?" warn":""}" data-path="${k(s)}"><code>${k(s)}</code>${i?`<span class="chip-note">${k(i)}</span>`:""}<button type="button" class="chip-x" data-remove-file="${k(s)}" data-step="${k(e)}" aria-label="Stop listing ${k(s)}">×</button></li>`}).join(""):'<li class="chips-none">None yet.</li>'}const hs=(e,t)=>e.id===t||e.from===t||e.to===t||Array.isArray(e.ids)&&e.ids.includes(t);function ps(e,t,n=6){return[...e??[]].reverse().map(s=>({line:s,ops:(s.ops??[]).filter(i=>hs(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=>tn(o)).join("; "),...s.proposed?{proposed:s.proposed}:{}}))}function Ao({plan:e,id:t,derived:n={},review:s={},recent:i=[],drafts:o={},fileInfo:l={},arch:a=null}){const r=e?.nodes?.[t];if(!r)return"";const u=r.kind==="context"?"context":r.status??"not_started",f=L[u]??"var(--wire-soft)",g=He(r),h=n.blocked?.[t],d=n.stalled?.[t],c=n.atRisk?.[t],$=n.proposed?.[t],m=[`<b>${k(r.kind==="context"?"context, not work":ct[u]??u)}</b>`];g&&m.push(`${k(We[g.from])} ${k(C(g.who))}, ${k(Ne[g.from])}`),h?.length&&m.push(k(jt(h))),d&&m.push(`<span class="risk">stalled: ${k(C(d.owner))} is ${k(d.state)}</span>`),c?.length&&m.push(`<span class="risk">at risk: ${c.map(k).join(", ")} failed</span>`),s[t]&&m.push(`needs review: ${s[t].because.map(k).join("; ")} <button class="plain small" data-review="${k(t)}" title="I looked: no change is needed">Looks fine</button>`),$?.length&&m.push(`${$.length===1?"a proposal waits":`${$.length} proposals wait`} to change it (${$.map(k).join(", ")}): shown on the board`);const S=(T,x)=>T.length?`<ul class="rel">${T.map(A=>{const M=e.nodes[A],P=M.kind==="context"?"context":M.status??"not_started";return`<li><i class="dot" style="background:${L[P]??"var(--wire-soft)"}"></i>${k(M.label)} <code>${k(A)}</code> <span class="how">${k(ct[P]??P)}</span></li>`}).join("")}</ul>`:`<p class="help">${x}</p>`,O=ps(i,t),q=o.detail??r.detail??"",E=T=>T?' <b class="unsaved">Not saved yet.</b>':"";return`
43
+ <section class="inspector" aria-label="Step: ${k(r.label)}">
44
+ <header>
45
+ <div><i class="dot" style="background:${f}"></i><b class="name">${k(r.label)}</b> <code>${k(t)}</code></div>
46
+ <button class="plain" data-close-inspector aria-label="Close the details of ${k(r.label)}">Close</button>
47
+ </header>
48
+ <p class="facts">${m.join(" · ")}</p>
49
+
50
+ <label for="insp-detail">What done means</label>
51
+ <textarea id="insp-detail" data-field="detail" data-step="${k(t)}" rows="5" maxlength="${Y}" placeholder="Not written yet. Say what is true when this step is finished: the tests that pass, the behaviour that works.">${k(q)}</textarea>
52
+ <p class="help">An agent is given this with the step. Saved when you leave the box.${E(o.detail!==void 0&&o.detail!==(r.detail??""))}</p>
53
+ <div class="row"><button class="primary" data-save-field="detail" data-step="${k(t)}">Save</button></div>
54
+
55
+ <label for="insp-files">Files this step changes</label>
56
+ <div class="files" data-files-for="${k(t)}">
57
+ <ul class="chips" aria-label="Files this step lists">${Rt(t,r.files??[],l)}</ul>
58
+ <div class="files-add">
59
+ <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="${k(t)}" placeholder="Search the repository, or type a path or a pattern">
60
+ <ul class="files-menu" id="insp-files-list" role="listbox" aria-label="Files to add" hidden></ul>
61
+ </div>
62
+ </div>
63
+ <p class="help">At most ${oe}. 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>
64
+
65
+ ${gs(a,t,r)}
66
+ ${$s(e,t,r,n)}
67
+ <h5>Depends on</h5>
68
+ ${S(Wt(e,t),"Nothing: it can start.")}
69
+ <h5>Waited on by</h5>
70
+ ${S($t(e,t),"Nothing depends on it.")}
71
+ <h5>History</h5>
72
+ ${O.length?`<ul class="hist">${O.map(T=>`<li><span class="how">rev ${k(T.rev)} · ${k(C(T.actor))}${T.proposed?" (a proposal)":""}</span> ${k(fs(T.text))}</li>`).join("")}</ul>`:'<p class="help">Nothing done to it lately.</p>'}
73
+ </section>`}function $s(e,t,n,s){if(n.kind==="context")return"";const i=n.status??"not_started",o=(f,g)=>`<button data-act="${f}" data-step="${k(t)}">${g}</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="${k(f.from)}" data-to="${k(f.to)}">Let it start without asking</button>`);return l.length?`<h5>Do it yourself</h5><p class="help">${n.owner&&n.owner!=="you"?`${k(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 gs(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=Cn(e,n),i=new Set(n.touches??[]),o=a=>{const r=e.nodes[a.id],u=r?r.label:a.id;return a.by==="hand"?`<li class="file-chip${r?"":" warn"}" data-box="${k(a.id)}"><span>${k(u)}</span>${r?"":'<span class="chip-note">not in the architecture</span>'}<button type="button" class="chip-x" data-remove-touch="${k(a.id)}" data-step="${k(t)}" aria-label="Stop saying it changes ${k(u)}">×</button></li>`:`<li class="file-chip" data-box="${k(a.id)}"><span>${k(u)}</span><span class="chip-note">from its files</span></li>`},l=Object.entries(e.nodes).filter(([a])=>!i.has(a));return`
74
+ <h5>Boxes it changes</h5>
75
+ <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>
76
+ <select data-touch-add="${k(t)}" aria-label="Add a box this step changes"><option value="">Add a box…</option>${l.map(([a,r])=>`<option value="${k(a)}">${k(r.label)} (${k(r.kind)})</option>`).join("")}</select>
77
+ <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 ut={person:"Person",service:"Service",component:"Component",store:"Store",queue:"Queue",group:"Group"},ms={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 jo(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,u=n+i/2,f=[],g=(d,c,$={})=>f.push({tag:"path",role:c,attrs:{d,...$}}),h=(d,c=0,$=0)=>`M${y(l+c+d)} ${y(r+$)}H${y(a+c-d)}A${d} ${d} 0 0 1 ${y(a+c)} ${y(r+$+d)}V${y(u+$-d)}A${d} ${d} 0 0 1 ${y(a+c-d)} ${y(u+$)}H${y(l+c+d)}A${d} ${d} 0 0 1 ${y(l+c)} ${y(u+$-d)}V${y(r+$+d)}A${d} ${d} 0 0 1 ${y(l+c+d)} ${y(r+$)}Z`;switch(e){case"store":{const d=s/2,c=Math.min(9,Math.max(5,i*.18));g(`M${y(l)} ${y(r+c)}A${y(d)} ${y(c)} 0 0 1 ${y(a)} ${y(r+c)}V${y(u-c)}A${y(d)} ${y(c)} 0 0 1 ${y(l)} ${y(u-c)}Z`,"fill"),g(`M${y(l)} ${y(r+c)}A${y(d)} ${y(c)} 0 0 0 ${y(a)} ${y(r+c)}`,"line");break}case"queue":{const d=Math.min(12,s/5),c=i/2;g(`M${y(l+d)} ${y(r)}H${y(a-d)}A${y(d)} ${y(c)} 0 0 1 ${y(a-d)} ${y(u)}H${y(l+d)}A${y(d)} ${y(c)} 0 0 1 ${y(l+d)} ${y(r)}Z`,"fill"),g(`M${y(l+d)} ${y(r)}A${y(d)} ${y(c)} 0 0 0 ${y(l+d)} ${y(u)}`,"line");break}case"person":{f.push({tag:"circle",role:"fill",attrs:{cx:y(t),cy:y(r-4),r:7.5}}),g(h(Math.min(i/2,13)),"fill");break}case"component":o&&g(h(3,5,-5),"back"),g(h(3),"fill");break;case"group":{o&&g(h(10,5,-5),"back",{dashed:1}),g(h(10),"fill",{dashed:1});break}default:{const d=Math.min(14,i/2);o&&g(h(d,5,-5),"back"),g(h(d),"fill")}}return f}const ws={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"/>'},Oo={approve:"check",ask:"question",input:"pencil"},To={approve:"approve",ask:"ask first",input:"needs input"},bs=e=>`<g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${ws[e]??""}</g>`,ys=(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}"`:""}>${bs(e)}</svg>`,w=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),ks=(e,t=150)=>e.length>t?`${e.slice(0,t-1)}…`:e,xs=e=>`${e.external?"an outside":"a"} ${e.kind}`;function Mo({arch:e,id:t,footprint:n=null,steps:s={},drafts:i={},fileInfo:o={},recent:l=[],editable:a=!0}){const r=e.nodes[t];if(!r)return"";const u=X(e,t),f=r.in?e.nodes[r.in]:void 0,g=n?St(e,n,t):null,h=[`<b>${w(xs(r))}</b>`];f&&h.push(`in <button class="plain small" data-inspect="${w(r.in)}">${w(f.label)}</button>`),u.length&&h.push(`a frame: it holds ${u.length} box${u.length===1?"":"es"}, and takes no arrows of its own`),r.planned&&h.push(`<span class="plan-note new">${r.planned==="next"?"planned":`planned by <code>${w(r.planned)}</code>`}: it does not exist yet</span>`),r.retiring&&h.push(`<span class="plan-note removed">retiring: <code>${w(r.retiring)}</code> removes it</span>`),g&&g!=="untouched"&&h.push(`<span class="plan-note ${g}">${ys(Le[g].icon,{size:12})} ${w(Le[g].word)} by ${w(n?.plan??"")}</span>`);const d=n?.changed.get(t)??[],c=i.detail??r.detail??"",$=i.tech??r.tech??"",m=a?"":" disabled",S=(x,A)=>x.length?`<ul class="rel">${x.map(M=>{const P=e.nodes[M];return`<li><button class="plain small" data-inspect="${w(M)}">${w(P.label)}</button> <span class="how">${w(P.kind)}</span></li>`}).join("")}</ul>`:`<p class="help">${A}</p>`,O=e.edges.filter(x=>x.from===t),q=e.edges.filter(x=>x.to===t),E=(x,A)=>`<ul class="rel">${x.map(M=>{const P=e.nodes[M[A]];return`<li><button class="plain small" data-inspect="${w(M[A])}">${w(P.label)}</button> <span class="how">${w([M.label,M.tech,M.async?"async":""].filter(Boolean).join(" · ")||P.kind)}</span></li>`}).join("")}</ul>`,T=[...l].reverse().map(x=>({l:x,ops:(x.ops??[]).filter(A=>A.id===t||A.from===t||A.to===t)})).filter(x=>x.ops.length).slice(0,6);return`
78
+ <section class="inspector box-card" aria-label="Box: ${w(r.label)}" data-box="${w(t)}">
79
+ <header>
80
+ <div><i class="dot kind-${w(r.kind)}"></i><b class="name">${w(r.label)}</b> <code>${w(t)}</code></div>
81
+ <button class="plain" data-close-inspector aria-label="Close the details of ${w(r.label)}">Close</button>
82
+ </header>
83
+ <p class="facts">${h.join(" · ")}</p>
84
+ ${d.length?`<p class="facts">Changed by ${d.map(x=>w(s[x]?.label??x)).join(", ")}.</p>`:""}
85
+ <p class="help">${w(ms[r.kind]??"")}. Double-click the box to rename it.</p>
86
+
87
+ <div class="row fields">
88
+ <label>What it is <select data-box-field="kind" data-box="${w(t)}"${m} aria-label="What ${w(r.label)} is">${Object.keys(ut).map(x=>`<option value="${x}"${x===r.kind?" selected":""}${u.length&&x!=="service"&&x!=="group"?" disabled":""}>${w(ut[x])}</option>`).join("")}</select></label>
89
+ <label class="check"><input type="checkbox" data-box-field="external" data-box="${w(t)}"${r.external?" checked":""}${m}> Someone else runs it</label>
90
+ </div>
91
+
92
+ <label for="insp-tech">What it runs on</label>
93
+ <input id="insp-tech" type="text" data-box-field="tech" data-box="${w(t)}" maxlength="${Z}" value="${w($)}" placeholder="Python, FastAPI"${m}>
94
+
95
+ <label for="insp-detail">What it is for</label>
96
+ <textarea id="insp-detail" data-box-field="detail" data-box="${w(t)}" rows="4" maxlength="${Y}" placeholder="Not written yet. Say what this box is for, and what it is not."${m}>${w(c)}</textarea>
97
+ <p class="help">An agent reads this with the architecture. Saved when you leave the box.${i.detail!==void 0&&i.detail!==(r.detail??"")?' <b class="unsaved">Not saved yet.</b>':""}</p>
98
+
99
+ ${a?`<label for="insp-files">The files that are its</label>
100
+ <div class="files" data-files-for="${w(t)}">
101
+ <ul class="chips" aria-label="Files this box owns">${Rt(t,r.files??[],o)}</ul>
102
+ <div class="files-add">
103
+ <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">
104
+ <ul class="files-menu" id="insp-files-list" role="listbox" aria-label="Files to add" hidden></ul>
105
+ </div>
106
+ </div>
107
+ <p class="help">At most ${oe}. A plan whose step lists a file one of these covers is shown as changing this box.</p>`:""}
108
+
109
+ <h5>Uses</h5>
110
+ ${O.length?E(O,"to"):'<p class="help">Nothing.</p>'}
111
+ <h5>Used by</h5>
112
+ ${q.length?E(q,"from"):'<p class="help">Nothing.</p>'}
113
+ ${u.length?`<h5>Holds</h5>${S(u,"")}`:""}
114
+ <h5>History</h5>
115
+ ${T.length?`<ul class="hist">${T.map(({l:x,ops:A})=>`<li><span class="how">rev ${w(x.rev)} · ${w(C(x.actor))}${x.proposed?" (a proposal)":""}</span> ${w(ks(A.map(M=>xe(M)).join("; ")))}</li>`).join("")}</ul>`:'<p class="help">Nothing done to it lately.</p>'}
116
+ </section>`}function Eo({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],u=X(e,a),f=s?St(e,s,a):null,g=f&&f!=="untouched"?` <span class="plan-note ${f}">${w(Le[f].word)}</span>`:r.planned?' <span class="plan-note new">planned</span>':r.retiring?' <span class="plan-note removed">retiring</span>':"",h=n.includes(a);return`<li class="box-item" data-box="${w(a)}">
117
+ <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>${g}</button>
118
+ ${u.length&&i?`<button class="plain small fold" data-fold="${w(a)}" aria-pressed="${h}" title="${h?"Unfold: show what is inside":"Fold: hide what is inside"}">${h?"Unfold":"Fold"}</button>`:""}
119
+ ${u.length?`<ul class="box-children">${u.map(l).join("")}</ul>`:""}
120
+ </li>`};return`<ul class="boxlist" aria-label="Boxes">${o.filter(a=>!e.nodes[a].in).map(l).join("")}</ul>`}function _o({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>
121
+ <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=>`
122
+ <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,u)=>{const f=_n(e,r),g=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="${u}"${u===n?' aria-current="step"':""}><button class="plain" data-flow-at="${u}"><span class="n">${u+1}</span> ${l(r.from)} <span aria-hidden="true">→</span> ${l(r.to)}${r.label?` <span class="how">${w(r.label)}</span>`:""}${g}</button></li>`}).join("");return`${o}
123
+ <section class="flow-open" aria-label="${w(i.title)}">
124
+ <header><b>${w(i.title)}</b></header>
125
+ <div class="row">
126
+ <button data-flow-prev aria-label="Previous step"${n===null||n<=0?" disabled":""}>&lsaquo; Back</button>
127
+ <button class="primary" data-flow-play>${s?"Pause":n===null?"Play":n>=i.steps.length-1?"Play again":"Play"}</button>
128
+ <button data-flow-next aria-label="Next step"${n!==null&&n>=i.steps.length-1?" disabled":""}>Next &rsaquo;</button>
129
+ <button class="plain" data-flow-clear>Show everything</button>
130
+ </div>
131
+ <ol class="flow-steps">${a}</ol>
132
+ </section>`}function Co(e){const t=[...e].reverse();return t.length?`
133
+ <p class="lede">The architecture's log, newest first. It is committed with the architecture, so a pull request shows who did what.</p>
134
+ <ul class="log">${t.map(n=>`
135
+ <li><span class="rev">rev ${n.rev}</span> <code>${w(n.actor)}</code> <span class="via">via ${w(n.via)}</span>
136
+ ${n.proposed?`<span class="via">→ proposal ${w(n.proposed)}</span>`:""}
137
+ <div>${(n.ops??[]).map(s=>w(xe(s))).join(" · ")}</div></li>`).join("")}</ul>`:'<p class="lede">No changes yet. Everything you do here is logged, with who did it.</p>'}function Ro(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=>xe(i)).join("; "),proposal:s.id});return n}function vs(e,{show:t=n=>`<button class="plain small" data-arch-show="${w(n)}">Show on the board</button>`}={}){return e.map(n=>`
138
+ <li class="inbox-item" data-kind="${n.kind}">
139
+ <div class="inbox-what"><b>${w(n.title)}</b>${n.detail?`<span class="inbox-detail">${w(n.detail)}</span>`:""}</div>
140
+ <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>${qt(n.proposal??"")}<button data-arch-reject="${w(n.proposal??"")}">Reject</button>${t(n.proposal??"")}`}</div>
141
+ </li>`).join("")}const qo=(e,t)=>`<ul class="inbox">${vs(e,t)}</ul>`;function No(e,{at:t,of:n,applies:s,why:i,arch:o}){const l=a=>Ss(xe(a),o);return`
142
+ <header><b>${w(C(e.by))} proposes</b>${n>1?` <span class="how">${t} of ${n}</span>`:""}</header>
143
+ ${e.reason?`<p class="reason">${w(e.reason)}</p>`:""}
144
+ <ul class="ops">${e.ops.map(a=>`<li>${w(l(a))}</li>`).join("")}</ul>
145
+ ${s?"":`<p class="risk">It no longer applies: ${w(i??"the architecture changed under it")}.</p>`}
146
+ <div class="row actions"><button class="primary" data-arch-accept="${w(e.id)}"${s?"":" disabled"}>Accept</button>${qt(e.id)}<button data-arch-reject="${w(e.id)}">Reject</button>${n>1?'<button class="plain small" data-arch-next>Next</button>':""}</div>`}const qt=e=>`<input data-arch-why="${w(e)}" placeholder="why not (optional)" aria-label="Why you reject ${w(e)}">`;function Ss(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 As({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 Lo=e=>`/app/#${As(e)}`;function Do(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 I={padding:9,maxWidth:168,minWidth:66,minHeight:34,fontSize:12.5},Nt=Math.round(I.fontSize*1.35),js=e=>Math.max(I.minHeight,e*Nt+I.padding*2),Os=16,ft=6,ht={x:Math.ceil(I.maxWidth/2+ft),y:Math.ceil(js(3)/2+Os+ft/2)},Po=e=>({width:e.canvas.width+ht.x*2,height:e.canvas.height+ht.y*2}),$e={left:16,right:16,top:32,bottom:14},Ts=e=>!!e&&e!==ue;function Ms(e){const t=new Map;for(const n of e){if(!Ts(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))-$e.left,o=Math.max(...s.map(r=>r.x+r.w/2))+$e.right,l=Math.min(...s.map(r=>r.y-r.h/2))-$e.top,a=Math.max(...s.map(r=>r.y+r.h/2))+$e.bottom;return{group:n,x:i,y:l,w:o-i,h:a-l,members:s.map(r=>r.id)}})}const Fo=(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 Es(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 _s={x:14,y:14};let _e;function Lt(e){_e||=document.createElement("canvas").getContext("2d");const t=getComputedStyle(document.documentElement).getPropertyValue("--sans").trim()||"sans-serif";return _e.font=`normal ${I.fontSize}px ${t}`,_e.measureText(e).width}function Cs(e){const t=I.maxWidth-I.padding*2,n=String(e??"").split(/\s+/).filter(Boolean),s=[];let i="";for(const o of n){const l=i?`${i} ${o}`:o;i&&Lt(l)>t?(s.push(i),i=o):i=l}return i&&s.push(i),s.length?s:[""]}function ke(e){const t=Cs(e),n=Math.max(...t.map(Lt)),s=Nt;return{width:Math.max(I.minWidth,Math.min(I.maxWidth,n+I.padding*2)),height:Math.max(I.minHeight,t.length*s+I.padding*2),lines:t,step:s}}const Ce=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]);function Rs(e,t,n){const s={...e,...ke(e.label)},i={...t,...ke(t.label)};if(n==="TD"){const f=s.x,g=s.y+s.height/2,h=i.x,d=i.y-i.height/2;if(d<=g)return`M${s.x} ${s.y} L${i.x} ${i.y}`;const c=(g+d)/2;return Math.abs(f-h)<1?`M${f} ${g} V${d}`:`M${f} ${g} V${c} H${h} V${d}`}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 u=(o+a)/2;return Math.abs(l-r)<1?`M${o} ${l} H${a}`:`M${o} ${l} H${u} V${r} H${a}`}let qs=0;function Io(e,{labels:t=!1,className:n="",title:s="",margin:i=_s,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])),u=e.direction==="TD"?"TD":"LR",f=`ah${++qs}`,g=e.depends.filter(c=>r.has(c.source)&&r.has(c.target)).map(c=>`<path d="${Rs(r.get(c.source),r.get(c.target),u)}" marker-end="url(#${f})"/>`).join(""),h=Ms(e.steps.map(c=>{const $=ke(c.label);return{id:c.id,group:c.group,x:c.x,y:c.y,w:$.width,h:$.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)">${Ce(Es(c.group,c.w))}</text>`:"")).join(""),d=e.steps.map(c=>{const $=ke(c.label),m=c.x-$.width/2,S=c.y-$.height/2,O=o?.(c.id);let q=`<rect x="${m.toFixed(1)}" y="${S.toFixed(1)}" width="${$.width.toFixed(1)}" height="${$.height.toFixed(1)}" rx="7" fill="var(--surface)" stroke="${O??"var(--wire)"}" stroke-width="${O?3:1.5}"/>`;if(t){const E=$.step,T=c.y-($.lines.length-1)*E/2;q+=$.lines.map((x,A)=>`<text x="${c.x}" y="${(T+A*E).toFixed(1)}" dy=".35em" text-anchor="middle">${Ce(x)}</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="${Ce(s||e.title)}" preserveAspectRatio="xMidYMid meet">
147
+ <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>
148
+ <g transform="translate(${i.x} ${i.y})">
149
+ <g class="frames">${h}</g>
150
+ <g fill="none" stroke="var(--wire)" stroke-width="1.4">${g}</g>
151
+ <g class="boxes" font-size="${I.fontSize}" fill="var(--ink)" font-family="var(--sans)">${d}</g>
152
+ </g>
153
+ </svg>`}const Bo=()=>(document.fonts?.load('400 12.5px "Geist Variable"',"generator.js drawMaze")??Promise.resolve()).catch(()=>{});export{ht as $,to as A,oo as B,$o as C,Js as D,Ne as E,Le as F,We as G,yo as H,Qs as I,Qn as J,Io as K,Ks as L,Ps as M,Ds as N,Wt as O,Ht as P,$t as Q,pt as R,L as S,Ls as T,Ns as U,gt as V,wn as W,ce as X,at as Y,Us as Z,ue as _,Ro as a,I as a0,Po as a1,Hs as a2,bt as a3,$e as a4,Is as a5,An as a6,St as a7,Ms as a8,Es as a9,mo as aA,no as aB,zs as aC,wo as aD,Rt as aE,xo as aF,lo as aG,To as aH,ho as aI,go as aJ,tn as aK,Ys as aL,Ct as aM,vo as aN,ko as aO,bs as aa,Oo as ab,jo as ac,ut as ad,Ws as ae,qo as af,Gs as ag,Mo as ah,Eo as ai,_o as aj,Co as ak,ao as al,Xn as am,io as an,No as ao,Fs as ap,Ee as aq,Fo as ar,eo as as,Do as at,So as au,De as av,Jn as aw,co as ax,ro as ay,Ao as az,vs as b,as as c,po as d,rs as e,ls as f,Tt as g,Lo as h,bo as i,Ot as j,Bs as k,ys as l,so as m,ds as n,Zs as o,ss as p,fo as q,uo as r,C as s,Bo as t,As as u,Zn as v,He as w,Vn as x,Vs as y,Xs as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "diacode",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "A plan you and your coding agents share: a diagram in your repository that you edit by hand, with each step showing who has it and how that is known. For OpenCode, Claude Code, Cursor and Antigravity.",
5
5
  "type": "module",
6
6
  "bin": {