@popmelt.com/core 0.8.4 → 0.8.5

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.
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as Fr}from"child_process";import{readFile as jr,unlink as Lr}from"fs/promises";import{join as Ur}from"path";import{execFileSync as gt,spawn as Un}from"child_process";import{createHash as mr,randomUUID as Pe}from"crypto";import{mkdir as gr,readFile as Wn,readdir as yr,realpath as vr,stat as wr,unlink as Sr,writeFile as Ue}from"fs/promises";import{createServer as xr}from"http";import{tmpdir as br}from"os";import{basename as ht,dirname as Ir,join as ve}from"path";import{fileURLToPath as Pr}from"url";function Ft(s,e){return`<!DOCTYPE html>
2
+ import{spawn as sd}from"child_process";import{readFile as id,unlink as ad}from"fs/promises";import{join as cd}from"path";import{execFileSync as Zn,spawn as hs}from"child_process";import{createHash as Ss,randomUUID as pt}from"crypto";import{mkdir as Cc,readFile as Bo,readdir as Oc,realpath as Dc,stat as Jc,unlink as Nc,writeFile as ln}from"fs/promises";import{createServer as Bc}from"http";import{tmpdir as Fc}from"os";import{basename as Qn,dirname as Lc,isAbsolute as Fo,join as Me,relative as gs,resolve as ks}from"path";import{fileURLToPath as zc}from"url";function Wo(o,e){return`<!DOCTYPE html>
3
3
  <html>
4
4
  <head>
5
5
  <meta charset="utf-8">
@@ -19,105 +19,50 @@ import{spawn as Fr}from"child_process";import{readFile as jr,unlink as Lr}from"f
19
19
  }}
20
20
  </script>
21
21
  <script type="module">
22
- import { mountCanvas } from 'http://localhost:${s}/canvas/app.mjs';
22
+ import { mountCanvas } from 'http://localhost:${o}/canvas/app.mjs';
23
23
  mountCanvas(document.getElementById('root'), {
24
24
  devOrigin: '${e}',
25
- bridgeOrigin: 'http://localhost:${s}',
25
+ bridgeOrigin: 'http://localhost:${o}',
26
26
  });
27
27
  </script>
28
28
  </body>
