@popmelt.com/core 0.8.3 → 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.
@@ -1,4 +1,4 @@
1
- import{mkdir as $r,unlink as _r,writeFile as Or}from"fs/promises";import{join as jn}from"path";import{execFileSync as ct,spawn as _n}from"child_process";import{createHash as ar,randomUUID as xe}from"crypto";import{mkdir as lr,readFile as On,readdir as cr,realpath as dr,stat as ur,unlink as pr,writeFile as Fe}from"fs/promises";import{createServer as fr}from"http";import{tmpdir as hr}from"os";import{basename as at,dirname as mr,join as ye}from"path";import{fileURLToPath as gr}from"url";function At(s,e){return`<!DOCTYPE html>
1
+ import{mkdir as cd,unlink as dd,writeFile as ld}from"fs/promises";import{join as ks}from"path";import{execFileSync as Qn,spawn as us}from"child_process";import{createHash as Is,randomUUID as lt}from"crypto";import{mkdir as Jc,readFile as Jo,readdir as Nc,realpath as Bc,stat as Fc,unlink as Lc,writeFile as an}from"fs/promises";import{createServer as zc}from"http";import{tmpdir as qc}from"os";import{basename as Gn,dirname as Uc,isAbsolute as No,join as Me,relative as ms,resolve as bs}from"path";import{fileURLToPath as Wc}from"url";function zo(o,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -18,105 +18,50 @@ import{mkdir as $r,unlink as _r,writeFile as Or}from"fs/promises";import{join as
18
18
  }}
19
19
  </script>
20
20
  <script type="module">
21
- import { mountCanvas } from 'http://localhost:${s}/canvas/app.mjs';
21
+ import { mountCanvas } from 'http://localhost:${o}/canvas/app.mjs';
22
22
  mountCanvas(document.getElementById('root'), {
23
23
  devOrigin: '${e}',
24
- bridgeOrigin: 'http://localhost:${s}',
24
+ bridgeOrigin: 'http://localhost:${o}',
25
25
  });
26
26
  </script>
27
27
  </body>
28
- </html>`}import{spawn as xs}from"child_process";import{createInterface as bs}from"readline";var Ps=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"]),Ct=1e5;function Is(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ps.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>Ct?t.slice(0,Ct)+`
29
- \u2026[truncated]`:t}function Ue(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:b,timeoutMs:E=3e5,onEvent:F}=e,D=[];f?D.push("--resume",f,"-p",n):D.push("-p",n),D.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),v&&D.push("--model",v),b&&D.push("--effort",b);for(let w of a)D.push("--allowedTools",w);let H=xs(l,D,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),U=new Promise(w=>{let G,Y=[],q=[],V=[],J=!1,K="",N,$,k=!1,m=setTimeout(()=>{k=!0,H.kill("SIGTERM"),setTimeout(()=>{try{H.kill("SIGKILL")}catch{}},5e3)},E),A=bs({input:H.stdout}),T=new Set;A.on("line",L=>{if(L.trim())try{let _=JSON.parse(L);_.session_id&&!G&&(G=_.session_id);let Z=_.type??(_.event?.type?`event.${_.event.type}`:"unknown");if(T.add(Z),_.type==="result"&&_.result&&Y.length===0){let z=typeof _.result=="string"?_.result:"";z&&(Y.push(z),F?.({type:"delta",jobId:s,text:z},s))}if(_.type==="assistant"&&Array.isArray(_.message?.content)){typeof _.error=="string"&&(N=_.error);for(let z of _.message.content){if(z.type==="text"&&z.text&&(Y.push(z.text),F?.({type:"delta",jobId:s,text:z.text},s)),z.type==="tool_use"&&z.name){let ne=z.input?.file_path||z.input?.path||void 0,pe=Is(z);if(F?.({type:"tool_use",jobId:s,tool:z.name,...ne?{file:ne}:{},...pe?{content:pe}:{}},s),z.name==="Edit"&&z.input?.file_path){let fe={tool:"Edit",file_path:z.input.file_path,old_string:z.input.old_string,new_string:z.input.new_string,replace_all:z.input.replace_all};q.push(fe),V.push({sequence:V.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 z.name==="Write"&&z.input?.file_path&&(q.push({tool:"Write",file_path:z.input.file_path,content:z.input.content}),V.push({sequence:V.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:z.input.file_path,content:typeof z.input.content=="string"?z.input.content:void 0}))}z.type==="thinking"&&z.thinking&&F?.({type:"thinking",jobId:s,text:z.thinking},s)}}_.type==="result"&&_.is_error===!0&&(J=!0,typeof _.error=="string"&&(N=_.error),typeof _.result=="string"&&($=_.result)),_.type==="user"&&_.tool_use_result?.file?.filePath&&F?.({type:"tool_use",jobId:s,tool:"Read",file:_.tool_use_result.file.filePath},s)}catch{}});let x=[];H.stderr?.on("data",L=>{x.push(L.toString())}),H.on("close",L=>{if(clearTimeout(m),A.close(),Y.length===0&&T.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...T].join(", ")}`),k)J=!0,K=`Timed out after ${Math.round(E/6e4)} minutes`;else if(L!==0&&L!==null){J=!0;let Z=x.join("").trim(),z=Y.join("").trim(),ne=Y.length===0&&T.size>0?` (no text captured, event types: ${[...T].join(", ")})`:"";K=Z||$||z||`Claude process exited with code ${L}${ne}`}J&&!K&&$&&(K=$);let _=ks(K,N);w({sessionId:G,text:Y.join(""),success:!J,error:J?_.message:void 0,errorCode:J?_.code:void 0,recoverableError:J?_.recoverable:void 0,fileEdits:q.length>0?q:void 0,editEvents:V.length>0?V:void 0})}),H.on("error",L=>{clearTimeout(m),J=!0,K=L.message,w({sessionId:G,text:Y.join(""),success:!1,error:K,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:q.length>0?q:void 0,editEvents:V.length>0?V:void 0})})});return{process:H,result:U}}function ks(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 Ms,spawnSync as Jt}from"child_process";import{readFileSync as Rs,statSync as Es}from"fs";import{basename as Ts,extname as As,isAbsolute as Cs,relative as zt,resolve as $s}from"path";import{createInterface as _s}from"readline";function $t(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var _t=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"]),pt=2e5,Os=1e5,Ft=2e5;function Bt(s){let e=Ts(s).toLowerCase(),n=As(s).toLowerCase();return _t.has(n)||_t.has(e)}function jt(s,e){let n=Cs(e)?e:$s(s,e),t=zt(s,n);return t===""||t.startsWith("..")?null:n}function We(s,e){if(!Bt(e))return;let n=jt(s,e);if(n)try{let t=Es(n);return t.isFile()?t.size>pt?{exists:!0,truncated:!0}:{exists:!0,content:Rs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Ds(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Ns(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 Ot(s){return Ds(s,["patch","diff","unifiedDiff","unified_diff"])}function ft(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function Dt(s,e){let n=Jt("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Ft+65536});return n.status!==0?null:n.stdout??""}function Js(s){let e=new Set;for(let n of s.split(`
30
- `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let o=t.split(" -> ");for(let i of o)i&&e.add(i)}return[...e]}function Nt(s){let e=Dt(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Dt(s,["diff","--no-ext-diff","HEAD","--"])??"",t=ft(n,Ft);return{status:e,changedFiles:Js(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function zs(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Fs(s,e){if(!Bt(e))return;let n=jt(s,e);if(!n)return;let t=zt(s,n);if(t===""||t.startsWith(".."))return;let o=Jt("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:pt+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=ft(i,pt);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function Bs(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Fs(s,t),i=We(s,t);return{filePath:t,...o?{before:o}:{},...i?{after:i}:{}}})}function He(s,e){let{prompt:n,projectRoot:t,screenshotPath:o,resumeSessionId:i,model:a,onEvent:l,sandboxMode:f="workspace-write",configOverrides:v=[]}=e,b=[];if(i){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${f}"`);for(let D of v)b.push("-c",D);a&&b.push("-m",a),b.push(i),b.push(n),o&&b.push("--image",o)}else{b.push("exec","--skip-git-repo-check","--json","--sandbox",f);for(let D of v)b.push("-c",D);a&&b.push("-m",a),b.push(n),o&&b.push("--image",o)}let E=Ms("codex",b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),F=new Promise(D=>{let H,U=[],w=[],G=[],Y=new Map,q=new Map,V=!1,J="",K=_s({input:E.stdout}),N=new Set;K.on("line",k=>{if(k.trim())try{let m=JSON.parse(k),A=m.type??"unknown";if(N.add(A),A==="thread.started"&&m.thread_id&&!H&&(H=m.thread_id),(A==="item.agentMessage.delta"||A==="item/agentMessage/delta")&&m.delta?.text&&(U.push(m.delta.text),l?.({type:"delta",jobId:s,text:m.delta.text},s)),(A==="item.reasoning.delta"||A==="item/reasoning/delta")&&m.delta?.text&&l?.({type:"thinking",jobId:s,text:m.delta.text},s),(A==="item.started"||A==="item/started")&&m.item){let T=m.item.type;if(T==="command_execution"){let x=m.item.command,L=x?$t(x):void 0,_=Nt(t),Z=new Map;for(let ne of _?.changedFiles??[])Z.set(ne,We(t,ne));typeof m.item.id=="string"&&q.set(m.item.id,{...x?{rawCommand:x}:{},...L?{command:L}:{},..._?{beforeWorktree:_}:{},beforeSnapshots:Z});let z=L?`Bash: ${L.split(`
31
- `)[0].slice(0,80)}`:"Bash";w.push(z),l?.({type:"tool_use",jobId:s,tool:"Bash",...L?{content:L}:{}},s)}else if(T==="file_change"){let x=m.item.filename||m.item.path;x&&!Y.has(x)&&Y.set(x,We(t,x)),w.push(x?`Edit ${x.split("/").pop()}`:"Edit"),l?.({type:"tool_use",jobId:s,tool:"Edit",...x?{file:x}:{}},s)}else if(T==="file_read"){let x=m.item.filename||m.item.path;w.push(x?`Read ${x.split("/").pop()}`:"Read"),l?.({type:"tool_use",jobId:s,tool:"Read",...x?{file:x}:{}},s)}else if(T==="web_search")w.push("WebSearch"),l?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if(T==="mcp_tool_call"){let x=m.item.tool_name||m.item.name||"MCP";w.push(x),l?.({type:"tool_use",jobId:s,tool:x},s)}}if((A==="item.completed"||A==="item/completed")&&m.item){if(m.item.type==="agent_message"){let T=m.item.text;typeof T=="string"&&T&&(U.push(T),l?.({type:"delta",jobId:s,text:T},s))}else if(m.item.type==="reasoning"){let T=m.item.text;typeof T=="string"&&T&&l?.({type:"thinking",jobId:s,text:T},s)}else if(m.item.type==="file_change"&&Array.isArray(m.item.changes))for(let T of m.item.changes){let x=T.path||T.filename,L=T.kind==="add"?"Write":"Edit";if(x){w.push(`${L} ${x.split("/").pop()}`),l?.({type:"tool_use",jobId:s,tool:L,file:x},s);let _=T,Z=typeof _.kind=="string"?_.kind:void 0,z=Ns(Z),ne=Y.get(x),pe=We(t,x);G.push({sequence:G.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:z,filePath:x,...ne?{before:ne}:{},...pe?{after:pe}:{},...Ot(_)?{patch:Ot(_)}:{},...Z?{rawKind:Z}:{}}),Y.set(x,pe)}}else if(m.item.type==="command_execution"){let T=typeof m.item.id=="string"?m.item.id:void 0,x=T?q.get(T):void 0,L=typeof m.item.command=="string"?m.item.command:x?.rawCommand,_=L?$t(L):x?.command,Z=Nt(t);if(zs(x?.beforeWorktree,Z)){let z=[...new Set([...x?.beforeWorktree?.changedFiles??[],...Z?.changedFiles??[]])],ne=typeof m.item.aggregated_output=="string"?ft(m.item.aggregated_output,Os):void 0,pe=typeof m.item.exit_code=="number"?m.item.exit_code:m.item.exit_code===null?null:void 0,fe=typeof m.item.status=="string"?m.item.status:void 0;G.push({sequence:G.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...L?{rawCommand:L}:{},..._?{command:_}:{},...pe!==void 0?{exitCode:pe}:{},...fe?{status:fe}:{},...ne?{output:ne.text}:{},...ne?.truncated?{outputTruncated:!0}:{},...x?.beforeWorktree?{beforeWorktree:x.beforeWorktree}:{},...Z?{afterWorktree:Z}:{},...z.length>0?{touchedFiles:Bs(t,z,x?.beforeSnapshots??new Map)}:{}})}T&&q.delete(T)}}A==="turn.failed"&&(V=!0,J=m.error?.message||m.message||"Turn failed")}catch{}});let $=[];E.stderr?.on("data",k=>{$.push(k.toString())}),E.on("close",k=>{K.close(),U.length===0&&N.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...N].join(", ")}`),k!==0&&k!==null&&(V=!0,J=$.join("")||`Codex process exited with code ${k}`),D({sessionId:H,text:U.join(""),success:!V,error:V?J:void 0,editEvents:G.length>0?G:void 0,toolsUsed:w.length>0?w:void 0})}),E.on("error",k=>{V=!0,J=k.message,D({sessionId:H,text:U.join(""),success:!1,error:J,editEvents:G.length>0?G:void 0,toolsUsed:w.length>0?w:void 0})})});return{process:E,result:F}}import{spawn as js}from"child_process";import{createInterface as Ls}from"readline";function Lt(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 Ut(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 b=js(f,v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),E=new Promise(F=>{let D,H=[],U=[],w=!1,G="",Y=!1,q=setTimeout(()=>{Y=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},a),V=Ls({input:b.stdout}),J=new Set,K=[];V.on("line",$=>{if($.trim())try{let k=JSON.parse($),m=Ee(k);J.add(m),K.length<5&&Ws(m)&&K.push($.slice(0,800));let A=Re(k,["sessionId","session_id","id"],["session","conversation","thread"]);A&&!D&&(D=A);let T=Us(k,H.length===0);T&&(H.push(T),l?.({type:"delta",jobId:s,text:T},s));let x=Hs(k);x&&l?.({type:"thinking",jobId:s,text:x},s);let L=Gs(k);L&&(U.push(L.label),l?.({type:"tool_use",jobId:s,tool:L.tool,...L.file?{file:L.file}:{},...L.content?{content:L.content}:{}},s));let _=qs(k);_&&(w=!0,G=_)}catch{}});let N=[];b.stderr?.on("data",$=>{N.push($.toString())}),b.on("close",$=>{clearTimeout(q),V.close(),H.length===0&&J.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...J].join(", ")}`),K.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${K.join(`
32
- `)}`)),Y?(w=!0,G=`Timed out after ${Math.round(a/6e4)} minutes`):$!==0&&$!==null&&(w=!0,G=N.join("").trim()||G||`Copilot process exited with code ${$}`);let k=w?Lt(G,i):null;F({sessionId:D,text:H.join(""),success:!w,error:k?.message,errorCode:k?.code,recoverableError:k?.recoverable,provider:"copilot",toolsUsed:U.length>0?U:void 0})}),b.on("error",$=>{clearTimeout(q);let k=Lt($.message,i);F({sessionId:D,text:H.join(""),success:!1,error:k.message,errorCode:k.code,recoverableError:k.recoverable,provider:"copilot",toolsUsed:U.length>0?U:void 0})})});return{process:b,result:E}}function Ee(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 Us(s,e=!1){let n=Ee(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"&&ht(s))return s.text;if(typeof s.message=="string"&&ht(s))return s.message;if(typeof s.delta=="string"&&ht(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 Ws(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function Hs(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 Gs(s){let e=Re(s,["tool","toolName","tool_name","name"]),n=Re(s,["command","cmd"]),t=Re(s,["file","path","filename","filePath"]),o=Ee(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
- `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let i=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function qs(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"&&Ee(s).toLowerCase().includes("error"))return s.message}function Re(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=Re(o,e);if(i)return i}}function ht(s){let e=Ee(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{execFile as Qs}from"child_process";import{copyFile as Wt,mkdir as Ht,readdir as Xs,readFile as Ys,writeFile as Vs}from"fs/promises";import{join as be}from"path";var Ge=class{constructor(e){this.projectRoot=e;let n=be(e,".popmelt");this.decisionsDir=be(n,"decisions"),this.screenshotsDir=be(n,"screenshots")}async persist(e,n,t){try{await Ht(this.decisionsDir,{recursive:!0}),await Ht(this.screenshotsDir,{recursive:!0});try{await Wt(n,be(this.screenshotsDir,`s-${e.id}.webp`))}catch{}for(let o=0;o<t.length;o++)try{let i=e.pastedImagePaths[o];i&&await Wt(t[o],be(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await Vs(be(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 Xs(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 Ys(be(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=>{Qs("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as Te,readFile as Gt,writeFile as Ae}from"fs/promises";import{join as Ce}from"path";var Ks=80,Zs=24,qt=1e3,qe=class{constructor(e){this.evalsDir=Ce(e,".popmelt","evals"),this.suitePath=Ce(this.evalsDir,"evals.json"),this.runsPath=Ce(this.evalsDir,"runs.json"),this.screenshotsDir=Ce(this.evalsDir,"screenshots")}async loadSuite(){try{let e=await Gt(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 Gt(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 Te(this.evalsDir,{recursive:!0}),await Ae(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 Te(this.evalsDir,{recursive:!0}),await Ae(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 Te(this.evalsDir,{recursive:!0}),await Ae(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 Te(this.evalsDir,{recursive:!0}),await Ae(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await Te(this.screenshotsDir,{recursive:!0}),await Ae(Ce(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 Qt(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?Vt(t):null}catch{return null}}function Xt(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?Vt(t,"pending"):null}catch{return null}}function Yt(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=ro(t.assertionResults,e),i=io(o);return{status:i,summary:ge(t.summary)||tn(i),assertionResults:o,tooling:ao(t.tooling)}}catch{}return{status:"needs_review",summary:Qe(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 Vt(s,e="approved"){let n=[];return s.forEach((t,o)=>{if(!t||typeof t!="object")return;let i=t,a=ge(i.title),l=ge(i.prompt),f=ge(i.rationale),v=ke(i.assertions);if(!a||!l||v.length===0)return;let b=no(i.category),E=lo(ge(i.id))||`eval-${nn(a).slice(0,32)||o+1}`,F=so(i.status)??e;n.push({id:E,title:a,status:F,category:b,prompt:l,assertions:v,rationale:f||"Inferred from Popmelt design history.",sourceDecisionIds:ke(i.sourceDecisionIds),sourceThreadIds:ke(i.sourceThreadIds)})}),n}function Kt(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,Ks),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,Zs);return`You are helping a designer turn organic Popmelt annotation history into a project eval suite.
34
-
35
- The designer does NOT work eval-first. They use annotations and conversation threads to zhuzh the UI over time. Your job is to infer useful eval proposals from that trail. The developer will reject, refine, or approve proposals in this thread. Do not write files or run commands.
36
-
37
- ## Current Design Model
38
- \`\`\`json
39
- ${JSON.stringify(s.model??null,null,2)}
40
- \`\`\`
41
-
42
- ## Existing Eval Suite
43
- \`\`\`json
44
- ${JSON.stringify(s.existingSuite,null,2)}
45
- \`\`\`
46
-
47
- ## Recent Decisions
48
- ${e.map(eo).join(`
49
-
50
- `)||"No decisions found."}
51
-
52
- ## Recent Threads
53
- ${n.map(to).join(`
54
-
55
- `)||"No threads found."}
56
-
57
- ## Instructions
58
- 1. Infer evals that encode reusable taste, design judgment, product behavior, or interaction expectations.
59
- 2. Prefer proposals backed by multiple decisions, rich thread context, or explicit approved/resolved outcomes.
60
- 3. Avoid one-off implementation chores, temporary bug fixes, vague preferences, or evals that cannot be checked later.
61
- 4. Cite source decision ids and thread ids for each proposal.
62
- 5. Present proposals as clear text first. Group them by Component, Layout, Copy, Interaction, Visual, and Workflow.
63
- 6. Ask the developer what to approve, reject, or adjust.
64
- 7. Include a machine-readable <eval_proposals> block containing the same proposals as pending eval JSON. These will be saved as draft proposals for panel review.
65
- 8. Tell the developer that the proposals have been saved to the Eval panel for accept/reject review.
66
- 9. Do NOT output an <evals> block yet. First get the developer's approval.
67
-
68
- ## After Approval
69
- When the developer approves or asks you to save the final set, output a complete JSON array inside <evals> tags. Each object must use this shape:
70
-
71
- \`\`\`json
72
- {
73
- "id": "eval-short-stable-id",
74
- "title": "Short human-readable name",
75
- "status": "approved",
76
- "category": "component",
77
- "prompt": "The eval instruction an agent should satisfy.",
78
- "assertions": ["Observable expectation 1", "Observable expectation 2"],
79
- "rationale": "Why this eval represents the designer's taste.",
80
- "sourceDecisionIds": ["decision-id"],
81
- "sourceThreadIds": ["thread-id"]
82
- }
83
- \`\`\`
84
-
85
- Allowed categories: component, layout, copy, interaction, visual, workflow.
86
- Return only the <evals> block after approval.
87
-
88
- ## First Response Structured Block
89
- At the end of your first proposal response, output a JSON array inside <eval_proposals> tags using the same schema, but with "status": "pending".`}function Zt(s){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
28
+ </html>`}var Fs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ls=new Set(["default","flex","fast","priority"]);function ft(o){let e=typeof o.reasoningEffort=="string"&&Fs.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Ls.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function ln(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as zs}from"child_process";import{createInterface as qs}from"readline";var Us=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),qo=1e5;function Ws(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Us.has(n))return;let t;if(o.name==="Write"&&typeof o.input?.content=="string"?t=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(t=o.input.new_string),!!t)return t.length>qo?t.slice(0,qo)+`
29
+ \u2026[truncated]`:t}function pn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:v,timeoutMs: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),v&&I.push("--effort",v);for(let h of i)I.push("--allowedTools",h);let g=zs(c,I,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(h=>{let f,y=[],x=[],S=[],A=!1,J="",_,N,T=!1,B=setTimeout(()=>{T=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},P),W=qs({input:g.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&&y.length===0){let Y=typeof oe.result=="string"?oe.result:"";Y&&(y.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&&(y.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=Ws(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=[];g.stderr?.on("data",ne=>{H.push(ne.toString())}),g.on("close",ne=>{if(clearTimeout(B),W.close(),y.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=y.join("").trim(),G=y.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=Hs(J,_);h({sessionId:f,text:y.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})}),g.on("error",ne=>{clearTimeout(B),A=!0,J=ne.message,h({sessionId:f,text:y.join(""),success:!1,error:J,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})})});return{process:g,result:p}}function Hs(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 Gs,spawnSync as Ko}from"child_process";import{readFileSync as Vs,statSync as Ks}from"fs";import{basename as Qs,extname as Xs,isAbsolute as Ys,relative as Qo,resolve as Zs}from"path";import{createInterface as ei}from"readline";function Uo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Wo=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"]),eo=2e5,ti=1e5,Xo=2e5;function Yo(o){let e=Qs(o).toLowerCase(),n=Xs(o).toLowerCase();return Wo.has(n)||Wo.has(e)}function Lt(o,e){let n=Ys(e)?e:Zs(o,e),t=Qo(o,n);return t===""||t.startsWith("..")?null:n}function un(o,e){if(!Yo(e))return;let n=Lt(o,e);if(n)try{let t=Ks(n);return t.isFile()?t.size>eo?{exists:!0,truncated:!0}:{exists:!0,content:Vs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function ni(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function oi(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 Ho(o){return ni(o,["patch","diff","unifiedDiff","unified_diff"])}function to(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Go(o,e){let n=Ko("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Xo+65536});return n.status!==0?null:n.stdout??""}function ri(o){let e=new Set;for(let n of o.split(`
30
+ `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let s of r)s&&e.add(s)}return[...e]}function Vo(o){let e=Go(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Go(o,["diff","--no-ext-diff","HEAD","--"])??"",t=to(n,Xo);return{status:e,changedFiles:ri(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function si(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function ii(o,e){if(!Yo(e))return;let n=Lt(o,e);if(!n)return;let t=Qo(o,n);if(t===""||t.startsWith(".."))return;let r=Ko("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:eo+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=to(s,eo);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function ai(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):ii(o,t),s=un(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function mn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,v=[];if(s){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let I of l)v.push("-c",I);i&&v.push("-m",i),v.push(s),v.push(n),r&&v.push("--image",r)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let I of l)v.push("-c",I);i&&v.push("-m",i),v.push(n),r&&v.push("--image",r)}let P=Gs("codex",v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),b=new Promise(I=>{let g,p=[],h=[],f=[],y=new Map,x=new Map,S=!1,A="",J=ei({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&&!g&&(g=B.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),c?.({type:"delta",jobId:o,text:B.delta.text},o)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&B.delta?.text&&c?.({type:"thinking",jobId:o,text:B.delta.text},o),(W==="item.started"||W==="item/started")&&B.item){let te=B.item.type;if(te==="command_execution"){let H=B.item.command,ne=H?Uo(H):void 0,oe=Vo(t),he=new Map;for(let G of oe?.changedFiles??[])he.set(G,un(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(`
31
+ `)[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&&!y.has(H)&&y.set(H,un(t,H)),h.push(H?`Edit ${H.split("/").pop()}`:"Edit");let ne=H?Lt(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?Lt(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=Lt(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=oi(Y),q=y.get(H),fe=un(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}:{},...Ho(he)?{patch:Ho(he)}:{},...Y?{rawKind:Y}:{}}),y.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?Uo(ne):H?.command,he=Vo(t);if(si(H?.beforeWorktree,he)){let Y=[...new Set([...H?.beforeWorktree?.changedFiles??[],...he?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?to(B.item.aggregated_output,ti):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:ai(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:g,text:p.join(""),success:!S,error:S?A:void 0,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})}),P.on("error",T=>{S=!0,A=T.message,I({sessionId:g,text:p.join(""),success:!1,error:A,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})})});return{process:P,result:b}}import{spawn as ci}from"child_process";import{createInterface as di}from"readline";function Zo(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 er(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:s,timeoutMs:i=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),s&&l.push("--model",s),l.push("-p",n);let v=ci(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,g=[],p=[],h=!1,f="",y=!1,x=setTimeout(()=>{y=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},i),S=di({input:v.stdout}),A=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=qt(T);A.add(B),J.length<5&&pi(B)&&J.push(N.slice(0,800));let W=zt(T,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!I&&(I=W);let te=li(T,g.length===0);te&&(g.push(te),c?.({type:"delta",jobId:o,text:te},o));let H=ui(T);H&&c?.({type:"thinking",jobId:o,text:H},o);let ne=mi(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=fi(T);oe&&(h=!0,f=oe)}catch{}});let _=[];v.stderr?.on("data",N=>{_.push(N.toString())}),v.on("close",N=>{clearTimeout(x),S.close(),g.length===0&&A.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),J.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${J.join(`
32
+ `)}`)),y?(h=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(h=!0,f=_.join("").trim()||f||`Copilot process exited with code ${N}`);let T=h?Zo(f,s):null;b({sessionId:I,text:g.join(""),success:!h,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),v.on("error",N=>{clearTimeout(x);let T=Zo(N.message,s);b({sessionId:I,text:g.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:v,result:P}}function qt(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 li(o,e=!1){let n=qt(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 Le(o.delta)??Le(o.content)??Le(o.message);if(n==="assistant.message"&&e)return Le(o.message)??Le(o.content)??Le(o);if(n==="result"&&e)return Le(o.result)??Le(o.output)??Le(o.message)??Le(o);let s=o.content;if(s?.type==="text"&&typeof s.text=="string")return s.text;if(typeof o.text=="string"&&no(o))return o.text;if(typeof o.message=="string"&&no(o))return o.message;if(typeof o.delta=="string"&&no(o))return o.delta}function Le(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Le).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=Le(e[n]);if(t)return t}}function pi(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function ui(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 mi(o){let e=zt(o,["tool","toolName","tool_name","name"]),n=zt(o,["command","cmd"]),t=zt(o,["file","path","filename","filePath"]),r=qt(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
+ `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let s=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:s,label:`${s} ${t.split("/").pop()}`,file:t}}}function fi(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"&&qt(o).toLowerCase().includes("error"))return o.message}function zt(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(i=>t.toLowerCase().includes(i)))continue;let s=zt(r,e);if(s)return s}}function no(o){let e=qt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as hi,readFile as gi}from"fs/promises";import{join as oo}from"path";var fn=class{constructor(e){let n=oo(e,".popmelt");this.decisionsDir=oo(n,"decisions")}async listDecisionIds(){try{return(await hi(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 gi(oo(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 nr(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=ki(t.assertionResults,e),s=Ri(r);return{status:s,summary:et(t.summary)||ir(s),assertionResults:r,tooling:Pi(t.tooling)}}catch{}return{status:"needs_review",summary:Ti(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 or(o,e){let n=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length?[y.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(y=>y.path),s=[...new Set(r.map(y=>y.map(String).join(".")).filter(Boolean))].map(y=>({kind:"model_path",value:y}));if(s.length===0||o.decisionIds.length===0)return[];let i=new Set(o.decisionIds),c=new Set(s.map(y=>y.value)),d=e.cases.find(y=>y.status!=="rejected"&&(y.sourceDecisionIds.some(x=>i.has(x))||(y.dependencies??[]).some(x=>x.kind==="model_path"&&c.has(x.value)))),l=(o.selectedChanges??[]).find(y=>y.label?.trim())?.label?.trim()??t.find(y=>y.label?.trim())?.label?.trim()??o.title,v=d?.id.startsWith("eval-model-")??!1,P=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length>0?[{path:y.path,value:y.value,label:y.label,detail:y.detail}]:[]),I=(P.length>0?P:t.map(y=>({path:y.path,value:y.value,label:y.label,detail:y.rationale}))).flatMap(y=>yi(y,o.decisionIds)),g=gn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!v?d.assertions:[],...I,...I.length===0&&g?[g]:[]])],h=s[0].value,f=h.startsWith("components.")?"component":h.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!v?d.title:l,status:"pending",category:d?.category??f,prompt:d&&!v?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!v?d.rationale:Ii(h),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...s].map(y=>[`${y.kind}:${y.value}`,y])).values()]}]}function yi(o,e){let n=String(o.path[0]??"");if(n==="rules")return vi(o.value,e);if(n==="components"){let i=rr(String(o.path[1]??o.label??"component")),c=hn(o.value),d=c?Wt(c.usage):[];if(d.length>0){let v=bi(d),P=d.length===1?"uses":"use";return[`The ${v} ${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?et(c.constraint):"";if(l){let v=wi(l,i);if(v)return[v]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),c=hn(o.value),d=c&&"value"in c?c.value:o.value,l=xi(d);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=hn(o.value),r=t?et(t.text)||et(t.constraint):typeof o.value=="string"?o.value:"",s=gn(r||o.detail||"");return s?[s]:[]}function vi(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let c=hn(i),d=c?et(c.text):"";return d?[{text:d,sources:c?Wt(c.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(i=>gn(i.text)).filter(i=>!!i)}function wi(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?St(`Wherever ${Ut(n[1])}, the shared ${e} implementation is used instead of ${Ut(n[2])}`):gn(o)}function ro(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return St(`${tr(n[1])} is ${Ut(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return St(tr(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return St(`The product uses ${Ut(r[1])}`);let s=e.match(/^Do not (.+?)\.?$/i);return s?St(`The product does not ${Ut(s[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":St(e)}var gn=ro;function Ii(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${rr(e[1]??"component")} contract across its declared product surfaces.`:e[0]==="tokens"?`Protects the ${e.slice(1).join(".")} token from implementation drift.`:e[0]==="rules"?"Protects an enforceable product rule across its declared scope.":"Protects an enforceable product expectation across its declared scope."}function hn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function rr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function bi(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 xi(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function St(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function tr(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Ut(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function sr(o){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
90
34
 
91
35
  ## Eval
92
36
  \`\`\`json
93
- ${JSON.stringify(s.evalCase,null,2)}
37
+ ${JSON.stringify(o.evalCase,null,2)}
94
38
  \`\`\`
95
39
 
96
40
  ## Scope
97
41
  \`\`\`json
98
- ${JSON.stringify(s.scope,null,2)}
42
+ ${JSON.stringify(o.scope,null,2)}
99
43
  \`\`\`
100
44
 
101
45
  ## Current Design Model
102
46
  \`\`\`json
103
- ${JSON.stringify(s.model??null,null,2)}
47
+ ${JSON.stringify(o.model??null,null,2)}
104
48
  \`\`\`
105
49
 
106
50
  ## Evidence
107
- - Current page screenshot: ${s.screenshotPath}
108
- - Chrome DevTools MCP is ${s.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
51
+ - Current page screenshot: ${o.screenshotPath}
52
+ - Chrome DevTools MCP is ${o.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
109
53
 
110
54
  ## Instructions
111
- 1. Evaluate only the current page scope.
112
- 2. Use the screenshot as baseline evidence.
113
- 3. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
114
- 4. Judge each assertion independently as "pass", "fail", or "needs_review".
115
- 5. Keep failures actionable and grounded in observed evidence.
116
- 6. Do not propose visual markers yet.
117
- 7. End with exactly one machine-readable <eval_run_result> block.
118
- 8. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
119
- 9. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
55
+ 1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
56
+ 2. Compare the runtime URL, component evidence, and visible state with the eval's declared scenarios. If the runtime does not satisfy an applicable declared scenario, mark affected assertions "needs_review" and name the scope mismatch instead of guessing.
57
+ 3. Use the screenshot as baseline evidence.
58
+ 4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
59
+ 5. Judge each assertion independently as "pass", "fail", or "needs_review".
60
+ 6. Keep failures actionable and grounded in observed evidence.
61
+ 7. Do not propose visual markers yet.
62
+ 8. End with exactly one machine-readable <eval_run_result> block.
63
+ 9. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
64
+ 10. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
120
65
 
121
66
  The block must be valid JSON with this shape:
122
67
 
@@ -141,106 +86,42 @@ The block must be valid JSON with this shape:
141
86
  \`\`\`
142
87
 
143
88
  Allowed statuses: pass, fail, needs_review.
144
- Allowed chromeDevtools values: available, unavailable, unknown.`}function en(s){return`You are turning an approved Popmelt taste-model update into draft evals.
145
-
146
- The model is the source of truth. Evals are executable projections of model properties and values. Your job is to translate the approved model proposal into concrete, falsifiable eval proposals that a designer can review in the Eval panel.
89
+ Allowed chromeDevtools values: available, unavailable, unknown.`}function et(o){return typeof o=="string"?o.trim():""}function Wt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Si(o){let e=et(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function ki(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let s=r,i=et(s.assertion);return i?{assertion:i,status:Si(s.status)??"needs_review",summary:et(s.summary)||ir("needs_review"),evidence:Wt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Ri(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Pi(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=et(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Wt(e.evidenceTypes).length>0?Wt(e.evidenceTypes):["screenshot"]}}function ir(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 Ti(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as ji}from"crypto";import{mkdir as Mi,writeFile as Ei}from"fs/promises";import{join as so}from"path";var yn=class{constructor(e){this.root=so(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=so(this.root,"eval-screenshots"),t=ji("sha256").update(e).digest("hex"),r=so(n,`${t}.webp`);return await Mi(n,{recursive:!0}),await Ei(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as ar}from"crypto";import{mkdir as io,readFile as ao,writeFile as vn}from"fs/promises";import{dirname as co,join as kt}from"path";var We="[ProjectionWorker]",Ai={version:1,runs:[]},_i={version:1,updatedAt:0,proposals:[]},Ci=12;function $i(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 cr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function Oi(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Di(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let g of s){if(!g||typeof g!="object")continue;let p=g.sources;if(Array.isArray(p))for(let h of p)typeof h=="string"&&t.has(h)&&r.add(h)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,h=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(h)!==JSON.stringify(g)}).length,v=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},P=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(v[g])).length,I=Object.keys(c).filter(g=>JSON.stringify(c[g])!==JSON.stringify(P[g])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:I,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function Ji(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ni(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function wn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Ni(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=Ji(n)}function dr(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 Bi(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 Fi(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 lr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Bi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Fi(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var In=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=kt(e,".popmelt");this.runsPath=kt(t,"projection-runs.json"),this.legacyRunsPath=kt(t,"materialization-runs.json"),this.proposalsPath=kt(t,"projection-queue.json"),this.legacyProposalsPath=kt(t,"model-proposals.json"),this.modelPath=kt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ao(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=$i(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?dr(n,r):wn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Ci),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let s=r.map(g=>g.id);console.log(`${We} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),c=Ui(r,i),d=Oi(r,t.totalCandidateDecisionCount,c);n=ar().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:s,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let v=!0,P,b,I;try{let g=`projection-${Date.now()}`,{provider:p,result:h}=this.spawnModelAgent(g,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await h;if(!f.success)v=!1,P=f.error,console.error(`${We} ${p} spawn error:`,P);else{let y=qi(f.text,s);if(y){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of y)wn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=cr(x.rules));let S=Di(x,s,i);if(y){let J=[...new Set(y.flatMap(_=>_.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(_=>!J.includes(_))}b=S;let A=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:b,changes:y});I=A.id,console.log(`${We} Created model proposal ${A.id} for ${s.length} decision(s)`)}else v=!1,P="No valid bounded <model-changes> block found in response",console.error(`${We} ${P}`)}}catch(g){v=!1,P=g instanceof Error?g.message:String(g),console.error(`${We} Error:`,P)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:P,outputStats:b,proposalId:I}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:v,error:P}),{processedIds:s,success:v,error:P,runId:n,proposalId:I}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=cr(e.rules)),await vn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await io(co(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2)),n):{...Ai,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??{..._i,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let s=structuredClone(t);for(let i of r.changes??[])wn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?dr(i,d.path):wn(i,d.path,d.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let c=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(c.evalId),s.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:ar().slice(0,8),status:"pending",title:Li(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"}.`:zi(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 io(co(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await vn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await io(co(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await ao(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await ao(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return s==="codex"?{provider:"codex",...mn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:ln(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...pn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:s==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:i})})}};function Li(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 zi(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function qi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,c)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let d=i;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(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 v=Array.isArray(d.decisionIds)?d.decisionIds.filter(P=>typeof P=="string"&&r.has(P)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Ui(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
90
+ Kind: ${s.kind}
91
+ Claim: ${s.claim}
92
+ ${s.rationale?`Rationale: ${s.rationale}`:""}
93
+ Subjects: ${s.subjects.map(i=>`${i.role}:${i.subjectId}`).join(", ")}
94
+ Authority: ${s.authority.level}/${s.authority.mode}`).join(`
147
95
 
148
- Do not edit files or run commands.
149
-
150
- ## Approved Model Proposal
151
- \`\`\`json
152
- ${JSON.stringify({id:s.proposal.id,title:s.proposal.title,summary:s.proposal.summary,decisionIds:s.proposal.decisionIds,proposedModel:s.proposal.proposedModel},null,2)}
153
- \`\`\`
154
-
155
- ## Current Applied Model
156
- \`\`\`json
157
- ${JSON.stringify(s.currentModel??null,null,2)}
158
- \`\`\`
159
-
160
- ## Existing Eval Suite
161
- \`\`\`json
162
- ${JSON.stringify(s.existingSuite,null,2)}
163
- \`\`\`
164
-
165
- ## Instructions
166
- 1. Generate only evals that directly project the approved model proposal into observable checks.
167
- 2. Prefer a small number of durable evals over broad coverage. Avoid duplicates of existing evals.
168
- 3. Each eval should include concise assertions that can be judged on a page or codebase.
169
- 4. Set every generated eval status to "pending" so the designer can approve, edit, or reject it.
170
- 5. Cite the proposal's decision IDs in sourceDecisionIds.
171
- 6. End with exactly one <eval_proposals> block containing valid JSON.
172
-
173
- Each eval must use this shape:
174
-
175
- \`\`\`json
176
- {
177
- "id": "eval-short-stable-id",
178
- "title": "Short human-readable name",
179
- "status": "pending",
180
- "category": "component",
181
- "prompt": "The eval instruction an agent should satisfy.",
182
- "assertions": ["Observable expectation 1", "Observable expectation 2"],
183
- "rationale": "Why this eval projects the approved model value.",
184
- "sourceDecisionIds": ["decision-id"],
185
- "sourceThreadIds": ["${s.proposal.threadId??""}"]
186
- }
187
- \`\`\`
188
-
189
- Allowed categories: component, layout, copy, interaction, visual, workflow.
190
-
191
- <eval_proposals>
192
- []
193
- </eval_proposals>`}function eo(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
194
- `),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
195
- `),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
196
- Thread: ${s.threadId??"none"}
197
- Created: ${new Date(s.createdAt).toISOString()}
198
- URL: ${s.url||"unknown"}
199
- Instructions:
200
- ${Qe(o||"(none)",qt)}
201
- Resolutions:
202
- ${Qe(i||"(none)",qt)}
203
- Files: ${a.length>0?a.join(", "):"none"}`}function to(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}: ${Qe(o||i||"(no text)",500)}`}).join(`
204
- `);return`### Thread ${s.id}
205
- Messages: ${s.messages.length}
206
- Updated: ${new Date(s.updatedAt).toISOString()}
207
- ${n}`}function ge(s){return typeof s=="string"?s.trim():""}function ke(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function no(s){let e=ge(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function so(s){let e=ge(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function oo(s){let e=ge(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function ro(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=ge(i.assertion);return a?{assertion:a,status:oo(i.status)??"needs_review",summary:ge(i.summary)||tn("needs_review"),evidence:ke(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 io(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function ao(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=ge(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:ke(e.evidenceTypes).length>0?ke(e.evidenceTypes):["screenshot"]}}function tn(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 lo(s){return nn(s).slice(0,48)}function nn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Qe(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as sn}from"crypto";import{mkdir as mt,readFile as Xe,writeFile as Se}from"fs/promises";import{dirname as gt,join as $e}from"path";var ie="[Materializer]",on={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},co={version:1,runs:[]},uo={version:1,updatedAt:0,proposals:[]},po=12;function fo(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 _e(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(`${ie} 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(`${ie} Rule count ${e.length} exceeds cap of 30`),e}function ho(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function mo(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 go(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function yo(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 vo(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=yo(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=go(n)}function wo(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 Ye=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=$e(e,".popmelt");this.indexPath=$e(o,"materialized.json"),this.runsPath=$e(o,"materialization-runs.json"),this.proposalsPath=$e(o,"model-proposals.json"),this.modelPath=$e(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Xe(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=fo(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 Se(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ie} 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 Se(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ie} 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 Se(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ie} 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 Se(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ie} 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,po);return i.length>a.length&&console.log(`${ie} 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(U=>U.id);console.log(`${ie} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=Po(o,a),f=ho(o,t.totalCandidateDecisionCount,l);n=sn().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 b=!0,E,F,D;try{let U=`mat-${Date.now()}`,{provider:w,result:G}=this.spawnModelAgent(U,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});v={...v,provider:w},await this.persistRun(v);let Y=await G;if(!Y.success)b=!1,E=Y.error,console.error(`${ie} ${w} spawn error:`,E);else{let q=Ve(Y.text);if(q){Array.isArray(q.rules)&&(q.rules=_e(q.rules)),F=mo(q,i);let V=await this.createModelProposal({decisionIds:i,proposedModel:q,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});D=V.id,console.log(`${ie} Created model proposal ${V.id} for ${i.length} decision(s)`)}else b=!1,E="No <model> block found in response",console.error(`${ie} ${E}`)}}catch(U){b=!1,E=U instanceof Error?U.message:String(U),console.error(`${ie} Error:`,E)}let H=await this.loadIndex();return H.lastRunAt=Date.now(),H.lastRunDecisionIds=i,H.lastRunError=E??null,await this.persistIndex(H),await this.updateDecisionStates(i,b?"proposed":"failed",n,E),await this.persistRun({...v,status:b?"proposed":"failed",completedAt:Date.now(),error:E,outputStats:F,proposalId:D}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:b,error:E}),{processedIds:i,success:b,error:E,runId:n,proposalId:D}}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=Io(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(`${ie} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=Ve(a.text);return l?(Array.isArray(l.rules)&&(l.rules=_e(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await Se(this.modelPath,JSON.stringify(l,null,2)),console.log(`${ie} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${ie} 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(`${ie} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=_e(e.rules)),await Se(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ie} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await Xe(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={...on,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...on,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 mt(gt(this.indexPath),{recursive:!0}),await Se(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ie} Failed to write index:`,n)}}async loadRuns(){try{let e=await Xe(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...co,runs:[]}}async loadModelProposals(){try{let e=await Xe(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...uo,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?wo(i,l.path):vo(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:sn().slice(0,8),status:"pending",title:xo(e.proposedModel),summary:bo(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 mt(gt(this.proposalsPath),{recursive:!0}),await Se(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ie} 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 mt(gt(this.runsPath),{recursive:!0}),await Se(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${ie} 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",...He(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:So(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${ie} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Ue(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 So(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}function xo(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 bo(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 Ve(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 Po(s,e){let n=s.map(i=>{let l=i.resolutions.filter(b=>(b.finalScope??b.inferredScope)?.breadth==="pattern").map(b=>{let F=(b.finalScope??b.inferredScope)?.target??"unknown",D=b.filesModified?.join(", ")??"none";return`- **${b.summary}** [scope: pattern/${F}]
208
- Files modified: ${D}`}).join(`
209
- `),f=i.annotations.map(b=>b.instruction).filter(Boolean).join(`
210
- `),v=i.gitDiff?`
211
- \`\`\`diff
212
- ${i.gitDiff.slice(0,2e3)}
213
- \`\`\``:"";return`### Decision ${i.id} (${new Date(i.createdAt).toISOString()})
214
- Page: ${i.url}
215
- ${l}
216
- ${v}
217
- ${f?`
218
- Original instructions:
219
- ${f}`:""}`}).join(`
220
-
221
- `),t=s.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
96
+ `),t=o.map(s=>s.id);return`You are extracting a local design model from accumulated design decisions.
222
97
 
223
98
  ## Instructions
224
99
  1. Review the current model (if any) and the new decisions below.
225
- 2. Determine what design tokens, component patterns, and rules to add or update.
226
- 3. Output the complete updated model as a JSON object inside <model> tags.
227
- 4. Do not edit files or run commands. Return only the <model> block.
100
+ 2. Determine the smallest concrete set of design-token, component-pattern, and rule changes supported by those decisions.
101
+ 3. Attribute every change to one or more accepted decision IDs from this prompt.
102
+ 4. Output no more than 40 changes as a JSON array inside <model-changes> tags.
103
+ 5. Do not edit files or run commands. Return only the <model-changes> block.
228
104
 
229
105
  ${e?`## Current Model
230
106
  \`\`\`json
231
107
  ${JSON.stringify(e,null,2)}
232
108
  \`\`\`
233
109
 
234
- Merge the new decisions into the existing model. Preserve existing entries that are not contradicted by new decisions.`:"No model exists yet. Create one from scratch based on the decisions below."}
110
+ Use this only to understand the existing state and avoid proposing unchanged values.`:"No model exists yet. Propose only the entries directly supported by the accepted decisions below."}
235
111
 
236
- ## Design Decisions to Materialize
112
+ ## Accepted Decisions to Project
237
113
  ${n}
238
114
 
239
115
  ## Output Format
240
- Output the full model inside <model> tags. The model is a JSON object with these sections:
241
- - \`tokens\`: Design tokens (colors, spacing, typography, etc.)
242
- - \`components\`: Component-level patterns (e.g., button styles, card layouts)
243
- - \`rules\`: Array of structured rule objects
116
+ Each change is a JSON object with:
117
+ - \`id\`: stable descriptive identifier for this proposed change
118
+ - \`path\`: JSON path in the derived model; the first segment must be \`tokens\`, \`components\`, or \`rules\`
119
+ - \`label\`: short human-readable label
120
+ - \`value\`: complete JSON value to set at that path
121
+ - \`decisionIds\`: one or more IDs from ${JSON.stringify(t)} that directly support the change
122
+ - \`rationale\`: concise explanation of the projection from decision to model entry
123
+
124
+ For tokens and components, choose the narrowest durable path. For rules, emit a single change at path \`["rules"]\` whose value is the complete next rules array. Preserve unchanged rule IDs and order, and keep the array at 30 rules maximum.
244
125
 
245
126
  ### Rule format
246
127
  Each rule is a JSON object:
@@ -260,163 +141,98 @@ Fields:
260
141
  - **Keep:** Enforceable patterns, constraints, relationships between elements, accessibility requirements.
261
142
 
262
143
  Example:
263
- <model>
264
- {
265
- "tokens": {
266
- "colors": { "primary": "#3b82f6" },
267
- "spacing": {
268
- "sm": "4px",
269
- "md": "8px",
270
- "section-gap": { "value": "32px", "property": "gap", "bindings": ["gap-8"] }
271
- }
272
- },
273
- "components": {
274
- "button": { "padding": "12px 24px", "borderRadius": "8px" }
275
- },
276
- "rules": [
277
- { "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] },
278
- { "id": "e5f6a7b8", "scope": "color", "text": "Primary actions use the primary color token", "sources": ["d-def456"] }
279
- ]
280
- }
281
- </model>
144
+ <model-changes>
145
+ [
146
+ {
147
+ "id": "primary-color",
148
+ "path": ["tokens", "colors", "primary"],
149
+ "label": "Primary color",
150
+ "value": "#3b82f6",
151
+ "decisionIds": [${JSON.stringify(t[0]??"")}],
152
+ "rationale": "The accepted decision establishes this as the shared primary action color."
153
+ }
154
+ ]
155
+ </model-changes>
282
156
 
283
157
  ## Guidelines
284
158
  - Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
285
159
  - Extract clear, enforceable rules into the \`rules\` array as structured objects.
286
- - When merging, new decisions override conflicting older values.
160
+ - Do not silently override conflicting existing values; propose the explicit change for owner review.
287
161
  - Keep the model concise \u2014 only include patterns with clear evidence from decisions.
288
- - Do NOT output resolution or question blocks. Just output the <model> block.
162
+ - Do not emit unchanged entries or copy the complete model.
163
+ - Do NOT output resolution or question blocks. Just output the <model-changes> block.
289
164
  - Spacing tokens can be plain strings ("8px") or objects with code bindings:
290
165
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
291
166
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
292
167
  - bindings: Tailwind class names (without responsive prefixes) that use this token
293
- Include property and bindings when the decision context has class-level evidence.`}function Io(s){return`You are consolidating a design model's rules. The model has accumulated too many rules and needs cleanup.
294
-
295
- ## Current Model
296
- \`\`\`json
297
- ${JSON.stringify(s,null,2)}
298
- \`\`\`
299
-
300
- ## Instructions
301
- 1. Review all current rules.
302
- 2. Merge rules that cover the same concern into single, clear rules.
303
- 3. Remove rules that are:
304
- - Workflow advice ("After SSR fixes, re-verify headless output")
305
- - Instance-level observations ("Footer tagline is 'Design everything.'")
306
- - Restating tokens or components already defined elsewhere in the model
307
- - Procedural instructions rather than design constraints
308
- 4. Output the full model with consolidated rules.
309
- 5. Do not edit files or run commands. Return only the <model> block.
310
-
311
- ## Rule format
312
- Each rule MUST be a JSON object:
313
- { "id": "a1b2c3d4", "scope": "<scope>", "text": "<rule text>", "sources": ["<decision-id>", ...] }
314
-
315
- - \`id\`: 8-char hex. Preserve the ID of the most representative source rule when merging. Generate new 8-char hex IDs for genuinely new rules.
316
- - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
317
- - \`text\`: Clear, enforceable design constraint
318
- - \`sources\`: Merge source arrays when combining rules
319
-
320
- ## Hard cap: 30 rules maximum.
321
-
322
- Prioritize rules that are:
323
- - Enforceable constraints (not preferences)
324
- - Cross-cutting (affect many elements)
325
- - Not already captured by tokens or component definitions in the model
326
-
327
- ## Output
328
- Output the complete model inside <model> tags. Preserve tokens and components as-is \u2014 only rules change.
329
-
330
- <model>
331
- { "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
332
- </model>`}function rn(s){return`You are a design system curator reviewing a project's design model. Your job is to propose improvements to the rules \u2014 merging duplicates, filling gaps, removing noise.
333
-
334
- ## Current Model
335
- \`\`\`json
336
- ${JSON.stringify(s,null,2)}
337
- \`\`\`
338
-
339
- ## Instructions
340
- 1. Review all current rules, tokens, and components.
341
- 2. Propose specific changes \u2014 additions, merges, removals \u2014 with brief reasoning for each.
342
- 3. Present your proposals as clear text so the developer can review them.
343
- 4. Do NOT output a <model> block yet. First get the developer's approval.
344
-
345
- ## Output format
346
- - List each proposed change as a numbered item with a short rationale.
347
- - Group by action: **Merge**, **Add**, **Remove**, **Reword**.
348
- - After your proposals, output a <question> block asking the developer to approve, adjust, or reject.
349
-
350
- Example:
351
- **Merge**
352
- 1. Rules "Body text uses Inter 16px" and "Paragraph text is Inter 16/1.5" \u2192 "Body/paragraph text uses Inter at 16px/1.5" (they say the same thing)
353
-
354
- **Remove**
355
- 2. "After fixing SSR, re-verify headless output" \u2014 workflow advice, not a design constraint
356
-
357
- **Add**
358
- 3. "Primary actions use the primary color token; secondary actions use gray-500" \u2014 implied by token usage but not codified
359
-
360
- <question>
361
- These are my proposed rule changes. Would you like to approve all of them, adjust specific items, or add more? Once you're happy I'll output the final model.
362
- </question>
363
-
364
- ## After approval
365
- When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var Ke=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}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 ko}from"child_process";import{readFile as vt}from"fs/promises";import{homedir as et}from"os";import{join as he}from"path";var wt=/popmelt/i,Mo=/chrome|devtools/i;function Pe(){return{found:!1,name:null,scope:null,disabled:!1}}function Me(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function Oe(s){for(let e of Object.keys(s))if(wt.test(e))return e;return null}async function Ze(s){try{let e=await vt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function St(s){let e=et(),n=await Ze(he(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Oe(o.mcpServers);if(i)return Me(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=Oe(l.mcpServers);if(f){let v=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(b=>wt.test(b));return Me(f,"project",v)}}}}}let t=await Ze(he(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=Oe(o.mcpServers);if(a){let l=await an(s,a);return Me(a,"mcp.json",l)}}let i=Oe(o);if(i&&i!=="mcpServers"){let a=await an(s,i);return Me(i,"mcp.json",a)}}return Pe()}async function an(s,e){let n=he(s,".claude","settings.local.json"),t=await Ze(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var Ro=/^\[mcp_servers\.([^\]]+)\]/;function Eo(s){return s.replace(/^"(.+)"$/,"$1")}function To(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function cn(s){let e=s.split(`
366
- `),n=[],t=null;for(let o of e){let i=o.match(Ro);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
367
- `)}),t={name:i[1],bodyLines:[]}):o.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
368
- `)}),t=null):t&&t.bodyLines.push(o)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
369
- `)}),n}function dn(s){return/enabled\s*=\s*false/i.test(s)}async function xt(s){let e=process.env.CODEX_HOME||he(et(),".codex"),n=await ln(he(e,"config.toml"),"user");if(n.found)return n;let t=await ln(he(s,".codex","config.toml"),"project");return t.found?t:Pe()}async function Ao(s,e){let n=process.env.CODEX_HOME||he(et(),".codex"),t=new Set;for(let o of[he(n,"config.toml"),he(s,".codex","config.toml")])try{let i=await vt(o,"utf-8");for(let a of cn(i)){if(To(a.name)||dn(a.body))continue;let l=Eo(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function un(s){return Ao(s,Mo)}async function bt(s,e="copilot"){let n=await Co(e);if(n.found)return n;let t=process.env.COPILOT_HOME||he(et(),".copilot"),o=await yt(he(t,"mcp-config.json"),"user");if(o.found)return o;let i=await yt(he(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await yt(he(s,".github","mcp.json"),"mcp.json");return a.found?a:Pe()}async function Co(s){try{let e=await new Promise((n,t)=>{ko(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return pn(JSON.parse(e),"user")}catch{return Pe()}}async function yt(s,e){let n=await Ze(s);return pn(n,e)}function pn(s,e){if(!s||typeof s!="object")return Pe();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=Oe(t);return o?Me(o,e):Pe()}async function ln(s,e){try{let n=await vt(s,"utf-8"),t=cn(n);for(let o of t)if(wt.test(o.name)){let i=dn(o.body);return Me(o.name,e,i)}}catch{}return Pe()}import{execFile as fn}from"child_process";import{mkdir as $o,readFile as hn,writeFile as mn}from"fs/promises";import{homedir as gn}from"os";import{dirname as _o,join as Pt}from"path";var It="https://mcp.popmelt.com/mcp";async function yn(s=It){let e=Pt(gn(),".claude.json"),n;try{let o=await hn(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 mn(e,JSON.stringify(n,null,2)+`
370
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function vn(s=It){let e=process.env.CODEX_HOME||Pt(gn(),".codex"),n=Pt(e,"config.toml"),t;try{t=await hn(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await $o(_o(n),{recursive:!0});let o=`
168
+ Include property and bindings when the decision context has class-level evidence.`}var bn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as Wi}from"child_process";import{readFile as po}from"fs/promises";import{homedir as Sn}from"os";import{join as Fe}from"path";var uo=/popmelt/i,Hi=/chrome|devtools/i;function ht(){return{found:!1,name:null,scope:null,disabled:!1}}function Rt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Ht(o){for(let e of Object.keys(o))if(uo.test(e))return e;return null}async function xn(o){try{let e=await po(o,"utf-8");return JSON.parse(e)}catch{return null}}async function mo(o){let e=Sn(),n=await xn(Fe(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Ht(r.mcpServers);if(s)return Rt(s,"user")}if(r.projects&&typeof r.projects=="object"){let i=r.projects[o];if(i&&typeof i=="object"){let c=i;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Ht(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(v=>uo.test(v));return Rt(d,"project",l)}}}}}let t=await xn(Fe(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Ht(r.mcpServers);if(i){let c=await pr(o,i);return Rt(i,"mcp.json",c)}}let s=Ht(r);if(s&&s!=="mcpServers"){let i=await pr(o,s);return Rt(s,"mcp.json",i)}}return ht()}async function pr(o,e){let n=Fe(o,".claude","settings.local.json"),t=await xn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(s=>s===e)}return!1}var Gi=/^\[mcp_servers\.([^\]]+)\]/;function Vi(o){return o.replace(/^"(.+)"$/,"$1")}function Ki(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function mr(o){let e=o.split(`
169
+ `),n=[],t=null;for(let r of e){let s=r.match(Gi);s?(t&&n.push({name:t.name,body:t.bodyLines.join(`
170
+ `)}),t={name:s[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
171
+ `)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
172
+ `)}),n}function fr(o){return/enabled\s*=\s*false/i.test(o)}async function fo(o){let e=process.env.CODEX_HOME||Fe(Sn(),".codex"),n=await ur(Fe(e,"config.toml"),"user");if(n.found)return n;let t=await ur(Fe(o,".codex","config.toml"),"project");return t.found?t:ht()}async function Qi(o,e){let n=process.env.CODEX_HOME||Fe(Sn(),".codex"),t=new Set;for(let r of[Fe(n,"config.toml"),Fe(o,".codex","config.toml")])try{let s=await po(r,"utf-8");for(let i of mr(s)){if(Ki(i.name)||fr(i.body))continue;let c=Vi(i.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function hr(o){return Qi(o,Hi)}async function ho(o,e="copilot"){let n=await Xi(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Fe(Sn(),".copilot"),r=await lo(Fe(t,"mcp-config.json"),"user");if(r.found)return r;let s=await lo(Fe(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await lo(Fe(o,".github","mcp.json"),"mcp.json");return i.found?i:ht()}async function Xi(o){try{let e=await new Promise((n,t)=>{Wi(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return gr(JSON.parse(e),"user")}catch{return ht()}}async function lo(o,e){let n=await xn(o);return gr(n,e)}function gr(o,e){if(!o||typeof o!="object")return ht();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Ht(t);return r?Rt(r,e):ht()}async function ur(o,e){try{let n=await po(o,"utf-8"),t=mr(n);for(let r of t)if(uo.test(r.name)){let s=fr(r.body);return Rt(r.name,e,s)}}catch{}return ht()}import{execFile as yr}from"child_process";import{mkdir as Yi,readFile as vr,writeFile as wr}from"fs/promises";import{homedir as Ir}from"os";import{dirname as Zi,join as go}from"path";var yo="https://mcp.popmelt.com/mcp";async function br(o=yo){let e=go(Ir(),".claude.json"),n;try{let r=await vr(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 wr(e,JSON.stringify(n,null,2)+`
173
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function xr(o=yo){let e=process.env.CODEX_HOME||go(Ir(),".codex"),n=go(e,"config.toml"),t;try{t=await vr(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Yi(Zi(n),{recursive:!0});let r=`
371
174
  [mcp_servers.popmelt]
372
- url = "${s}"
373
- `;return await mn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function wn(s=It,e="copilot"){let n=await Oo(e);if(Do(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{fn(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 Oo(s){try{let e=await new Promise((n,t)=>{fn(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 Do(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))}async function tt(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 No(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),l,f,v,b,E,F,D,H,U,w,G,Y,q,V,J=[],K=[],N=0,$=[];for(;N<o.length;){let k=o.indexOf(i,N);if(k===-1)break;let m=k+i.length;if(o.slice(k,k+a.length).equals(a))break;let A=m;o[A]===13&&o[A+1]===10&&(A+=2);let T=o.indexOf(`\r
175
+ url = "${o}"
176
+ `;return await wr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Sr(o=yo,e="copilot"){let n=await ea(e);if(ta(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{yr(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 ea(o){try{let e=await new Promise((n,t)=>{yr(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 ta(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 kn=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 Po,readFile as Mt,writeFile as To}from"fs/promises";import{join as dt}from"path";var na=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function vo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Rn(o){return new Set(vo(o).split(" ").filter(e=>e.length>2&&!na.has(e)))}function kr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function oa(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 ra(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(vo).filter(Boolean),s=Rn([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 oa(i)){let l=vo(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(kr(Rn(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 sa(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 ia(o){return Math.ceil(JSON.stringify(o).length/4)}function wo(o,e){let n=o.records.filter(h=>h.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(h=>{if(h.recordType!=="proposal"||r&&!r.has(h.id))return!1;if(h.state==="pending")return!0;if(h.state!=="deferred")return!1;let f=[...o.events].reverse().find(y=>y.entity.entityType==="proposal"&&y.entity.entityId===h.id&&y.toState==="deferred"&&y.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(h=>h.recordType==="implementation_attempt"),c=ra(n,e),d=[...c.values()].sort((h,f)=>f.score-h.score),l=Rn([e.action,e.text].filter(Boolean).join(" ")),v=s.flatMap(h=>{let f=h.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),y=Math.max(0,...f.map(A=>A.score)),x=Math.round(kr(Rn(h.claim),l)*35),S=y+x;return S>=50?[{proposal:h,proposalMatches:f,score:S}]:[]}).sort((h,f)=>f.score-h.score||h.proposal.id.localeCompare(f.proposal.id)),P=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),I=[],g=0;for(let h of v){if(I.length>=P)break;let f=h.proposal.sourceRefs.slice(0,4),y={contractVersion:1,packetId:`review:${h.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:h.proposalMatches.length?`Historical proposal intersects ${h.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:h.proposalMatches.map(({score:S,...A})=>A)},proposal:{id:h.proposal.id,claim:h.proposal.claim,state:h.proposal.state,proposedKind:h.proposal.proposedKind,subjectIds:h.proposal.subjects.map(S=>S.subjectId),origin:h.proposal.origin.mode},authority:"unaccepted",presentation:h.score>=100&&["constraint","rule"].includes(h.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:sa(h.proposal,i),evidence:{sourceCount:h.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:h.proposal.id},...f]},x={...y,estimatedTokens:ia(y)};if(g+x.estimatedTokens>b)break;I.push(x),g+=x.estimatedTokens}let p=Math.max(0,v.length-I.length);return{packets:I,subjectMatches:d.map(({score:h,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:p,maxEstimatedTokens:b,estimatedTokens:g},uncertainty:c.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var aa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Io(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Pn(o){return new Set(Io(o).split(" ").filter(e=>e.length>2&&!aa.has(e)))}function Rr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ca(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(Io).filter(Boolean),r=Pn([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=Io(l.value);for(let I of t){let g=v===I?95:v.includes(I)||I.includes(v)?75:0;g>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let b=["/","#","[","]","="].some(I=>l.value.includes(I))?0:Math.round(Rr(Pn(v),r)*55);b>=30&&b>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}c&&s.push(c)}return s.sort((i,c)=>c.score-i.score||i.subjectId.localeCompare(c.subjectId))}function da(o){return Math.ceil(JSON.stringify(o).length/4)}function Pt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function la(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 pa(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 Pr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(_=>_.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(_=>_.recordType==="decision"&&_.state==="active"),c=s?i.filter(_=>s.has(_.id)):i,d=o.records.filter(_=>_.recordType==="implementation_attempt"),l=o.records.filter(_=>_.recordType==="verification_attempt"),v=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),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),g=ca(r,e),p=new Map(g.map(_=>[_.subjectId,_.score])),h=Pn([e.action,e.text].filter(Boolean).join(" ")),f=c.flatMap(_=>{let N=Math.max(0,..._.subjects.map(W=>p.get(W.subjectId)??0)),T=Math.round(Rr(Pn(_.claim),h)*35),B=N+T;return B>=50?[{decision:_,score:B}]:[]}).sort((_,N)=>N.score-_.score||_.decision.id.localeCompare(N.decision.id)),y=new Map;for(let _ of f.slice(0,t))y.set(_.decision.id,_.decision);for(let _ of o.relationships){if(!Pt(_,"excepts")&&!Pt(_,"contradicts"))continue;let N=i.find(B=>B.id===_.from.entityId),T=i.find(B=>B.id===_.to.entityId);!N||!T||!y.has(N.id)&&!y.has(T.id)||(y.size<t&&y.set(N.id,N),y.size<t&&y.set(T.id,T))}let x=[...y.values()],S=_=>_.from.entityType==="decision"&&_.to.entityType==="decision"&&y.has(_.from.entityId)&&y.has(_.to.entityId),A=(_,N=!1)=>{let T=new Set(_.map(M=>M.id)),B=v.filter(M=>M.target.entityType==="decision"&&T.has(M.target.entityId)),W=new Set(o.relationships.filter(M=>Pt(M,"excepts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).flatMap(M=>[M.from.entityId,M.to.entityId])),H=o.relationships.filter(M=>Pt(M,"contradicts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).map(M=>({id:M.id,decisionIds:[M.from.entityId,M.to.entityId],unresolvedQuestion:M.reason,expansionRefs:[{kind:"record",id:M.id}]})),ne=new Set(H.flatMap(M=>M.decisionIds)),oe=P.filter(M=>M.sourceRefs.some(Z=>Z.kind==="record"&&T.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===M.id&&Z.to.entityType==="decision"&&T.has(Z.to.entityId))),he=Math.max(0,f.length-_.length),Y=o.relationships.some(M=>Pt(M,"contradicts")&&S(M)&&(!T.has(M.from.entityId)||!T.has(M.to.entityId))),G=N||he>0||Y,q=[];g.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(M=>M.expansionRefs)}),oe.some(M=>M.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map(M=>({kind:"record",id:M.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:g.map(({score:M,...Z})=>Z),modelEntries:b.filter(M=>M.decisionIds.some(Z=>T.has(Z))).map(M=>({id:M.id,key:M.key,value:M.value,decisionIds:M.decisionIds})),evalSpecs:I.filter(M=>M.decisionIds.some(Z=>T.has(Z))).map(M=>({id:M.id,legacyId:M.legacyId,state:M.state,title:M.title,assertionCount:M.assertions.length,decisionIds:M.decisionIds,expansionRef:{kind:"record",id:M.id}})),decisions:_.map(M=>({id:M.id,kind:M.kind,claim:M.claim,subjectIds:M.subjects.map(Z=>Z.subjectId),authority:M.authority,effectiveState:ne.has(M.id)?"conflicted":W.has(M.id)?"excepted":"active",freshness:B.filter(Z=>Z.target.entityId===M.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:M.id}})),conflicts:H,uncertainties:q,implementation:_.map(M=>la(M.id,d)),verification:_.map(M=>pa(M.id,l,B)),evidence:oe.map(M=>({evidenceId:M.id,summary:M.summary,availability:M.availability,sourceRefs:M.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:he,omittedEvidenceCount:0,conflictsComplete:!Y}};return fe.budget.estimatedTokens=da(fe),fe},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>Pt(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 ua=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Tt(o){return ua.test(o)}function ma(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 bo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){Tt(n)||ce(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function ct(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ce(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function gt(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 fa={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"])},ha=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function ga(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),ct(o,`${n}.createdAt`,e.createdAt),gt(o,`${n}.authority`,e.authority);let t=fa[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(ha.has(s)&&(gt(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&&ct(o,`${n}.transitionContext.revisitAfter`,i.revisitAfter)}}function ya(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),ct(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"&&(gt(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"&&bo(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"&&(ct(o,`${n}.appliedAt`,e.appliedAt),gt(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&&bo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&bo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function va(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),ct(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?gt(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 yt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),ct(e,"manifest.createdAt",o.manifest.createdAt),ct(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),ya(e,p,f,o.manifest.projectId)}),o.events.forEach((p,h)=>{let f=`events[${h}]`;t(p.id,f),ga(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),va(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,h)=>{t(p.id,`artifacts[${h}]`),Te(e,`artifacts[${h}].id`,p.id)}),o.tombstones.forEach((p,h)=>{let f=`tombstones[${h}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),ct(e,`${f}.deletedAt`,p.deletedAt),gt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,h)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,h,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,h)=>i(p.entity,`events[${h}].entity`)),o.relationships.forEach((p,h)=>{i(p.from,`relationships[${h}].from`),i(p.to,`relationships[${h}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,h)=>{c.has(p)||ce(e,h,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,h,f)=>{!r.has(`${p}:${h}`)&&!s.has(`${p}:${h}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,h)=>{let f=`records[${h}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((y,x)=>l("subject",y,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((y,x)=>d(y,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((y,x)=>l("subject",y.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((y,x)=>d(y,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((y,x)=>i(y,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((y,x)=>l("thread",y,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((y,x)=>l("iteration",y,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((y,x)=>{y.kind==="subject"&&y.subjectId&&l("subject",y.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((y,x)=>{y.subjectIds?.forEach((S,A)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${A}]`))}),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`));break;case"model_projection":gt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((y,x)=>l("model_entry",y,`${f}.entryIds[${x}]`)),p.coverage.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;default:break}});let v=new Map(o.events.map(p=>[p.id,p])),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"}`,y=b.get(f)??new Set;y.add(p.toState),b.set(f,y),y.size>1&&ce(e,`events[${h}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let I=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,h,f,y,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=I.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==h||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(f);(A<Date.parse(S.startsAt)||S.endsAt&&A>Date.parse(S.endsAt)||S.revokedAt&&A>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&y.length&&!y.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(h=>h.subjectId),`records:${p.id}.authority`);o.events.forEach((p,h)=>{let f=P.get(`${p.entity.entityType}:${p.entity.entityId}`),y=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,y,`events[${h}].authority`)}),o.relationships.forEach((p,h)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(y=>{let x=P.get(`${y.entityType}:${y.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${h}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let h=v.get(p.acceptanceEventId);(!h||h.entity.entityType!=="proposal"||h.entity.entityId!==p.proposalId||h.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),h&&h.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),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(y=>y.relationshipType==="supersedes"&&y.to.entityType==="decision"&&y.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(y=>y.entity.entityType==="decision"&&y.entity.entityId===p.id&&y.toState==="revoked"&&!!y.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return ma(e)}function Gt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Tr(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 wa(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function Tn(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Tt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of wa(e))Tt(s)||n.push({code:"invalid_generated_id",message:`${s} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=Tr(o,t,e,s.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:i.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let s={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},i={...Gt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Gt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Tr(o,s,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,d],events:[i,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ia}from"crypto";import{readFile as ba,readdir as xa,realpath as Sa}from"fs/promises";import{join as Vt,relative as ka}from"path";var Ra=["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 jt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function ze(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function jr(...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=Ia("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 xo(o,e){try{return JSON.parse(await ba(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Pa(o){let e=jt(o);if(!e)return 0;let n=0,t=r=>{let s=jt(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 Ta(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Kt(o){let e=[],n=await Sa(o.projectRoot).catch(()=>o.projectRoot),t=Vt(n,".popmelt"),r=await xo(Vt(t,"threads.json"),e),s=await xo(Vt(t,"model.json"),e),i=jt(r),c=jt(i?.threads)??{},d=Object.entries(c).map(([M,Z])=>({key:M,value:jt(Z)})).filter(M=>!!M.value),l=Vt(t,"decisions"),v=await xa(l).catch(()=>[]),P=[];for(let M of v.filter(Z=>Z.endsWith(".json")).sort()){let Z=jt(await xo(Vt(l,M),e));Z&&P.push({file:M,value:Z})}let b=d.flatMap(({value:M})=>[M.createdAt,M.updatedAt]).filter(M=>typeof M=="number"&&Number.isFinite(M)),I=b.length?Math.min(...b):0,g=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ge(g,"project",g,I),h=ge(g,"participant","legacy-owner",I),f=ge(g,"participant","legacy-agent",I),y=ge(g,"subject","project",I),x=ze(Math.max(I,...b)),S=[],A=[],J=new Map,_=new Map,N=new Map(P.map(M=>[M.value.id??M.file.replace(/^d-|\.json$/g,""),M.value])),T=new Map,B=(M,Z,V,Pe,Ee)=>{let Ie=J.get(V);if(Ie)return Ie;let Ae=ge(g,"artifact",M,Pe);return A.push({id:Ae,kind:Z,mediaType:Ee,location:V,availability:"available"}),J.set(V,Ae),Ae};for(let{file:M,value:Z}of P){let V=Z.id??M.replace(/^d-|\.json$/g,""),Pe=Z.createdAt??I,Ee=[B(`${V}:envelope`,"other",`.popmelt/decisions/${M}`,Pe,"application/json")];Z.screenshotPath&&Ee.push(B(`${V}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,Pe,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ie,Ae]of(Z.pastedImagePaths??[]).entries())Ee.push(B(`${V}:image:${Ie}`,"image",Ae,Pe));T.set(V,Ee)}let W=(M,Z,V)=>({id:M,schemaVersion:1,projectId:p,createdAt:x,participantId:Z,sourceRefs:V}),te=(M,Z)=>{S.push(Z);let V=_.get(M)??[];V.push(Z.id),_.set(M,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(y,h,[]),recordType:"subject",subjectType:"project",label:ka(process.cwd(),n)||n,aliases:[],locators:[{id:ge(g,"locator",n,I),kind:"project_root",value:n,status:"current",validFrom:ze(I),sourceRefs:[]}]});let ne=new Map,oe=(M,Z)=>{let V=ne.get(M);if(V)return V;let Pe=ge(g,"subject",M,Z),Ee={...W(Pe,h,[{kind:"external",id:M}]),createdAt:ze(Z),recordType:"subject",subjectType:"element",label:M,aliases:[],locators:[{id:ge(g,"locator",M,Z),kind:"dom_selector",value:M,status:"current",validFrom:ze(Z),sourceRefs:[{kind:"external",id:M}]}]};return S.push(Ee),ne.set(M,Pe),Pe};for(let{key:M,value:Z}of d){let V=Z.id??M,Pe=Z.createdAt??I,Ee=ge(g,"thread",V,Pe),Ie={kind:"thread",id:V},Ae=[],Je=[],Dt=Array.isArray(Z.messages)?Z.messages:[],qe,ot,Jt=0;Dt.forEach((ve,rt)=>{let _e=ve.timestamp??Pe,Ye=ge(g,"artifact",`${V}:message:${rt}`,_e);if(Ae.push(Ye),A.push({id:Ye,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${V}/messages/${rt}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${V}/messages/${rt}`,Ye),ve.screenshotPath&&B(`${V}:message:${rt}:screenshot`,"screenshot",ve.screenshotPath,_e),ve.role==="human"){qe=ve;let Ne=ve.feedbackSummary??ve.replyToQuestion;if(Ne?.trim()){let Be=ge(g,"observation",`${V}:${rt}`,_e),at=Z.elementIdentifiers??[],xt={...W(Be,h,[Ie,{kind:"message",id:Ye}]),createdAt:ze(_e),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:at.map(ut=>oe(ut,Pe)),artifactIds:[Ye]},resolvedByIds:[]};te(V,xt),ot=Be,Je.push({entityType:"observation",entityId:Be})}return}if(ve.role!=="assistant")return;let st=ve.jobId??`${V}:${rt}`,it=ge(g,"iteration",st,_e),pt=N.get(st),Nt=ve.cancelled?"cancelled":ve.error?"failed":ve.question?"question_asked":(ve.resolutions?.length??0)>0?"completed":"no_change",Yn={...W(it,f,[Ie,{kind:"message",id:Ye},...(T.get(st)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:ze(_e),recordType:"iteration",threadIds:[Ee],startedAt:ze(qe?.timestamp,_e),completedAt:ze(_e),requestSummary:jr(qe?.feedbackSummary,qe?.replyToQuestion)??"[legacy request unavailable]",responseSummary:ve.question??ve.error??ve.responseText?.slice(0,1e3),outcome:Nt,execution:{provider:ve.provider??pt?.provider,model:ve.model??pt?.model,sessionId:ve.sessionId??pt?.sessionId},artifactIds:[Ye,...T.get(st)??[]]};te(V,Yn),Je.push({entityType:"iteration",entityId:it});let Bt=ve.resolutions??pt?.resolutions??[];for(let[Ne,Be]of Bt.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let at=Z.elementIdentifiers??[],xt=(at.length?at:[n]).map(cn=>({subjectId:cn===n?y:oe(cn,Pe),role:"governed"})),ut=ge(g,"proposal",`${st}:${Be.annotationId??"resolution"}:${Ne}`,_e),Zn={...W(ut,f,[Ie,{kind:"iteration",id:it}]),createdAt:ze(_e),recordType:"proposal",state:"pending",claim:Be.summary,subjects:xt,subjectSemantics:xt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:jr(qe?.feedbackSummary,qe?.replyToQuestion,Be.summary),iterationId:it,inferredById:f}};te(V,Zn),Je.push({entityType:"proposal",entityId:ut}),e.push({severity:"warning",code:"acceptance_unresolved",source:V,message:`Proposal ${ut} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Bt.some(Ne=>Ne.status==="resolved")||pt?.gitDiff){let Ne=ge(g,"implementation",st,_e),Be={...W(Ne,f,[Ie,{kind:"iteration",id:it}]),createdAt:ze(_e),recordType:"implementation_attempt",state:"completed",iterationIds:[it],coverageClaims:[],summary:Bt.map(at=>at.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};te(V,Be),Je.push({entityType:"implementation_attempt",entityId:Ne}),Jt+=1}ot&&(ot=void 0)});let bt=Dt.at(-1),Xn={...W(Ee,h,[Ie]),createdAt:ze(Pe),recordType:"thread",state:bt?.question?"open":"resolved",messageArtifactIds:Ae,outcome:bt?.question?"question_unresolved":Jt?"implementation_only":"no_outcome",resultRefs:Je};S.push(Xn),_.set(V,[Ee,..._.get(V)??[]])}let he=Pa(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:ze(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=yt(Y),fe=(o.proofCaseIds??Ra).map(M=>({legacyId:M,threadFound:d.some(({key:Z,value:V})=>(V.id??Z)===M),decisionEnvelopeFound:N.has(M),recordIds:_.get(M)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((M,Z)=>M+(Z.value.messages?.length??0),0),decisionEnvelopes:P.length,modelEntries:he,artifactsReferenced:A.length},imported:Ta(S),unresolvedAcceptance:e.filter(M=>M.code==="acceptance_unresolved").length,deferredModelEntries:he,proofCases:fe,issues:e,schemaIssues:G.issues}}}import{createHash as ja}from"crypto";import{mkdir as Mr,open as So,readFile as ko,readdir as Ma,rename as Ea,unlink as Ro}from"fs/promises";import{join as tt}from"path";var Aa={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Mn(o){return ja("sha256").update(JSON.stringify(o)).digest("hex")}function Er(o){return Mn(o)}function Ar(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 _a(o,e,n){return Ar(structuredClone(o),e,n)}async function vt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await So(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
177
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Ea(n,o)}catch(r){throw await Ro(n).catch(()=>{}),r}}async function jn(o){return JSON.parse(await ko(o,"utf8"))}var En=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=tt(e,".popmelt","memory"),this.journalDir=tt(this.memoryDir,"journal"),this.manifestPath=tt(this.memoryDir,"manifest.json"),this.checkpointPath=tt(this.memoryDir,"checkpoint.json"),this.lockPath=tt(this.memoryDir,"writer.lock")}async initialize(e){let n=yt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Mr(this.journalDir,{recursive:!0});try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}let t=Mn(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 vt(this.checkpointPath,r),await vt(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 vt(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=Mn(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 vt(tt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await vt(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(!Tt(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:Er(s)},c=_a(t.bundle,e,n.committedAt),d=yt(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 vt(tt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await vt(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({...Aa,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await jn(this.manifestPath),n=await jn(tt(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!==Mn(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Ma(this.journalDir),r=t.filter(b=>b.endsWith(".tmp")),i=t.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,v=new Set;for(let b of i){let I=await jn(tt(this.journalDir,b)),{hash:g,...p}=I;if(g!==Er(p))throw new Error(`Journal hash mismatch: ${b}`);if(I.sequence!==d+1)throw new Error(`Journal sequence gap at ${b}`);if(I.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(I.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(v.has(I.transactionId))throw new Error(`Duplicate transaction ID: ${I.transactionId}`);Ar(c,I.mutation,I.committedAt),d=I.sequence,l=I.hash,v.add(I.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let P=yt(c);if(!P.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(P.issues)}`);return{bundle:c,manifest:e,transactionIds:v,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Mr(this.memoryDir,{recursive:!0});let n;try{n=await So(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await jn(this.lockPath).catch(()=>({})),s=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(i){s=i.code!=="ESRCH"}if(s)throw new Error("Memory journal is locked by another writer.");await Ro(this.lockPath),n=await So(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Ro(this.lockPath).catch(()=>{})}}};import{randomBytes as Ca}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Ca(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 $a=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function _r(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=$a(),l=d.records,v=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));v||(v={id: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(v));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 g=ge(r,"live-iteration",s,e.completedAt),p={id:g,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...I?[{kind:"record",id:I}]:[]],recordType:"iteration",threadIds:[v.id],startedAt:i,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let h=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),y=P.length>0?P:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(b.length>0&&y.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of b.entries()){let A=ge(r,"live-proposal",`${s}:${x}`,e.completedAt),J=y.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:S.claim.trim(),rationale:S.rationale?.trim()||void 0,proposedKind:S.proposedKind,subjects:J,subjectSemantics:J.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:S.sourceText?.trim()||e.requestSummary,iterationId:g,inferredById:t.id}};l.push(_),h.push(A)}if(f.length>0){let x=new Set(e.governingDecisionIds??[]),S=o.records.filter(J=>J.recordType==="decision"&&J.state==="active"&&x.has(J.id)),A={id:ge(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g}],recordType:"implementation_attempt",state:"completed",iterationIds:[g],coverageClaims:S.map(J=>({decisionId:J.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(_=>_.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:d,iterationId:g,proposalIds:h,observationId:I}}import{createHash as Oa}from"crypto";import{mkdir as Da,open as Ja,readFile as Na,rename as Ba,unlink as Fa}from"fs/promises";import{join as Cr}from"path";function $r(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Or(o){return Oa("sha256").update(JSON.stringify(o)).digest("hex")}async function La(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ja(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Ba(n,o)}catch(r){throw await Fa(n).catch(()=>{}),r}}function za(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(d,l,v)=>{let P=d[l]??=[];P.includes(v)||P.push(v)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(P=>P.status==="current").map(P=>P.value)]){let P=$r(v);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:Or(c)}}function Dr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[$r(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var An=class{constructor(e){this.indexDir=Cr(e,".popmelt","memory","indexes"),this.indexPath=Cr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Na(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===Or(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=za(e,n);return await Da(this.indexDir,{recursive:!0}),await La(this.indexPath,t),t}};var _n=class{constructor(e){this.projectRoot=e;this.store=new En(e),this.indexStore=new An(e),this.manifestPath=dt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Mt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Kt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Kt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=dt(this.projectRoot,".popmelt","memory","migrations"),n=dt(e,"legacy-evals-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await Mt(dt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await Mt(dt(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 Po(e,{recursive:!0}),await To(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=dt(this.projectRoot,".popmelt","memory","migrations"),n=dt(e,"imprint-evidence-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await Mt(dt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Po(e,{recursive:!0}),await To(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 Po(e,{recursive:!0}),await To(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:wo(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Pr(t.bundle,r),reviewSelection:wo(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Tn(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Kt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=Tn(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},d=e.action==="accept"?{...c,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:le(s),reason:e.reason}:{...c,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=Tn(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(v);let 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:v.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=_r(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=[],v=[];for(let b of e.summary.changes){let I={kind:"external",id:b.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(h=>h.recordType==="observation"&&h.sourceRefs.some(f=>f.kind==="external"&&f.id===b.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:b.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),v.push({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let 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:v,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(v=>v.entityType==="decision"&&v.entityId===c.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(c=>c.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),c=le(s),d=le(s),l=le(s),v=le(s),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)),g={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],h={...g,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},y={...g,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...g,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id: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:[v],coverage:[{decisionId:l,status:"projected"}]},A={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=I.map(T=>({...g,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=I.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:y.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[h,y,x,S],events:[f,...J],relationships:[A,..._],artifacts:[],tombstones:[],projectionUpdates:I.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:v}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),s=n.bundle.records.flatMap(g=>g.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===g.id||g.sourceRefs.some(h=>h.id===p))?[g.id]:[]),i=[...new Set(n.bundle.records.flatMap(g=>g.recordType==="decision"&&s.includes(g.id)?g.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!l)throw new Error("No active local owner participant is available.");let v=Date.now(),P=new Date(v).toISOString(),b={id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:P,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},I=r?[{id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt: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(v),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(v=>v.evalSpecId===i.id).sort((v,P)=>P.createdAt.localeCompare(v.createdAt))[0],d=c&&s.some(v=>v.target.entityType==="verification_attempt"&&v.target.entityId===c.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(b=>b.recordType==="verification_attempt"&&b.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active"&&b.kind==="ai")??t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active");if(!s)return;let i=n.completedAt,c=new Date(i).toISOString(),d={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},v=r.targets.map(b=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:b,reason:n.summary})),P=await this.store.commit({records:[d,l],events:[],relationships:v,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(v=>({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:v.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="model_projection"&&g.state==="applied"&&g.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(g=>g.recordType==="decision"&&e.decisionIds.includes(g.id)&&g.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let s=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),c=new Date(i).toISOString(),d=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(y=>e.decisionIds.includes(y)),h=p?.length?p:e.decisionIds,f=[...new Set(r.filter(y=>h.includes(y.id)).flatMap(y=>y.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:h.map(y=>({kind:"record",id:y})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:h,value:g.value}}),v=new Set(l.flatMap(g=>g.decisionIds)),P={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:e.decisionIds.map(g=>({kind:"record",id:g})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:v.has(g)?"projected":"unprojected"})},b=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:P.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),I=await this.store.commit({records:[...l,P],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});return await this.refreshIndex(I),{projectionId:d,entryIds:l.map(g=>g.id),headSequence:I.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Kt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Dr(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 At(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Et(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function jo(o){let e=At(o),n=At(e.authority),t=n.level,r=n.mode,s=Et(t,"authority.level",["owner","delegate","contributor"]),i=Et(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:Et(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=At(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>Et(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:Et(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=At(d);return{subjectId:Se(l.subjectId,"subjectId"),role:Et(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Mo(o){let e=At(o),n=(s,i)=>{if(s!==void 0){if(!Array.isArray(s))throw new Error(`${i} must be an array.`);return s.map(c=>Se(c,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0:At(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Cn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
179
+ `)}async function Jr(o,e,n,t){let r=Cn(e);if(!(!r&&n.length===0))try{let s=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(s.actionPacket.decisions.length===0&&s.reviewSelection.packets.length===0)return;let i=new Map(s.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(s.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:s.source,...s.actionPacket.decisions.length>0?{acceptedTruth:{decisions:s.actionPacket.decisions.map(d=>({...d,implementation:i.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:s.actionPacket.conflicts,truncated:s.actionPacket.completeness.status==="truncated"}}:{},packets:s.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:s.reviewSelection.completeness.status==="truncated",estimatedTokens:s.actionPacket.budget.estimatedTokens+s.reviewSelection.completeness.estimatedTokens}}catch(s){t?.(s);return}}function Nr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,r)=>["",`${r+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,r)=>["",`${r+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
180
+ `)}function Br(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 Fr(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!t||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:t,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function $n(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],r=await qa(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),c,d,l,v,P,b,I,g,p,h,f,y,x,S,A=[],J=[],_=0,N=[];for(;_<r.length;){let T=r.indexOf(s,_);if(T===-1)break;let B=T+s.length;if(r.slice(T,T+i.length).equals(i))break;let W=B;r[W]===13&&r[W+1]===10&&(W+=2);let te=r.indexOf(`\r
374
181
  \r
375
- `,A);if(T===-1)break;let x=o.slice(A,T).toString("utf-8"),L=T+4,_=o.indexOf(i,L),Z=_!==-1?_-2:o.length;$.push({headers:x,body:o.slice(L,Z)}),N=_!==-1?_:o.length}for(let k of $){let m=k.headers.match(/name="([^"]+)"/);if(!m)continue;let A=m[1];if(A==="screenshot")l=k.body;else if(A==="feedback")f=k.body.toString("utf-8");else if(A==="color")v=k.body.toString("utf-8");else if(A==="provider")b=k.body.toString("utf-8");else if(A==="model")E=k.body.toString("utf-8");else if(A==="reasoningEffort")F=k.body.toString("utf-8");else if(A==="serviceTier")D=k.body.toString("utf-8");else if(A==="goal")H=k.body.toString("utf-8");else if(A==="pageUrl")U=k.body.toString("utf-8");else if(A==="viewport")w=k.body.toString("utf-8");else if(A==="planId")G=k.body.toString("utf-8");else if(A==="manifest")Y=k.body.toString("utf-8");else if(A==="tasks")q=k.body.toString("utf-8");else if(A==="sourceId")V=k.body.toString("utf-8");else if(A.startsWith("screenshot-")){let T=A.slice(11);try{let x=decodeURIComponent(T);K.push({pathname:x,data:k.body})}catch{}}else if(A.startsWith("image-")){let T=A.split("-"),x=parseInt(T[T.length-1],10),L=T.slice(1,-1).join("-");L&&!isNaN(x)&&J.push({annotationId:L,index:x,data:k.body})}}if(!l)throw new Error("Missing screenshot field");return f||(f=""),{screenshot:l,feedback:f,color:v,provider:b,model:E,reasoningEffort:F,serviceTier:D,goal:H,pageUrl:U,viewport:w,planId:G,manifest:Y,tasks:q,sourceId:V,pastedImages:J,pageScreenshots:K}}function No(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 De(s,e){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let t of s.annotations){let o=t.elements.map(l=>{let f=[l.selector];return l.reactComponent&&f.push(`(${l.reactComponent})`),f.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${o||"none"}`);let a=e?.[t.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`)}}if(s.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of s.styleModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${o}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(s.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of s.textModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=JSON.stringify(t.original),a=JSON.stringify(t.modified),l=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${o}${l}: ${i} \u2192 ${a}`)}}if(s.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of s.domModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",a=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${o}${i} \u2192 ${t.targetParentSelector}${a}`)}}if(s.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of s.spacingTokenChanges){n.push(`
376
- ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let o of t.affectedElements){let i=o.reactComponent?` (${o.reactComponent})`:"";o.matchedClass&&o.suggestedClass?n.push(`- ${o.selector}${i}: \`${o.matchedClass}\` \u2192 \`${o.suggestedClass}\``):n.push(`- ${o.selector}${i}: ${o.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${o.className}"`)}}}if(s.inspectedElement){let t=s.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let o=[t.selector];t.reactComponent&&o.push(`(${t.reactComponent})`),t.context&&o.push(`in ${t.context}`),t.textContent&&o.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${o.join(" ")}`)}return n.join(`
377
- `)}function Sn(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,b=v?` [${v.breadth} ${v.target}]`:"";t.push(`- ${f.annotationId}: ${f.status}${b} \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 b=new Map;for(let E of a)if(typeof E=="object"&&E!==null&&"text"in E){let F=E,D=F.scope||"general";b.has(D)||b.set(D,[]),b.get(D).push(F.text)}for(let[E,F]of b){t.push(`**${E.charAt(0).toUpperCase()+E.slice(1)}**`);for(let D of F)t.push(`- ${D}`)}}else for(let b of a)typeof b=="string"&&t.push(`- ${b}`);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 b=a[f];b&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${b}`):!b&&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},F=De(E,n?.imagePaths);F&&(t.push(""),t.push(F))}}else{let a=De(e,n?.imagePaths);a&&(t.push(""),t.push(a))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
378
- `)}function xn(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function kt(s,e,n,t){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),n!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${s}`);let i=e.find(a=>a.role==="human"&&a.feedbackContext);if(i?.feedbackContext&&(o.push(""),o.push(i.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let a=0;for(let l of e)l.role==="human"?(a++,l.replyToQuestion?(o.push(`### Round ${a} (human) \u2014 reply`),o.push(`"${l.replyToQuestion}"`)):(o.push(`### Round ${a} (human)`),l.feedbackSummary&&o.push(`Annotations: ${l.feedbackSummary}`))):l.question?(o.push(`### Round ${a} (assistant) \u2014 question`),o.push(`"${l.question}"`)):(o.push(`### Round ${a} (assistant)`),l.responseText&&o.push(`Response: ${l.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let a of t)o.push(`Attached image: use the Read tool to view the image at: ${a}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output a resolution block listing what you did for each annotation:"),o.push("<resolution>"),o.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),o.push("</resolution>"),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
379
- `)}function Jo(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 zo(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&&!Jo(e[n]))return!1;return!0}function bn(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(zo):[]}catch{return[]}}function Pn(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 Fo}from"child_process";import{readdir as Bo,readFile as jo,stat as Lo}from"fs/promises";import{homedir as Ne}from"os";import{join as ve}from"path";var st=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:In()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:In()}],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"}],ze={id:"",label:"Default",source:"cli"},Uo=/^\s*-\s+"([^"]+)"/;function Wo(s){let e=[],n=!1;for(let t of s.split(`
380
- `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let o=t.match(Uo);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:Mt(i),source:"cli"})}return ot([ze,...e])}function Ho(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():Mt(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 In(){return["low","medium","high","xhigh","max"].map(s=>({effort:s}))}function Go(s){let e=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return ot(e.map(n=>({id:n,label:Mt(n),source:"cli"})))}function Mt(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":Yo(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 kn(s="copilot"){let e=await nt(s,["help","config"]),n=Wo(e);return n.length>1?n:[ze]}async function Mn(s="codex"){let e=await nt(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||ve(Ne(),".codex");return En(ve(t,"models_cache.json"))}),n=Ho(e);return n.length>0?ot([...n,...Je]):Je}async function Rn(s="claude"){let e=ve(Ne(),".claude"),n=[ve(Ne(),".claude","stats-cache.json"),ve(Ne(),".claude","settings.json"),ve(Ne(),".claude.json"),ve(e,"cache","changelog.md")],[t,o,i]=await Promise.all([nt(s,["--help"]).catch(()=>""),nt(s,["--version"]).catch(()=>""),qo(e).catch(()=>[])]),a=Xo([...n,...i]),l=await Promise.all(a.map(v=>En(v).catch(()=>""))),f=Go([t,o,...l].join(`
381
- `));return ot([...st,...f])}function nt(s,e,n=5e3){return new Promise((t,o)=>{Fo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function En(s){return jo(s,"utf-8")}async function qo(s){let e=[ve(s,"projects"),ve(s,"telemetry")],n=[];for(let t of e)await Tn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Tn(s,e,n){if(n<0)return;let t;try{t=await Bo(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=ve(s,o.name);if(o.isDirectory()){await Tn(i,e,n-1);return}if(!(!o.isFile()||!Qo(o.name)))try{let a=await Lo(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function Qo(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function ot(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 Xo(s){return[...new Set(s)]}function Yo(s){return s.charAt(0).toUpperCase()+s.slice(1)}var rt=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 Vo,readFile as Ko,writeFile as Zo}from"fs/promises";import{dirname as er,join as tr}from"path";var nr={version:1,threads:{}},it=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=tr(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await Ko(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={...nr,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 Vo(er(this.filePath),{recursive:!0}),await Zo(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function An(s){return or(s).slice(0,12)}var sr=[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 or(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):rr(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let F=7;F>=0;F--)e.push(n/Math.pow(2,F*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,l=1359893119,f=2600822924,v=528734635,b=1541459225,E=new Array(64);for(let F=0;F<e.length;F+=64){for(let J=0;J<16;J++){let K=F+J*4;E[J]=(e[K]<<24|e[K+1]<<16|e[K+2]<<8|e[K+3])>>>0}for(let J=16;J<64;J++){let K=we(E[J-15],7)^we(E[J-15],18)^E[J-15]>>>3,N=we(E[J-2],17)^we(E[J-2],19)^E[J-2]>>>10;E[J]=E[J-16]+K+E[J-7]+N>>>0}let D=t,H=o,U=i,w=a,G=l,Y=f,q=v,V=b;for(let J=0;J<64;J++){let K=we(G,6)^we(G,11)^we(G,25),N=G&Y^~G&q,$=V+K+N+sr[J]+E[J]>>>0,k=we(D,2)^we(D,13)^we(D,22),m=D&H^D&U^H&U,A=k+m>>>0;V=q,q=Y,Y=G,G=w+$>>>0,w=U,U=H,H=D,D=$+A>>>0}t=t+D>>>0,o=o+H>>>0,i=i+U>>>0,a=a+w>>>0,l=l+G>>>0,f=f+Y>>>0,v=v+q>>>0,b=b+V>>>0}return[t,o,i,a,l,f,v,b].map(F=>F.toString(16).padStart(8,"0")).join("")}function we(s,e){return s>>>e|s<<32-e}function rr(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 Cn={name:"@popmelt.com/core",version:"0.8.3",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 .",prepublishOnly:"pnpm run build",typecheck:"tsc --noEmit"},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",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{},devDependencies:{"@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0","lucide-react":"^1.23.0",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3"}};var $n=Cn.version;var yr=1111,vr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],wr=1800*1e3,Sr=3600*1e3;function Dn(s){return s.length<=1?s[0]??"":["The developer sent these queued steering messages while you were working:","",...s.map((e,n)=>`${n+1}. ${e}`)].join(`
382
- `)}function Fn(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 xr(s){let e=[];for(let n of s)if(n.type==="delta"){let t=n.text;if(!t)continue;let o=e[e.length-1];o&&o.kind==="text"?o.text+=t:e.push({kind:"text",text:t})}else if(n.type==="tool_use"){let t=n.tool||"",o=n.file??void 0,i=n.content??void 0,a=o?o.split("/").pop()??o:void 0,l;switch(t){case"Read":l=a?`Reading ${a}`:"Reading file";break;case"Edit":l=a?`Editing ${a}`:"Editing file";break;case"Write":l=a?`Writing ${a}`:"Writing file";break;case"Bash":l=i?i.split(`
383
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=t?`Using ${t}`:"tool";break}let f=o??i??void 0,v=e[e.length-1];v&&v.kind==="tool_group"&&v.tool===t?v.items.push({label:l,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:l,detail:f}]})}return e}function br(s,e){if(s.processedIds.length===0&&s.success)return"No unmaterialized pattern decisions were ready for model materialization.";let n=[];return s.success?n.push("Model suggestion ready."):n.push("Model materialization failed."),s.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),s.error&&(n.push(""),n.push(`Error: ${s.error}`),n.push("The selected decisions were not marked applied and remain visible in materialization history.")),n.join(`
384
- `)}function Pr(s,e=96){let n=s.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Nn(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=>Pr(a)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Ir(s,e){let n=s.headers.origin;Fn(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 g(s,e,n){s.writeHead(e,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}function kr(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function Mr(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 lt(s,e){try{s.res.write(`event: ${e.type}
182
+ `,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")v=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")g=T.body.toString("utf-8");else if(W==="pageUrl")p=T.body.toString("utf-8");else if(W==="viewport")h=T.body.toString("utf-8");else if(W==="planId")f=T.body.toString("utf-8");else if(W==="manifest")y=T.body.toString("utf-8");else if(W==="tasks")x=T.body.toString("utf-8");else if(W==="sourceId")S=T.body.toString("utf-8");else if(W.startsWith("screenshot-")){let 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:v,model:P,reasoningEffort:b,serviceTier:I,goal:g,pageUrl:p,viewport:h,planId:f,manifest:y,tasks:x,sourceId:S,pastedImages:A,pageScreenshots:J}}function qa(o){return new Promise((e,n)=>{let t=[];o.on("data",r=>t.push(r)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as Ua}from"crypto";var Wa=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,Ha=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Ga=new Set(["strengthened","weakened","mixed","unknown"]);function Qt(o,e=180){if(typeof o!="string")return;let n=o.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function Va(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Lr(o,e,n,t=Date.now()){let r=Va(o);if(!r)return null;let s=typeof r.transition=="string"&&Ha.has(r.transition)?r.transition:null,i=Qt(r.focus);if(!s||!i)return null;let c=typeof r.evidencePosture=="string"&&Ga.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Ua(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Qt(r.seeking),workingHypothesis:Qt(r.workingHypothesis),evidencePosture:c,update:Qt(r.update),nextObservation:Qt(r.nextObservation)},contextPolicy:"exclude"}}function Eo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Ka(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(Wa,(c,d)=>{try{let l=Lr(JSON.parse(d),e,s);if(!l)return"";let v=Eo(l);if(r.has(v))return"";r.add(v),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
183
+
184
+ `).trim(),orientations:t}}function Qa(o){let e="<orientation>",n=Math.min(o.length,e.length-1);for(let t=n;t>0;t--)if(e.startsWith(o.slice(-t)))return t;return 0}var On=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let c=Qa(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=Lr(JSON.parse(i),this.jobId,this.sequence);if(!c)continue;let d=Eo(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=Ka(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=Eo(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},zr=`## Public orientation updates
185
+ During meaningful transitions in the work, emit a brief public coordination update using this exact form:
186
+ <orientation>{"transition":"focus_shifted","focus":"Investigating the responsive overflow","seeking":"Which container introduces the extra width","update":"Padding is no longer the leading explanation","nextObservation":"Inspect computed widths at the failing breakpoint"}</orientation>
187
+
188
+ Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
189
+ Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
190
+
191
+ These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function Xt(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),s=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${s} \u2192 Elements: ${r||"none"}`);let i=e?.[t.id];if(i&&i.length>0)for(let c of i)n.push(` Attached image: use the Read tool to view ${c}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let s of t.changes)n.push(`- ${t.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=JSON.stringify(t.original),i=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${c}: ${s} \u2192 ${i}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",i=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${s} \u2192 ${t.targetParentSelector}${i}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
192
+ ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let r of t.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let t=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[t.selector];t.reactComponent&&r.push(`(${t.reactComponent})`),t.context&&r.push(`in ${t.context}`),t.textContent&&r.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
193
+ `)}function qr(o,e,n){let t=[],s=new Set(e.annotations.map(i=>i.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!s&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let i=0;for(let c of n.threadHistory)if(c.role==="human")i++,c.replyToQuestion?(t.push(`### Round ${i} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${i} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${i} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${i} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,v=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${v} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0)if(t.push(""),t.push("Rules:"),i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"scope"in i[0]){let v=new Map;for(let P of i)if(typeof P=="object"&&P!==null&&"text"in P){let b=P,I=b.scope||"general";v.has(I)||v.set(I,[]),v.get(I).push(b.text)}for(let[P,b]of v){t.push(`**${P.charAt(0).toUpperCase()+P.slice(1)}**`);for(let I of b)t.push(`- ${I}`)}}else for(let v of i)typeof v=="string"&&t.push(`- ${v}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),s){let i=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;c.has(l)||c.set(l,[]),c.get(l).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of c){t.push(""),t.push(`## Page: ${d}`);let v=i[d];v&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&n?.provider!=="codex"&&(Object.keys(i).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let P={...e,annotations:l,styleModifications:e.styleModifications},b=Xt(P,n?.imagePaths);b&&(t.push(""),t.push(b))}}else{let i=Xt(e,n?.imagePaths);i&&(t.push(""),t.push(i))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
194
+ `)}function Ur(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Wr(o,e,n,t){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let s=e.find(i=>i.role==="human"&&i.feedbackContext);if(s?.feedbackContext&&(r.push(""),r.push(s.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let i=0;for(let c of e)c.role==="human"?(i++,c.replyToQuestion?(r.push(`### Round ${i} (human) \u2014 reply`),r.push(`"${c.replyToQuestion}"`)):(r.push(`### Round ${i} (human)`),c.feedbackSummary&&r.push(`Annotations: ${c.feedbackSummary}`))):c.question?(r.push(`### Round ${i} (assistant) \u2014 question`),r.push(`"${c.question}"`)):(r.push(`### Round ${i} (assistant)`),c.responseText&&r.push(`Response: ${c.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let i of t)r.push(`Attached image: use the Read tool to view the image at: ${i}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
195
+ `)}function Xa(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 Ya(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&&!Xa(e[n]))return!1;return!0}function Hr(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(Ya):[]}catch{return[]}}function Gr(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 Za}from"child_process";import{readdir as ec,readFile as tc,stat as nc}from"fs/promises";import{homedir as Yt}from"os";import{join as Qe}from"path";var Jn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Vr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Vr()}],Zt=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],en={id:"",label:"Default",source:"cli"},oc=/^\s*-\s+"([^"]+)"/;function rc(o){let e=[],n=!1;for(let t of o.split(`
196
+ `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(oc);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:Ao(s),source:"cli"})}return Nn([en,...e])}function sc(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():Ao(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 Vr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function ic(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Nn(e.map(n=>({id:n,label:Ao(n),source:"cli"})))}function Ao(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":lc(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 Kr(o="copilot"){let e=await Dn(o,["help","config"]),n=rc(e);return n.length>1?n:[en]}async function Qr(o="codex"){let e=await Dn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(Yt(),".codex");return Yr(Qe(t,"models_cache.json"))}),n=sc(e);return n.length>0?Nn([...n,...Zt]):Zt}async function Xr(o="claude"){let e=Qe(Yt(),".claude"),n=[Qe(Yt(),".claude","stats-cache.json"),Qe(Yt(),".claude","settings.json"),Qe(Yt(),".claude.json"),Qe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Dn(o,["--help"]).catch(()=>""),Dn(o,["--version"]).catch(()=>""),ac(e).catch(()=>[])]),i=dc([...n,...s]),c=await Promise.all(i.map(l=>Yr(l).catch(()=>""))),d=ic([t,r,...c].join(`
197
+ `));return Nn([...Jn,...d])}function Dn(o,e,n=5e3){return new Promise((t,r)=>{Za(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function Yr(o){return tc(o,"utf-8")}async function ac(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await Zr(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Zr(o,e,n){if(n<0)return;let t;try{t=await ec(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Qe(o,r.name);if(r.isDirectory()){await Zr(s,e,n-1);return}if(!(!r.isFile()||!cc(r.name)))try{let i=await nc(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function cc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Nn(o){let e=new Set,n=[];for(let t of o)e.has(t.id)||(e.add(t.id),n.push(t));return n}function dc(o){return[...new Set(o)]}function lc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Bn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let s=this.queue.length-1;s>=0;s--)if(this.queue[s]?.threadId===e.threadId){n=s;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let s of this.listeners)s(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},s=this.activeJobs.has(e);if(!t)return null;let i=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:i,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:s}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let s=!1,i=()=>{s||(s=!0,r())};t.on("exit",i),t.on("error",i),setTimeout(()=>{if(!s){try{t.kill("SIGKILL")}catch{}setTimeout(i,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as He}from"crypto";import{createHash as pc}from"crypto";import{mkdir as uc,open as mc,readFile as es,readdir as fc,rename as hc,unlink as gc}from"fs/promises";import{dirname as yc,join as _t}from"path";function Oe(o){return structuredClone(o)}function ts(o){return pc("sha256").update(JSON.stringify(o)).digest("hex")}async function tn(o,e){await uc(yc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await mc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
198
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await hc(n,o)}catch(r){throw await gc(n).catch(()=>{}),r}}function vc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function wc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Oe(e):o.explanations.push(Oe(e))}function _o(o,e){let n=Oe(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(Oe(t.explanation))}else if(t.op==="replace_explanation")wc(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(Oe(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(Oe(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,Oe(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(Oe(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Ic(o,e){let n=[],t=Oe(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:Oe(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:Oe(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:Oe(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:Oe(s)})}t=_o(t,[r])}return n}function ns(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Fn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=_t(e,".popmelt","imprint"),this.manifestPath=_t(this.imprintDir,"manifest.json"),this.graphPath=_t(this.imprintDir,"graph.json"),this.journalDir=_t(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await es(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 fc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=vc(this.projectId,e.createdAt),s=[],i=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await es(_t(this.journalDir,t[c]),"utf8")),{hash:l,...v}=d;if(d.sequence!==c+1||d.previousHash!==i||l!==ts(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=_o(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=Ic(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:Oe(e.mutations),inverseMutations:s,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...i,hash:ts(i)},d=_o(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await tn(_t(this.journalDir,l),c);let v={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await tn(this.graphPath,d),await tn(this.manifestPath,v),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(i.mutations.flatMap(ns));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(v=>ns(v).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 tn(this.graphPath,e.graph),await tn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var bc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),xc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Sc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ln(o){return new Set(Sc(o).split(" ").filter(e=>e.length>2&&!xc.has(e)))}function zn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Co(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 nt(o,e,n){return{id:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function os(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 kc(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 $o(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(!bc.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:je(s?.title,120),detail:je(s?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(b=>typeof b=="string"&&!!b.trim()):[],l=[];for(let b of Array.isArray(r.mutations)?r.mutations:[]){if(!b||typeof b!="object")continue;let I=b;if(I.op==="add"&&["intention","principle","pattern"].includes(String(I.kind))){let g=je(I.statement),p=je(I.rationale);if(!g||!p)continue;l.push({op:"add",clientId:je(I.clientId,100)||void 0,kind:I.kind,statement:g,rationale:p,scope:os(I.scope)})}else if(I.op==="revise"&&typeof I.explanationId=="string"){let g={op:"revise",explanationId:I.explanationId,statement:je(I.statement)||void 0,rationale:je(I.rationale)||void 0,scope:os(I.scope),reopenGrounding:I.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(I.op==="evidence"&&typeof I.explanationId=="string"&&["supports","challenges","excepts"].includes(String(I.stance))){let g=je(I.summary);g&&l.push({op:"evidence",explanationId:I.explanationId,stance:I.stance,summary:g})}else if(I.op==="relation"&&typeof I.fromId=="string"&&typeof I.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(I.type)))l.push({op:"relation",type:I.type,fromId:I.fromId,toId:I.toId,rationale:je(I.rationale)});else if(I.op==="supersede"&&typeof I.explanationId=="string"&&typeof I.replacementId=="string"){let g=je(I.reason);g&&l.push({op:"supersede",explanationId:I.explanationId,replacementId:I.replacementId,reason:g})}else if(I.op==="bind_concrete"&&typeof I.explanationId=="string"){let g=je(I.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:I.explanationId,modelPath:g,rationale:je(I.rationale)})}else I.op==="retire"&&typeof I.explanationId=="string"&&l.push({op:"retire",explanationId:I.explanationId,reason:je(I.reason)})}let v=r.grounding,P=v&&typeof v.explanationId=="string"&&je(v.question)?{explanationId:v.explanationId,question:je(v.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 Oo(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(s=>` - Concrete terminal: ${s.modelPath} = ${JSON.stringify(s.value)}`)].join(`
199
+ `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]}},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
200
+ `)}var nn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Fn(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Ln(e.text??""),t=Ln((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:s}=await this.store.load(),i=s.explanations.filter(d=>d.state!=="retired"&&d.state!=="challenged").map(d=>{let l=Ln([d.statement,d.rationale].join(" ")),v=Ln(d.scope.values.join(" ")),P=zn(l,n),b=zn(v,n),I=zn(v,t),g=zn(l,t),p=P+b*.2+I*.25+g*.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||g>=.2);return{item:d,score:p,relevant:h}}).filter(d=>d.relevant&&d.score>=.18).sort((d,l)=>l.score-d.score||l.item.updatedAt.localeCompare(d.item.updatedAt)),c=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,c).map(({item:d})=>{let l=new Set(s.relations.filter(v=>v.fromId===d.id&&v.type==="instantiates").map(v=>v.toId));return{id:d.id,kind:d.kind,statement:d.statement,rationale:d.rationale,scope:d.scope,state:d.state,concrete:s.concrete.filter(v=>l.has(v.id)).map(v=>({id:v.id,modelPath:v.modelPath,value:v.value}))}}),truncated:i.length>c,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,c=new Map,d=[],l=new Set,v=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=He();S.clientId&&i.set(S.clientId,A);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,_={id:A,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:Co(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[nt(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 _=He(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?Co(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[nt(n,"supports",e.summary.detail)]};s.set(_,N),c.set(A,_),l.add(_),d.push({op:"add_explanation",explanation:N}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let b=S=>{let A=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 _=kc(n.concreteModel,S.modelPath);if(!_.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(_.value));N||(N={id:He(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:N})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=b(S.fromId),_=b(S.toId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_relation",relation:{id:He(),type:S.type,fromId:J,toId:_,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(_);continue}if(S.op==="supersede"){let J=b(S.explanationId),_=b(S.replacementId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_evidence",explanationId:J,evidence:nt(n,"challenges",S.reason)}),d.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:_},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"contradicts",fromId:_,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(_);continue}let A=b(S.explanationId);if(s.has(A))if(l.add(A),S.op==="revise"){if(c.has(P(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:Co(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:nt(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:nt(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let A=b(S),J=s.get(A);!J||J.state==="grounded"||J.state==="retired"||v.has(A)&&!l.has(A)||(l.has(A)||(l.add(A),d.push({op:"add_evidence",explanationId:A,evidence:{...nt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=He(),g=await this.store.commit({transactionId:I,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),h=[...l].flatMap(S=>{let A=p.get(S);if(!A)return[];let J=!r.graph.explanations.some(N=>N.id===S),_=A.state==="challenged"||A.state==="retired";return[{explanationId:S,action:J?"added":_?"challenged":"revised",statement:A.statement,state:A.state}]}),f=e.grounding?b(e.grounding.explanationId):void 0,y=f?p.get(f):void 0,x=y?.state==="testing"&&!v.has(y.id)?{explanationId:y.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:I,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:h,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let v of l)await this.store.undo(v,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...nt(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:{...nt(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(v=>v.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:i,summary:d,mutations:c})}};function rs(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function qn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Do(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 ss(o){let e=Do(qn(o.origin));if(e)return e;let n=Do(qn(o.referer));if(n)return n;let t=qn(o["x-forwarded-host"]);if(!t)return null;let r=qn(o["x-forwarded-proto"])==="https"?"https":"http";return Do(`${r}://${t}`)}function is(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 Un}from"crypto";import{mkdir as on,readFile as wt,unlink as Tc,writeFile as $t}from"fs/promises";import{dirname as Wn,extname as jc,join as De}from"path";var Rc={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 Pc(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 as(o,e){let n=e??Pc(o);return{kind:n,...Rc[n]}}function Ct(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function cs(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 Mc={version:1,threads:{}},ds=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],rn={version:2,updatedAt:0,files:{}};function Ec(o){return JSON.stringify(o,null,2)}function Ac(o){return Object.fromEntries(ds.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function _c(o){let e={...o};for(let n of ds)delete e[n];return e}function Ot(o){let e=o;if(o.error){let n=as(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=Ct(e.result,!1),t=Ct(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Hn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=De(e,".popmelt");this.legacyFilePath=De(n,"threads.json"),this.threadsDir=De(n,"threads"),this.indexPath=De(this.threadsDir,"index.json"),this.artifactsDir=De(n,"artifacts","thread-messages"),this.mediaDir=De(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await wt(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(De(this.threadsDir,r));s&&(n[t]=s)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await wt(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(Ot)}]))},this.index={...rn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Mc,threads:{}},this.index={...rn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Ot(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,Ot(n)):r.messages.push(Ot(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=Ot(c);Object.assign(c,d),delete c.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(h=>h.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(h=>h.role==="assistant"),d=h=>{if(h.role!=="assistant")return;if(h.question)return h.question;let f=h.imprintSummary?.grounding;if(f?.question&&!h.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(h=>!!d(h)),v=r.messages.findLastIndex(h=>h.role==="human"),P=l>v?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,I=Array.from(new Set(r.messages.slice(0,Math.max(0,v)).filter(h=>h.role==="assistant"&&!!h.jobId).map(h=>h.jobId))),g=c.some(h=>!!h.responseText||!!h.question||!!h.result||!!h.memoryReviewCard||!!h.memoryReceipt),p=c.some(h=>!!h.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:b,pendingQuestion: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 wt(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 wt(De(Wn(this.legacyFilePath),r.path),"utf8");Un("sha256").update(c).digest("hex")===r.sha256&&(i=JSON.parse(c))}catch{}return Ot({...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=Ac(e),t=_c(e);if(Object.keys(n).length===0)return t;let r=Ec(n),s=Un("sha256").update(r).digest("hex"),i=De("artifacts","thread-messages",`${s}.json`);await on(this.artifactsDir,{recursive:!0});try{await wt(De(Wn(this.legacyFilePath),i),"utf8")}catch{await $t(De(Wn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Wn(t)===this.mediaDir)return t;try{let r=await wt(t),s=Un("sha256").update(r).digest("hex"),i=De(this.mediaDir,`${s}${jc(t)||".bin"}`);await on(this.mediaDir,{recursive:!0});try{await wt(i)}catch{await $t(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await on(this.threadsDir,{recursive:!0});let n=this.index??{...rn,files:{}},t=n.files[e.id]??`${Un("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 $t(De(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await $t(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await on(this.threadsDir,{recursive:!0}),this.index=this.index??{...rn,files:{}},await $t(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...rn,files:{}},t=n.files[e];t&&await Tc(De(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await on(this.threadsDir,{recursive:!0}),await $t(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};function ls(o){return $c(o).slice(0,12)}var Cc=[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 $c(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Oc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(n/Math.pow(2,b*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,c=1359893119,d=2600822924,l=528734635,v=1541459225,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=Xe(P[A-15],7)^Xe(P[A-15],18)^P[A-15]>>>3,_=Xe(P[A-2],17)^Xe(P[A-2],19)^P[A-2]>>>10;P[A]=P[A-16]+J+P[A-7]+_>>>0}let I=t,g=r,p=s,h=i,f=c,y=d,x=l,S=v;for(let A=0;A<64;A++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),_=f&y^~f&x,N=S+J+_+Cc[A]+P[A]>>>0,T=Xe(I,2)^Xe(I,13)^Xe(I,22),B=I&g^I&p^g&p,W=T+B>>>0;S=x,x=y,y=f,f=h+N>>>0,h=p,p=g,g=I,I=N+W>>>0}t=t+I>>>0,r=r+g>>>0,s=s+p>>>0,i=i+h>>>0,c=c+f>>>0,d=d+y>>>0,l=l+x>>>0,v=v+S>>>0}return[t,r,s,i,c,d,l,v].map(b=>b.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Oc(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 ps={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 sn=ps.version;var Hc=1111,Gc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Vc=1800*1e3,Kc=3600*1e3,fs=45e3,Qc=5e3,Xc=1e4;function hs(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(`
201
+ `)}function Vn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function Yc(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 xs(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 Zc(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(`
202
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let l=s??i??void 0,v=s?No(s)?s:bs(e,s):void 0,P=n[n.length-1];P&&P.kind==="tool_group"&&P.tool===r?P.items.push({label:d,detail:l,...v?{filePath:v}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...v?{filePath:v}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function ed(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(`
203
+ `)}function td(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function gs(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=>td(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function nd(o,e){let n=o.headers.origin;xs(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function E(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function Ge(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 od(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function rd(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 Kn(o,e){try{o.res.write(`event: ${e.type}
385
204
  data: ${JSON.stringify(e)}
386
205
 
387
- `)}catch{}}function Be(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}var Rr=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Er=new Set(["default","flex","fast","priority"]);function je(s){let e=typeof s.reasoningEffort=="string"&&Rr.has(s.reasoningEffort)?s.reasoningEffort:void 0,n=typeof s.serviceTier=="string"&&Er.has(s.serviceTier)?s.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function Tr(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}async function Ar(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 Cr(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 Jn(s){try{let e=ct("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=ct("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=ct("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return ar("sha256").update(`${e}
206
+ `)}catch{}}function It(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function sd(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 id(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 ys(o){try{let e=Qn("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=Qn("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=Qn("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Is("sha256").update(`${e}
388
207
  ${t}
389
- ${o}`).digest("hex").slice(0,16)}catch{return}}async function Bn(s={}){let e=s.port??yr,n=s.projectRoot??process.cwd(),t=await dr(n).catch(()=>n),o=An(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??ye(hr(),"popmelt-bridge"),l=s.maxTurns??40,f=s.maxBudgetUsd??1,v=[...s.allowedTools??vr],b=s.claudePath??"claude",E=s.copilotPath??"copilot",F=s.provider??"claude",D=s.timeoutMs,H=s.restartMode??"embedded",U=e,w={},G={claude:b,codex:"codex",copilot:E};for(let[r,c]of Object.entries(G))try{let u=c.includes("/")?c:ct("which",[c],{encoding:"utf-8"}).trim();w[r]={available:!0,path:u}}catch{w[r]={available:!1,path:null}}function Y(r,c){return new Promise(u=>{let p=_n(c,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=y=>{h||(h=!0,u(y))},P=setTimeout(()=>{p.kill("SIGTERM"),d(!0)},5e3);p.on("error",()=>{clearTimeout(P),d(!1)}),p.on("close",y=>{clearTimeout(P),d(y===0)})})}await Promise.all([(async()=>{w.claude&&(w.claude.models=w.claude.available&&w.claude.path?await Rn(w.claude.path).catch(()=>st):st)})(),(async()=>{w.codex&&(w.codex.models=w.codex.available&&w.codex.path?await Mn(w.codex.path).catch(()=>Je):Je)})(),(async()=>{w.copilot&&(w.copilot.models=w.copilot.available&&w.copilot.path?await kn(w.copilot.path).catch(()=>[ze]):[ze])})()]);let[q,V,J]=await Promise.all([St(t),xt(t),bt(t,w.copilot?.path??E)]),K=await un(t);w.claude&&(w.claude.mcp=q),w.codex&&(w.codex.mcp=V),w.copilot&&(w.copilot.mcp=J),q.found&&q.name&&v.push(`mcp__${q.name}__*`),await lr(a,{recursive:!0}),zn(a).catch(()=>{});let N=new rt(1),$=new Ke,k=new Set,m=new it(t),A=new Ge(t),T=new qe(t),x=new Ye(t,A,{claudePath:b,provider:F,timeoutMs:D,onEvent:r=>{for(let c of k)lt(c,r)}}),L=20,_=300*1e3,Z=[];function z(){let r=Date.now()-_;for(;Z.length>0&&(Z[0].completedAt<r||Z.length>L);)Z.shift()}let ne=new Map,pe=null,fe;N.addListener((r,c,u)=>{for(let p of k)(!u||!p.sourceId||p.sourceId===u)&&lt(p,r)}),$.addListener((r,c,u)=>{for(let p of k)(!u||!p.sourceId||p.sourceId===u)&&lt(p,r)}),$.setProcessor(async r=>{let c=r.provider??F;try{let u=await x.run({provider:c,model:r.model,threadId:r.threadId,agentSettings:r.agentSettings});if(r.status==="cancelled")return;let p=await x.loadRuns(),h=u.runId?p.runs.find(P=>P.id===u.runId):void 0,d=br(u,h);if(r.threadId&&(await m.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})||await m.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,$.broadcast({type:"done",jobId:r.id,success:!0,responseText:d,threadId:r.threadId},r.id,r.sourceId),Z.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),z();else{if(r.status="error",r.error=u.error??"Materialization failed",r.threadId){let P=`Model materialization failed.
208
+ ${r}`).digest("hex").slice(0,16)}catch{return}}function ad(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 vs(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,ad(n,s.value)]);else if(s.kind==="source_file"){let i=bs(o,s.value),d=i===o||i.startsWith(`${o}/`)?await Jo(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,d])}else r.push([s.kind,s.value]);return Is("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ss(o={}){let e=new Date().toISOString(),n=o.port??Hc,t=o.projectRoot??process.cwd(),r=await Bc(t).catch(()=>t),s=ls(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Me(qc(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,v=[...o.allowedTools??Gc],P=o.claudePath??"claude",b=o.copilotPath??"copilot",I=o.provider??"claude",g=o.timeoutMs,p=o.restartMode??"embedded",h=n,f={},y={claude:P,codex:"codex",copilot:b};for(let[a,u]of Object.entries(y))try{let R=u.includes("/")?u:Qn("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=us(u,["--version"],{stdio:["ignore","ignore","ignore"]}),k=!1,w=$=>{k||(k=!0,R($))},j=setTimeout(()=>{m.kill("SIGTERM"),w(!0)},5e3);m.on("error",()=>{clearTimeout(j),w(!1)}),m.on("close",$=>{clearTimeout(j),w($===0)})})}await Promise.all([(async()=>{f.claude&&(f.claude.models=f.claude.available&&f.claude.path?await Xr(f.claude.path).catch(()=>Jn):Jn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await Qr(f.codex.path).catch(()=>Zt):Zt)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await Kr(f.copilot.path).catch(()=>[en]):[en])})()]);let[S,A,J]=await Promise.all([mo(r),fo(r),ho(r,f.copilot?.path??b)]),_=await hr(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=A),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&v.push(`mcp__${S.name}__*`),await Jc(c,{recursive:!0}),ws(c).catch(()=>{});let N=new Bn(1),T=new bn,B=new kn(fs),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()+Xc,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 Hn(r),q=new _n(r),fe=new nn(r,s),M=new fn(r),Z=new yn(r),V=new In(r,{claudePath:P,provider:I,timeoutMs:g,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let u of Y)Kn(u,a)}});q.beginAutomaticInitialization({writerVersion:sn}).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 Nt({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 Pe=20,Ee=300*1e3,Ie=[];function Ae(){let a=Date.now()-Ee;for(;Ie.length>0&&(Ie[0].completedAt<a||Ie.length>Pe);)Ie.shift()}let Je=new Map;async function Dt(a){if(a.status!=="applied")return[];let u={version:1,updatedAt:Date.now(),cases:await q.getJournalEvalCases()},R=or(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=>No(D)?ms(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"),C=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:C.map(ae=>({name:ae})),subjectIds:O})):[{id:C.length>0?`component-${C[0]}`:"current-page",components:C.map(U=>({name:U})),subjectIds:O}];return{...D,dependencies:L,scenarios:D.scenarios?.length?D.scenarios:Q}}),$=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:$.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 qe(a){let u=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",R=ro(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 ot=null,Jt;N.addListener((a,u,R)=>{for(let m of Y)(!R||!m.sourceId||m.sourceId===R)&&Kn(m,a)}),T.addListener((a,u,R)=>{for(let m of Y)(!R||!m.sourceId||m.sourceId===R)&&Kn(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),$=await V.loadModel(),D=j?lr(j,$):null;if(j&&D){let L=j.decisionIds.map(C=>({decisionId:C,status:"projected"}));await q.applyModelProjection({runId:j.runId??j.id,presentationJobId:j.presentationJobId,decisionIds:j.decisionIds,changes:D.map(C=>({path:C.path,value:C.value,decisionIds:C.decisionIds})),coverage:L});let F=await V.applySelectedModelProposal(j.id,D.map(C=>({path:C.path,value:C.value})),D.map(C=>({group:C.path[0]==="rules"||C.path[0]==="components"||C.path[0]==="tokens"?C.path[0]:"model",label:C.label??C.id,detail:C.rationale,path:C.path,value:C.value})),"automatic");F&&await Dt(F)}}let w=ed(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),Ie.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ae();else{if(a.status="error",a.error=R.error??"Projection failed",a.threadId){let j=`Model projection failed.
390
209
 
391
- ${r.error}`;await m.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})||await m.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})}$.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),Z.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),z()}}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.
210
+ ${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),Ie.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ae()}}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.
392
211
 
393
- ${r.error}`;await m.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})||await m.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})}$.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),Z.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),z()}}),N.setProcessor(async r=>{let c=r,u=c._replyPrompt,p=c._replyText,h=c._replyImagePaths,d=r.provider??F;r.threadId&&p!==void 0&&await m.updateMessage(r.threadId,r.id,{queued:!1});let P;if(r.threadId){let O=await m.getThread(r.threadId);if(O){for(let W=O.messages.length-1;W>=0;W--)if(O.messages[W].sessionId){P=O.messages[W].sessionId;break}}}let y;if(P&&u){if(y=p??u,h&&h.length>0){y+=`
212
+ ${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),Ie.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ae()}}),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),$=!!u._evalRemediation,D=!j&&!["run_eval","synthesize_evals","synthesize","project_model"].includes(a.kind??"");a.threadId&&m!==void 0&&await G.updateMessage(a.threadId,a.id,{queued:!1});let L;if(a.threadId){let de=await G.getThread(a.threadId);if(de){for(let pe=de.messages.length-1;pe>=0;pe--)if(de.messages[pe].sessionId){L=de.messages[pe].sessionId;break}}}(j||$)&&(L=void 0);let F;if(L&&R){if(F=m??R,k&&k.length>0){F+=`
394
213
 
395
- The developer attached reference images with their reply:`;for(let O of h)y+=`
396
- Attached image: use the Read tool to view the image at: ${O}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?y+=`
214
+ The developer attached reference images with their reply:`;for(let de of k)F+=`
215
+ Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?F+=`
397
216
 
398
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:y+=`
217
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+=`
399
218
 
400
- After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(P)y=De(r.feedback,r.imagePaths)+`
219
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(L)F=Xt(a.feedback,a.imagePaths)+`
401
220
 
402
221
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
403
222
 
404
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(d!=="codex"?`
223
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(w!=="codex"?`
405
224
 
406
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let O=!u&&r.threadId?await m.getThreadHistory(r.threadId):void 0,W=u?null:await x.loadModel();y=u??Sn(r.screenshotPath,r.feedback,{threadHistory:O&&O.length>0?O:void 0,provider:d,imagePaths:r.imagePaths,designModel:W??void 0,screenshotPaths:r.screenshotPaths})}let R=Mr(r.color,`[\u22B9 ${U}:${r.id}]`),I=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${R} Reviewing ${I} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${P?` (resuming: ${P.slice(0,8)})`:""}`);let C=(O,W)=>{O.type==="delta"&&"text"in O?N.accumulateText(W,"response",O.text):O.type==="thinking"&&"text"in O&&N.accumulateText(W,"thinking",O.text),N.broadcast(O,W,r.sourceId)},{process:ee,result:Q}=d==="codex"?He(r.id,{prompt:y,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:P,model:r.model,configOverrides:Tr(r.agentSettings),onEvent:C}):d==="copilot"?Ut(r.id,{prompt:y,projectRoot:t,resumeSessionId:P,model:r.model,timeoutMs:D,copilotPath:w.copilot?.path??E,onEvent:C}):Ue(r.id,{prompt:y,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:v,claudePath:b,resumeSessionId:P,model:r.model,reasoningEffort:r.agentSettings?.reasoningEffort,timeoutMs:D,onEvent:C});N.setActiveProcess(r.id,ee);let S=await Q;if(r.result=S.text,S.success){console.log(`${R} Iteration complete`),S.fileEdits&&S.fileEdits.length>0&&console.log(`${R} Captured ${S.fileEdits.length} file edit(s): ${S.fileEdits.map(B=>`${B.tool} ${B.file_path}`).join(", ")}`),S.editEvents&&S.editEvents.length>0&&console.log(`${R} Captured ${S.editEvents.length} edit event(s): ${S.editEvents.map(B=>`${B.operation} ${B.filePath}`).join(", ")}`),r.status="done";let O=xn(S.text),W=bn(S.text),se=W.some(B=>(B.finalScope??B.inferredScope)?.breadth==="pattern");if(W.length>0&&r.annotationIds&&r.annotationIds.length>0){let B=new Set(r.annotationIds);W.every(te=>B.has(te.annotationId))||(W=W.map((te,ue)=>({...te,annotationId:r.annotationIds[ue%r.annotationIds.length]})))}let ae=S.fileEdits&&S.fileEdits.length>0?S.fileEdits.map(B=>`${B.tool} ${B.file_path.split("/").pop()}`):S.toolsUsed,ce=N.getBufferedEvents(r.id),de=ce?xr(ce.events):void 0;if(r.threadId&&await m.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:S.text,resolutions:W.length>0?W:void 0,question:O??void 0,sessionId:S.sessionId,toolsUsed:ae,editEvents:S.editEvents&&S.editEvents.length>0?S.editEvents:void 0,segments:de&&de.length>0?de:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&A.captureGitDiff(t).then(async B=>{let oe=Date.now(),te=r.imagePaths?Object.values(r.imagePaths).flat():[],ue=[];if(r.imagePaths)for(let[j,M]of Object.entries(r.imagePaths))for(let X=0;X<M.length;X++)ue.push(`screenshots/p-${r.id}-${j}-${X}.webp`);await A.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:ue,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:W.length>0?W:[],question:O??void 0,fileEdits:S.fileEdits??[],editEvents:S.editEvents??[],toolsUsed:ae,gitDiff:B},r.screenshotPath,te),se&&d!=="copilot"?await Rt({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(`${R} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&S.text){let B=Ve(S.text);if(B){Array.isArray(B.rules)&&(B.rules=_e(B.rules));let oe=await x.loadModel();oe&&(!B.tokens&&oe.tokens&&(B.tokens=oe.tokens),!B.components&&oe.components&&(B.components=oe.components)),await x.writeModel(B),console.log(`${R} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&S.text){let B=Qt(S.text),oe=Xt(S.text),te=B??oe;if(te&&te.length>0){let ue=await T.writeSynthesized(te),j=r._proposalId;j&&await x.attachGeneratedEvals(j,te.map(M=>M.id)),console.log(`${R} Eval synthesis: wrote ${te.length} ${B?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${ue.cases.length} total)`)}}else if(r.kind==="run_eval"&&S.text&&r.evalId&&r.evalRunId){let B=await T.findCase(r.evalId),oe=r._evalRunScope;if(B&&oe){let te=Yt(S.text,B.assertions),ue=Date.now();await T.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:ue,durationMs:ue-r.createdAt,scope:oe,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:Jn(t),rawResponse:S.text,...te}),console.log(`${R} Eval run: ${B.title} \u2192 ${te.status}`)}}O&&(console.log(`${R} \u{1F4AC} Question detected: "${O.slice(0,120)}" \u2192 broadcasting to ${k.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),N.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:O,annotationIds:r.annotationIds},r.id,r.sourceId));let le=Pn(S.text);le.length>0&&(console.log(`${R} Novel pattern(s): ${le.map(B=>`${B.category}/${B.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:r.id,patterns:le,threadId:r.threadId},r.id,r.sourceId)),N.broadcast({type:"done",jobId:r.id,success:!0,resolutions:W.length>0?W:void 0,responseText:S.text,threadId:r.threadId},r.id,r.sourceId),Z.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${R} Error: ${S.error}`),r.status="error",r.error=S.error,r.threadId&&await m.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:S.error||"Unknown error",model:r.model,provider:d}),N.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),Z.push({id:r.id,status:"error",completedAt:Date.now(),error:S.error,threadId:r.threadId,annotationIds:r.annotationIds});z()});let dt=fr(async(r,c)=>{if(Ir(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:${U}`),d=h.pathname,P=kr(r,h);if(P&&P!==o){g(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:at(t)});return}if(r.headers.origin){if(!Fn(r.headers.origin)){g(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(P!==o){g(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:at(t)});return}}try{if(r.method==="POST"&&d==="/send")await Gn(r,c);else if(r.method==="GET"&&d==="/events")Qn(r,c);else if(r.method==="GET"&&d==="/status")await Xn(c,P);else if(r.method==="PATCH"&&d==="/config")await Yn(r,c);else if(r.method==="POST"&&d==="/shutdown"){if(H!=="detached"){g(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:H});return}g(c,200,{ok:!0}),setTimeout(()=>process.exit(0),100)}else if(r.method==="POST"&&d==="/restart"){if(H!=="detached"){g(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:H});return}g(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let y of k)try{y.res.end()}catch{}dt.close(()=>{_n(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")g(c,200,{providers:w});else if(r.method==="POST"&&d==="/mcp/install")await ls(r,c);else if(r.method==="POST"&&d==="/reply")await qn(r,c);else if(r.method==="POST"&&d==="/cancel")Vn(r,c);else if(r.method==="POST"&&d==="/materialize")await Kn(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let y=await x.loadRuns();g(c,200,y)}else if(r.method==="GET"&&d==="/model/proposals"){let y=await x.loadModelProposals();g(c,200,y)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let y=d.slice(17,-15);await es(y,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let y=d.slice(17,-6);await Zn(y,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let y=d.slice(17,-8);await ts(y,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let y=d.slice(17,-14);await ns(y,r,c)}else if(r.method==="POST"&&d==="/model/component")await cs(r,c);else if(r.method==="DELETE"&&d==="/model/component")await ds(r,c);else if(r.method==="PATCH"&&d==="/model/token")await us(r,c);else if(r.method==="DELETE"&&d==="/model/token")await ps(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:y,model:R,agentSettings:I}=await Ie(r);if(y==="copilot"){g(c,400,{error:"Model consolidation is not available for Copilot yet."});return}x.consolidate({provider:y,model:R,agentSettings:I}).catch(C=>console.error("[Bridge] Consolidation error:",C)),g(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await ss(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await os(r,c);else if(r.method==="GET"&&d==="/evals"){let y=await T.loadSuiteWithCurrentRuns(Jn(t));g(c,200,y)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let y=d.slice(7,-4);await rs(y,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await is(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let y=await x.loadModel();g(c,200,{model:y})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let y=d.slice(6,d.length-7),R=parseInt(h.searchParams.get("afterSeq")??"-1",10),I=N.getBufferedEvents(y,isNaN(R)?-1:R);I?g(c,200,I):g(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await gs(p.slice(7),c);else if(r.method==="GET"&&d==="/threads/recent"){let y=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),R=await m.listRecent(y);g(c,200,R)}else if(r.method==="GET"&&d.startsWith("/thread/")){let y=d.slice(8);await ys(y,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let y=d.slice(8);await vs(y,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?fs(r,c):r.method==="GET"&&d==="/canvas/manifest"?await hs(c):r.method==="GET"&&d==="/canvas/app.mjs"?await ms(c):g(c,404,{error:"Not found"})}catch(y){console.error("[Bridge] Request error:",y),g(c,500,{error:y instanceof Error?y.message:"Internal error"})}});async function Gn(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:P,reasoningEffort:y,serviceTier:R,sourceId:I,pastedImages:C,pageScreenshots:ee}=await tt(r),Q;try{Q=JSON.parse(p)}catch{g(c,400,{error:"Invalid feedback JSON"});return}let S=xe().slice(0,8),O={};if(ee.length>0)for(let M of ee){let X=encodeURIComponent(M.pathname),re=ye(a,`screenshot-${S}-${X}.webp`);await Fe(re,M.data),O[M.pathname]=re}let W=ye(a,`screenshot-${S}.webp`);await Fe(W,u);let se={};if(C.length>0)for(let M of C){let X=ye(a,`pasted-${S}-${M.annotationId}-${M.index}.webp`);await Fe(X,M.data),se[M.annotationId]||(se[M.annotationId]=[]),se[M.annotationId].push(X)}let ae=Q.annotations.map(M=>M.linkedSelector?M.pathname?`${M.pathname}:${M.linkedSelector}`:M.linkedSelector:null).filter(M=>!!M),ce;if(ae.length>0){let M=await m.findContinuationThread(ae);M?(ce=M.id,await m.addElementIdentifiers(ce,ae)):ce=(await m.createThread(S,ae)).id}else ce=(await m.createThread(S,[])).id;let de=Q.annotations.map(M=>M.id),le=Object.keys(O).length>0,B={id:S,status:"queued",screenshotPath:W,feedback:Q,createdAt:Date.now(),color:h,threadId:ce,annotationIds:de,provider:Be(d),model:P||void 0,agentSettings:je({reasoningEffort:y,serviceTier:R}),...Object.keys(se).length>0?{imagePaths:se}:{},sourceId:I||void 0,...le?{screenshotPaths:O}:{}},oe=new Set(Q.annotations.map(M=>M.pathname).filter(Boolean)),te;if(oe.size>1){let M=new Map;for(let X of Q.annotations){let re=X.pathname||"(unknown)";M.has(re)||M.set(re,[]),M.get(re).push(X.instruction||Nn({...Q,annotations:[X]}))}te=[...M.entries()].map(([X,re])=>`\`${X}\`
407
- ${re.map(ut=>`- ${ut}`).join(`
225
+ 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??qr(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:w,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}F+=Nr(a.memoryReview),D&&(F+=Oo(a.imprintContext)),F+=`
226
+
227
+ ${zr}`;let C=rd(a.color,`[\u22B9 ${h}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${C} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${L?` (resuming: ${L.slice(0,8)})`:""}`);let Q=new On(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 $e of Ce.orientations)N.broadcast({type:"orientation",jobId:pe,orientation:$e},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"?mn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:L,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:ln(a.agentSettings),onEvent:U}):w==="copilot"?er(a.id,{prompt:F,projectRoot:r,resumeSessionId:L,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??b,onEvent:U}):pn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:j?["Read"]:v,claudePath:P,resumeSessionId:L,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:g,onEvent:U});N.setActiveProcess(a.id,ie);let re=await ae,be=Q.finalize(re.text),ye=be.visibleText,K=D?$o(ye):{visibleText:ye,draft:void 0,error:void 0},we=K.visibleText;for(let de of be.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=we,re.success){console.log(`${C} Iteration complete`),re.fileEdits&&re.fileEdits.length>0&&console.log(`${C} 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(`${C} Captured ${re.editEvents.length} edit event(s): ${re.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Ur(ye),pe=Hr(ye);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let z=new Set(a.annotationIds);pe.every(Ve=>z.has(Ve.annotationId))||(pe=pe.map((Ve,Ke)=>({...Ve,annotationId:a.annotationIds[Ke%a.annotationIds.length]})))}let Ce=re.fileEdits&&re.fileEdits.length>0?re.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):re.toolsUsed,$e=N.getBufferedEvents(a.id),Ze=$e?Zc($e.events,r):void 0,ke,ee=Fr(ye),me=Br(ye);if(me)if(!(a.memoryReview?.packets.some(se=>se.proposalId===me.proposalId)||a.surfacedProposalIds?.includes(me.proposalId)))ke={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{ke=await q.commitConversationalReview(me)}catch(se){ke={status:"rejected",action:me.action,proposalId:me.proposalId,message:se instanceof Error?se.message:String(se)}}let Re=[...(re.fileEdits??[]).map(z=>z.file_path),...(re.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],xe,mt=a.imprintContext?.pendingGroundingExplanationIds??[];if(K.draft?.decision==="none"&&fe.recordNoop(K.draft.reason),a.threadId&&K.draft?.decision==="mutate"&&!me&&!ee)try{xe=await fe.capture(K.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await V.loadModel(),pendingGroundingExplanationIds:mt}),xe&&await q.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(z=>console.warn(`${C} Canonical Imprint evidence linkage failed:`,z))}catch(z){console.warn(`${C} Continuous imprint update failed; the thread result remains available:`,z instanceof Error?z.message:String(z))}else K.error&&console.warn(`${C} Ignored invalid imprint block: ${K.error}`);let Ue=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let z=await G.getThread(a.threadId),se=new Set(xe.changes.map(Ke=>Ke.explanationId)),Ve=z?Yc(z.messages,se):void 0;if(Ve?.imprintSummary){let Ke=Ve.imprintSummary;await G.updateAssistantMessage(a.threadId,Ve.jobId,{imprintSummary:{...Ke,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Ke.additionalObservationCount??0)+1,coalescedTransactionIds:[...Ke.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let Ft=cs({question:de,resolutions:pe,changedFiles:Re,decisionRequired:!!ee,imprintTransactionId:Ue,groundingRequired:!!xe?.grounding}),X=Ze?.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.":we;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&&Ze&&Ze.length>0?Ze:void 0,turn:{phase:"complete",orientation:X,result:Ft},result:Ft,memoryReviewCard:ee??void 0,memoryReceipt:ke,imprintSummary:xe,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??(Cn(a.feedback)||"[request unavailable]"),responseSummary:de??we,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=>No(se)?ms(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(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,se instanceof Error?se.message:String(se))}}if(ke?.status==="committed"&&ke.decisionId&&w!=="copilot"&&await Nt({provider:w,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${ke.decisionId}`}),a.kind==="run_eval"&&we&&a.evalId&&a.evalRunId){let z=await q.findJournalEvalCase(a.evalId),se=a._evalRunScope;if(z&&se){let Ve=nr(ye,z.assertions),Ke=Date.now(),Bs={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:se,provider:w,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:ys(r),rawResponse:ye,scopeFingerprint:a._evalScopeFingerprint,...Ve};await q.recordEvalVerification(z,Bs),console.log(`${C} Eval run: ${z.title} \u2192 ${Ve.status}`)}}de&&(console.log(`${C} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${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=Gr(ye);ue.length>0&&(console.log(`${C} 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:we,threadId:a.threadId,annotationIds:a.annotationIds,result:Ft},a.id,a.sourceId),Ie.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${C} 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),Ie.push({id:a.id,status:"error",completedAt:Date.now(),error:re.error,threadId:a.threadId,annotationIds:a.annotationIds});Ae()});let bt=zc(async(a,u)=>{if(nd(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=od(a,k);if(j&&j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Gn(r)});return}if(a.headers.origin){if(!xs(a.headers.origin)){E(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Gn(r)});return}}try{if(a.method==="POST"&&w==="/send")await rt(a,u);else if(a.method==="GET"&&w==="/events")Ye(a,u);else if(a.method==="GET"&&w==="/status")await st(a,u,j);else if(a.method==="PATCH"&&w==="/config")await it(a,u);else if(a.method==="POST"&&w==="/leases"){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Ge(a),D=typeof $.leaseId=="string"?$.leaseId.trim():"",L=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){E(u,400,{error:"A valid leaseId is required."});return}ne();let F=B.acquire(D,L);E(u,201,{ok:!0,lease:F,ttlMs:fs})}catch{E(u,400,{error:"Invalid lease request."})}}else if(w.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(w.slice(8))}catch{E(u,400,{error:"Invalid lease id."});return}if(!$){E(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat($);if(!D){E(u,404,{error:"Lease not found."});return}E(u,200,{ok:!0,lease:D})}else{let D=B.release($);E(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&he()}}else if(a.method==="POST"&&w==="/shutdown"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&w==="/restart"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of Y)try{$.res.end()}catch{}bt.close(()=>{us(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&w==="/capabilities")E(u,200,{providers:f});else if(w.startsWith("/imprint/"))await ve(a,u,w);else if(w.startsWith("/memory/"))await Xn(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await Zn(a,u);else if(a.method==="POST"&&w==="/reply")await _e(a,u);else if(a.method==="POST"&&w==="/cancel")pt(a,u);else if(a.method==="POST"&&w==="/materialize")E(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&w==="/materialization-runs")E(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&w==="/projection-runs"){let $=await V.loadRuns();E(u,200,$)}else if(a.method==="GET"&&w==="/projection/proposals"){let $=await V.loadModelProposals();E(u,200,$)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply-selected")){let $=w.slice(22,-15);await Bt($,a,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply")){let $=w.slice(22,-6);await Yn($,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/dismiss")){let $=w.slice(22,-8);await Ne($,a,u)}else if(w.startsWith("/model/proposals/"))E(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await cn(a,u);else if(a.method==="DELETE"&&w==="/model/component")await Ms(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Es(a,u);else if(a.method==="DELETE"&&w==="/model/token")await As(a,u);else if(a.method==="POST"&&w==="/model/consolidate")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/model/synthesize")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/evals/synthesize")E(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&w==="/evals"){let $=await V.loadModel(),D=await Promise.all((await q.getJournalEvalCases()).map(async C=>{let O=await vs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),L=ys(r),F=(await q.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===L);E(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:F,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&w.startsWith("/evals/")&&w.endsWith("/run")){let $=w.slice(7,-4);await at($,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await xt(w.slice(7),a,u);else if(a.method==="GET"&&w==="/model"){let $=await V.loadModel();E(u,200,{model:$})}else if(a.method==="GET"&&w.startsWith("/jobs/")&&w.endsWith("/events")){let $=w.slice(6,w.length-7),D=parseInt(k.searchParams.get("afterSeq")??"-1",10),L=N.getBufferedEvents($,isNaN(D)?-1:D);L?E(u,200,L):E(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await Os(m.slice(7),u);else if(a.method==="GET"&&w==="/threads/recent"){let $=Math.min(Math.max(parseInt(k.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent($);E(u,200,D)}else if(a.method==="GET"&&w.startsWith("/decision/")){let $=w.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))E(u,400,{error:"Invalid decision id"});else{let D=await G.getThread($),L=[...D?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(D&&L?.annotationSnapshot){let F=[...D.messages].reverse().find(C=>C.resolutions?.length);E(u,200,{decision:{id:D.id,createdAt:L.timestamp,url:L.annotationSnapshot.url,viewport:L.annotationSnapshot.viewport,color:L.annotationSnapshot.color,annotations:L.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await M.loadDecision($);F?E(u,200,{decision:F,authority:"legacy_archive"}):E(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let $=w.slice(8);await Ds($,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let $=w.slice(8);await Js($,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?_s(a,u):a.method==="GET"&&w==="/canvas/manifest"?await Cs(u):a.method==="GET"&&w==="/canvas/app.mjs"?await $s(u):E(u,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),E(u,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function Xn(a,u,R){try{if(a.method==="GET"&&R==="/memory/status"){E(u,200,await q.status());return}if(a.method==="GET"&&R==="/memory/diagnostics"){E(u,200,await q.diagnostics());return}if(a.method==="GET"&&R==="/memory/model-view"){E(u,200,await q.getModelView());return}if(a.method==="POST"&&R==="/memory/constraints"){let m=await Ge(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():"",$=await q.getModelView(),D=k?$.entries.filter(C=>C.key===`components.${k}`||C.key.startsWith(`components.${k}.`)):[],L=(C,O)=>{if(!O)return!1;if(!C.includes("*"))return C===O;let Q=C.split("*").map(U=>U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`).test(O)},F=(await q.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(U=>U.kind==="route"&&L(U.value,w)||U.kind==="subject"&&U.value===j),Q=(C.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(C=>({id:C.id,title:C.title,verificationState:C.verificationState,assertions:C.assertions}));E(u,200,{modelEntries:D,evals:F});return}if(a.method==="POST"&&R==="/memory/conversation-action"){let m=await Ge(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)){E(u,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await G.getThread(k),D=$?.messages.find(ae=>ae.memoryReviewCard?.proposalId===w)?.memoryReviewCard;if(!$||!D){E(u,409,{error:"This decision review card is not available in the thread."});return}let L=await 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,C={proposalId:w,action:j,kind:D.kind,claim:j==="edit_and_accept"&&typeof m.claim=="string"?m.claim.trim():void 0,reason:j==="defer"?void 0:`The owner explicitly chose ${j.replaceAll("_"," ")} from the decision review card.`,taskContext:j==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:j==="defer"?["different_action","owner_request"]:void 0};if(C.action==="edit_and_accept"&&!C.claim){E(u,400,{error:"Edited decision wording is required."});return}let O=await q.commitConversationalReview(C),Q=`memory-${lt().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:It(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=It(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&ie!=="copilot"&&await Nt({provider:ie,model:typeof m.model=="string"?m.model:void 0,agentSettings:ft(m),threadId:k,reason:`Project accepted decision ${O.decisionId}`}),E(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&R==="/memory/analyze"){let m=await Ge(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($=>$.code===j).length]));E(u,200,{...k,issues:void 0,issueCounts:w});return}if(a.method==="POST"&&R==="/memory/review"){let m=await Ge(a),k=await q.review(Mo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,k);return}if(a.method==="POST"&&R==="/memory/context"){let m=await Ge(a),k=await q.contextualize(Mo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,k);return}if(a.method==="POST"&&R==="/memory/initialize"){let m=await Ge(a),k=await q.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:sn});E(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 Ge(a),k=await q.planReview(jo(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,k.result.ok?200:422,k);return}if(a.method==="POST"&&R==="/memory/commit"){let m=await Ge(a),k=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},w=await q.commitReview(jo(m.command),{transactionId:typeof k.transactionId=="string"?k.transactionId:"",committedAt:typeof k.committedAt=="string"?k.committedAt:""});E(u,200,{status:await q.status(),journal:w.report});return}if(a.method==="POST"&&R==="/memory/recover"){let m=await Ge(a),k=await q.recover(m.confirm===!0);E(u,200,{status:await q.status(),journal:k.report});return}E(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){E(u,w?409:400,{error:k});return}throw m}}async function ve(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=>Vn(j.messages)))];E(u,200,{state:"ready",head:m.graph.head,updatedAt:m.graph.updatedAt,explanationCount:m.graph.explanations.filter(j=>j.state!=="retired").length,concreteCount:m.graph.concrete.length,relationCount:m.graph.relations.length,pendingGroundingCount:w.length,recoveredTransactions:m.recoveredTransactions,admission:fe.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&R==="/imprint/action"){let m=await Ge(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)){E(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){E(u,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){E(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${lt().slice(0,8)}`;await fe.applyGroundingAction({summary:F,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:k,jobId:C}),await q.recordImprintEvidence({summary:F,action:j,threadId:k,jobId:C}).catch(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let O=Ct(L.result,!!L.question),Q=L.turn?{...L.turn,result:Ct(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:C,replyToQuestion:U[j]}),E(u,200,{ok:!0,action:j});return}E(u,404,{error:"Imprint endpoint not found."})}async function rt(a,u){let{screenshot:R,feedback:m,color:k,provider:w,model:j,reasoningEffort:$,serviceTier:D,sourceId:L,pastedImages:F,pageScreenshots:C}=await $n(a),O;try{O=JSON.parse(m)}catch{E(u,400,{error:"Invalid feedback JSON"});return}let Q=lt().slice(0,8),U={};if(C.length>0)for(let ee of C){let me=encodeURIComponent(ee.pathname),Re=Me(c,`screenshot-${Q}-${me}.webp`);await an(Re,ee.data),U[ee.pathname]=Re}let ie=Me(c,`screenshot-${Q}.webp`);await an(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 an(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),be;if(re.length>0){let ee=await G.findContinuationThread(re);ee?(be=ee.id,await G.addElementIdentifiers(be,re)):be=(await G.createThread(Q,re)).id}else be=(await G.createThread(Q,[])).id;let ye=O.annotations.map(ee=>ee.id),K=Object.keys(U).length>0,we=await Jr(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:Cn(O),subjectHints:[...re,...O.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(me=>!!me))],pendingGroundingExplanationIds:Vn((await G.getThread(be))?.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:be,annotationIds:ye,provider:It(w),model:j||void 0,agentSettings:ft({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:L||void 0,...K?{screenshotPaths:U}:{},...we?{memoryReview:we}:{},...de?{imprintContext:de}:{}},Ce=new Set(O.annotations.map(ee=>ee.pathname).filter(Boolean)),$e;if(Ce.size>1){let ee=new Map;for(let me of O.annotations){let Re=me.pathname||"(unknown)";ee.has(Re)||ee.set(Re,[]),ee.get(Re).push(me.instruction||gs({...O,annotations:[me]}))}$e=[...ee.entries()].map(([me,Re])=>`\`${me}\`
228
+ ${Re.map(xe=>`- ${xe}`).join(`
408
229
  `)}`).join(`
409
- `)}else te=Nn(Q);let ue=De(Q,Object.keys(se).length>0?se:void 0);await m.appendMessage(ce,{role:"human",timestamp:Date.now(),jobId:S,screenshotPath:W,...le?{screenshotPaths:O}:{},...Object.keys(se).length>0?{imagePaths:se}:{},annotationIds:de,feedbackSummary:te,feedbackContext:ue||void 0});let j=N.enqueue(B);g(c,200,{jobId:S,position:j,threadId:ce})}async function qn(r,c){let u=r.headers["content-type"]||"",p,h,d,P,y,R,I,C=[];if(u.includes("multipart/form-data")){let j=await tt(r),M=j.feedback?JSON.parse(j.feedback):{};p=M.threadId,h=M.reply,d=M.color,P=M.provider,y=M.model,R=je(M),I=M.sourceId||j.sourceId;for(let X of j.pastedImages)C.push(X.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"),X;try{X=JSON.parse(M)}catch{g(c,400,{error:"Invalid JSON"});return}p=X.threadId,h=X.reply,d=X.color,P=X.provider,y=X.model,R=je(X),I=X.sourceId}if(!p||!h){g(c,400,{error:"Missing threadId or reply"});return}if(!await m.getThread(p)){g(c,404,{error:"Thread not found"});return}let Q="";{let j=await m.getThreadHistory(p);for(let M=j.length-1;M>=0;M--)if(j[M].screenshotPath){Q=j[M].screenshotPath;break}}let S=await as(p);if(!Q&&!S){g(c,400,{error:"No screenshot available"});return}let O=N.hasActiveThread(p),W=O?N.getQueuedThreadJob(p,j=>j._replyText!==void 0||j._replyPrompt!==void 0):null,se=W?.id??xe().slice(0,8),ae=[],ce=`${se}-${Date.now()}`;for(let j=0;j<C.length;j++){let M=ye(a,`reply-${ce}-${j}.webp`);await Fe(M,C[j]),ae.push(M)}await m.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:se,replyToQuestion:h,screenshotPath:Q,...O?{queued:!0}:{},...ae.length>0?{replyImagePaths:ae}:{}});let de=await m.getThreadHistory(p),le=[];for(let j of de)if(j.annotationIds)for(let M of j.annotationIds)le.includes(M)||le.push(M);let B=Be(P),oe=kt(Q,de,B,ae.length>0?ae:void 0);if(W){let j=W,X=[...j._replyTexts??(j._replyText?[j._replyText]:[]),h],re=[...j._replyImagePaths??[],...ae];j._replyTexts=X,j._replyText=Dn(X),j._replyImagePaths=re.length>0?re:void 0,j._replyPrompt=kt(Q,de,B,re.length>0?re:void 0),j.annotationIds=le.length>0?le:j.annotationIds,j.agentSettings=R??j.agentSettings,g(c,200,{jobId:se,position:1,threadId:p,bundled:!0});return}let te={id:se,status:"queued",screenshotPath:Q,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:le.length>0?le:void 0,provider:B,model:y||void 0,agentSettings:R,sourceId:I||void 0};S&&(te.kind=S),te._replyPrompt=oe,te._replyTexts=[h],te._replyText=Dn([h]),ae.length>0&&(te._replyImagePaths=ae);let ue=O?N.enqueueNext(te):N.enqueue(te);g(c,200,{jobId:se,position:ue,threadId:p})}function Qn(r,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
230
+ `)}else $e=gs(O);let Ze=Xt(O,Object.keys(ae).length>0?ae:void 0);await G.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:Q,screenshotPath:ie,...K?{screenshotPaths:U}:{},...Object.keys(ae).length>0?{imagePaths:ae}:{},annotationIds:ye,annotationSnapshot:{url:O.url,viewport:O.viewport,annotations:O.annotations,color:k||void 0},feedbackSummary:$e,feedbackContext:Ze||void 0,...we?{memoryReview:we}:{},...de?{imprintContext:de}:{}});let ke=N.enqueue(pe);E(u,200,{jobId:Q,position:ke,threadId:be})}async function _e(a,u){let R=a.headers["content-type"]||"",m,k,w,j,$,D,L,F,C,O=[];if(R.includes("multipart/form-data")){let X=await $n(a),ue=X.feedback?JSON.parse(X.feedback):{};m=ue.threadId,k=ue.reply,w=ue.color,j=ue.provider,$=ue.model,D=ft(ue),L=ue.sourceId||X.sourceId,F=typeof ue.memoryReviewProposalId=="string"?ue.memoryReviewProposalId:void 0,C=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{E(u,400,{error:"Invalid JSON"});return}m=z.threadId,k=z.reply,w=z.color,j=z.provider,$=z.model,D=ft(z),L=z.sourceId,F=z.memoryReviewProposalId,C=z.evalRemediation?.action==="resolve"&&typeof z.evalRemediation.evalId=="string"?{evalId:z.evalRemediation.evalId,action:"resolve"}:void 0}if(!m||!k){E(u,400,{error:"Missing threadId or reply"});return}let Q=await G.getThread(m);if(!Q){E(u,404,{error:"Thread not found"});return}let U,ie;if(C){let X=await q.findJournalEvalCase(C.evalId),ue=(await q.getJournalEvalRuns()).filter(z=>z.evalId===C.evalId&&z.threadId===m).sort((z,se)=>se.completedAt-z.completedAt)[0];if(!X||!ue){E(u,409,{error:"The failed eval run is not available in this thread."});return}if(ue.status!=="fail"){E(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){E(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 ut(m);if(!ae&&!re){E(u,400,{error:"No screenshot available"});return}let be=N.hasActiveThread(m),ye=be?N.getQueuedThreadJob(m,X=>X._replyText!==void 0||X._replyPrompt!==void 0):null,K=ye?.id??lt().slice(0,8),we=[],de=`${K}-${Date.now()}`;for(let X=0;X<O.length;X++){let ue=Me(c,`reply-${de}-${X}.webp`);await an(ue,O[X]),we.push(ue)}await G.appendMessage(m,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:k,screenshotPath:ae,...be?{queued:!0}:{},...we.length>0?{replyImagePaths:we}:{}});let pe=await G.getThreadHistory(m),Ce=[...pe].reverse().find(X=>X.memoryReview)?.memoryReview,$e=await fe.contextualize({text:k,subjectHints:Q.elementIdentifiers,pendingGroundingExplanationIds:Vn(pe)}).catch(X=>{console.warn(`[\u22B9 ${h}:${K}] Imprint context unavailable for reply; continuing without it:`,X instanceof Error?X.message:String(X))}),Ze=new Set(pe.flatMap(X=>X.memoryReceipt?.status==="committed"?[X.memoryReceipt.proposalId]:[])),ke=[...pe].reverse().find(X=>X.memoryReviewCard&&!Ze.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=It(j),Re=U,xe=Re?[Re.underlying.proposalId]:ke?[ke.proposalId]:[],mt=Wr(ae,pe,me,we.length>0?we:void 0);if(ie?mt+=["","## 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(`
231
+ `):Re?mt+=["","## Decision review card",`Privately review proposal ${Re.underlying.proposalId}: ${Re.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
232
+ `):ke&&(mt+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(ke)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
233
+ `)),ye){let X=ye,z=[...X._replyTexts??(X._replyText?[X._replyText]:[]),k],se=[...X._replyImagePaths??[],...we];X._replyTexts=z,X._replyText=hs(z),X._replyImagePaths=se.length>0?se:void 0,X._replyPrompt=mt,X.annotationIds=ee.length>0?ee:X.annotationIds,X.agentSettings=D??X.agentSettings,X.memoryReview=Ce??X.memoryReview,X.imprintContext=$e??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...xe])],E(u,200,{jobId:K,position:1,threadId:m,bundled:!0});return}let Ue={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:$||void 0,agentSettings:D,sourceId:L||void 0,...Ce?{memoryReview:Ce}:{},...$e?{imprintContext:$e}:{},...xe.length?{surfacedProposalIds:xe}:{}};ie?Ue.kind="resolve_eval":re&&(Ue.kind=re),Ue._replyPrompt=mt,Ue._evalRemediation=!!ie,Ue._replyTexts=[k],Ue._replyText=hs([k]),we.length>0&&(Ue._replyImagePaths=we);let Ft=be?N.enqueueNext(Ue):N.enqueue(Ue);E(u,200,{jobId:K,position:Ft,threadId:m})}function Ye(a,u){u.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),u.write(`event: connected
410
234
  data: {"status":"connected"}
411
235
 
412
- `);let p=new URL(r.url||"/",`http://127.0.0.1:${U}`).searchParams.get("sourceId")||void 0,h={id:xe().slice(0,8),res:c,sourceId:p};k.add(h),r.on("close",()=>{k.delete(h)})}async function Xn(r,c){let u=[...N.allActive,...$.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([x.loadRuns(),x.loadModelProposals()]);g(r,200,{ok:!0,version:$n,restartMode:H,projectId:o,projectName:at(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:N.depth+$.depth,materializerQueueDepth:$.depth,materialization:{activeJob:$.active?{id:$.active.id,status:$.active.status,threadId:$.active.threadId,annotationIds:$.active.annotationIds??[],provider:$.active.provider,model:$.active.model}:null,queueDepth:$.depth,recentRuns:[...p.runs].sort((d,P)=>(P.completedAt??P.startedAt)-(d.completedAt??d.startedAt)).slice(0,10),proposals:h.proposals.slice(0,20).map(d=>({id:d.id,status:d.status,title:d.title,summary:d.summary,decisionIds:d.decisionIds,threadId:d.threadId,runId:d.runId,createdAt:d.createdAt,updatedAt:d.updatedAt,appliedAt:d.appliedAt,dismissedAt:d.dismissedAt,generatedEvalIds:d.generatedEvalIds,error:d.error}))},recentJobs:Z})}async function Yn(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),g(c,200,{ok:!0,devOrigin:i})}catch{g(c,400,{error:"Invalid JSON"})}}async function Vn(r,c){let p=new URL(r.url||"/",`http://127.0.0.1:${U}`).searchParams.get("jobId"),h=p?N.allActive.filter(C=>C.id===p):N.allActive,d=p?$.allActive.filter(C=>C.id===p):$.allActive,P=[...h.map(C=>C.threadId),...d.map(C=>C.threadId)].filter(Boolean),y=p?N.cancelJob(p):N.cancelActive(),R=p?$.cancelJob(p):$.cancelActive(),I=!!(y||R);for(let C of P)await m.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:p||R?.id||"",cancelled:!0});g(c,200,{cancelled:I})}async function Rt(r){let c=xe().slice(0,8),u=r.threadId,p=!u;u||(u=(await m.createThread(c,[])).id,ne.set(u,"materialize_model")),p&&await m.appendMessage(u,{role:"human",timestamp:Date.now(),jobId:c,feedbackSummary:r.reason}),await m.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=$.enqueue(h);return{jobId:c,position:d,threadId:u}}async function Kn(r,c){if($.isRunning){g(c,200,{skipped:!0,reason:"Already running"});return}let{provider:u,model:p,agentSettings:h}=await Ie(r);if(u==="copilot"){g(c,400,{error:"Materialization is not available for Copilot yet."});return}let d=await x.getUnmaterializedPatternDecisions();if(d.length===0){g(c,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let P=await Rt({provider:u,model:p,agentSettings:h,reason:"Materialize model \u2014 promote pattern decisions into the local taste model"});g(c,200,{started:!0,decisionCount:d.length,decisionIds:d.map(y=>y.id),...P})}async function Zn(r,c){let u=decodeURIComponent(r),p=await x.applyModelProposal(u);if(!p){g(c,404,{error:"Model proposal not found"});return}p.threadId&&await m.appendMessage(p.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${p.id}`,responseText:`Model proposal applied.
413
-
414
- ${p.title}
415
- ${p.summary}`}),g(c,200,{proposal:p})}async function es(r,c,u){let p=decodeURIComponent(r),h=[];for await(let I of c)h.push(typeof I=="string"?Buffer.from(I):I);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{g(u,400,{error:"Invalid JSON"});return}let P=(d.changes??[]).flatMap(I=>{if(!Array.isArray(I.path)||I.path.length===0)return[];let C=I.path.filter(ee=>typeof ee=="string"||typeof ee=="number");return C.length!==I.path.length?[]:[{path:C,value:I.value,remove:I.remove===!0}]});if(P.length===0){g(u,400,{error:"No selected model changes"});return}let y=(d.changeSummaries??[]).flatMap(I=>{if(!I||typeof I!="object")return[];let C=Array.isArray(I.path)?I.path.filter(ee=>typeof ee=="string"||typeof ee=="number"):void 0;return Array.isArray(I.path)&&C?.length!==I.path.length?[]:[{group:typeof I.group=="string"?I.group:void 0,label:typeof I.label=="string"?I.label:void 0,detail:typeof I.detail=="string"?I.detail:void 0,path:C,value:I.value,currentValue:I.currentValue}]}),R=await x.applySelectedModelProposal(p,P,y);if(!R){g(u,404,{error:"Model proposal not found"});return}if(R.threadId){let I=Be(d.provider),C=typeof d.model=="string"&&d.model?d.model:void 0;await m.appendMessage(R.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${R.id}`,responseText:`Model proposal applied with ${P.length} selected change${P.length===1?"":"s"}.
416
-
417
- ${R.title}`,provider:I,model:C})}g(u,200,{proposal:R})}async function ts(r,c,u){let p=decodeURIComponent(r),{provider:h,model:d}=await Ie(c),P=await x.dismissModelProposal(p);if(!P){g(u,404,{error:"Model proposal not found"});return}P.threadId&&await m.appendMessage(P.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${P.id}`,responseText:`Model proposal dismissed.
418
-
419
- ${P.title}`,provider:h,model:d}),g(u,200,{proposal:P})}async function ns(r,c,u){let p=decodeURIComponent(r),h=await x.findModelProposal(p);if(!h){g(u,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){g(u,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:P,agentSettings:y}=await Ie(c),R=d??h.provider??F;if(R==="copilot"){g(u,400,{error:"Eval projection is not available for Copilot yet."});return}let I=await x.loadModel(),C=await T.loadSuite(),ee=en({proposal:h,currentModel:I,existingSuite:C}),Q=xe().slice(0,8),S=h.threadId??(await m.createThread(Q,[])).id;ne.set(S,"synthesize_evals"),await m.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:Q,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
420
- `)});let O={id:Q,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:R,model:P??h.model,agentSettings:y};O._replyPrompt=ee,O._proposalId=h.id;let W=N.enqueue(O);g(u,200,{jobId:Q,position:W,threadId:S})}async function Ie(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:Be(typeof u.provider=="string"?u.provider:void 0),model:typeof u.model=="string"&&u.model?u.model:void 0,agentSettings:je(u)}}catch{return{}}}async function ss(r,c){let u=await x.loadModel();if(!u){g(c,400,{error:"No model exists yet"});return}let{provider:p,model:h,agentSettings:d}=await Ie(r);if(p==="copilot"){g(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let P=rn(u),y=xe().slice(0,8),I=(await m.createThread(y,[])).id;ne.set(I,"synthesize"),await m.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:y,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let C={id:y,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:I,kind:"synthesize",provider:p,model:h,agentSettings:d};C._replyPrompt=P;let ee=N.enqueue(C);g(c,200,{jobId:y,position:ee,threadId:I})}async function os(r,c){let{provider:u,model:p,agentSettings:h}=await Ie(r);if(u==="copilot"){g(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let d=await A.listDecisionIds(),P=await A.loadDecisions(d),y=await m.load(),R=await x.loadModel(),I=await T.loadSuite(),C=Kt({decisions:P,threads:y,model:R,existingSuite:I}),ee=xe().slice(0,8),S=(await m.createThread(ee,[])).id;ne.set(S,"synthesize_evals"),await m.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:ee,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let O={id:ee,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=C;let W=N.enqueue(O);g(c,200,{jobId:ee,position:W,threadId:S})}async function rs(r,c,u){let p=decodeURIComponent(r),h=await T.findCase(p);if(!h){g(u,404,{error:"Eval not found"});return}if(h.status!=="approved"){g(u,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:P,provider:y,model:R,reasoningEffort:I,serviceTier:C,sourceId:ee}=await tt(c),Q=Be(y)??F;if(Q==="copilot"){g(u,400,{error:"Eval runs are not available for Copilot yet."});return}let S={};try{S=P?JSON.parse(P):{}}catch{g(u,400,{error:"Invalid eval run context JSON"});return}let O=xe().slice(0,8),W=xe().slice(0,8),se=ye(a,`eval-run-${O}.webp`);await Fe(se,d);let ae=await T.writeRunScreenshot(O,d),ce=S.viewport,de=ce&&typeof ce=="object"?ce:{},le={type:"current_page",url:typeof S.url=="string"?S.url:"",viewport:{width:typeof de.width=="number"?de.width:0,height:typeof de.height=="number"?de.height:0}},B=await x.loadModel(),oe=Q==="claude"?q.name:Q==="codex"?V.name:null,te=Q==="codex"?K.length>0:typeof oe=="string"&&/chrome|devtools/i.test(oe),ue=Zt({evalCase:h,scope:le,model:B,screenshotPath:se,chromeDevtoolsAvailable:te}),M=(await m.createThread(W,[])).id;ne.set(M,"run_eval");let X={timestamp:new Date().toISOString(),url:le.url,viewport:le.viewport,scrollPosition:{x:typeof S.scrollX=="number"?S.scrollX:0,y:typeof S.scrollY=="number"?S.scrollY:0},annotations:[],styleModifications:[]};await m.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:W,screenshotPath:se,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${le.url||"unknown"}`,"Assertions:",...h.assertions.map(Ss=>`- ${Ss}`)].join(`
421
- `)});let re={id:W,status:"queued",screenshotPath:se,feedback:X,createdAt:Date.now(),color:"#111827",threadId:M,kind:"run_eval",evalId:p,evalRunId:O,provider:Q,model:R||void 0,agentSettings:je({reasoningEffort:I,serviceTier:C}),sourceId:ee||void 0};re._replyPrompt=ue,re._evalRunScope=le,re._evalScreenshotPath=ae;let ut=N.enqueue(re);g(u,200,{jobId:W,runId:O,position:ut,threadId:M,screenshotPath:ae})}async function is(r,c,u){let p=decodeURIComponent(r),h={},d,P,y;try{let I=[];for await(let ee of c)I.push(typeof ee=="string"?Buffer.from(ee):ee);let C=JSON.parse(Buffer.concat(I).toString());d=C.status,P=C.title,y=C.assertions}catch{g(u,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){g(u,400,{error:"Invalid status"});return}if(d&&(h.status=d),P!==void 0){if(typeof P!="string"||P.trim().length===0){g(u,400,{error:"Invalid title"});return}h.title=P.trim()}if(y!==void 0){if(!Array.isArray(y)){g(u,400,{error:"Invalid assertions"});return}let I=y.filter(C=>typeof C=="string").map(C=>C.trim()).filter(Boolean);if(I.length===0){g(u,400,{error:"Invalid assertions"});return}h.assertions=I}if(!h.status&&!h.title&&!h.assertions){g(u,400,{error:"No eval changes provided"});return}let R=await T.updateCase(p,h);if(!R){g(u,404,{error:"Eval not found"});return}g(u,200,{eval:R})}async function as(r){let c=ne.get(r);if(c)return c;let h=(await m.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return ne.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return ne.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return ne.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return ne.set(r,"materialize_model"),"materialize_model"}async function ls(r,c){let u=[];for await(let R of r)u.push(typeof R=="string"?Buffer.from(R):R);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 yn(p)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await vn(p)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await wn(p,w.copilot.path??E));let[d,P,y]=await Promise.all([St(t),xt(t),bt(t,w.copilot?.path??E)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=P),w.copilot&&(w.copilot.mcp=y),g(c,200,{results:h,capabilities:{providers:w}})}async function cs(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{g(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){g(c,400,{error:"Missing or invalid name"});return}let h=await x.addComponent(p.name);g(c,200,h)}async function ds(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{g(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){g(c,400,{error:"Missing or invalid name"});return}let h=await x.removeComponent(p.name);g(c,200,h)}async function us(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{g(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"||typeof p.value!="string"){g(c,400,{error:"Missing or invalid path/value"});return}let h=await x.updateToken(p.path,p.value);g(c,200,h)}async function ps(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{g(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"){g(c,400,{error:"Missing or invalid path"});return}let h=await x.removeToken(p.path);g(c,200,h)}function fs(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=At(U,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(p)}async function hs(r){let c=Date.now();if(pe&&c<pe.expires){g(r,200,pe.data);return}try{let{scanForComponents:u}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:p}=await import("./render-generator-HWFLZYC3.mjs"),h=await u(t);pe={data:h,expires:c+5e3},p(h,t,fe).then(d=>{fe=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),g(r,200,h)}catch(u){console.error("[Bridge] Scanner error:",u),g(r,500,{error:"Failed to scan components"})}}async function ms(r){let c=[ye(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ye(t,"packages","popmelt","dist","canvas.mjs")];try{let u=gr(import.meta.url);c.unshift(ye(mr(u),"canvas.mjs"))}catch{}for(let u of c)try{let p=await On(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),g(r,404,{error:"Canvas bundle not found"})}async function gs(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){g(c,400,{error:"Invalid filename"});return}try{let u=await On(ye(a,r)),p=r.split(".").pop()?.toLowerCase(),h=p==="png"?"image/png":p==="webp"?"image/webp":p==="jpg"||p==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(u)}catch{g(c,404,{error:"File not found"})}}function Le(r){return`/files/${at(r)}`}async function ys(r,c){let u=await m.getThread(r);if(!u){g(c,404,{error:"Thread not found"});return}let p=(await T.loadRuns()).runs.filter(R=>R.threadId===r).sort((R,I)=>I.completedAt-R.completedAt)[0],h=p?await T.findCase(p.evalId):null,d=await x.findModelProposalsByThread(r),P=[...d].sort((R,I)=>I.updatedAt-R.updatedAt)[0]??null,y=u.messages.map(({screenshotPath:R,screenshotPaths:I,imagePaths:C,replyImagePaths:ee,...Q})=>({...Q,...Q.role==="assistant"&&p?{evalRun:{...p,title:h?.title}}:{},...R?{screenshotUrl:Le(R)}:{},...I?{screenshotUrls:Object.fromEntries(Object.entries(I).map(([S,O])=>[S,Le(O)]))}:{},...C?{imageUrls:Object.fromEntries(Object.entries(C).map(([S,O])=>[S,O.map(Le)]))}:{},...ee?{replyImageUrls:ee.map(Le)}:{}}));g(c,200,{id:u.id,createdAt:u.createdAt,messages:y,modelProposal:P,modelProposals:d})}async function vs(r,c){let u=decodeURIComponent(r);if(!await m.deleteThread(u)){g(c,404,{deleted:!1,error:"Thread not found"});return}g(c,200,{deleted:!0})}let Et=9,Tt=!1;for(let r=e;r<e+Et;r++)try{await Cr(dt,r),U=r,Tt=!0,console.log(`[\u22B9 is watching :${U}]`);break}catch(c){if(c.code==="EADDRINUSE"){let u=await Ar(r);if(u&&u.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Tt)throw new Error(`[Bridge] All ports ${e}\u2013${e+Et-1} in use`);for(let[r,c]of Object.entries(w))!c.available||!c.path||Y(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 k)lt(p,{type:"capabilities_changed",data:{}})}});let ws=setInterval(()=>{zn(a).catch(()=>{})},wr);return{port:U,projectId:o,close:async()=>{clearInterval(ws),await N.destroyAsync();for(let r of k)try{r.res.end()}catch{}return k.clear(),new Promise(r=>{dt.close(()=>r())})}}}async function zn(s){try{let e=await cr(s),n=Date.now();for(let t of e){let o=ye(s,t);try{let i=await ur(o);n-i.mtimeMs>Sr&&await pr(o)}catch{}}}catch{}}var Dr=parseInt(process.env.POPMELT_PORT||"1111",10),Ln=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Nr=process.env.POPMELT_DEV_ORIGIN||void 0,Jr=process.env.POPMELT_COPILOT_PATH||void 0,Un=jn(Ln,".popmelt"),Wn=jn(Un,"bridge.lock");async function zr(s){await $r(Un,{recursive:!0}),await Or(Wn,JSON.stringify({pid:process.pid,port:s,startedAt:Date.now()})+`
422
- `)}async function Hn(){try{await _r(Wn)}catch{}}async function Fr(){let s=await Bn({port:Dr,projectRoot:Ln,devOrigin:Nr,copilotPath:Jr,restartMode:"detached"});await zr(s.port),await new Promise(e=>{let n=async()=>{await s.close(),await Hn(),e()};process.on("SIGTERM",n),process.on("SIGINT",n)})}Fr().catch(s=>{console.error("[popmelt bridge-entry] Fatal:",s),Hn().finally(()=>process.exit(1))});
236
+ `);let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,k={id:lt().slice(0,8),res:u,sourceId:m};Y.add(k),a.on("close",()=>{Y.delete(k)})}async function st(a,u,R){i??=ss(a.headers),Ae();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,$,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."}),$.status==="rejected"&&L.push({subsystem:"imprint",message:F($)}),D.status==="rejected"&&L.push({subsystem:"threads",message:F(D)});let C=k.status==="fulfilled"?k.value.runs:[],O=w.status==="fulfilled"?w.value.proposals:[],Q=is(C,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=>Vn(K.messages)))]:[],re=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(K=>K.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:$.value.recoveredTransactions,admission:fe.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F($),pendingGroundingCount:ae.length,admission:fe.diagnostics(),admissionWindowStartedAt:e},be=L.length>0?"degraded":ie.state==="absent"||ie.state==="initializing"?"initializing":"healthy",ye=new Date().toISOString();E(u,200,{ok:!0,schemaVersion:3,generatedAt:ye,serverStartedAt:e,health:{state:be,issues:L},version:sn,restartMode:p,projectId:s,projectName:Gn(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:Ee,recentJobs:Ie})}async function it(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),E(u,200,{ok:!0,devOrigin:i})}catch{E(u,400,{error:"Invalid JSON"})}}async function pt(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),$=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),L=!!($||D);for(let F of j)await G.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});E(u,200,{cancelled:L})}async function Nt(a){let u=lt().slice(0,8),R=a.threadId,m=!R;R||(R=(await G.createThread(u,[])).id,Je.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 Yn(a,u){let R=decodeURIComponent(a),m=await V.findModelProposal(R);if(!m){E(u,404,{error:"Model proposal not found"});return}E(u,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:m})}async function Bt(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{E(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){E(R,400,{error:"No selected model changes"});return}let $=(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){E(R,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){E(R,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){E(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}),C=await V.applySelectedModelProposal(m,j,$);if(!C){E(R,404,{error:"Model proposal not found"});return}if(await Dt(C),C.threadId){let O=It(w.provider),Q=typeof w.model=="string"&&w.model?w.model:void 0;await G.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${C.id}`,responseText:"",provider:O,model:Q})}E(R,200,{proposal:C,projection:F})}async function Ne(a,u,R){let m=decodeURIComponent(a),{provider:k,model:w}=await Be(u),j=await V.dismissModelProposal(m);if(!j){E(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}),E(R,200,{proposal:j})}async function Be(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:It(typeof R.provider=="string"?R.provider:void 0),model:typeof R.model=="string"&&R.model?R.model:void 0,agentSettings:ft(R)}}catch{return{}}}async function at(a,u,R){let m=decodeURIComponent(a),k=await q.findJournalEvalCase(m);if(!k){E(R,404,{error:"Eval not found"});return}if(k.status!=="approved"){E(R,400,{error:"Only approved evals can be run"});return}let{screenshot:w,feedback:j,provider:$,model:D,reasoningEffort:L,serviceTier:F,sourceId:C}=await $n(u),O=It($)??I;if(O==="copilot"){E(R,400,{error:"Eval runs are not available for Copilot yet."});return}let Q={};try{Q=j?JSON.parse(j):{}}catch{E(R,400,{error:"Invalid eval run context JSON"});return}let U=lt().slice(0,8),ie=lt().slice(0,8),ae=Me(c,`eval-run-${U}.webp`);await an(ae,w);let re=await Z.persistEvalScreenshot(w),be=Q.viewport,ye=be&&typeof be=="object"?be:{},K={type:"current_page",url:typeof Q.url=="string"?Q.url:"",viewport:{width:typeof ye.width=="number"?ye.width:0,height:typeof ye.height=="number"?ye.height:0}},we=await V.loadModel(),de=await vs(r,k,we),pe=O==="claude"?S.name:O==="codex"?A.name:null,Ce=O==="codex"?_.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),$e=sr({evalCase:k,scope:K,model:we,screenshotPath:ae,chromeDevtoolsAvailable:Ce}),ke=(await G.createThread(ie,[])).id;Je.set(ke,"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(ke,{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(xe=>`- ${xe}`)].join(`
237
+ `)});let me={id:ie,status:"queued",screenshotPath:ae,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:ke,kind:"run_eval",evalId:m,evalRunId:U,provider:O,model:D||void 0,agentSettings:ft({reasoningEffort:L,serviceTier:F}),sourceId:C||void 0};me._replyPrompt=$e,me._evalRunScope=K,me._evalScreenshotPath=re,me._evalScopeFingerprint=de;let Re=N.enqueue(me);E(R,200,{jobId:ie,runId:U,position:Re,threadId:ke,screenshotPath:re})}async function xt(a,u,R){let m=decodeURIComponent(a),k={},w,j,$;try{let L=[];for await(let C of u)L.push(typeof C=="string"?Buffer.from(C):C);let F=JSON.parse(Buffer.concat(L).toString());w=F.status,j=F.title,$=F.assertions}catch{E(R,400,{error:"Invalid JSON"});return}if(w!==void 0&&w!=="pending"&&w!=="approved"&&w!=="rejected"){E(R,400,{error:"Invalid status"});return}if(w&&(k.status=w),j!==void 0){if(typeof j!="string"||j.trim().length===0){E(R,400,{error:"Invalid title"});return}k.title=j.trim()}if($!==void 0){if(!Array.isArray($)){E(R,400,{error:"Invalid assertions"});return}let L=$.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(L.length===0){E(R,400,{error:"Invalid assertions"});return}k.assertions=L}if(!k.status&&!k.title&&!k.assertions){E(R,400,{error:"No eval changes provided"});return}let D=await q.updateJournalEvalCase(m,k);if(!D){E(R,404,{error:"Eval not found"});return}E(R,200,{eval:D})}async function ut(a){let u=Je.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 Je.set(a,"synthesize_evals"),"synthesize_evals";if(k.startsWith("Synthesize rules"))return Je.set(a,"synthesize"),"synthesize";if(k.startsWith("Run eval"))return Je.set(a,"run_eval"),"run_eval";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return Je.set(a,"project_model"),"project_model"}async function Zn(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 br(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&k.push(await xr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&k.push(await Sr(m,f.copilot.path??b));let[w,j,$]=await Promise.all([mo(r),fo(r),ho(r,f.copilot?.path??b)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),E(u,200,{results:k,capabilities:{providers:f}})}async function cn(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{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(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 qe({decisionId:k.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});E(u,200,{added:!0,alreadyExists:!1,...k,evalId:w})}async function Ms(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{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(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 qe({decisionId:k.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});E(u,200,{removed:!0,...k,evalId:w})}async function Es(a,u){let R=[];for await(let $ of a)R.push(typeof $=="string"?Buffer.from($):$);let m;try{m=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){E(u,400,{error:"Missing or invalid path/value"});return}let k=m.value;try{let $=JSON.parse(m.value);$&&typeof $=="object"&&(k=$)}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 qe({decisionId:w.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});E(u,200,{updated:!0,...w,evalId:j})}async function As(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{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){E(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 qe({decisionId:k.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});E(u,200,{removed:!0,...k,evalId:w})}function _s(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=zo(h,R);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Cs(a){let u=Date.now();if(ot&&u<ot.expires){E(a,200,ot.data);return}try{let{scanForComponents:R}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),k=await R(r);ot={data:k,expires:u+5e3},m(k,r,Jt).then(w=>{Jt=w}).catch(w=>console.warn("[Bridge] Render generation failed:",w)),E(a,200,k)}catch(R){console.error("[Bridge] Scanner error:",R),E(a,500,{error:"Failed to scan components"})}}async function $s(a){let u=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let R=Wc(import.meta.url);u.unshift(Me(Uc(R),"canvas.mjs"))}catch{}for(let R of u)try{let m=await Jo(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),E(a,404,{error:"Canvas bundle not found"})}async function Os(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(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 Jo(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{E(u,404,{error:"File not found"})}}function dn(a){return`/files/${Gn(a)}`}async function Ds(a,u){let R=await G.getThread(a);if(!R){E(u,404,{error:"Thread not found"});return}let m=R.messages.some(C=>C.role==="assistant"&&C.responseText?.includes("<eval_run_result>")),k=R.messages.filter(C=>C.role==="assistant"&&C.responseText?.includes("Model suggestion ready")),[w,j]=await Promise.all([m?q.getJournalEvalRuns().then(C=>C.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([])]),$=w?await q.findJournalEvalCase(w.evalId):null,D=await Promise.all(j.map(async(C,O)=>{if(C.authorityStatus==="accepted")return C;let Q=(await Promise.all(C.decisionIds.map(U=>q.findPendingProposalForLegacyDecision(U)))).find(Boolean);return{...C,authorityStatus:"legacy_untrusted",presentationJobId:C.presentationJobId??k[O]?.jobId??k.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),L=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,F=R.messages.map(({screenshotPath:C,screenshotPaths:O,imagePaths:Q,replyImagePaths:U,...ie})=>({...ie,...ie.role==="assistant"&&w&&ie.responseText?.includes("<eval_run_result>")?{evalRun:{...w,title:$?.title}}:{},...C?{screenshotUrl:dn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,re])=>[ae,dn(re)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ae,re])=>[ae,re.map(dn)]))}:{},...U?{replyImageUrls:U.map(dn)}:{}}));E(u,200,{id:R.id,createdAt:R.createdAt,messages:F,modelProposal:L,modelProposals:D})}async function Js(a,u){let R=decodeURIComponent(a);if(!await G.deleteThread(R)){E(u,404,{deleted:!1,error:"Thread not found"});return}E(u,200,{deleted:!0})}let Bo=9,Fo=!1;for(let a=n;a<n+Bo;a++)try{await id(bt,a),h=a,Fo=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(u){if(u.code==="EADDRINUSE"){let R=await sd(a);if(rs(R,{projectId:s,version:sn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Fo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Bo-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)Kn(m,{type:"capabilities_changed",data:{}})}});let Ns=setInterval(()=>{ws(c).catch(()=>{})},Vc),Lo=setInterval(()=>{B.expireStale().becameEmpty&&he()},Qc);return Lo.unref?.(),{port:h,projectId:s,close:async()=>{clearInterval(Ns),clearInterval(Lo),ne(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{bt.close(()=>a())})}}}async function ws(o){try{let e=await Nc(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let s=await Fc(r);n-s.mtimeMs>Kc&&await Lc(r)}catch{}}}catch{}}var pd=parseInt(process.env.POPMELT_PORT||"1111",10),Rs=process.env.POPMELT_PROJECT_ROOT||process.cwd(),ud=process.env.POPMELT_DEV_ORIGIN||void 0,md=process.env.POPMELT_COPILOT_PATH||void 0,Ps=ks(Rs,".popmelt"),Ts=ks(Ps,"bridge.lock");async function fd(o){await cd(Ps,{recursive:!0}),await ld(Ts,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
238
+ `)}async function js(){try{await dd(Ts)}catch{}}async function hd(){let o=await Ss({port:pd,projectRoot:Rs,devOrigin:ud,copilotPath:md,restartMode:"detached"});await fd(o.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await o.close(),await js(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}hd().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),js().finally(()=>process.exit(1))});