@popmelt.com/core 0.8.4 → 0.8.6

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.
@@ -1,4 +1,4 @@
1
- import{mkdir as Wr,unlink as Hr,writeFile as Gr}from"fs/promises";import{join as Yn}from"path";import{execFileSync as mt,spawn as jn}from"child_process";import{createHash as wr,randomUUID as Pe}from"crypto";import{mkdir as Sr,readFile as Ln,readdir as xr,realpath as br,stat as Pr,unlink as Ir,writeFile as Le}from"fs/promises";import{createServer as kr}from"http";import{tmpdir as Mr}from"os";import{basename as ft,dirname as Rr,join as ye}from"path";import{fileURLToPath as Er}from"url";function zt(s,e){return`<!DOCTYPE html>
1
+ import{mkdir as Sd,unlink as Pd,writeFile as kd}from"fs/promises";import{join as js}from"path";import{execFileSync as Xn,spawn as gs}from"child_process";import{createHash as Ps,randomUUID as pt}from"crypto";import{mkdir as Yc,readFile as No,readdir as Zc,realpath as ed,stat as td,unlink as nd,writeFile as an}from"fs/promises";import{createServer as od}from"http";import{tmpdir as rd}from"os";import{basename as Vn,dirname as sd,isAbsolute as Bo,join as Me,relative as ys,resolve as ks}from"path";import{fileURLToPath as id}from"url";function Uo(o,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -18,105 +18,50 @@ import{mkdir as Wr,unlink as Hr,writeFile as Gr}from"fs/promises";import{join as
18
18
  }}
19
19
  </script>
20
20
  <script type="module">
21
- import { mountCanvas } from 'http://localhost:${s}/canvas/app.mjs';
21
+ import { mountCanvas } from 'http://localhost:${o}/canvas/app.mjs';
22
22
  mountCanvas(document.getElementById('root'), {
23
23
  devOrigin: '${e}',
24
- bridgeOrigin: 'http://localhost:${s}',
24
+ bridgeOrigin: 'http://localhost:${o}',
25
25
  });
26
26
  </script>
27
27
  </body>
28
- </html>`}var $s=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),_s=new Set(["default","flex","fast","priority"]);function Re(s){let e=typeof s.reasoningEffort=="string"&&$s.has(s.reasoningEffort)?s.reasoningEffort:void 0,n=typeof s.serviceTier=="string"&&_s.has(s.serviceTier)?s.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function qe(s){let e=[];return s?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(s.reasoningEffort)}`),s?.serviceTier&&e.push(`service_tier=${JSON.stringify(s.serviceTier)}`),e}import{spawn as Os}from"child_process";import{createInterface as Ds}from"readline";var Ns=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Bt=1e5;function Js(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ns.has(n))return;let t;if(s.name==="Write"&&typeof s.input?.content=="string"?t=s.input.content:s.name==="Edit"&&typeof s.input?.new_string=="string"&&(t=s.input.new_string),!!t)return t.length>Bt?t.slice(0,Bt)+`
29
- \u2026[truncated]`:t}function Qe(s,e){let{prompt:n,projectRoot:t,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:a=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:l="claude",resumeSessionId:f,model:v,reasoningEffort:x,timeoutMs:E=3e5,onEvent:B}=e,J=[];f?J.push("--resume",f,"-p",n):J.push("-p",n),J.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),v&&J.push("--model",v),x&&J.push("--effort",x);for(let w of a)J.push("--allowedTools",w);let U=Os(l,J,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),W=new Promise(w=>{let q,V=[],Q=[],K=[],z=!1,Z="",O,A,k=!1,M=setTimeout(()=>{k=!0,U.kill("SIGTERM"),setTimeout(()=>{try{U.kill("SIGKILL")}catch{}},5e3)},E),N=Ds({input:U.stdout}),$=new Set;N.on("line",L=>{if(L.trim())try{let _=JSON.parse(L);_.session_id&&!q&&(q=_.session_id);let ee=_.type??(_.event?.type?`event.${_.event.type}`:"unknown");if($.add(ee),_.type==="result"&&_.result&&V.length===0){let y=typeof _.result=="string"?_.result:"";y&&(V.push(y),B?.({type:"delta",jobId:s,text:y},s))}if(_.type==="assistant"&&Array.isArray(_.message?.content)){typeof _.error=="string"&&(O=_.error);for(let y of _.message.content){if(y.type==="text"&&y.text&&(V.push(y.text),B?.({type:"delta",jobId:s,text:y.text},s)),y.type==="tool_use"&&y.name){let le=y.input?.file_path||y.input?.path||void 0,ie=Js(y);if(B?.({type:"tool_use",jobId:s,tool:y.name,...le?{file:le}:{},...ie?{content:ie}:{}},s),y.name==="Edit"&&y.input?.file_path){let G={tool:"Edit",file_path:y.input.file_path,old_string:y.input.old_string,new_string:y.input.new_string,replace_all:y.input.replace_all};Q.push(G),K.push({sequence:K.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:G.file_path,oldString:typeof G.old_string=="string"?G.old_string:void 0,newString:typeof G.new_string=="string"?G.new_string:void 0,replaceAll:typeof G.replace_all=="boolean"?G.replace_all:void 0})}else y.name==="Write"&&y.input?.file_path&&(Q.push({tool:"Write",file_path:y.input.file_path,content:y.input.content}),K.push({sequence:K.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:y.input.file_path,content:typeof y.input.content=="string"?y.input.content:void 0}))}y.type==="thinking"&&y.thinking&&B?.({type:"thinking",jobId:s,text:y.thinking},s)}}_.type==="result"&&_.is_error===!0&&(z=!0,typeof _.error=="string"&&(O=_.error),typeof _.result=="string"&&(A=_.result)),_.type==="user"&&_.tool_use_result?.file?.filePath&&B?.({type:"tool_use",jobId:s,tool:"Read",file:_.tool_use_result.file.filePath},s)}catch{}});let T=[];U.stderr?.on("data",L=>{T.push(L.toString())}),U.on("close",L=>{if(clearTimeout(M),N.close(),V.length===0&&$.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...$].join(", ")}`),k)z=!0,Z=`Timed out after ${Math.round(E/6e4)} minutes`;else if(L!==0&&L!==null){z=!0;let ee=T.join("").trim(),y=V.join("").trim(),le=V.length===0&&$.size>0?` (no text captured, event types: ${[...$].join(", ")})`:"";Z=ee||A||y||`Claude process exited with code ${L}${le}`}z&&!Z&&A&&(Z=A);let _=zs(Z,O);w({sessionId:q,text:V.join(""),success:!z,error:z?_.message:void 0,errorCode:z?_.code:void 0,recoverableError:z?_.recoverable:void 0,fileEdits:Q.length>0?Q:void 0,editEvents:K.length>0?K:void 0})}),U.on("error",L=>{clearTimeout(M),z=!0,Z=L.message,w({sessionId:q,text:V.join(""),success:!1,error:Z,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:Q.length>0?Q:void 0,editEvents:K.length>0?K:void 0})})});return{process:U,result:W}}function zs(s,e){let n=s.trim()||"Claude CLI failed",t=`${e??""} ${n}`.toLowerCase();return t.includes("authentication_failed")||t.includes("not logged in")||t.includes("please run /login")||t.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:t.includes("model")&&(t.includes("not found")||t.includes("unknown")||t.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as Bs,spawnSync as Ht}from"child_process";import{readFileSync as Fs,statSync as js}from"fs";import{basename as Ls,extname as Us,isAbsolute as Ws,relative as Gt,resolve as Hs}from"path";import{createInterface as Gs}from"readline";function Ft(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var jt=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),vt=2e5,qs=1e5,qt=2e5;function Qt(s){let e=Ls(s).toLowerCase(),n=Us(s).toLowerCase();return jt.has(n)||jt.has(e)}function Xt(s,e){let n=Ws(e)?e:Hs(s,e),t=Gt(s,n);return t===""||t.startsWith("..")?null:n}function Xe(s,e){if(!Qt(e))return;let n=Xt(s,e);if(n)try{let t=js(n);return t.isFile()?t.size>vt?{exists:!0,truncated:!0}:{exists:!0,content:Fs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Qs(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Xs(s){let e=s?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Lt(s){return Qs(s,["patch","diff","unifiedDiff","unified_diff"])}function wt(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function Ut(s,e){let n=Ht("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:qt+65536});return n.status!==0?null:n.stdout??""}function Ys(s){let e=new Set;for(let n of s.split(`
30
- `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let o=t.split(" -> ");for(let i of o)i&&e.add(i)}return[...e]}function Wt(s){let e=Ut(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Ut(s,["diff","--no-ext-diff","HEAD","--"])??"",t=wt(n,qt);return{status:e,changedFiles:Ys(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Vs(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Ks(s,e){if(!Qt(e))return;let n=Xt(s,e);if(!n)return;let t=Gt(s,n);if(t===""||t.startsWith(".."))return;let o=Ht("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:vt+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=wt(i,vt);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function Zs(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Ks(s,t),i=Xe(s,t);return{filePath:t,...o?{before:o}:{},...i?{after:i}:{}}})}function Ye(s,e){let{prompt:n,projectRoot:t,screenshotPath:o,resumeSessionId:i,model:a,onEvent:l,sandboxMode:f="workspace-write",configOverrides:v=[]}=e,x=[];if(i){x.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${f}"`);for(let J of v)x.push("-c",J);a&&x.push("-m",a),x.push(i),x.push(n),o&&x.push("--image",o)}else{x.push("exec","--skip-git-repo-check","--json","--sandbox",f);for(let J of v)x.push("-c",J);a&&x.push("-m",a),x.push(n),o&&x.push("--image",o)}let E=Bs("codex",x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),B=new Promise(J=>{let U,W=[],w=[],q=[],V=new Map,Q=new Map,K=!1,z="",Z=Gs({input:E.stdout}),O=new Set;Z.on("line",k=>{if(k.trim())try{let M=JSON.parse(k),N=M.type??"unknown";if(O.add(N),N==="thread.started"&&M.thread_id&&!U&&(U=M.thread_id),(N==="item.agentMessage.delta"||N==="item/agentMessage/delta")&&M.delta?.text&&(W.push(M.delta.text),l?.({type:"delta",jobId:s,text:M.delta.text},s)),(N==="item.reasoning.delta"||N==="item/reasoning/delta")&&M.delta?.text&&l?.({type:"thinking",jobId:s,text:M.delta.text},s),(N==="item.started"||N==="item/started")&&M.item){let $=M.item.type;if($==="command_execution"){let T=M.item.command,L=T?Ft(T):void 0,_=Wt(t),ee=new Map;for(let le of _?.changedFiles??[])ee.set(le,Xe(t,le));typeof M.item.id=="string"&&Q.set(M.item.id,{...T?{rawCommand:T}:{},...L?{command:L}:{},..._?{beforeWorktree:_}:{},beforeSnapshots:ee});let y=L?`Bash: ${L.split(`
31
- `)[0].slice(0,80)}`:"Bash";w.push(y),l?.({type:"tool_use",jobId:s,tool:"Bash",...L?{content:L}:{}},s)}else if($==="file_change"){let T=M.item.filename||M.item.path;T&&!V.has(T)&&V.set(T,Xe(t,T)),w.push(T?`Edit ${T.split("/").pop()}`:"Edit"),l?.({type:"tool_use",jobId:s,tool:"Edit",...T?{file:T}:{}},s)}else if($==="file_read"){let T=M.item.filename||M.item.path;w.push(T?`Read ${T.split("/").pop()}`:"Read"),l?.({type:"tool_use",jobId:s,tool:"Read",...T?{file:T}:{}},s)}else if($==="web_search")w.push("WebSearch"),l?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if($==="mcp_tool_call"){let T=M.item.tool_name||M.item.name||"MCP";w.push(T),l?.({type:"tool_use",jobId:s,tool:T},s)}}if((N==="item.completed"||N==="item/completed")&&M.item){if(M.item.type==="agent_message"){let $=M.item.text;typeof $=="string"&&$&&(W.push($),l?.({type:"delta",jobId:s,text:$},s))}else if(M.item.type==="reasoning"){let $=M.item.text;typeof $=="string"&&$&&l?.({type:"thinking",jobId:s,text:$},s)}else if(M.item.type==="file_change"&&Array.isArray(M.item.changes))for(let $ of M.item.changes){let T=$.path||$.filename,L=$.kind==="add"?"Write":"Edit";if(T){w.push(`${L} ${T.split("/").pop()}`),l?.({type:"tool_use",jobId:s,tool:L,file:T},s);let _=$,ee=typeof _.kind=="string"?_.kind:void 0,y=Xs(ee),le=V.get(T),ie=Xe(t,T);q.push({sequence:q.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:y,filePath:T,...le?{before:le}:{},...ie?{after:ie}:{},...Lt(_)?{patch:Lt(_)}:{},...ee?{rawKind:ee}:{}}),V.set(T,ie)}}else if(M.item.type==="command_execution"){let $=typeof M.item.id=="string"?M.item.id:void 0,T=$?Q.get($):void 0,L=typeof M.item.command=="string"?M.item.command:T?.rawCommand,_=L?Ft(L):T?.command,ee=Wt(t);if(Vs(T?.beforeWorktree,ee)){let y=[...new Set([...T?.beforeWorktree?.changedFiles??[],...ee?.changedFiles??[]])],le=typeof M.item.aggregated_output=="string"?wt(M.item.aggregated_output,qs):void 0,ie=typeof M.item.exit_code=="number"?M.item.exit_code:M.item.exit_code===null?null:void 0,G=typeof M.item.status=="string"?M.item.status:void 0;q.push({sequence:q.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...L?{rawCommand:L}:{},..._?{command:_}:{},...ie!==void 0?{exitCode:ie}:{},...G?{status:G}:{},...le?{output:le.text}:{},...le?.truncated?{outputTruncated:!0}:{},...T?.beforeWorktree?{beforeWorktree:T.beforeWorktree}:{},...ee?{afterWorktree:ee}:{},...y.length>0?{touchedFiles:Zs(t,y,T?.beforeSnapshots??new Map)}:{}})}$&&Q.delete($)}}N==="turn.failed"&&(K=!0,z=M.error?.message||M.message||"Turn failed")}catch{}});let A=[];E.stderr?.on("data",k=>{A.push(k.toString())}),E.on("close",k=>{Z.close(),W.length===0&&O.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...O].join(", ")}`),k!==0&&k!==null&&(K=!0,z=A.join("")||`Codex process exited with code ${k}`),J({sessionId:U,text:W.join(""),success:!K,error:K?z:void 0,editEvents:q.length>0?q:void 0,toolsUsed:w.length>0?w:void 0})}),E.on("error",k=>{K=!0,z=k.message,J({sessionId:U,text:W.join(""),success:!1,error:z,editEvents:q.length>0?q:void 0,toolsUsed:w.length>0?w:void 0})})});return{process:E,result:B}}import{spawn as eo}from"child_process";import{createInterface as to}from"readline";function Yt(s,e){let n=s.trim()||"Copilot CLI failed",t=n.toLowerCase();return t.includes("no authentication information")||t.includes("not authenticated")||t.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:t.includes("model")&&(t.includes("not available")||t.includes("not found")||t.includes("disabled")||t.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:n}:t.includes("mcp")&&(t.includes("blocked")||t.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:t.includes("permission")||t.includes("denied")||t.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function Vt(s,e){let{prompt:n,projectRoot:t,resumeSessionId:o,model:i,timeoutMs:a=3e5,onEvent:l,copilotPath:f="copilot"}=e,v=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];o&&v.push(`--resume=${o}`),i&&v.push("--model",i),v.push("-p",n);let x=eo(f,v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),E=new Promise(B=>{let J,U=[],W=[],w=!1,q="",V=!1,Q=setTimeout(()=>{V=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},a),K=to({input:x.stdout}),z=new Set,Z=[];K.on("line",A=>{if(A.trim())try{let k=JSON.parse(A),M=Ce(k);z.add(M),Z.length<5&&so(M)&&Z.push(A.slice(0,800));let N=Ae(k,["sessionId","session_id","id"],["session","conversation","thread"]);N&&!J&&(J=N);let $=no(k,U.length===0);$&&(U.push($),l?.({type:"delta",jobId:s,text:$},s));let T=oo(k);T&&l?.({type:"thinking",jobId:s,text:T},s);let L=ro(k);L&&(W.push(L.label),l?.({type:"tool_use",jobId:s,tool:L.tool,...L.file?{file:L.file}:{},...L.content?{content:L.content}:{}},s));let _=io(k);_&&(w=!0,q=_)}catch{}});let O=[];x.stderr?.on("data",A=>{O.push(A.toString())}),x.on("close",A=>{clearTimeout(Q),K.close(),U.length===0&&z.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...z].join(", ")}`),Z.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${Z.join(`
32
- `)}`)),V?(w=!0,q=`Timed out after ${Math.round(a/6e4)} minutes`):A!==0&&A!==null&&(w=!0,q=O.join("").trim()||q||`Copilot process exited with code ${A}`);let k=w?Yt(q,i):null;B({sessionId:J,text:U.join(""),success:!w,error:k?.message,errorCode:k?.code,recoverableError:k?.recoverable,provider:"copilot",toolsUsed:W.length>0?W:void 0})}),x.on("error",A=>{clearTimeout(Q);let k=Yt(A.message,i);B({sessionId:J,text:U.join(""),success:!1,error:k.message,errorCode:k.code,recoverableError:k.recoverable,provider:"copilot",toolsUsed:W.length>0?W:void 0})})});return{process:x,result:E}}function Ce(s){if(typeof s.type=="string")return s.type;let e=s.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof s.event=="string"?s.event:"unknown"}function no(s,e=!1){let n=Ce(s).toLowerCase(),t=s.update,o=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&o?.type==="text"&&typeof o.text=="string")return o.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return me(s.delta)??me(s.content)??me(s.message);if(n==="assistant.message"&&e)return me(s.message)??me(s.content)??me(s);if(n==="result"&&e)return me(s.result)??me(s.output)??me(s.message)??me(s);let i=s.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof s.text=="string"&&St(s))return s.text;if(typeof s.message=="string"&&St(s))return s.message;if(typeof s.delta=="string"&&St(s))return s.delta}function me(s){if(typeof s=="string")return s;if(!s)return;if(Array.isArray(s)){let n=s.map(me).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof s!="object")return;let e=s;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=me(e[n]);if(t)return t}}function so(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function oo(s){if(typeof s.thinking=="string")return s.thinking;if(typeof s.reasoning=="string")return s.reasoning;let e=s.update;if(e?.sessionUpdate==="reasoning_chunk"){let n=e.content;if(typeof n?.text=="string")return n.text}}function ro(s){let e=Ae(s,["tool","toolName","tool_name","name"]),n=Ae(s,["command","cmd"]),t=Ae(s,["file","path","filename","filePath"]),o=Ce(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
- `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let i=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function io(s){if(typeof s.error=="string")return s.error;if(s.error&&typeof s.error=="object"){let e=s.error;if(typeof e.message=="string")return e.message}if(typeof s.message=="string"&&Ce(s).toLowerCase().includes("error"))return s.message}function Ae(s,e,n=[]){for(let t of e){let o=s[t];if(typeof o=="string")return o}for(let[t,o]of Object.entries(s)){if(!o||typeof o!="object"||n.length>0&&!n.some(a=>t.toLowerCase().includes(a)))continue;let i=Ae(o,e);if(i)return i}}function St(s){let e=Ce(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{execFile as ao}from"child_process";import{copyFile as Kt,mkdir as Zt,readdir as lo,readFile as co,writeFile as uo}from"fs/promises";import{join as Ie}from"path";var Ve=class{constructor(e){this.projectRoot=e;let n=Ie(e,".popmelt");this.decisionsDir=Ie(n,"decisions"),this.screenshotsDir=Ie(n,"screenshots")}async persist(e,n,t){try{await Zt(this.decisionsDir,{recursive:!0}),await Zt(this.screenshotsDir,{recursive:!0});try{await Kt(n,Ie(this.screenshotsDir,`s-${e.id}.webp`))}catch{}for(let o=0;o<t.length;o++)try{let i=e.pastedImagePaths[o];i&&await Kt(t[o],Ie(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await uo(Ie(this.decisionsDir,`d-${e.id}.json`),JSON.stringify(e,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await lo(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await co(Ie(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}captureGitDiff(e){return new Promise(n=>{ao("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as $e,readFile as en,writeFile as _e}from"fs/promises";import{join as Oe}from"path";var po=80,fo=24,tn=1e3,Ke=class{constructor(e){this.evalsDir=Oe(e,".popmelt","evals"),this.suitePath=Oe(this.evalsDir,"evals.json"),this.runsPath=Oe(this.evalsDir,"runs.json"),this.screenshotsDir=Oe(this.evalsDir,"screenshots")}async loadSuite(){try{let e=await en(this.suitePath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.cases))return n}catch{}return{version:1,updatedAt:0,cases:[]}}async loadRuns(){try{let e=await en(this.runsPath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.runs))return n}catch{}return{version:1,updatedAt:0,runs:[]}}async loadSuiteWithRuns(){let[e,n]=await Promise.all([this.loadSuite(),this.loadRuns()]);return{...e,runs:n.runs}}async loadSuiteWithCurrentRuns(e){let n=await this.loadSuiteWithRuns();return e?{...n,runs:n.runs.filter(t=>t.codeFingerprint===e)}:n}async writeSynthesized(e){let n=await this.loadSuite(),t=new Map(n.cases.map(a=>[a.id,a])),o=new Set;for(let a of e){let l=t.get(a.id);l&&(l.title!==a.title||l.prompt!==a.prompt||JSON.stringify(l.assertions)!==JSON.stringify(a.assertions))&&o.add(a.id),t.set(a.id,a)}let i={version:1,updatedAt:Date.now(),cases:[...t.values()]};return await $e(this.evalsDir,{recursive:!0}),await _e(this.suitePath,JSON.stringify(i,null,2)),o.size>0&&await this.invalidateRunsForEvals(o),i}async updateCase(e,n){let t=await this.loadSuite(),o=n.title!==void 0||n.assertions!==void 0,i=t.cases.map(l=>l.id===e?{...l,...n.status?{status:n.status}:{},...n.title?{title:n.title}:{},...n.assertions?{assertions:n.assertions}:{}}:l),a=i.find(l=>l.id===e)??null;return a?(await $e(this.evalsDir,{recursive:!0}),await _e(this.suitePath,JSON.stringify({version:1,updatedAt:Date.now(),cases:i},null,2)),o&&await this.invalidateRunsForEvals(new Set([e])),a):null}async invalidateRunsForEvals(e){let t=(await this.loadRuns()).runs.filter(i=>!e.has(i.evalId)),o={version:1,updatedAt:Date.now(),runs:t};return await $e(this.evalsDir,{recursive:!0}),await _e(this.runsPath,JSON.stringify(o,null,2)),o}async writeRun(e){let n=await this.loadRuns(),t=[e,...n.runs.filter(i=>i.id!==e.id)].slice(0,200),o={version:1,updatedAt:Date.now(),runs:t};return await $e(this.evalsDir,{recursive:!0}),await _e(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await $e(this.screenshotsDir,{recursive:!0}),await _e(Oe(this.screenshotsDir,`eval-${e}.webp`),n),`evals/screenshots/eval-${e}.webp`}async findCase(e){return(await this.loadSuite()).cases.find(t=>t.id===e)??null}};function nn(s){let e=s.match(/<evals>\s*([\s\S]*?)\s*<\/evals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?rn(t):null}catch{return null}}function sn(s){let e=s.match(/<eval_proposals>\s*([\s\S]*?)\s*<\/eval_proposals>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.evals)?n.evals:null;return t?rn(t,"pending"):null}catch{return null}}function on(s,e){let n=s.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),o=wo(t.assertionResults,e),i=So(o);return{status:i,summary:ge(t.summary)||dn(i),assertionResults:o,tooling:xo(t.tooling)}}catch{}return{status:"needs_review",summary:Ze(s.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function rn(s,e="approved"){let n=[];return s.forEach((t,o)=>{if(!t||typeof t!="object")return;let i=t,a=ge(i.title),l=ge(i.prompt),f=ge(i.rationale),v=Ee(i.assertions);if(!a||!l||v.length===0)return;let x=go(i.category),E=bo(ge(i.id))||`eval-${un(a).slice(0,32)||o+1}`,B=yo(i.status)??e;n.push({id:E,title:a,status:B,category:x,prompt:l,assertions:v,rationale:f||"Inferred from Popmelt design history.",sourceDecisionIds:Ee(i.sourceDecisionIds),sourceThreadIds:Ee(i.sourceThreadIds)})}),n}function an(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,po),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,fo);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
34
-
35
- The designer does NOT work eval-first. They use annotations and conversation threads to zhuzh the UI over time. Your job is to infer useful eval proposals from that trail. The developer will reject, refine, or approve proposals in this thread. Do not write files or run commands.
36
-
37
- ## Current Design Model
38
- \`\`\`json
39
- ${JSON.stringify(s.model??null,null,2)}
40
- \`\`\`
41
-
42
- ## Existing Eval Suite
43
- \`\`\`json
44
- ${JSON.stringify(s.existingSuite,null,2)}
45
- \`\`\`
46
-
47
- ## Recent Decisions
48
- ${e.map(ho).join(`
49
-
50
- `)||"No decisions found."}
51
-
52
- ## Recent Threads
53
- ${n.map(mo).join(`
54
-
55
- `)||"No threads found."}
56
-
57
- ## Instructions
58
- 1. Infer evals that encode reusable taste, design judgment, product behavior, or interaction expectations.
59
- 2. Prefer proposals backed by multiple decisions, rich thread context, or explicit approved/resolved outcomes.
60
- 3. Avoid one-off implementation chores, temporary bug fixes, vague preferences, or evals that cannot be checked later.
61
- 4. Cite source decision ids and thread ids for each proposal.
62
- 5. Present proposals as clear text first. Group them by Component, Layout, Copy, Interaction, Visual, and Workflow.
63
- 6. Ask the developer what to approve, reject, or adjust.
64
- 7. Include a machine-readable <eval_proposals> block containing the same proposals as pending eval JSON. These will be saved as draft proposals for panel review.
65
- 8. Tell the developer that the proposals have been saved to the Eval panel for accept/reject review.
66
- 9. Do NOT output an <evals> block yet. First get the developer's approval.
67
-
68
- ## After Approval
69
- When the developer approves or asks you to save the final set, output a complete JSON array inside <evals> tags. Each object must use this shape:
70
-
71
- \`\`\`json
72
- {
73
- "id": "eval-short-stable-id",
74
- "title": "Short human-readable name",
75
- "status": "approved",
76
- "category": "component",
77
- "prompt": "The eval instruction an agent should satisfy.",
78
- "assertions": ["Observable expectation 1", "Observable expectation 2"],
79
- "rationale": "Why this eval represents the designer's taste.",
80
- "sourceDecisionIds": ["decision-id"],
81
- "sourceThreadIds": ["thread-id"]
82
- }
83
- \`\`\`
84
-
85
- Allowed categories: component, layout, copy, interaction, visual, workflow.
86
- Return only the <evals> block after approval.
87
-
88
- ## First Response Structured Block
89
- At the end of your first proposal response, output a JSON array inside <eval_proposals> tags using the same schema, but with "status": "pending".`}function ln(s){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
28
+ </html>`}var Gs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Vs=new Set(["default","flex","fast","priority"]);function gt(o){let e=typeof o.reasoningEffort=="string"&&Gs.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Vs.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function ln(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as Ks}from"child_process";import{createInterface as Qs}from"readline";var Xs=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),qo=1e5;function Ys(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Xs.has(n))return;let t;if(o.name==="Write"&&typeof o.input?.content=="string"?t=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(t=o.input.new_string),!!t)return t.length>qo?t.slice(0,qo)+`
29
+ \u2026[truncated]`:t}function pn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:v,timeoutMs:R=3e5,onEvent:b}=e,I=[];d?I.push("--resume",d,"-p",n):I.push("-p",n),I.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(s)),l&&I.push("--model",l),v&&I.push("--effort",v);for(let h of i)I.push("--allowedTools",h);let g=Ks(c,I,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(h=>{let f,y=[],x=[],S=[],A=!1,J="",_,N,T=!1,B=setTimeout(()=>{T=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},R),W=Qs({input:g.stdout}),ee=new Set;W.on("line",te=>{if(te.trim())try{let ne=JSON.parse(te);ne.session_id&&!f&&(f=ne.session_id);let ge=ne.type??(ne.event?.type?`event.${ne.event.type}`:"unknown");if(ee.add(ge),ne.type==="result"&&ne.result&&y.length===0){let X=typeof ne.result=="string"?ne.result:"";X&&(y.push(X),b?.({type:"delta",jobId:o,text:X},o))}if(ne.type==="assistant"&&Array.isArray(ne.message?.content)){typeof ne.error=="string"&&(_=ne.error);for(let X of ne.message.content){if(X.type==="text"&&X.text&&(y.push(X.text),b?.({type:"delta",jobId:o,text:X.text},o)),X.type==="tool_use"&&X.name){let G=X.input?.file_path||X.input?.path||void 0,U=Ys(X);if(b?.({type:"tool_use",jobId:o,tool:X.name,...G?{file:G}:{},...U?{content:U}:{}},o),X.name==="Edit"&&X.input?.file_path){let he={tool:"Edit",file_path:X.input.file_path,old_string:X.input.old_string,new_string:X.input.new_string,replace_all:X.input.replace_all};x.push(he),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:he.file_path,oldString:typeof he.old_string=="string"?he.old_string:void 0,newString:typeof he.new_string=="string"?he.new_string:void 0,replaceAll:typeof he.replace_all=="boolean"?he.replace_all:void 0})}else X.name==="Write"&&X.input?.file_path&&(x.push({tool:"Write",file_path:X.input.file_path,content:X.input.content}),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:X.input.file_path,content:typeof X.input.content=="string"?X.input.content:void 0}))}X.type==="thinking"&&X.thinking&&b?.({type:"thinking",jobId:o,text:X.thinking},o)}}ne.type==="result"&&ne.is_error===!0&&(A=!0,typeof ne.error=="string"&&(_=ne.error),typeof ne.result=="string"&&(N=ne.result)),ne.type==="user"&&ne.tool_use_result?.file?.filePath&&b?.({type:"tool_use",jobId:o,tool:"Read",file:ne.tool_use_result.file.filePath},o)}catch{}});let H=[];g.stderr?.on("data",te=>{H.push(te.toString())}),g.on("close",te=>{if(clearTimeout(B),W.close(),y.length===0&&ee.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...ee].join(", ")}`),T)A=!0,J=`Timed out after ${Math.round(R/6e4)} minutes`;else if(te!==0&&te!==null){A=!0;let ge=H.join("").trim(),X=y.join("").trim(),G=y.length===0&&ee.size>0?` (no text captured, event types: ${[...ee].join(", ")})`:"";J=ge||N||X||`Claude process exited with code ${te}${G}`}A&&!J&&N&&(J=N);let ne=Zs(J,_);h({sessionId:f,text:y.join(""),success:!A,error:A?ne.message:void 0,errorCode:A?ne.code:void 0,recoverableError:A?ne.recoverable:void 0,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})}),g.on("error",te=>{clearTimeout(B),A=!0,J=te.message,h({sessionId:f,text:y.join(""),success:!1,error:J,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})})});return{process:g,result:p}}function Zs(o,e){let n=o.trim()||"Claude CLI failed",t=`${e??""} ${n}`.toLowerCase();return t.includes("authentication_failed")||t.includes("not logged in")||t.includes("please run /login")||t.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:t.includes("model")&&(t.includes("not found")||t.includes("unknown")||t.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as ei,spawnSync as Qo}from"child_process";import{readFileSync as ti,statSync as ni}from"fs";import{basename as oi,extname as ri,isAbsolute as si,relative as Xo,resolve as ii}from"path";import{createInterface as ai}from"readline";function Wo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Ho=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),to=2e5,ci=1e5,Yo=2e5;function Zo(o){let e=oi(o).toLowerCase(),n=ri(o).toLowerCase();return Ho.has(n)||Ho.has(e)}function Lt(o,e){let n=si(e)?e:ii(o,e),t=Xo(o,n);return t===""||t.startsWith("..")?null:n}function un(o,e){if(!Zo(e))return;let n=Lt(o,e);if(n)try{let t=ni(n);return t.isFile()?t.size>to?{exists:!0,truncated:!0}:{exists:!0,content:ti(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function di(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function li(o){let e=o?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Go(o){return di(o,["patch","diff","unifiedDiff","unified_diff"])}function no(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Vo(o,e){let n=Qo("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Yo+65536});return n.status!==0?null:n.stdout??""}function pi(o){let e=new Set;for(let n of o.split(`
30
+ `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let s of r)s&&e.add(s)}return[...e]}function Ko(o){let e=Vo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Vo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=no(n,Yo);return{status:e,changedFiles:pi(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function ui(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function mi(o,e){if(!Zo(e))return;let n=Lt(o,e);if(!n)return;let t=Xo(o,n);if(t===""||t.startsWith(".."))return;let r=Qo("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:to+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=no(s,to);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function fi(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):mi(o,t),s=un(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function mn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,v=[];if(s){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let I of l)v.push("-c",I);i&&v.push("-m",i),v.push(s),v.push(n),r&&v.push("--image",r)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let I of l)v.push("-c",I);i&&v.push("-m",i),v.push(n),r&&v.push("--image",r)}let R=ei("codex",v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),b=new Promise(I=>{let g,p=[],h=[],f=[],y=new Map,x=new Map,S=!1,A="",J=ai({input:R.stdout}),_=new Set;J.on("line",T=>{if(T.trim())try{let B=JSON.parse(T),W=B.type??"unknown";if(_.add(W),W==="thread.started"&&B.thread_id&&!g&&(g=B.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),c?.({type:"delta",jobId:o,text:B.delta.text},o)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&B.delta?.text&&c?.({type:"thinking",jobId:o,text:B.delta.text},o),(W==="item.started"||W==="item/started")&&B.item){let ee=B.item.type;if(ee==="command_execution"){let H=B.item.command,te=H?Wo(H):void 0,ne=Ko(t),ge=new Map;for(let G of ne?.changedFiles??[])ge.set(G,un(t,G));typeof B.item.id=="string"&&x.set(B.item.id,{...H?{rawCommand:H}:{},...te?{command:te}:{},...ne?{beforeWorktree:ne}:{},beforeSnapshots:ge});let X=te?`Bash: ${te.split(`
31
+ `)[0].slice(0,80)}`:"Bash";h.push(X),c?.({type:"tool_use",jobId:o,tool:"Bash",...te?{content:te}:{}},o)}else if(ee==="file_change"){let H=B.item.filename||B.item.path;H&&!y.has(H)&&y.set(H,un(t,H)),h.push(H?`Edit ${H.split("/").pop()}`:"Edit");let te=H?Lt(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...te?{file:te}:{}},o)}else if(ee==="file_read"){let H=B.item.filename||B.item.path;h.push(H?`Read ${H.split("/").pop()}`:"Read");let te=H?Lt(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...te?{file:te}:{}},o)}else if(ee==="web_search")h.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(ee==="mcp_tool_call"){let H=B.item.tool_name||B.item.name||"MCP";h.push(H),c?.({type:"tool_use",jobId:o,tool:H},o)}}if((W==="item.completed"||W==="item/completed")&&B.item){if(B.item.type==="agent_message"){let ee=B.item.text;typeof ee=="string"&&ee&&(p.push(ee),c?.({type:"delta",jobId:o,text:ee},o))}else if(B.item.type==="reasoning"){let ee=B.item.text;typeof ee=="string"&&ee&&c?.({type:"thinking",jobId:o,text:ee},o)}else if(B.item.type==="file_change"&&Array.isArray(B.item.changes))for(let ee of B.item.changes){let H=ee.path||ee.filename,te=ee.kind==="add"?"Write":"Edit";if(H){h.push(`${te} ${H.split("/").pop()}`);let ne=Lt(t,H)??H;c?.({type:"tool_use",jobId:o,tool:te,file:ne},o);let ge=ee,X=typeof ge.kind=="string"?ge.kind:void 0,G=li(X),U=y.get(H),he=un(t,H);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:H,...U?{before:U}:{},...he?{after:he}:{},...Go(ge)?{patch:Go(ge)}:{},...X?{rawKind:X}:{}}),y.set(H,he)}}else if(B.item.type==="command_execution"){let ee=typeof B.item.id=="string"?B.item.id:void 0,H=ee?x.get(ee):void 0,te=typeof B.item.command=="string"?B.item.command:H?.rawCommand,ne=te?Wo(te):H?.command,ge=Ko(t);if(ui(H?.beforeWorktree,ge)){let X=[...new Set([...H?.beforeWorktree?.changedFiles??[],...ge?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?no(B.item.aggregated_output,ci):void 0,U=typeof B.item.exit_code=="number"?B.item.exit_code:B.item.exit_code===null?null:void 0,he=typeof B.item.status=="string"?B.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...te?{rawCommand:te}:{},...ne?{command:ne}:{},...U!==void 0?{exitCode:U}:{},...he?{status:he}:{},...G?{output:G.text}:{},...G?.truncated?{outputTruncated:!0}:{},...H?.beforeWorktree?{beforeWorktree:H.beforeWorktree}:{},...ge?{afterWorktree:ge}:{},...X.length>0?{touchedFiles:fi(t,X,H?.beforeSnapshots??new Map)}:{}})}ee&&x.delete(ee)}}W==="turn.failed"&&(S=!0,A=B.error?.message||B.message||"Turn failed")}catch{}});let N=[];R.stderr?.on("data",T=>{N.push(T.toString())}),R.on("close",T=>{J.close(),p.length===0&&_.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[..._].join(", ")}`),T!==0&&T!==null&&(S=!0,A=N.join("")||`Codex process exited with code ${T}`),I({sessionId:g,text:p.join(""),success:!S,error:S?A:void 0,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})}),R.on("error",T=>{S=!0,A=T.message,I({sessionId:g,text:p.join(""),success:!1,error:A,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})})});return{process:R,result:b}}import{spawn as hi}from"child_process";import{createInterface as gi}from"readline";function er(o,e){let n=o.trim()||"Copilot CLI failed",t=n.toLowerCase();return t.includes("no authentication information")||t.includes("not authenticated")||t.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:t.includes("model")&&(t.includes("not available")||t.includes("not found")||t.includes("disabled")||t.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:n}:t.includes("mcp")&&(t.includes("blocked")||t.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:t.includes("permission")||t.includes("denied")||t.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function tr(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:s,timeoutMs:i=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),s&&l.push("--model",s),l.push("-p",n);let v=hi(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(b=>{let I,g=[],p=[],h=!1,f="",y=!1,x=setTimeout(()=>{y=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},i),S=gi({input:v.stdout}),A=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Ut(T);A.add(B),J.length<5&&vi(B)&&J.push(N.slice(0,800));let W=zt(T,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!I&&(I=W);let ee=yi(T,g.length===0);ee&&(g.push(ee),c?.({type:"delta",jobId:o,text:ee},o));let H=wi(T);H&&c?.({type:"thinking",jobId:o,text:H},o);let te=Ii(T);te&&(p.push(te.label),c?.({type:"tool_use",jobId:o,tool:te.tool,...te.file?{file:te.file}:{},...te.content?{content:te.content}:{}},o));let ne=bi(T);ne&&(h=!0,f=ne)}catch{}});let _=[];v.stderr?.on("data",N=>{_.push(N.toString())}),v.on("close",N=>{clearTimeout(x),S.close(),g.length===0&&A.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),J.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${J.join(`
32
+ `)}`)),y?(h=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(h=!0,f=_.join("").trim()||f||`Copilot process exited with code ${N}`);let T=h?er(f,s):null;b({sessionId:I,text:g.join(""),success:!h,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),v.on("error",N=>{clearTimeout(x);let T=er(N.message,s);b({sessionId:I,text:g.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:v,result:R}}function Ut(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function yi(o,e=!1){let n=Ut(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Fe(o.delta)??Fe(o.content)??Fe(o.message);if(n==="assistant.message"&&e)return Fe(o.message)??Fe(o.content)??Fe(o);if(n==="result"&&e)return Fe(o.result)??Fe(o.output)??Fe(o.message)??Fe(o);let s=o.content;if(s?.type==="text"&&typeof s.text=="string")return s.text;if(typeof o.text=="string"&&oo(o))return o.text;if(typeof o.message=="string"&&oo(o))return o.message;if(typeof o.delta=="string"&&oo(o))return o.delta}function Fe(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Fe).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Fe(e[n]);if(t)return t}}function vi(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function wi(o){if(typeof o.thinking=="string")return o.thinking;if(typeof o.reasoning=="string")return o.reasoning;let e=o.update;if(e?.sessionUpdate==="reasoning_chunk"){let n=e.content;if(typeof n?.text=="string")return n.text}}function Ii(o){let e=zt(o,["tool","toolName","tool_name","name"]),n=zt(o,["command","cmd"]),t=zt(o,["file","path","filename","filePath"]),r=Ut(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
+ `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let s=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:s,label:`${s} ${t.split("/").pop()}`,file:t}}}function bi(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&Ut(o).toLowerCase().includes("error"))return o.message}function zt(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(i=>t.toLowerCase().includes(i)))continue;let s=zt(r,e);if(s)return s}}function oo(o){let e=Ut(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as xi,readFile as Si}from"fs/promises";import{join as ro}from"path";var fn=class{constructor(e){let n=ro(e,".popmelt");this.decisionsDir=ro(n,"decisions")}async listDecisionIds(){try{return(await xi(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await Si(ro(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}};function or(o,e){let n=o.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),r=Ai(t.assertionResults,e),s=_i(r);return{status:s,summary:tt(t.summary)||ar(s),assertionResults:r,tooling:Ci(t.tooling)}}catch{}return{status:"needs_review",summary:$i(o.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function rr(o,e){let n=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length?[y.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(y=>y.path),s=[...new Set(r.map(y=>y.map(String).join(".")).filter(Boolean))].map(y=>({kind:"model_path",value:y}));if(s.length===0||o.decisionIds.length===0)return[];let i=new Set(o.decisionIds),c=new Set(s.map(y=>y.value)),d=e.cases.find(y=>y.status!=="rejected"&&(y.sourceDecisionIds.some(x=>i.has(x))||(y.dependencies??[]).some(x=>x.kind==="model_path"&&c.has(x.value)))),l=(o.selectedChanges??[]).find(y=>y.label?.trim())?.label?.trim()??t.find(y=>y.label?.trim())?.label?.trim()??o.title,v=d?.id.startsWith("eval-model-")??!1,R=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length>0?[{path:y.path,value:y.value,label:y.label,detail:y.detail}]:[]),I=(R.length>0?R:t.map(y=>({path:y.path,value:y.value,label:y.label,detail:y.rationale}))).flatMap(y=>Pi(y,o.decisionIds)),g=gn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!v?d.assertions:[],...I,...I.length===0&&g?[g]:[]])],h=s[0].value,f=h.startsWith("components.")?"component":h.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!v?d.title:l,status:"pending",category:d?.category??f,prompt:d&&!v?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!v?d.rationale:Ti(h),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...s].map(y=>[`${y.kind}:${y.value}`,y])).values()]}]}function Pi(o,e){let n=String(o.path[0]??"");if(n==="rules")return ki(o.value,e);if(n==="components"){let i=sr(String(o.path[1]??o.label??"component")),c=hn(o.value),d=c?Wt(c.usage):[];if(d.length>0){let v=ji(d),R=d.length===1?"uses":"use";return[`The ${v} ${R} the same shared implementation for the ${i} pattern.`]}if(c?.shared===!0)return[`The product uses a shared implementation for the ${i} pattern.`];let l=c?tt(c.constraint):"";if(l){let v=Ri(l,i);if(v)return[v]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),c=hn(o.value),d=c&&"value"in c?c.value:o.value,l=Ei(d);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=hn(o.value),r=t?tt(t.text)||tt(t.constraint):typeof o.value=="string"?o.value:"",s=gn(r||o.detail||"");return s?[s]:[]}function ki(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let c=hn(i),d=c?tt(c.text):"";return d?[{text:d,sources:c?Wt(c.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(i=>gn(i.text)).filter(i=>!!i)}function Ri(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?Pt(`Wherever ${qt(n[1])}, the shared ${e} implementation is used instead of ${qt(n[2])}`):gn(o)}function so(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Pt(`${nr(n[1])} is ${qt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Pt(nr(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Pt(`The product uses ${qt(r[1])}`);let s=e.match(/^Do not (.+?)\.?$/i);return s?Pt(`The product does not ${qt(s[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Pt(e)}var gn=so;function Ti(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${sr(e[1]??"component")} contract across its declared product surfaces.`:e[0]==="tokens"?`Protects the ${e.slice(1).join(".")} token from implementation drift.`:e[0]==="rules"?"Protects an enforceable product rule across its declared scope.":"Protects an enforceable product expectation across its declared scope."}function hn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function sr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function ji(o){return o.length<=1?o[0]??"":o.length===2?`${o[0]} and ${o[1]}`:`${o.slice(0,-1).join(", ")}, and ${o.at(-1)}`}function Ei(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function Pt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function nr(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function qt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function ir(o){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
90
34
 
91
35
  ## Eval
92
36
  \`\`\`json
93
- ${JSON.stringify(s.evalCase,null,2)}
37
+ ${JSON.stringify(o.evalCase,null,2)}
94
38
  \`\`\`
95
39
 
96
40
  ## Scope
97
41
  \`\`\`json
98
- ${JSON.stringify(s.scope,null,2)}
42
+ ${JSON.stringify(o.scope,null,2)}
99
43
  \`\`\`
100
44
 
101
45
  ## Current Design Model
102
46
  \`\`\`json
103
- ${JSON.stringify(s.model??null,null,2)}
47
+ ${JSON.stringify(o.model??null,null,2)}
104
48
  \`\`\`
105
49
 
106
50
  ## Evidence
107
- - Current page screenshot: ${s.screenshotPath}
108
- - Chrome DevTools MCP is ${s.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
51
+ - Current page screenshot: ${o.screenshotPath}
52
+ - Chrome DevTools MCP is ${o.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
109
53
 
110
54
  ## Instructions
111
- 1. Evaluate only the current page scope.
112
- 2. Use the screenshot as baseline evidence.
113
- 3. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
114
- 4. Judge each assertion independently as "pass", "fail", or "needs_review".
115
- 5. Keep failures actionable and grounded in observed evidence.
116
- 6. Do not propose visual markers yet.
117
- 7. End with exactly one machine-readable <eval_run_result> block.
118
- 8. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
119
- 9. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
55
+ 1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
56
+ 2. Compare the runtime URL, component evidence, and visible state with the eval's declared scenarios. If the runtime does not satisfy an applicable declared scenario, mark affected assertions "needs_review" and name the scope mismatch instead of guessing.
57
+ 3. Use the screenshot as baseline evidence.
58
+ 4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
59
+ 5. Judge each assertion independently as "pass", "fail", or "needs_review".
60
+ 6. Keep failures actionable and grounded in observed evidence.
61
+ 7. Do not propose visual markers yet.
62
+ 8. End with exactly one machine-readable <eval_run_result> block.
63
+ 9. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
64
+ 10. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
120
65
 
121
66
  The block must be valid JSON with this shape:
122
67
 
@@ -141,106 +86,42 @@ The block must be valid JSON with this shape:
141
86
  \`\`\`
142
87
 
143
88
  Allowed statuses: pass, fail, needs_review.
144
- Allowed chromeDevtools values: available, unavailable, unknown.`}function cn(s){return`You are turning an approved Popmelt taste-model update into draft evals.
145
-
146
- The model is the source of truth. Evals are executable projections of model properties and values. Your job is to translate the approved model proposal into concrete, falsifiable eval proposals that a designer can review in the Eval panel.
89
+ Allowed chromeDevtools values: available, unavailable, unknown.`}function tt(o){return typeof o=="string"?o.trim():""}function Wt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Mi(o){let e=tt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ai(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let s=r,i=tt(s.assertion);return i?{assertion:i,status:Mi(s.status)??"needs_review",summary:tt(s.summary)||ar("needs_review"),evidence:Wt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function _i(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Ci(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=tt(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Wt(e.evidenceTypes).length>0?Wt(e.evidenceTypes):["screenshot"]}}function ar(o){return o==="pass"?"The current page appears to satisfy this eval.":o==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function $i(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Oi}from"crypto";import{mkdir as Di,writeFile as Ji}from"fs/promises";import{join as io}from"path";var yn=class{constructor(e){this.root=io(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=io(this.root,"eval-screenshots"),t=Oi("sha256").update(e).digest("hex"),r=io(n,`${t}.webp`);return await Di(n,{recursive:!0}),await Ji(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as cr}from"crypto";import{mkdir as ao,readFile as co,writeFile as vn}from"fs/promises";import{dirname as lo,join as kt}from"path";var We="[ProjectionWorker]",Ni={version:1,runs:[]},Bi={version:1,updatedAt:0,proposals:[]},Fi=12;function Li(o){return Array.isArray(o)?o.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function dr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function zi(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ui(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let g of s){if(!g||typeof g!="object")continue;let p=g.sources;if(Array.isArray(p))for(let h of p)typeof h=="string"&&t.has(h)&&r.add(h)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,h=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(h)!==JSON.stringify(g)}).length,v=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(v[g])).length,I=Object.keys(c).filter(g=>JSON.stringify(c[g])!==JSON.stringify(R[g])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:I,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function qi(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Wi(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function wn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Wi(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=qi(n)}function lr(o,e){let n=o;for(let r=0;r<e.length-1;r++){let s=n[String(e[r])];if(!s||typeof s!="object")return;n=s}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Hi(o,e){if(!o)return{exists:!1};let n=o;for(let t of e){if(!n||typeof n!="object"||!(String(t)in n))return{exists:!1};n=n[String(t)]}return{exists:!0,value:n}}function Gi(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((n,t)=>JSON.stringify(n)===JSON.stringify(e[t])):!1}function pr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Hi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Gi(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var In=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=kt(e,".popmelt");this.runsPath=kt(t,"projection-runs.json"),this.legacyRunsPath=kt(t,"materialization-runs.json"),this.proposalsPath=kt(t,"projection-queue.json"),this.legacyProposalsPath=kt(t,"model-proposals.json"),this.modelPath=kt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await co(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Li(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let r=t.key.split(".");t.value===null?lr(n,r):wn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Fi),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let s=r.map(g=>g.id);console.log(`${We} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),c=Xi(r,i),d=zi(r,t.totalCandidateDecisionCount,c);n=cr().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:s,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let v=!0,R,b,I;try{let g=`projection-${Date.now()}`,{provider:p,result:h}=this.spawnModelAgent(g,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await h;if(!f.success)v=!1,R=f.error,console.error(`${We} ${p} spawn error:`,R);else{let y=Qi(f.text,s);if(y){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of y)wn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=dr(x.rules));let S=Ui(x,s,i);if(y){let J=[...new Set(y.flatMap(_=>_.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(_=>!J.includes(_))}b=S;let A=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:b,changes:y});I=A.id,console.log(`${We} Created model proposal ${A.id} for ${s.length} decision(s)`)}else v=!1,R="No valid bounded <model-changes> block found in response",console.error(`${We} ${R}`)}}catch(g){v=!1,R=g instanceof Error?g.message:String(g),console.error(`${We} Error:`,R)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:b,proposalId:I}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:v,error:R}),{processedIds:s,success:v,error:R,runId:n,proposalId:I}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=dr(e.rules)),await vn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await ao(lo(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2)),n):{...Ni,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(s=>s.authorityStatus==="accepted"&&Array.isArray(s.changes)&&s.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Bi,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let s=structuredClone(t);for(let i of r.changes??[])wn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?lr(i,d.path):wn(i,d.path,d.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let c=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(c.evalId),s.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:cr().slice(0,8),status:"pending",title:Vi(e.proposedModel),summary:e.outputStats?`Proposes ${e.outputStats.ruleCount} rule, ${e.outputStats.componentCount} component, and ${e.outputStats.tokenSectionCount} token change${e.outputStats.ruleCount+e.outputStats.componentCount+e.outputStats.tokenSectionCount===1?"":"s"} from ${e.decisionIds.length} accepted decision${e.decisionIds.length===1?"":"s"}.`:Ki(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(s=>s.id!==e?s:(r={...s,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await ao(lo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await vn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await ao(lo(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await co(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await co(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return s==="codex"?{provider:"codex",...mn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:ln(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...pn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:s==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:i})})}};function Vi(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Ki(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Qi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,c)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let d=i;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(R=>typeof R=="string"||typeof R=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let v=Array.isArray(d.decisionIds)?d.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Xi(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
90
+ Kind: ${s.kind}
91
+ Claim: ${s.claim}
92
+ ${s.rationale?`Rationale: ${s.rationale}`:""}
93
+ Subjects: ${s.subjects.map(i=>`${i.role}:${i.subjectId}`).join(", ")}
94
+ Authority: ${s.authority.level}/${s.authority.mode}`).join(`
147
95
 
148
- Do not edit files or run commands.
149
-
150
- ## Approved Model Proposal
151
- \`\`\`json
152
- ${JSON.stringify({id:s.proposal.id,title:s.proposal.title,summary:s.proposal.summary,decisionIds:s.proposal.decisionIds,proposedModel:s.proposal.proposedModel},null,2)}
153
- \`\`\`
154
-
155
- ## Current Applied Model
156
- \`\`\`json
157
- ${JSON.stringify(s.currentModel??null,null,2)}
158
- \`\`\`
159
-
160
- ## Existing Eval Suite
161
- \`\`\`json
162
- ${JSON.stringify(s.existingSuite,null,2)}
163
- \`\`\`
164
-
165
- ## Instructions
166
- 1. Generate only evals that directly project the approved model proposal into observable checks.
167
- 2. Prefer a small number of durable evals over broad coverage. Avoid duplicates of existing evals.
168
- 3. Each eval should include concise assertions that can be judged on a page or codebase.
169
- 4. Set every generated eval status to "pending" so the designer can approve, edit, or reject it.
170
- 5. Cite the proposal's decision IDs in sourceDecisionIds.
171
- 6. End with exactly one <eval_proposals> block containing valid JSON.
172
-
173
- Each eval must use this shape:
174
-
175
- \`\`\`json
176
- {
177
- "id": "eval-short-stable-id",
178
- "title": "Short human-readable name",
179
- "status": "pending",
180
- "category": "component",
181
- "prompt": "The eval instruction an agent should satisfy.",
182
- "assertions": ["Observable expectation 1", "Observable expectation 2"],
183
- "rationale": "Why this eval projects the approved model value.",
184
- "sourceDecisionIds": ["decision-id"],
185
- "sourceThreadIds": ["${s.proposal.threadId??""}"]
186
- }
187
- \`\`\`
188
-
189
- Allowed categories: component, layout, copy, interaction, visual, workflow.
190
-
191
- <eval_proposals>
192
- []
193
- </eval_proposals>`}function ho(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
194
- `),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
195
- `),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
196
- Thread: ${s.threadId??"none"}
197
- Created: ${new Date(s.createdAt).toISOString()}
198
- URL: ${s.url||"unknown"}
199
- Instructions:
200
- ${Ze(o||"(none)",tn)}
201
- Resolutions:
202
- ${Ze(i||"(none)",tn)}
203
- Files: ${a.length>0?a.join(", "):"none"}`}function mo(s){let n=s.messages.slice(0,2).concat(s.messages.length>4?s.messages.slice(-2):s.messages.slice(2)).map(t=>{let o=t.feedbackSummary??t.replyToQuestion??t.question??t.responseText??"",i=t.resolutions?.map(a=>`${a.status}: ${a.summary}`).join("; ")??"";return`- ${t.role}: ${Ze(o||i||"(no text)",500)}`}).join(`
204
- `);return`### Thread ${s.id}
205
- Messages: ${s.messages.length}
206
- Updated: ${new Date(s.updatedAt).toISOString()}
207
- ${n}`}function ge(s){return typeof s=="string"?s.trim():""}function Ee(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function go(s){let e=ge(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function yo(s){let e=ge(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function vo(s){let e=ge(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function wo(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=ge(i.assertion);return a?{assertion:a,status:vo(i.status)??"needs_review",summary:ge(i.summary)||dn("needs_review"),evidence:Ee(i.evidence)}:null}).filter(o=>o!==null);return t.length>0?t:e.map(o=>({assertion:o,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function So(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function xo(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=ge(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Ee(e.evidenceTypes).length>0?Ee(e.evidenceTypes):["screenshot"]}}function dn(s){return s==="pass"?"The current page appears to satisfy this eval.":s==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function bo(s){return un(s).slice(0,48)}function un(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ze(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as pn}from"crypto";import{mkdir as xt,readFile as et,writeFile as be}from"fs/promises";import{dirname as bt,join as De}from"path";var ae="[Materializer]",fn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},Po={version:1,runs:[]},Io={version:1,updatedAt:0,proposals:[]},ko=12;function Mo(s){return Array.isArray(s)?s.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function Ne(s){let e=[];for(let n of s){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${ae} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${ae} Rule count ${e.length} exceeds cap of 30`),e}function Ro(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Eo(s,e){let n=new Set(e),t=new Set,o=Array.isArray(s.rules)?s.rules:[];for(let l of o){if(!l||typeof l!="object")continue;let f=l.sources;if(Array.isArray(f))for(let v of f)typeof v=="string"&&n.has(v)&&t.add(v)}let i=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?s.tokens:{},a=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?s.components:{};return{ruleCount:o.length,tokenSectionCount:Object.keys(i).length,componentCount:Object.keys(a).length,coveredDecisionIds:[...t],uncoveredDecisionIds:e.filter(l=>!t.has(l))}}function To(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function Ao(s,e,n){let t=s[e];if(t&&typeof t=="object")return t;let o=typeof n=="number"?[]:{};return s[String(e)]=o,o}function Co(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=Ao(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=To(n)}function $o(s,e){let n=s;for(let o=0;o<e.length-1;o++){let i=n[String(e[o])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}var tt=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=De(e,".popmelt");this.indexPath=De(o,"materialized.json"),this.runsPath=De(o,"materialization-runs.json"),this.proposalsPath=De(o,"model-proposals.json"),this.modelPath=De(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await et(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Mo(n.rules)),n}catch{return null}}async addComponent(e){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let t=n.components;return t[e]?{added:!1,alreadyExists:!0}:(t[e]={description:""},await be(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let f=0;f<o.length-1;f++){let v=o[f];(!i[v]||typeof i[v]!="object")&&(i[v]={}),i=i[v]}let a=o[o.length-1],l;try{l=JSON.parse(n)}catch{l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)i[a]=l;else{let f=i[a];f&&typeof f=="object"&&f!==null&&"value"in f?f.value=n:i[a]=n}return await be(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ae} Updated token "${e}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=e.split("."),o=n;for(let a=0;a<t.length-1;a++){let l=t[a];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let i=t[t.length-1];return i in o?(delete o[i],await be(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=n.components;return!t||!t[e]?{removed:!1}:(delete t[e],await be(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(l=>{let f=e.decisions[l];return f?f.status==="applied"||f.status==="merged"||f.status==="rejected"||f.status==="running"||f.status==="queued"||f.status==="proposed"?!1:f.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(l=>l.resolutions.some(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern")),a=i.sort((l,f)=>f.createdAt-l.createdAt).slice(0,ko);return i.length>a.length&&console.log(`${ae} Selected ${a.length}/${i.length} pattern decision(s); remaining decisions stay pending for later runs.`),{decisions:a,totalCandidateDecisionCount:i.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnmaterializedPatternDecisions(),o=t.decisions;if(o.length===0)return{processedIds:[],success:!0};let i=o.map(W=>W.id);console.log(`${ae} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=Do(o,a),f=Ro(o,t.totalCandidateDecisionCount,l);n=pn().slice(0,8);let v={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,decisionIds:i,startedAt:Date.now(),promptStats:f};await this.persistRun(v),await this.updateDecisionStates(i,"running",n);let x=!0,E,B,J;try{let W=`mat-${Date.now()}`,{provider:w,result:q}=this.spawnModelAgent(W,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});v={...v,provider:w},await this.persistRun(v);let V=await q;if(!V.success)x=!1,E=V.error,console.error(`${ae} ${w} spawn error:`,E);else{let Q=nt(V.text);if(Q){Array.isArray(Q.rules)&&(Q.rules=Ne(Q.rules)),B=Eo(Q,i);let K=await this.createModelProposal({decisionIds:i,proposedModel:Q,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});J=K.id,console.log(`${ae} Created model proposal ${K.id} for ${i.length} decision(s)`)}else x=!1,E="No <model> block found in response",console.error(`${ae} ${E}`)}}catch(W){x=!1,E=W instanceof Error?W.message:String(W),console.error(`${ae} Error:`,E)}let U=await this.loadIndex();return U.lastRunAt=Date.now(),U.lastRunDecisionIds=i,U.lastRunError=E??null,await this.persistIndex(U),await this.updateDecisionStates(i,x?"proposed":"failed",n,E),await this.persistRun({...v,status:x?"proposed":"failed",completedAt:Date.now(),error:E,outputStats:B,proposalId:J}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:x,error:E}),{processedIds:i,success:x,error:E,runId:n,proposalId:J}}finally{this.running=!1}}async consolidate(e={}){if(this.running)return{success:!1,error:"Already running"};this.running=!0;try{let n=await this.loadModel();if(!n)return{success:!1,error:"No model exists"};let t=No(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,t,e,{maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[]}),a=await i;if(!a.success)return console.error(`${ae} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=nt(a.text);return l?(Array.isArray(l.rules)&&(l.rules=Ne(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await be(this.modelPath,JSON.stringify(l,null,2)),console.log(`${ae} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${ae} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(n){let t=n instanceof Error?n.message:String(n);return console.error(`${ae} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ne(e.rules)),await be(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ae} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await et(this.indexPath,"utf-8"),n=JSON.parse(e);if(n.version===2&&n.decisions)return this.cachedIndex=n,this.cachedIndex;if(n.version===1&&Array.isArray(n.materializedIds)){let t=Date.now(),o=Object.fromEntries(n.materializedIds.map(i=>[i,{status:"applied",runIds:[],attemptCount:1,updatedAt:t}]));return this.cachedIndex={version:2,decisions:o,lastRunAt:n.lastRunAt??null,lastRunDecisionIds:n.lastRunDecisionIds??[],lastRunError:n.lastRunError??null,materializedIds:n.materializedIds},this.cachedIndex}}catch{return this.cachedIndex={...fn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...fn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}async persistIndex(e){e.materializedIds=Object.entries(e.decisions).filter(([,n])=>n.status==="applied"||n.status==="merged").map(([n])=>n),this.cachedIndex=e;try{await xt(bt(this.indexPath),{recursive:!0}),await be(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write index:`,n)}}async loadRuns(){try{let e=await et(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...Po,runs:[]}}async loadModelProposals(){try{let e=await et(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...Io,proposals:[]}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,o)=>o.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,o)=>t.createdAt-o.createdAt||t.updatedAt-o.updatedAt)}async applyModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;if(n.status==="dismissed")return n;await this.writeModel(n.proposedModel);let t=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(n.decisionIds,"applied",n.runId??e),t}async applySelectedModelProposal(e,n,t){let o=await this.findModelProposal(e);if(!o)return null;if(o.status==="dismissed")return o;let i=await this.loadModel()??{};for(let l of n)!Array.isArray(l.path)||l.path.length===0||(l.remove?$o(i,l.path):Co(i,l.path,l.value));await this.writeModel(i);let a=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0,selectedChanges:t});return await this.updateDecisionStates(o.decisionIds,"applied",o.runId??e),a}async dismissModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;let t=await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()});return await this.updateDecisionStates(n.decisionIds,"rejected",n.runId??e),t}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let o=new Set(t.generatedEvalIds??[]);for(let i of n)o.add(i);return this.updateModelProposal(e,{generatedEvalIds:[...o]})}async createModelProposal(e){let n={id:pn().slice(0,8),status:"pending",title:_o(e.proposedModel),summary:Oo(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,provider:e.provider,model:e.model,proposedModel:e.proposedModel,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(o=>o.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),o=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(o={...i,...n,updatedAt:Date.now()},o)),o?(t.updatedAt=Date.now(),await this.persistModelProposals(t),o):null}async persistModelProposals(e){try{await xt(bt(this.proposalsPath),{recursive:!0}),await be(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(o=>o.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await xt(bt(this.runsPath),{recursive:!0}),await be(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${ae} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let l of e){let f=i.decisions[l],v=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[l]={status:n,runIds:v,error:o,attemptCount:n==="running"?f?.attemptCount??0:(f?.attemptCount??0)+1,updatedAt:a}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",a=this.options.onEvent?(l,f)=>this.options.onEvent?.(l):void 0;return i==="codex"?{provider:"codex",...Ye(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:qe(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${ae} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Qe(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function _o(s){let n=(Array.isArray(s.rules)?s.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Oo(s,e){let n=Array.isArray(s.rules)?s.rules.length:0,t=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?Object.keys(s.tokens).length:0,o=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function nt(s){let e=s.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function Do(s,e){let n=s.map(i=>{let l=i.resolutions.filter(x=>(x.finalScope??x.inferredScope)?.breadth==="pattern").map(x=>{let B=(x.finalScope??x.inferredScope)?.target??"unknown",J=x.filesModified?.join(", ")??"none";return`- **${x.summary}** [scope: pattern/${B}]
208
- Files modified: ${J}`}).join(`
209
- `),f=i.annotations.map(x=>x.instruction).filter(Boolean).join(`
210
- `),v=i.gitDiff?`
211
- \`\`\`diff
212
- ${i.gitDiff.slice(0,2e3)}
213
- \`\`\``:"";return`### Decision ${i.id} (${new Date(i.createdAt).toISOString()})
214
- Page: ${i.url}
215
- ${l}
216
- ${v}
217
- ${f?`
218
- Original instructions:
219
- ${f}`:""}`}).join(`
220
-
221
- `),t=s.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
96
+ `),t=o.map(s=>s.id);return`You are extracting a local design model from accumulated design decisions.
222
97
 
223
98
  ## Instructions
224
99
  1. Review the current model (if any) and the new decisions below.
225
- 2. Determine what design tokens, component patterns, and rules to add or update.
226
- 3. Output the complete updated model as a JSON object inside <model> tags.
227
- 4. Do not edit files or run commands. Return only the <model> block.
100
+ 2. Determine the smallest concrete set of design-token, component-pattern, and rule changes supported by those decisions.
101
+ 3. Attribute every change to one or more accepted decision IDs from this prompt.
102
+ 4. Output no more than 40 changes as a JSON array inside <model-changes> tags.
103
+ 5. Do not edit files or run commands. Return only the <model-changes> block.
228
104
 
229
105
  ${e?`## Current Model
230
106
  \`\`\`json
231
107
  ${JSON.stringify(e,null,2)}
232
108
  \`\`\`
233
109
 
234
- Merge the new decisions into the existing model. Preserve existing entries that are not contradicted by new decisions.`:"No model exists yet. Create one from scratch based on the decisions below."}
110
+ Use this only to understand the existing state and avoid proposing unchanged values.`:"No model exists yet. Propose only the entries directly supported by the accepted decisions below."}
235
111
 
236
- ## Design Decisions to Materialize
112
+ ## Accepted Decisions to Project
237
113
  ${n}
238
114
 
239
115
  ## Output Format
240
- Output the full model inside <model> tags. The model is a JSON object with these sections:
241
- - \`tokens\`: Design tokens (colors, spacing, typography, etc.)
242
- - \`components\`: Component-level patterns (e.g., button styles, card layouts)
243
- - \`rules\`: Array of structured rule objects
116
+ Each change is a JSON object with:
117
+ - \`id\`: stable descriptive identifier for this proposed change
118
+ - \`path\`: JSON path in the derived model; the first segment must be \`tokens\`, \`components\`, or \`rules\`
119
+ - \`label\`: short human-readable label
120
+ - \`value\`: complete JSON value to set at that path
121
+ - \`decisionIds\`: one or more IDs from ${JSON.stringify(t)} that directly support the change
122
+ - \`rationale\`: concise explanation of the projection from decision to model entry
123
+
124
+ For tokens and components, choose the narrowest durable path. For rules, emit a single change at path \`["rules"]\` whose value is the complete next rules array. Preserve unchanged rule IDs and order, and keep the array at 30 rules maximum.
244
125
 
245
126
  ### Rule format
246
127
  Each rule is a JSON object:
@@ -260,163 +141,99 @@ Fields:
260
141
  - **Keep:** Enforceable patterns, constraints, relationships between elements, accessibility requirements.
261
142
 
262
143
  Example:
263
- <model>
264
- {
265
- "tokens": {
266
- "colors": { "primary": "#3b82f6" },
267
- "spacing": {
268
- "sm": "4px",
269
- "md": "8px",
270
- "section-gap": { "value": "32px", "property": "gap", "bindings": ["gap-8"] }
271
- }
272
- },
273
- "components": {
274
- "button": { "padding": "12px 24px", "borderRadius": "8px" }
275
- },
276
- "rules": [
277
- { "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] },
278
- { "id": "e5f6a7b8", "scope": "color", "text": "Primary actions use the primary color token", "sources": ["d-def456"] }
279
- ]
280
- }
281
- </model>
144
+ <model-changes>
145
+ [
146
+ {
147
+ "id": "primary-color",
148
+ "path": ["tokens", "colors", "primary"],
149
+ "label": "Primary color",
150
+ "value": "#3b82f6",
151
+ "decisionIds": [${JSON.stringify(t[0]??"")}],
152
+ "rationale": "The accepted decision establishes this as the shared primary action color."
153
+ }
154
+ ]
155
+ </model-changes>
282
156
 
283
157
  ## Guidelines
284
158
  - Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
285
159
  - Extract clear, enforceable rules into the \`rules\` array as structured objects.
286
- - When merging, new decisions override conflicting older values.
160
+ - Do not silently override conflicting existing values; propose the explicit change for owner review.
287
161
  - Keep the model concise \u2014 only include patterns with clear evidence from decisions.
288
- - Do NOT output resolution or question blocks. Just output the <model> block.
162
+ - Do not emit unchanged entries or copy the complete model.
163
+ - Do NOT output resolution or question blocks. Just output the <model-changes> block.
289
164
  - Spacing tokens can be plain strings ("8px") or objects with code bindings:
290
165
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
291
166
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
292
167
  - bindings: Tailwind class names (without responsive prefixes) that use this token
293
- Include property and bindings when the decision context has class-level evidence.`}function No(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
294
-
295
- ## Current Model
296
- \`\`\`json
297
- ${JSON.stringify(s,null,2)}
298
- \`\`\`
299
-
300
- ## Instructions
301
- 1. Review all current rules.
302
- 2. Merge rules that cover the same concern into single, clear rules.
303
- 3. Remove rules that are:
304
- - Workflow advice ("After SSR fixes, re-verify headless output")
305
- - Instance-level observations ("Footer tagline is 'Design everything.'")
306
- - Restating tokens or components already defined elsewhere in the model
307
- - Procedural instructions rather than design constraints
308
- 4. Output the full model with consolidated rules.
309
- 5. Do not edit files or run commands. Return only the <model> block.
310
-
311
- ## Rule format
312
- Each rule MUST be a JSON object:
313
- { "id": "a1b2c3d4", "scope": "<scope>", "text": "<rule text>", "sources": ["<decision-id>", ...] }
314
-
315
- - \`id\`: 8-char hex. Preserve the ID of the most representative source rule when merging. Generate new 8-char hex IDs for genuinely new rules.
316
- - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
317
- - \`text\`: Clear, enforceable design constraint
318
- - \`sources\`: Merge source arrays when combining rules
319
-
320
- ## Hard cap: 30 rules maximum.
321
-
322
- Prioritize rules that are:
323
- - Enforceable constraints (not preferences)
324
- - Cross-cutting (affect many elements)
325
- - Not already captured by tokens or component definitions in the model
326
-
327
- ## Output
328
- Output the complete model inside <model> tags. Preserve tokens and components as-is \u2014 only rules change.
329
-
330
- <model>
331
- { "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
332
- </model>`}function hn(s){return`You are a design system curator reviewing a project's design model. Your job is to propose improvements to the rules \u2014 merging duplicates, filling gaps, removing noise.
333
-
334
- ## Current Model
335
- \`\`\`json
336
- ${JSON.stringify(s,null,2)}
337
- \`\`\`
338
-
339
- ## Instructions
340
- 1. Review all current rules, tokens, and components.
341
- 2. Propose specific changes \u2014 additions, merges, removals \u2014 with brief reasoning for each.
342
- 3. Present your proposals as clear text so the developer can review them.
343
- 4. Do NOT output a <model> block yet. First get the developer's approval.
344
-
345
- ## Output format
346
- - List each proposed change as a numbered item with a short rationale.
347
- - Group by action: **Merge**, **Add**, **Remove**, **Reword**.
348
- - After your proposals, output a <question> block asking the developer to approve, adjust, or reject.
349
-
350
- Example:
351
- **Merge**
352
- 1. Rules "Body text uses Inter 16px" and "Paragraph text is Inter 16/1.5" \u2192 "Body/paragraph text uses Inter at 16px/1.5" (they say the same thing)
353
-
354
- **Remove**
355
- 2. "After fixing SSR, re-verify headless output" \u2014 workflow advice, not a design constraint
356
-
357
- **Add**
358
- 3. "Primary actions use the primary color token; secondary actions use gray-500" \u2014 implied by token usage but not codified
359
-
360
- <question>
361
- These are my proposed rule changes. Would you like to approve all of them, adjust specific items, or add more? Once you're happy I'll output the final model.
362
- </question>
363
-
364
- ## After approval
365
- When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var st=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let o of this.listeners)o(e,n,t)}cancelJob(e){let n=this.queue.findIndex(o=>o.id===e);if(n>=0){let[o]=this.queue.splice(n,1);return o?(o.status="cancelled",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),o):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"materialize_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as Jo}from"child_process";import{readFile as It}from"fs/promises";import{homedir as rt}from"os";import{join as he}from"path";var kt=/popmelt/i,zo=/chrome|devtools/i;function ke(){return{found:!1,name:null,scope:null,disabled:!1}}function Te(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function Je(s){for(let e of Object.keys(s))if(kt.test(e))return e;return null}async function ot(s){try{let e=await It(s,"utf-8");return JSON.parse(e)}catch{return null}}async function Mt(s){let e=rt(),n=await ot(he(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Je(o.mcpServers);if(i)return Te(i,"user")}if(o.projects&&typeof o.projects=="object"){let a=o.projects[s];if(a&&typeof a=="object"){let l=a;if(l.mcpServers&&typeof l.mcpServers=="object"){let f=Je(l.mcpServers);if(f){let v=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(x=>kt.test(x));return Te(f,"project",v)}}}}}let t=await ot(he(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=Je(o.mcpServers);if(a){let l=await mn(s,a);return Te(a,"mcp.json",l)}}let i=Je(o);if(i&&i!=="mcpServers"){let a=await mn(s,i);return Te(i,"mcp.json",a)}}return ke()}async function mn(s,e){let n=he(s,".claude","settings.local.json"),t=await ot(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var Bo=/^\[mcp_servers\.([^\]]+)\]/;function Fo(s){return s.replace(/^"(.+)"$/,"$1")}function jo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function yn(s){let e=s.split(`
366
- `),n=[],t=null;for(let o of e){let i=o.match(Bo);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
367
- `)}),t={name:i[1],bodyLines:[]}):o.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
368
- `)}),t=null):t&&t.bodyLines.push(o)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
369
- `)}),n}function vn(s){return/enabled\s*=\s*false/i.test(s)}async function Rt(s){let e=process.env.CODEX_HOME||he(rt(),".codex"),n=await gn(he(e,"config.toml"),"user");if(n.found)return n;let t=await gn(he(s,".codex","config.toml"),"project");return t.found?t:ke()}async function Lo(s,e){let n=process.env.CODEX_HOME||he(rt(),".codex"),t=new Set;for(let o of[he(n,"config.toml"),he(s,".codex","config.toml")])try{let i=await It(o,"utf-8");for(let a of yn(i)){if(jo(a.name)||vn(a.body))continue;let l=Fo(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function wn(s){return Lo(s,zo)}async function Et(s,e="copilot"){let n=await Uo(e);if(n.found)return n;let t=process.env.COPILOT_HOME||he(rt(),".copilot"),o=await Pt(he(t,"mcp-config.json"),"user");if(o.found)return o;let i=await Pt(he(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await Pt(he(s,".github","mcp.json"),"mcp.json");return a.found?a:ke()}async function Uo(s){try{let e=await new Promise((n,t)=>{Jo(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return Sn(JSON.parse(e),"user")}catch{return ke()}}async function Pt(s,e){let n=await ot(s);return Sn(n,e)}function Sn(s,e){if(!s||typeof s!="object")return ke();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=Je(t);return o?Te(o,e):ke()}async function gn(s,e){try{let n=await It(s,"utf-8"),t=yn(n);for(let o of t)if(kt.test(o.name)){let i=vn(o.body);return Te(o.name,e,i)}}catch{}return ke()}import{execFile as xn}from"child_process";import{mkdir as Wo,readFile as bn,writeFile as Pn}from"fs/promises";import{homedir as In}from"os";import{dirname as Ho,join as Tt}from"path";var At="https://mcp.popmelt.com/mcp";async function kn(s=At){let e=Tt(In(),".claude.json"),n;try{let o=await bn(e,"utf-8");n=JSON.parse(o)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let o of Object.keys(t))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:s},await Pn(e,JSON.stringify(n,null,2)+`
370
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Mn(s=At){let e=process.env.CODEX_HOME||Tt(In(),".codex"),n=Tt(e,"config.toml"),t;try{t=await bn(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Wo(Ho(n),{recursive:!0});let o=`
168
+ Include property and bindings when the decision context has class-level evidence.`}var bn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as Yi}from"child_process";import{readFile as uo}from"fs/promises";import{homedir as Sn}from"os";import{join as Be}from"path";var mo=/popmelt/i,Zi=/chrome|devtools/i;function yt(){return{found:!1,name:null,scope:null,disabled:!1}}function Rt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Ht(o){for(let e of Object.keys(o))if(mo.test(e))return e;return null}async function xn(o){try{let e=await uo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function fo(o){let e=Sn(),n=await xn(Be(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Ht(r.mcpServers);if(s)return Rt(s,"user")}if(r.projects&&typeof r.projects=="object"){let i=r.projects[o];if(i&&typeof i=="object"){let c=i;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Ht(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(v=>mo.test(v));return Rt(d,"project",l)}}}}}let t=await xn(Be(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Ht(r.mcpServers);if(i){let c=await ur(o,i);return Rt(i,"mcp.json",c)}}let s=Ht(r);if(s&&s!=="mcpServers"){let i=await ur(o,s);return Rt(s,"mcp.json",i)}}return yt()}async function ur(o,e){let n=Be(o,".claude","settings.local.json"),t=await xn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(s=>s===e)}return!1}var ea=/^\[mcp_servers\.([^\]]+)\]/;function ta(o){return o.replace(/^"(.+)"$/,"$1")}function na(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function fr(o){let e=o.split(`
169
+ `),n=[],t=null;for(let r of e){let s=r.match(ea);s?(t&&n.push({name:t.name,body:t.bodyLines.join(`
170
+ `)}),t={name:s[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
171
+ `)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
172
+ `)}),n}function hr(o){return/enabled\s*=\s*false/i.test(o)}async function ho(o){let e=process.env.CODEX_HOME||Be(Sn(),".codex"),n=await mr(Be(e,"config.toml"),"user");if(n.found)return n;let t=await mr(Be(o,".codex","config.toml"),"project");return t.found?t:yt()}async function oa(o,e){let n=process.env.CODEX_HOME||Be(Sn(),".codex"),t=new Set;for(let r of[Be(n,"config.toml"),Be(o,".codex","config.toml")])try{let s=await uo(r,"utf-8");for(let i of fr(s)){if(na(i.name)||hr(i.body))continue;let c=ta(i.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function gr(o){return oa(o,Zi)}async function go(o,e="copilot"){let n=await ra(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Be(Sn(),".copilot"),r=await po(Be(t,"mcp-config.json"),"user");if(r.found)return r;let s=await po(Be(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await po(Be(o,".github","mcp.json"),"mcp.json");return i.found?i:yt()}async function ra(o){try{let e=await new Promise((n,t)=>{Yi(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return yr(JSON.parse(e),"user")}catch{return yt()}}async function po(o,e){let n=await xn(o);return yr(n,e)}function yr(o,e){if(!o||typeof o!="object")return yt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Ht(t);return r?Rt(r,e):yt()}async function mr(o,e){try{let n=await uo(o,"utf-8"),t=fr(n);for(let r of t)if(mo.test(r.name)){let s=hr(r.body);return Rt(r.name,e,s)}}catch{}return yt()}import{execFile as vr}from"child_process";import{mkdir as sa,readFile as wr,writeFile as Ir}from"fs/promises";import{homedir as br}from"os";import{dirname as ia,join as yo}from"path";var vo="https://mcp.popmelt.com/mcp";async function xr(o=vo){let e=yo(br(),".claude.json"),n;try{let r=await wr(e,"utf-8");n=JSON.parse(r)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let r of Object.keys(t))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await Ir(e,JSON.stringify(n,null,2)+`
173
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Sr(o=vo){let e=process.env.CODEX_HOME||yo(br(),".codex"),n=yo(e,"config.toml"),t;try{t=await wr(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await sa(ia(n),{recursive:!0});let r=`
371
174
  [mcp_servers.popmelt]
372
- url = "${s}"
373
- `;return await Pn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Rn(s=At,e="copilot"){let n=await Go(e);if(qo(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{xn(e,["mcp","add","--transport","http","--json","popmelt",s],{encoding:"utf-8",timeout:1e4},i=>{if(i){o(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function Go(s){try{let e=await new Promise((n,t)=>{xn(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return JSON.parse(e)}catch{return null}}function qo(s){if(!s||typeof s!="object")return!1;let e=s,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var it=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let o=this.leases.get(e),i={id:e,ownerPid:n,createdAt:o?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,o]of this.leases)o.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};async function at(s){let n=(s.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],o=await Qo(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),l,f,v,x,E,B,J,U,W,w,q,V,Q,K,z=[],Z=[],O=0,A=[];for(;O<o.length;){let k=o.indexOf(i,O);if(k===-1)break;let M=k+i.length;if(o.slice(k,k+a.length).equals(a))break;let N=M;o[N]===13&&o[N+1]===10&&(N+=2);let $=o.indexOf(`\r
175
+ url = "${o}"
176
+ `;return await Ir(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Pr(o=vo,e="copilot"){let n=await aa(e);if(ca(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{vr(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},s=>{if(s){r(s);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function aa(o){try{let e=await new Promise((n,t)=>{vr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return JSON.parse(e)}catch{return null}}function ca(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var Pn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),s={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,s),s}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as To,readFile as Mt,writeFile as jo}from"fs/promises";import{join as lt}from"path";var da=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function wo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function kn(o){return new Set(wo(o).split(" ").filter(e=>e.length>2&&!da.has(e)))}function kr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function la(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function pa(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(wo).filter(Boolean),s=kn([e.action,e.text].filter(Boolean).join(" "));for(let i of o){if(t.has(i.id)){n.set(i.id,{subjectId:i.id,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of la(i)){let l=wo(d.value);for(let b of r){let I=l===b?95:l.includes(b)||b.includes(l)?75:0;I>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:I>=90?"exact":"strong",matchedBy:d.by,score:I})}let R=["/","#","[","]","="].some(b=>d.value.includes(b))?0:Math.round(kr(kn(l),s)*55);R>=30&&R>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}c&&n.set(i.id,c)}return n}function ua(o,e){let n=new Set(o.sourceRefs.filter(i=>i.kind==="iteration").map(i=>i.id)),t=new Set(o.sourceRefs.filter(i=>i.kind==="thread").map(i=>i.id)),r=e.filter(i=>i.iterationIds.some(c=>n.has(c))||i.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let s=new Set(r.map(i=>i.state));return{state:s.size>1?"mixed":s.has("completed")?"completed":"attempted",attemptIds:r.map(i=>i.id)}}function ma(o){return Math.ceil(JSON.stringify(o).length/4)}function Io(o,e){let n=o.records.filter(h=>h.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(h=>{if(h.recordType!=="proposal"||r&&!r.has(h.id))return!1;if(h.state==="pending")return!0;if(h.state!=="deferred")return!1;let f=[...o.events].reverse().find(y=>y.entity.entityType==="proposal"&&y.entity.entityId===h.id&&y.toState==="deferred"&&y.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(h=>h.recordType==="implementation_attempt"),c=pa(n,e),d=[...c.values()].sort((h,f)=>f.score-h.score),l=kn([e.action,e.text].filter(Boolean).join(" ")),v=s.flatMap(h=>{let f=h.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),y=Math.max(0,...f.map(A=>A.score)),x=Math.round(kr(kn(h.claim),l)*35),S=y+x;return S>=50?[{proposal:h,proposalMatches:f,score:S}]:[]}).sort((h,f)=>f.score-h.score||h.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),I=[],g=0;for(let h of v){if(I.length>=R)break;let f=h.proposal.sourceRefs.slice(0,4),y={contractVersion:1,packetId:`review:${h.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:h.proposalMatches.length?`Historical proposal intersects ${h.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:h.proposalMatches.map(({score:S,...A})=>A)},proposal:{id:h.proposal.id,claim:h.proposal.claim,state:h.proposal.state,proposedKind:h.proposal.proposedKind,subjectIds:h.proposal.subjects.map(S=>S.subjectId),origin:h.proposal.origin.mode},authority:"unaccepted",presentation:h.score>=100&&["constraint","rule"].includes(h.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ua(h.proposal,i),evidence:{sourceCount:h.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:h.proposal.id},...f]},x={...y,estimatedTokens:ma(y)};if(g+x.estimatedTokens>b)break;I.push(x),g+=x.estimatedTokens}let p=Math.max(0,v.length-I.length);return{packets:I,subjectMatches:d.map(({score:h,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:p,maxEstimatedTokens:b,estimatedTokens:g},uncertainty:c.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var fa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function bo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Rn(o){return new Set(bo(o).split(" ").filter(e=>e.length>2&&!fa.has(e)))}function Rr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ha(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(bo).filter(Boolean),r=Rn([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=bo(l.value);for(let I of t){let g=v===I?95:v.includes(I)||I.includes(v)?75:0;g>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let b=["/","#","[","]","="].some(I=>l.value.includes(I))?0:Math.round(Rr(Rn(v),r)*55);b>=30&&b>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}c&&s.push(c)}return s.sort((i,c)=>c.score-i.score||i.subjectId.localeCompare(c.subjectId))}function ga(o){return Math.ceil(JSON.stringify(o).length/4)}function Tt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ya(o,e){let n=e.filter(s=>s.coverageClaims.some(i=>i.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(s=>s.state==="completed"),r=t.some(s=>s.coverageClaims.some(i=>i.decisionId===o&&i.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(s=>s.id)}}function va(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),s=t[0],i=r?"stale":s?s.state==="passed"?"passing":s.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(s.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:i,attemptIds:t.map(c=>c.id)}}function Tr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(_=>_.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(_=>_.recordType==="decision"&&_.state==="active"),c=s?i.filter(_=>s.has(_.id)):i,d=o.records.filter(_=>_.recordType==="implementation_attempt"),l=o.records.filter(_=>_.recordType==="verification_attempt"),v=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),R=o.records.filter(_=>_.recordType==="evidence"),b=o.records.filter(_=>_.recordType==="model_entry"),I=[...o.records].reverse().filter(_=>_.recordType==="eval_spec").filter((_,N,T)=>T.findIndex(B=>B.legacyId===_.legacyId)===N),g=ha(r,e),p=new Map(g.map(_=>[_.subjectId,_.score])),h=Rn([e.action,e.text].filter(Boolean).join(" ")),f=c.flatMap(_=>{let N=Math.max(0,..._.subjects.map(W=>p.get(W.subjectId)??0)),T=Math.round(Rr(Rn(_.claim),h)*35),B=N+T;return B>=50?[{decision:_,score:B}]:[]}).sort((_,N)=>N.score-_.score||_.decision.id.localeCompare(N.decision.id)),y=new Map;for(let _ of f.slice(0,t))y.set(_.decision.id,_.decision);for(let _ of o.relationships){if(!Tt(_,"excepts")&&!Tt(_,"contradicts"))continue;let N=i.find(B=>B.id===_.from.entityId),T=i.find(B=>B.id===_.to.entityId);!N||!T||!y.has(N.id)&&!y.has(T.id)||(y.size<t&&y.set(N.id,N),y.size<t&&y.set(T.id,T))}let x=[...y.values()],S=_=>_.from.entityType==="decision"&&_.to.entityType==="decision"&&y.has(_.from.entityId)&&y.has(_.to.entityId),A=(_,N=!1)=>{let T=new Set(_.map(M=>M.id)),B=v.filter(M=>M.target.entityType==="decision"&&T.has(M.target.entityId)),W=new Set(o.relationships.filter(M=>Tt(M,"excepts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).flatMap(M=>[M.from.entityId,M.to.entityId])),H=o.relationships.filter(M=>Tt(M,"contradicts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).map(M=>({id:M.id,decisionIds:[M.from.entityId,M.to.entityId],unresolvedQuestion:M.reason,expansionRefs:[{kind:"record",id:M.id}]})),te=new Set(H.flatMap(M=>M.decisionIds)),ne=R.filter(M=>M.sourceRefs.some(Y=>Y.kind==="record"&&T.has(Y.id))||o.relationships.some(Y=>Y.relationshipType==="supports"&&Y.from.entityType==="evidence"&&Y.from.entityId===M.id&&Y.to.entityType==="decision"&&T.has(Y.to.entityId))),ge=Math.max(0,f.length-_.length),X=o.relationships.some(M=>Tt(M,"contradicts")&&S(M)&&(!T.has(M.from.entityId)||!T.has(M.to.entityId))),G=N||ge>0||X,U=[];g.length===0&&(e.subjectHints?.length??0)>0?U.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):_.length===0&&U.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),H.length&&U.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.flatMap(M=>M.expansionRefs)}),ne.some(M=>M.availability!=="available")&&U.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:ne.map(M=>({kind:"record",id:M.id}))}),G&&U.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let he={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:g.map(({score:M,...Y})=>Y),modelEntries:b.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,key:M.key,value:M.value,decisionIds:M.decisionIds})),evalSpecs:I.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,legacyId:M.legacyId,state:M.state,title:M.title,assertionCount:M.assertions.length,decisionIds:M.decisionIds,expansionRef:{kind:"record",id:M.id}})),decisions:_.map(M=>({id:M.id,kind:M.kind,claim:M.claim,subjectIds:M.subjects.map(Y=>Y.subjectId),authority:M.authority,effectiveState:te.has(M.id)?"conflicted":W.has(M.id)?"excepted":"active",freshness:B.filter(Y=>Y.target.entityId===M.id).map(Y=>Y.signalType),expansionRef:{kind:"record",id:M.id}})),conflicts:H,uncertainties:U,implementation:_.map(M=>ya(M.id,d)),verification:_.map(M=>va(M.id,l,B)),evidence:ne.map(M=>({evidenceId:M.id,summary:M.summary,availability:M.availability,sourceRefs:M.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:ge,omittedEvidenceCount:0,conflictsComplete:!X}};return he.budget.estimatedTokens=ga(he),he},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>Tt(T,"contradicts")&&(T.from.entityId===_.id||T.to.entityId===_.id)).flatMap(T=>[T.from.entityId,T.to.entityId]);x=x.filter(T=>!N.includes(T.id)),J=A(x,!0)}return J}var wa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function jt(o){return wa.test(o)}function Ia(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ce(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function xo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){jt(n)||ce(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function dt(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ce(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function vt(o,e,n,t=!1){t&&n.level==="contributor"&&ce(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ce(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ba={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},xa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Sa(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),dt(o,`${n}.createdAt`,e.createdAt),vt(o,`${n}.authority`,e.authority);let t=ba[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ce(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let s=`${e.entity.entityType}:${e.toState}`;if(xa.has(s)&&(vt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ce(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let i=e.transitionContext;(i?.kind!=="proposal_deferral"||i.resurfaceWhen.length===0)&&ce(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),i?.resurfaceWhen.includes("after_date")&&!i.revisitAfter&&ce(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),i?.revisitAfter&&dt(o,`${n}.transitionContext.revisitAfter`,i.revisitAfter)}}function Pa(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),dt(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ce(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ce(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ce(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ce(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(vt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ce(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&xo(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ce(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(dt(o,`${n}.appliedAt`,e.appliedAt),vt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ce(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&ce(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ce(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&xo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&xo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ka(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),dt(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ce(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)&&((e.from.entityType!=="decision"||e.to.entityType!=="decision")&&ce(o,n,"invalid_normative_relationship","Normative relationships connect decisions to decisions."),e.authority?vt(o,`${n}.authority`,e.authority,!0):ce(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context.")),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ce(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&ce(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ce(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function wt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),dt(e,"manifest.createdAt",o.manifest.createdAt),dt(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,h)=>{let f=n.get(p);f?ce(e,h,"duplicate_id",`ID is already used at ${f}.`):n.set(p,h)};o.records.forEach((p,h)=>{let f=`records[${h}]`;t(p.id,f),Pa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,h)=>{let f=`events[${h}]`;t(p.id,f),Sa(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,h)=>{let f=`relationships[${h}]`;t(p.id,f),ka(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,h)=>{t(p.id,`artifacts[${h}]`),Te(e,`artifacts[${h}].id`,p.id)}),o.tombstones.forEach((p,h)=>{let f=`tombstones[${h}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),dt(e,`${f}.deletedAt`,p.deletedAt),vt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,h)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,h,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,h)=>i(p.entity,`events[${h}].entity`)),o.relationships.forEach((p,h)=>{i(p.from,`relationships[${h}].from`),i(p.to,`relationships[${h}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,h)=>{c.has(p)||ce(e,h,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,h,f)=>{!r.has(`${p}:${h}`)&&!s.has(`${p}:${h}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,h)=>{let f=`records[${h}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((y,x)=>l("subject",y,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((y,x)=>d(y,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((y,x)=>l("subject",y.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((y,x)=>d(y,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((y,x)=>i(y,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((y,x)=>l("thread",y,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((y,x)=>l("iteration",y,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((y,x)=>{y.kind==="subject"&&y.subjectId&&l("subject",y.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((y,x)=>{y.subjectIds?.forEach((S,A)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${A}]`))}),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`));break;case"model_projection":vt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((y,x)=>l("model_entry",y,`${f}.entryIds[${x}]`)),p.coverage.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;default:break}});let v=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),b=new Map;o.events.forEach((p,h)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,y=b.get(f)??new Set;y.add(p.toState),b.set(f,y),y.size>1&&ce(e,`events[${h}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let I=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,h,f,y,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=I.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==h||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(f);(A<Date.parse(S.startsAt)||S.endsAt&&A>Date.parse(S.endsAt)||S.revokedAt&&A>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&y.length&&!y.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(h=>h.subjectId),`records:${p.id}.authority`);o.events.forEach((p,h)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),y=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,y,`events[${h}].authority`)}),o.relationships.forEach((p,h)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(y=>{let x=R.get(`${y.entityType}:${y.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${h}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let h=v.get(p.acceptanceEventId);(!h||h.entity.entityType!=="proposal"||h.entity.entityId!==p.proposalId||h.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),h&&h.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(y=>y.relationshipType==="supersedes"&&y.to.entityType==="decision"&&y.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(y=>y.entity.entityType==="decision"&&y.entity.entityId===p.id&&y.toState==="revoked"&&!!y.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ia(e)}function Gt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function jr(o,e,n,t,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Ra(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function Tn(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),jt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of Ra(e))jt(s)||n.push({code:"invalid_generated_id",message:`${s} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=jr(o,t,e,s.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:i.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let s={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},i={...Gt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Gt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=jr(o,s,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,d],events:[i,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ta}from"crypto";import{readFile as ja,readdir as Ea,realpath as Ma}from"fs/promises";import{join as Vt,relative as Aa}from"path";var _a=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Et(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Le(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Er(...o){return o.find(e=>!!e?.trim())?.trim()}function ye(o,e,n,t){let s=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),i=Ta("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${c}${i.slice(4,7)}-${i.slice(7,19)}`}async function So(o,e){try{return JSON.parse(await ja(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Ca(o){let e=Et(o);if(!e)return 0;let n=0,t=r=>{let s=Et(r);if(!s){n+=1;return}for(let i of Object.values(s))t(i)};for(let r of Object.values(e))t(r);return n}function $a(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Kt(o){let e=[],n=await Ma(o.projectRoot).catch(()=>o.projectRoot),t=Vt(n,".popmelt"),r=await So(Vt(t,"threads.json"),e),s=await So(Vt(t,"model.json"),e),i=Et(r),c=Et(i?.threads)??{},d=Object.entries(c).map(([M,Y])=>({key:M,value:Et(Y)})).filter(M=>!!M.value),l=Vt(t,"decisions"),v=await Ea(l).catch(()=>[]),R=[];for(let M of v.filter(Y=>Y.endsWith(".json")).sort()){let Y=Et(await So(Vt(l,M),e));Y&&R.push({file:M,value:Y})}let b=d.flatMap(({value:M})=>[M.createdAt,M.updatedAt]).filter(M=>typeof M=="number"&&Number.isFinite(M)),I=b.length?Math.min(...b):0,g=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ye(g,"project",g,I),h=ye(g,"participant","legacy-owner",I),f=ye(g,"participant","legacy-agent",I),y=ye(g,"subject","project",I),x=Le(Math.max(I,...b)),S=[],A=[],J=new Map,_=new Map,N=new Map(R.map(M=>[M.value.id??M.file.replace(/^d-|\.json$/g,""),M.value])),T=new Map,B=(M,Y,ue,ie,De)=>{let Je=J.get(ue);if(Je)return Je;let Pe=ye(g,"artifact",M,ie);return A.push({id:Pe,kind:Y,mediaType:De,location:ue,availability:"available"}),J.set(ue,Pe),Pe};for(let{file:M,value:Y}of R){let ue=Y.id??M.replace(/^d-|\.json$/g,""),ie=Y.createdAt??I,De=[B(`${ue}:envelope`,"other",`.popmelt/decisions/${M}`,ie,"application/json")];Y.screenshotPath&&De.push(B(`${ue}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,ie,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Je,Pe]of(Y.pastedImagePaths??[]).entries())De.push(B(`${ue}:image:${Je}`,"image",Pe,ie));T.set(ue,De)}let W=(M,Y,ue)=>({id:M,schemaVersion:1,projectId:p,createdAt:x,participantId:Y,sourceRefs:ue}),ee=(M,Y)=>{S.push(Y);let ue=_.get(M)??[];ue.push(Y.id),_.set(M,ue)},H=[{...W(h,h,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...W(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...H),S.push({...W(y,h,[]),recordType:"subject",subjectType:"project",label:Aa(process.cwd(),n)||n,aliases:[],locators:[{id:ye(g,"locator",n,I),kind:"project_root",value:n,status:"current",validFrom:Le(I),sourceRefs:[]}]});let te=new Map,ne=(M,Y)=>{let ue=te.get(M);if(ue)return ue;let ie=ye(g,"subject",M,Y),De={...W(ie,h,[{kind:"external",id:M}]),createdAt:Le(Y),recordType:"subject",subjectType:"element",label:M,aliases:[],locators:[{id:ye(g,"locator",M,Y),kind:"dom_selector",value:M,status:"current",validFrom:Le(Y),sourceRefs:[{kind:"external",id:M}]}]};return S.push(De),te.set(M,ie),ie};for(let{key:M,value:Y}of d){let ue=Y.id??M,ie=Y.createdAt??I,De=ye(g,"thread",ue,ie),Je={kind:"thread",id:ue},Pe=[],Ue=[],Ge=Array.isArray(Y.messages)?Y.messages:[],Ye,rt,ut=0;Ge.forEach((we,st)=>{let Ae=we.timestamp??ie,Ze=ye(g,"artifact",`${ue}:message:${st}`,Ae);if(Pe.push(Ze),A.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${st}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${ue}/messages/${st}`,Ze),we.screenshotPath&&B(`${ue}:message:${st}:screenshot`,"screenshot",we.screenshotPath,Ae),we.role==="human"){Ye=we;let je=we.feedbackSummary??we.replyToQuestion;if(je?.trim()){let Ne=ye(g,"observation",`${ue}:${st}`,Ae),ct=Y.elementIdentifiers??[],St={...W(Ne,h,[Je,{kind:"message",id:Ze}]),createdAt:Le(Ae),recordType:"observation",state:"open",statement:je,captureContext:{subjectIds:ct.map(ft=>ne(ft,ie)),artifactIds:[Ze]},resolvedByIds:[]};ee(ue,St),rt=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let it=we.jobId??`${ue}:${st}`,at=ye(g,"iteration",it,Ae),mt=N.get(it),Yn=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",Zn={...W(at,f,[Je,{kind:"message",id:Ze},...(T.get(it)??[]).map(je=>({kind:"artifact",id:je}))]),createdAt:Le(Ae),recordType:"iteration",threadIds:[De],startedAt:Le(Ye?.timestamp,Ae),completedAt:Le(Ae),requestSummary:Er(Ye?.feedbackSummary,Ye?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:Yn,execution:{provider:we.provider??mt?.provider,model:we.model??mt?.model,sessionId:we.sessionId??mt?.sessionId},artifactIds:[Ze,...T.get(it)??[]]};ee(ue,Zn),Ue.push({entityType:"iteration",entityId:at});let Bt=we.resolutions??mt?.resolutions??[];for(let[je,Ne]of Bt.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let ct=Y.elementIdentifiers??[],St=(ct.length?ct:[n]).map(cn=>({subjectId:cn===n?y:ne(cn,ie),role:"governed"})),ft=ye(g,"proposal",`${it}:${Ne.annotationId??"resolution"}:${je}`,Ae),eo={...W(ft,f,[Je,{kind:"iteration",id:at}]),createdAt:Le(Ae),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:St,subjectSemantics:St.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Er(Ye?.feedbackSummary,Ye?.replyToQuestion,Ne.summary),iterationId:at,inferredById:f}};ee(ue,eo),Ue.push({entityType:"proposal",entityId:ft}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${ft} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Bt.some(je=>je.status==="resolved")||mt?.gitDiff){let je=ye(g,"implementation",it,Ae),Ne={...W(je,f,[Je,{kind:"iteration",id:at}]),createdAt:Le(Ae),recordType:"implementation_attempt",state:"completed",iterationIds:[at],coverageClaims:[],summary:Bt.map(ct=>ct.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};ee(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:je}),ut+=1}rt&&(rt=void 0)});let Jt=Ge.at(-1),Nt={...W(De,h,[Je]),createdAt:Le(ie),recordType:"thread",state:Jt?.question?"open":"resolved",messageArtifactIds:Pe,outcome:Jt?.question?"question_unresolved":ut?"implementation_only":"no_outcome",resultRefs:Ue};S.push(Nt),_.set(ue,[De,..._.get(ue)??[]])}let ge=Ca(s);ge&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ge} model values were not promoted because their accepted decision provenance is unresolved.`});let X={manifest:{formatVersion:1,projectId:p,createdAt:Le(I),updatedAt:x,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:S,events:[],relationships:[],artifacts:A,tombstones:[]},G=wt(X),he=(o.proofCaseIds??_a).map(M=>({legacyId:M,threadFound:d.some(({key:Y,value:ue})=>(ue.id??Y)===M),decisionEnvelopeFound:N.has(M),recordIds:_.get(M)??[]}));return{bundle:X,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((M,Y)=>M+(Y.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:ge,artifactsReferenced:A.length},imported:$a(S),unresolvedAcceptance:e.filter(M=>M.code==="acceptance_unresolved").length,deferredModelEntries:ge,proofCases:he,issues:e,schemaIssues:G.issues}}}import{createHash as Oa}from"crypto";import{mkdir as Mr,open as Po,readFile as ko,readdir as Da,rename as Ja,unlink as Ro}from"fs/promises";import{join as nt}from"path";var Na={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function En(o){return Oa("sha256").update(JSON.stringify(o)).digest("hex")}function Ar(o){return En(o)}function _r(o,e,n){for(let t of e.projectionUpdates){let r=o.records.find(s=>s.recordType===t.entityType&&s.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Ba(o,e,n){return _r(structuredClone(o),e,n)}async function It(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Po(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
177
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Ja(n,o)}catch(r){throw await Ro(n).catch(()=>{}),r}}async function jn(o){return JSON.parse(await ko(o,"utf8"))}var Mn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=nt(e,".popmelt","memory"),this.journalDir=nt(this.memoryDir,"journal"),this.manifestPath=nt(this.memoryDir,"manifest.json"),this.checkpointPath=nt(this.memoryDir,"checkpoint.json"),this.lockPath=nt(this.memoryDir,"writer.lock")}async initialize(e){let n=wt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Mr(this.journalDir,{recursive:!0});try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}let t=En(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},s={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await It(this.checkpointPath,r),await It(this.manifestPath,s)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await It(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=En(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await It(nt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await It(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!jt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,s={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},i={...s,hash:Ar(s)},c=Ba(t.bundle,e,n.committedAt),d=wt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await It(nt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await It(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:i.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Na,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await jn(this.manifestPath),n=await jn(nt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==En(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Da(this.journalDir),r=t.filter(b=>b.endsWith(".tmp")),i=t.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,v=new Set;for(let b of i){let I=await jn(nt(this.journalDir,b)),{hash:g,...p}=I;if(g!==Ar(p))throw new Error(`Journal hash mismatch: ${b}`);if(I.sequence!==d+1)throw new Error(`Journal sequence gap at ${b}`);if(I.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(I.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(v.has(I.transactionId))throw new Error(`Duplicate transaction ID: ${I.transactionId}`);_r(c,I.mutation,I.committedAt),d=I.sequence,l=I.hash,v.add(I.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=wt(c);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:c,manifest:e,transactionIds:v,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Mr(this.memoryDir,{recursive:!0});let n;try{n=await Po(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await jn(this.lockPath).catch(()=>({})),s=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(i){s=i.code!=="ESRCH"}if(s)throw new Error("Memory journal is locked by another writer.");await Ro(this.lockPath),n=await Po(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Ro(this.lockPath).catch(()=>{})}}};import{randomBytes as Fa}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Fa(10).toString("hex"),r=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${r}${t.slice(4,7)}-${t.slice(7,19)}`}var La=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Cr(o,e){let n=o.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active"),t=o.records.find(x=>x.recordType==="participant"&&x.kind==="ai"&&x.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,s=`${e.threadId}:${e.jobId}`,i=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=La(),l=d.records,v=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));v||(v={id:ye(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(x=>x.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(v));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"element",label:x,aliases:[],locators:[{id:ye(r,"live-locator",x,e.createdAt),kind:"dom_selector",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}for(let x of[...new Set((e.filePaths??[]).filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.kind==="source_file"&&J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-file-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"file",label:x,aliases:[],locators:[{id:ye(r,"live-file-locator",x,e.createdAt),kind:"source_file",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}let b=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),I;if(b.length>0){I=ye(r,"live-observation",s,e.createdAt);let x={id:I,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds:R.map(S=>S.id),artifactIds:[]},resolvedByIds:[]};l.push(x)}let g=ye(r,"live-iteration",s,e.completedAt),p={id:g,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...I?[{kind:"record",id:I}]:[]],recordType:"iteration",threadIds:[v.id],startedAt:i,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let h=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),y=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(b.length>0&&y.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of b.entries()){let A=ye(r,"live-proposal",`${s}:${x}`,e.completedAt),J=y.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:S.claim.trim(),rationale:S.rationale?.trim()||void 0,proposedKind:S.proposedKind,subjects:J,subjectSemantics:J.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:S.sourceText?.trim()||e.requestSummary,iterationId:g,inferredById:t.id}};l.push(_),h.push(A)}if(f.length>0){let x=new Set(e.governingDecisionIds??[]),S=o.records.filter(J=>J.recordType==="decision"&&J.state==="active"&&x.has(J.id)),A={id:ye(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g}],recordType:"implementation_attempt",state:"completed",iterationIds:[g],coverageClaims:S.map(J=>({decisionId:J.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(_=>_.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:d,iterationId:g,proposalIds:h,observationId:I}}import{createHash as za}from"crypto";import{mkdir as Ua,open as qa,readFile as Wa,rename as Ha,unlink as Ga}from"fs/promises";import{join as $r}from"path";function Or(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dr(o){return za("sha256").update(JSON.stringify(o)).digest("hex")}async function Va(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await qa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Ha(n,o)}catch(r){throw await Ga(n).catch(()=>{}),r}}function Ka(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(d,l,v)=>{let R=d[l]??=[];R.includes(v)||R.push(v)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Or(v);R&&i(t,R,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)i(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)i(s,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...c,checksum:Dr(c)}}function Jr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Or(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var An=class{constructor(e){this.indexDir=$r(e,".popmelt","memory","indexes"),this.indexPath=$r(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Wa(this.indexPath,"utf8")),{checksum:s,...i}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&s===Dr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ka(e,n);return await Ua(this.indexDir,{recursive:!0}),await Va(this.indexPath,t),t}};var _n=class{constructor(e){this.projectRoot=e;this.store=new Mn(e),this.indexStore=new An(e),this.manifestPath=lt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Mt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Kt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Kt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"legacy-evals-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(s.runs)?s.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:r.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:r.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"imprint-evidence-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=0;for(let s of t.explanations){let i=s.evidence.length?s.evidence:[{id:s.id,kind:"observation",stance:"supports",summary:s.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:s.createdAt}];for(let c of i){let d=c.kind==="confirmation"?"confirm":c.kind==="correction"||c.kind==="rejection"?"reason_wrong":c.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:c.id,kind:d?"strengthened":"added",title:s.statement.slice(0,120),detail:c.summary,changes:[{explanationId:s.id,action:d==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:c.threadId,jobId:c.jobId,action:d,occurredAt:c.createdAt}),r+=1}}return await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:t.explanations.length,evidence:r,source:".popmelt/imprint (linked projection)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:r}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Io(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Tr(t.bundle,r),reviewSelection:Io(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Tn(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Kt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=Tn(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},d=e.action==="accept"?{...c,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:le(s),reason:e.reason}:{...c,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=Tn(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(v);let R=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:v.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Cr(n.bundle,e),r=ye(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let s=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(s),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:s.report.headSequence}}catch(s){if(s instanceof Error&&s.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw s}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active"),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="ai"&&b.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(b=>b.recordType==="subject"&&b.subjectType==="project");if(!s||!i)return;let c=e.occurredAt??new Date().toISOString(),d=Date.parse(c),l=[],v=[];for(let b of e.summary.changes){let I={kind:"external",id:b.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(h=>h.recordType==="observation"&&h.sourceRefs.some(f=>f.kind==="external"&&f.id===b.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:b.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),v.push({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ye(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,d);try{let b=await this.store.commit({records:l,events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:c});await this.refreshIndex(b)}catch(b){if(!(b instanceof Error)||!b.message.includes("Transaction already exists"))throw b}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="model_projection"&&i.state==="applied"?i.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(i=>i.relationshipType==="contradicts"&&i.from.entityType==="decision"&&i.to.entityType==="decision"?[i.from.entityId,i.to.entityId]:[])),s=new Set(n.records.flatMap(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.target.entityType==="decision"?[i.target.entityId]:[]));return n.records.filter(i=>i.recordType==="decision"&&i.state==="active"&&!t.has(i.id)&&!r.has(i.id)&&!s.has(i.id)).sort((i,c)=>c.createdAt.localeCompare(i.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(s=>s.recordType==="model_entry").sort((s,i)=>s.createdAt.localeCompare(i.createdAt)))r.decisionIds.some(s=>n.has(s))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let r=[...t.values()],s=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=s.filter(l=>l.targets.some(v=>v.entityType==="decision"&&v.entityId===c.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(c=>c.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),c=le(s),d=le(s),l=le(s),v=le(s),R=le(s),b=new Set(n.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),I=n.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&b.has(T.id)),g={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],h={...g,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},y={...g,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...g,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${s}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:i,decisionIds:[l],entryIds:[v],coverage:[{decisionId:l,status:"projected"}]},A={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=I.map(T=>({...g,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=I.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:y.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[h,y,x,S],events:[f,...J],relationships:[A,..._],artifacts:[],tombstones:[],projectionUpdates:I.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:v}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),s=n.bundle.records.flatMap(g=>g.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===g.id||g.sourceRefs.some(h=>h.id===p))?[g.id]:[]),i=[...new Set(n.bundle.records.flatMap(g=>g.recordType==="decision"&&s.includes(g.id)?g.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!l)throw new Error("No active local owner participant is available.");let v=Date.now(),R=new Date(v).toISOString(),b={id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},I=r?[{id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:b.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:b.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[b],events:[],relationships:I,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(v),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(i=>i.objectType==="eval_spec").map(i=>i.objectId)),t=e.records.filter(i=>i.recordType==="eval_spec").reverse().filter((i,c,d)=>d.findIndex(l=>l.legacyId===i.legacyId)===c).filter(i=>!n.has(i.id)),r=e.records.filter(i=>i.recordType==="verification_attempt"),s=e.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.targetKind==="verification_result");return t.map(i=>{let c=r.filter(v=>v.evalSpecId===i.id).sort((v,R)=>R.createdAt.localeCompare(v.createdAt))[0],d=c&&s.some(v=>v.target.entityType==="verification_attempt"&&v.target.entityId===c.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(b=>b.recordType==="verification_attempt"&&b.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active"&&b.kind==="ai")??t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active");if(!s)return;let i=n.completedAt,c=new Date(i).toISOString(),d={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},v=r.targets.map(b=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:b,reason:n.summary})),R=await this.store.commit({records:[d,l],events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),c={id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),r=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(d=>!r.includes(d)).map(d=>d.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!i)return{valid:r,discardedIds:s};let c=s.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(v=>({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:v.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="model_projection"&&g.state==="applied"&&g.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(g=>g.recordType==="decision"&&e.decisionIds.includes(g.id)&&g.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let s=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),c=new Date(i).toISOString(),d=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(y=>e.decisionIds.includes(y)),h=p?.length?p:e.decisionIds,f=[...new Set(r.filter(y=>h.includes(y.id)).flatMap(y=>y.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:h.map(y=>({kind:"record",id:y})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:h,value:g.value}}),v=new Set(l.flatMap(g=>g.decisionIds)),R={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:e.decisionIds.map(g=>({kind:"record",id:g})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:v.has(g)?"projected":"unprojected"})},b=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),I=await this.store.commit({records:[...l,R],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});return await this.refreshIndex(I),{projectionId:d,entryIds:l.map(g=>g.id),headSequence:I.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Kt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Jr(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function _t(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function At(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Eo(o){let e=_t(o),n=_t(e.authority),t=n.level,r=n.mode,s=At(t,"authority.level",["owner","delegate","contributor"]),i=At(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:At(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=_t(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>At(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:At(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=_t(d);return{subjectId:Se(l.subjectId,"subjectId"),role:At(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Mo(o){let e=_t(o),n=(s,i)=>{if(s!==void 0){if(!Array.isArray(s))throw new Error(`${i} must be an array.`);return s.map(c=>Se(c,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0:_t(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Cn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
179
+ `)}async function Nr(o,e,n,t){let r=Cn(e);if(!(!r&&n.length===0))try{let s=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(s.actionPacket.decisions.length===0&&s.reviewSelection.packets.length===0)return;let i=new Map(s.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(s.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:s.source,...s.actionPacket.decisions.length>0?{acceptedTruth:{decisions:s.actionPacket.decisions.map(d=>({...d,implementation:i.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:s.actionPacket.conflicts,truncated:s.actionPacket.completeness.status==="truncated"}}:{},packets:s.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:s.reviewSelection.completeness.status==="truncated",estimatedTokens:s.actionPacket.budget.estimatedTokens+s.reviewSelection.completeness.estimatedTokens}}catch(s){t?.(s);return}}function Br(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,r)=>["",`${r+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,r)=>["",`${r+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
180
+ `)}function Fr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!r||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let s=new Set(["different_action","new_evidence","new_conflict","owner_request"]),i=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&s.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:i}}catch{return null}}function Lr(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!t||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:t,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function $n(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],r=await Qa(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),c,d,l,v,R,b,I,g,p,h,f,y,x,S,A=[],J=[],_=0,N=[];for(;_<r.length;){let T=r.indexOf(s,_);if(T===-1)break;let B=T+s.length;if(r.slice(T,T+i.length).equals(i))break;let W=B;r[W]===13&&r[W+1]===10&&(W+=2);let ee=r.indexOf(`\r
374
181
  \r
375
- `,N);if($===-1)break;let T=o.slice(N,$).toString("utf-8"),L=$+4,_=o.indexOf(i,L),ee=_!==-1?_-2:o.length;A.push({headers:T,body:o.slice(L,ee)}),O=_!==-1?_:o.length}for(let k of A){let M=k.headers.match(/name="([^"]+)"/);if(!M)continue;let N=M[1];if(N==="screenshot")l=k.body;else if(N==="feedback")f=k.body.toString("utf-8");else if(N==="color")v=k.body.toString("utf-8");else if(N==="provider")x=k.body.toString("utf-8");else if(N==="model")E=k.body.toString("utf-8");else if(N==="reasoningEffort")B=k.body.toString("utf-8");else if(N==="serviceTier")J=k.body.toString("utf-8");else if(N==="goal")U=k.body.toString("utf-8");else if(N==="pageUrl")W=k.body.toString("utf-8");else if(N==="viewport")w=k.body.toString("utf-8");else if(N==="planId")q=k.body.toString("utf-8");else if(N==="manifest")V=k.body.toString("utf-8");else if(N==="tasks")Q=k.body.toString("utf-8");else if(N==="sourceId")K=k.body.toString("utf-8");else if(N.startsWith("screenshot-")){let $=N.slice(11);try{let T=decodeURIComponent($);Z.push({pathname:T,data:k.body})}catch{}}else if(N.startsWith("image-")){let $=N.split("-"),T=parseInt($[$.length-1],10),L=$.slice(1,-1).join("-");L&&!isNaN(T)&&z.push({annotationId:L,index:T,data:k.body})}}if(!l)throw new Error("Missing screenshot field");return f||(f=""),{screenshot:l,feedback:f,color:v,provider:x,model:E,reasoningEffort:B,serviceTier:J,goal:U,pageUrl:W,viewport:w,planId:q,manifest:V,tasks:Q,sourceId:K,pastedImages:z,pageScreenshots:Z}}function Qo(s){return new Promise((e,n)=>{let t=[];s.on("data",o=>t.push(o)),s.on("end",()=>e(Buffer.concat(t))),s.on("error",n)})}function ze(s,e){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let t of s.annotations){let o=t.elements.map(l=>{let f=[l.selector];return l.reactComponent&&f.push(`(${l.reactComponent})`),f.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${o||"none"}`);let a=e?.[t.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`)}}if(s.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of s.styleModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${o}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(s.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of s.textModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=JSON.stringify(t.original),a=JSON.stringify(t.modified),l=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${o}${l}: ${i} \u2192 ${a}`)}}if(s.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of s.domModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",a=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${o}${i} \u2192 ${t.targetParentSelector}${a}`)}}if(s.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of s.spacingTokenChanges){n.push(`
376
- ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let o of t.affectedElements){let i=o.reactComponent?` (${o.reactComponent})`:"";o.matchedClass&&o.suggestedClass?n.push(`- ${o.selector}${i}: \`${o.matchedClass}\` \u2192 \`${o.suggestedClass}\``):n.push(`- ${o.selector}${i}: ${o.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${o.className}"`)}}}if(s.inspectedElement){let t=s.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let o=[t.selector];t.reactComponent&&o.push(`(${t.reactComponent})`),t.context&&o.push(`in ${t.context}`),t.textContent&&o.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${o.join(" ")}`)}return n.join(`
377
- `)}function En(s,e,n){let t=[],i=new Set(e.annotations.map(a=>a.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!i&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let a=0;for(let l of n.threadHistory)if(l.role==="human")a++,l.replyToQuestion?(t.push(`### Round ${a} (human) \u2014 reply`),t.push(`"${l.replyToQuestion}"`)):(t.push(`### Round ${a} (human)`),l.feedbackSummary&&t.push(`Annotations: ${l.feedbackSummary}`),l.annotationIds&&l.annotationIds.length>0&&t.push(`Annotation IDs: ${l.annotationIds.join(", ")}`));else if(l.question)t.push(`### Round ${a} (assistant) \u2014 question`),t.push(`"${l.question}"`);else{if(t.push(`### Round ${a} (assistant)`),l.responseText&&t.push(`Response: ${l.responseText}`),l.resolutions&&l.resolutions.length>0)for(let f of l.resolutions){let v=f.finalScope??f.inferredScope,x=v?` [${v.breadth} ${v.target}]`:"";t.push(`- ${f.annotationId}: ${f.status}${x} \u2014 ${f.summary}`),f.filesModified&&f.filesModified.length>0&&t.push(` Files: ${f.filesModified.join(", ")}`)}l.toolsUsed&&l.toolsUsed.length>0&&t.push(`Tools used: ${l.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an established design model (stored in .popmelt/model.json), extracted from the developer's previous design decisions. When making changes, follow these patterns unless the developer explicitly overrides them. When asked about design tokens, component patterns, or design decisions, reference this model as the authoritative source.");let a=n.designModel.rules;if(Array.isArray(a)&&a.length>0)if(t.push(""),t.push("Rules:"),a.length>0&&typeof a[0]=="object"&&a[0]!==null&&"scope"in a[0]){let x=new Map;for(let E of a)if(typeof E=="object"&&E!==null&&"text"in E){let B=E,J=B.scope||"general";x.has(J)||x.set(J,[]),x.get(J).push(B.text)}for(let[E,B]of x){t.push(`**${E.charAt(0).toUpperCase()+E.slice(1)}**`);for(let J of B)t.push(`- ${J}`)}}else for(let x of a)typeof x=="string"&&t.push(`- ${x}`);let l=n.designModel.tokens;l&&typeof l=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(l,null,2)),t.push("```"));let f=n.designModel.components;f&&typeof f=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(f,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for design governance. Design decisions are stored in .popmelt/decisions/ (JSON files). A materialized design model may exist at .popmelt/model.json. When the developer asks about design tokens, patterns, or past decisions, check these files first before searching source code.")),i){let a=n?.screenshotPaths??{},l=new Map;for(let f of e.annotations){let v=f.pathname||new URL(e.url).pathname;l.has(v)||l.set(v,[]),l.get(v).push(f)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[f,v]of l){t.push(""),t.push(`## Page: ${f}`);let x=a[f];x&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${x}`):!x&&n?.provider!=="codex"&&(Object.keys(a).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${s}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let E={...e,annotations:v,styleModifications:e.styleModifications},B=ze(E,n?.imagePaths);B&&(t.push(""),t.push(B))}}else{let a=ze(e,n?.imagePaths);a&&(t.push(""),t.push(a))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
378
- `)}function Tn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ct(s,e,n,t){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=e.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let l of e)l.role==="human"?(a++,l.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${l.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),l.feedbackSummary&&o.push(`Annotations: ${l.feedbackSummary}`))):l.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${l.question}"`)):(o.push(`### Round ${a} (assistant)`),l.responseText&&o.push(`Response: ${l.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of t)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
379
- `)}function Xo(s){if(typeof s!="object"||s===null)return!1;let e=s;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function Yo(s){if(typeof s!="object"||s===null||typeof s.annotationId!="string"||s.status!=="resolved"&&s.status!=="needs_review"||typeof s.summary!="string")return!1;let e=s;for(let n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!Xo(e[n]))return!1;return!0}function An(s){let e=s.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(Yo):[]}catch{return[]}}function Cn(s){let e=s.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let o=t;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}import{execFile as Vo}from"child_process";import{readdir as Ko,readFile as Zo,stat as er}from"fs/promises";import{homedir as Be}from"os";import{join as Se}from"path";var ct=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:$n()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:$n()}],Fe=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],je={id:"",label:"Default",source:"cli"},tr=/^\s*-\s+"([^"]+)"/;function nr(s){let e=[],n=!1;for(let t of s.split(`
380
- `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(tr);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:$t(i),source:"cli"})}return dt([je,...e])}function sr(s){let e=JSON.parse(s);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,o)=>{let i=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,a=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return i-a}).flatMap(t=>{let o=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!o)return[];let i=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():$t(o),a=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(f=>{if(!f||typeof f!="object")return[];let v=f;return typeof v.effort!="string"?[]:[{effort:v.effort,...typeof v.description=="string"?{description:v.description}:{}}]}):void 0,l=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(f=>{if(!f||typeof f!="object")return[];let v=f;return typeof v.id!="string"?[]:[{id:v.id,label:typeof v.name=="string"?v.name:v.id,...typeof v.description=="string"?{description:v.description}:{}}]}):void 0;return[{id:o,label:i,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...a&&a.length>0?{supportedReasoningLevels:a}:{},...l&&l.length>0?{speedTiers:l}:{}}]})}function $n(){return["low","medium","high","xhigh","max"].map(s=>({effort:s}))}function or(s){let e=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return dt(e.map(n=>({id:n,label:$t(n),source:"cli"})))}function $t(s){if(!s)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=s.replace(/-\d{8,}$/,"");if(e[s])return e[s];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let i=t[1]==="sonnet"?"Sonn":lr(t[1]),a=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${a}${t[4]?" Fast":""}`}let o=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let i=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${i}`:o[3]==="codex"?`Codex ${i}`:o[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function _n(s="copilot"){let e=await lt(s,["help","config"]),n=nr(e);return n.length>1?n:[je]}async function On(s="codex"){let e=await lt(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Se(Be(),".codex");return Nn(Se(t,"models_cache.json"))}),n=sr(e);return n.length>0?dt([...n,...Fe]):Fe}async function Dn(s="claude"){let e=Se(Be(),".claude"),n=[Se(Be(),".claude","stats-cache.json"),Se(Be(),".claude","settings.json"),Se(Be(),".claude.json"),Se(e,"cache","changelog.md")],[t,o,i]=await Promise.all([lt(s,["--help"]).catch(()=>""),lt(s,["--version"]).catch(()=>""),rr(e).catch(()=>[])]),a=ar([...n,...i]),l=await Promise.all(a.map(v=>Nn(v).catch(()=>""))),f=or([t,o,...l].join(`
381
- `));return dt([...ct,...f])}function lt(s,e,n=5e3){return new Promise((t,o)=>{Vo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function Nn(s){return Zo(s,"utf-8")}async function rr(s){let e=[Se(s,"projects"),Se(s,"telemetry")],n=[];for(let t of e)await Jn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Jn(s,e,n){if(n<0)return;let t;try{t=await Ko(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=Se(s,o.name);if(o.isDirectory()){await Jn(i,e,n-1);return}if(!(!o.isFile()||!ir(o.name)))try{let a=await er(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function ir(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function dt(s){let e=new Set,n=[];for(let t of s)e.has(t.id)||(e.add(t.id),n.push(t));return n}function ar(s){return[...new Set(s)]}function lr(s){return s.charAt(0).toUpperCase()+s.slice(1)}var ut=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,o=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),o}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let o=this.bufferEvent(n,e);for(let i of this.listeners)i(o,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let o={...n,seq:t.nextSeq++};return t.events.push(o),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),o}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let a=n<0?t.events:t.events.filter(l=>l.seq>n);return{jobId:e,events:a,currentSeq:t.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(e,n,t){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};t.on("exit",a),t.on("error",a),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(a,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="materialize_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{mkdir as cr,readFile as dr,writeFile as ur}from"fs/promises";import{dirname as pr,join as fr}from"path";var hr={version:1,threads:{}},pt=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=fr(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await dr(this.filePath,"utf-8"),n=JSON.parse(e);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...hr,threads:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>t.has(a)))return o;return null}async createThread(e,n){let t=await this.load(),o={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=o,await this.persist(),o}async appendMessage(e,n){let o=(await this.load()).threads[e];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async appendMessageBeforeQueuedReplies(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=o.messages.findIndex(a=>a.role==="human"&&!!a.replyToQuestion&&a.queued);i>=0?o.messages.splice(i,0,n):o.messages.push(n),o.updatedAt=Date.now(),await this.persist()}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let a=i.messages.filter(l=>l.jobId===n);if(a.length===0)return!1;for(let l of a)Object.assign(l,t);return i.updatedAt=Date.now(),await this.persist(),!0}async addElementIdentifiers(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.persist(),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((o,i)=>i.updatedAt-o.updatedAt),t.slice(0,e).map(o=>{let a=o.messages.find(l=>l.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await cr(pr(this.filePath),{recursive:!0}),await ur(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function zn(s){return gr(s).slice(0,12)}var mr=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function gr(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):yr(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let B=7;B>=0;B--)e.push(n/Math.pow(2,B*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,l=1359893119,f=2600822924,v=528734635,x=1541459225,E=new Array(64);for(let B=0;B<e.length;B+=64){for(let z=0;z<16;z++){let Z=B+z*4;E[z]=(e[Z]<<24|e[Z+1]<<16|e[Z+2]<<8|e[Z+3])>>>0}for(let z=16;z<64;z++){let Z=xe(E[z-15],7)^xe(E[z-15],18)^E[z-15]>>>3,O=xe(E[z-2],17)^xe(E[z-2],19)^E[z-2]>>>10;E[z]=E[z-16]+Z+E[z-7]+O>>>0}let J=t,U=o,W=i,w=a,q=l,V=f,Q=v,K=x;for(let z=0;z<64;z++){let Z=xe(q,6)^xe(q,11)^xe(q,25),O=q&V^~q&Q,A=K+Z+O+mr[z]+E[z]>>>0,k=xe(J,2)^xe(J,13)^xe(J,22),M=J&U^J&W^U&W,N=k+M>>>0;K=Q,Q=V,V=q,q=w+A>>>0,w=W,W=U,U=J,J=A+N>>>0}t=t+J>>>0,o=o+U>>>0,i=i+W>>>0,a=a+w>>>0,l=l+q>>>0,f=f+V>>>0,v=v+Q>>>0,x=x+K>>>0}return[t,o,i,a,l,f,v,x].map(B=>B.toString(16).padStart(8,"0")).join("")}function xe(s,e){return s>>>e|s<<32-e}function yr(s){let e=[];for(let n=0;n<s.length;n++){let t=s.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var Bn={name:"@popmelt.com/core",version:"0.8.4",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var Fn=Bn.version;var Tr=1111,Ar=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Cr=1800*1e3,$r=3600*1e3,Un=45e3,_r=5e3,Or=1e4;function Wn(s){return s.length<=1?s[0]??"":["The developer sent these queued steering messages while you were working:","",...s.map((e,n)=>`${n+1}. ${e}`)].join(`
382
- `)}function Qn(s){if(!s)return!1;try{let e=new URL(s);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Dr(s){let e=[];for(let n of s)if(n.type==="delta"){let t=n.text;if(!t)continue;let o=e[e.length-1];o&&o.kind==="text"?o.text+=t:e.push({kind:"text",text:t})}else if(n.type==="tool_use"){let t=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,l;switch(t){case"Read":l=a?`Reading ${a}`:"Reading file";break;case"Edit":l=a?`Editing ${a}`:"Editing file";break;case"Write":l=a?`Writing ${a}`:"Writing file";break;case"Bash":l=i?i.split(`
383
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=t?`Using ${t}`:"tool";break}let f=o??i??void 0,v=e[e.length-1];v&&v.kind==="tool_group"&&v.tool===t?v.items.push({label:l,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:l,detail:f}]})}return e}function Nr(s,e){if(s.processedIds.length===0&&s.success)return"No unmaterialized pattern decisions were ready for model materialization.";let n=[];return s.success?n.push("Model suggestion ready."):n.push("Model materialization failed."),s.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),s.error&&(n.push(""),n.push(`Error: ${s.error}`),n.push("The selected decisions were not marked applied and remain visible in materialization history.")),n.join(`
384
- `)}function Jr(s,e=96){let n=s.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Hn(s){let e=s.styleModifications.flatMap(a=>{let l=a.element?.reactComponent||a.element?.tagName||a.selector;return a.changes.map(f=>`${l}: ${f.property} ${f.original||"unset"} -> ${f.modified||"unset"}`)}),n=(s.spacingTokenChanges??[]).map(a=>`${a.tokenName}: ${a.originalPx}px -> ${a.newPx}px`),t=(s.textModifications??[]).map(a=>`${a.element?.reactComponent||a.element?.tagName||a.selector}: text ${a.original||"empty"} -> ${a.modified||"empty"}`),o=s.annotations.map(a=>{let l=a.instruction?.trim();if(l)return l;if(a.imageCount&&a.imageCount>0)return`${a.imageCount} image${a.imageCount===1?"":"s"}`;let f=a.elements?.[0]?.reactComponent||a.elements?.[0]?.selector||a.linkedSelector||a.type;return`${a.type==="annotation"?"Annotation":`${a.type} annotation`} on ${f}`}),i=[...e,...t,...n,...o].map(a=>Jr(a)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function zr(s,e){let n=s.headers.origin;Qn(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function m(s,e,n){s.writeHead(e,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}async function Br(s){let e=[],n=0;for await(let o of s){let i=typeof o=="string"?Buffer.from(o):o;if(n+=i.length,n>16384)throw new Error("Request body too large");e.push(i)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Fr(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function jr(s,e){if(!s)return e;let n=s.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,o,i]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(o,16)};${parseInt(i,16)}m${e}\x1B[0m`}function ht(s,e){try{s.res.write(`event: ${e.type}
182
+ `,W);if(ee===-1)break;let H=r.slice(W,ee).toString("utf-8"),te=ee+4,ne=r.indexOf(s,te),ge=ne!==-1?ne-2:r.length;N.push({headers:H,body:r.slice(te,ge)}),_=ne!==-1?ne:r.length}for(let T of N){let B=T.headers.match(/name="([^"]+)"/);if(!B)continue;let W=B[1];if(W==="screenshot")c=T.body;else if(W==="feedback")d=T.body.toString("utf-8");else if(W==="color")l=T.body.toString("utf-8");else if(W==="provider")v=T.body.toString("utf-8");else if(W==="model")R=T.body.toString("utf-8");else if(W==="reasoningEffort")b=T.body.toString("utf-8");else if(W==="serviceTier")I=T.body.toString("utf-8");else if(W==="goal")g=T.body.toString("utf-8");else if(W==="pageUrl")p=T.body.toString("utf-8");else if(W==="viewport")h=T.body.toString("utf-8");else if(W==="planId")f=T.body.toString("utf-8");else if(W==="manifest")y=T.body.toString("utf-8");else if(W==="tasks")x=T.body.toString("utf-8");else if(W==="sourceId")S=T.body.toString("utf-8");else if(W.startsWith("screenshot-")){let ee=W.slice(11);try{let H=decodeURIComponent(ee);J.push({pathname:H,data:T.body})}catch{}}else if(W.startsWith("image-")){let ee=W.split("-"),H=parseInt(ee[ee.length-1],10),te=ee.slice(1,-1).join("-");te&&!isNaN(H)&&A.push({annotationId:te,index:H,data:T.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:v,model:R,reasoningEffort:b,serviceTier:I,goal:g,pageUrl:p,viewport:h,planId:f,manifest:y,tasks:x,sourceId:S,pastedImages:A,pageScreenshots:J}}function Qa(o){return new Promise((e,n)=>{let t=[];o.on("data",r=>t.push(r)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as Xa}from"crypto";var Ya=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,Za=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),ec=new Set(["strengthened","weakened","mixed","unknown"]);function Qt(o,e=180){if(typeof o!="string")return;let n=o.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function tc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function zr(o,e,n,t=Date.now()){let r=tc(o);if(!r)return null;let s=typeof r.transition=="string"&&Za.has(r.transition)?r.transition:null,i=Qt(r.focus);if(!s||!i)return null;let c=typeof r.evidencePosture=="string"&&ec.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Xa(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Qt(r.seeking),workingHypothesis:Qt(r.workingHypothesis),evidencePosture:c,update:Qt(r.update),nextObservation:Qt(r.nextObservation)},contextPolicy:"exclude"}}function Ao(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function nc(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(Ya,(c,d)=>{try{let l=zr(JSON.parse(d),e,s);if(!l)return"";let v=Ao(l);if(r.has(v))return"";r.add(v),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
183
+
184
+ `).trim(),orientations:t}}function oc(o){let e="<orientation>",n=Math.min(o.length,e.length-1);for(let t=n;t>0;t--)if(e.startsWith(o.slice(-t)))return t;return 0}var On=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let c=oc(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,r);let s=this.buffer.indexOf("</orientation>",r+13);if(s<0){this.buffer=this.buffer.slice(r);break}let i=this.buffer.slice(r+13,s).trim();this.buffer=this.buffer.slice(s+14);try{let c=zr(JSON.parse(i),this.jobId,this.sequence);if(!c)continue;let d=Ao(c);if(this.signatures.has(d))continue;this.signatures.add(d),t.push(c),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=nc(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=Ao(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Ur=`## Public orientation updates
185
+ During meaningful transitions in the work, emit a brief public coordination update using this exact form:
186
+ <orientation>{"transition":"focus_shifted","focus":"Investigating the responsive overflow","seeking":"Which container introduces the extra width","update":"Padding is no longer the leading explanation","nextObservation":"Inspect computed widths at the failing breakpoint"}</orientation>
187
+
188
+ Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
189
+ Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
190
+
191
+ These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function Xt(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),s=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${s} \u2192 Elements: ${r||"none"}`);let i=e?.[t.id];if(i&&i.length>0)for(let c of i)n.push(` Attached image: use the Read tool to view ${c}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let s of t.changes)n.push(`- ${t.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=JSON.stringify(t.original),i=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${c}: ${s} \u2192 ${i}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",i=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${s} \u2192 ${t.targetParentSelector}${i}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
192
+ ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let r of t.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let t=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[t.selector];t.reactComponent&&r.push(`(${t.reactComponent})`),t.context&&r.push(`in ${t.context}`),t.textContent&&r.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
193
+ `)}function qr(o,e,n){let t=[],s=new Set(e.annotations.map(i=>i.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!s&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let i=0;for(let c of n.threadHistory)if(c.role==="human")i++,c.replyToQuestion?(t.push(`### Round ${i} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${i} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${i} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${i} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,v=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${v} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0)if(t.push(""),t.push("Rules:"),i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"scope"in i[0]){let v=new Map;for(let R of i)if(typeof R=="object"&&R!==null&&"text"in R){let b=R,I=b.scope||"general";v.has(I)||v.set(I,[]),v.get(I).push(b.text)}for(let[R,b]of v){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let I of b)t.push(`- ${I}`)}}else for(let v of i)typeof v=="string"&&t.push(`- ${v}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),s){let i=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;c.has(l)||c.set(l,[]),c.get(l).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of c){t.push(""),t.push(`## Page: ${d}`);let v=i[d];v&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&n?.provider!=="codex"&&(Object.keys(i).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:l,styleModifications:e.styleModifications},b=Xt(R,n?.imagePaths);b&&(t.push(""),t.push(b))}}else{let i=Xt(e,n?.imagePaths);i&&(t.push(""),t.push(i))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
194
+ `)}function Wr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Hr(o,e,n,t){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let s=e.find(i=>i.role==="human"&&i.feedbackContext);if(s?.feedbackContext&&(r.push(""),r.push(s.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let i=0;for(let c of e)c.role==="human"?(i++,c.replyToQuestion?(r.push(`### Round ${i} (human) \u2014 reply`),r.push(`"${c.replyToQuestion}"`)):(r.push(`### Round ${i} (human)`),c.feedbackSummary&&r.push(`Annotations: ${c.feedbackSummary}`))):c.question?(r.push(`### Round ${i} (assistant) \u2014 question`),r.push(`"${c.question}"`)):(r.push(`### Round ${i} (assistant)`),c.responseText&&r.push(`Response: ${c.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let i of t)r.push(`Attached image: use the Read tool to view the image at: ${i}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
195
+ `)}function rc(o){if(typeof o!="object"||o===null)return!1;let e=o;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function sc(o){if(typeof o!="object"||o===null||typeof o.annotationId!="string"||o.status!=="resolved"&&o.status!=="needs_review"||typeof o.summary!="string")return!1;let e=o;for(let n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!rc(e[n]))return!1;return!0}function Gr(o){let e=o.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(sc):[]}catch{return[]}}function Vr(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let r=t;return(r.category==="token"||r.category==="component"||r.category==="element")&&typeof r.element=="string"&&typeof r.decision=="string"&&typeof r.reason=="string"}):[]}catch{return[]}}import{execFile as ic}from"child_process";import{readdir as ac,readFile as cc,stat as dc}from"fs/promises";import{homedir as Yt}from"os";import{join as Qe}from"path";var Jn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Kr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Kr()}],Zt=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],en={id:"",label:"Default",source:"cli"},lc=/^\s*-\s+"([^"]+)"/;function pc(o){let e=[],n=!1;for(let t of o.split(`
196
+ `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(lc);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:_o(s),source:"cli"})}return Nn([en,...e])}function uc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,r)=>{let s=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,i=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return s-i}).flatMap(t=>{let r=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!r)return[];let s=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():_o(r),i=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:s,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...i&&i.length>0?{supportedReasoningLevels:i}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function Kr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function mc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Nn(e.map(n=>({id:n,label:_o(n),source:"cli"})))}function _o(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let s=t[1]==="sonnet"?"Sonn":yc(t[1]),i=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${s}${i}${t[4]?" Fast":""}`}let r=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let s=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${s}`:r[3]==="codex"?`Codex ${s}`:r[3]==="spark"?`Spark ${s}`:`GPT ${s}`}return n}async function Qr(o="copilot"){let e=await Dn(o,["help","config"]),n=pc(e);return n.length>1?n:[en]}async function Xr(o="codex"){let e=await Dn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(Yt(),".codex");return Zr(Qe(t,"models_cache.json"))}),n=uc(e);return n.length>0?Nn([...n,...Zt]):Zt}async function Yr(o="claude"){let e=Qe(Yt(),".claude"),n=[Qe(Yt(),".claude","stats-cache.json"),Qe(Yt(),".claude","settings.json"),Qe(Yt(),".claude.json"),Qe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Dn(o,["--help"]).catch(()=>""),Dn(o,["--version"]).catch(()=>""),fc(e).catch(()=>[])]),i=gc([...n,...s]),c=await Promise.all(i.map(l=>Zr(l).catch(()=>""))),d=mc([t,r,...c].join(`
197
+ `));return Nn([...Jn,...d])}function Dn(o,e,n=5e3){return new Promise((t,r)=>{ic(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function Zr(o){return cc(o,"utf-8")}async function fc(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await es(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function es(o,e,n){if(n<0)return;let t;try{t=await ac(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Qe(o,r.name);if(r.isDirectory()){await es(s,e,n-1);return}if(!(!r.isFile()||!hc(r.name)))try{let i=await dc(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function hc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Nn(o){let e=new Set,n=[];for(let t of o)e.has(t.id)||(e.add(t.id),n.push(t));return n}function gc(o){return[...new Set(o)]}function yc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Bn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let s=this.queue.length-1;s>=0;s--)if(this.queue[s]?.threadId===e.threadId){n=s;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let s of this.listeners)s(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},s=this.activeJobs.has(e);if(!t)return null;let i=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:i,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:s}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let s=!1,i=()=>{s||(s=!0,r())};t.on("exit",i),t.on("error",i),setTimeout(()=>{if(!s){try{t.kill("SIGKILL")}catch{}setTimeout(i,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as He}from"crypto";import{createHash as vc}from"crypto";import{mkdir as wc,open as Ic,readFile as ts,readdir as bc,rename as xc,unlink as Sc}from"fs/promises";import{dirname as Pc,join as Ct}from"path";function $e(o){return structuredClone(o)}function ns(o){return vc("sha256").update(JSON.stringify(o)).digest("hex")}async function tn(o,e){await wc(Pc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ic(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
198
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await xc(n,o)}catch(r){throw await Sc(n).catch(()=>{}),r}}function kc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Rc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=$e(e):o.explanations.push($e(e))}function Co(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")Rc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(s=>s.id===t.evidence.id)||(r.evidence.push($e(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,$e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(i=>i.id===t.relation.fromId),s=n.explanations.some(i=>i.id===t.relation.toId)||n.concrete.some(i=>i.id===t.relation.toId);if(!r||!s)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(i=>i.id===t.relation.id)||n.relations.push($e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Tc(o,e){let n=[],t=$e(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let s=t.explanations.find(i=>i.id===r.explanationId);s&&n.unshift({op:"add_explanation",explanation:$e(s)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let s=t.concrete.find(i=>i.id===r.concreteId);s&&n.unshift({op:"add_concrete",concrete:$e(s)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let s=r.op==="replace_explanation"?r.explanation.id:r.explanationId,i=t.explanations.find(c=>c.id===s);i&&n.unshift({op:"replace_explanation",explanation:$e(i)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let s=t.relations.find(i=>i.id===r.relationId);s&&n.unshift({op:"add_relation",relation:$e(s)})}t=Co(t,[r])}return n}function os(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Fn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ct(e,".popmelt","imprint"),this.manifestPath=Ct(this.imprintDir,"manifest.json"),this.graphPath=Ct(this.imprintDir,"graph.json"),this.journalDir=Ct(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ts(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async load(){let e=await this.readManifest(),t=(await bc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=kc(this.projectId,e.createdAt),s=[],i=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await ts(Ct(this.journalDir,t[c]),"utf8")),{hash:l,...v}=d;if(d.sequence!==c+1||d.previousHash!==i||l!==ns(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Co(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},s.push(d),i=d.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=Tc(t.graph,e.mutations),i={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:s,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...i,hash:ns(i)},d=Co(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await tn(Ct(this.journalDir,l),c);let v={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await tn(this.graphPath,d),await tn(this.manifestPath,v),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(i.mutations.flatMap(os));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(v=>os(v).some(R=>c.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await tn(this.graphPath,e.graph),await tn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var jc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ec=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Mc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ln(o){return new Set(Mc(o).split(" ").filter(e=>e.length>2&&!Ec.has(e)))}function zn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function $o(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function ot(o,e,n){return{id:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function Ee(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function rs(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let n=e.values.filter(t=>typeof t=="string"&&!!t.trim());return n.length?{kind:e.kind,values:n}:void 0}function Ac(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Oo(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let b=String(r.reason);if(!jc.has(b))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:b},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let s=r.summary,i=s?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(i)))throw new Error("summary.kind is invalid");let c={kind:i,title:Ee(s?.title,120),detail:Ee(s?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(b=>typeof b=="string"&&!!b.trim()):[],l=[];for(let b of Array.isArray(r.mutations)?r.mutations:[]){if(!b||typeof b!="object")continue;let I=b;if(I.op==="add"&&["intention","principle","pattern"].includes(String(I.kind))){let g=Ee(I.statement),p=Ee(I.rationale);if(!g||!p)continue;l.push({op:"add",clientId:Ee(I.clientId,100)||void 0,kind:I.kind,statement:g,rationale:p,scope:rs(I.scope)})}else if(I.op==="revise"&&typeof I.explanationId=="string"){let g={op:"revise",explanationId:I.explanationId,statement:Ee(I.statement)||void 0,rationale:Ee(I.rationale)||void 0,scope:rs(I.scope),reopenGrounding:I.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(I.op==="evidence"&&typeof I.explanationId=="string"&&["supports","challenges","excepts"].includes(String(I.stance))){let g=Ee(I.summary);g&&l.push({op:"evidence",explanationId:I.explanationId,stance:I.stance,summary:g})}else if(I.op==="relation"&&typeof I.fromId=="string"&&typeof I.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(I.type)))l.push({op:"relation",type:I.type,fromId:I.fromId,toId:I.toId,rationale:Ee(I.rationale)});else if(I.op==="supersede"&&typeof I.explanationId=="string"&&typeof I.replacementId=="string"){let g=Ee(I.reason);g&&l.push({op:"supersede",explanationId:I.explanationId,replacementId:I.replacementId,reason:g})}else if(I.op==="bind_concrete"&&typeof I.explanationId=="string"){let g=Ee(I.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:I.explanationId,modelPath:g,rationale:Ee(I.rationale)})}else I.op==="retire"&&typeof I.explanationId=="string"&&l.push({op:"retire",explanationId:I.explanationId,reason:Ee(I.reason)})}let v=r.grounding,R=v&&typeof v.explanationId=="string"&&Ee(v.question)?{explanationId:v.explanationId,question:Ee(v.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Do(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(s=>` - Concrete terminal: ${s.modelPath} = ${JSON.stringify(s.value)}`)].join(`
199
+ `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]}},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
200
+ `)}var nn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Fn(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Ln(e.text??""),t=Ln((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:s}=await this.store.load(),i=s.explanations.filter(d=>d.state!=="retired"&&d.state!=="challenged").map(d=>{let l=Ln([d.statement,d.rationale].join(" ")),v=Ln(d.scope.values.join(" ")),R=zn(l,n),b=zn(v,n),I=zn(v,t),g=zn(l,t),p=R+b*.2+I*.25+g*.1+(d.state==="grounded"?.08:0)+(r.has(d.id)?1:0),h=r.has(d.id)||(n.size?R>=.12||b>=.5:I>=.2||g>=.2);return{item:d,score:p,relevant:h}}).filter(d=>d.relevant&&d.score>=.18).sort((d,l)=>l.score-d.score||l.item.updatedAt.localeCompare(d.item.updatedAt)),c=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,c).map(({item:d})=>{let l=new Set(s.relations.filter(v=>v.fromId===d.id&&v.type==="instantiates").map(v=>v.toId));return{id:d.id,kind:d.kind,statement:d.statement,rationale:d.rationale,scope:d.scope,state:d.state,concrete:s.concrete.filter(v=>l.has(v.id)).map(v=>({id:v.id,modelPath:v.modelPath,value:v.value}))}}),truncated:i.length>c,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,c=new Map,d=[],l=new Set,v=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=He();S.clientId&&i.set(S.clientId,A);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,_={id:A,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:$o(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(A,_),l.add(A),d.push({op:"add_explanation",explanation:_})}let R=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let A=R(S.explanationId),J=s.get(A);if(J?.state!=="grounded")continue;let _=He(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?$o(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(_,N),c.set(A,_),l.add(_),d.push({op:"add_explanation",explanation:N}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let b=S=>{let A=R(S);return c.get(A)??A};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=b(S.explanationId);if(!s.has(J))continue;let _=Ac(n.concreteModel,S.modelPath);if(!_.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(_.value));N||(N={id:He(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:N})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=b(S.fromId),_=b(S.toId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_relation",relation:{id:He(),type:S.type,fromId:J,toId:_,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(_);continue}if(S.op==="supersede"){let J=b(S.explanationId),_=b(S.replacementId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_evidence",explanationId:J,evidence:ot(n,"challenges",S.reason)}),d.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:_},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"contradicts",fromId:_,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(_);continue}let A=b(S.explanationId);if(s.has(A))if(l.add(A),S.op==="revise"){if(c.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:$o(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:A,patch:J,updatedAt:t})}else S.op==="evidence"?(d.push({op:"add_evidence",explanationId:A,evidence:ot(n,S.stance,S.summary)}),S.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(d.push({op:"add_evidence",explanationId:A,evidence:ot(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let A=b(S),J=s.get(A);!J||J.state==="grounded"||J.state==="retired"||v.has(A)&&!l.has(A)||(l.has(A)||(l.add(A),d.push({op:"add_evidence",explanationId:A,evidence:{...ot(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=He(),g=await this.store.commit({transactionId:I,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),h=[...l].flatMap(S=>{let A=p.get(S);if(!A)return[];let J=!r.graph.explanations.some(N=>N.id===S),_=A.state==="challenged"||A.state==="retired";return[{explanationId:S,action:J?"added":_?"challenged":"revised",statement:A.statement,state:A.state}]}),f=e.grounding?b(e.grounding.explanationId):void 0,y=f?p.get(f):void 0,x=y?.state==="testing"&&!v.has(y.id)?{explanationId:y.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:I,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:h,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let v of l)await this.store.undo(v,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(v=>v.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:i,summary:d,mutations:c})}};function ss(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Un(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Jo(o){if(!o)return null;try{let e=new URL(o);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function is(o){let e=Jo(Un(o.origin));if(e)return e;let n=Jo(Un(o.referer));if(n)return n;let t=Un(o["x-forwarded-host"]);if(!t)return null;let r=Un(o["x-forwarded-proto"])==="https"?"https":"http";return Jo(`${r}://${t}`)}function as(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),i=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=i.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:c,actionableProposals:i}}import{createHash as qn}from"crypto";import{mkdir as on,readFile as bt,unlink as $c,writeFile as Ot}from"fs/promises";import{dirname as Wn,extname as Oc,join as Oe}from"path";var _c={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function Cc(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function cs(o,e){let n=e??Cc(o);return{kind:n,..._c[n]}}function $t(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ds(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Dc={version:1,threads:{}},ls=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],rn={version:2,updatedAt:0,files:{}};function Jc(o){return JSON.stringify(o,null,2)}function Nc(o){return Object.fromEntries(ls.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Bc(o){let e={...o};for(let n of ls)delete e[n];return e}function Dt(o){let e=o;if(o.error){let n=cs(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=$t(e.result,!1),t=$t(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Hn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Oe(e,".popmelt");this.legacyFilePath=Oe(n,"threads.json"),this.threadsDir=Oe(n,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(n,"artifacts","thread-messages"),this.mediaDir=Oe(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await bt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let s=await this.readThread(Oe(this.threadsDir,r));s&&(n[t]=s)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await bt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Dt)}]))},this.index={...rn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Dc,threads:{}},this.index={...rn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Dt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=r.messages.findIndex(i=>i.role==="human"&&!!i.replyToQuestion&&i.queued);s>=0?r.messages.splice(s,0,Dt(n)):r.messages.push(Dt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=s.messages.filter(c=>c.jobId===n);if(i.length===0)return!1;for(let c of i)if(Object.assign(c,t),c.error){let d=Dt(c);Object.assign(c,d),delete c.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(h=>h.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(h=>h.role==="assistant"),d=h=>{if(h.role!=="assistant")return;if(h.question)return h.question;let f=h.imprintSummary?.grounding;if(f?.question&&!h.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(h=>!!d(h)),v=r.messages.findLastIndex(h=>h.role==="human"),R=l>v?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,I=Array.from(new Set(r.messages.slice(0,Math.max(0,v)).filter(h=>h.role==="assistant"&&!!h.jobId).map(h=>h.jobId))),g=c.some(h=>!!h.responseText||!!h.question||!!h.result||!!h.memoryReviewCard||!!h.memoryReceipt),p=c.some(h=>!!h.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:b,pendingQuestion:R,acknowledgedJobIds:I,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await bt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...s})=>{let i={};if(r?.path)try{let c=await bt(Oe(Wn(this.legacyFilePath),r.path),"utf8");qn("sha256").update(c).digest("hex")===r.sha256&&(i=JSON.parse(c))}catch{}return Dt({...s,...i})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Nc(e),t=Bc(e);if(Object.keys(n).length===0)return t;let r=Jc(n),s=qn("sha256").update(r).digest("hex"),i=Oe("artifacts","thread-messages",`${s}.json`);await on(this.artifactsDir,{recursive:!0});try{await bt(Oe(Wn(this.legacyFilePath),i),"utf8")}catch{await Ot(Oe(Wn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Wn(t)===this.mediaDir)return t;try{let r=await bt(t),s=qn("sha256").update(r).digest("hex"),i=Oe(this.mediaDir,`${s}${Oc(t)||".bin"}`);await on(this.mediaDir,{recursive:!0});try{await bt(i)}catch{await Ot(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await on(this.threadsDir,{recursive:!0});let n=this.index??{...rn,files:{}},t=n.files[e.id]??`${qn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(i=>this.encodeMessage(i))),s={...e,version:2,messages:r};await Ot(Oe(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Ot(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await on(this.threadsDir,{recursive:!0}),this.index=this.index??{...rn,files:{}},await Ot(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...rn,files:{}},t=n.files[e];t&&await $c(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await on(this.threadsDir,{recursive:!0}),await Ot(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Fc,open as Lc,readFile as zc,rename as Uc,unlink as qc}from"fs/promises";import{dirname as Wc,join as Hc}from"path";var ps={schemaVersion:1,theme:"auto",updatedAt:null};function us(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Gc(o,e){await Fc(Wc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Lc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
201
+ `,"utf8"),await t.sync()}finally{await t.close()}await Uc(n,o)}catch(t){throw await qc(n).catch(()=>{}),t}}var Gn=class{constructor(e){this.path=Hc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await zc(this.path,"utf8")),n=us(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...ps}}}catch{return{exists:!1,preferences:{...ps}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Gc(this.path,n),n}};function ms(o){return us(o)!==null}function fs(o){return Kc(o).slice(0,12)}var Vc=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Kc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Qc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(n/Math.pow(2,b*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,c=1359893119,d=2600822924,l=528734635,v=1541459225,R=new Array(64);for(let b=0;b<e.length;b+=64){for(let A=0;A<16;A++){let J=b+A*4;R[A]=(e[J]<<24|e[J+1]<<16|e[J+2]<<8|e[J+3])>>>0}for(let A=16;A<64;A++){let J=Xe(R[A-15],7)^Xe(R[A-15],18)^R[A-15]>>>3,_=Xe(R[A-2],17)^Xe(R[A-2],19)^R[A-2]>>>10;R[A]=R[A-16]+J+R[A-7]+_>>>0}let I=t,g=r,p=s,h=i,f=c,y=d,x=l,S=v;for(let A=0;A<64;A++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),_=f&y^~f&x,N=S+J+_+Vc[A]+R[A]>>>0,T=Xe(I,2)^Xe(I,13)^Xe(I,22),B=I&g^I&p^g&p,W=T+B>>>0;S=x,x=y,y=f,f=h+N>>>0,h=p,p=g,g=I,I=N+W>>>0}t=t+I>>>0,r=r+g>>>0,s=s+p>>>0,i=i+h>>>0,c=c+f>>>0,d=d+y>>>0,l=l+x>>>0,v=v+S>>>0}return[t,r,s,i,c,d,l,v].map(b=>b.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Qc(o){let e=[];for(let n=0;n<o.length;n++){let t=o.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var hs={name:"@popmelt.com/core",version:"0.8.6",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var sn=hs.version;var ad=1111,cd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],dd=1800*1e3,ld=3600*1e3,vs=45e3,pd=5e3,ud=1e4;function ws(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
202
+ `)}function Kn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function md(o,e){if(e.size===1)return[...o].reverse().find(n=>{let t=n.imprintSummary;return n.role==="assistant"&&!!t?.grounding&&!t?.resolvedAction&&e.has(t.grounding.explanationId)})}function Rs(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function fd(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let s=n[n.length-1];s&&s.kind==="text"?s.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",s=t.file??void 0,i=t.content??void 0,c=s?s.split("/").pop()??s:void 0,d;switch(r){case"Read":d=c?`Reading ${c}`:"Reading file";break;case"Edit":d=c?`Editing ${c}`:"Editing file";break;case"Write":d=c?`Writing ${c}`:"Writing file";break;case"Bash":d=i?i.split(`
203
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let l=s??i??void 0,v=s?Bo(s)?s:ks(e,s):void 0,R=n[n.length-1];R&&R.kind==="tool_group"&&R.tool===r?R.items.push({label:d,detail:l,...v?{filePath:v}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...v?{filePath:v}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function hd(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let n=[];return o.success?n.push("Model suggestion ready."):n.push("Model projection failed."),o.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(n.push(""),n.push(`Error: ${o.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
204
+ `)}function gd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Is(o){let e=o.styleModifications.flatMap(i=>{let c=i.element?.reactComponent||i.element?.tagName||i.selector;return i.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(i=>`${i.tokenName}: ${i.originalPx}px -> ${i.newPx}px`),t=(o.textModifications??[]).map(i=>`${i.element?.reactComponent||i.element?.tagName||i.selector}: text ${i.original||"empty"} -> ${i.modified||"empty"}`),r=o.annotations.map(i=>{let c=i.instruction?.trim();if(c)return c;if(i.imageCount&&i.imageCount>0)return`${i.imageCount} image${i.imageCount===1?"":"s"}`;let d=i.elements?.[0]?.reactComponent||i.elements?.[0]?.selector||i.linkedSelector||i.type;return`${i.type==="annotation"?"Annotation":`${i.type} annotation`} on ${d}`}),s=[...e,...t,...n,...r].map(i=>gd(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function yd(o,e){let n=o.headers.origin;Rs(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function E(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function ze(o){let e=[],n=0;for await(let r of o){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>16384)throw new Error("Request body too large");e.push(s)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function vd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function wd(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,r,s]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(r,16)};${parseInt(s,16)}m${e}\x1B[0m`}function Qn(o,e){try{o.res.write(`event: ${e.type}
385
205
  data: ${JSON.stringify(e)}
386
206
 
387
- `)}catch{}}function Ue(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function Lr(s){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${s}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function Ur(s,e){return new Promise((n,t)=>{let o=a=>{s.removeListener("listening",i),t(a)},i=()=>{s.removeListener("error",o),n()};s.once("error",o),s.once("listening",i),s.listen(e,"127.0.0.1")})}function Gn(s){try{let e=mt("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=mt("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=mt("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return wr("sha256").update(`${e}
207
+ `)}catch{}}function xt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function Id(o){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function bd(o,e){return new Promise((n,t)=>{let r=i=>{o.removeListener("listening",s),t(i)},s=()=>{o.removeListener("error",r),n()};o.once("error",r),o.once("listening",s),o.listen(e,"127.0.0.1")})}function bs(o){try{let e=Xn("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=Xn("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=Xn("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Ps("sha256").update(`${e}
388
208
  ${t}
389
- ${o}`).digest("hex").slice(0,16)}catch{return}}async function Xn(s={}){let e=s.port??Tr,n=s.projectRoot??process.cwd(),t=await br(n).catch(()=>n),o=zn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??ye(Mr(),"popmelt-bridge"),l=s.maxTurns??40,f=s.maxBudgetUsd??1,v=[...s.allowedTools??Ar],x=s.claudePath??"claude",E=s.copilotPath??"copilot",B=s.provider??"claude",J=s.timeoutMs,U=s.restartMode??"embedded",W=e,w={},q={claude:x,codex:"codex",copilot:E};for(let[r,c]of Object.entries(q))try{let u=c.includes("/")?c:mt("which",[c],{encoding:"utf-8"}).trim();w[r]={available:!0,path:u}}catch{w[r]={available:!1,path:null}}function V(r,c){return new Promise(u=>{let p=jn(c,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=g=>{h||(h=!0,u(g))},P=setTimeout(()=>{p.kill("SIGTERM"),d(!0)},5e3);p.on("error",()=>{clearTimeout(P),d(!1)}),p.on("close",g=>{clearTimeout(P),d(g===0)})})}await Promise.all([(async()=>{w.claude&&(w.claude.models=w.claude.available&&w.claude.path?await Dn(w.claude.path).catch(()=>ct):ct)})(),(async()=>{w.codex&&(w.codex.models=w.codex.available&&w.codex.path?await On(w.codex.path).catch(()=>Fe):Fe)})(),(async()=>{w.copilot&&(w.copilot.models=w.copilot.available&&w.copilot.path?await _n(w.copilot.path).catch(()=>[je]):[je])})()]);let[Q,K,z]=await Promise.all([Mt(t),Rt(t),Et(t,w.copilot?.path??E)]),Z=await wn(t);w.claude&&(w.claude.mcp=Q),w.codex&&(w.codex.mcp=K),w.copilot&&(w.copilot.mcp=z),Q.found&&Q.name&&v.push(`mcp__${Q.name}__*`),await Sr(a,{recursive:!0}),qn(a).catch(()=>{});let O=new ut(1),A=new st,k=new it(Un),M=null,N=0,$=!1,T=()=>{N+=1,$=!1,M&&clearTimeout(M),M=null},L=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},_=()=>{if(U!=="detached"||k.size>0||$)return;$=!0;let r=++N,c=Date.now()+Or,u=()=>{if(r!==N)return;if(k.size>0){T();return}if(!(O.isRunning||O.depth>0||A.isRunning||A.depth>0)||Date.now()>=c){$=!1,M=setTimeout(L,50),M.unref?.();return}M=setTimeout(u,250),M.unref?.()};u()},ee=new Set,y=new pt(t),le=new Ve(t),ie=new Ke(t),G=new tt(t,le,{claudePath:x,provider:B,timeoutMs:J,onEvent:r=>{for(let c of ee)ht(c,r)}}),ts=20,ns=300*1e3,ve=[];function We(){let r=Date.now()-ns;for(;ve.length>0&&(ve[0].completedAt<r||ve.length>ts);)ve.shift()}let we=new Map,He=null,_t;O.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&ht(p,r)}),A.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&ht(p,r)}),A.setProcessor(async r=>{let c=r.provider??B;try{let u=await G.run({provider:c,model:r.model,threadId:r.threadId,agentSettings:r.agentSettings});if(r.status==="cancelled")return;let p=await G.loadRuns(),h=u.runId?p.runs.find(P=>P.id===u.runId):void 0,d=Nr(u,h);if(r.threadId&&(await y.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})||await y.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})),u.success)r.status="done",r.result=d,A.broadcast({type:"done",jobId:r.id,success:!0,responseText:d,threadId:r.threadId},r.id,r.sourceId),ve.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We();else{if(r.status="error",r.error=u.error??"Materialization failed",r.threadId){let P=`Model materialization failed.
209
+ ${r}`).digest("hex").slice(0,16)}catch{return}}function xd(o,e){let n=o;for(let t of e.split(".").filter(Boolean)){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[t]}return n}async function xs(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let s of[...t].sort((i,c)=>`${i.kind}:${i.value}`.localeCompare(`${c.kind}:${c.value}`)))if(s.kind==="model_path")r.push([s.kind,s.value,xd(n,s.value)]);else if(s.kind==="source_file"){let i=ks(o,s.value),d=i===o||i.startsWith(`${o}/`)?await No(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,d])}else r.push([s.kind,s.value]);return Ps("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ts(o={}){let e=new Date().toISOString(),n=o.port??ad,t=o.projectRoot??process.cwd(),r=await ed(t).catch(()=>t),s=fs(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Me(rd(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,v=[...o.allowedTools??cd],R=o.claudePath??"claude",b=o.copilotPath??"copilot",I=o.provider??"claude",g=o.timeoutMs,p=o.restartMode??"embedded",h=n,f={},y={claude:R,codex:"codex",copilot:b};for(let[a,u]of Object.entries(y))try{let k=u.includes("/")?u:Xn("which",[u],{encoding:"utf-8"}).trim();f[a]={available:!0,path:k}}catch{f[a]={available:!1,path:null}}function x(a,u){return new Promise(k=>{let m=gs(u,["--version"],{stdio:["ignore","ignore","ignore"]}),P=!1,w=$=>{P||(P=!0,k($))},j=setTimeout(()=>{m.kill("SIGTERM"),w(!0)},5e3);m.on("error",()=>{clearTimeout(j),w(!1)}),m.on("close",$=>{clearTimeout(j),w($===0)})})}await Promise.all([(async()=>{f.claude&&(f.claude.models=f.claude.available&&f.claude.path?await Yr(f.claude.path).catch(()=>Jn):Jn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await Xr(f.codex.path).catch(()=>Zt):Zt)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await Qr(f.copilot.path).catch(()=>[en]):[en])})()]);let[S,A,J]=await Promise.all([fo(r),ho(r),go(r,f.copilot?.path??b)]),_=await gr(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=A),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&v.push(`mcp__${S.name}__*`),await Yc(c,{recursive:!0}),Ss(c).catch(()=>{});let N=new Bn(1),T=new bn,B=new Pn(vs),W=null,ee=0,H=!1,te=()=>{ee+=1,H=!1,W&&clearTimeout(W),W=null},ne=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ge=()=>{if(p!=="detached"||B.size>0||H)return;H=!0;let a=++ee,u=Date.now()+ud,k=()=>{if(a!==ee)return;if(B.size>0){te();return}if(!(N.isRunning||N.depth>0||T.isRunning||T.depth>0)||Date.now()>=u){H=!1,W=setTimeout(ne,50),W.unref?.();return}W=setTimeout(k,250),W.unref?.()};k()},X=new Set,G=new Hn(r),U=new _n(r),he=new nn(r,s),M=new Gn(r),Y=new fn(r),ue=new yn(r),ie=new In(r,{claudePath:R,provider:I,timeoutMs:g,loadProjectableDecisions:a=>U.getProjectableDecisions(a),onEvent:a=>{for(let u of X)Qn(u,a)}});U.beginAutomaticInitialization({writerVersion:sn}).then(async a=>{a.state==="ready"?(await U.migrateLegacyEvals(),await U.migrateImprintSnapshot(),await ie.applyCanonicalEntries(await U.getCanonicalModelEntries()),I!=="copilot"&&(await ie.getUnprojectedPatternDecisions()).length>0&&await je({provider:I,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${h}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let De=20,Je=300*1e3,Pe=[];function Ue(){let a=Date.now()-Je;for(;Pe.length>0&&(Pe[0].completedAt<a||Pe.length>De);)Pe.shift()}let Ge=new Map;async function Ye(a){if(a.status!=="applied")return[];let u={version:1,updatedAt:Date.now(),cases:await U.getJournalEvalCases()},k=rr(a,u);if(k.length===0)return[];let m=await U.getEvalDependenciesForDecisions(a.decisionIds),P=a.threadId?await G.getThread(a.threadId):null,w=[...new Set((P?.messages??[]).flatMap(D=>(D.editEvents??[]).flatMap(L=>L.filePath?[L.filePath]:[])).map(D=>Bo(D)?ys(r,D):D))].map(D=>({kind:"source_file",value:D})),j=k.map(D=>{let L=[...new Map([...D.dependencies??[],...m,...w].map(q=>[`${q.kind}:${q.value}:${"subjectId"in q?q.subjectId??"":""}`,q])).values()],F=L.filter(q=>q.kind==="route"),C=L.flatMap(q=>q.kind==="model_path"&&q.value.startsWith("components.")?[q.value.slice(11).split(".")[0]]:[]),O=[...new Set(L.flatMap(q=>"subjectId"in q&&q.subjectId?[q.subjectId]:[]))],K=F.length>0?F.map((q,se)=>({id:`route-${se+1}`,...q.value.includes("*")?{routePattern:q.value}:{route:q.value},components:C.map(ae=>({name:ae})),subjectIds:O})):[{id:C.length>0?`component-${C[0]}`:"current-page",components:C.map(q=>({name:q})),subjectIds:O}];return{...D,dependencies:L,scenarios:D.scenarios?.length?D.scenarios:K}}),$=new Set(u.cases.map(D=>D.id));return await U.syncEvalSpecs(j),await ie.attachGeneratedEvals(a.id,j.map(D=>({evalId:D.id,title:D.title,action:$.has(D.id)&&(a.evalProjections?.some(L=>L.evalId===D.id)||!a.generatedEvalIds?.includes(D.id))?"extended":"created"}))),j.map(D=>D.id)}async function rt(a){let u=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",k=so(a.claim)||"The product satisfies the declared model constraint.",m={id:`eval-decision-${a.decisionId}`,title:u.charAt(0).toUpperCase()+u.slice(1),status:"pending",category:a.modelPath.startsWith("components.")?"component":a.modelPath.startsWith("tokens.")?"visual":"workflow",prompt:"Verify this product expectation across the declared scenarios.",assertions:[k],rationale:`Protects the ${a.modelPath} constraint from implementation drift.`,sourceDecisionIds:[a.decisionId],sourceThreadIds:[],dependencies:[{kind:"model_path",value:a.modelPath}],scenarios:[{id:a.modelPath.startsWith("components.")?`component-${u.replace(/\s+/g,"-")}`:"current-page",components:a.modelPath.startsWith("components.")?[{name:a.modelPath.slice(11).split(".")[0]}]:void 0}]};return await U.syncEvalSpecs([m]),m.id}let ut=null,Jt;N.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&Qn(m,a)}),T.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&Qn(m,a)}),T.setProcessor(async a=>{let u=a.provider??I;try{let k=await ie.run({provider:u,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let m=await ie.loadRuns(),P=k.runId?m.runs.find(j=>j.id===k.runId):void 0;if(k.success&&k.proposalId){let j=await ie.findModelProposal(k.proposalId),$=await ie.loadModel(),D=j?pr(j,$):null;if(j&&D){let L=j.decisionIds.map(C=>({decisionId:C,status:"projected"}));await U.applyModelProjection({runId:j.runId??j.id,presentationJobId:j.presentationJobId,decisionIds:j.decisionIds,changes:D.map(C=>({path:C.path,value:C.value,decisionIds:C.decisionIds})),coverage:L});let F=await ie.applySelectedModelProposal(j.id,D.map(C=>({path:C.path,value:C.value})),D.map(C=>({group:C.path[0]==="rules"||C.path[0]==="components"||C.path[0]==="tokens"?C.path[0]:"model",label:C.label??C.id,detail:C.rationale,path:C.path,value:C.value})),"automatic");F&&await Ye(F)}}let w=hd(k,P);if(a.threadId&&(await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,model:a.model,provider:u})),k.success)a.status="done",a.result=w,T.broadcast({type:"done",jobId:a.id,success:!0,responseText:w,threadId:a.threadId},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue();else{if(a.status="error",a.error=k.error??"Projection failed",a.threadId){let j=`Model projection failed.
390
210
 
391
- ${r.error}`;await y.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})||await y.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})}A.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We()}}catch(u){if(r.status==="cancelled")return;if(r.status="error",r.error=u instanceof Error?u.message:String(u),r.threadId){let p=`Model materialization failed.
211
+ ${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}catch(k){if(a.status==="cancelled")return;if(a.status="error",a.error=k instanceof Error?k.message:String(k),a.threadId){let m=`Model projection failed.
392
212
 
393
- ${r.error}`;await y.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})||await y.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})}A.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We()}}),O.setProcessor(async r=>{let c=r,u=c._replyPrompt,p=c._replyText,h=c._replyImagePaths,d=r.provider??B;r.threadId&&p!==void 0&&await y.updateMessage(r.threadId,r.id,{queued:!1});let P;if(r.threadId){let D=await y.getThread(r.threadId);if(D){for(let H=D.messages.length-1;H>=0;H--)if(D.messages[H].sessionId){P=D.messages[H].sessionId;break}}}let g;if(P&&u){if(g=p??u,h&&h.length>0){g+=`
213
+ ${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}),N.setProcessor(async a=>{let u=a,k=u._replyPrompt,m=u._replyText,P=u._replyImagePaths,w=a.provider??I,j=!!(a.surfacedProposalIds?.length&&k),$=!!u._evalRemediation,D=!j&&!["run_eval","synthesize_evals","synthesize","project_model"].includes(a.kind??"");a.threadId&&m!==void 0&&await G.updateMessage(a.threadId,a.id,{queued:!1});let L;if(a.threadId){let de=await G.getThread(a.threadId);if(de){for(let pe=de.messages.length-1;pe>=0;pe--)if(de.messages[pe].sessionId){L=de.messages[pe].sessionId;break}}}(j||$)&&(L=void 0);let F;if(L&&k){if(F=m??k,P&&P.length>0){F+=`
394
214
 
395
- The developer attached reference images with their reply:`;for(let D of h)g+=`
396
- Attached image: use the Read tool to view the image at: ${D}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?g+=`
215
+ The developer attached reference images with their reply:`;for(let de of P)F+=`
216
+ Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?F+=`
397
217
 
398
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:g+=`
218
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+=`
399
219
 
400
- After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(P)g=ze(r.feedback,r.imagePaths)+`
220
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(L)F=Xt(a.feedback,a.imagePaths)+`
401
221
 
402
222
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
403
223
 
404
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
224
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(w!=="codex"?`
405
225
 
406
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let D=!u&&r.threadId?await y.getThreadHistory(r.threadId):void 0,H=u?null:await G.loadModel();g=u??En(r.screenshotPath,r.feedback,{threadHistory:D&&D.length>0?D:void 0,provider:d,imagePaths:r.imagePaths,designModel:H??void 0,screenshotPaths:r.screenshotPaths})}let b=jr(r.color,`[\u22B9 ${W}:${r.id}]`),I=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${b} Reviewing ${I} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${P?` (resuming: ${P.slice(0,8)})`:""}`);let C=(D,H)=>{D.type==="delta"&&"text"in D?O.accumulateText(H,"response",D.text):D.type==="thinking"&&"text"in D&&O.accumulateText(H,"thinking",D.text),O.broadcast(D,H,r.sourceId)},{process:te,result:X}=d==="codex"?Ye(r.id,{prompt:g,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:P,model:r.model,configOverrides:qe(r.agentSettings),onEvent:C}):d==="copilot"?Vt(r.id,{prompt:g,projectRoot:t,resumeSessionId:P,model:r.model,timeoutMs:J,copilotPath:w.copilot?.path??E,onEvent:C}):Qe(r.id,{prompt:g,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:v,claudePath:x,resumeSessionId:P,model:r.model,reasoningEffort:r.agentSettings?.reasoningEffort,timeoutMs:J,onEvent:C});O.setActiveProcess(r.id,te);let S=await X;if(r.result=S.text,S.success){console.log(`${b} Iteration complete`),S.fileEdits&&S.fileEdits.length>0&&console.log(`${b} Captured ${S.fileEdits.length} file edit(s): ${S.fileEdits.map(F=>`${F.tool} ${F.file_path}`).join(", ")}`),S.editEvents&&S.editEvents.length>0&&console.log(`${b} Captured ${S.editEvents.length} edit event(s): ${S.editEvents.map(F=>`${F.operation} ${F.filePath}`).join(", ")}`),r.status="done";let D=Tn(S.text),H=An(S.text),se=H.some(F=>(F.finalScope??F.inferredScope)?.breadth==="pattern");if(H.length>0&&r.annotationIds&&r.annotationIds.length>0){let F=new Set(r.annotationIds);H.every(ne=>F.has(ne.annotationId))||(H=H.map((ne,fe)=>({...ne,annotationId:r.annotationIds[fe%r.annotationIds.length]})))}let ce=S.fileEdits&&S.fileEdits.length>0?S.fileEdits.map(F=>`${F.tool} ${F.file_path.split("/").pop()}`):S.toolsUsed,ue=O.getBufferedEvents(r.id),pe=ue?Dr(ue.events):void 0;if(r.threadId&&await y.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:S.text,resolutions:H.length>0?H:void 0,question:D??void 0,sessionId:S.sessionId,toolsUsed:ce,editEvents:S.editEvents&&S.editEvents.length>0?S.editEvents:void 0,segments:pe&&pe.length>0?pe:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&le.captureGitDiff(t).then(async F=>{let oe=Date.now(),ne=r.imagePaths?Object.values(r.imagePaths).flat():[],fe=[];if(r.imagePaths)for(let[j,R]of Object.entries(r.imagePaths))for(let Y=0;Y<R.length;Y++)fe.push(`screenshots/p-${r.id}-${j}-${Y}.webp`);await le.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:oe,durationMs:oe-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:fe,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:S.sessionId,threadId:r.threadId,responseText:S.text,resolutions:H.length>0?H:[],question:D??void 0,fileEdits:S.fileEdits??[],editEvents:S.editEvents??[],toolsUsed:ce,gitDiff:F},r.screenshotPath,ne),se&&d!=="copilot"?await Ot({provider:d,model:r.model,agentSettings:r.agentSettings,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):se&&console.log(`${b} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&S.text){let F=nt(S.text);if(F){Array.isArray(F.rules)&&(F.rules=Ne(F.rules));let oe=await G.loadModel();oe&&(!F.tokens&&oe.tokens&&(F.tokens=oe.tokens),!F.components&&oe.components&&(F.components=oe.components)),await G.writeModel(F),console.log(`${b} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&S.text){let F=nn(S.text),oe=sn(S.text),ne=F??oe;if(ne&&ne.length>0){let fe=await ie.writeSynthesized(ne),j=r._proposalId;j&&await G.attachGeneratedEvals(j,ne.map(R=>R.id)),console.log(`${b} Eval synthesis: wrote ${ne.length} ${F?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${fe.cases.length} total)`)}}else if(r.kind==="run_eval"&&S.text&&r.evalId&&r.evalRunId){let F=await ie.findCase(r.evalId),oe=r._evalRunScope;if(F&&oe){let ne=on(S.text,F.assertions),fe=Date.now();await ie.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:fe,durationMs:fe-r.createdAt,scope:oe,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:Gn(t),rawResponse:S.text,...ne}),console.log(`${b} Eval run: ${F.title} \u2192 ${ne.status}`)}}D&&(console.log(`${b} \u{1F4AC} Question detected: "${D.slice(0,120)}" \u2192 broadcasting to ${ee.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),O.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:D,annotationIds:r.annotationIds},r.id,r.sourceId));let de=Cn(S.text);de.length>0&&(console.log(`${b} Novel pattern(s): ${de.map(F=>`${F.category}/${F.element}`).join(", ")}`),O.broadcast({type:"novel_patterns",jobId:r.id,patterns:de,threadId:r.threadId},r.id,r.sourceId)),O.broadcast({type:"done",jobId:r.id,success:!0,resolutions:H.length>0?H:void 0,responseText:S.text,threadId:r.threadId},r.id,r.sourceId),ve.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${b} Error: ${S.error}`),r.status="error",r.error=S.error,r.threadId&&await y.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:S.error||"Unknown error",model:r.model,provider:d}),O.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:S.error||"Unknown error",provider:d,model:r.model,recoverable:S.recoverableError,code:S.errorCode},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:S.error,threadId:r.threadId,annotationIds:r.annotationIds});We()});let gt=kr(async(r,c)=>{if(zr(r,c),r.method==="OPTIONS"){c.writeHead(204),c.end();return}let u=r.url||"/",p=u.split("?")[0],h=new URL(u,`http://127.0.0.1:${W}`),d=h.pathname,P=Fr(r,h);if(P&&P!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:ft(t)});return}if(r.headers.origin){if(!Qn(r.headers.origin)){m(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(P!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:ft(t)});return}}try{if(r.method==="POST"&&d==="/send")await ss(r,c);else if(r.method==="GET"&&d==="/events")rs(r,c);else if(r.method==="GET"&&d==="/status")await is(c,P);else if(r.method==="PATCH"&&d==="/config")await as(r,c);else if(r.method==="POST"&&d==="/leases"){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}try{let g=await Br(r),b=typeof g.leaseId=="string"?g.leaseId.trim():"",I=typeof g.ownerPid=="number"&&Number.isInteger(g.ownerPid)&&g.ownerPid>0?g.ownerPid:void 0;if(!b||b.length>128){m(c,400,{error:"A valid leaseId is required."});return}T();let C=k.acquire(b,I);m(c,201,{ok:!0,lease:C,ttlMs:Un})}catch{m(c,400,{error:"Invalid lease request."})}}else if(d.startsWith("/leases/")&&(r.method==="PATCH"||r.method==="DELETE")){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}let g="";try{g=decodeURIComponent(d.slice(8))}catch{m(c,400,{error:"Invalid lease id."});return}if(!g){m(c,400,{error:"A lease id is required."});return}if(r.method==="PATCH"){let b=k.heartbeat(g);if(!b){m(c,404,{error:"Lease not found."});return}m(c,200,{ok:!0,lease:b})}else{let b=k.release(g);m(c,b.found?200:404,{ok:b.found}),b.becameEmpty&&_()}}else if(r.method==="POST"&&d==="/shutdown"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0}),setTimeout(L,100)}else if(r.method==="POST"&&d==="/restart"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let g of ee)try{g.res.end()}catch{}gt.close(()=>{jn(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(r.method==="GET"&&d==="/capabilities")m(c,200,{providers:w});else if(r.method==="POST"&&d==="/mcp/install")await ws(r,c);else if(r.method==="POST"&&d==="/reply")await os(r,c);else if(r.method==="POST"&&d==="/cancel")ls(r,c);else if(r.method==="POST"&&d==="/materialize")await cs(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let g=await G.loadRuns();m(c,200,g)}else if(r.method==="GET"&&d==="/model/proposals"){let g=await G.loadModelProposals();m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let g=d.slice(17,-15);await us(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let g=d.slice(17,-6);await ds(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let g=d.slice(17,-8);await ps(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let g=d.slice(17,-14);await fs(g,r,c)}else if(r.method==="POST"&&d==="/model/component")await Ss(r,c);else if(r.method==="DELETE"&&d==="/model/component")await xs(r,c);else if(r.method==="PATCH"&&d==="/model/token")await bs(r,c);else if(r.method==="DELETE"&&d==="/model/token")await Ps(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:g,model:b,agentSettings:I}=await Me(r);if(g==="copilot"){m(c,400,{error:"Model consolidation is not available for Copilot yet."});return}G.consolidate({provider:g,model:b,agentSettings:I}).catch(C=>console.error("[Bridge] Consolidation error:",C)),m(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await hs(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await ms(r,c);else if(r.method==="GET"&&d==="/evals"){let g=await ie.loadSuiteWithCurrentRuns(Gn(t));m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let g=d.slice(7,-4);await gs(g,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await ys(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let g=await G.loadModel();m(c,200,{model:g})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let g=d.slice(6,d.length-7),b=parseInt(h.searchParams.get("afterSeq")??"-1",10),I=O.getBufferedEvents(g,isNaN(b)?-1:b);I?m(c,200,I):m(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await Rs(p.slice(7),c);else if(r.method==="GET"&&d==="/threads/recent"){let g=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),b=await y.listRecent(g);m(c,200,b)}else if(r.method==="GET"&&d.startsWith("/thread/")){let g=d.slice(8);await Es(g,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let g=d.slice(8);await Ts(g,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?Is(r,c):r.method==="GET"&&d==="/canvas/manifest"?await ks(c):r.method==="GET"&&d==="/canvas/app.mjs"?await Ms(c):m(c,404,{error:"Not found"})}catch(g){console.error("[Bridge] Request error:",g),m(c,500,{error:g instanceof Error?g.message:"Internal error"})}});async function ss(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:P,reasoningEffort:g,serviceTier:b,sourceId:I,pastedImages:C,pageScreenshots:te}=await at(r),X;try{X=JSON.parse(p)}catch{m(c,400,{error:"Invalid feedback JSON"});return}let S=Pe().slice(0,8),D={};if(te.length>0)for(let R of te){let Y=encodeURIComponent(R.pathname),re=ye(a,`screenshot-${S}-${Y}.webp`);await Le(re,R.data),D[R.pathname]=re}let H=ye(a,`screenshot-${S}.webp`);await Le(H,u);let se={};if(C.length>0)for(let R of C){let Y=ye(a,`pasted-${S}-${R.annotationId}-${R.index}.webp`);await Le(Y,R.data),se[R.annotationId]||(se[R.annotationId]=[]),se[R.annotationId].push(Y)}let ce=X.annotations.map(R=>R.linkedSelector?R.pathname?`${R.pathname}:${R.linkedSelector}`:R.linkedSelector:null).filter(R=>!!R),ue;if(ce.length>0){let R=await y.findContinuationThread(ce);R?(ue=R.id,await y.addElementIdentifiers(ue,ce)):ue=(await y.createThread(S,ce)).id}else ue=(await y.createThread(S,[])).id;let pe=X.annotations.map(R=>R.id),de=Object.keys(D).length>0,F={id:S,status:"queued",screenshotPath:H,feedback:X,createdAt:Date.now(),color:h,threadId:ue,annotationIds:pe,provider:Ue(d),model:P||void 0,agentSettings:Re({reasoningEffort:g,serviceTier:b}),...Object.keys(se).length>0?{imagePaths:se}:{},sourceId:I||void 0,...de?{screenshotPaths:D}:{}},oe=new Set(X.annotations.map(R=>R.pathname).filter(Boolean)),ne;if(oe.size>1){let R=new Map;for(let Y of X.annotations){let re=Y.pathname||"(unknown)";R.has(re)||R.set(re,[]),R.get(re).push(Y.instruction||Hn({...X,annotations:[Y]}))}ne=[...R.entries()].map(([Y,re])=>`\`${Y}\`
407
- ${re.map(yt=>`- ${yt}`).join(`
226
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!k&&a.threadId?await G.getThreadHistory(a.threadId):void 0,pe=k?null:await ie.loadModel();F=k??qr(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:w,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}F+=Br(a.memoryReview),D&&(F+=Do(a.imprintContext)),F+=`
227
+
228
+ ${Ur}`;let C=wd(a.color,`[\u22B9 ${h}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${C} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${L?` (resuming: ${L.slice(0,8)})`:""}`);let K=new On(a.id),q=(de,pe)=>{if(de.type==="delta"&&"text"in de){let _e=K.push(de.text);_e.visibleText&&(N.accumulateText(pe,"response",_e.visibleText),N.broadcast({...de,text:_e.visibleText},pe,a.sourceId));for(let Ce of _e.orientations)N.broadcast({type:"orientation",jobId:pe,orientation:Ce},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&N.accumulateText(pe,"thinking",de.text);N.broadcast(de,pe,a.sourceId)},{process:se,result:ae}=w==="codex"?mn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:L,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:ln(a.agentSettings),onEvent:q}):w==="copilot"?tr(a.id,{prompt:F,projectRoot:r,resumeSessionId:L,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??b,onEvent:q}):pn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:j?["Read"]:v,claudePath:R,resumeSessionId:L,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:g,onEvent:q});N.setActiveProcess(a.id,se);let oe=await ae,be=K.finalize(oe.text),ve=be.visibleText,V=D?Oo(ve):{visibleText:ve,draft:void 0,error:void 0},Ie=V.visibleText;for(let de of be.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=Ie,oe.success){console.log(`${C} Iteration complete`),oe.fileEdits&&oe.fileEdits.length>0&&console.log(`${C} Captured ${oe.fileEdits.length} file edit(s): ${oe.fileEdits.map(z=>`${z.tool} ${z.file_path}`).join(", ")}`),oe.editEvents&&oe.editEvents.length>0&&console.log(`${C} Captured ${oe.editEvents.length} edit event(s): ${oe.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Wr(ve),pe=Gr(ve);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let z=new Set(a.annotationIds);pe.every(Ve=>z.has(Ve.annotationId))||(pe=pe.map((Ve,Ke)=>({...Ve,annotationId:a.annotationIds[Ke%a.annotationIds.length]})))}let _e=oe.fileEdits&&oe.fileEdits.length>0?oe.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):oe.toolsUsed,Ce=N.getBufferedEvents(a.id),et=Ce?fd(Ce.events,r):void 0,ke,Z=Lr(ve),fe=Fr(ve);if(fe)if(!(a.memoryReview?.packets.some(re=>re.proposalId===fe.proposalId)||a.surfacedProposalIds?.includes(fe.proposalId)))ke={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{ke=await U.commitConversationalReview(fe)}catch(re){ke={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:re instanceof Error?re.message:String(re)}}let Re=[...(oe.fileEdits??[]).map(z=>z.file_path),...(oe.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],xe,ht=a.imprintContext?.pendingGroundingExplanationIds??[];if(V.draft?.decision==="none"&&he.recordNoop(V.draft.reason),a.threadId&&V.draft?.decision==="mutate"&&!fe&&!Z)try{xe=await he.capture(V.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await ie.loadModel(),pendingGroundingExplanationIds:ht}),xe&&await U.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(z=>console.warn(`${C} Canonical Imprint evidence linkage failed:`,z))}catch(z){console.warn(`${C} Continuous imprint update failed; the thread result remains available:`,z instanceof Error?z.message:String(z))}else V.error&&console.warn(`${C} Ignored invalid imprint block: ${V.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let z=await G.getThread(a.threadId),re=new Set(xe.changes.map(Ke=>Ke.explanationId)),Ve=z?md(z.messages,re):void 0;if(Ve?.imprintSummary){let Ke=Ve.imprintSummary;await G.updateAssistantMessage(a.threadId,Ve.jobId,{imprintSummary:{...Ke,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Ke.additionalObservationCount??0)+1,coalescedTransactionIds:[...Ke.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let Ft=ds({question:de,resolutions:pe,changedFiles:Re,decisionRequired:!!Z,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),Q=et?.flatMap(z=>z.kind==="orientation"?[z.orientation]:[])??[];if(a.threadId){let z=j?Z?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Ie;await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:z,resolutions:!j&&pe.length>0?pe:void 0,question:j?void 0:de??void 0,sessionId:oe.sessionId,toolsUsed:j?void 0:_e,editEvents:!j&&oe.editEvents&&oe.editEvents.length>0?oe.editEvents:void 0,segments:!j&&et&&et.length>0?et:void 0,turn:{phase:"complete",orientation:Q,result:Ft},result:Ft,memoryReviewCard:Z??void 0,memoryReceipt:ke,imprintSummary:xe,model:a.model,provider:w})}if(a.threadId&&!fe&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let z=a.feedback.annotations.flatMap(re=>re.linkedSelector?[re.pathname?`${re.pathname}:${re.linkedSelector}`:re.linkedSelector]:[]);try{await U.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:m??(Cn(a.feedback)||"[request unavailable]"),responseSummary:de??Ie,outcome:de?"question_asked":pe.some(re=>re.status==="resolved")?"completed":"no_change",execution:{provider:w,model:a.model,sessionId:oe.sessionId},subjectHints:z,filePaths:[...(oe.fileEdits??[]).map(re=>re.file_path),...(oe.editEvents??[]).flatMap(re=>re.filePath?[re.filePath]:[])].map(re=>Bo(re)?ys(r,re):re),resolutions:pe.map(re=>({status:re.status,summary:re.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(re=>re.id)})}catch(re){console.warn(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,re instanceof Error?re.message:String(re))}}if(ke?.status==="committed"&&ke.decisionId&&w!=="copilot"&&await je({provider:w,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${ke.decisionId}`}),a.kind==="run_eval"&&Ie&&a.evalId&&a.evalRunId){let z=await U.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(z&&re){let Ve=or(ve,z.assertions),Ke=Date.now(),Hs={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:re,provider:w,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:bs(r),rawResponse:ve,scopeFingerprint:a._evalScopeFingerprint,...Ve};await U.recordEvalVerification(z,Hs),console.log(`${C} Eval run: ${z.title} \u2192 ${Ve.status}`)}}de&&(console.log(`${C} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${X.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),N.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:de,annotationIds:a.annotationIds},a.id,a.sourceId));let me=Vr(ve);me.length>0&&(console.log(`${C} Novel pattern(s): ${me.map(z=>`${z.category}/${z.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),N.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:Ie,threadId:a.threadId,annotationIds:a.annotationIds,result:Ft},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${C} Error: ${oe.error}`),a.status="error",a.error=oe.error,a.threadId&&await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:oe.error||"Unknown error",model:a.model,provider:w}),N.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:oe.error||"Unknown error",provider:w,model:a.model,recoverable:oe.recoverableError,code:oe.errorCode},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:oe.error,threadId:a.threadId,annotationIds:a.annotationIds});Ue()});let Nt=od(async(a,u)=>{if(yd(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let k=a.url||"/",m=k.split("?")[0],P=new URL(k,`http://127.0.0.1:${h}`),w=P.pathname,j=vd(a,P);if(j&&j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Vn(r)});return}if(a.headers.origin){if(!Rs(a.headers.origin)){E(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Vn(r)});return}}try{if(a.method==="POST"&&w==="/send")await Ae(a,u);else if(a.method==="GET"&&w==="/events")it(a,u);else if(a.method==="GET"&&w==="/status")await at(a,u,j);else if(a.method==="GET"&&w==="/ui-preferences")await Yn(u);else if(a.method==="PATCH"&&w==="/ui-preferences")await Zn(a,u);else if(a.method==="PATCH"&&w==="/config")await mt(a,u);else if(a.method==="POST"&&w==="/leases"){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await ze(a),D=typeof $.leaseId=="string"?$.leaseId.trim():"",L=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){E(u,400,{error:"A valid leaseId is required."});return}te();let F=B.acquire(D,L);E(u,201,{ok:!0,lease:F,ttlMs:vs})}catch{E(u,400,{error:"Invalid lease request."})}}else if(w.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(w.slice(8))}catch{E(u,400,{error:"Invalid lease id."});return}if(!$){E(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat($);if(!D){E(u,404,{error:"Lease not found."});return}E(u,200,{ok:!0,lease:D})}else{let D=B.release($);E(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&ge()}}else if(a.method==="POST"&&w==="/shutdown"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0}),setTimeout(ne,100)}else if(a.method==="POST"&&w==="/restart"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of X)try{$.res.end()}catch{}Nt.close(()=>{gs(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&w==="/capabilities")E(u,200,{providers:f});else if(w.startsWith("/imprint/"))await st(a,u,w);else if(w.startsWith("/memory/"))await we(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await $s(a,u);else if(a.method==="POST"&&w==="/reply")await Ze(a,u);else if(a.method==="POST"&&w==="/cancel")Bt(a,u);else if(a.method==="POST"&&w==="/materialize")E(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&w==="/materialization-runs")E(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&w==="/projection-runs"){let $=await ie.loadRuns();E(u,200,$)}else if(a.method==="GET"&&w==="/projection/proposals"){let $=await ie.loadModelProposals();E(u,200,$)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply-selected")){let $=w.slice(22,-15);await ct($,a,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply")){let $=w.slice(22,-6);await Ne($,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/dismiss")){let $=w.slice(22,-8);await St($,a,u)}else if(w.startsWith("/model/proposals/"))E(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await Os(a,u);else if(a.method==="DELETE"&&w==="/model/component")await Ds(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Js(a,u);else if(a.method==="DELETE"&&w==="/model/token")await Ns(a,u);else if(a.method==="POST"&&w==="/model/consolidate")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/model/synthesize")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/evals/synthesize")E(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&w==="/evals"){let $=await ie.loadModel(),D=await Promise.all((await U.getJournalEvalCases()).map(async C=>{let O=await xs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),L=bs(r),F=(await U.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===L);E(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:F,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&w.startsWith("/evals/")&&w.endsWith("/run")){let $=w.slice(7,-4);await eo($,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await cn(w.slice(7),a,u);else if(a.method==="GET"&&w==="/model"){let $=await ie.loadModel();E(u,200,{model:$})}else if(a.method==="GET"&&w.startsWith("/jobs/")&&w.endsWith("/events")){let $=w.slice(6,w.length-7),D=parseInt(P.searchParams.get("afterSeq")??"-1",10),L=N.getBufferedEvents($,isNaN(D)?-1:D);L?E(u,200,L):E(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await zs(m.slice(7),u);else if(a.method==="GET"&&w==="/threads/recent"){let $=Math.min(Math.max(parseInt(P.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent($);E(u,200,D)}else if(a.method==="GET"&&w.startsWith("/decision/")){let $=w.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))E(u,400,{error:"Invalid decision id"});else{let D=await G.getThread($),L=[...D?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(D&&L?.annotationSnapshot){let F=[...D.messages].reverse().find(C=>C.resolutions?.length);E(u,200,{decision:{id:D.id,createdAt:L.timestamp,url:L.annotationSnapshot.url,viewport:L.annotationSnapshot.viewport,color:L.annotationSnapshot.color,annotations:L.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await Y.loadDecision($);F?E(u,200,{decision:F,authority:"legacy_archive"}):E(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let $=w.slice(8);await Us($,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let $=w.slice(8);await qs($,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?Bs(a,u):a.method==="GET"&&w==="/canvas/manifest"?await Fs(u):a.method==="GET"&&w==="/canvas/app.mjs"?await Ls(u):E(u,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),E(u,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function we(a,u,k){try{if(a.method==="GET"&&k==="/memory/status"){E(u,200,await U.status());return}if(a.method==="GET"&&k==="/memory/diagnostics"){E(u,200,await U.diagnostics());return}if(a.method==="GET"&&k==="/memory/model-view"){E(u,200,await U.getModelView());return}if(a.method==="POST"&&k==="/memory/constraints"){let m=await ze(a),P=typeof m.reactComponent=="string"?m.reactComponent.trim():"",w=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",$=await U.getModelView(),D=P?$.entries.filter(C=>C.key===`components.${P}`||C.key.startsWith(`components.${P}.`)):[],L=(C,O)=>{if(!O)return!1;if(!C.includes("*"))return C===O;let K=C.split("*").map(q=>q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${K}$`).test(O)},F=(await U.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(q=>q.kind==="route"&&L(q.value,w)||q.kind==="subject"&&q.value===j),K=(C.scenarios??[]).some(q=>!!P&&(q.components??[]).some(se=>se.name===P||se.exportName===P)||!!w&&!!q.route&&q.route===w||!!w&&!!q.routePattern&&L(q.routePattern,w));return O||K}).map(C=>({id:C.id,title:C.title,verificationState:C.verificationState,assertions:C.assertions}));E(u,200,{modelEntries:D,evals:F});return}if(a.method==="POST"&&k==="/memory/conversation-action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!P||!w||!["accept","edit_and_accept","reject","defer"].includes(j)){E(u,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await G.getThread(P),D=$?.messages.find(ae=>ae.memoryReviewCard?.proposalId===w)?.memoryReviewCard;if(!$||!D){E(u,409,{error:"This decision review card is not available in the thread."});return}let L=await ie.findModelProposalsByThread(P),F=(await Promise.all(L.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(oe=>U.findPendingProposalForLegacyDecision(oe)))).some(oe=>oe?.proposalId===w)})))).find(ae=>ae.matches)?.proposal,C={proposalId:w,action:j,kind:D.kind,claim:j==="edit_and_accept"&&typeof m.claim=="string"?m.claim.trim():void 0,reason:j==="defer"?void 0:`The owner explicitly chose ${j.replaceAll("_"," ")} from the decision review card.`,taskContext:j==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:j==="defer"?["different_action","owner_request"]:void 0};if(C.action==="edit_and_accept"&&!C.claim){E(u,400,{error:"Edited decision wording is required."});return}let O=await U.commitConversationalReview(C),K=`memory-${pt().slice(0,8)}`,q=j==="accept"?"> Accepted decision":j==="edit_and_accept"?"> Edited and accepted decision":j==="reject"?"> Rejected decision":"> Deferred decision";await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:q}),await G.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:K,responseText:"",memoryReceipt:O,provider:xt(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&F&&await ie.dismissModelProposal(F.id);let se=xt(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&se!=="copilot"&&await je({provider:se,model:typeof m.model=="string"?m.model:void 0,agentSettings:gt(m),threadId:P,reason:`Project accepted decision ${O.decisionId}`}),E(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&k==="/memory/analyze"){let m=await ze(a),P=await U.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),w=Object.fromEntries([...new Set(P.issues.map(j=>j.code))].map(j=>[j,P.issues.filter($=>$.code===j).length]));E(u,200,{...P,issues:void 0,issueCounts:w});return}if(a.method==="POST"&&k==="/memory/review"){let m=await ze(a),P=await U.review(Mo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/context"){let m=await ze(a),P=await U.contextualize(Mo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/initialize"){let m=await ze(a),P=await U.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:sn});E(u,201,{status:P.status,report:{source:P.report.source,imported:P.report.imported,unresolvedAcceptance:P.report.unresolvedAcceptance,deferredModelEntries:P.report.deferredModelEntries,proofCases:P.report.proofCases,schemaIssues:P.report.schemaIssues}});return}if(a.method==="POST"&&k==="/memory/plan"){let m=await ze(a),P=await U.planReview(Eo(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,P.result.ok?200:422,P);return}if(a.method==="POST"&&k==="/memory/commit"){let m=await ze(a),P=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},w=await U.commitReview(Eo(m.command),{transactionId:typeof P.transactionId=="string"?P.transactionId:"",committedAt:typeof P.committedAt=="string"?P.committedAt:""});E(u,200,{status:await U.status(),journal:w.report});return}if(a.method==="POST"&&k==="/memory/recover"){let m=await ze(a),P=await U.recover(m.confirm===!0);E(u,200,{status:await U.status(),journal:P.report});return}E(u,404,{error:"Memory endpoint not found."})}catch(m){let P=m instanceof Error?m.message:String(m),w=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(P),j=/required|invalid|unsupported|expected|must be|confirmation/i.test(P);if(w||j){E(u,w?409:400,{error:P});return}throw m}}async function st(a,u,k){if(a.method==="GET"&&k==="/imprint/status"){let[m,P]=await Promise.all([he.store.load(),G.load()]),w=[...new Set(Object.values(P.threads).flatMap(j=>Kn(j.messages)))];E(u,200,{state:"ready",head:m.graph.head,updatedAt:m.graph.updatedAt,explanationCount:m.graph.explanations.filter(j=>j.state!=="retired").length,concreteCount:m.graph.concrete.length,relationCount:m.graph.relations.length,pendingGroundingCount:w.length,recoveredTransactions:m.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&k==="/imprint/action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!P||!w||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(j)){E(u,400,{error:"A valid thread, imprint update, and action are required."});return}let D=await G.getThread(P),L=[...D?.messages??[]].reverse().find(se=>se.role==="assistant"&&se.imprintSummary?.transactionId===w),F=L?.imprintSummary;if(!D||!L||!F){E(u,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){E(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${pt().slice(0,8)}`;await he.applyGroundingAction({summary:F,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:P,jobId:C}),await U.recordImprintEvidence({summary:F,action:j,threadId:P,jobId:C}).catch(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));let O=$t(L.result,!!L.question),K=L.turn?{...L.turn,result:$t(L.turn.result,!!L.question)}:void 0;await G.updateAssistantMessage(P,L.jobId,{imprintSummary:{...F,resolvedAction:j},...O?{result:O}:{},...K?{turn:K}:{}});let q={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:C,replyToQuestion:q[j]}),E(u,200,{ok:!0,action:j});return}E(u,404,{error:"Imprint endpoint not found."})}async function Ae(a,u){let{screenshot:k,feedback:m,color:P,provider:w,model:j,reasoningEffort:$,serviceTier:D,sourceId:L,pastedImages:F,pageScreenshots:C}=await $n(a),O;try{O=JSON.parse(m)}catch{E(u,400,{error:"Invalid feedback JSON"});return}let K=pt().slice(0,8),q={};if(C.length>0)for(let Z of C){let fe=encodeURIComponent(Z.pathname),Re=Me(c,`screenshot-${K}-${fe}.webp`);await an(Re,Z.data),q[Z.pathname]=Re}let se=Me(c,`screenshot-${K}.webp`);await an(se,k);let ae={};if(F.length>0)for(let Z of F){let fe=Me(c,`pasted-${K}-${Z.annotationId}-${Z.index}.webp`);await an(fe,Z.data),ae[Z.annotationId]||(ae[Z.annotationId]=[]),ae[Z.annotationId].push(fe)}let oe=O.annotations.map(Z=>Z.linkedSelector?Z.pathname?`${Z.pathname}:${Z.linkedSelector}`:Z.linkedSelector:null).filter(Z=>!!Z),be;if(oe.length>0){let Z=await G.findContinuationThread(oe);Z?(be=Z.id,await G.addElementIdentifiers(be,oe)):be=(await G.createThread(K,oe)).id}else be=(await G.createThread(K,[])).id;let ve=O.annotations.map(Z=>Z.id),V=Object.keys(q).length>0,Ie=await Nr(U,O,oe,Z=>console.warn(`[\u22B9 ${h}:${K}] Contextual memory unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))),de=await he.contextualize({text:Cn(O),subjectHints:[...oe,...O.annotations.flatMap(Z=>[Z.pathname,Z.elements?.[0]?.reactComponent].filter(fe=>!!fe))],pendingGroundingExplanationIds:Kn((await G.getThread(be))?.messages??[])}).catch(Z=>{console.warn(`[\u22B9 ${h}:${K}] Imprint context unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))}),pe={id:K,status:"queued",screenshotPath:se,feedback:O,createdAt:Date.now(),color:P,threadId:be,annotationIds:ve,provider:xt(w),model:j||void 0,agentSettings:gt({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:L||void 0,...V?{screenshotPaths:q}:{},...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}},_e=new Set(O.annotations.map(Z=>Z.pathname).filter(Boolean)),Ce;if(_e.size>1){let Z=new Map;for(let fe of O.annotations){let Re=fe.pathname||"(unknown)";Z.has(Re)||Z.set(Re,[]),Z.get(Re).push(fe.instruction||Is({...O,annotations:[fe]}))}Ce=[...Z.entries()].map(([fe,Re])=>`\`${fe}\`
229
+ ${Re.map(xe=>`- ${xe}`).join(`
408
230
  `)}`).join(`
409
- `)}else ne=Hn(X);let fe=ze(X,Object.keys(se).length>0?se:void 0);await y.appendMessage(ue,{role:"human",timestamp:Date.now(),jobId:S,screenshotPath:H,...de?{screenshotPaths:D}:{},...Object.keys(se).length>0?{imagePaths:se}:{},annotationIds:pe,feedbackSummary:ne,feedbackContext:fe||void 0});let j=O.enqueue(F);m(c,200,{jobId:S,position:j,threadId:ue})}async function os(r,c){let u=r.headers["content-type"]||"",p,h,d,P,g,b,I,C=[];if(u.includes("multipart/form-data")){let j=await at(r),R=j.feedback?JSON.parse(j.feedback):{};p=R.threadId,h=R.reply,d=R.color,P=R.provider,g=R.model,b=Re(R),I=R.sourceId||j.sourceId;for(let Y of j.pastedImages)C.push(Y.data)}else{let j=[];for await(let re of r)j.push(typeof re=="string"?Buffer.from(re):re);let R=Buffer.concat(j).toString("utf-8"),Y;try{Y=JSON.parse(R)}catch{m(c,400,{error:"Invalid JSON"});return}p=Y.threadId,h=Y.reply,d=Y.color,P=Y.provider,g=Y.model,b=Re(Y),I=Y.sourceId}if(!p||!h){m(c,400,{error:"Missing threadId or reply"});return}if(!await y.getThread(p)){m(c,404,{error:"Thread not found"});return}let X="";{let j=await y.getThreadHistory(p);for(let R=j.length-1;R>=0;R--)if(j[R].screenshotPath){X=j[R].screenshotPath;break}}let S=await vs(p);if(!X&&!S){m(c,400,{error:"No screenshot available"});return}let D=O.hasActiveThread(p),H=D?O.getQueuedThreadJob(p,j=>j._replyText!==void 0||j._replyPrompt!==void 0):null,se=H?.id??Pe().slice(0,8),ce=[],ue=`${se}-${Date.now()}`;for(let j=0;j<C.length;j++){let R=ye(a,`reply-${ue}-${j}.webp`);await Le(R,C[j]),ce.push(R)}await y.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:se,replyToQuestion:h,screenshotPath:X,...D?{queued:!0}:{},...ce.length>0?{replyImagePaths:ce}:{}});let pe=await y.getThreadHistory(p),de=[];for(let j of pe)if(j.annotationIds)for(let R of j.annotationIds)de.includes(R)||de.push(R);let F=Ue(P),oe=Ct(X,pe,F,ce.length>0?ce:void 0);if(H){let j=H,Y=[...j._replyTexts??(j._replyText?[j._replyText]:[]),h],re=[...j._replyImagePaths??[],...ce];j._replyTexts=Y,j._replyText=Wn(Y),j._replyImagePaths=re.length>0?re:void 0,j._replyPrompt=Ct(X,pe,F,re.length>0?re:void 0),j.annotationIds=de.length>0?de:j.annotationIds,j.agentSettings=b??j.agentSettings,m(c,200,{jobId:se,position:1,threadId:p,bundled:!0});return}let ne={id:se,status:"queued",screenshotPath:X,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:d,threadId:p,annotationIds:de.length>0?de:void 0,provider:F,model:g||void 0,agentSettings:b,sourceId:I||void 0};S&&(ne.kind=S),ne._replyPrompt=oe,ne._replyTexts=[h],ne._replyText=Wn([h]),ce.length>0&&(ne._replyImagePaths=ce);let fe=D?O.enqueueNext(ne):O.enqueue(ne);m(c,200,{jobId:se,position:fe,threadId:p})}function rs(r,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
231
+ `)}else Ce=Is(O);let et=Xt(O,Object.keys(ae).length>0?ae:void 0);await G.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:K,screenshotPath:se,...V?{screenshotPaths:q}:{},...Object.keys(ae).length>0?{imagePaths:ae}:{},annotationIds:ve,annotationSnapshot:{url:O.url,viewport:O.viewport,annotations:O.annotations,color:P||void 0},feedbackSummary:Ce,feedbackContext:et||void 0,...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}});let ke=N.enqueue(pe);E(u,200,{jobId:K,position:ke,threadId:be})}async function Ze(a,u){let k=a.headers["content-type"]||"",m,P,w,j,$,D,L,F,C,O=[];if(k.includes("multipart/form-data")){let Q=await $n(a),me=Q.feedback?JSON.parse(Q.feedback):{};m=me.threadId,P=me.reply,w=me.color,j=me.provider,$=me.model,D=gt(me),L=me.sourceId||Q.sourceId,F=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0,C=me.evalRemediation?.action==="resolve"&&typeof me.evalRemediation.evalId=="string"?{evalId:me.evalRemediation.evalId,action:"resolve"}:void 0;for(let z of Q.pastedImages)O.push(z.data)}else{let Q=[];for await(let re of a)Q.push(typeof re=="string"?Buffer.from(re):re);let me=Buffer.concat(Q).toString("utf-8"),z;try{z=JSON.parse(me)}catch{E(u,400,{error:"Invalid JSON"});return}m=z.threadId,P=z.reply,w=z.color,j=z.provider,$=z.model,D=gt(z),L=z.sourceId,F=z.memoryReviewProposalId,C=z.evalRemediation?.action==="resolve"&&typeof z.evalRemediation.evalId=="string"?{evalId:z.evalRemediation.evalId,action:"resolve"}:void 0}if(!m||!P){E(u,400,{error:"Missing threadId or reply"});return}let K=await G.getThread(m);if(!K){E(u,404,{error:"Thread not found"});return}let q,se;if(C){let Q=await U.findJournalEvalCase(C.evalId),me=(await U.getJournalEvalRuns()).filter(z=>z.evalId===C.evalId&&z.threadId===m).sort((z,re)=>re.completedAt-z.completedAt)[0];if(!Q||!me){E(u,409,{error:"The failed eval run is not available in this thread."});return}if(me.status!=="fail"){E(u,409,{error:"Only a failed eval can start remediation."});return}se={evalCase:Q,run:me}}if(F){let Q=await ie.findModelProposalsByThread(m);if(q=(await Promise.all(Q.flatMap(z=>z.authorityStatus==="accepted"?[]:z.decisionIds.map(async re=>({modelProposalId:z.id,underlying:await U.findPendingProposalForLegacyDecision(re)}))))).filter(z=>!!z.underlying).find(z=>z.underlying.proposalId===F),!q){E(u,409,{error:"The requested memory decision is not pending in this thread."});return}}let ae="";{let Q=await G.getThreadHistory(m);for(let me=Q.length-1;me>=0;me--)if(Q[me].screenshotPath){ae=Q[me].screenshotPath;break}}let oe=await Cs(m);if(!ae&&!oe){E(u,400,{error:"No screenshot available"});return}let be=N.hasActiveThread(m),ve=be?N.getQueuedThreadJob(m,Q=>Q._replyText!==void 0||Q._replyPrompt!==void 0):null,V=ve?.id??pt().slice(0,8),Ie=[],de=`${V}-${Date.now()}`;for(let Q=0;Q<O.length;Q++){let me=Me(c,`reply-${de}-${Q}.webp`);await an(me,O[Q]),Ie.push(me)}await G.appendMessage(m,{role:"human",timestamp:Date.now(),jobId:V,replyToQuestion:P,screenshotPath:ae,...be?{queued:!0}:{},...Ie.length>0?{replyImagePaths:Ie}:{}});let pe=await G.getThreadHistory(m),_e=[...pe].reverse().find(Q=>Q.memoryReview)?.memoryReview,Ce=await he.contextualize({text:P,subjectHints:K.elementIdentifiers,pendingGroundingExplanationIds:Kn(pe)}).catch(Q=>{console.warn(`[\u22B9 ${h}:${V}] Imprint context unavailable for reply; continuing without it:`,Q instanceof Error?Q.message:String(Q))}),et=new Set(pe.flatMap(Q=>Q.memoryReceipt?.status==="committed"?[Q.memoryReceipt.proposalId]:[])),ke=[...pe].reverse().find(Q=>Q.memoryReviewCard&&!et.has(Q.memoryReviewCard.proposalId))?.memoryReviewCard,Z=[];for(let Q of pe)if(Q.annotationIds)for(let me of Q.annotationIds)Z.includes(me)||Z.push(me);let fe=xt(j),Re=q,xe=Re?[Re.underlying.proposalId]:ke?[ke.proposalId]:[],ht=Hr(ae,pe,fe,Ie.length>0?Ie:void 0);if(se?ht+=["","## Failed eval remediation","This is a new implementation goal based on a failed Popmelt eval. Fix the product gaps identified by the evaluator.","Do not weaken, rewrite, approve, retire, or otherwise modify the eval specification unless the developer explicitly asks.","Treat the accepted product decision as governing truth; the failed implementation is what should change.",`Eval: ${JSON.stringify(se.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:se.run.summary,assertionResults:se.run.assertionResults,scope:se.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
232
+ `):Re?ht+=["","## Decision review card",`Privately review proposal ${Re.underlying.proposalId}: ${Re.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
233
+ `):ke&&(ht+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(ke)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
234
+ `)),ve){let Q=ve,z=[...Q._replyTexts??(Q._replyText?[Q._replyText]:[]),P],re=[...Q._replyImagePaths??[],...Ie];Q._replyTexts=z,Q._replyText=ws(z),Q._replyImagePaths=re.length>0?re:void 0,Q._replyPrompt=ht,Q.annotationIds=Z.length>0?Z:Q.annotationIds,Q.agentSettings=D??Q.agentSettings,Q.memoryReview=_e??Q.memoryReview,Q.imprintContext=Ce??Q.imprintContext,Q.surfacedProposalIds=[...new Set([...Q.surfacedProposalIds??[],...xe])],E(u,200,{jobId:V,position:1,threadId:m,bundled:!0});return}let qe={id:V,status:"queued",screenshotPath:ae,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:w,threadId:m,annotationIds:Z.length>0?Z:void 0,provider:fe,model:$||void 0,agentSettings:D,sourceId:L||void 0,..._e?{memoryReview:_e}:{},...Ce?{imprintContext:Ce}:{},...xe.length?{surfacedProposalIds:xe}:{}};se?qe.kind="resolve_eval":oe&&(qe.kind=oe),qe._replyPrompt=ht,qe._evalRemediation=!!se,qe._replyTexts=[P],qe._replyText=ws([P]),Ie.length>0&&(qe._replyImagePaths=Ie);let Ft=be?N.enqueueNext(qe):N.enqueue(qe);E(u,200,{jobId:V,position:Ft,threadId:m})}function it(a,u){u.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),u.write(`event: connected
410
235
  data: {"status":"connected"}
411
236
 
412
- `);let p=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("sourceId")||void 0,h={id:Pe().slice(0,8),res:c,sourceId:p};ee.add(h),r.on("close",()=>{ee.delete(h)})}async function is(r,c){let u=[...O.allActive,...A.allActive.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds??[],color:"#000000",kind:"materialize_model",standalone:d.standalone}))],[p,h]=await Promise.all([G.loadRuns(),G.loadModelProposals()]);m(r,200,{ok:!0,version:Fn,restartMode:U,projectId:o,projectName:ft(t),projectRoot:t,requestProjectId:c,projectIdVerified:c===o,devOrigin:i,activeJob:u[0]?{id:u[0].id,status:u[0].status}:null,activeJobs:u.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds,color:d.color,kind:d.kind,standalone:"standalone"in d?d.standalone:void 0})),queueDepth:O.depth+A.depth,materializerQueueDepth:A.depth,leases:{active:k.isActivated,count:k.size,nextExpiryAt:k.nextExpiryAt,shutdownPending:$},materialization:{activeJob:A.active?{id:A.active.id,status:A.active.status,threadId:A.active.threadId,annotationIds:A.active.annotationIds??[],provider:A.active.provider,model:A.active.model}:null,queueDepth:A.depth,recentRuns:[...p.runs].sort((d,P)=>(P.completedAt??P.startedAt)-(d.completedAt??d.startedAt)).slice(0,10),proposals:h.proposals.slice(0,20).map(d=>({id:d.id,status:d.status,title:d.title,summary:d.summary,decisionIds:d.decisionIds,threadId:d.threadId,runId:d.runId,createdAt:d.createdAt,updatedAt:d.updatedAt,appliedAt:d.appliedAt,dismissedAt:d.dismissedAt,generatedEvalIds:d.generatedEvalIds,error:d.error}))},recentJobs:ve})}async function as(r,c){let u=await new Promise(p=>{let h="";r.on("data",d=>{h+=d.toString()}),r.on("end",()=>p(h))});try{let p=JSON.parse(u);typeof p.devOrigin=="string"&&(i=p.devOrigin||null),m(c,200,{ok:!0,devOrigin:i})}catch{m(c,400,{error:"Invalid JSON"})}}async function ls(r,c){let p=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("jobId"),h=p?O.allActive.filter(C=>C.id===p):O.allActive,d=p?A.allActive.filter(C=>C.id===p):A.allActive,P=[...h.map(C=>C.threadId),...d.map(C=>C.threadId)].filter(Boolean),g=p?O.cancelJob(p):O.cancelActive(),b=p?A.cancelJob(p):A.cancelActive(),I=!!(g||b);for(let C of P)await y.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:p||b?.id||"",cancelled:!0});m(c,200,{cancelled:I})}async function Ot(r){let c=Pe().slice(0,8),u=r.threadId,p=!u;u||(u=(await y.createThread(c,[])).id,we.set(u,"materialize_model")),p&&await y.appendMessage(u,{role:"human",timestamp:Date.now(),jobId:c,feedbackSummary:r.reason}),await y.appendMessage(u,{role:"assistant",timestamp:Date.now(),jobId:c,responseText:p?"Materializing model suggestions...":"Thinking through model suggestions from this decision...",model:r.model,provider:r.provider});let h={id:c,status:"queued",createdAt:Date.now(),provider:r.provider,model:r.model,agentSettings:r.agentSettings,threadId:u,annotationIds:r.annotationIds,sourceId:r.sourceId,standalone:p},d=A.enqueue(h);return{jobId:c,position:d,threadId:u}}async function cs(r,c){if(A.isRunning){m(c,200,{skipped:!0,reason:"Already running"});return}let{provider:u,model:p,agentSettings:h}=await Me(r);if(u==="copilot"){m(c,400,{error:"Materialization is not available for Copilot yet."});return}let d=await G.getUnmaterializedPatternDecisions();if(d.length===0){m(c,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let P=await Ot({provider:u,model:p,agentSettings:h,reason:"Materialize model \u2014 promote pattern decisions into the local taste model"});m(c,200,{started:!0,decisionCount:d.length,decisionIds:d.map(g=>g.id),...P})}async function ds(r,c){let u=decodeURIComponent(r),p=await G.applyModelProposal(u);if(!p){m(c,404,{error:"Model proposal not found"});return}p.threadId&&await y.appendMessage(p.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${p.id}`,responseText:`Model proposal applied.
413
-
414
- ${p.title}
415
- ${p.summary}`}),m(c,200,{proposal:p})}async function us(r,c,u){let p=decodeURIComponent(r),h=[];for await(let I of c)h.push(typeof I=="string"?Buffer.from(I):I);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{m(u,400,{error:"Invalid JSON"});return}let P=(d.changes??[]).flatMap(I=>{if(!Array.isArray(I.path)||I.path.length===0)return[];let C=I.path.filter(te=>typeof te=="string"||typeof te=="number");return C.length!==I.path.length?[]:[{path:C,value:I.value,remove:I.remove===!0}]});if(P.length===0){m(u,400,{error:"No selected model changes"});return}let g=(d.changeSummaries??[]).flatMap(I=>{if(!I||typeof I!="object")return[];let C=Array.isArray(I.path)?I.path.filter(te=>typeof te=="string"||typeof te=="number"):void 0;return Array.isArray(I.path)&&C?.length!==I.path.length?[]:[{group:typeof I.group=="string"?I.group:void 0,label:typeof I.label=="string"?I.label:void 0,detail:typeof I.detail=="string"?I.detail:void 0,path:C,value:I.value,currentValue:I.currentValue}]}),b=await G.applySelectedModelProposal(p,P,g);if(!b){m(u,404,{error:"Model proposal not found"});return}if(b.threadId){let I=Ue(d.provider),C=typeof d.model=="string"&&d.model?d.model:void 0;await y.appendMessage(b.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${b.id}`,responseText:`Model proposal applied with ${P.length} selected change${P.length===1?"":"s"}.
416
-
417
- ${b.title}`,provider:I,model:C})}m(u,200,{proposal:b})}async function ps(r,c,u){let p=decodeURIComponent(r),{provider:h,model:d}=await Me(c),P=await G.dismissModelProposal(p);if(!P){m(u,404,{error:"Model proposal not found"});return}P.threadId&&await y.appendMessage(P.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${P.id}`,responseText:`Model proposal dismissed.
418
-
419
- ${P.title}`,provider:h,model:d}),m(u,200,{proposal:P})}async function fs(r,c,u){let p=decodeURIComponent(r),h=await G.findModelProposal(p);if(!h){m(u,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){m(u,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:P,agentSettings:g}=await Me(c),b=d??h.provider??B;if(b==="copilot"){m(u,400,{error:"Eval projection is not available for Copilot yet."});return}let I=await G.loadModel(),C=await ie.loadSuite(),te=cn({proposal:h,currentModel:I,existingSuite:C}),X=Pe().slice(0,8),S=h.threadId??(await y.createThread(X,[])).id;we.set(S,"synthesize_evals"),await y.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:X,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
420
- `)});let D={id:X,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#111827",threadId:S,kind:"synthesize_evals",provider:b,model:P??h.model,agentSettings:g};D._replyPrompt=te,D._proposalId=h.id;let H=O.enqueue(D);m(u,200,{jobId:X,position:H,threadId:S})}async function Me(r){try{let c=[];for await(let p of r)c.push(typeof p=="string"?Buffer.from(p):p);if(c.length===0)return{};let u=JSON.parse(Buffer.concat(c).toString());return{provider:Ue(typeof u.provider=="string"?u.provider:void 0),model:typeof u.model=="string"&&u.model?u.model:void 0,agentSettings:Re(u)}}catch{return{}}}async function hs(r,c){let u=await G.loadModel();if(!u){m(c,400,{error:"No model exists yet"});return}let{provider:p,model:h,agentSettings:d}=await Me(r);if(p==="copilot"){m(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let P=hn(u),g=Pe().slice(0,8),I=(await y.createThread(g,[])).id;we.set(I,"synthesize"),await y.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let C={id:g,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:I,kind:"synthesize",provider:p,model:h,agentSettings:d};C._replyPrompt=P;let te=O.enqueue(C);m(c,200,{jobId:g,position:te,threadId:I})}async function ms(r,c){let{provider:u,model:p,agentSettings:h}=await Me(r);if(u==="copilot"){m(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let d=await le.listDecisionIds(),P=await le.loadDecisions(d),g=await y.load(),b=await G.loadModel(),I=await ie.loadSuite(),C=an({decisions:P,threads:g,model:b,existingSuite:I}),te=Pe().slice(0,8),S=(await y.createThread(te,[])).id;we.set(S,"synthesize_evals"),await y.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:te,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let D={id:te,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#6b7280",threadId:S,kind:"synthesize_evals",provider:u,model:p||void 0,agentSettings:h};D._replyPrompt=C;let H=O.enqueue(D);m(c,200,{jobId:te,position:H,threadId:S})}async function gs(r,c,u){let p=decodeURIComponent(r),h=await ie.findCase(p);if(!h){m(u,404,{error:"Eval not found"});return}if(h.status!=="approved"){m(u,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:P,provider:g,model:b,reasoningEffort:I,serviceTier:C,sourceId:te}=await at(c),X=Ue(g)??B;if(X==="copilot"){m(u,400,{error:"Eval runs are not available for Copilot yet."});return}let S={};try{S=P?JSON.parse(P):{}}catch{m(u,400,{error:"Invalid eval run context JSON"});return}let D=Pe().slice(0,8),H=Pe().slice(0,8),se=ye(a,`eval-run-${D}.webp`);await Le(se,d);let ce=await ie.writeRunScreenshot(D,d),ue=S.viewport,pe=ue&&typeof ue=="object"?ue:{},de={type:"current_page",url:typeof S.url=="string"?S.url:"",viewport:{width:typeof pe.width=="number"?pe.width:0,height:typeof pe.height=="number"?pe.height:0}},F=await G.loadModel(),oe=X==="claude"?Q.name:X==="codex"?K.name:null,ne=X==="codex"?Z.length>0:typeof oe=="string"&&/chrome|devtools/i.test(oe),fe=ln({evalCase:h,scope:de,model:F,screenshotPath:se,chromeDevtoolsAvailable:ne}),R=(await y.createThread(H,[])).id;we.set(R,"run_eval");let Y={timestamp:new Date().toISOString(),url:de.url,viewport:de.viewport,scrollPosition:{x:typeof S.scrollX=="number"?S.scrollX:0,y:typeof S.scrollY=="number"?S.scrollY:0},annotations:[],styleModifications:[]};await y.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:H,screenshotPath:se,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${de.url||"unknown"}`,"Assertions:",...h.assertions.map(Cs=>`- ${Cs}`)].join(`
421
- `)});let re={id:H,status:"queued",screenshotPath:se,feedback:Y,createdAt:Date.now(),color:"#111827",threadId:R,kind:"run_eval",evalId:p,evalRunId:D,provider:X,model:b||void 0,agentSettings:Re({reasoningEffort:I,serviceTier:C}),sourceId:te||void 0};re._replyPrompt=fe,re._evalRunScope=de,re._evalScreenshotPath=ce;let yt=O.enqueue(re);m(u,200,{jobId:H,runId:D,position:yt,threadId:R,screenshotPath:ce})}async function ys(r,c,u){let p=decodeURIComponent(r),h={},d,P,g;try{let I=[];for await(let te of c)I.push(typeof te=="string"?Buffer.from(te):te);let C=JSON.parse(Buffer.concat(I).toString());d=C.status,P=C.title,g=C.assertions}catch{m(u,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){m(u,400,{error:"Invalid status"});return}if(d&&(h.status=d),P!==void 0){if(typeof P!="string"||P.trim().length===0){m(u,400,{error:"Invalid title"});return}h.title=P.trim()}if(g!==void 0){if(!Array.isArray(g)){m(u,400,{error:"Invalid assertions"});return}let I=g.filter(C=>typeof C=="string").map(C=>C.trim()).filter(Boolean);if(I.length===0){m(u,400,{error:"Invalid assertions"});return}h.assertions=I}if(!h.status&&!h.title&&!h.assertions){m(u,400,{error:"No eval changes provided"});return}let b=await ie.updateCase(p,h);if(!b){m(u,404,{error:"Eval not found"});return}m(u,200,{eval:b})}async function vs(r){let c=we.get(r);if(c)return c;let h=(await y.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return we.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return we.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return we.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return we.set(r,"materialize_model"),"materialize_model"}async function ws(r,c){let u=[];for await(let b of r)u.push(typeof b=="string"?Buffer.from(b):b);let p;if(u.length>0)try{p=JSON.parse(Buffer.concat(u).toString("utf-8")).serverUrl}catch{}let h=[];w.claude?.available&&w.claude.mcp&&!w.claude.mcp.found&&h.push(await kn(p)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await Mn(p)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await Rn(p,w.copilot.path??E));let[d,P,g]=await Promise.all([Mt(t),Rt(t),Et(t,w.copilot?.path??E)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=P),w.copilot&&(w.copilot.mcp=g),m(c,200,{results:h,capabilities:{providers:w}})}async function Ss(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await G.addComponent(p.name);m(c,200,h)}async function xs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await G.removeComponent(p.name);m(c,200,h)}async function bs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"||typeof p.value!="string"){m(c,400,{error:"Missing or invalid path/value"});return}let h=await G.updateToken(p.path,p.value);m(c,200,h)}async function Ps(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"){m(c,400,{error:"Missing or invalid path"});return}let h=await G.removeToken(p.path);m(c,200,h)}function Is(r,c){let u=i??"http://localhost:3000";if(!i){let h=r.headers.referer||r.headers.origin;if(h)try{let d=new URL(typeof h=="string"?h:h[0]||"");(d.hostname==="localhost"||d.hostname==="127.0.0.1")&&(u=d.origin)}catch{}}let p=zt(W,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(p)}async function ks(r){let c=Date.now();if(He&&c<He.expires){m(r,200,He.data);return}try{let{scanForComponents:u}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:p}=await import("./render-generator-HWFLZYC3.mjs"),h=await u(t);He={data:h,expires:c+5e3},p(h,t,_t).then(d=>{_t=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),m(r,200,h)}catch(u){console.error("[Bridge] Scanner error:",u),m(r,500,{error:"Failed to scan components"})}}async function Ms(r){let c=[ye(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ye(t,"packages","popmelt","dist","canvas.mjs")];try{let u=Er(import.meta.url);c.unshift(ye(Rr(u),"canvas.mjs"))}catch{}for(let u of c)try{let p=await Ln(u,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(p);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),m(r,404,{error:"Canvas bundle not found"})}async function Rs(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){m(c,400,{error:"Invalid filename"});return}try{let u=await Ln(ye(a,r)),p=r.split(".").pop()?.toLowerCase(),h=p==="png"?"image/png":p==="webp"?"image/webp":p==="jpg"||p==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(u)}catch{m(c,404,{error:"File not found"})}}function Ge(r){return`/files/${ft(r)}`}async function Es(r,c){let u=await y.getThread(r);if(!u){m(c,404,{error:"Thread not found"});return}let p=(await ie.loadRuns()).runs.filter(b=>b.threadId===r).sort((b,I)=>I.completedAt-b.completedAt)[0],h=p?await ie.findCase(p.evalId):null,d=await G.findModelProposalsByThread(r),P=[...d].sort((b,I)=>I.updatedAt-b.updatedAt)[0]??null,g=u.messages.map(({screenshotPath:b,screenshotPaths:I,imagePaths:C,replyImagePaths:te,...X})=>({...X,...X.role==="assistant"&&p?{evalRun:{...p,title:h?.title}}:{},...b?{screenshotUrl:Ge(b)}:{},...I?{screenshotUrls:Object.fromEntries(Object.entries(I).map(([S,D])=>[S,Ge(D)]))}:{},...C?{imageUrls:Object.fromEntries(Object.entries(C).map(([S,D])=>[S,D.map(Ge)]))}:{},...te?{replyImageUrls:te.map(Ge)}:{}}));m(c,200,{id:u.id,createdAt:u.createdAt,messages:g,modelProposal:P,modelProposals:d})}async function Ts(r,c){let u=decodeURIComponent(r);if(!await y.deleteThread(u)){m(c,404,{deleted:!1,error:"Thread not found"});return}m(c,200,{deleted:!0})}let Dt=9,Nt=!1;for(let r=e;r<e+Dt;r++)try{await Ur(gt,r),W=r,Nt=!0,console.log(`[\u22B9 is watching :${W}]`);break}catch(c){if(c.code==="EADDRINUSE"){let u=await Lr(r);if(u&&u.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Nt)throw new Error(`[Bridge] All ports ${e}\u2013${e+Dt-1} in use`);for(let[r,c]of Object.entries(w))!c.available||!c.path||V(r,c.path).then(u=>{if(u)console.log(`[Bridge] ${r} warmed up`);else{console.warn(`[Bridge] ${r} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let p of ee)ht(p,{type:"capabilities_changed",data:{}})}});let As=setInterval(()=>{qn(a).catch(()=>{})},Cr),Jt=setInterval(()=>{k.expireStale().becameEmpty&&_()},_r);return Jt.unref?.(),{port:W,projectId:o,close:async()=>{clearInterval(As),clearInterval(Jt),T(),k.clear(),await O.destroyAsync(),A.destroy();for(let r of ee)try{r.res.end()}catch{}return ee.clear(),new Promise(r=>{gt.close(()=>r())})}}}async function qn(s){try{let e=await xr(s),n=Date.now();for(let t of e){let o=ye(s,t);try{let i=await Pr(o);n-i.mtimeMs>$r&&await Ir(o)}catch{}}}catch{}}var qr=parseInt(process.env.POPMELT_PORT||"1111",10),Vn=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Qr=process.env.POPMELT_DEV_ORIGIN||void 0,Xr=process.env.POPMELT_COPILOT_PATH||void 0,Kn=Yn(Vn,".popmelt"),Zn=Yn(Kn,"bridge.lock");async function Yr(s){await Wr(Kn,{recursive:!0}),await Gr(Zn,JSON.stringify({pid:process.pid,port:s,startedAt:Date.now()})+`
422
- `)}async function es(){try{await Hr(Zn)}catch{}}async function Vr(){let s=await Xn({port:qr,projectRoot:Vn,devOrigin:Qr,copilotPath:Xr,restartMode:"detached"});await Yr(s.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await s.close(),await es(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}Vr().catch(s=>{console.error("[popmelt bridge-entry] Fatal:",s),es().finally(()=>process.exit(1))});
237
+ `);let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,P={id:pt().slice(0,8),res:u,sourceId:m};X.add(P),a.on("close",()=>{X.delete(P)})}async function at(a,u,k){i??=is(a.headers),Ue();let m=[...N.allActive,...T.allActive.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds??[],color:"#000000",kind:"project_model",standalone:V.standalone}))],[P,w,j,$,D]=await Promise.allSettled([ie.loadRuns(),ie.loadModelProposals(),U.status(),he.store.load(),G.load()]),L=[],F=V=>V.reason instanceof Error?V.reason.message:String(V.reason);P.status==="rejected"&&L.push({subsystem:"projection",message:F(P)}),w.status==="rejected"&&L.push({subsystem:"projection",message:F(w)}),j.status==="rejected"?L.push({subsystem:"memory",message:F(j)}):j.value.state==="degraded"&&L.push({subsystem:"memory",message:j.value.error??"Product memory is degraded."}),$.status==="rejected"&&L.push({subsystem:"imprint",message:F($)}),D.status==="rejected"&&L.push({subsystem:"threads",message:F(D)});let C=P.status==="fulfilled"?P.value.runs:[],O=w.status==="fulfilled"?w.value.proposals:[],K=as(C,O),q=K.actionableProposals.map(V=>({id:V.id,status:V.status,title:V.title,summary:V.summary,decisionIds:V.decisionIds,threadId:V.threadId,runId:V.runId,presentationJobId:V.presentationJobId,authorityStatus:V.authorityStatus,underlyingProposalId:V.underlyingProposalId,createdAt:V.createdAt,updatedAt:V.updatedAt,appliedAt:V.appliedAt,dismissedAt:V.dismissedAt,generatedEvalIds:V.generatedEvalIds,evalProjections:V.evalProjections,error:V.error})),se=j.status==="fulfilled"?j.value:{initialized:!1,state:"degraded",error:F(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(V=>Kn(V.messages)))]:[],oe=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(V=>V.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:$.value.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F($),pendingGroundingCount:ae.length,admission:he.diagnostics(),admissionWindowStartedAt:e},be=L.length>0?"degraded":se.state==="absent"||se.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();E(u,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:be,issues:L},version:sn,restartMode:p,projectId:s,projectName:Vn(r),projectRoot:r,requestProjectId:k,projectIdVerified:k===s,devOrigin:i,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds,color:V.color,kind:V.kind,standalone:"standalone"in V?V.standalone:void 0})),queueDepth:N.depth+T.depth,projectionQueueDepth:T.depth,leases:{active:B.isActivated,count:B.size,nextExpiryAt:B.nextExpiryAt,shutdownPending:H},projection:{state:P.status==="fulfilled"&&w.status==="fulfilled"?"ready":"degraded",activeJob:T.active?{id:T.active.id,status:T.active.status,threadId:T.active.threadId,annotationIds:T.active.annotationIds??[],provider:T.active.provider,model:T.active.model}:null,queueDepth:T.depth,recentRuns:K.recentRuns,recentAppliedRuns:K.recentAppliedRuns,actionableProposalCounts:K.actionableProposalCounts,actionableProposals:q},memory:se,imprint:oe,recentJobsRetentionMs:Je,recentJobs:Pe})}async function mt(a,u){let k=await new Promise(m=>{let P="";a.on("data",w=>{P+=w.toString()}),a.on("end",()=>m(P))});try{let m=JSON.parse(k);typeof m.devOrigin=="string"&&(i=m.devOrigin||null),E(u,200,{ok:!0,devOrigin:i})}catch{E(u,400,{error:"Invalid JSON"})}}async function Yn(a){let u=await M.load();E(a,200,{ok:!0,...u})}async function Zn(a,u){let k=await ze(a);if(!ms(k.theme)){E(u,400,{error:"theme must be light, dark, or auto"});return}let m=await M.setTheme(k.theme);E(u,200,{ok:!0,exists:!0,preferences:m})}async function Bt(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("jobId"),P=m?N.allActive.filter(F=>F.id===m):N.allActive,w=m?T.allActive.filter(F=>F.id===m):T.allActive,j=[...P.map(F=>F.threadId),...w.map(F=>F.threadId)].filter(Boolean),$=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),L=!!($||D);for(let F of j)await G.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});E(u,200,{cancelled:L})}async function je(a){let u=pt().slice(0,8),k=a.threadId,m=!k;k||(k=(await G.createThread(u,[])).id,Ge.set(k,"project_model")),m&&await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:u,feedbackSummary:a.reason}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:u,responseText:m?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let P={id:u,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:k,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:m},w=T.enqueue(P);return{jobId:u,position:w,threadId:k}}async function Ne(a,u){let k=decodeURIComponent(a),m=await ie.findModelProposal(k);if(!m){E(u,404,{error:"Model proposal not found"});return}E(u,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:m})}async function ct(a,u,k){let m=decodeURIComponent(a),P=[];for await(let O of u)P.push(typeof O=="string"?Buffer.from(O):O);let w;try{w=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{E(k,400,{error:"Invalid JSON"});return}let j=(w.changes??[]).flatMap(O=>{if(!Array.isArray(O.path)||O.path.length===0)return[];let K=O.path.filter(se=>typeof se=="string"||typeof se=="number");if(K.length!==O.path.length)return[];let q=Array.isArray(O.decisionIds)?O.decisionIds.filter(se=>typeof se=="string"):void 0;return[{path:K,value:O.value,remove:O.remove===!0,decisionIds:q}]});if(j.length===0){E(k,400,{error:"No selected model changes"});return}let $=(w.changeSummaries??[]).flatMap(O=>{if(!O||typeof O!="object")return[];let K=Array.isArray(O.path)?O.path.filter(q=>typeof q=="string"||typeof q=="number"):void 0;return Array.isArray(O.path)&&K?.length!==O.path.length?[]:[{group:typeof O.group=="string"?O.group:void 0,label:typeof O.label=="string"?O.label:void 0,detail:typeof O.detail=="string"?O.detail:void 0,path:K,value:O.value,currentValue:O.currentValue}]}),D=await ie.findModelProposal(m);if(!D){E(k,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){E(k,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){E(k,409,{error:`Model proposal is already ${D.status}.`});return}let L=D.decisionIds.map(O=>{let K=D.changes?.filter(ae=>ae.decisionIds.includes(O)).length??0,q=j.filter(ae=>ae.decisionIds?.includes(O)).length,se=q===0?"unprojected":K>q?"partially_projected":"projected";return{decisionId:O,status:se}}),F=await U.applyModelProjection({runId:D.runId??D.id,presentationJobId:D.presentationJobId,decisionIds:D.decisionIds,changes:j.map(O=>({path:O.path,value:O.value,decisionIds:O.decisionIds})),coverage:L}),C=await ie.applySelectedModelProposal(m,j,$);if(!C){E(k,404,{error:"Model proposal not found"});return}if(await Ye(C),C.threadId){let O=xt(w.provider),K=typeof w.model=="string"&&w.model?w.model:void 0;await G.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${C.id}`,responseText:"",provider:O,model:K})}E(k,200,{proposal:C,projection:F})}async function St(a,u,k){let m=decodeURIComponent(a),{provider:P,model:w}=await ft(u),j=await ie.dismissModelProposal(m);if(!j){E(k,404,{error:"Model proposal not found"});return}j.threadId&&await G.appendMessage(j.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${j.id}`,responseText:"",provider:P,model:w}),E(k,200,{proposal:j})}async function ft(a){try{let u=[];for await(let m of a)u.push(typeof m=="string"?Buffer.from(m):m);if(u.length===0)return{};let k=JSON.parse(Buffer.concat(u).toString());return{provider:xt(typeof k.provider=="string"?k.provider:void 0),model:typeof k.model=="string"&&k.model?k.model:void 0,agentSettings:gt(k)}}catch{return{}}}async function eo(a,u,k){let m=decodeURIComponent(a),P=await U.findJournalEvalCase(m);if(!P){E(k,404,{error:"Eval not found"});return}if(P.status!=="approved"){E(k,400,{error:"Only approved evals can be run"});return}let{screenshot:w,feedback:j,provider:$,model:D,reasoningEffort:L,serviceTier:F,sourceId:C}=await $n(u),O=xt($)??I;if(O==="copilot"){E(k,400,{error:"Eval runs are not available for Copilot yet."});return}let K={};try{K=j?JSON.parse(j):{}}catch{E(k,400,{error:"Invalid eval run context JSON"});return}let q=pt().slice(0,8),se=pt().slice(0,8),ae=Me(c,`eval-run-${q}.webp`);await an(ae,w);let oe=await ue.persistEvalScreenshot(w),be=K.viewport,ve=be&&typeof be=="object"?be:{},V={type:"current_page",url:typeof K.url=="string"?K.url:"",viewport:{width:typeof ve.width=="number"?ve.width:0,height:typeof ve.height=="number"?ve.height:0}},Ie=await ie.loadModel(),de=await xs(r,P,Ie),pe=O==="claude"?S.name:O==="codex"?A.name:null,_e=O==="codex"?_.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=ir({evalCase:P,scope:V,model:Ie,screenshotPath:ae,chromeDevtoolsAvailable:_e}),ke=(await G.createThread(se,[])).id;Ge.set(ke,"run_eval");let Z={timestamp:new Date().toISOString(),url:V.url,viewport:V.viewport,scrollPosition:{x:typeof K.scrollX=="number"?K.scrollX:0,y:typeof K.scrollY=="number"?K.scrollY:0},annotations:[],styleModifications:[]};await G.appendMessage(ke,{role:"human",timestamp:Date.now(),jobId:se,screenshotPath:ae,feedbackSummary:`Run eval \u2014 ${P.title}`,feedbackContext:[`Eval: ${P.title}`,"Scope: current page",`URL: ${V.url||"unknown"}`,"Assertions:",...P.assertions.map(xe=>`- ${xe}`)].join(`
238
+ `)});let fe={id:se,status:"queued",screenshotPath:ae,feedback:Z,createdAt:Date.now(),color:"#111827",threadId:ke,kind:"run_eval",evalId:m,evalRunId:q,provider:O,model:D||void 0,agentSettings:gt({reasoningEffort:L,serviceTier:F}),sourceId:C||void 0};fe._replyPrompt=Ce,fe._evalRunScope=V,fe._evalScreenshotPath=oe,fe._evalScopeFingerprint=de;let Re=N.enqueue(fe);E(k,200,{jobId:se,runId:q,position:Re,threadId:ke,screenshotPath:oe})}async function cn(a,u,k){let m=decodeURIComponent(a),P={},w,j,$;try{let L=[];for await(let C of u)L.push(typeof C=="string"?Buffer.from(C):C);let F=JSON.parse(Buffer.concat(L).toString());w=F.status,j=F.title,$=F.assertions}catch{E(k,400,{error:"Invalid JSON"});return}if(w!==void 0&&w!=="pending"&&w!=="approved"&&w!=="rejected"){E(k,400,{error:"Invalid status"});return}if(w&&(P.status=w),j!==void 0){if(typeof j!="string"||j.trim().length===0){E(k,400,{error:"Invalid title"});return}P.title=j.trim()}if($!==void 0){if(!Array.isArray($)){E(k,400,{error:"Invalid assertions"});return}let L=$.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(L.length===0){E(k,400,{error:"Invalid assertions"});return}P.assertions=L}if(!P.status&&!P.title&&!P.assertions){E(k,400,{error:"No eval changes provided"});return}let D=await U.updateJournalEvalCase(m,P);if(!D){E(k,404,{error:"Eval not found"});return}E(k,200,{eval:D})}async function Cs(a){let u=Ge.get(a);if(u)return u;let P=(await G.getThread(a))?.messages.find(w=>w.role==="human")?.feedbackSummary??"";if(P.startsWith("Synthesize evals"))return Ge.set(a,"synthesize_evals"),"synthesize_evals";if(P.startsWith("Synthesize rules"))return Ge.set(a,"synthesize"),"synthesize";if(P.startsWith("Run eval"))return Ge.set(a,"run_eval"),"run_eval";if(P.startsWith("Materialize model")||P.startsWith("Project model"))return Ge.set(a,"project_model"),"project_model"}async function $s(a,u){let k=[];for await(let D of a)k.push(typeof D=="string"?Buffer.from(D):D);let m;if(k.length>0)try{m=JSON.parse(Buffer.concat(k).toString("utf-8")).serverUrl}catch{}let P=[];f.claude?.available&&f.claude.mcp&&!f.claude.mcp.found&&P.push(await xr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&P.push(await Sr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&P.push(await Pr(m,f.copilot.path??b));let[w,j,$]=await Promise.all([fo(r),ho(r),go(r,f.copilot?.path??b)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),E(u,200,{results:P,capabilities:{providers:f}})}async function Os(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:{description:""},claim:`${m.name} is an explicitly governed component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await rt({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});E(u,200,{added:!0,alreadyExists:!1,...P,evalId:w})}async function Ds(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:null,claim:`${m.name} is not governed as a component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await rt({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});E(u,200,{removed:!0,...P,evalId:w})}async function Js(a,u){let k=[];for await(let $ of a)k.push(typeof $=="string"?Buffer.from($):$);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){E(u,400,{error:"Missing or invalid path/value"});return}let P=m.value;try{let $=JSON.parse(m.value);$&&typeof $=="object"&&(P=$)}catch{}let w=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:P,claim:`${m.path} uses ${m.value} in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let j=await rt({decisionId:w.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});E(u,200,{updated:!0,...w,evalId:j})}async function Ns(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){E(u,400,{error:"Missing or invalid path"});return}let P=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:null,claim:`${m.path} is intentionally absent from the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await rt({decisionId:P.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});E(u,200,{removed:!0,...P,evalId:w})}function Bs(a,u){let k=i??"http://localhost:3000";if(!i){let P=a.headers.referer||a.headers.origin;if(P)try{let w=new URL(typeof P=="string"?P:P[0]||"");(w.hostname==="localhost"||w.hostname==="127.0.0.1")&&(k=w.origin)}catch{}}let m=Uo(h,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Fs(a){let u=Date.now();if(ut&&u<ut.expires){E(a,200,ut.data);return}try{let{scanForComponents:k}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),P=await k(r);ut={data:P,expires:u+5e3},m(P,r,Jt).then(w=>{Jt=w}).catch(w=>console.warn("[Bridge] Render generation failed:",w)),E(a,200,P)}catch(k){console.error("[Bridge] Scanner error:",k),E(a,500,{error:"Failed to scan components"})}}async function Ls(a){let u=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let k=id(import.meta.url);u.unshift(Me(sd(k),"canvas.mjs"))}catch{}for(let k of u)try{let m=await No(k,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(m);return}catch{}console.error("[Bridge] Canvas bundle not found in:",u),E(a,404,{error:"Canvas bundle not found"})}async function zs(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(u,400,{error:"Invalid filename"});return}try{let k=[Me(c,a),Me(r,".popmelt","artifacts","thread-media",a),Me(r,".popmelt","artifacts","eval-screenshots",a),Me(r,".popmelt","evals","screenshots",a),Me(r,".popmelt","screenshots",a)],m;for(let j of k)try{m=await No(j);break}catch{}if(!m)throw new Error("File not found");let P=a.split(".").pop()?.toLowerCase(),w=P==="png"?"image/png":P==="webp"?"image/webp":P==="jpg"||P==="jpeg"?"image/jpeg":"application/octet-stream";u.writeHead(200,{"Content-Type":w,"Cache-Control":"public, max-age=3600"}),u.end(m)}catch{E(u,404,{error:"File not found"})}}function dn(a){return`/files/${Vn(a)}`}async function Us(a,u){let k=await G.getThread(a);if(!k){E(u,404,{error:"Thread not found"});return}let m=k.messages.some(C=>C.role==="assistant"&&C.responseText?.includes("<eval_run_result>")),P=k.messages.filter(C=>C.role==="assistant"&&C.responseText?.includes("Model suggestion ready")),[w,j]=await Promise.all([m?U.getJournalEvalRuns().then(C=>C.filter(O=>O.threadId===a).sort((O,K)=>K.completedAt-O.completedAt)[0]):Promise.resolve(void 0),P.length>0?ie.findModelProposalsByThread(a):Promise.resolve([])]),$=w?await U.findJournalEvalCase(w.evalId):null,D=await Promise.all(j.map(async(C,O)=>{if(C.authorityStatus==="accepted")return C;let K=(await Promise.all(C.decisionIds.map(q=>U.findPendingProposalForLegacyDecision(q)))).find(Boolean);return{...C,authorityStatus:"legacy_untrusted",presentationJobId:C.presentationJobId??P[O]?.jobId??P.at(-1)?.jobId,underlyingProposalId:K?.proposalId,underlyingClaim:K?.claim}})),L=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,F=k.messages.map(({screenshotPath:C,screenshotPaths:O,imagePaths:K,replyImagePaths:q,...se})=>({...se,...se.role==="assistant"&&w&&se.responseText?.includes("<eval_run_result>")?{evalRun:{...w,title:$?.title}}:{},...C?{screenshotUrl:dn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,oe])=>[ae,dn(oe)]))}:{},...K?{imageUrls:Object.fromEntries(Object.entries(K).map(([ae,oe])=>[ae,oe.map(dn)]))}:{},...q?{replyImageUrls:q.map(dn)}:{}}));E(u,200,{id:k.id,createdAt:k.createdAt,messages:F,modelProposal:L,modelProposals:D})}async function qs(a,u){let k=decodeURIComponent(a);if(!await G.deleteThread(k)){E(u,404,{deleted:!1,error:"Thread not found"});return}E(u,200,{deleted:!0})}let Fo=9,Lo=!1;for(let a=n;a<n+Fo;a++)try{await bd(Nt,a),h=a,Lo=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await Id(a);if(ss(k,{projectId:s,version:sn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Lo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Fo-1} in use`);for(let[a,u]of Object.entries(f))!u.available||!u.path||x(a,u.path).then(k=>{if(k)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),u.available=!1,u.path=null;for(let m of X)Qn(m,{type:"capabilities_changed",data:{}})}});let Ws=setInterval(()=>{Ss(c).catch(()=>{})},dd),zo=setInterval(()=>{B.expireStale().becameEmpty&&ge()},pd);return zo.unref?.(),{port:h,projectId:s,close:async()=>{clearInterval(Ws),clearInterval(zo),te(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of X)try{a.res.end()}catch{}return X.clear(),new Promise(a=>{Nt.close(()=>a())})}}}async function Ss(o){try{let e=await Zc(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let s=await td(r);n-s.mtimeMs>ld&&await nd(r)}catch{}}}catch{}}var Rd=parseInt(process.env.POPMELT_PORT||"1111",10),Es=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Td=process.env.POPMELT_DEV_ORIGIN||void 0,jd=process.env.POPMELT_COPILOT_PATH||void 0,Ms=js(Es,".popmelt"),As=js(Ms,"bridge.lock");async function Ed(o){await Sd(Ms,{recursive:!0}),await kd(As,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
239
+ `)}async function _s(){try{await Pd(As)}catch{}}async function Md(){let o=await Ts({port:Rd,projectRoot:Es,devOrigin:Td,copilotPath:jd,restartMode:"detached"});await Ed(o.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await o.close(),await _s(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}Md().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),_s().finally(()=>process.exit(1))});