29
- </html>`}var Es=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ts=new Set(["default","flex","fast","priority"]);function Ee(s){let e=typeof s.reasoningEffort=="string"&&Es.has(s.reasoningEffort)?s.reasoningEffort:void 0,n=typeof s.serviceTier=="string"&&Ts.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 As}from"child_process";import{createInterface as $s}from"readline";var Cs=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"]),jt=1e5;function _s(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Cs.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>jt?t.slice(0,jt)+`
30
- \u2026[truncated]`:t}function Xe(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=As(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="",D,A,k=!1,R=setTimeout(()=>{k=!0,U.kill("SIGTERM"),setTimeout(()=>{try{U.kill("SIGKILL")}catch{}},5e3)},E),N=$s({input:U.stdout}),C=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(C.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"&&(D=_.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=_s(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 H={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(H),K.push({sequence:K.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:H.file_path,oldString:typeof H.old_string=="string"?H.old_string:void 0,newString:typeof H.new_string=="string"?H.new_string:void 0,replaceAll:typeof H.replace_all=="boolean"?H.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"&&(D=_.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(R),N.close(),V.length===0&&C.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...C].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&&C.size>0?` (no text captured, event types: ${[...C].join(", ")})`:"";Z=ee||A||y||`Claude process exited with code ${L}${le}`}z&&!Z&&A&&(Z=A);let _=Ds(Z,D);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(R),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 Ds(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 Os,spawnSync as qt}from"child_process";import{readFileSync as Ns,statSync as Js}from"fs";import{basename as zs,extname as Bs,isAbsolute as Fs,relative as Qt,resolve as js}from"path";import{createInterface as Ls}from"readline";function Lt(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var Ut=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"]),wt=2e5,Us=1e5,Xt=2e5;function Yt(s){let e=zs(s).toLowerCase(),n=Bs(s).toLowerCase();return Ut.has(n)||Ut.has(e)}function Vt(s,e){let n=Fs(e)?e:js(s,e),t=Qt(s,n);return t===""||t.startsWith("..")?null:n}function Ye(s,e){if(!Yt(e))return;let n=Vt(s,e);if(n)try{let t=Js(n);return t.isFile()?t.size>wt?{exists:!0,truncated:!0}:{exists:!0,content:Ns(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Ws(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Gs(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 Wt(s){return Ws(s,["patch","diff","unifiedDiff","unified_diff"])}function St(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function Gt(s,e){let n=qt("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Xt+65536});return n.status!==0?null:n.stdout??""}function Hs(s){let e=new Set;for(let n of s.split(`
31
- `)){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 Ht(s){let e=Gt(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Gt(s,["diff","--no-ext-diff","HEAD","--"])??"",t=St(n,Xt);return{status:e,changedFiles:Hs(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function qs(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Qs(s,e){if(!Yt(e))return;let n=Vt(s,e);if(!n)return;let t=Qt(s,n);if(t===""||t.startsWith(".."))return;let o=qt("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:wt+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=St(i,wt);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function Xs(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Qs(s,t),i=Ye(s,t);return{filePath:t,...o?{before:o}:{},...i?{after:i}:{}}})}function Ve(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=Os("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=Ls({input:E.stdout}),D=new Set;Z.on("line",k=>{if(k.trim())try{let R=JSON.parse(k),N=R.type??"unknown";if(D.add(N),N==="thread.started"&&R.thread_id&&!U&&(U=R.thread_id),(N==="item.agentMessage.delta"||N==="item/agentMessage/delta")&&R.delta?.text&&(W.push(R.delta.text),l?.({type:"delta",jobId:s,text:R.delta.text},s)),(N==="item.reasoning.delta"||N==="item/reasoning/delta")&&R.delta?.text&&l?.({type:"thinking",jobId:s,text:R.delta.text},s),(N==="item.started"||N==="item/started")&&R.item){let C=R.item.type;if(C==="command_execution"){let T=R.item.command,L=T?Lt(T):void 0,_=Ht(t),ee=new Map;for(let le of _?.changedFiles??[])ee.set(le,Ye(t,le));typeof R.item.id=="string"&&Q.set(R.item.id,{...T?{rawCommand:T}:{},...L?{command:L}:{},..._?{beforeWorktree:_}:{},beforeSnapshots:ee});let y=L?`Bash: ${L.split(`
32
- `)[0].slice(0,80)}`:"Bash";w.push(y),l?.({type:"tool_use",jobId:s,tool:"Bash",...L?{content:L}:{}},s)}else if(C==="file_change"){let T=R.item.filename||R.item.path;T&&!V.has(T)&&V.set(T,Ye(t,T)),w.push(T?`Edit ${T.split("/").pop()}`:"Edit"),l?.({type:"tool_use",jobId:s,tool:"Edit",...T?{file:T}:{}},s)}else if(C==="file_read"){let T=R.item.filename||R.item.path;w.push(T?`Read ${T.split("/").pop()}`:"Read"),l?.({type:"tool_use",jobId:s,tool:"Read",...T?{file:T}:{}},s)}else if(C==="web_search")w.push("WebSearch"),l?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if(C==="mcp_tool_call"){let T=R.item.tool_name||R.item.name||"MCP";w.push(T),l?.({type:"tool_use",jobId:s,tool:T},s)}}if((N==="item.completed"||N==="item/completed")&&R.item){if(R.item.type==="agent_message"){let C=R.item.text;typeof C=="string"&&C&&(W.push(C),l?.({type:"delta",jobId:s,text:C},s))}else if(R.item.type==="reasoning"){let C=R.item.text;typeof C=="string"&&C&&l?.({type:"thinking",jobId:s,text:C},s)}else if(R.item.type==="file_change"&&Array.isArray(R.item.changes))for(let C of R.item.changes){let T=C.path||C.filename,L=C.kind==="add"?"Write":"Edit";if(T){w.push(`${L} ${T.split("/").pop()}`),l?.({type:"tool_use",jobId:s,tool:L,file:T},s);let _=C,ee=typeof _.kind=="string"?_.kind:void 0,y=Gs(ee),le=V.get(T),ie=Ye(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}:{},...Wt(_)?{patch:Wt(_)}:{},...ee?{rawKind:ee}:{}}),V.set(T,ie)}}else if(R.item.type==="command_execution"){let C=typeof R.item.id=="string"?R.item.id:void 0,T=C?Q.get(C):void 0,L=typeof R.item.command=="string"?R.item.command:T?.rawCommand,_=L?Lt(L):T?.command,ee=Ht(t);if(qs(T?.beforeWorktree,ee)){let y=[...new Set([...T?.beforeWorktree?.changedFiles??[],...ee?.changedFiles??[]])],le=typeof R.item.aggregated_output=="string"?St(R.item.aggregated_output,Us):void 0,ie=typeof R.item.exit_code=="number"?R.item.exit_code:R.item.exit_code===null?null:void 0,H=typeof R.item.status=="string"?R.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}:{},...H?{status:H}:{},...le?{output:le.text}:{},...le?.truncated?{outputTruncated:!0}:{},...T?.beforeWorktree?{beforeWorktree:T.beforeWorktree}:{},...ee?{afterWorktree:ee}:{},...y.length>0?{touchedFiles:Xs(t,y,T?.beforeSnapshots??new Map)}:{}})}C&&Q.delete(C)}}N==="turn.failed"&&(K=!0,z=R.error?.message||R.message||"Turn failed")}catch{}});let A=[];E.stderr?.on("data",k=>{A.push(k.toString())}),E.on("close",k=>{Z.close(),W.length===0&&D.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...D].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 Ys}from"child_process";import{createInterface as Vs}from"readline";function Kt(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 Zt(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=Ys(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=Vs({input:x.stdout}),z=new Set,Z=[];K.on("line",A=>{if(A.trim())try{let k=JSON.parse(A),R=Ce(k);z.add(R),Z.length<5&&Zs(R)&&Z.push(A.slice(0,800));let N=$e(k,["sessionId","session_id","id"],["session","conversation","thread"]);N&&!J&&(J=N);let C=Ks(k,U.length===0);C&&(U.push(C),l?.({type:"delta",jobId:s,text:C},s));let T=eo(k);T&&l?.({type:"thinking",jobId:s,text:T},s);let L=to(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 _=no(k);_&&(w=!0,q=_)}catch{}});let D=[];x.stderr?.on("data",A=>{D.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(`
33
- `)}`)),V?(w=!0,q=`Timed out after ${Math.round(a/6e4)} minutes`):A!==0&&A!==null&&(w=!0,q=D.join("").trim()||q||`Copilot process exited with code ${A}`);let k=w?Kt(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=Kt(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 Ks(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"&&xt(s))return s.text;if(typeof s.message=="string"&&xt(s))return s.message;if(typeof s.delta=="string"&&xt(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 Zs(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function eo(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 to(s){let e=$e(s,["tool","toolName","tool_name","name"]),n=$e(s,["command","cmd"]),t=$e(s,["file","path","filename","filePath"]),o=Ce(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
34
- `)[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 no(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 $e(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=$e(o,e);if(i)return i}}function xt(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 so}from"child_process";import{copyFile as en,mkdir as tn,readdir as oo,readFile as ro,writeFile as io}from"fs/promises";import{join as ke}from"path";var Ke=class{constructor(e){this.projectRoot=e;let n=ke(e,".popmelt");this.decisionsDir=ke(n,"decisions"),this.screenshotsDir=ke(n,"screenshots")}async persist(e,n,t){try{await tn(this.decisionsDir,{recursive:!0}),await tn(this.screenshotsDir,{recursive:!0});try{await en(n,ke(this.screenshotsDir,`s-${e.id}.webp`))}catch{}for(let o=0;o<t.length;o++)try{let i=e.pastedImagePaths[o];i&&await en(t[o],ke(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await io(ke(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 oo(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 ro(ke(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=>{so("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 nn,writeFile as De}from"fs/promises";import{join as Oe}from"path";var ao=80,lo=24,sn=1e3,Ze=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 nn(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 nn(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 De(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 De(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 De(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 De(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await _e(this.screenshotsDir,{recursive:!0}),await De(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 on(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?ln(t):null}catch{return null}}function rn(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?ln(t,"pending"):null}catch{return null}}function an(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=mo(t.assertionResults,e),i=go(o);return{status:i,summary:ye(t.summary)||pn(i),assertionResults:o,tooling:yo(t.tooling)}}catch{}return{status:"needs_review",summary:et(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 ln(s,e="approved"){let n=[];return s.forEach((t,o)=>{if(!t||typeof t!="object")return;let i=t,a=ye(i.title),l=ye(i.prompt),f=ye(i.rationale),v=Te(i.assertions);if(!a||!l||v.length===0)return;let x=po(i.category),E=vo(ye(i.id))||`eval-${fn(a).slice(0,32)||o+1}`,B=fo(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:Te(i.sourceDecisionIds),sourceThreadIds:Te(i.sourceThreadIds)})}),n}function cn(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,ao),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,lo);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
35
-
36
- 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.
37
-
38
- ## Current Design Model
39
- \`\`\`json
40
- ${JSON.stringify(s.model??null,null,2)}
41
- \`\`\`
42
-
43
- ## Existing Eval Suite
44
- \`\`\`json
45
- ${JSON.stringify(s.existingSuite,null,2)}
46
- \`\`\`
47
-
48
- ## Recent Decisions
49
- ${e.map(co).join(`
50
-
51
- `)||"No decisions found."}
52
-
53
- ## Recent Threads
54
- ${n.map(uo).join(`
55
-
56
- `)||"No threads found."}
57
-
58
- ## Instructions
59
- 1. Infer evals that encode reusable taste, design judgment, product behavior, or interaction expectations.
60
- 2. Prefer proposals backed by multiple decisions, rich thread context, or explicit approved/resolved outcomes.
61
- 3. Avoid one-off implementation chores, temporary bug fixes, vague preferences, or evals that cannot be checked later.
62
- 4. Cite source decision ids and thread ids for each proposal.
63
- 5. Present proposals as clear text first. Group them by Component, Layout, Copy, Interaction, Visual, and Workflow.
64
- 6. Ask the developer what to approve, reject, or adjust.
65
- 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.
66
- 8. Tell the developer that the proposals have been saved to the Eval panel for accept/reject review.
67
- 9. Do NOT output an <evals> block yet. First get the developer's approval.
68
-
69
- ## After Approval
70
- 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:
71
-
72
- \`\`\`json
73
- {
74
- "id": "eval-short-stable-id",
75
- "title": "Short human-readable name",
76
- "status": "approved",
77
- "category": "component",
78
- "prompt": "The eval instruction an agent should satisfy.",
79
- "assertions": ["Observable expectation 1", "Observable expectation 2"],
80
- "rationale": "Why this eval represents the designer's taste.",
81
- "sourceDecisionIds": ["decision-id"],
82
- "sourceThreadIds": ["thread-id"]
83
- }
84
- \`\`\`
85
-
86
- Allowed categories: component, layout, copy, interaction, visual, workflow.
87
- Return only the <evals> block after approval.
88
-
89
- ## First Response Structured Block
90
- 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 dn(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.
29
+ </html>`}var Js=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ns=new Set(["default","flex","fast","priority"]);function ht(o){let e=typeof o.reasoningEffort=="string"&&Js.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Ns.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function mn(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 Bs}from"child_process";import{createInterface as Fs}from"readline";var Ls=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"]),Ho=1e5;function zs(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ls.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>Ho?t.slice(0,Ho)+`
30
+ \u2026[truncated]`:t}function fn(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:g,timeoutMs:P=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),g&&I.push("--effort",g);for(let h of i)I.push("--allowedTools",h);let y=Bs(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,v=[],x=[],S=[],A=!1,J="",_,N,T=!1,B=setTimeout(()=>{T=!0,y.kill("SIGTERM"),setTimeout(()=>{try{y.kill("SIGKILL")}catch{}},5e3)},P),W=Fs({input:y.stdout}),te=new Set;W.on("line",ne=>{if(ne.trim())try{let oe=JSON.parse(ne);oe.session_id&&!f&&(f=oe.session_id);let he=oe.type??(oe.event?.type?`event.${oe.event.type}`:"unknown");if(te.add(he),oe.type==="result"&&oe.result&&v.length===0){let Y=typeof oe.result=="string"?oe.result:"";Y&&(v.push(Y),b?.({type:"delta",jobId:o,text:Y},o))}if(oe.type==="assistant"&&Array.isArray(oe.message?.content)){typeof oe.error=="string"&&(_=oe.error);for(let Y of oe.message.content){if(Y.type==="text"&&Y.text&&(v.push(Y.text),b?.({type:"delta",jobId:o,text:Y.text},o)),Y.type==="tool_use"&&Y.name){let G=Y.input?.file_path||Y.input?.path||void 0,q=zs(Y);if(b?.({type:"tool_use",jobId:o,tool:Y.name,...G?{file:G}:{},...q?{content:q}:{}},o),Y.name==="Edit"&&Y.input?.file_path){let fe={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};x.push(fe),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:fe.file_path,oldString:typeof fe.old_string=="string"?fe.old_string:void 0,newString:typeof fe.new_string=="string"?fe.new_string:void 0,replaceAll:typeof fe.replace_all=="boolean"?fe.replace_all:void 0})}else Y.name==="Write"&&Y.input?.file_path&&(x.push({tool:"Write",file_path:Y.input.file_path,content:Y.input.content}),S.push({sequence:S.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:o,text:Y.thinking},o)}}oe.type==="result"&&oe.is_error===!0&&(A=!0,typeof oe.error=="string"&&(_=oe.error),typeof oe.result=="string"&&(N=oe.result)),oe.type==="user"&&oe.tool_use_result?.file?.filePath&&b?.({type:"tool_use",jobId:o,tool:"Read",file:oe.tool_use_result.file.filePath},o)}catch{}});let H=[];y.stderr?.on("data",ne=>{H.push(ne.toString())}),y.on("close",ne=>{if(clearTimeout(B),W.close(),v.length===0&&te.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...te].join(", ")}`),T)A=!0,J=`Timed out after ${Math.round(P/6e4)} minutes`;else if(ne!==0&&ne!==null){A=!0;let he=H.join("").trim(),Y=v.join("").trim(),G=v.length===0&&te.size>0?` (no text captured, event types: ${[...te].join(", ")})`:"";J=he||N||Y||`Claude process exited with code ${ne}${G}`}A&&!J&&N&&(J=N);let oe=qs(J,_);h({sessionId:f,text:v.join(""),success:!A,error:A?oe.message:void 0,errorCode:A?oe.code:void 0,recoverableError:A?oe.recoverable:void 0,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})}),y.on("error",ne=>{clearTimeout(B),A=!0,J=ne.message,h({sessionId:f,text:v.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:y,result:p}}function qs(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 Us,spawnSync as Yo}from"child_process";import{readFileSync as Ws,statSync as Hs}from"fs";import{basename as Gs,extname as Vs,isAbsolute as Ks,relative as Zo,resolve as Qs}from"path";import{createInterface as Xs}from"readline";function Go(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Vo=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"]),oo=2e5,Ys=1e5,er=2e5;function tr(o){let e=Gs(o).toLowerCase(),n=Vs(o).toLowerCase();return Vo.has(n)||Vo.has(e)}function Ut(o,e){let n=Ks(e)?e:Qs(o,e),t=Zo(o,n);return t===""||t.startsWith("..")?null:n}function hn(o,e){if(!tr(e))return;let n=Ut(o,e);if(n)try{let t=Hs(n);return t.isFile()?t.size>oo?{exists:!0,truncated:!0}:{exists:!0,content:Ws(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Zs(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function ei(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 Ko(o){return Zs(o,["patch","diff","unifiedDiff","unified_diff"])}function ro(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Qo(o,e){let n=Yo("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:er+65536});return n.status!==0?null:n.stdout??""}function ti(o){let e=new Set;for(let n of o.split(`
31
+ `)){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 Xo(o){let e=Qo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Qo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=ro(n,er);return{status:e,changedFiles:ti(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function ni(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function oi(o,e){if(!tr(e))return;let n=Ut(o,e);if(!n)return;let t=Zo(o,n);if(t===""||t.startsWith(".."))return;let r=Yo("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:oo+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=ro(s,oo);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function ri(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):oi(o,t),s=hn(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function gn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,g=[];if(s){g.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let I of l)g.push("-c",I);i&&g.push("-m",i),g.push(s),g.push(n),r&&g.push("--image",r)}else{g.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let I of l)g.push("-c",I);i&&g.push("-m",i),g.push(n),r&&g.push("--image",r)}let P=Us("codex",g,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),b=new Promise(I=>{let y,p=[],h=[],f=[],v=new Map,x=new Map,S=!1,A="",J=Xs({input:P.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&&!y&&(y=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 te=B.item.type;if(te==="command_execution"){let H=B.item.command,ne=H?Go(H):void 0,oe=Xo(t),he=new Map;for(let G of oe?.changedFiles??[])he.set(G,hn(t,G));typeof B.item.id=="string"&&x.set(B.item.id,{...H?{rawCommand:H}:{},...ne?{command:ne}:{},...oe?{beforeWorktree:oe}:{},beforeSnapshots:he});let Y=ne?`Bash: ${ne.split(`
32
+ `)[0].slice(0,80)}`:"Bash";h.push(Y),c?.({type:"tool_use",jobId:o,tool:"Bash",...ne?{content:ne}:{}},o)}else if(te==="file_change"){let H=B.item.filename||B.item.path;H&&!v.has(H)&&v.set(H,hn(t,H)),h.push(H?`Edit ${H.split("/").pop()}`:"Edit");let ne=H?Ut(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...ne?{file:ne}:{}},o)}else if(te==="file_read"){let H=B.item.filename||B.item.path;h.push(H?`Read ${H.split("/").pop()}`:"Read");let ne=H?Ut(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...ne?{file:ne}:{}},o)}else if(te==="web_search")h.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(te==="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 te=B.item.text;typeof te=="string"&&te&&(p.push(te),c?.({type:"delta",jobId:o,text:te},o))}else if(B.item.type==="reasoning"){let te=B.item.text;typeof te=="string"&&te&&c?.({type:"thinking",jobId:o,text:te},o)}else if(B.item.type==="file_change"&&Array.isArray(B.item.changes))for(let te of B.item.changes){let H=te.path||te.filename,ne=te.kind==="add"?"Write":"Edit";if(H){h.push(`${ne} ${H.split("/").pop()}`);let oe=Ut(t,H)??H;c?.({type:"tool_use",jobId:o,tool:ne,file:oe},o);let he=te,Y=typeof he.kind=="string"?he.kind:void 0,G=ei(Y),q=v.get(H),fe=hn(t,H);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:H,...q?{before:q}:{},...fe?{after:fe}:{},...Ko(he)?{patch:Ko(he)}:{},...Y?{rawKind:Y}:{}}),v.set(H,fe)}}else if(B.item.type==="command_execution"){let te=typeof B.item.id=="string"?B.item.id:void 0,H=te?x.get(te):void 0,ne=typeof B.item.command=="string"?B.item.command:H?.rawCommand,oe=ne?Go(ne):H?.command,he=Xo(t);if(ni(H?.beforeWorktree,he)){let Y=[...new Set([...H?.beforeWorktree?.changedFiles??[],...he?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?ro(B.item.aggregated_output,Ys):void 0,q=typeof B.item.exit_code=="number"?B.item.exit_code:B.item.exit_code===null?null:void 0,fe=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",...ne?{rawCommand:ne}:{},...oe?{command:oe}:{},...q!==void 0?{exitCode:q}:{},...fe?{status:fe}:{},...G?{output:G.text}:{},...G?.truncated?{outputTruncated:!0}:{},...H?.beforeWorktree?{beforeWorktree:H.beforeWorktree}:{},...he?{afterWorktree:he}:{},...Y.length>0?{touchedFiles:ri(t,Y,H?.beforeSnapshots??new Map)}:{}})}te&&x.delete(te)}}W==="turn.failed"&&(S=!0,A=B.error?.message||B.message||"Turn failed")}catch{}});let N=[];P.stderr?.on("data",T=>{N.push(T.toString())}),P.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:y,text:p.join(""),success:!S,error:S?A:void 0,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})}),P.on("error",T=>{S=!0,A=T.message,I({sessionId:y,text:p.join(""),success:!1,error:A,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})})});return{process:P,result:b}}import{spawn as si}from"child_process";import{createInterface as ii}from"readline";function nr(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 or(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 g=si(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),P=new Promise(b=>{let I,y=[],p=[],h=!1,f="",v=!1,x=setTimeout(()=>{v=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},i),S=ii({input:g.stdout}),A=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Ht(T);A.add(B),J.length<5&&ci(B)&&J.push(N.slice(0,800));let W=Wt(T,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!I&&(I=W);let te=ai(T,y.length===0);te&&(y.push(te),c?.({type:"delta",jobId:o,text:te},o));let H=di(T);H&&c?.({type:"thinking",jobId:o,text:H},o);let ne=li(T);ne&&(p.push(ne.label),c?.({type:"tool_use",jobId:o,tool:ne.tool,...ne.file?{file:ne.file}:{},...ne.content?{content:ne.content}:{}},o));let oe=pi(T);oe&&(h=!0,f=oe)}catch{}});let _=[];g.stderr?.on("data",N=>{_.push(N.toString())}),g.on("close",N=>{clearTimeout(x),S.close(),y.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(`
33
+ `)}`)),v?(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?nr(f,s):null;b({sessionId:I,text:y.join(""),success:!h,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),g.on("error",N=>{clearTimeout(x);let T=nr(N.message,s);b({sessionId:I,text:y.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:g,result:P}}function Ht(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 ai(o,e=!1){let n=Ht(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 ze(o.delta)??ze(o.content)??ze(o.message);if(n==="assistant.message"&&e)return ze(o.message)??ze(o.content)??ze(o);if(n==="result"&&e)return ze(o.result)??ze(o.output)??ze(o.message)??ze(o);let s=o.content;if(s?.type==="text"&&typeof s.text=="string")return s.text;if(typeof o.text=="string"&&so(o))return o.text;if(typeof o.message=="string"&&so(o))return o.message;if(typeof o.delta=="string"&&so(o))return o.delta}function ze(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(ze).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=ze(e[n]);if(t)return t}}function ci(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function di(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 li(o){let e=Wt(o,["tool","toolName","tool_name","name"]),n=Wt(o,["command","cmd"]),t=Wt(o,["file","path","filename","filePath"]),r=Ht(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
34
+ `)[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 pi(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"&&Ht(o).toLowerCase().includes("error"))return o.message}function Wt(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=Wt(r,e);if(s)return s}}function so(o){let e=Ht(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as ui,readFile as mi}from"fs/promises";import{join as io}from"path";var yn=class{constructor(e){let n=io(e,".popmelt");this.decisionsDir=io(n,"decisions")}async listDecisionIds(){try{return(await ui(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 mi(io(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 sr(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=bi(t.assertionResults,e),s=xi(r);return{status:s,summary:tt(t.summary)||dr(s),assertionResults:r,tooling:Si(t.tooling)}}catch{}return{status:"needs_review",summary:ki(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 ir(o,e){let n=(o.selectedChanges??[]).flatMap(v=>Array.isArray(v.path)&&v.path.length?[v.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(v=>v.path),s=[...new Set(r.map(v=>v.map(String).join(".")).filter(Boolean))].map(v=>({kind:"model_path",value:v}));if(s.length===0||o.decisionIds.length===0)return[];let i=new Set(o.decisionIds),c=new Set(s.map(v=>v.value)),d=e.cases.find(v=>v.status!=="rejected"&&(v.sourceDecisionIds.some(x=>i.has(x))||(v.dependencies??[]).some(x=>x.kind==="model_path"&&c.has(x.value)))),l=(o.selectedChanges??[]).find(v=>v.label?.trim())?.label?.trim()??t.find(v=>v.label?.trim())?.label?.trim()??o.title,g=d?.id.startsWith("eval-model-")??!1,P=(o.selectedChanges??[]).flatMap(v=>Array.isArray(v.path)&&v.path.length>0?[{path:v.path,value:v.value,label:v.label,detail:v.detail}]:[]),I=(P.length>0?P:t.map(v=>({path:v.path,value:v.value,label:v.label,detail:v.rationale}))).flatMap(v=>fi(v,o.decisionIds)),y=wn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!g?d.assertions:[],...I,...I.length===0&&y?[y]:[]])],h=s[0].value,f=h.startsWith("components.")?"component":h.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!g?d.title:l,status:"pending",category:d?.category??f,prompt:d&&!g?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!g?d.rationale:yi(h),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...s].map(v=>[`${v.kind}:${v.value}`,v])).values()]}]}function fi(o,e){let n=String(o.path[0]??"");if(n==="rules")return hi(o.value,e);if(n==="components"){let i=ar(String(o.path[1]??o.label??"component")),c=vn(o.value),d=c?Vt(c.usage):[];if(d.length>0){let g=vi(d),P=d.length===1?"uses":"use";return[`The ${g} ${P} 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 g=gi(l,i);if(g)return[g]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),c=vn(o.value),d=c&&"value"in c?c.value:o.value,l=wi(d);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=vn(o.value),r=t?tt(t.text)||tt(t.constraint):typeof o.value=="string"?o.value:"",s=wn(r||o.detail||"");return s?[s]:[]}function hi(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let c=vn(i),d=c?tt(c.text):"";return d?[{text:d,sources:c?Vt(c.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(i=>wn(i.text)).filter(i=>!!i)}function gi(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?Rt(`Wherever ${Gt(n[1])}, the shared ${e} implementation is used instead of ${Gt(n[2])}`):wn(o)}function ao(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Rt(`${rr(n[1])} is ${Gt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Rt(rr(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Rt(`The product uses ${Gt(r[1])}`);let s=e.match(/^Do not (.+?)\.?$/i);return s?Rt(`The product does not ${Gt(s[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Rt(e)}var wn=ao;function yi(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${ar(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 vn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function ar(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function vi(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 wi(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function Rt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function rr(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Gt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function cr(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.
91
35
 
92
36
  ## Eval
93
37
  \`\`\`json
94
- ${JSON.stringify(s.evalCase,null,2)}
38
+ ${JSON.stringify(o.evalCase,null,2)}
95
39
  \`\`\`
96
40
 
97
41
  ## Scope
98
42
  \`\`\`json
99
- ${JSON.stringify(s.scope,null,2)}
43
+ ${JSON.stringify(o.scope,null,2)}
100
44
  \`\`\`
101
45
 
102
46
  ## Current Design Model
103
47
  \`\`\`json
104
- ${JSON.stringify(s.model??null,null,2)}
48
+ ${JSON.stringify(o.model??null,null,2)}
105
49
  \`\`\`
106
50
 
107
51
  ## Evidence
108
- - Current page screenshot: ${s.screenshotPath}
109
- - 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"}.
52
+ - Current page screenshot: ${o.screenshotPath}
53
+ - 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"}.
110
54
 
111
55
  ## Instructions
112
- 1. Evaluate only the current page scope.
113
- 2. Use the screenshot as baseline evidence.
114
- 3. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
115
- 4. Judge each assertion independently as "pass", "fail", or "needs_review".
116
- 5. Keep failures actionable and grounded in observed evidence.
117
- 6. Do not propose visual markers yet.
118
- 7. End with exactly one machine-readable <eval_run_result> block.
119
- 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.
120
- 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.
56
+ 1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
57
+ 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.
58
+ 3. Use the screenshot as baseline evidence.
59
+ 4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
60
+ 5. Judge each assertion independently as "pass", "fail", or "needs_review".
61
+ 6. Keep failures actionable and grounded in observed evidence.
62
+ 7. Do not propose visual markers yet.
63
+ 8. End with exactly one machine-readable <eval_run_result> block.
64
+ 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.
65
+ 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.
121
66
 
122
67
  The block must be valid JSON with this shape:
123
68
 
@@ -142,106 +87,42 @@ The block must be valid JSON with this shape:
142
87
  \`\`\`
143
88
 
144
89
  Allowed statuses: pass, fail, needs_review.
145
- Allowed chromeDevtools values: available, unavailable, unknown.`}function un(s){return`You are turning an approved Popmelt taste-model update into draft evals.
146
-
147
- 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.
90
+ Allowed chromeDevtools values: available, unavailable, unknown.`}function tt(o){return typeof o=="string"?o.trim():""}function Vt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Ii(o){let e=tt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function bi(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:Ii(s.status)??"needs_review",summary:tt(s.summary)||dr("needs_review"),evidence:Vt(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 xi(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Si(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:Vt(e.evidenceTypes).length>0?Vt(e.evidenceTypes):["screenshot"]}}function dr(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 ki(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Ri}from"crypto";import{mkdir as Pi,writeFile as Ti}from"fs/promises";import{join as co}from"path";var In=class{constructor(e){this.root=co(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=co(this.root,"eval-screenshots"),t=Ri("sha256").update(e).digest("hex"),r=co(n,`${t}.webp`);return await Pi(n,{recursive:!0}),await Ti(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as lr}from"crypto";import{mkdir as lo,readFile as po,writeFile as bn}from"fs/promises";import{dirname as uo,join as Pt}from"path";var He="[ProjectionWorker]",ji={version:1,runs:[]},Ei={version:1,updatedAt:0,proposals:[]},Mi=12;function Ai(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 pr(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(`${He} 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(`${He} Rule count ${e.length} exceeds cap of 30`),e}function _i(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function $i(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let y of s){if(!y||typeof y!="object")continue;let p=y.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(y=>{if(!y||typeof y!="object")return!1;let p=y.id,h=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(h)!==JSON.stringify(y)}).length,g=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},P=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(i).filter(y=>JSON.stringify(i[y])!==JSON.stringify(g[y])).length,I=Object.keys(c).filter(y=>JSON.stringify(c[y])!==JSON.stringify(P[y])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:I,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(y=>!r.has(y))}}function Ci(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Oi(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 xn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Oi(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=Ci(n)}function ur(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 Di(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 Ji(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 mr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Di(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Ji(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Sn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Pt(e,".popmelt");this.runsPath=Pt(t,"projection-runs.json"),this.legacyRunsPath=Pt(t,"materialization-runs.json"),this.proposalsPath=Pt(t,"projection-queue.json"),this.legacyProposalsPath=Pt(t,"model-proposals.json"),this.modelPath=Pt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await po(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Ai(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?ur(n,r):xn(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(Mi),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(y=>y.id);console.log(`${He} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),c=Li(r,i),d=_i(r,t.totalCandidateDecisionCount,c);n=lr().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 g=!0,P,b,I;try{let y=`projection-${Date.now()}`,{provider:p,result:h}=this.spawnModelAgent(y,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)g=!1,P=f.error,console.error(`${He} ${p} spawn error:`,P);else{let v=Fi(f.text,s);if(v){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of v)xn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=pr(x.rules));let S=$i(x,s,i);if(v){let J=[...new Set(v.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:v});I=A.id,console.log(`${He} Created model proposal ${A.id} for ${s.length} decision(s)`)}else g=!1,P="No valid bounded <model-changes> block found in response",console.error(`${He} ${P}`)}}catch(y){g=!1,P=y instanceof Error?y.message:String(y),console.error(`${He} Error:`,P)}return await this.persistRun({...l,status:g?"proposed":"failed",completedAt:Date.now(),error:P,outputStats:b,proposalId:I}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:g,error:P}),{processedIds:s,success:g,error:P,runId:n,proposalId:I}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=pr(e.rules)),await bn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${He} 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 lo(uo(this.runsPath),{recursive:!0}),await bn(this.runsPath,JSON.stringify(n,null,2)),n):{...ji,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??{...Ei,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??[])xn(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?ur(i,d.path):xn(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:lr().slice(0,8),status:"pending",title:Ni(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"}.`:Bi(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 lo(uo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await bn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} 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 lo(uo(this.runsPath),{recursive:!0}),await bn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await po(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await po(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",...gn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:mn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${He} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...fn(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 Ni(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 Bi(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 Fi(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(P=>typeof P=="string"||typeof P=="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 g=Array.isArray(d.decisionIds)?d.decisionIds.filter(P=>typeof P=="string"&&r.has(P)):[];return g.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:g,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Li(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
91
+ Kind: ${s.kind}
92
+ Claim: ${s.claim}
93
+ ${s.rationale?`Rationale: ${s.rationale}`:""}
94
+ Subjects: ${s.subjects.map(i=>`${i.role}:${i.subjectId}`).join(", ")}
95
+ Authority: ${s.authority.level}/${s.authority.mode}`).join(`
148
96
 
149
- Do not edit files or run commands.
150
-
151
- ## Approved Model Proposal
152
- \`\`\`json
153
- ${JSON.stringify({id:s.proposal.id,title:s.proposal.title,summary:s.proposal.summary,decisionIds:s.proposal.decisionIds,proposedModel:s.proposal.proposedModel},null,2)}
154
- \`\`\`
155
-
156
- ## Current Applied Model
157
- \`\`\`json
158
- ${JSON.stringify(s.currentModel??null,null,2)}
159
- \`\`\`
160
-
161
- ## Existing Eval Suite
162
- \`\`\`json
163
- ${JSON.stringify(s.existingSuite,null,2)}
164
- \`\`\`
165
-
166
- ## Instructions
167
- 1. Generate only evals that directly project the approved model proposal into observable checks.
168
- 2. Prefer a small number of durable evals over broad coverage. Avoid duplicates of existing evals.
169
- 3. Each eval should include concise assertions that can be judged on a page or codebase.
170
- 4. Set every generated eval status to "pending" so the designer can approve, edit, or reject it.
171
- 5. Cite the proposal's decision IDs in sourceDecisionIds.
172
- 6. End with exactly one <eval_proposals> block containing valid JSON.
173
-
174
- Each eval must use this shape:
175
-
176
- \`\`\`json
177
- {
178
- "id": "eval-short-stable-id",
179
- "title": "Short human-readable name",
180
- "status": "pending",
181
- "category": "component",
182
- "prompt": "The eval instruction an agent should satisfy.",
183
- "assertions": ["Observable expectation 1", "Observable expectation 2"],
184
- "rationale": "Why this eval projects the approved model value.",
185
- "sourceDecisionIds": ["decision-id"],
186
- "sourceThreadIds": ["${s.proposal.threadId??""}"]
187
- }
188
- \`\`\`
189
-
190
- Allowed categories: component, layout, copy, interaction, visual, workflow.
191
-
192
- <eval_proposals>
193
- []
194
- </eval_proposals>`}function co(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
195
- `),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
196
- `),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
197
- Thread: ${s.threadId??"none"}
198
- Created: ${new Date(s.createdAt).toISOString()}
199
- URL: ${s.url||"unknown"}
200
- Instructions:
201
- ${et(o||"(none)",sn)}
202
- Resolutions:
203
- ${et(i||"(none)",sn)}
204
- Files: ${a.length>0?a.join(", "):"none"}`}function uo(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}: ${et(o||i||"(no text)",500)}`}).join(`
205
- `);return`### Thread ${s.id}
206
- Messages: ${s.messages.length}
207
- Updated: ${new Date(s.updatedAt).toISOString()}
208
- ${n}`}function ye(s){return typeof s=="string"?s.trim():""}function Te(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function po(s){let e=ye(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function fo(s){let e=ye(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function ho(s){let e=ye(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function mo(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=ye(i.assertion);return a?{assertion:a,status:ho(i.status)??"needs_review",summary:ye(i.summary)||pn("needs_review"),evidence:Te(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 go(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function yo(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=ye(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Te(e.evidenceTypes).length>0?Te(e.evidenceTypes):["screenshot"]}}function pn(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 vo(s){return fn(s).slice(0,48)}function fn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function et(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as hn}from"crypto";import{mkdir as bt,readFile as tt,writeFile as Ie}from"fs/promises";import{dirname as It,join as Ne}from"path";var ae="[Materializer]",mn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},wo={version:1,runs:[]},So={version:1,updatedAt:0,proposals:[]},xo=12;function bo(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 Je(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 Io(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Po(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 ko(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function Ro(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 Mo(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=Ro(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=ko(n)}function Eo(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 nt=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=Ne(e,".popmelt");this.indexPath=Ne(o,"materialized.json"),this.runsPath=Ne(o,"materialization-runs.json"),this.proposalsPath=Ne(o,"model-proposals.json"),this.modelPath=Ne(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await tt(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=bo(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 Ie(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 Ie(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 Ie(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 Ie(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,xo);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=$o(o,a),f=Io(o,t.totalCandidateDecisionCount,l);n=hn().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=st(V.text);if(Q){Array.isArray(Q.rules)&&(Q.rules=Je(Q.rules)),B=Po(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=Co(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=st(a.text);return l?(Array.isArray(l.rules)&&(l.rules=Je(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await Ie(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=Je(e.rules)),await Ie(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 tt(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={...mn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...mn,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 bt(It(this.indexPath),{recursive:!0}),await Ie(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write index:`,n)}}async loadRuns(){try{let e=await tt(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...wo,runs:[]}}async loadModelProposals(){try{let e=await tt(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...So,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?Eo(i,l.path):Mo(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:hn().slice(0,8),status:"pending",title:To(e.proposedModel),summary:Ao(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 bt(It(this.proposalsPath),{recursive:!0}),await Ie(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 bt(It(this.runsPath),{recursive:!0}),await Ie(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",...Ve(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",...Xe(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 To(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 Ao(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 st(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 $o(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}]
209
- Files modified: ${J}`}).join(`
210
- `),f=i.annotations.map(x=>x.instruction).filter(Boolean).join(`
211
- `),v=i.gitDiff?`
212
- \`\`\`diff
213
- ${i.gitDiff.slice(0,2e3)}
214
- \`\`\``:"";return`### Decision ${i.id} (${new Date(i.createdAt).toISOString()})
215
- Page: ${i.url}
216
- ${l}
217
- ${v}
218
- ${f?`
219
- Original instructions:
220
- ${f}`:""}`}).join(`
221
-
222
- `),t=s.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
97
+ `),t=o.map(s=>s.id);return`You are extracting a local design model from accumulated design decisions.
223
98
 
224
99
  ## Instructions
225
100
  1. Review the current model (if any) and the new decisions below.
226
- 2. Determine what design tokens, component patterns, and rules to add or update.
227
- 3. Output the complete updated model as a JSON object inside <model> tags.
228
- 4. Do not edit files or run commands. Return only the <model> block.
101
+ 2. Determine the smallest concrete set of design-token, component-pattern, and rule changes supported by those decisions.
102
+ 3. Attribute every change to one or more accepted decision IDs from this prompt.
103
+ 4. Output no more than 40 changes as a JSON array inside <model-changes> tags.
104
+ 5. Do not edit files or run commands. Return only the <model-changes> block.
229
105
 
230
106
  ${e?`## Current Model
231
107
  \`\`\`json
232
108
  ${JSON.stringify(e,null,2)}
233
109
  \`\`\`
234
110
 
235
- 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."}
111
+ 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."}
236
112
 
237
- ## Design Decisions to Materialize
113
+ ## Accepted Decisions to Project
238
114
  ${n}
239
115
 
240
116
  ## Output Format
241
- Output the full model inside <model> tags. The model is a JSON object with these sections:
242
- - \`tokens\`: Design tokens (colors, spacing, typography, etc.)
243
- - \`components\`: Component-level patterns (e.g., button styles, card layouts)
244
- - \`rules\`: Array of structured rule objects
117
+ Each change is a JSON object with:
118
+ - \`id\`: stable descriptive identifier for this proposed change
119
+ - \`path\`: JSON path in the derived model; the first segment must be \`tokens\`, \`components\`, or \`rules\`
120
+ - \`label\`: short human-readable label
121
+ - \`value\`: complete JSON value to set at that path
122
+ - \`decisionIds\`: one or more IDs from ${JSON.stringify(t)} that directly support the change
123
+ - \`rationale\`: concise explanation of the projection from decision to model entry
124
+
125
+ 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.
245
126
 
246
127
  ### Rule format
247
128
  Each rule is a JSON object:
@@ -261,163 +142,98 @@ Fields:
261
142
  - **Keep:** Enforceable patterns, constraints, relationships between elements, accessibility requirements.
262
143
 
263
144
  Example:
264
- <model>
265
- {
266
- "tokens": {
267
- "colors": { "primary": "#3b82f6" },
268
- "spacing": {
269
- "sm": "4px",
270
- "md": "8px",
271
- "section-gap": { "value": "32px", "property": "gap", "bindings": ["gap-8"] }
272
- }
273
- },
274
- "components": {
275
- "button": { "padding": "12px 24px", "borderRadius": "8px" }
276
- },
277
- "rules": [
278
- { "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] },
279
- { "id": "e5f6a7b8", "scope": "color", "text": "Primary actions use the primary color token", "sources": ["d-def456"] }
280
- ]
281
- }
282
- </model>
145
+ <model-changes>
146
+ [
147
+ {
148
+ "id": "primary-color",
149
+ "path": ["tokens", "colors", "primary"],
150
+ "label": "Primary color",
151
+ "value": "#3b82f6",
152
+ "decisionIds": [${JSON.stringify(t[0]??"")}],
153
+ "rationale": "The accepted decision establishes this as the shared primary action color."
154
+ }
155
+ ]
156
+ </model-changes>
283
157
 
284
158
  ## Guidelines
285
159
  - Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
286
160
  - Extract clear, enforceable rules into the \`rules\` array as structured objects.
287
- - When merging, new decisions override conflicting older values.
161
+ - Do not silently override conflicting existing values; propose the explicit change for owner review.
288
162
  - Keep the model concise \u2014 only include patterns with clear evidence from decisions.
289
- - Do NOT output resolution or question blocks. Just output the <model> block.
163
+ - Do not emit unchanged entries or copy the complete model.
164
+ - Do NOT output resolution or question blocks. Just output the <model-changes> block.
290
165
  - Spacing tokens can be plain strings ("8px") or objects with code bindings:
291
166
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
292
167
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
293
168
  - bindings: Tailwind class names (without responsive prefixes) that use this token
294
- Include property and bindings when the decision context has class-level evidence.`}function Co(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
295
-
296
- ## Current Model
297
- \`\`\`json
298
- ${JSON.stringify(s,null,2)}
299
- \`\`\`
300
-
301
- ## Instructions
302
- 1. Review all current rules.
303
- 2. Merge rules that cover the same concern into single, clear rules.
304
- 3. Remove rules that are:
305
- - Workflow advice ("After SSR fixes, re-verify headless output")
306
- - Instance-level observations ("Footer tagline is 'Design everything.'")
307
- - Restating tokens or components already defined elsewhere in the model
308
- - Procedural instructions rather than design constraints
309
- 4. Output the full model with consolidated rules.
310
- 5. Do not edit files or run commands. Return only the <model> block.
311
-
312
- ## Rule format
313
- Each rule MUST be a JSON object:
314
- { "id": "a1b2c3d4", "scope": "<scope>", "text": "<rule text>", "sources": ["<decision-id>", ...] }
315
-
316
- - \`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.
317
- - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
318
- - \`text\`: Clear, enforceable design constraint
319
- - \`sources\`: Merge source arrays when combining rules
320
-
321
- ## Hard cap: 30 rules maximum.
322
-
323
- Prioritize rules that are:
324
- - Enforceable constraints (not preferences)
325
- - Cross-cutting (affect many elements)
326
- - Not already captured by tokens or component definitions in the model
327
-
328
- ## Output
329
- Output the complete model inside <model> tags. Preserve tokens and components as-is \u2014 only rules change.
330
-
331
- <model>
332
- { "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
333
- </model>`}function gn(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.
334
-
335
- ## Current Model
336
- \`\`\`json
337
- ${JSON.stringify(s,null,2)}
338
- \`\`\`
339
-
340
- ## Instructions
341
- 1. Review all current rules, tokens, and components.
342
- 2. Propose specific changes \u2014 additions, merges, removals \u2014 with brief reasoning for each.
343
- 3. Present your proposals as clear text so the developer can review them.
344
- 4. Do NOT output a <model> block yet. First get the developer's approval.
345
-
346
- ## Output format
347
- - List each proposed change as a numbered item with a short rationale.
348
- - Group by action: **Merge**, **Add**, **Remove**, **Reword**.
349
- - After your proposals, output a <question> block asking the developer to approve, adjust, or reject.
350
-
351
- Example:
352
- **Merge**
353
- 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)
354
-
355
- **Remove**
356
- 2. "After fixing SSR, re-verify headless output" \u2014 workflow advice, not a design constraint
357
-
358
- **Add**
359
- 3. "Primary actions use the primary color token; secondary actions use gray-500" \u2014 implied by token usage but not codified
360
-
361
- <question>
362
- 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.
363
- </question>
364
-
365
- ## After approval
366
- 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 ot=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 _o}from"child_process";import{readFile as kt}from"fs/promises";import{homedir as it}from"os";import{join as he}from"path";var Rt=/popmelt/i,Do=/chrome|devtools/i;function Re(){return{found:!1,name:null,scope:null,disabled:!1}}function Ae(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function ze(s){for(let e of Object.keys(s))if(Rt.test(e))return e;return null}async function rt(s){try{let e=await kt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function Mt(s){let e=it(),n=await rt(he(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=ze(o.mcpServers);if(i)return Ae(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=ze(l.mcpServers);if(f){let v=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(x=>Rt.test(x));return Ae(f,"project",v)}}}}}let t=await rt(he(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=ze(o.mcpServers);if(a){let l=await yn(s,a);return Ae(a,"mcp.json",l)}}let i=ze(o);if(i&&i!=="mcpServers"){let a=await yn(s,i);return Ae(i,"mcp.json",a)}}return Re()}async function yn(s,e){let n=he(s,".claude","settings.local.json"),t=await rt(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var Oo=/^\[mcp_servers\.([^\]]+)\]/;function No(s){return s.replace(/^"(.+)"$/,"$1")}function Jo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function wn(s){let e=s.split(`
367
- `),n=[],t=null;for(let o of e){let i=o.match(Oo);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
368
- `)}),t={name:i[1],bodyLines:[]}):o.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
369
- `)}),t=null):t&&t.bodyLines.push(o)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
370
- `)}),n}function Sn(s){return/enabled\s*=\s*false/i.test(s)}async function Et(s){let e=process.env.CODEX_HOME||he(it(),".codex"),n=await vn(he(e,"config.toml"),"user");if(n.found)return n;let t=await vn(he(s,".codex","config.toml"),"project");return t.found?t:Re()}async function zo(s,e){let n=process.env.CODEX_HOME||he(it(),".codex"),t=new Set;for(let o of[he(n,"config.toml"),he(s,".codex","config.toml")])try{let i=await kt(o,"utf-8");for(let a of wn(i)){if(Jo(a.name)||Sn(a.body))continue;let l=No(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function xn(s){return zo(s,Do)}async function Tt(s,e="copilot"){let n=await Bo(e);if(n.found)return n;let t=process.env.COPILOT_HOME||he(it(),".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:Re()}async function Bo(s){try{let e=await new Promise((n,t)=>{_o(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return bn(JSON.parse(e),"user")}catch{return Re()}}async function Pt(s,e){let n=await rt(s);return bn(n,e)}function bn(s,e){if(!s||typeof s!="object")return Re();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=ze(t);return o?Ae(o,e):Re()}async function vn(s,e){try{let n=await kt(s,"utf-8"),t=wn(n);for(let o of t)if(Rt.test(o.name)){let i=Sn(o.body);return Ae(o.name,e,i)}}catch{}return Re()}import{execFile as In}from"child_process";import{mkdir as Fo,readFile as Pn,writeFile as kn}from"fs/promises";import{homedir as Rn}from"os";import{dirname as jo,join as At}from"path";var $t="https://mcp.popmelt.com/mcp";async function Mn(s=$t){let e=At(Rn(),".claude.json"),n;try{let o=await Pn(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 kn(e,JSON.stringify(n,null,2)+`
371
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function En(s=$t){let e=process.env.CODEX_HOME||At(Rn(),".codex"),n=At(e,"config.toml"),t;try{t=await Pn(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Fo(jo(n),{recursive:!0});let o=`
169
+ Include property and bindings when the decision context has class-level evidence.`}var kn=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 zi}from"child_process";import{readFile as fo}from"fs/promises";import{homedir as Pn}from"os";import{join as Le}from"path";var ho=/popmelt/i,qi=/chrome|devtools/i;function gt(){return{found:!1,name:null,scope:null,disabled:!1}}function Tt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Kt(o){for(let e of Object.keys(o))if(ho.test(e))return e;return null}async function Rn(o){try{let e=await fo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function go(o){let e=Pn(),n=await Rn(Le(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Kt(r.mcpServers);if(s)return Tt(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=Kt(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(g=>ho.test(g));return Tt(d,"project",l)}}}}}let t=await Rn(Le(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Kt(r.mcpServers);if(i){let c=await fr(o,i);return Tt(i,"mcp.json",c)}}let s=Kt(r);if(s&&s!=="mcpServers"){let i=await fr(o,s);return Tt(s,"mcp.json",i)}}return gt()}async function fr(o,e){let n=Le(o,".claude","settings.local.json"),t=await Rn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(s=>s===e)}return!1}var Ui=/^\[mcp_servers\.([^\]]+)\]/;function Wi(o){return o.replace(/^"(.+)"$/,"$1")}function Hi(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function gr(o){let e=o.split(`
170
+ `),n=[],t=null;for(let r of e){let s=r.match(Ui);s?(t&&n.push({name:t.name,body:t.bodyLines.join(`
171
+ `)}),t={name:s[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
172
+ `)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
173
+ `)}),n}function yr(o){return/enabled\s*=\s*false/i.test(o)}async function yo(o){let e=process.env.CODEX_HOME||Le(Pn(),".codex"),n=await hr(Le(e,"config.toml"),"user");if(n.found)return n;let t=await hr(Le(o,".codex","config.toml"),"project");return t.found?t:gt()}async function Gi(o,e){let n=process.env.CODEX_HOME||Le(Pn(),".codex"),t=new Set;for(let r of[Le(n,"config.toml"),Le(o,".codex","config.toml")])try{let s=await fo(r,"utf-8");for(let i of gr(s)){if(Hi(i.name)||yr(i.body))continue;let c=Wi(i.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function vr(o){return Gi(o,qi)}async function vo(o,e="copilot"){let n=await Vi(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Le(Pn(),".copilot"),r=await mo(Le(t,"mcp-config.json"),"user");if(r.found)return r;let s=await mo(Le(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await mo(Le(o,".github","mcp.json"),"mcp.json");return i.found?i:gt()}async function Vi(o){try{let e=await new Promise((n,t)=>{zi(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return wr(JSON.parse(e),"user")}catch{return gt()}}async function mo(o,e){let n=await Rn(o);return wr(n,e)}function wr(o,e){if(!o||typeof o!="object")return gt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Kt(t);return r?Tt(r,e):gt()}async function hr(o,e){try{let n=await fo(o,"utf-8"),t=gr(n);for(let r of t)if(ho.test(r.name)){let s=yr(r.body);return Tt(r.name,e,s)}}catch{}return gt()}import{execFile as Ir}from"child_process";import{mkdir as Ki,readFile as br,writeFile as xr}from"fs/promises";import{homedir as Sr}from"os";import{dirname as Qi,join as wo}from"path";var Io="https://mcp.popmelt.com/mcp";async function kr(o=Io){let e=wo(Sr(),".claude.json"),n;try{let r=await br(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 xr(e,JSON.stringify(n,null,2)+`
174
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Rr(o=Io){let e=process.env.CODEX_HOME||wo(Sr(),".codex"),n=wo(e,"config.toml"),t;try{t=await br(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Ki(Qi(n),{recursive:!0});let r=`
372
175
  [mcp_servers.popmelt]
373
- url = "${s}"
374
- `;return await kn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Tn(s=$t,e="copilot"){let n=await Lo(e);if(Uo(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{In(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 Lo(s){try{let e=await new Promise((n,t)=>{In(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 Uo(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 at=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 lt(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 Wo(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=[],D=0,A=[];for(;D<o.length;){let k=o.indexOf(i,D);if(k===-1)break;let R=k+i.length;if(o.slice(k,k+a.length).equals(a))break;let N=R;o[N]===13&&o[N+1]===10&&(N+=2);let C=o.indexOf(`\r
176
+ url = "${o}"
177
+ `;return await xr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Pr(o=Io,e="copilot"){let n=await Xi(e);if(Yi(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{Ir(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 Xi(o){try{let e=await new Promise((n,t)=>{Ir(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 Yi(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 Tn=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 jo,readFile as At,writeFile as Eo}from"fs/promises";import{join as lt}from"path";var Zi=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 jn(o){return new Set(bo(o).split(" ").filter(e=>e.length>2&&!Zi.has(e)))}function Tr(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 ea(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 ta(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(bo).filter(Boolean),s=jn([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 ea(i)){let l=bo(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 P=["/","#","[","]","="].some(b=>d.value.includes(b))?0:Math.round(Tr(jn(l),s)*55);P>=30&&P>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:P>=45?"strong":"weak",matchedBy:"query_text",score:P})}c&&n.set(i.id,c)}return n}function na(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 oa(o){return Math.ceil(JSON.stringify(o).length/4)}function Qt(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(v=>v.entity.entityType==="proposal"&&v.entity.entityId===h.id&&v.toState==="deferred"&&v.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=ta(n,e),d=[...c.values()].sort((h,f)=>f.score-h.score),l=jn([e.action,e.text].filter(Boolean).join(" ")),g=s.flatMap(h=>{let f=h.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),v=Math.max(0,...f.map(A=>A.score)),x=Math.round(Tr(jn(h.claim),l)*35),S=v+x;return S>=50?[{proposal:h,proposalMatches:f,score:S}]:[]}).sort((h,f)=>f.score-h.score||h.proposal.id.localeCompare(f.proposal.id)),P=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),I=[],y=0;for(let h of g){if(I.length>=P)break;let f=h.proposal.sourceRefs.slice(0,4),v={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:na(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={...v,estimatedTokens:oa(v)};if(y+x.estimatedTokens>b)break;I.push(x),y+=x.estimatedTokens}let p=Math.max(0,g.length-I.length);return{packets:I,subjectMatches:d.map(({score:h,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:g.length,omittedPacketCount:p,maxEstimatedTokens:b,estimatedTokens:y},uncertainty:c.size===0?"subject_unresolved":g.length===0?"no_relevant_pending_proposal":void 0}}var ra=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function xo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function En(o){return new Set(xo(o).split(" ").filter(e=>e.length>2&&!ra.has(e)))}function jr(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 sa(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(xo).filter(Boolean),r=En([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 g=xo(l.value);for(let I of t){let y=g===I?95:g.includes(I)||I.includes(g)?75:0;y>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:y>=90?"exact":"strong",matchedBy:l.by,score:y})}let b=["/","#","[","]","="].some(I=>l.value.includes(I))?0:Math.round(jr(En(g),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 ia(o){return Math.ceil(JSON.stringify(o).length/4)}function jt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function aa(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 ca(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 Er(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"),g=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),P=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),y=sa(r,e),p=new Map(y.map(_=>[_.subjectId,_.score])),h=En([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(jr(En(_.claim),h)*35),B=N+T;return B>=50?[{decision:_,score:B}]:[]}).sort((_,N)=>N.score-_.score||_.decision.id.localeCompare(N.decision.id)),v=new Map;for(let _ of f.slice(0,t))v.set(_.decision.id,_.decision);for(let _ of o.relationships){if(!jt(_,"excepts")&&!jt(_,"contradicts"))continue;let N=i.find(B=>B.id===_.from.entityId),T=i.find(B=>B.id===_.to.entityId);!N||!T||!v.has(N.id)&&!v.has(T.id)||(v.size<t&&v.set(N.id,N),v.size<t&&v.set(T.id,T))}let x=[...v.values()],S=_=>_.from.entityType==="decision"&&_.to.entityType==="decision"&&v.has(_.from.entityId)&&v.has(_.to.entityId),A=(_,N=!1)=>{let T=new Set(_.map(E=>E.id)),B=g.filter(E=>E.target.entityType==="decision"&&T.has(E.target.entityId)),W=new Set(o.relationships.filter(E=>jt(E,"excepts")&&T.has(E.from.entityId)&&T.has(E.to.entityId)).flatMap(E=>[E.from.entityId,E.to.entityId])),H=o.relationships.filter(E=>jt(E,"contradicts")&&T.has(E.from.entityId)&&T.has(E.to.entityId)).map(E=>({id:E.id,decisionIds:[E.from.entityId,E.to.entityId],unresolvedQuestion:E.reason,expansionRefs:[{kind:"record",id:E.id}]})),ne=new Set(H.flatMap(E=>E.decisionIds)),oe=P.filter(E=>E.sourceRefs.some(Z=>Z.kind==="record"&&T.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===E.id&&Z.to.entityType==="decision"&&T.has(Z.to.entityId))),he=Math.max(0,f.length-_.length),Y=o.relationships.some(E=>jt(E,"contradicts")&&S(E)&&(!T.has(E.from.entityId)||!T.has(E.to.entityId))),G=N||he>0||Y,q=[];y.length===0&&(e.subjectHints?.length??0)>0?q.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):_.length===0&&q.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),H.length&&q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.flatMap(E=>E.expansionRefs)}),oe.some(E=>E.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map(E=>({kind:"record",id:E.id}))}),G&&q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let fe={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:y.map(({score:E,...Z})=>Z),modelEntries:b.filter(E=>E.decisionIds.some(Z=>T.has(Z))).map(E=>({id:E.id,key:E.key,value:E.value,decisionIds:E.decisionIds})),evalSpecs:I.filter(E=>E.decisionIds.some(Z=>T.has(Z))).map(E=>({id:E.id,legacyId:E.legacyId,state:E.state,title:E.title,assertionCount:E.assertions.length,decisionIds:E.decisionIds,expansionRef:{kind:"record",id:E.id}})),decisions:_.map(E=>({id:E.id,kind:E.kind,claim:E.claim,subjectIds:E.subjects.map(Z=>Z.subjectId),authority:E.authority,effectiveState:ne.has(E.id)?"conflicted":W.has(E.id)?"excepted":"active",freshness:B.filter(Z=>Z.target.entityId===E.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:E.id}})),conflicts:H,uncertainties:q,implementation:_.map(E=>aa(E.id,d)),verification:_.map(E=>ca(E.id,l,B)),evidence:oe.map(E=>({evidenceId:E.id,summary:E.summary,availability:E.availability,sourceRefs:E.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:he,omittedEvidenceCount:0,conflictsComplete:!Y}};return fe.budget.estimatedTokens=ia(fe),fe},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>jt(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 da=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Et(o){return da.test(o)}function la(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 So(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function je(o,e,n){Et(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 yt(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 pa={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"])},ua=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function ma(o,e,n){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(o,`${n}.participantId`,e.participantId),je(o,`${n}.entity.entityId`,e.entity.entityId),dt(o,`${n}.createdAt`,e.createdAt),yt(o,`${n}.authority`,e.authority);let t=pa[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(ua.has(s)&&(yt(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 fa(o,e,n,t){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(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"&&(yt(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"&&So(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),yt(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&&So(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&So(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ha(o,e,n){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(o,`${n}.participantId`,e.participantId),je(o,`${n}.from.entityId`,e.from.entityId),je(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?yt(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 vt(o){let e=[];je(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),fa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,h)=>{let f=`events[${h}]`;t(p.id,f),ma(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),ha(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}]`),je(e,`artifacts[${h}].id`,p.id)}),o.tombstones.forEach((p,h)=>{let f=`tombstones[${h}]`;t(p.id,f),je(e,`${f}.id`,p.id),je(e,`${f}.objectId`,p.objectId),je(e,`${f}.deletedById`,p.deletedById),dt(e,`${f}.deletedAt`,p.deletedAt),yt(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((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((v,x)=>l("subject",v,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((v,x)=>d(v,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((v,x)=>l("subject",v.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((v,x)=>d(v,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((v,x)=>i(v,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((v,x)=>l("thread",v,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((v,x)=>d(v,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((v,x)=>d(v,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((v,x)=>l("iteration",v,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((v,x)=>d(v,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((v,x)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((v,x)=>{v.subjectIds?.forEach((S,A)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${A}]`))}),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`));break;case"model_projection":yt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((v,x)=>l("model_entry",v,`${f}.entryIds[${x}]`)),p.coverage.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;default:break}});let g=new Map(o.events.map(p=>[p.id,p])),P=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"}`,v=b.get(f)??new Set;v.add(p.toState),b.set(f,v),v.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]]:[])),y=(p,h,f,v,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&&v.length&&!v.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"&&y(p.authority,p.acceptedById,p.createdAt,p.subjects.map(h=>h.subjectId),`records:${p.id}.authority`);o.events.forEach((p,h)=>{let f=P.get(`${p.entity.entityType}:${p.entity.entityId}`),v=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];y(p.authority,p.participantId,p.createdAt,v,`events[${h}].authority`)}),o.relationships.forEach((p,h)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(v=>{let x=P.get(`${v.entityType}:${v.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});y(p.authority,p.participantId,p.createdAt,f,`relationships[${h}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let h=g.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."),P.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.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(v=>v.entity.entityType==="decision"&&v.entity.entityId===p.id&&v.toState==="revoked"&&!!v.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 la(e)}function Xt(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 Mr(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 ga(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 Mn(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."}),Et(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of ga(e))Et(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={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=Mr(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={...Xt(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={...Xt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Mr(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={...Xt(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={...Xt(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 ya}from"crypto";import{readFile as va,readdir as wa,realpath as Ia}from"fs/promises";import{join as Yt,relative as ba}from"path";var xa=["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 Mt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function qe(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Ar(...o){return o.find(e=>!!e?.trim())?.trim()}function ge(o,e,n,t){let s=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),i=ya("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 ko(o,e){try{return JSON.parse(await va(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Sa(o){let e=Mt(o);if(!e)return 0;let n=0,t=r=>{let s=Mt(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 ka(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function wt(o){let e=[],n=await Ia(o.projectRoot).catch(()=>o.projectRoot),t=Yt(n,".popmelt"),r=await ko(Yt(t,"threads.json"),e),s=await ko(Yt(t,"model.json"),e),i=Mt(r),c=Mt(i?.threads)??{},d=Object.entries(c).map(([E,Z])=>({key:E,value:Mt(Z)})).filter(E=>!!E.value),l=Yt(t,"decisions"),g=await wa(l).catch(()=>[]),P=[];for(let E of g.filter(Z=>Z.endsWith(".json")).sort()){let Z=Mt(await ko(Yt(l,E),e));Z&&P.push({file:E,value:Z})}let b=d.flatMap(({value:E})=>[E.createdAt,E.updatedAt]).filter(E=>typeof E=="number"&&Number.isFinite(E)),I=b.length?Math.min(...b):0,y=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=ge(y,"project",y,I),h=ge(y,"participant","legacy-owner",I),f=ge(y,"participant","legacy-agent",I),v=ge(y,"subject","project",I),x=qe(Math.max(I,...b)),S=[],A=[],J=new Map,_=new Map,N=new Map(P.map(E=>[E.value.id??E.file.replace(/^d-|\.json$/g,""),E.value])),T=new Map,B=(E,Z,V,Te,Ae)=>{let be=J.get(V);if(be)return be;let _e=ge(y,"artifact",E,Te);return A.push({id:_e,kind:Z,mediaType:Ae,location:V,availability:"available"}),J.set(V,_e),_e};for(let{file:E,value:Z}of P){let V=Z.id??E.replace(/^d-|\.json$/g,""),Te=Z.createdAt??I,Ae=[B(`${V}:envelope`,"other",`.popmelt/decisions/${E}`,Te,"application/json")];Z.screenshotPath&&Ae.push(B(`${V}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,Te,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[be,_e]of(Z.pastedImagePaths??[]).entries())Ae.push(B(`${V}:image:${be}`,"image",_e,Te));T.set(V,Ae)}let W=(E,Z,V)=>({id:E,schemaVersion:1,projectId:p,createdAt:x,participantId:Z,sourceRefs:V}),te=(E,Z)=>{S.push(Z);let V=_.get(E)??[];V.push(Z.id),_.set(E,V)},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(v,h,[]),recordType:"subject",subjectType:"project",label:ba(process.cwd(),n)||n,aliases:[],locators:[{id:ge(y,"locator",n,I),kind:"project_root",value:n,status:"current",validFrom:qe(I),sourceRefs:[]}]});let ne=new Map,oe=(E,Z)=>{let V=ne.get(E);if(V)return V;let Te=ge(y,"subject",E,Z),Ae={...W(Te,h,[{kind:"external",id:E}]),createdAt:qe(Z),recordType:"subject",subjectType:"element",label:E,aliases:[],locators:[{id:ge(y,"locator",E,Z),kind:"dom_selector",value:E,status:"current",validFrom:qe(Z),sourceRefs:[{kind:"external",id:E}]}]};return S.push(Ae),ne.set(E,Te),Te};for(let{key:E,value:Z}of d){let V=Z.id??E,Te=Z.createdAt??I,Ae=ge(y,"thread",V,Te),be={kind:"thread",id:V},_e=[],Ne=[],Bt=Array.isArray(Z.messages)?Z.messages:[],Ue,rt,Ft=0;Bt.forEach((we,st)=>{let $e=we.timestamp??Te,Ze=ge(y,"artifact",`${V}:message:${st}`,$e);if(_e.push(Ze),A.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${V}/messages/${st}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${V}/messages/${st}`,Ze),we.screenshotPath&&B(`${V}:message:${st}:screenshot`,"screenshot",we.screenshotPath,$e),we.role==="human"){Ue=we;let Be=we.feedbackSummary??we.replyToQuestion;if(Be?.trim()){let Fe=ge(y,"observation",`${V}:${st}`,$e),ct=Z.elementIdentifiers??[],kt={...W(Fe,h,[be,{kind:"message",id:Ze}]),createdAt:qe($e),recordType:"observation",state:"open",statement:Be,captureContext:{subjectIds:ct.map(mt=>oe(mt,Te)),artifactIds:[Ze]},resolvedByIds:[]};te(V,kt),rt=Fe,Ne.push({entityType:"observation",entityId:Fe})}return}if(we.role!=="assistant")return;let it=we.jobId??`${V}:${st}`,at=ge(y,"iteration",it,$e),ut=N.get(it),Lt=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",to={...W(at,f,[be,{kind:"message",id:Ze},...(T.get(it)??[]).map(Be=>({kind:"artifact",id:Be}))]),createdAt:qe($e),recordType:"iteration",threadIds:[Ae],startedAt:qe(Ue?.timestamp,$e),completedAt:qe($e),requestSummary:Ar(Ue?.feedbackSummary,Ue?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:Lt,execution:{provider:we.provider??ut?.provider,model:we.model??ut?.model,sessionId:we.sessionId??ut?.sessionId},artifactIds:[Ze,...T.get(it)??[]]};te(V,to),Ne.push({entityType:"iteration",entityId:at});let zt=we.resolutions??ut?.resolutions??[];for(let[Be,Fe]of zt.entries()){if(Fe.status!=="resolved"||!Fe.summary?.trim())continue;let ct=Z.elementIdentifiers??[],kt=(ct.length?ct:[n]).map(pn=>({subjectId:pn===n?v:oe(pn,Te),role:"governed"})),mt=ge(y,"proposal",`${it}:${Fe.annotationId??"resolution"}:${Be}`,$e),no={...W(mt,f,[be,{kind:"iteration",id:at}]),createdAt:qe($e),recordType:"proposal",state:"pending",claim:Fe.summary,subjects:kt,subjectSemantics:kt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Ar(Ue?.feedbackSummary,Ue?.replyToQuestion,Fe.summary),iterationId:at,inferredById:f}};te(V,no),Ne.push({entityType:"proposal",entityId:mt}),e.push({severity:"warning",code:"acceptance_unresolved",source:V,message:`Proposal ${mt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(zt.some(Be=>Be.status==="resolved")||ut?.gitDiff){let Be=ge(y,"implementation",it,$e),Fe={...W(Be,f,[be,{kind:"iteration",id:at}]),createdAt:qe($e),recordType:"implementation_attempt",state:"completed",iterationIds:[at],coverageClaims:[],summary:zt.map(ct=>ct.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};te(V,Fe),Ne.push({entityType:"implementation_attempt",entityId:Be}),Ft+=1}rt&&(rt=void 0)});let St=Bt.at(-1),eo={...W(Ae,h,[be]),createdAt:qe(Te),recordType:"thread",state:St?.question?"open":"resolved",messageArtifactIds:_e,outcome:St?.question?"question_unresolved":Ft?"implementation_only":"no_outcome",resultRefs:Ne};S.push(eo),_.set(V,[Ae,..._.get(V)??[]])}let he=Sa(s);he&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${he} model values were not promoted because their accepted decision provenance is unresolved.`});let Y={manifest:{formatVersion:1,projectId:p,createdAt:qe(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=vt(Y),fe=(o.proofCaseIds??xa).map(E=>({legacyId:E,threadFound:d.some(({key:Z,value:V})=>(V.id??Z)===E),decisionEnvelopeFound:N.has(E),recordIds:_.get(E)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((E,Z)=>E+(Z.value.messages?.length??0),0),decisionEnvelopes:P.length,modelEntries:he,artifactsReferenced:A.length},imported:ka(S),unresolvedAcceptance:e.filter(E=>E.code==="acceptance_unresolved").length,deferredModelEntries:he,proofCases:fe,issues:e,schemaIssues:G.issues}}}import{createHash as Ra}from"crypto";import{mkdir as _r,open as Ro,readFile as Po,readdir as Pa,rename as Ta,unlink as To}from"fs/promises";import{join as nt}from"path";var ja={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function _n(o){return Ra("sha256").update(JSON.stringify(o)).digest("hex")}function $r(o){return _n(o)}function Cr(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 Ea(o,e,n){return Cr(structuredClone(o),e,n)}async function It(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ro(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Ta(n,o)}catch(r){throw await To(n).catch(()=>{}),r}}async function An(o){return JSON.parse(await Po(o,"utf8"))}var $n=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=vt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await _r(this.journalDir,{recursive:!0});try{throw await Po(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 Po(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=_n(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=_n(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(!Et(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:$r(s)},c=Ea(t.bundle,e,n.committedAt),d=vt(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({...ja,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await An(this.manifestPath),n=await An(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!==_n(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Pa(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,g=new Set;for(let b of i){let I=await An(nt(this.journalDir,b)),{hash:y,...p}=I;if(y!==$r(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(g.has(I.transactionId))throw new Error(`Duplicate transaction ID: ${I.transactionId}`);Cr(c,I.mutation,I.committedAt),d=I.sequence,l=I.hash,g.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 P=vt(c);if(!P.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(P.issues)}`);return{bundle:c,manifest:e,transactionIds:g,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 _r(this.memoryDir,{recursive:!0});let n;try{n=await Ro(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await An(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 To(this.lockPath),n=await Ro(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await To(this.lockPath).catch(()=>{})}}};import{randomBytes as Ma}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Ma(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 Aa=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Or(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=Aa(),l=d.records,g=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));g||(g={id:ge(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(g));let P=[];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:ge(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:ge(r,"live-locator",x,e.createdAt),kind:"dom_selector",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),P.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:ge(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:ge(r,"live-file-locator",x,e.createdAt),kind:"source_file",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),P.push(S)}let b=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),I;if(b.length>0){I=ge(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:P.map(S=>S.id),artifactIds:[]},resolvedByIds:[]};l.push(x)}let y=ge(r,"live-iteration",s,e.completedAt),p={id:y,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:[g.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()),v=P.length>0?P:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(b.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of b.entries()){let A=ge(r,"live-proposal",`${s}:${x}`,e.completedAt),J=v.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:y},{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:y,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:ge(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:y}],recordType:"implementation_attempt",state:"completed",iterationIds:[y],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:y}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:d,iterationId:y,proposalIds:h,observationId:I}}import{createHash as _a}from"crypto";import{mkdir as $a,open as Ca,readFile as Oa,rename as Da,unlink as Ja}from"fs/promises";import{join as Dr}from"path";function Jr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Nr(o){return _a("sha256").update(JSON.stringify(o)).digest("hex")}async function Na(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ca(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
179
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Da(n,o)}catch(r){throw await Ja(n).catch(()=>{}),r}}function Ba(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(d,l,g)=>{let P=d[l]??=[];P.includes(g)||P.push(g)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let g of[l.label,...l.aliases,...l.locators.filter(P=>P.status==="current").map(P=>P.value)]){let P=Jr(g);P&&i(t,P,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:Nr(c)}}function Br(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Jr(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 Cn=class{constructor(e){this.indexDir=Dr(e,".popmelt","memory","indexes"),this.indexPath=Dr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Oa(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===Nr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ba(e,n);return await $a(this.indexDir,{recursive:!0}),await Na(this.indexPath,t),t}};var On=class{constructor(e){this.projectRoot=e;this.store=new $n(e),this.indexStore=new Cn(e),this.manifestPath=lt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await At(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 wt({...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 wt({...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 At(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await At(lt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await At(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 jo(e,{recursive:!0}),await Eo(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 At(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await At(lt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await jo(e,{recursive:!0}),await Eo(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 jo(e,{recursive:!0}),await Eo(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:Qt(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Er(t.bundle,r),reviewSelection:Qt(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Mn(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 wt({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=Mn(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=Mn(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let g=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(g);let P=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:P,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:g.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=Or(n.bundle,e),r=ge(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=[],g=[];for(let b of e.summary.changes){let I={kind:"external",id:b.explanationId,uri:"popmelt:imprint"},y=n.bundle.records.find(h=>h.recordType==="observation"&&h.sourceRefs.some(f=>f.kind==="external"&&f.id===b.explanationId&&f.uri==="popmelt:imprint"));y||(y={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(y));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),g.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:y.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 P=ge(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,d);try{let b=await this.store.commit({records:l,events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:P,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(g=>g.entityType==="decision"&&g.entityId===c.id)).sort((l,g)=>g.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),g=le(s),P=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)),y={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={...y,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...y,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."},v={...y,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={...y,id:g,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...y,id:P,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:[g],coverage:[{decisionId:l,status:"projected"}]},A={...y,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=I.map(T=>({...y,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=>({...y,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.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,v,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:g}}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(y=>y.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===y.id||y.sourceRefs.some(h=>h.id===p))?[y.id]:[]),i=[...new Set(n.bundle.records.flatMap(y=>y.recordType==="decision"&&s.includes(y.id)?y.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(y=>y.recordType==="participant"&&y.kind==="human"&&y.status==="active");if(!l)throw new Error("No active local owner participant is available.");let g=Date.now(),P=new Date(g).toISOString(),b={id:le(g),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:P,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(y=>({kind:"record",id:y}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:s.map(y=>({entityType:"decision",entityId:y})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},I=r?[{id:le(g),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:P,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(g),committedAt:P})}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(g=>g.evalSpecId===i.id).sort((g,P)=>P.createdAt.localeCompare(g.createdAt))[0],d=c&&s.some(g=>g.target.entityType==="verification_attempt"&&g.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}},g=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})),P=await this.store.commit({records:[d,l],events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});await this.refreshIndex(P)}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(g=>({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:g.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(y=>y.recordType==="model_projection"&&y.state==="applied"&&y.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(y=>y.recordType==="decision"&&e.decisionIds.includes(y.id)&&y.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(y=>y.recordType==="participant"&&y.kind==="human"&&y.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(y=>{let p=y.decisionIds?.filter(v=>e.decisionIds.includes(v)),h=p?.length?p:e.decisionIds,f=[...new Set(r.filter(v=>h.includes(v.id)).flatMap(v=>v.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:h.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:y.path.map(String).join("."),subjectIds:f,decisionIds:h,value:y.value}}),g=new Set(l.flatMap(y=>y.decisionIds)),P={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:e.decisionIds.map(y=>({kind:"record",id:y})),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(y=>y.id),coverage:e.decisionIds.map(y=>e.coverage?.find(p=>p.decisionId===y)??{decisionId:y,status:g.has(y)?"projected":"unprojected"})},b=l.flatMap(y=>y.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:P.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:y.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,P],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});return await this.refreshIndex(I),{projectionId:d,entryIds:l.map(y=>y.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 wt({...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=Br(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 ke(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function _t(o,e,n){let t=ke(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Mo(o){let e=$t(o),n=$t(e.authority),t=n.level,r=n.mode,s=_t(t,"authority.level",["owner","delegate","contributor"]),i=_t(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:ke(e.proposalId,"proposalId"),participantId:ke(e.participantId,"participantId"),occurredAt:ke(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:ke(e.eventId,"eventId"),decisionId:ke(e.decisionId,"decisionId"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:ke(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:ke(e.eventId,"eventId"),reason:ke(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:ke(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=>ke(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>_t(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:ke(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:ke(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:ke(e.acceptanceEventId,"acceptanceEventId"),decisionId:ke(e.decisionId,"decisionId"),relationshipId:ke(e.relationshipId,"relationshipId"),claim:ke(e.claim,"claim"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=$t(d);return{subjectId:ke(l.subjectId,"subjectId"),role:_t(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:ke(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Ao(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=>ke(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 Dn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
180
+ `)}async function Fr(o,e,n,t){let r=Dn(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 Lr(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(`
181
+ `)}function zr(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 qr(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 Jn(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 Fa(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),c,d,l,g,P,b,I,y,p,h,f,v,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 te=r.indexOf(`\r
375
182
  \r
376
- `,N);if(C===-1)break;let T=o.slice(N,C).toString("utf-8"),L=C+4,_=o.indexOf(i,L),ee=_!==-1?_-2:o.length;A.push({headers:T,body:o.slice(L,ee)}),D=_!==-1?_:o.length}for(let k of A){let R=k.headers.match(/name="([^"]+)"/);if(!R)continue;let N=R[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 C=N.slice(11);try{let T=decodeURIComponent(C);Z.push({pathname:T,data:k.body})}catch{}}else if(N.startsWith("image-")){let C=N.split("-"),T=parseInt(C[C.length-1],10),L=C.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 Wo(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 Be(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(`
377
- ### ${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(`
378
- `)}function An(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=Be(E,n?.imagePaths);B&&(t.push(""),t.push(B))}}else{let a=Be(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(`
379
- `)}function $n(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(`
380
- `)}function Go(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 Ho(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&&!Go(e[n]))return!1;return!0}function Cn(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(Ho):[]}catch{return[]}}function _n(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 qo}from"child_process";import{readdir as Qo,readFile as Xo,stat as Yo}from"fs/promises";import{homedir as Fe}from"os";import{join as xe}from"path";var dt=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Dn()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Dn()}],je=[{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"}],Le={id:"",label:"Default",source:"cli"},Vo=/^\s*-\s+"([^"]+)"/;function Ko(s){let e=[],n=!1;for(let t of s.split(`
381
- `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(Vo);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:_t(i),source:"cli"})}return ut([Le,...e])}function Zo(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 Dn(){return["low","medium","high","xhigh","max"].map(s=>({effort:s}))}function er(s){let e=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return ut(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":or(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 On(s="copilot"){let e=await ct(s,["help","config"]),n=Ko(e);return n.length>1?n:[Le]}async function Nn(s="codex"){let e=await ct(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||xe(Fe(),".codex");return zn(xe(t,"models_cache.json"))}),n=Zo(e);return n.length>0?ut([...n,...je]):je}async function Jn(s="claude"){let e=xe(Fe(),".claude"),n=[xe(Fe(),".claude","stats-cache.json"),xe(Fe(),".claude","settings.json"),xe(Fe(),".claude.json"),xe(e,"cache","changelog.md")],[t,o,i]=await Promise.all([ct(s,["--help"]).catch(()=>""),ct(s,["--version"]).catch(()=>""),tr(e).catch(()=>[])]),a=sr([...n,...i]),l=await Promise.all(a.map(v=>zn(v).catch(()=>""))),f=er([t,o,...l].join(`
382
- `));return ut([...dt,...f])}function ct(s,e,n=5e3){return new Promise((t,o)=>{qo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function zn(s){return Xo(s,"utf-8")}async function tr(s){let e=[xe(s,"projects"),xe(s,"telemetry")],n=[];for(let t of e)await Bn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Bn(s,e,n){if(n<0)return;let t;try{t=await Qo(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=xe(s,o.name);if(o.isDirectory()){await Bn(i,e,n-1);return}if(!(!o.isFile()||!nr(o.name)))try{let a=await Yo(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function nr(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function ut(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 sr(s){return[...new Set(s)]}function or(s){return s.charAt(0).toUpperCase()+s.slice(1)}var pt=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 rr,readFile as ir,writeFile as ar}from"fs/promises";import{dirname as lr,join as cr}from"path";var dr={version:1,threads:{}},ft=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=cr(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await ir(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={...dr,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 rr(lr(this.filePath),{recursive:!0}),await ar(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function Fn(s){return pr(s).slice(0,12)}var ur=[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 pr(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):fr(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=be(E[z-15],7)^be(E[z-15],18)^E[z-15]>>>3,D=be(E[z-2],17)^be(E[z-2],19)^E[z-2]>>>10;E[z]=E[z-16]+Z+E[z-7]+D>>>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=be(q,6)^be(q,11)^be(q,25),D=q&V^~q&Q,A=K+Z+D+ur[z]+E[z]>>>0,k=be(J,2)^be(J,13)^be(J,22),R=J&U^J&W^U&W,N=k+R>>>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 be(s,e){return s>>>e|s<<32-e}function fr(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 jn={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 Ln=jn.version;var kr=1111,Rr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Mr=1800*1e3,Er=3600*1e3,Gn=45e3,Tr=5e3,Ar=1e4;function Hn(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(`
383
- `)}function Yn(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 $r(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(`
384
- `)[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 Cr(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(`
385
- `)}function _r(s,e=96){let n=s.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function qn(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=>_r(a)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Dr(s,e){let n=s.headers.origin;Yn(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 Or(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 Nr(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 mt(s,e){try{s.res.write(`event: ${e.type}
183
+ `,W);if(te===-1)break;let H=r.slice(W,te).toString("utf-8"),ne=te+4,oe=r.indexOf(s,ne),he=oe!==-1?oe-2:r.length;N.push({headers:H,body:r.slice(ne,he)}),_=oe!==-1?oe: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")g=T.body.toString("utf-8");else if(W==="model")P=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")y=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")v=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 te=W.slice(11);try{let H=decodeURIComponent(te);J.push({pathname:H,data:T.body})}catch{}}else if(W.startsWith("image-")){let te=W.split("-"),H=parseInt(te[te.length-1],10),ne=te.slice(1,-1).join("-");ne&&!isNaN(H)&&A.push({annotationId:ne,index:H,data:T.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:g,model:P,reasoningEffort:b,serviceTier:I,goal:y,pageUrl:p,viewport:h,planId:f,manifest:v,tasks:x,sourceId:S,pastedImages:A,pageScreenshots:J}}function Fa(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 La}from"crypto";var za=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,qa=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Ua=new Set(["strengthened","weakened","mixed","unknown"]);function Zt(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 Wa(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Ur(o,e,n,t=Date.now()){let r=Wa(o);if(!r)return null;let s=typeof r.transition=="string"&&qa.has(r.transition)?r.transition:null,i=Zt(r.focus);if(!s||!i)return null;let c=typeof r.evidencePosture=="string"&&Ua.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:La(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Zt(r.seeking),workingHypothesis:Zt(r.workingHypothesis),evidencePosture:c,update:Zt(r.update),nextObservation:Zt(r.nextObservation)},contextPolicy:"exclude"}}function _o(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Ha(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(za,(c,d)=>{try{let l=Ur(JSON.parse(d),e,s);if(!l)return"";let g=_o(l);if(r.has(g))return"";r.add(g),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
184
+
185
+ `).trim(),orientations:t}}function Ga(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 Nn=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=Ga(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=Ur(JSON.parse(i),this.jobId,this.sequence);if(!c)continue;let d=_o(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=Ha(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=_o(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Wr=`## Public orientation updates
186
+ During meaningful transitions in the work, emit a brief public coordination update using this exact form:
187
+ <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>
188
+
189
+ Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
190
+ Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
191
+
192
+ 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 en(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(`
193
+ ### ${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(`
194
+ `)}function Hr(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,g=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${g} \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 g=new Map;for(let P of i)if(typeof P=="object"&&P!==null&&"text"in P){let b=P,I=b.scope||"general";g.has(I)||g.set(I,[]),g.get(I).push(b.text)}for(let[P,b]of g){t.push(`**${P.charAt(0).toUpperCase()+P.slice(1)}**`);for(let I of b)t.push(`- ${I}`)}}else for(let g of i)typeof g=="string"&&t.push(`- ${g}`);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 g=i[d];g&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${g}`):!g&&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 P={...e,annotations:l,styleModifications:e.styleModifications},b=en(P,n?.imagePaths);b&&(t.push(""),t.push(b))}}else{let i=en(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(`
195
+ `)}function Gr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Vr(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(`
196
+ `)}function Va(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 Ka(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&&!Va(e[n]))return!1;return!0}function Kr(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(Ka):[]}catch{return[]}}function Qr(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 Qa}from"child_process";import{readdir as Xa,readFile as Ya,stat as Za}from"fs/promises";import{homedir as tn}from"os";import{join as Xe}from"path";var Fn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Xr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Xr()}],nn=[{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"}],on={id:"",label:"Default",source:"cli"},ec=/^\s*-\s+"([^"]+)"/;function tc(o){let e=[],n=!1;for(let t of o.split(`
197
+ `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(ec);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:$o(s),source:"cli"})}return Ln([on,...e])}function nc(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 Xr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function oc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ln(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":ac(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 Yr(o="copilot"){let e=await Bn(o,["help","config"]),n=tc(e);return n.length>1?n:[on]}async function Zr(o="codex"){let e=await Bn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Xe(tn(),".codex");return ts(Xe(t,"models_cache.json"))}),n=nc(e);return n.length>0?Ln([...n,...nn]):nn}async function es(o="claude"){let e=Xe(tn(),".claude"),n=[Xe(tn(),".claude","stats-cache.json"),Xe(tn(),".claude","settings.json"),Xe(tn(),".claude.json"),Xe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Bn(o,["--help"]).catch(()=>""),Bn(o,["--version"]).catch(()=>""),rc(e).catch(()=>[])]),i=ic([...n,...s]),c=await Promise.all(i.map(l=>ts(l).catch(()=>""))),d=oc([t,r,...c].join(`
198
+ `));return Ln([...Fn,...d])}function Bn(o,e,n=5e3){return new Promise((t,r)=>{Qa(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function ts(o){return Ya(o,"utf-8")}async function rc(o){let e=[Xe(o,"projects"),Xe(o,"telemetry")],n=[];for(let t of e)await ns(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function ns(o,e,n){if(n<0)return;let t;try{t=await Xa(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Xe(o,r.name);if(r.isDirectory()){await ns(s,e,n-1);return}if(!(!r.isFile()||!sc(r.name)))try{let i=await Za(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function sc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Ln(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 ic(o){return[...new Set(o)]}function ac(o){return o.charAt(0).toUpperCase()+o.slice(1)}var zn=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 Ge}from"crypto";import{createHash as cc}from"crypto";import{mkdir as dc,open as lc,readFile as os,readdir as pc,rename as uc,unlink as mc}from"fs/promises";import{dirname as fc,join as Ct}from"path";function De(o){return structuredClone(o)}function rs(o){return cc("sha256").update(JSON.stringify(o)).digest("hex")}async function rn(o,e){await dc(fc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await lc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
199
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await uc(n,o)}catch(r){throw await mc(n).catch(()=>{}),r}}function hc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function gc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=De(e):o.explanations.push(De(e))}function Co(o,e){let n=De(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(De(t.explanation))}else if(t.op==="replace_explanation")gc(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(De(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(De(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,De(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(De(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function yc(o,e){let n=[],t=De(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:De(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:De(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:De(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:De(s)})}t=Co(t,[r])}return n}function ss(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 qn=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 os(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 pc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=hc(this.projectId,e.createdAt),s=[],i=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await os(Ct(this.journalDir,t[c]),"utf8")),{hash:l,...g}=d;if(d.sequence!==c+1||d.previousHash!==i||l!==rs(g))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(P=>P.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=yc(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:De(e.mutations),inverseMutations:s,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...i,hash:rs(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 rn(Ct(this.journalDir,l),c);let g={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await rn(this.graphPath,d),await rn(this.manifestPath,g),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(ss));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(g=>ss(g).some(P=>c.has(P)))))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 rn(this.graphPath,e.graph),await rn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var vc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),wc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Ic(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Un(o){return new Set(Ic(o).split(" ").filter(e=>e.length>2&&!wc.has(e)))}function Wn(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 Oo(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:Ge(),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 is(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 bc(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 Do(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(!vc.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 y=Ee(I.statement),p=Ee(I.rationale);if(!y||!p)continue;l.push({op:"add",clientId:Ee(I.clientId,100)||void 0,kind:I.kind,statement:y,rationale:p,scope:is(I.scope)})}else if(I.op==="revise"&&typeof I.explanationId=="string"){let y={op:"revise",explanationId:I.explanationId,statement:Ee(I.statement)||void 0,rationale:Ee(I.rationale)||void 0,scope:is(I.scope),reopenGrounding:I.reopenGrounding===!0};(y.statement||y.rationale||y.scope||y.reopenGrounding)&&l.push(y)}else if(I.op==="evidence"&&typeof I.explanationId=="string"&&["supports","challenges","excepts"].includes(String(I.stance))){let y=Ee(I.summary);y&&l.push({op:"evidence",explanationId:I.explanationId,stance:I.stance,summary:y})}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 y=Ee(I.reason);y&&l.push({op:"supersede",explanationId:I.explanationId,replacementId:I.replacementId,reason:y})}else if(I.op==="bind_concrete"&&typeof I.explanationId=="string"){let y=Ee(I.modelPath,300);y&&l.push({op:"bind_concrete",explanationId:I.explanationId,modelPath:y,rationale:Ee(I.rationale)})}else I.op==="retire"&&typeof I.explanationId=="string"&&l.push({op:"retire",explanationId:I.explanationId,reason:Ee(I.reason)})}let g=r.grounding,P=g&&typeof g.explanationId=="string"&&Ee(g.question)?{explanationId:g.explanationId,question:Ee(g.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:P},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Jo(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(`
200
+ `)),...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(`
201
+ `)}var sn=class{constructor(e,n){this.noopCounts=new Map;this.store=new qn(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=Un(e.text??""),t=Un((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=Un([d.statement,d.rationale].join(" ")),g=Un(d.scope.values.join(" ")),P=Wn(l,n),b=Wn(g,n),I=Wn(g,t),y=Wn(l,t),p=P+b*.2+I*.25+y*.1+(d.state==="grounded"?.08:0)+(r.has(d.id)?1:0),h=r.has(d.id)||(n.size?P>=.12||b>=.5:I>=.2||y>=.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(g=>g.fromId===d.id&&g.type==="instantiates").map(g=>g.toId));return{id:d.id,kind:d.kind,statement:d.statement,rationale:d.rationale,scope:d.scope,state:d.state,concrete:s.concrete.filter(g=>l.has(g.id)).map(g=>({id:g.id,modelPath:g.modelPath,value:g.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,g=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=Ge();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:Oo(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 P=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let A=P(S.explanationId),J=s.get(A);if(J?.state!=="grounded")continue;let _=Ge(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?Oo(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:Ge(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let b=S=>{let A=P(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 _=bc(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:Ge(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:N})),d.push({op:"add_relation",relation:{id:Ge(),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:Ge(),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:Ge(),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(P(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:Oo(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"||g.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=Ge(),y=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(y.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,v=f?p.get(f):void 0,x=v?.state==="testing"&&!g.has(v.id)?{explanationId:v.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 g of l)await this.store.undo(g,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,Ge());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(g=>g.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:Ge(),committedAt:n,source:i,summary:d,mutations:c})}};function as(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Hn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function No(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 cs(o){let e=No(Hn(o.origin));if(e)return e;let n=No(Hn(o.referer));if(n)return n;let t=Hn(o["x-forwarded-host"]);if(!t)return null;let r=Hn(o["x-forwarded-proto"])==="https"?"https":"http";return No(`${r}://${t}`)}function ds(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 Gn}from"crypto";import{mkdir as an,readFile as bt,unlink as kc,writeFile as Dt}from"fs/promises";import{dirname as Vn,extname as Rc,join as Je}from"path";var xc={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 Sc(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 ls(o,e){let n=e??Sc(o);return{kind:n,...xc[n]}}function Ot(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ps(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 Pc={version:1,threads:{}},us=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],cn={version:2,updatedAt:0,files:{}};function Tc(o){return JSON.stringify(o,null,2)}function jc(o){return Object.fromEntries(us.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Ec(o){let e={...o};for(let n of us)delete e[n];return e}function Jt(o){let e=o;if(o.error){let n=ls(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=Ot(e.result,!1),t=Ot(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 Kn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Je(e,".popmelt");this.legacyFilePath=Je(n,"threads.json"),this.threadsDir=Je(n,"threads"),this.indexPath=Je(this.threadsDir,"index.json"),this.artifactsDir=Je(n,"artifacts","thread-messages"),this.mediaDir=Je(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(Je(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(Jt)}]))},this.index={...cn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Pc,threads:{}},this.index={...cn,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(Jt(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,Jt(n)):r.messages.push(Jt(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=Jt(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)),g=r.messages.findLastIndex(h=>h.role==="human"),P=l>g?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,I=Array.from(new Set(r.messages.slice(0,Math.max(0,g)).filter(h=>h.role==="assistant"&&!!h.jobId).map(h=>h.jobId))),y=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:y,hasError:p,lastMessageRole:b,pendingQuestion:P,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(Je(Vn(this.legacyFilePath),r.path),"utf8");Gn("sha256").update(c).digest("hex")===r.sha256&&(i=JSON.parse(c))}catch{}return Jt({...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=jc(e),t=Ec(e);if(Object.keys(n).length===0)return t;let r=Tc(n),s=Gn("sha256").update(r).digest("hex"),i=Je("artifacts","thread-messages",`${s}.json`);await an(this.artifactsDir,{recursive:!0});try{await bt(Je(Vn(this.legacyFilePath),i),"utf8")}catch{await Dt(Je(Vn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Vn(t)===this.mediaDir)return t;try{let r=await bt(t),s=Gn("sha256").update(r).digest("hex"),i=Je(this.mediaDir,`${s}${Rc(t)||".bin"}`);await an(this.mediaDir,{recursive:!0});try{await bt(i)}catch{await Dt(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 an(this.threadsDir,{recursive:!0});let n=this.index??{...cn,files:{}},t=n.files[e.id]??`${Gn("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 Dt(Je(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Dt(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 an(this.threadsDir,{recursive:!0}),this.index=this.index??{...cn,files:{}},await Dt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...cn,files:{}},t=n.files[e];t&&await kc(Je(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await an(this.threadsDir,{recursive:!0}),await Dt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};function ms(o){return Ac(o).slice(0,12)}var Mc=[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 Ac(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):_c(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,g=1541459225,P=new Array(64);for(let b=0;b<e.length;b+=64){for(let A=0;A<16;A++){let J=b+A*4;P[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=Ye(P[A-15],7)^Ye(P[A-15],18)^P[A-15]>>>3,_=Ye(P[A-2],17)^Ye(P[A-2],19)^P[A-2]>>>10;P[A]=P[A-16]+J+P[A-7]+_>>>0}let I=t,y=r,p=s,h=i,f=c,v=d,x=l,S=g;for(let A=0;A<64;A++){let J=Ye(f,6)^Ye(f,11)^Ye(f,25),_=f&v^~f&x,N=S+J+_+Mc[A]+P[A]>>>0,T=Ye(I,2)^Ye(I,13)^Ye(I,22),B=I&y^I&p^y&p,W=T+B>>>0;S=x,x=v,v=f,f=h+N>>>0,h=p,p=y,y=I,I=N+W>>>0}t=t+I>>>0,r=r+y>>>0,s=s+p>>>0,i=i+h>>>0,c=c+f>>>0,d=d+v>>>0,l=l+x>>>0,g=g+S>>>0}return[t,r,s,i,c,d,l,g].map(b=>b.toString(16).padStart(8,"0")).join("")}function Ye(o,e){return o>>>e|o<<32-e}function _c(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 fs={name:"@popmelt.com/core",version:"0.8.5",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 dn=fs.version;var qc=1111,Uc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Wc=1800*1e3,Hc=3600*1e3,ys=45e3,Gc=5e3,Vc=1e4;function vs(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 Xn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function Kc(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 Qc(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,g=s?Fo(s)?s:ks(e,s):void 0,P=n[n.length-1];P&&P.kind==="tool_group"&&P.tool===r?P.items.push({label:d,detail:l,...g?{filePath:g}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...g?{filePath:g}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function Xc(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 Yc(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function ws(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=>Yc(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function Zc(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 M(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function Ve(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 ed(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function td(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 Yn(o,e){try{o.res.write(`event: ${e.type}
386
205
  data: ${JSON.stringify(e)}
387
206
 
388
- `)}catch{}}function We(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function zr(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 Br(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 Qn(s){try{let e=gt("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=gt("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=gt("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return mr("sha256").update(`${e}
207
+ `)}catch{}}function xt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function nd(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 od(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 Is(o){try{let e=Zn("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=Zn("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=Zn("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Ss("sha256").update(`${e}
389
208
  ${t}
390
- ${o}`).digest("hex").slice(0,16)}catch{return}}async function Dt(s={}){let e=s.port??kr,n=s.projectRoot??process.cwd(),t=await vr(n).catch(()=>n),o=Fn(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??ve(br(),"popmelt-bridge"),l=s.maxTurns??40,f=s.maxBudgetUsd??1,v=[...s.allowedTools??Rr],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:gt("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=Un(c,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=g=>{h||(h=!0,u(g))},I=setTimeout(()=>{p.kill("SIGTERM"),d(!0)},5e3);p.on("error",()=>{clearTimeout(I),d(!1)}),p.on("close",g=>{clearTimeout(I),d(g===0)})})}await Promise.all([(async()=>{w.claude&&(w.claude.models=w.claude.available&&w.claude.path?await Jn(w.claude.path).catch(()=>dt):dt)})(),(async()=>{w.codex&&(w.codex.models=w.codex.available&&w.codex.path?await Nn(w.codex.path).catch(()=>je):je)})(),(async()=>{w.copilot&&(w.copilot.models=w.copilot.available&&w.copilot.path?await On(w.copilot.path).catch(()=>[Le]):[Le])})()]);let[Q,K,z]=await Promise.all([Mt(t),Et(t),Tt(t,w.copilot?.path??E)]),Z=await xn(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 gr(a,{recursive:!0}),Xn(a).catch(()=>{});let D=new pt(1),A=new ot,k=new at(Gn),R=null,N=0,C=!1,T=()=>{N+=1,C=!1,R&&clearTimeout(R),R=null},L=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},_=()=>{if(U!=="detached"||k.size>0||C)return;C=!0;let r=++N,c=Date.now()+Ar,u=()=>{if(r!==N)return;if(k.size>0){T();return}if(!(D.isRunning||D.depth>0||A.isRunning||A.depth>0)||Date.now()>=c){C=!1,R=setTimeout(L,50),R.unref?.();return}R=setTimeout(u,250),R.unref?.()};u()},ee=new Set,y=new ft(t),le=new Ke(t),ie=new Ze(t),H=new nt(t,le,{claudePath:x,provider:B,timeoutMs:J,onEvent:r=>{for(let c of ee)mt(c,r)}}),Vn=20,Kn=300*1e3,we=[];function Ge(){let r=Date.now()-Kn;for(;we.length>0&&(we[0].completedAt<r||we.length>Vn);)we.shift()}let Se=new Map,He=null,Ot;D.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&mt(p,r)}),A.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&mt(p,r)}),A.setProcessor(async r=>{let c=r.provider??B;try{let u=await H.run({provider:c,model:r.model,threadId:r.threadId,agentSettings:r.agentSettings});if(r.status==="cancelled")return;let p=await H.loadRuns(),h=u.runId?p.runs.find(I=>I.id===u.runId):void 0,d=Cr(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),we.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),Ge();else{if(r.status="error",r.error=u.error??"Materialization failed",r.threadId){let I=`Model materialization failed.
209
+ ${r}`).digest("hex").slice(0,16)}catch{return}}function rd(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 bs(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,rd(n,s.value)]);else if(s.kind==="source_file"){let i=ks(o,s.value),d=i===o||i.startsWith(`${o}/`)?await Bo(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,d])}else r.push([s.kind,s.value]);return Ss("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Lo(o={}){let e=new Date().toISOString(),n=o.port??qc,t=o.projectRoot??process.cwd(),r=await Dc(t).catch(()=>t),s=ms(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Me(Fc(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,g=[...o.allowedTools??Uc],P=o.claudePath??"claude",b=o.copilotPath??"copilot",I=o.provider??"claude",y=o.timeoutMs,p=o.restartMode??"embedded",h=n,f={},v={claude:P,codex:"codex",copilot:b};for(let[a,u]of Object.entries(v))try{let R=u.includes("/")?u:Zn("which",[u],{encoding:"utf-8"}).trim();f[a]={available:!0,path:R}}catch{f[a]={available:!1,path:null}}function x(a,u){return new Promise(R=>{let m=hs(u,["--version"],{stdio:["ignore","ignore","ignore"]}),k=!1,w=C=>{k||(k=!0,R(C))},j=setTimeout(()=>{m.kill("SIGTERM"),w(!0)},5e3);m.on("error",()=>{clearTimeout(j),w(!1)}),m.on("close",C=>{clearTimeout(j),w(C===0)})})}await Promise.all([(async()=>{f.claude&&(f.claude.models=f.claude.available&&f.claude.path?await es(f.claude.path).catch(()=>Fn):Fn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await Zr(f.codex.path).catch(()=>nn):nn)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await Yr(f.copilot.path).catch(()=>[on]):[on])})()]);let[S,A,J]=await Promise.all([go(r),yo(r),vo(r,f.copilot?.path??b)]),_=await vr(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=A),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&g.push(`mcp__${S.name}__*`),await Cc(c,{recursive:!0}),xs(c).catch(()=>{});let N=new zn(1),T=new kn,B=new Tn(ys),W=null,te=0,H=!1,ne=()=>{te+=1,H=!1,W&&clearTimeout(W),W=null},oe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},he=()=>{if(p!=="detached"||B.size>0||H)return;H=!0;let a=++te,u=Date.now()+Vc,R=()=>{if(a!==te)return;if(B.size>0){ne();return}if(!(N.isRunning||N.depth>0||T.isRunning||T.depth>0)||Date.now()>=u){H=!1,W=setTimeout(oe,50),W.unref?.();return}W=setTimeout(R,250),W.unref?.()};R()},Y=new Set,G=new Kn(r),q=new On(r),fe=new sn(r,s),E=new yn(r),Z=new In(r),V=new Sn(r,{claudePath:P,provider:I,timeoutMs:y,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let u of Y)Yn(u,a)}});q.beginAutomaticInitialization({writerVersion:dn}).then(async a=>{a.state==="ready"?(await q.migrateLegacyEvals(),await q.migrateImprintSnapshot(),await V.applyCanonicalEntries(await q.getCanonicalModelEntries()),I!=="copilot"&&(await V.getUnprojectedPatternDecisions()).length>0&&await Lt({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 Te=20,Ae=300*1e3,be=[];function _e(){let a=Date.now()-Ae;for(;be.length>0&&(be[0].completedAt<a||be.length>Te);)be.shift()}let Ne=new Map;async function Bt(a){if(a.status!=="applied")return[];let u={version:1,updatedAt:Date.now(),cases:await q.getJournalEvalCases()},R=ir(a,u);if(R.length===0)return[];let m=await q.getEvalDependenciesForDecisions(a.decisionIds),k=a.threadId?await G.getThread(a.threadId):null,w=[...new Set((k?.messages??[]).flatMap(D=>(D.editEvents??[]).flatMap(L=>L.filePath?[L.filePath]:[])).map(D=>Fo(D)?gs(r,D):D))].map(D=>({kind:"source_file",value:D})),j=R.map(D=>{let L=[...new Map([...D.dependencies??[],...m,...w].map(U=>[`${U.kind}:${U.value}:${"subjectId"in U?U.subjectId??"":""}`,U])).values()],F=L.filter(U=>U.kind==="route"),$=L.flatMap(U=>U.kind==="model_path"&&U.value.startsWith("components.")?[U.value.slice(11).split(".")[0]]:[]),O=[...new Set(L.flatMap(U=>"subjectId"in U&&U.subjectId?[U.subjectId]:[]))],Q=F.length>0?F.map((U,ie)=>({id:`route-${ie+1}`,...U.value.includes("*")?{routePattern:U.value}:{route:U.value},components:$.map(ae=>({name:ae})),subjectIds:O})):[{id:$.length>0?`component-${$[0]}`:"current-page",components:$.map(U=>({name:U})),subjectIds:O}];return{...D,dependencies:L,scenarios:D.scenarios?.length?D.scenarios:Q}}),C=new Set(u.cases.map(D=>D.id));return await q.syncEvalSpecs(j),await V.attachGeneratedEvals(a.id,j.map(D=>({evalId:D.id,title:D.title,action:C.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 Ue(a){let u=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",R=ao(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:[R],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 q.syncEvalSpecs([m]),m.id}let rt=null,Ft;N.addListener((a,u,R)=>{for(let m of Y)(!R||!m.sourceId||m.sourceId===R)&&Yn(m,a)}),T.addListener((a,u,R)=>{for(let m of Y)(!R||!m.sourceId||m.sourceId===R)&&Yn(m,a)}),T.setProcessor(async a=>{let u=a.provider??I;try{let R=await V.run({provider:u,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let m=await V.loadRuns(),k=R.runId?m.runs.find(j=>j.id===R.runId):void 0;if(R.success&&R.proposalId){let j=await V.findModelProposal(R.proposalId),C=await V.loadModel(),D=j?mr(j,C):null;if(j&&D){let L=j.decisionIds.map($=>({decisionId:$,status:"projected"}));await q.applyModelProjection({runId:j.runId??j.id,presentationJobId:j.presentationJobId,decisionIds:j.decisionIds,changes:D.map($=>({path:$.path,value:$.value,decisionIds:$.decisionIds})),coverage:L});let F=await V.applySelectedModelProposal(j.id,D.map($=>({path:$.path,value:$.value})),D.map($=>({group:$.path[0]==="rules"||$.path[0]==="components"||$.path[0]==="tokens"?$.path[0]:"model",label:$.label??$.id,detail:$.rationale,path:$.path,value:$.value})),"automatic");F&&await Bt(F)}}let w=Xc(R,k);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})),R.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),be.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),_e();else{if(a.status="error",a.error=R.error??"Projection failed",a.threadId){let j=`Model projection failed.
391
210
 
392
- ${r.error}`;await y.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:I,error:r.error,model:r.model,provider:c})||await y.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:I,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),we.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),Ge()}}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),be.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),_e()}}catch(R){if(a.status==="cancelled")return;if(a.status="error",a.error=R instanceof Error?R.message:String(R),a.threadId){let m=`Model projection failed.
393
212
 
394
- ${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),we.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),Ge()}}),D.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 I;if(r.threadId){let O=await y.getThread(r.threadId);if(O){for(let G=O.messages.length-1;G>=0;G--)if(O.messages[G].sessionId){I=O.messages[G].sessionId;break}}}let g;if(I&&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),be.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),_e()}}),N.setProcessor(async a=>{let u=a,R=u._replyPrompt,m=u._replyText,k=u._replyImagePaths,w=a.provider??I,j=!!(a.surfacedProposalIds?.length&&R),C=!!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||C)&&(L=void 0);let F;if(L&&R){if(F=m??R,k&&k.length>0){F+=`
395
214
 
396
- The developer attached reference images with their reply:`;for(let O of h)g+=`
397
- Attached image: use the Read tool to view the image at: ${O}`}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 k)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+=`
398
217
 
399
- 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+=`
400
219
 
401
- 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(I)g=Be(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=en(a.feedback,a.imagePaths)+`
402
221
 
403
222
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
404
223
 
405
- 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"?`
406
225
 
407
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let O=!u&&r.threadId?await y.getThreadHistory(r.threadId):void 0,G=u?null:await H.loadModel();g=u??An(r.screenshotPath,r.feedback,{threadHistory:O&&O.length>0?O:void 0,provider:d,imagePaths:r.imagePaths,designModel:G??void 0,screenshotPaths:r.screenshotPaths})}let b=Jr(r.color,`[\u22B9 ${W}:${r.id}]`),P=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 ${P} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${I?` (resuming: ${I.slice(0,8)})`:""}`);let $=(O,G)=>{O.type==="delta"&&"text"in O?D.accumulateText(G,"response",O.text):O.type==="thinking"&&"text"in O&&D.accumulateText(G,"thinking",O.text),D.broadcast(O,G,r.sourceId)},{process:te,result:X}=d==="codex"?Ve(r.id,{prompt:g,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:I,model:r.model,configOverrides:Qe(r.agentSettings),onEvent:$}):d==="copilot"?Zt(r.id,{prompt:g,projectRoot:t,resumeSessionId:I,model:r.model,timeoutMs:J,copilotPath:w.copilot?.path??E,onEvent:$}):Xe(r.id,{prompt:g,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:v,claudePath:x,resumeSessionId:I,model:r.model,reasoningEffort:r.agentSettings?.reasoningEffort,timeoutMs:J,onEvent:$});D.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 O=$n(S.text),G=Cn(S.text),se=G.some(F=>(F.finalScope??F.inferredScope)?.breadth==="pattern");if(G.length>0&&r.annotationIds&&r.annotationIds.length>0){let F=new Set(r.annotationIds);G.every(ne=>F.has(ne.annotationId))||(G=G.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=D.getBufferedEvents(r.id),pe=ue?$r(ue.events):void 0;if(r.threadId&&await y.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:S.text,resolutions:G.length>0?G:void 0,question:O??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,M]of Object.entries(r.imagePaths))for(let Y=0;Y<M.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:G.length>0?G:[],question:O??void 0,fileEdits:S.fileEdits??[],editEvents:S.editEvents??[],toolsUsed:ce,gitDiff:F},r.screenshotPath,ne),se&&d!=="copilot"?await Nt({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=st(S.text);if(F){Array.isArray(F.rules)&&(F.rules=Je(F.rules));let oe=await H.loadModel();oe&&(!F.tokens&&oe.tokens&&(F.tokens=oe.tokens),!F.components&&oe.components&&(F.components=oe.components)),await H.writeModel(F),console.log(`${b} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&S.text){let F=on(S.text),oe=rn(S.text),ne=F??oe;if(ne&&ne.length>0){let fe=await ie.writeSynthesized(ne),j=r._proposalId;j&&await H.attachGeneratedEvals(j,ne.map(M=>M.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=an(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:Qn(t),rawResponse:S.text,...ne}),console.log(`${b} Eval run: ${F.title} \u2192 ${ne.status}`)}}O&&(console.log(`${b} \u{1F4AC} Question detected: "${O.slice(0,120)}" \u2192 broadcasting to ${ee.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),D.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:O,annotationIds:r.annotationIds},r.id,r.sourceId));let de=_n(S.text);de.length>0&&(console.log(`${b} Novel pattern(s): ${de.map(F=>`${F.category}/${F.element}`).join(", ")}`),D.broadcast({type:"novel_patterns",jobId:r.id,patterns:de,threadId:r.threadId},r.id,r.sourceId)),D.broadcast({type:"done",jobId:r.id,success:!0,resolutions:G.length>0?G:void 0,responseText:S.text,threadId:r.threadId},r.id,r.sourceId),we.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}),D.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),we.push({id:r.id,status:"error",completedAt:Date.now(),error:S.error,threadId:r.threadId,annotationIds:r.annotationIds});Ge()});let yt=xr(async(r,c)=>{if(Dr(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,I=Nr(r,h);if(I&&I!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,projectName:ht(t)});return}if(r.headers.origin){if(!Yn(r.headers.origin)){m(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(I!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,projectName:ht(t)});return}}try{if(r.method==="POST"&&d==="/send")await Zn(r,c);else if(r.method==="GET"&&d==="/events")ts(r,c);else if(r.method==="GET"&&d==="/status")await ns(c,I);else if(r.method==="PATCH"&&d==="/config")await ss(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 Or(r),b=typeof g.leaseId=="string"?g.leaseId.trim():"",P=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 $=k.acquire(b,P);m(c,201,{ok:!0,lease:$,ttlMs:Gn})}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{}yt.close(()=>{Un(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 ms(r,c);else if(r.method==="POST"&&d==="/reply")await es(r,c);else if(r.method==="POST"&&d==="/cancel")os(r,c);else if(r.method==="POST"&&d==="/materialize")await rs(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let g=await H.loadRuns();m(c,200,g)}else if(r.method==="GET"&&d==="/model/proposals"){let g=await H.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 as(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let g=d.slice(17,-6);await is(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let g=d.slice(17,-8);await ls(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let g=d.slice(17,-14);await cs(g,r,c)}else if(r.method==="POST"&&d==="/model/component")await gs(r,c);else if(r.method==="DELETE"&&d==="/model/component")await ys(r,c);else if(r.method==="PATCH"&&d==="/model/token")await vs(r,c);else if(r.method==="DELETE"&&d==="/model/token")await ws(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:g,model:b,agentSettings:P}=await Me(r);if(g==="copilot"){m(c,400,{error:"Model consolidation is not available for Copilot yet."});return}H.consolidate({provider:g,model:b,agentSettings:P}).catch($=>console.error("[Bridge] Consolidation error:",$)),m(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await ds(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await us(r,c);else if(r.method==="GET"&&d==="/evals"){let g=await ie.loadSuiteWithCurrentRuns(Qn(t));m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let g=d.slice(7,-4);await ps(g,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await fs(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let g=await H.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),P=D.getBufferedEvents(g,isNaN(b)?-1:b);P?m(c,200,P):m(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await Is(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 Ps(g,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let g=d.slice(8);await ks(g,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?Ss(r,c):r.method==="GET"&&d==="/canvas/manifest"?await xs(c):r.method==="GET"&&d==="/canvas/app.mjs"?await bs(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 Zn(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:I,reasoningEffort:g,serviceTier:b,sourceId:P,pastedImages:$,pageScreenshots:te}=await lt(r),X;try{X=JSON.parse(p)}catch{m(c,400,{error:"Invalid feedback JSON"});return}let S=Pe().slice(0,8),O={};if(te.length>0)for(let M of te){let Y=encodeURIComponent(M.pathname),re=ve(a,`screenshot-${S}-${Y}.webp`);await Ue(re,M.data),O[M.pathname]=re}let G=ve(a,`screenshot-${S}.webp`);await Ue(G,u);let se={};if($.length>0)for(let M of $){let Y=ve(a,`pasted-${S}-${M.annotationId}-${M.index}.webp`);await Ue(Y,M.data),se[M.annotationId]||(se[M.annotationId]=[]),se[M.annotationId].push(Y)}let ce=X.annotations.map(M=>M.linkedSelector?M.pathname?`${M.pathname}:${M.linkedSelector}`:M.linkedSelector:null).filter(M=>!!M),ue;if(ce.length>0){let M=await y.findContinuationThread(ce);M?(ue=M.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(M=>M.id),de=Object.keys(O).length>0,F={id:S,status:"queued",screenshotPath:G,feedback:X,createdAt:Date.now(),color:h,threadId:ue,annotationIds:pe,provider:We(d),model:I||void 0,agentSettings:Ee({reasoningEffort:g,serviceTier:b}),...Object.keys(se).length>0?{imagePaths:se}:{},sourceId:P||void 0,...de?{screenshotPaths:O}:{}},oe=new Set(X.annotations.map(M=>M.pathname).filter(Boolean)),ne;if(oe.size>1){let M=new Map;for(let Y of X.annotations){let re=Y.pathname||"(unknown)";M.has(re)||M.set(re,[]),M.get(re).push(Y.instruction||qn({...X,annotations:[Y]}))}ne=[...M.entries()].map(([Y,re])=>`\`${Y}\`
408
- ${re.map(vt=>`- ${vt}`).join(`
226
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!R&&a.threadId?await G.getThreadHistory(a.threadId):void 0,pe=R?null:await V.loadModel();F=R??Hr(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+=Lr(a.memoryReview),D&&(F+=Jo(a.imprintContext)),F+=`
227
+
228
+ ${Wr}`;let $=td(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(`${$} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${L?` (resuming: ${L.slice(0,8)})`:""}`);let Q=new Nn(a.id),U=(de,pe)=>{if(de.type==="delta"&&"text"in de){let Ce=Q.push(de.text);Ce.visibleText&&(N.accumulateText(pe,"response",Ce.visibleText),N.broadcast({...de,text:Ce.visibleText},pe,a.sourceId));for(let Oe of Ce.orientations)N.broadcast({type:"orientation",jobId:pe,orientation:Oe},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&N.accumulateText(pe,"thinking",de.text);N.broadcast(de,pe,a.sourceId)},{process:ie,result:ae}=w==="codex"?gn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:L,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:mn(a.agentSettings),onEvent:U}):w==="copilot"?or(a.id,{prompt:F,projectRoot:r,resumeSessionId:L,model:a.model,timeoutMs:y,copilotPath:f.copilot?.path??b,onEvent:U}):fn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:j?["Read"]:g,claudePath:P,resumeSessionId:L,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:y,onEvent:U});N.setActiveProcess(a.id,ie);let re=await ae,xe=Q.finalize(re.text),ve=xe.visibleText,K=D?Do(ve):{visibleText:ve,draft:void 0,error:void 0},Ie=K.visibleText;for(let de of xe.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=Ie,re.success){console.log(`${$} Iteration complete`),re.fileEdits&&re.fileEdits.length>0&&console.log(`${$} Captured ${re.fileEdits.length} file edit(s): ${re.fileEdits.map(z=>`${z.tool} ${z.file_path}`).join(", ")}`),re.editEvents&&re.editEvents.length>0&&console.log(`${$} Captured ${re.editEvents.length} edit event(s): ${re.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Gr(ve),pe=Kr(ve);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let z=new Set(a.annotationIds);pe.every(Ke=>z.has(Ke.annotationId))||(pe=pe.map((Ke,Qe)=>({...Ke,annotationId:a.annotationIds[Qe%a.annotationIds.length]})))}let Ce=re.fileEdits&&re.fileEdits.length>0?re.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):re.toolsUsed,Oe=N.getBufferedEvents(a.id),et=Oe?Qc(Oe.events,r):void 0,Re,ee=qr(ve),me=zr(ve);if(me)if(!(a.memoryReview?.packets.some(se=>se.proposalId===me.proposalId)||a.surfacedProposalIds?.includes(me.proposalId)))Re={status:"rejected",action:me.action,proposalId:me.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Re=await q.commitConversationalReview(me)}catch(se){Re={status:"rejected",action:me.action,proposalId:me.proposalId,message:se instanceof Error?se.message:String(se)}}let Pe=[...(re.fileEdits??[]).map(z=>z.file_path),...(re.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],Se,ft=a.imprintContext?.pendingGroundingExplanationIds??[];if(K.draft?.decision==="none"&&fe.recordNoop(K.draft.reason),a.threadId&&K.draft?.decision==="mutate"&&!me&&!ee)try{Se=await fe.capture(K.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await V.loadModel(),pendingGroundingExplanationIds:ft}),Se&&await q.recordImprintEvidence({summary:Se,threadId:a.threadId,jobId:a.id}).catch(z=>console.warn(`${$} Canonical Imprint evidence linkage failed:`,z))}catch(z){console.warn(`${$} Continuous imprint update failed; the thread result remains available:`,z instanceof Error?z.message:String(z))}else K.error&&console.warn(`${$} Ignored invalid imprint block: ${K.error}`);let We=Se?.transactionId;if(a.threadId&&Se&&!Se.grounding){let z=await G.getThread(a.threadId),se=new Set(Se.changes.map(Qe=>Qe.explanationId)),Ke=z?Kc(z.messages,se):void 0;if(Ke?.imprintSummary){let Qe=Ke.imprintSummary;await G.updateAssistantMessage(a.threadId,Ke.jobId,{imprintSummary:{...Qe,detail:Se.detail,changes:Se.changes,additionalObservationCount:(Qe.additionalObservationCount??0)+1,coalescedTransactionIds:[...Qe.coalescedTransactionIds??[],Se.transactionId]}}),Se=void 0}}let qt=ps({question:de,resolutions:pe,changedFiles:Pe,decisionRequired:!!ee,imprintTransactionId:We,groundingRequired:!!Se?.grounding}),X=et?.flatMap(z=>z.kind==="orientation"?[z.orientation]:[])??[];if(a.threadId){let z=j?ee?"":"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:re.sessionId,toolsUsed:j?void 0:Ce,editEvents:!j&&re.editEvents&&re.editEvents.length>0?re.editEvents:void 0,segments:!j&&et&&et.length>0?et:void 0,turn:{phase:"complete",orientation:X,result:qt},result:qt,memoryReviewCard:ee??void 0,memoryReceipt:Re,imprintSummary:Se,model:a.model,provider:w})}if(a.threadId&&!me&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let z=a.feedback.annotations.flatMap(se=>se.linkedSelector?[se.pathname?`${se.pathname}:${se.linkedSelector}`:se.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:m??(Dn(a.feedback)||"[request unavailable]"),responseSummary:de??Ie,outcome:de?"question_asked":pe.some(se=>se.status==="resolved")?"completed":"no_change",execution:{provider:w,model:a.model,sessionId:re.sessionId},subjectHints:z,filePaths:[...(re.fileEdits??[]).map(se=>se.file_path),...(re.editEvents??[]).flatMap(se=>se.filePath?[se.filePath]:[])].map(se=>Fo(se)?gs(r,se):se),resolutions:pe.map(se=>({status:se.status,summary:se.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(se=>se.id)})}catch(se){console.warn(`${$} Canonical memory capture failed; iteration remains available in legacy history:`,se instanceof Error?se.message:String(se))}}if(Re?.status==="committed"&&Re.decisionId&&w!=="copilot"&&await Lt({provider:w,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Re.decisionId}`}),a.kind==="run_eval"&&Ie&&a.evalId&&a.evalRunId){let z=await q.findJournalEvalCase(a.evalId),se=a._evalRunScope;if(z&&se){let Ke=sr(ve,z.assertions),Qe=Date.now(),Ds={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Qe,durationMs:Qe-a.createdAt,scope:se,provider:w,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:Is(r),rawResponse:ve,scopeFingerprint:a._evalScopeFingerprint,...Ke};await q.recordEvalVerification(z,Ds),console.log(`${$} Eval run: ${z.title} \u2192 ${Ke.status}`)}}de&&(console.log(`${$} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${Y.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 ue=Qr(ve);ue.length>0&&(console.log(`${$} Novel pattern(s): ${ue.map(z=>`${z.category}/${z.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:a.id,patterns:ue,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:qt},a.id,a.sourceId),be.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${$} Error: ${re.error}`),a.status="error",a.error=re.error,a.threadId&&await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:re.error||"Unknown error",model:a.model,provider:w}),N.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:re.error||"Unknown error",provider:w,model:a.model,recoverable:re.recoverableError,code:re.errorCode},a.id,a.sourceId),be.push({id:a.id,status:"error",completedAt:Date.now(),error:re.error,threadId:a.threadId,annotationIds:a.annotationIds});_e()});let St=Bc(async(a,u)=>{if(Zc(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let R=a.url||"/",m=R.split("?")[0],k=new URL(R,`http://127.0.0.1:${h}`),w=k.pathname,j=ed(a,k);if(j&&j!==s){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Qn(r)});return}if(a.headers.origin){if(!Rs(a.headers.origin)){M(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Qn(r)});return}}try{if(a.method==="POST"&&w==="/send")await st(a,u);else if(a.method==="GET"&&w==="/events")Ze(a,u);else if(a.method==="GET"&&w==="/status")await it(a,u,j);else if(a.method==="PATCH"&&w==="/config")await at(a,u);else if(a.method==="POST"&&w==="/leases"){if(p!=="detached"){M(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let C=await Ve(a),D=typeof C.leaseId=="string"?C.leaseId.trim():"",L=typeof C.ownerPid=="number"&&Number.isInteger(C.ownerPid)&&C.ownerPid>0?C.ownerPid:void 0;if(!D||D.length>128){M(u,400,{error:"A valid leaseId is required."});return}ne();let F=B.acquire(D,L);M(u,201,{ok:!0,lease:F,ttlMs:ys})}catch{M(u,400,{error:"Invalid lease request."})}}else if(w.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){M(u,409,{error:"Bridge leases are only available for detached bridges."});return}let C="";try{C=decodeURIComponent(w.slice(8))}catch{M(u,400,{error:"Invalid lease id."});return}if(!C){M(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat(C);if(!D){M(u,404,{error:"Lease not found."});return}M(u,200,{ok:!0,lease:D})}else{let D=B.release(C);M(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&he()}}else if(a.method==="POST"&&w==="/shutdown"){if(p!=="detached"){M(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}M(u,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&w==="/restart"){if(p!=="detached"){M(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}M(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let C of Y)try{C.res.end()}catch{}St.close(()=>{hs(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")M(u,200,{providers:f});else if(w.startsWith("/imprint/"))await we(a,u,w);else if(w.startsWith("/memory/"))await eo(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await no(a,u);else if(a.method==="POST"&&w==="/reply")await $e(a,u);else if(a.method==="POST"&&w==="/cancel")ut(a,u);else if(a.method==="POST"&&w==="/materialize")M(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&w==="/materialization-runs")M(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&w==="/projection-runs"){let C=await V.loadRuns();M(u,200,C)}else if(a.method==="GET"&&w==="/projection/proposals"){let C=await V.loadModelProposals();M(u,200,C)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply-selected")){let C=w.slice(22,-15);await zt(C,a,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply")){let C=w.slice(22,-6);await to(C,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/dismiss")){let C=w.slice(22,-8);await Be(C,a,u)}else if(w.startsWith("/model/proposals/"))M(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await pn(a,u);else if(a.method==="DELETE"&&w==="/model/component")await Ps(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Ts(a,u);else if(a.method==="DELETE"&&w==="/model/token")await js(a,u);else if(a.method==="POST"&&w==="/model/consolidate")M(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/model/synthesize")M(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/evals/synthesize")M(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&w==="/evals"){let C=await V.loadModel(),D=await Promise.all((await q.getJournalEvalCases()).map(async $=>{let O=await bs(r,$,C);return $.verificationState==="passing"&&(!$.verifiedScopeFingerprint||!O||$.verifiedScopeFingerprint!==O)?{...$,verificationState:"stale"}:$})),L=Is(r),F=(await q.getJournalEvalRuns()).filter($=>!$.codeFingerprint||$.codeFingerprint===L);M(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 C=w.slice(7,-4);await ct(C,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await kt(w.slice(7),a,u);else if(a.method==="GET"&&w==="/model"){let C=await V.loadModel();M(u,200,{model:C})}else if(a.method==="GET"&&w.startsWith("/jobs/")&&w.endsWith("/events")){let C=w.slice(6,w.length-7),D=parseInt(k.searchParams.get("afterSeq")??"-1",10),L=N.getBufferedEvents(C,isNaN(D)?-1:D);L?M(u,200,L):M(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await _s(m.slice(7),u);else if(a.method==="GET"&&w==="/threads/recent"){let C=Math.min(Math.max(parseInt(k.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent(C);M(u,200,D)}else if(a.method==="GET"&&w.startsWith("/decision/")){let C=w.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(C))M(u,400,{error:"Invalid decision id"});else{let D=await G.getThread(C),L=[...D?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(D&&L?.annotationSnapshot){let F=[...D.messages].reverse().find($=>$.resolutions?.length);M(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 E.loadDecision(C);F?M(u,200,{decision:F,authority:"legacy_archive"}):M(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let C=w.slice(8);await $s(C,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let C=w.slice(8);await Cs(C,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?Es(a,u):a.method==="GET"&&w==="/canvas/manifest"?await Ms(u):a.method==="GET"&&w==="/canvas/app.mjs"?await As(u):M(u,404,{error:"Not found"})}catch(C){console.error("[Bridge] Request error:",C),M(u,500,{error:C instanceof Error?C.message:"Internal error"})}});async function eo(a,u,R){try{if(a.method==="GET"&&R==="/memory/status"){M(u,200,await q.status());return}if(a.method==="GET"&&R==="/memory/diagnostics"){M(u,200,await q.diagnostics());return}if(a.method==="GET"&&R==="/memory/model-view"){M(u,200,await q.getModelView());return}if(a.method==="POST"&&R==="/memory/constraints"){let m=await Ve(a),k=typeof m.reactComponent=="string"?m.reactComponent.trim():"",w=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",C=await q.getModelView(),D=k?C.entries.filter($=>$.key===`components.${k}`||$.key.startsWith(`components.${k}.`)):[],L=($,O)=>{if(!O)return!1;if(!$.includes("*"))return $===O;let Q=$.split("*").map(U=>U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`).test(O)},F=(await q.getJournalEvalCases()).filter($=>{if($.status==="rejected")return!1;let O=($.dependencies??[]).some(U=>U.kind==="route"&&L(U.value,w)||U.kind==="subject"&&U.value===j),Q=($.scenarios??[]).some(U=>!!k&&(U.components??[]).some(ie=>ie.name===k||ie.exportName===k)||!!w&&!!U.route&&U.route===w||!!w&&!!U.routePattern&&L(U.routePattern,w));return O||Q}).map($=>({id:$.id,title:$.title,verificationState:$.verificationState,assertions:$.assertions}));M(u,200,{modelEntries:D,evals:F});return}if(a.method==="POST"&&R==="/memory/conversation-action"){let m=await Ve(a),k=typeof m.threadId=="string"?m.threadId:"",w=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!k||!w||!["accept","edit_and_accept","reject","defer"].includes(j)){M(u,400,{error:"A valid thread, proposal, and review action are required."});return}let C=await G.getThread(k),D=C?.messages.find(ae=>ae.memoryReviewCard?.proposalId===w)?.memoryReviewCard;if(!C||!D){M(u,409,{error:"This decision review card is not available in the thread."});return}let L=await V.findModelProposalsByThread(k),F=(await Promise.all(L.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(re=>q.findPendingProposalForLegacyDecision(re)))).some(re=>re?.proposalId===w)})))).find(ae=>ae.matches)?.proposal,$={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($.action==="edit_and_accept"&&!$.claim){M(u,400,{error:"Edited decision wording is required."});return}let O=await q.commitConversationalReview($),Q=`memory-${pt().slice(0,8)}`,U=j==="accept"?"> Accepted decision":j==="edit_and_accept"?"> Edited and accepted decision":j==="reject"?"> Rejected decision":"> Deferred decision";await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:Q,replyToQuestion:U}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:Q,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 V.dismissModelProposal(F.id);let ie=xt(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&ie!=="copilot"&&await Lt({provider:ie,model:typeof m.model=="string"?m.model:void 0,agentSettings:ht(m),threadId:k,reason:`Project accepted decision ${O.decisionId}`}),M(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&R==="/memory/analyze"){let m=await Ve(a),k=await q.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),w=Object.fromEntries([...new Set(k.issues.map(j=>j.code))].map(j=>[j,k.issues.filter(C=>C.code===j).length]));M(u,200,{...k,issues:void 0,issueCounts:w});return}if(a.method==="POST"&&R==="/memory/review"){let m=await Ve(a),k=await q.review(Ao(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,200,k);return}if(a.method==="POST"&&R==="/memory/context"){let m=await Ve(a),k=await q.contextualize(Ao(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,200,k);return}if(a.method==="POST"&&R==="/memory/initialize"){let m=await Ve(a),k=await q.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:dn});M(u,201,{status:k.status,report:{source:k.report.source,imported:k.report.imported,unresolvedAcceptance:k.report.unresolvedAcceptance,deferredModelEntries:k.report.deferredModelEntries,proofCases:k.report.proofCases,schemaIssues:k.report.schemaIssues}});return}if(a.method==="POST"&&R==="/memory/plan"){let m=await Ve(a),k=await q.planReview(Mo(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,k.result.ok?200:422,k);return}if(a.method==="POST"&&R==="/memory/commit"){let m=await Ve(a),k=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},w=await q.commitReview(Mo(m.command),{transactionId:typeof k.transactionId=="string"?k.transactionId:"",committedAt:typeof k.committedAt=="string"?k.committedAt:""});M(u,200,{status:await q.status(),journal:w.report});return}if(a.method==="POST"&&R==="/memory/recover"){let m=await Ve(a),k=await q.recover(m.confirm===!0);M(u,200,{status:await q.status(),journal:k.report});return}M(u,404,{error:"Memory endpoint not found."})}catch(m){let k=m instanceof Error?m.message:String(m),w=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(k),j=/required|invalid|unsupported|expected|must be|confirmation/i.test(k);if(w||j){M(u,w?409:400,{error:k});return}throw m}}async function we(a,u,R){if(a.method==="GET"&&R==="/imprint/status"){let[m,k]=await Promise.all([fe.store.load(),G.load()]),w=[...new Set(Object.values(k.threads).flatMap(j=>Xn(j.messages)))];M(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:fe.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&R==="/imprint/action"){let m=await Ve(a),k=typeof m.threadId=="string"?m.threadId:"",w=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!k||!w||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(j)){M(u,400,{error:"A valid thread, imprint update, and action are required."});return}let D=await G.getThread(k),L=[...D?.messages??[]].reverse().find(ie=>ie.role==="assistant"&&ie.imprintSummary?.transactionId===w),F=L?.imprintSummary;if(!D||!L||!F){M(u,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){M(u,409,{error:"This imprint summary has already been resolved."});return}let $=`imprint-${pt().slice(0,8)}`;await fe.applyGroundingAction({summary:F,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:k,jobId:$}),await q.recordImprintEvidence({summary:F,action:j,threadId:k,jobId:$}).catch(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let O=Ot(L.result,!!L.question),Q=L.turn?{...L.turn,result:Ot(L.turn.result,!!L.question)}:void 0;await G.updateAssistantMessage(k,L.jobId,{imprintSummary:{...F,resolvedAction:j},...O?{result:O}:{},...Q?{turn:Q}:{}});let U={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(k,{role:"human",timestamp:Date.now(),jobId:$,replyToQuestion:U[j]}),M(u,200,{ok:!0,action:j});return}M(u,404,{error:"Imprint endpoint not found."})}async function st(a,u){let{screenshot:R,feedback:m,color:k,provider:w,model:j,reasoningEffort:C,serviceTier:D,sourceId:L,pastedImages:F,pageScreenshots:$}=await Jn(a),O;try{O=JSON.parse(m)}catch{M(u,400,{error:"Invalid feedback JSON"});return}let Q=pt().slice(0,8),U={};if($.length>0)for(let ee of $){let me=encodeURIComponent(ee.pathname),Pe=Me(c,`screenshot-${Q}-${me}.webp`);await ln(Pe,ee.data),U[ee.pathname]=Pe}let ie=Me(c,`screenshot-${Q}.webp`);await ln(ie,R);let ae={};if(F.length>0)for(let ee of F){let me=Me(c,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await ln(me,ee.data),ae[ee.annotationId]||(ae[ee.annotationId]=[]),ae[ee.annotationId].push(me)}let re=O.annotations.map(ee=>ee.linkedSelector?ee.pathname?`${ee.pathname}:${ee.linkedSelector}`:ee.linkedSelector:null).filter(ee=>!!ee),xe;if(re.length>0){let ee=await G.findContinuationThread(re);ee?(xe=ee.id,await G.addElementIdentifiers(xe,re)):xe=(await G.createThread(Q,re)).id}else xe=(await G.createThread(Q,[])).id;let ve=O.annotations.map(ee=>ee.id),K=Object.keys(U).length>0,Ie=await Fr(q,O,re,ee=>console.warn(`[\u22B9 ${h}:${Q}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),de=await fe.contextualize({text:Dn(O),subjectHints:[...re,...O.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(me=>!!me))],pendingGroundingExplanationIds:Xn((await G.getThread(xe))?.messages??[])}).catch(ee=>{console.warn(`[\u22B9 ${h}:${Q}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),pe={id:Q,status:"queued",screenshotPath:ie,feedback:O,createdAt:Date.now(),color:k,threadId:xe,annotationIds:ve,provider:xt(w),model:j||void 0,agentSettings:ht({reasoningEffort:C,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:L||void 0,...K?{screenshotPaths:U}:{},...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}},Ce=new Set(O.annotations.map(ee=>ee.pathname).filter(Boolean)),Oe;if(Ce.size>1){let ee=new Map;for(let me of O.annotations){let Pe=me.pathname||"(unknown)";ee.has(Pe)||ee.set(Pe,[]),ee.get(Pe).push(me.instruction||ws({...O,annotations:[me]}))}Oe=[...ee.entries()].map(([me,Pe])=>`\`${me}\`
229
+ ${Pe.map(Se=>`- ${Se}`).join(`
409
230
  `)}`).join(`
410
- `)}else ne=qn(X);let fe=Be(X,Object.keys(se).length>0?se:void 0);await y.appendMessage(ue,{role:"human",timestamp:Date.now(),jobId:S,screenshotPath:G,...de?{screenshotPaths:O}:{},...Object.keys(se).length>0?{imagePaths:se}:{},annotationIds:pe,feedbackSummary:ne,feedbackContext:fe||void 0});let j=D.enqueue(F);m(c,200,{jobId:S,position:j,threadId:ue})}async function es(r,c){let u=r.headers["content-type"]||"",p,h,d,I,g,b,P,$=[];if(u.includes("multipart/form-data")){let j=await lt(r),M=j.feedback?JSON.parse(j.feedback):{};p=M.threadId,h=M.reply,d=M.color,I=M.provider,g=M.model,b=Ee(M),P=M.sourceId||j.sourceId;for(let Y of j.pastedImages)$.push(Y.data)}else{let j=[];for await(let re of r)j.push(typeof re=="string"?Buffer.from(re):re);let M=Buffer.concat(j).toString("utf-8"),Y;try{Y=JSON.parse(M)}catch{m(c,400,{error:"Invalid JSON"});return}p=Y.threadId,h=Y.reply,d=Y.color,I=Y.provider,g=Y.model,b=Ee(Y),P=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 M=j.length-1;M>=0;M--)if(j[M].screenshotPath){X=j[M].screenshotPath;break}}let S=await hs(p);if(!X&&!S){m(c,400,{error:"No screenshot available"});return}let O=D.hasActiveThread(p),G=O?D.getQueuedThreadJob(p,j=>j._replyText!==void 0||j._replyPrompt!==void 0):null,se=G?.id??Pe().slice(0,8),ce=[],ue=`${se}-${Date.now()}`;for(let j=0;j<$.length;j++){let M=ve(a,`reply-${ue}-${j}.webp`);await Ue(M,$[j]),ce.push(M)}await y.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:se,replyToQuestion:h,screenshotPath:X,...O?{queued:!0}:{},...ce.length>0?{replyImagePaths:ce}:{}});let pe=await y.getThreadHistory(p),de=[];for(let j of pe)if(j.annotationIds)for(let M of j.annotationIds)de.includes(M)||de.push(M);let F=We(I),oe=Ct(X,pe,F,ce.length>0?ce:void 0);if(G){let j=G,Y=[...j._replyTexts??(j._replyText?[j._replyText]:[]),h],re=[...j._replyImagePaths??[],...ce];j._replyTexts=Y,j._replyText=Hn(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:P||void 0};S&&(ne.kind=S),ne._replyPrompt=oe,ne._replyTexts=[h],ne._replyText=Hn([h]),ce.length>0&&(ne._replyImagePaths=ce);let fe=O?D.enqueueNext(ne):D.enqueue(ne);m(c,200,{jobId:se,position:fe,threadId:p})}function ts(r,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
231
+ `)}else Oe=ws(O);let et=en(O,Object.keys(ae).length>0?ae:void 0);await G.appendMessage(xe,{role:"human",timestamp:Date.now(),jobId:Q,screenshotPath:ie,...K?{screenshotPaths:U}:{},...Object.keys(ae).length>0?{imagePaths:ae}:{},annotationIds:ve,annotationSnapshot:{url:O.url,viewport:O.viewport,annotations:O.annotations,color:k||void 0},feedbackSummary:Oe,feedbackContext:et||void 0,...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}});let Re=N.enqueue(pe);M(u,200,{jobId:Q,position:Re,threadId:xe})}async function $e(a,u){let R=a.headers["content-type"]||"",m,k,w,j,C,D,L,F,$,O=[];if(R.includes("multipart/form-data")){let X=await Jn(a),ue=X.feedback?JSON.parse(X.feedback):{};m=ue.threadId,k=ue.reply,w=ue.color,j=ue.provider,C=ue.model,D=ht(ue),L=ue.sourceId||X.sourceId,F=typeof ue.memoryReviewProposalId=="string"?ue.memoryReviewProposalId:void 0,$=ue.evalRemediation?.action==="resolve"&&typeof ue.evalRemediation.evalId=="string"?{evalId:ue.evalRemediation.evalId,action:"resolve"}:void 0;for(let z of X.pastedImages)O.push(z.data)}else{let X=[];for await(let se of a)X.push(typeof se=="string"?Buffer.from(se):se);let ue=Buffer.concat(X).toString("utf-8"),z;try{z=JSON.parse(ue)}catch{M(u,400,{error:"Invalid JSON"});return}m=z.threadId,k=z.reply,w=z.color,j=z.provider,C=z.model,D=ht(z),L=z.sourceId,F=z.memoryReviewProposalId,$=z.evalRemediation?.action==="resolve"&&typeof z.evalRemediation.evalId=="string"?{evalId:z.evalRemediation.evalId,action:"resolve"}:void 0}if(!m||!k){M(u,400,{error:"Missing threadId or reply"});return}let Q=await G.getThread(m);if(!Q){M(u,404,{error:"Thread not found"});return}let U,ie;if($){let X=await q.findJournalEvalCase($.evalId),ue=(await q.getJournalEvalRuns()).filter(z=>z.evalId===$.evalId&&z.threadId===m).sort((z,se)=>se.completedAt-z.completedAt)[0];if(!X||!ue){M(u,409,{error:"The failed eval run is not available in this thread."});return}if(ue.status!=="fail"){M(u,409,{error:"Only a failed eval can start remediation."});return}ie={evalCase:X,run:ue}}if(F){let X=await V.findModelProposalsByThread(m);if(U=(await Promise.all(X.flatMap(z=>z.authorityStatus==="accepted"?[]:z.decisionIds.map(async se=>({modelProposalId:z.id,underlying:await q.findPendingProposalForLegacyDecision(se)}))))).filter(z=>!!z.underlying).find(z=>z.underlying.proposalId===F),!U){M(u,409,{error:"The requested memory decision is not pending in this thread."});return}}let ae="";{let X=await G.getThreadHistory(m);for(let ue=X.length-1;ue>=0;ue--)if(X[ue].screenshotPath){ae=X[ue].screenshotPath;break}}let re=await mt(m);if(!ae&&!re){M(u,400,{error:"No screenshot available"});return}let xe=N.hasActiveThread(m),ve=xe?N.getQueuedThreadJob(m,X=>X._replyText!==void 0||X._replyPrompt!==void 0):null,K=ve?.id??pt().slice(0,8),Ie=[],de=`${K}-${Date.now()}`;for(let X=0;X<O.length;X++){let ue=Me(c,`reply-${de}-${X}.webp`);await ln(ue,O[X]),Ie.push(ue)}await G.appendMessage(m,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:k,screenshotPath:ae,...xe?{queued:!0}:{},...Ie.length>0?{replyImagePaths:Ie}:{}});let pe=await G.getThreadHistory(m),Ce=[...pe].reverse().find(X=>X.memoryReview)?.memoryReview,Oe=await fe.contextualize({text:k,subjectHints:Q.elementIdentifiers,pendingGroundingExplanationIds:Xn(pe)}).catch(X=>{console.warn(`[\u22B9 ${h}:${K}] Imprint context unavailable for reply; continuing without it:`,X instanceof Error?X.message:String(X))}),et=new Set(pe.flatMap(X=>X.memoryReceipt?.status==="committed"?[X.memoryReceipt.proposalId]:[])),Re=[...pe].reverse().find(X=>X.memoryReviewCard&&!et.has(X.memoryReviewCard.proposalId))?.memoryReviewCard,ee=[];for(let X of pe)if(X.annotationIds)for(let ue of X.annotationIds)ee.includes(ue)||ee.push(ue);let me=xt(j),Pe=U,Se=Pe?[Pe.underlying.proposalId]:Re?[Re.proposalId]:[],ft=Vr(ae,pe,me,Ie.length>0?Ie:void 0);if(ie?ft+=["","## 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(ie.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:ie.run.summary,assertionResults:ie.run.assertionResults,scope:ie.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
232
+ `):Pe?ft+=["","## Decision review card",`Privately review proposal ${Pe.underlying.proposalId}: ${Pe.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
+ `):Re&&(ft+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Re)}`,"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 X=ve,z=[...X._replyTexts??(X._replyText?[X._replyText]:[]),k],se=[...X._replyImagePaths??[],...Ie];X._replyTexts=z,X._replyText=vs(z),X._replyImagePaths=se.length>0?se:void 0,X._replyPrompt=ft,X.annotationIds=ee.length>0?ee:X.annotationIds,X.agentSettings=D??X.agentSettings,X.memoryReview=Ce??X.memoryReview,X.imprintContext=Oe??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...Se])],M(u,200,{jobId:K,position:1,threadId:m,bundled:!0});return}let We={id:K,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:ee.length>0?ee:void 0,provider:me,model:C||void 0,agentSettings:D,sourceId:L||void 0,...Ce?{memoryReview:Ce}:{},...Oe?{imprintContext:Oe}:{},...Se.length?{surfacedProposalIds:Se}:{}};ie?We.kind="resolve_eval":re&&(We.kind=re),We._replyPrompt=ft,We._evalRemediation=!!ie,We._replyTexts=[k],We._replyText=vs([k]),Ie.length>0&&(We._replyImagePaths=Ie);let qt=xe?N.enqueueNext(We):N.enqueue(We);M(u,200,{jobId:K,position:qt,threadId:m})}function Ze(a,u){u.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),u.write(`event: connected
411
235
  data: {"status":"connected"}
412
236
 
413
- `);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 ns(r,c){let u=[...D.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([H.loadRuns(),H.loadModelProposals()]);m(r,200,{ok:!0,version:Ln,restartMode:U,projectId:o,projectName:ht(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:D.depth+A.depth,materializerQueueDepth:A.depth,leases:{active:k.isActivated,count:k.size,nextExpiryAt:k.nextExpiryAt,shutdownPending:C},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,I)=>(I.completedAt??I.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:we})}async function ss(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 os(r,c){let p=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("jobId"),h=p?D.allActive.filter($=>$.id===p):D.allActive,d=p?A.allActive.filter($=>$.id===p):A.allActive,I=[...h.map($=>$.threadId),...d.map($=>$.threadId)].filter(Boolean),g=p?D.cancelJob(p):D.cancelActive(),b=p?A.cancelJob(p):A.cancelActive(),P=!!(g||b);for(let $ of I)await y.appendMessage($,{role:"assistant",timestamp:Date.now(),jobId:p||b?.id||"",cancelled:!0});m(c,200,{cancelled:P})}async function Nt(r){let c=Pe().slice(0,8),u=r.threadId,p=!u;u||(u=(await y.createThread(c,[])).id,Se.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 rs(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 H.getUnmaterializedPatternDecisions();if(d.length===0){m(c,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let I=await Nt({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),...I})}async function is(r,c){let u=decodeURIComponent(r),p=await H.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.
414
-
415
- ${p.title}
416
- ${p.summary}`}),m(c,200,{proposal:p})}async function as(r,c,u){let p=decodeURIComponent(r),h=[];for await(let P of c)h.push(typeof P=="string"?Buffer.from(P):P);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{m(u,400,{error:"Invalid JSON"});return}let I=(d.changes??[]).flatMap(P=>{if(!Array.isArray(P.path)||P.path.length===0)return[];let $=P.path.filter(te=>typeof te=="string"||typeof te=="number");return $.length!==P.path.length?[]:[{path:$,value:P.value,remove:P.remove===!0}]});if(I.length===0){m(u,400,{error:"No selected model changes"});return}let g=(d.changeSummaries??[]).flatMap(P=>{if(!P||typeof P!="object")return[];let $=Array.isArray(P.path)?P.path.filter(te=>typeof te=="string"||typeof te=="number"):void 0;return Array.isArray(P.path)&&$?.length!==P.path.length?[]:[{group:typeof P.group=="string"?P.group:void 0,label:typeof P.label=="string"?P.label:void 0,detail:typeof P.detail=="string"?P.detail:void 0,path:$,value:P.value,currentValue:P.currentValue}]}),b=await H.applySelectedModelProposal(p,I,g);if(!b){m(u,404,{error:"Model proposal not found"});return}if(b.threadId){let P=We(d.provider),$=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 ${I.length} selected change${I.length===1?"":"s"}.
417
-
418
- ${b.title}`,provider:P,model:$})}m(u,200,{proposal:b})}async function ls(r,c,u){let p=decodeURIComponent(r),{provider:h,model:d}=await Me(c),I=await H.dismissModelProposal(p);if(!I){m(u,404,{error:"Model proposal not found"});return}I.threadId&&await y.appendMessage(I.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${I.id}`,responseText:`Model proposal dismissed.
419
-
420
- ${I.title}`,provider:h,model:d}),m(u,200,{proposal:I})}async function cs(r,c,u){let p=decodeURIComponent(r),h=await H.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:I,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 P=await H.loadModel(),$=await ie.loadSuite(),te=un({proposal:h,currentModel:P,existingSuite:$}),X=Pe().slice(0,8),S=h.threadId??(await y.createThread(X,[])).id;Se.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(`
421
- `)});let O={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:I??h.model,agentSettings:g};O._replyPrompt=te,O._proposalId=h.id;let G=D.enqueue(O);m(u,200,{jobId:X,position:G,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:We(typeof u.provider=="string"?u.provider:void 0),model:typeof u.model=="string"&&u.model?u.model:void 0,agentSettings:Ee(u)}}catch{return{}}}async function ds(r,c){let u=await H.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 I=gn(u),g=Pe().slice(0,8),P=(await y.createThread(g,[])).id;Se.set(P,"synthesize"),await y.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let $={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:P,kind:"synthesize",provider:p,model:h,agentSettings:d};$._replyPrompt=I;let te=D.enqueue($);m(c,200,{jobId:g,position:te,threadId:P})}async function us(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(),I=await le.loadDecisions(d),g=await y.load(),b=await H.loadModel(),P=await ie.loadSuite(),$=cn({decisions:I,threads:g,model:b,existingSuite:P}),te=Pe().slice(0,8),S=(await y.createThread(te,[])).id;Se.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 O={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};O._replyPrompt=$;let G=D.enqueue(O);m(c,200,{jobId:te,position:G,threadId:S})}async function ps(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:I,provider:g,model:b,reasoningEffort:P,serviceTier:$,sourceId:te}=await lt(c),X=We(g)??B;if(X==="copilot"){m(u,400,{error:"Eval runs are not available for Copilot yet."});return}let S={};try{S=I?JSON.parse(I):{}}catch{m(u,400,{error:"Invalid eval run context JSON"});return}let O=Pe().slice(0,8),G=Pe().slice(0,8),se=ve(a,`eval-run-${O}.webp`);await Ue(se,d);let ce=await ie.writeRunScreenshot(O,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 H.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=dn({evalCase:h,scope:de,model:F,screenshotPath:se,chromeDevtoolsAvailable:ne}),M=(await y.createThread(G,[])).id;Se.set(M,"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(M,{role:"human",timestamp:Date.now(),jobId:G,screenshotPath:se,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${de.url||"unknown"}`,"Assertions:",...h.assertions.map(Ms=>`- ${Ms}`)].join(`
422
- `)});let re={id:G,status:"queued",screenshotPath:se,feedback:Y,createdAt:Date.now(),color:"#111827",threadId:M,kind:"run_eval",evalId:p,evalRunId:O,provider:X,model:b||void 0,agentSettings:Ee({reasoningEffort:P,serviceTier:$}),sourceId:te||void 0};re._replyPrompt=fe,re._evalRunScope=de,re._evalScreenshotPath=ce;let vt=D.enqueue(re);m(u,200,{jobId:G,runId:O,position:vt,threadId:M,screenshotPath:ce})}async function fs(r,c,u){let p=decodeURIComponent(r),h={},d,I,g;try{let P=[];for await(let te of c)P.push(typeof te=="string"?Buffer.from(te):te);let $=JSON.parse(Buffer.concat(P).toString());d=$.status,I=$.title,g=$.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),I!==void 0){if(typeof I!="string"||I.trim().length===0){m(u,400,{error:"Invalid title"});return}h.title=I.trim()}if(g!==void 0){if(!Array.isArray(g)){m(u,400,{error:"Invalid assertions"});return}let P=g.filter($=>typeof $=="string").map($=>$.trim()).filter(Boolean);if(P.length===0){m(u,400,{error:"Invalid assertions"});return}h.assertions=P}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 hs(r){let c=Se.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 Se.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return Se.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return Se.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return Se.set(r,"materialize_model"),"materialize_model"}async function ms(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 Mn(p)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await En(p)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await Tn(p,w.copilot.path??E));let[d,I,g]=await Promise.all([Mt(t),Et(t),Tt(t,w.copilot?.path??E)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=I),w.copilot&&(w.copilot.mcp=g),m(c,200,{results:h,capabilities:{providers:w}})}async function gs(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 H.addComponent(p.name);m(c,200,h)}async function ys(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 H.removeComponent(p.name);m(c,200,h)}async function vs(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 H.updateToken(p.path,p.value);m(c,200,h)}async function ws(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 H.removeToken(p.path);m(c,200,h)}function Ss(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=Ft(W,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(p)}async function xs(r){let c=Date.now();if(He&&c<He.expires){m(r,200,He.data);return}try{let{scanForComponents:u}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:p}=await import("./render-generator-EANIDD2E.mjs"),h=await u(t);He={data:h,expires:c+5e3},p(h,t,Ot).then(d=>{Ot=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 bs(r){let c=[ve(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ve(t,"packages","popmelt","dist","canvas.mjs")];try{let u=Pr(import.meta.url);c.unshift(ve(Ir(u),"canvas.mjs"))}catch{}for(let u of c)try{let p=await Wn(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 Is(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){m(c,400,{error:"Invalid filename"});return}try{let u=await Wn(ve(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 qe(r){return`/files/${ht(r)}`}async function Ps(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,P)=>P.completedAt-b.completedAt)[0],h=p?await ie.findCase(p.evalId):null,d=await H.findModelProposalsByThread(r),I=[...d].sort((b,P)=>P.updatedAt-b.updatedAt)[0]??null,g=u.messages.map(({screenshotPath:b,screenshotPaths:P,imagePaths:$,replyImagePaths:te,...X})=>({...X,...X.role==="assistant"&&p?{evalRun:{...p,title:h?.title}}:{},...b?{screenshotUrl:qe(b)}:{},...P?{screenshotUrls:Object.fromEntries(Object.entries(P).map(([S,O])=>[S,qe(O)]))}:{},...$?{imageUrls:Object.fromEntries(Object.entries($).map(([S,O])=>[S,O.map(qe)]))}:{},...te?{replyImageUrls:te.map(qe)}:{}}));m(c,200,{id:u.id,createdAt:u.createdAt,messages:g,modelProposal:I,modelProposals:d})}async function ks(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 Jt=9,zt=!1;for(let r=e;r<e+Jt;r++)try{await Br(yt,r),W=r,zt=!0,console.log(`[\u22B9 is watching :${W}]`);break}catch(c){if(c.code==="EADDRINUSE"){let u=await zr(r);if(u&&u.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!zt)throw new Error(`[Bridge] All ports ${e}\u2013${e+Jt-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)mt(p,{type:"capabilities_changed",data:{}})}});let Rs=setInterval(()=>{Xn(a).catch(()=>{})},Mr),Bt=setInterval(()=>{k.expireStale().becameEmpty&&_()},Tr);return Bt.unref?.(),{port:W,projectId:o,close:async()=>{clearInterval(Rs),clearInterval(Bt),T(),k.clear(),await D.destroyAsync(),A.destroy();for(let r of ee)try{r.res.end()}catch{}return ee.clear(),new Promise(r=>{yt.close(()=>r())})}}}async function Xn(s){try{let e=await yr(s),n=Date.now();for(let t of e){let o=ve(s,t);try{let i=await wr(o);n-i.mtimeMs>Er&&await Sr(o)}catch{}}}catch{}}var ge="\x1B[35m[popmelt]\x1B[0m";async function Wr(){let s=process.argv.slice(2);if(s[0]==="wrap"){let e=s.indexOf("--");(e===-1||e===s.length-1)&&(console.error(`${ge} Usage: popmelt wrap -- <dev command>`),console.error(`${ge} Example: popmelt wrap -- next dev`),console.error(`${ge} Example: popmelt wrap -- astro dev`),process.exit(1));let n=s.slice(e+1);await qr(n);return}if(s[0]==="bridge"){await Gr();return}if(s[0]==="stop"){await Hr();return}console.log(`${ge} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function Gr(){let s=await Dt({projectRoot:process.cwd()});console.log(`${ge} Bridge running on http://localhost:${s.port}`),await new Promise(e=>{let n=async()=>{console.log(`
423
- ${ge} Shutting down bridge...`),await s.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function Hr(){let s=Ur(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await jr(s,"utf8"))}catch{console.log(`${ge} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${ge} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${ge} Bridge process ${e.pid} already dead`);else throw n}try{await Lr(s)}catch{}}async function qr(s){let e=await Dt({projectRoot:process.cwd()});console.log(`${ge} Bridge running on http://localhost:${e.port}`);let[n,...t]=s;console.log(`${ge} Starting: ${s.join(" ")}`);let o=Fr(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),i=a=>{o.kill(a)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),o.on("exit",async(a,l)=>{await e.close(),l?process.kill(process.pid,l):process.exit(a??0)})}Wr().catch(s=>{console.error(`${ge} Fatal:`,s),process.exit(1)});
237
+ `);let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,k={id:pt().slice(0,8),res:u,sourceId:m};Y.add(k),a.on("close",()=>{Y.delete(k)})}async function it(a,u,R){i??=cs(a.headers),_e();let m=[...N.allActive,...T.allActive.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds??[],color:"#000000",kind:"project_model",standalone:K.standalone}))],[k,w,j,C,D]=await Promise.allSettled([V.loadRuns(),V.loadModelProposals(),q.status(),fe.store.load(),G.load()]),L=[],F=K=>K.reason instanceof Error?K.reason.message:String(K.reason);k.status==="rejected"&&L.push({subsystem:"projection",message:F(k)}),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."}),C.status==="rejected"&&L.push({subsystem:"imprint",message:F(C)}),D.status==="rejected"&&L.push({subsystem:"threads",message:F(D)});let $=k.status==="fulfilled"?k.value.runs:[],O=w.status==="fulfilled"?w.value.proposals:[],Q=ds($,O),U=Q.actionableProposals.map(K=>({id:K.id,status:K.status,title:K.title,summary:K.summary,decisionIds:K.decisionIds,threadId:K.threadId,runId:K.runId,presentationJobId:K.presentationJobId,authorityStatus:K.authorityStatus,underlyingProposalId:K.underlyingProposalId,createdAt:K.createdAt,updatedAt:K.updatedAt,appliedAt:K.appliedAt,dismissedAt:K.dismissedAt,generatedEvalIds:K.generatedEvalIds,evalProjections:K.evalProjections,error:K.error})),ie=j.status==="fulfilled"?j.value:{initialized:!1,state:"degraded",error:F(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(K=>Xn(K.messages)))]:[],re=C.status==="fulfilled"?{state:"ready",head:C.value.graph.head,updatedAt:C.value.graph.updatedAt,explanationCount:C.value.graph.explanations.filter(K=>K.state!=="retired").length,concreteCount:C.value.graph.concrete.length,relationCount:C.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:C.value.recoveredTransactions,admission:fe.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(C),pendingGroundingCount:ae.length,admission:fe.diagnostics(),admissionWindowStartedAt:e},xe=L.length>0?"degraded":ie.state==="absent"||ie.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();M(u,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:xe,issues:L},version:dn,restartMode:p,projectId:s,projectName:Qn(r),projectRoot:r,requestProjectId:R,projectIdVerified:R===s,devOrigin:i,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds,color:K.color,kind:K.kind,standalone:"standalone"in K?K.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:k.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:Q.recentRuns,recentAppliedRuns:Q.recentAppliedRuns,actionableProposalCounts:Q.actionableProposalCounts,actionableProposals:U},memory:ie,imprint:re,recentJobsRetentionMs:Ae,recentJobs:be})}async function at(a,u){let R=await new Promise(m=>{let k="";a.on("data",w=>{k+=w.toString()}),a.on("end",()=>m(k))});try{let m=JSON.parse(R);typeof m.devOrigin=="string"&&(i=m.devOrigin||null),M(u,200,{ok:!0,devOrigin:i})}catch{M(u,400,{error:"Invalid JSON"})}}async function ut(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("jobId"),k=m?N.allActive.filter(F=>F.id===m):N.allActive,w=m?T.allActive.filter(F=>F.id===m):T.allActive,j=[...k.map(F=>F.threadId),...w.map(F=>F.threadId)].filter(Boolean),C=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),L=!!(C||D);for(let F of j)await G.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});M(u,200,{cancelled:L})}async function Lt(a){let u=pt().slice(0,8),R=a.threadId,m=!R;R||(R=(await G.createThread(u,[])).id,Ne.set(R,"project_model")),m&&await G.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:u,feedbackSummary:a.reason}),await G.appendMessage(R,{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 k={id:u,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:R,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:m},w=T.enqueue(k);return{jobId:u,position:w,threadId:R}}async function to(a,u){let R=decodeURIComponent(a),m=await V.findModelProposal(R);if(!m){M(u,404,{error:"Model proposal not found"});return}M(u,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:m})}async function zt(a,u,R){let m=decodeURIComponent(a),k=[];for await(let O of u)k.push(typeof O=="string"?Buffer.from(O):O);let w;try{w=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{M(R,400,{error:"Invalid JSON"});return}let j=(w.changes??[]).flatMap(O=>{if(!Array.isArray(O.path)||O.path.length===0)return[];let Q=O.path.filter(ie=>typeof ie=="string"||typeof ie=="number");if(Q.length!==O.path.length)return[];let U=Array.isArray(O.decisionIds)?O.decisionIds.filter(ie=>typeof ie=="string"):void 0;return[{path:Q,value:O.value,remove:O.remove===!0,decisionIds:U}]});if(j.length===0){M(R,400,{error:"No selected model changes"});return}let C=(w.changeSummaries??[]).flatMap(O=>{if(!O||typeof O!="object")return[];let Q=Array.isArray(O.path)?O.path.filter(U=>typeof U=="string"||typeof U=="number"):void 0;return Array.isArray(O.path)&&Q?.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:Q,value:O.value,currentValue:O.currentValue}]}),D=await V.findModelProposal(m);if(!D){M(R,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){M(R,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){M(R,409,{error:`Model proposal is already ${D.status}.`});return}let L=D.decisionIds.map(O=>{let Q=D.changes?.filter(ae=>ae.decisionIds.includes(O)).length??0,U=j.filter(ae=>ae.decisionIds?.includes(O)).length,ie=U===0?"unprojected":Q>U?"partially_projected":"projected";return{decisionId:O,status:ie}}),F=await q.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}),$=await V.applySelectedModelProposal(m,j,C);if(!$){M(R,404,{error:"Model proposal not found"});return}if(await Bt($),$.threadId){let O=xt(w.provider),Q=typeof w.model=="string"&&w.model?w.model:void 0;await G.appendMessage($.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${$.id}`,responseText:"",provider:O,model:Q})}M(R,200,{proposal:$,projection:F})}async function Be(a,u,R){let m=decodeURIComponent(a),{provider:k,model:w}=await Fe(u),j=await V.dismissModelProposal(m);if(!j){M(R,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:k,model:w}),M(R,200,{proposal:j})}async function Fe(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 R=JSON.parse(Buffer.concat(u).toString());return{provider:xt(typeof R.provider=="string"?R.provider:void 0),model:typeof R.model=="string"&&R.model?R.model:void 0,agentSettings:ht(R)}}catch{return{}}}async function ct(a,u,R){let m=decodeURIComponent(a),k=await q.findJournalEvalCase(m);if(!k){M(R,404,{error:"Eval not found"});return}if(k.status!=="approved"){M(R,400,{error:"Only approved evals can be run"});return}let{screenshot:w,feedback:j,provider:C,model:D,reasoningEffort:L,serviceTier:F,sourceId:$}=await Jn(u),O=xt(C)??I;if(O==="copilot"){M(R,400,{error:"Eval runs are not available for Copilot yet."});return}let Q={};try{Q=j?JSON.parse(j):{}}catch{M(R,400,{error:"Invalid eval run context JSON"});return}let U=pt().slice(0,8),ie=pt().slice(0,8),ae=Me(c,`eval-run-${U}.webp`);await ln(ae,w);let re=await Z.persistEvalScreenshot(w),xe=Q.viewport,ve=xe&&typeof xe=="object"?xe:{},K={type:"current_page",url:typeof Q.url=="string"?Q.url:"",viewport:{width:typeof ve.width=="number"?ve.width:0,height:typeof ve.height=="number"?ve.height:0}},Ie=await V.loadModel(),de=await bs(r,k,Ie),pe=O==="claude"?S.name:O==="codex"?A.name:null,Ce=O==="codex"?_.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Oe=cr({evalCase:k,scope:K,model:Ie,screenshotPath:ae,chromeDevtoolsAvailable:Ce}),Re=(await G.createThread(ie,[])).id;Ne.set(Re,"run_eval");let ee={timestamp:new Date().toISOString(),url:K.url,viewport:K.viewport,scrollPosition:{x:typeof Q.scrollX=="number"?Q.scrollX:0,y:typeof Q.scrollY=="number"?Q.scrollY:0},annotations:[],styleModifications:[]};await G.appendMessage(Re,{role:"human",timestamp:Date.now(),jobId:ie,screenshotPath:ae,feedbackSummary:`Run eval \u2014 ${k.title}`,feedbackContext:[`Eval: ${k.title}`,"Scope: current page",`URL: ${K.url||"unknown"}`,"Assertions:",...k.assertions.map(Se=>`- ${Se}`)].join(`
238
+ `)});let me={id:ie,status:"queued",screenshotPath:ae,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:Re,kind:"run_eval",evalId:m,evalRunId:U,provider:O,model:D||void 0,agentSettings:ht({reasoningEffort:L,serviceTier:F}),sourceId:$||void 0};me._replyPrompt=Oe,me._evalRunScope=K,me._evalScreenshotPath=re,me._evalScopeFingerprint=de;let Pe=N.enqueue(me);M(R,200,{jobId:ie,runId:U,position:Pe,threadId:Re,screenshotPath:re})}async function kt(a,u,R){let m=decodeURIComponent(a),k={},w,j,C;try{let L=[];for await(let $ of u)L.push(typeof $=="string"?Buffer.from($):$);let F=JSON.parse(Buffer.concat(L).toString());w=F.status,j=F.title,C=F.assertions}catch{M(R,400,{error:"Invalid JSON"});return}if(w!==void 0&&w!=="pending"&&w!=="approved"&&w!=="rejected"){M(R,400,{error:"Invalid status"});return}if(w&&(k.status=w),j!==void 0){if(typeof j!="string"||j.trim().length===0){M(R,400,{error:"Invalid title"});return}k.title=j.trim()}if(C!==void 0){if(!Array.isArray(C)){M(R,400,{error:"Invalid assertions"});return}let L=C.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(L.length===0){M(R,400,{error:"Invalid assertions"});return}k.assertions=L}if(!k.status&&!k.title&&!k.assertions){M(R,400,{error:"No eval changes provided"});return}let D=await q.updateJournalEvalCase(m,k);if(!D){M(R,404,{error:"Eval not found"});return}M(R,200,{eval:D})}async function mt(a){let u=Ne.get(a);if(u)return u;let k=(await G.getThread(a))?.messages.find(w=>w.role==="human")?.feedbackSummary??"";if(k.startsWith("Synthesize evals"))return Ne.set(a,"synthesize_evals"),"synthesize_evals";if(k.startsWith("Synthesize rules"))return Ne.set(a,"synthesize"),"synthesize";if(k.startsWith("Run eval"))return Ne.set(a,"run_eval"),"run_eval";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return Ne.set(a,"project_model"),"project_model"}async function no(a,u){let R=[];for await(let D of a)R.push(typeof D=="string"?Buffer.from(D):D);let m;if(R.length>0)try{m=JSON.parse(Buffer.concat(R).toString("utf-8")).serverUrl}catch{}let k=[];f.claude?.available&&f.claude.mcp&&!f.claude.mcp.found&&k.push(await kr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&k.push(await Rr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&k.push(await Pr(m,f.copilot.path??b));let[w,j,C]=await Promise.all([go(r),yo(r),vo(r,f.copilot?.path??b)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=C),M(u,200,{results:k,capabilities:{providers:f}})}async function pn(a,u){let R=[];for await(let j of a)R.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){M(u,400,{error:"Missing or invalid name"});return}let k=await q.recordDirectModelMutation({key:`components.${m.name}`,value:{description:""},claim:`${m.name} is an explicitly governed component in the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let w=await Ue({decisionId:k.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});M(u,200,{added:!0,alreadyExists:!1,...k,evalId:w})}async function Ps(a,u){let R=[];for await(let j of a)R.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){M(u,400,{error:"Missing or invalid name"});return}let k=await q.recordDirectModelMutation({key:`components.${m.name}`,value:null,claim:`${m.name} is not governed as a component in the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let w=await Ue({decisionId:k.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});M(u,200,{removed:!0,...k,evalId:w})}async function Ts(a,u){let R=[];for await(let C of a)R.push(typeof C=="string"?Buffer.from(C):C);let m;try{m=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){M(u,400,{error:"Missing or invalid path/value"});return}let k=m.value;try{let C=JSON.parse(m.value);C&&typeof C=="object"&&(k=C)}catch{}let w=await q.recordDirectModelMutation({key:`tokens.${m.path}`,value:k,claim:`${m.path} uses ${m.value} in the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let j=await Ue({decisionId:w.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});M(u,200,{updated:!0,...w,evalId:j})}async function js(a,u){let R=[];for await(let j of a)R.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){M(u,400,{error:"Missing or invalid path"});return}let k=await q.recordDirectModelMutation({key:`tokens.${m.path}`,value:null,claim:`${m.path} is intentionally absent from the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let w=await Ue({decisionId:k.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});M(u,200,{removed:!0,...k,evalId:w})}function Es(a,u){let R=i??"http://localhost:3000";if(!i){let k=a.headers.referer||a.headers.origin;if(k)try{let w=new URL(typeof k=="string"?k:k[0]||"");(w.hostname==="localhost"||w.hostname==="127.0.0.1")&&(R=w.origin)}catch{}}let m=Wo(h,R);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Ms(a){let u=Date.now();if(rt&&u<rt.expires){M(a,200,rt.data);return}try{let{scanForComponents:R}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:m}=await import("./render-generator-EANIDD2E.mjs"),k=await R(r);rt={data:k,expires:u+5e3},m(k,r,Ft).then(w=>{Ft=w}).catch(w=>console.warn("[Bridge] Render generation failed:",w)),M(a,200,k)}catch(R){console.error("[Bridge] Scanner error:",R),M(a,500,{error:"Failed to scan components"})}}async function As(a){let u=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let R=zc(import.meta.url);u.unshift(Me(Lc(R),"canvas.mjs"))}catch{}for(let R of u)try{let m=await Bo(R,"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),M(a,404,{error:"Canvas bundle not found"})}async function _s(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){M(u,400,{error:"Invalid filename"});return}try{let R=[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 R)try{m=await Bo(j);break}catch{}if(!m)throw new Error("File not found");let k=a.split(".").pop()?.toLowerCase(),w=k==="png"?"image/png":k==="webp"?"image/webp":k==="jpg"||k==="jpeg"?"image/jpeg":"application/octet-stream";u.writeHead(200,{"Content-Type":w,"Cache-Control":"public, max-age=3600"}),u.end(m)}catch{M(u,404,{error:"File not found"})}}function un(a){return`/files/${Qn(a)}`}async function $s(a,u){let R=await G.getThread(a);if(!R){M(u,404,{error:"Thread not found"});return}let m=R.messages.some($=>$.role==="assistant"&&$.responseText?.includes("<eval_run_result>")),k=R.messages.filter($=>$.role==="assistant"&&$.responseText?.includes("Model suggestion ready")),[w,j]=await Promise.all([m?q.getJournalEvalRuns().then($=>$.filter(O=>O.threadId===a).sort((O,Q)=>Q.completedAt-O.completedAt)[0]):Promise.resolve(void 0),k.length>0?V.findModelProposalsByThread(a):Promise.resolve([])]),C=w?await q.findJournalEvalCase(w.evalId):null,D=await Promise.all(j.map(async($,O)=>{if($.authorityStatus==="accepted")return $;let Q=(await Promise.all($.decisionIds.map(U=>q.findPendingProposalForLegacyDecision(U)))).find(Boolean);return{...$,authorityStatus:"legacy_untrusted",presentationJobId:$.presentationJobId??k[O]?.jobId??k.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),L=[...D].sort(($,O)=>O.updatedAt-$.updatedAt)[0]??null,F=R.messages.map(({screenshotPath:$,screenshotPaths:O,imagePaths:Q,replyImagePaths:U,...ie})=>({...ie,...ie.role==="assistant"&&w&&ie.responseText?.includes("<eval_run_result>")?{evalRun:{...w,title:C?.title}}:{},...$?{screenshotUrl:un($)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,re])=>[ae,un(re)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ae,re])=>[ae,re.map(un)]))}:{},...U?{replyImageUrls:U.map(un)}:{}}));M(u,200,{id:R.id,createdAt:R.createdAt,messages:F,modelProposal:L,modelProposals:D})}async function Cs(a,u){let R=decodeURIComponent(a);if(!await G.deleteThread(R)){M(u,404,{deleted:!1,error:"Thread not found"});return}M(u,200,{deleted:!0})}let zo=9,qo=!1;for(let a=n;a<n+zo;a++)try{await od(St,a),h=a,qo=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(u){if(u.code==="EADDRINUSE"){let R=await nd(a);if(as(R,{projectId:s,version:dn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!qo)throw new Error(`[Bridge] All ports ${n}\u2013${n+zo-1} in use`);for(let[a,u]of Object.entries(f))!u.available||!u.path||x(a,u.path).then(R=>{if(R)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 Y)Yn(m,{type:"capabilities_changed",data:{}})}});let Os=setInterval(()=>{xs(c).catch(()=>{})},Wc),Uo=setInterval(()=>{B.expireStale().becameEmpty&&he()},Gc);return Uo.unref?.(),{port:h,projectId:s,close:async()=>{clearInterval(Os),clearInterval(Uo),ne(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{St.close(()=>a())})}}}async function xs(o){try{let e=await Oc(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let s=await Jc(r);n-s.mtimeMs>Hc&&await Nc(r)}catch{}}}catch{}}var ye="\x1B[35m[popmelt]\x1B[0m";async function dd(){let o=process.argv.slice(2);if(o[0]==="memory"){await pd(o.slice(1));return}if(o[0]==="wrap"){let e=o.indexOf("--");(e===-1||e===o.length-1)&&(console.error(`${ye} Usage: popmelt wrap -- <dev command>`),console.error(`${ye} Example: popmelt wrap -- next dev`),console.error(`${ye} Example: popmelt wrap -- astro dev`),process.exit(1));let n=o.slice(e+1);await fd(n);return}if(o[0]==="bridge"){await ud();return}if(o[0]==="stop"){await md();return}console.log(`${ye} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(" popmelt memory import Analyze legacy project memory"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}function Nt(o,e){let n=o.indexOf(e);return n>=0?o[n+1]:void 0}function ld(){console.log(`${ye} Memory commands`),console.log(""),console.log(" popmelt memory import [--project <path>] [--project-key <key>] [--json]"),console.log(" popmelt memory review --subject <hint> [--action <text>] [--project <path>] [--json]"),console.log(""),console.log("The import command is analysis-only. It does not modify legacy or canonical storage."),console.log("Future namespace: memory inspect, verify, export, and commit.")}async function pd(o){if(o[0]!=="import"&&o[0]!=="review"){ld(),o.length>0&&o[0]!=="help"&&o[0]!=="--help"&&(process.exitCode=1);return}if(o.includes("--write")||o.includes("--commit"))throw new Error("Legacy import is currently read-only; --write and --commit are not supported.");let e=Nt(o,"--project")??process.cwd(),n=Nt(o,"--project-key"),t=await wt({projectRoot:e,projectKey:n});if(o[0]==="review"){let c=Nt(o,"--subject");if(!c)throw new Error("memory review requires --subject <hint>");let d=Qt(t.bundle,{subjectHints:[c],action:Nt(o,"--action"),maxPackets:Number(Nt(o,"--max-packets")??3),maxEstimatedTokens:Number(Nt(o,"--max-tokens")??1200)});if(o.includes("--json")){console.log(JSON.stringify(d,null,2));return}console.log(`${ye} Contextual memory review (read-only)`),console.log(`${ye} Subject: ${c}`),console.log(`${ye} Matches: ${d.subjectMatches.length}; packets: ${d.packets.length}; status: ${d.completeness.status}`),d.uncertainty&&console.log(`${ye} Uncertainty: ${d.uncertainty}`);for(let[l,g]of d.packets.entries())console.log(""),console.log(`${l+1}. ${g.proposal.claim}`),console.log(` Authority: ${g.authority}; presentation: ${g.presentation}; implementation: ${g.implementation.state}`),console.log(` Why now: ${g.trigger.reason}`),console.log(` Proposal: ${g.proposal.id}`);return}if(o.includes("--json")){console.log(JSON.stringify(t.report,null,2));return}let r=t.report,s=r.proofCases.filter(c=>c.threadFound).length,i=r.schemaIssues.filter(c=>c.severity==="error");if(console.log(`${ye} Legacy memory analysis (read-only)`),console.log(`${ye} Project: ${r.projectRoot}`),console.log(`${ye} Source: ${r.source.threads} threads, ${r.source.messages} messages, ${r.source.decisionEnvelopes} decision envelopes`),console.log(`${ye} Imported: ${Object.entries(r.imported).map(([c,d])=>`${d} ${c}`).join(", ")}`),console.log(`${ye} Acceptance unresolved: ${r.unresolvedAcceptance}`),console.log(`${ye} Model values deferred: ${r.deferredModelEntries}`),console.log(`${ye} Proof coverage: ${s}/${r.proofCases.length} threads found`),console.log(`${ye} Schema validation: ${i.length===0?"passed":`${i.length} errors`}`),r.issues.length){let c=new Map;for(let d of r.issues)c.set(d.code,(c.get(d.code)??0)+1);console.log(`${ye} Review flags: ${[...c].map(([d,l])=>`${d}=${l}`).join(", ")}`)}}async function ud(){let o=await Lo({projectRoot:process.cwd()});console.log(`${ye} Bridge running on http://localhost:${o.port}`),await new Promise(e=>{let n=async()=>{console.log(`
239
+ ${ye} Shutting down bridge...`),await o.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function md(){let o=cd(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await id(o,"utf8"))}catch{console.log(`${ye} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${ye} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${ye} Bridge process ${e.pid} already dead`);else throw n}try{await ad(o)}catch{}}async function fd(o){let e=await Lo({projectRoot:process.cwd()});console.log(`${ye} Bridge running on http://localhost:${e.port}`);let[n,...t]=o;console.log(`${ye} Starting: ${o.join(" ")}`);let r=sd(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),s=i=>{r.kill(i)};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM")),r.on("exit",async(i,c)=>{await e.close(),c?process.kill(process.pid,c):process.exit(i??0)})}dd().catch(o=>{console.error(`${ye} Fatal:`,o),process.exit(1)});