@popmelt.com/core 0.8.4 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{spawn as Hr}from"child_process";import{realpath as Gr}from"fs/promises";import{dirname as qr,join as Qr}from"path";import{fileURLToPath as Xr}from"url";import{execFileSync as yt,spawn as Un}from"child_process";import{createHash as vr,randomUUID as Pe}from"crypto";import{mkdir as wr,readFile as Wn,readdir as Sr,realpath as br,stat as xr,unlink as Pr,writeFile as Fe}from"fs/promises";import{createServer as Ir}from"http";import{tmpdir as kr}from"os";import{basename as mt,dirname as Er,join as ye}from"path";import{fileURLToPath as Rr}from"url";function Ft(s,e){return`<!DOCTYPE html>
1
+ import{spawn as ud}from"child_process";import{closeSync as md,openSync as fd}from"fs";import{appendFile as hd,mkdir as gd,readFile as yd,realpath as vd}from"fs/promises";import{dirname as wd,join as qo}from"path";import{fileURLToPath as Id}from"url";import{execFileSync as to,spawn as hs}from"child_process";import{createHash as Ss,randomUUID as pt}from"crypto";import{mkdir as Bc,readFile as Lo,readdir as Lc,realpath as Fc,stat as zc,unlink as qc,writeFile as dn}from"fs/promises";import{createServer as Uc}from"http";import{tmpdir as Hc}from"os";import{basename as Yn,dirname as Wc,isAbsolute as Fo,join as Ee,relative as gs,resolve as Ps}from"path";import{fileURLToPath as Gc}from"url";function Go(o,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -18,105 +18,50 @@ import{spawn as Hr}from"child_process";import{realpath as Gr}from"fs/promises";i
18
18
  }}
19
19
  </script>
20
20
  <script type="module">
21
- import { mountCanvas } from 'http://localhost:${s}/canvas/app.mjs';
21
+ import { mountCanvas } from 'http://localhost:${o}/canvas/app.mjs';
22
22
  mountCanvas(document.getElementById('root'), {
23
23
  devOrigin: '${e}',
24
- bridgeOrigin: 'http://localhost:${s}',
24
+ bridgeOrigin: 'http://localhost:${o}',
25
25
  });
26
26
  </script>
27
27
  </body>
28
- </html>`}var Cs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),$s=new Set(["default","flex","fast","priority"]);function Re(s){let e=typeof s.reasoningEffort=="string"&&Cs.has(s.reasoningEffort)?s.reasoningEffort:void 0,n=typeof s.serviceTier=="string"&&$s.has(s.serviceTier)?s.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function qe(s){let e=[];return s?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(s.reasoningEffort)}`),s?.serviceTier&&e.push(`service_tier=${JSON.stringify(s.serviceTier)}`),e}import{spawn as _s}from"child_process";import{createInterface as Os}from"readline";var Ds=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"]),Ut=1e5;function Ns(s){let e=s.input?.file_path||s.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ds.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>Ut?t.slice(0,Ut)+`
29
- \u2026[truncated]`:t}function Qe(s,e){let{prompt:n,projectRoot:t,maxTurns:o=40,maxBudgetUsd:i=1,allowedTools:a=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:l="claude",resumeSessionId:f,model:y,reasoningEffort:v,timeoutMs:M=3e5,onEvent:B}=e,J=[];f?J.push("--resume",f,"-p",n):J.push("-p",n),J.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(i)),y&&J.push("--model",y),v&&J.push("--effort",v);for(let S of a)J.push("--allowedTools",S);let U=_s(l,J,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),W=new Promise(S=>{let q,V=[],Q=[],K=[],z=!1,Z="",O,A,k=!1,E=setTimeout(()=>{k=!0,U.kill("SIGTERM"),setTimeout(()=>{try{U.kill("SIGKILL")}catch{}},5e3)},M),N=Os({input:U.stdout}),$=new Set;N.on("line",F=>{if(F.trim())try{let _=JSON.parse(F);_.session_id&&!q&&(q=_.session_id);let ee=_.type??(_.event?.type?`event.${_.event.type}`:"unknown");if($.add(ee),_.type==="result"&&_.result&&V.length===0){let w=typeof _.result=="string"?_.result:"";w&&(V.push(w),B?.({type:"delta",jobId:s,text:w},s))}if(_.type==="assistant"&&Array.isArray(_.message?.content)){typeof _.error=="string"&&(O=_.error);for(let w of _.message.content){if(w.type==="text"&&w.text&&(V.push(w.text),B?.({type:"delta",jobId:s,text:w.text},s)),w.type==="tool_use"&&w.name){let le=w.input?.file_path||w.input?.path||void 0,ie=Ns(w);if(B?.({type:"tool_use",jobId:s,tool:w.name,...le?{file:le}:{},...ie?{content:ie}:{}},s),w.name==="Edit"&&w.input?.file_path){let G={tool:"Edit",file_path:w.input.file_path,old_string:w.input.old_string,new_string:w.input.new_string,replace_all:w.input.replace_all};Q.push(G),K.push({sequence:K.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:G.file_path,oldString:typeof G.old_string=="string"?G.old_string:void 0,newString:typeof G.new_string=="string"?G.new_string:void 0,replaceAll:typeof G.replace_all=="boolean"?G.replace_all:void 0})}else w.name==="Write"&&w.input?.file_path&&(Q.push({tool:"Write",file_path:w.input.file_path,content:w.input.content}),K.push({sequence:K.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:w.input.file_path,content:typeof w.input.content=="string"?w.input.content:void 0}))}w.type==="thinking"&&w.thinking&&B?.({type:"thinking",jobId:s,text:w.thinking},s)}}_.type==="result"&&_.is_error===!0&&(z=!0,typeof _.error=="string"&&(O=_.error),typeof _.result=="string"&&(A=_.result)),_.type==="user"&&_.tool_use_result?.file?.filePath&&B?.({type:"tool_use",jobId:s,tool:"Read",file:_.tool_use_result.file.filePath},s)}catch{}});let T=[];U.stderr?.on("data",F=>{T.push(F.toString())}),U.on("close",F=>{if(clearTimeout(E),N.close(),V.length===0&&$.size>0&&console.warn(`[Claude:${s}] No text captured. Event types seen: ${[...$].join(", ")}`),k)z=!0,Z=`Timed out after ${Math.round(M/6e4)} minutes`;else if(F!==0&&F!==null){z=!0;let ee=T.join("").trim(),w=V.join("").trim(),le=V.length===0&&$.size>0?` (no text captured, event types: ${[...$].join(", ")})`:"";Z=ee||A||w||`Claude process exited with code ${F}${le}`}z&&!Z&&A&&(Z=A);let _=Js(Z,O);S({sessionId:q,text:V.join(""),success:!z,error:z?_.message:void 0,errorCode:z?_.code:void 0,recoverableError:z?_.recoverable:void 0,fileEdits:Q.length>0?Q:void 0,editEvents:K.length>0?K:void 0})}),U.on("error",F=>{clearTimeout(E),z=!0,Z=F.message,S({sessionId:q,text:V.join(""),success:!1,error:Z,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:Q.length>0?Q:void 0,editEvents:K.length>0?K:void 0})})});return{process:U,result:W}}function Js(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 zs,spawnSync as Xt}from"child_process";import{readFileSync as Bs,statSync as Ls}from"fs";import{basename as js,extname as Fs,isAbsolute as Us,relative as Yt,resolve as Ws}from"path";import{createInterface as Hs}from"readline";function Wt(s){let e=s.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):s}var Ht=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),bt=2e5,Gs=1e5,Vt=2e5;function Kt(s){let e=js(s).toLowerCase(),n=Fs(s).toLowerCase();return Ht.has(n)||Ht.has(e)}function Zt(s,e){let n=Us(e)?e:Ws(s,e),t=Yt(s,n);return t===""||t.startsWith("..")?null:n}function Xe(s,e){if(!Kt(e))return;let n=Zt(s,e);if(n)try{let t=Ls(n);return t.isFile()?t.size>bt?{exists:!0,truncated:!0}:{exists:!0,content:Bs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function qs(s,e){for(let n of e){let t=s[n];if(typeof t=="string")return t}}function Qs(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 Gt(s){return qs(s,["patch","diff","unifiedDiff","unified_diff"])}function xt(s,e){return s.length<=e?{text:s}:{text:s.slice(0,e),truncated:!0}}function qt(s,e){let n=Xt("git",e,{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:Vt+65536});return n.status!==0?null:n.stdout??""}function Xs(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 Qt(s){let e=qt(s,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=qt(s,["diff","--no-ext-diff","HEAD","--"])??"",t=xt(n,Vt);return{status:e,changedFiles:Xs(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Ys(s,e){return!s||!e?!1:s.status!==e.status||(s.diff??"")!==(e.diff??"")}function Vs(s,e){if(!Kt(e))return;let n=Zt(s,e);if(!n)return;let t=Yt(s,n);if(t===""||t.startsWith(".."))return;let o=Xt("git",["show",`HEAD:${t}`],{cwd:s,encoding:"utf8",timeout:5e3,maxBuffer:bt+65536});if(o.status!==0)return{exists:!1};let i=o.stdout??"",a=xt(i,bt);return{exists:!0,content:a.text,...a.truncated?{truncated:!0}:{}}}function Ks(s,e,n){return e.map(t=>{let o=n.has(t)?n.get(t):Vs(s,t),i=Xe(s,t);return{filePath:t,...o?{before:o}:{},...i?{after:i}:{}}})}function Ye(s,e){let{prompt:n,projectRoot:t,screenshotPath:o,resumeSessionId:i,model:a,onEvent:l,sandboxMode:f="workspace-write",configOverrides:y=[]}=e,v=[];if(i){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${f}"`);for(let J of y)v.push("-c",J);a&&v.push("-m",a),v.push(i),v.push(n),o&&v.push("--image",o)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",f);for(let J of y)v.push("-c",J);a&&v.push("-m",a),v.push(n),o&&v.push("--image",o)}let M=zs("codex",v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),B=new Promise(J=>{let U,W=[],S=[],q=[],V=new Map,Q=new Map,K=!1,z="",Z=Hs({input:M.stdout}),O=new Set;Z.on("line",k=>{if(k.trim())try{let E=JSON.parse(k),N=E.type??"unknown";if(O.add(N),N==="thread.started"&&E.thread_id&&!U&&(U=E.thread_id),(N==="item.agentMessage.delta"||N==="item/agentMessage/delta")&&E.delta?.text&&(W.push(E.delta.text),l?.({type:"delta",jobId:s,text:E.delta.text},s)),(N==="item.reasoning.delta"||N==="item/reasoning/delta")&&E.delta?.text&&l?.({type:"thinking",jobId:s,text:E.delta.text},s),(N==="item.started"||N==="item/started")&&E.item){let $=E.item.type;if($==="command_execution"){let T=E.item.command,F=T?Wt(T):void 0,_=Qt(t),ee=new Map;for(let le of _?.changedFiles??[])ee.set(le,Xe(t,le));typeof E.item.id=="string"&&Q.set(E.item.id,{...T?{rawCommand:T}:{},...F?{command:F}:{},..._?{beforeWorktree:_}:{},beforeSnapshots:ee});let w=F?`Bash: ${F.split(`
31
- `)[0].slice(0,80)}`:"Bash";S.push(w),l?.({type:"tool_use",jobId:s,tool:"Bash",...F?{content:F}:{}},s)}else if($==="file_change"){let T=E.item.filename||E.item.path;T&&!V.has(T)&&V.set(T,Xe(t,T)),S.push(T?`Edit ${T.split("/").pop()}`:"Edit"),l?.({type:"tool_use",jobId:s,tool:"Edit",...T?{file:T}:{}},s)}else if($==="file_read"){let T=E.item.filename||E.item.path;S.push(T?`Read ${T.split("/").pop()}`:"Read"),l?.({type:"tool_use",jobId:s,tool:"Read",...T?{file:T}:{}},s)}else if($==="web_search")S.push("WebSearch"),l?.({type:"tool_use",jobId:s,tool:"WebSearch"},s);else if($==="mcp_tool_call"){let T=E.item.tool_name||E.item.name||"MCP";S.push(T),l?.({type:"tool_use",jobId:s,tool:T},s)}}if((N==="item.completed"||N==="item/completed")&&E.item){if(E.item.type==="agent_message"){let $=E.item.text;typeof $=="string"&&$&&(W.push($),l?.({type:"delta",jobId:s,text:$},s))}else if(E.item.type==="reasoning"){let $=E.item.text;typeof $=="string"&&$&&l?.({type:"thinking",jobId:s,text:$},s)}else if(E.item.type==="file_change"&&Array.isArray(E.item.changes))for(let $ of E.item.changes){let T=$.path||$.filename,F=$.kind==="add"?"Write":"Edit";if(T){S.push(`${F} ${T.split("/").pop()}`),l?.({type:"tool_use",jobId:s,tool:F,file:T},s);let _=$,ee=typeof _.kind=="string"?_.kind:void 0,w=Qs(ee),le=V.get(T),ie=Xe(t,T);q.push({sequence:q.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:w,filePath:T,...le?{before:le}:{},...ie?{after:ie}:{},...Gt(_)?{patch:Gt(_)}:{},...ee?{rawKind:ee}:{}}),V.set(T,ie)}}else if(E.item.type==="command_execution"){let $=typeof E.item.id=="string"?E.item.id:void 0,T=$?Q.get($):void 0,F=typeof E.item.command=="string"?E.item.command:T?.rawCommand,_=F?Wt(F):T?.command,ee=Qt(t);if(Ys(T?.beforeWorktree,ee)){let w=[...new Set([...T?.beforeWorktree?.changedFiles??[],...ee?.changedFiles??[]])],le=typeof E.item.aggregated_output=="string"?xt(E.item.aggregated_output,Gs):void 0,ie=typeof E.item.exit_code=="number"?E.item.exit_code:E.item.exit_code===null?null:void 0,G=typeof E.item.status=="string"?E.item.status:void 0;q.push({sequence:q.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...F?{rawCommand:F}:{},..._?{command:_}:{},...ie!==void 0?{exitCode:ie}:{},...G?{status:G}:{},...le?{output:le.text}:{},...le?.truncated?{outputTruncated:!0}:{},...T?.beforeWorktree?{beforeWorktree:T.beforeWorktree}:{},...ee?{afterWorktree:ee}:{},...w.length>0?{touchedFiles:Ks(t,w,T?.beforeSnapshots??new Map)}:{}})}$&&Q.delete($)}}N==="turn.failed"&&(K=!0,z=E.error?.message||E.message||"Turn failed")}catch{}});let A=[];M.stderr?.on("data",k=>{A.push(k.toString())}),M.on("close",k=>{Z.close(),W.length===0&&O.size>0&&console.warn(`[Codex:${s}] No text captured. Event types seen: ${[...O].join(", ")}`),k!==0&&k!==null&&(K=!0,z=A.join("")||`Codex process exited with code ${k}`),J({sessionId:U,text:W.join(""),success:!K,error:K?z:void 0,editEvents:q.length>0?q:void 0,toolsUsed:S.length>0?S:void 0})}),M.on("error",k=>{K=!0,z=k.message,J({sessionId:U,text:W.join(""),success:!1,error:z,editEvents:q.length>0?q:void 0,toolsUsed:S.length>0?S:void 0})})});return{process:M,result:B}}import{spawn as Zs}from"child_process";import{createInterface as eo}from"readline";function en(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 tn(s,e){let{prompt:n,projectRoot:t,resumeSessionId:o,model:i,timeoutMs:a=3e5,onEvent:l,copilotPath:f="copilot"}=e,y=["--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&&y.push(`--resume=${o}`),i&&y.push("--model",i),y.push("-p",n);let v=Zs(f,y,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),M=new Promise(B=>{let J,U=[],W=[],S=!1,q="",V=!1,Q=setTimeout(()=>{V=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},a),K=eo({input:v.stdout}),z=new Set,Z=[];K.on("line",A=>{if(A.trim())try{let k=JSON.parse(A),E=Ce(k);z.add(E),Z.length<5&&no(E)&&Z.push(A.slice(0,800));let N=Ae(k,["sessionId","session_id","id"],["session","conversation","thread"]);N&&!J&&(J=N);let $=to(k,U.length===0);$&&(U.push($),l?.({type:"delta",jobId:s,text:$},s));let T=so(k);T&&l?.({type:"thinking",jobId:s,text:T},s);let F=oo(k);F&&(W.push(F.label),l?.({type:"tool_use",jobId:s,tool:F.tool,...F.file?{file:F.file}:{},...F.content?{content:F.content}:{}},s));let _=ro(k);_&&(S=!0,q=_)}catch{}});let O=[];v.stderr?.on("data",A=>{O.push(A.toString())}),v.on("close",A=>{clearTimeout(Q),K.close(),U.length===0&&z.size>0&&(console.warn(`[Copilot:${s}] No text captured. Event types seen: ${[...z].join(", ")}`),Z.length>0&&console.warn(`[Copilot:${s}] Sample text-bearing candidates: ${Z.join(`
32
- `)}`)),V?(S=!0,q=`Timed out after ${Math.round(a/6e4)} minutes`):A!==0&&A!==null&&(S=!0,q=O.join("").trim()||q||`Copilot process exited with code ${A}`);let k=S?en(q,i):null;B({sessionId:J,text:U.join(""),success:!S,error:k?.message,errorCode:k?.code,recoverableError:k?.recoverable,provider:"copilot",toolsUsed:W.length>0?W:void 0})}),v.on("error",A=>{clearTimeout(Q);let k=en(A.message,i);B({sessionId:J,text:U.join(""),success:!1,error:k.message,errorCode:k.code,recoverableError:k.recoverable,provider:"copilot",toolsUsed:W.length>0?W:void 0})})});return{process:v,result:M}}function Ce(s){if(typeof s.type=="string")return s.type;let e=s.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof s.event=="string"?s.event:"unknown"}function to(s,e=!1){let n=Ce(s).toLowerCase(),t=s.update,o=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&o?.type==="text"&&typeof o.text=="string")return o.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return me(s.delta)??me(s.content)??me(s.message);if(n==="assistant.message"&&e)return me(s.message)??me(s.content)??me(s);if(n==="result"&&e)return me(s.result)??me(s.output)??me(s.message)??me(s);let i=s.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof s.text=="string"&&Pt(s))return s.text;if(typeof s.message=="string"&&Pt(s))return s.message;if(typeof s.delta=="string"&&Pt(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 no(s){let e=s.toLowerCase();return e.includes("assistant.message")||e==="result"}function so(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 oo(s){let e=Ae(s,["tool","toolName","tool_name","name"]),n=Ae(s,["command","cmd"]),t=Ae(s,["file","path","filename","filePath"]),o=Ce(s);if(n||o.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
- `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let i=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function ro(s){if(typeof s.error=="string")return s.error;if(s.error&&typeof s.error=="object"){let e=s.error;if(typeof e.message=="string")return e.message}if(typeof s.message=="string"&&Ce(s).toLowerCase().includes("error"))return s.message}function Ae(s,e,n=[]){for(let t of e){let o=s[t];if(typeof o=="string")return o}for(let[t,o]of Object.entries(s)){if(!o||typeof o!="object"||n.length>0&&!n.some(a=>t.toLowerCase().includes(a)))continue;let i=Ae(o,e);if(i)return i}}function Pt(s){let e=Ce(s).toLowerCase();return(typeof s.role=="string"?s.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{execFile as io}from"child_process";import{copyFile as nn,mkdir as sn,readdir as ao,readFile as lo,writeFile as co}from"fs/promises";import{join as Ie}from"path";var Ve=class{constructor(e){this.projectRoot=e;let n=Ie(e,".popmelt");this.decisionsDir=Ie(n,"decisions"),this.screenshotsDir=Ie(n,"screenshots")}async persist(e,n,t){try{await sn(this.decisionsDir,{recursive:!0}),await sn(this.screenshotsDir,{recursive:!0});try{await nn(n,Ie(this.screenshotsDir,`s-${e.id}.webp`))}catch{}for(let o=0;o<t.length;o++)try{let i=e.pastedImagePaths[o];i&&await nn(t[o],Ie(this.screenshotsDir,i.replace("screenshots/","")))}catch{}await co(Ie(this.decisionsDir,`d-${e.id}.json`),JSON.stringify(e,null,2))}catch(o){console.error("[DecisionStore] Failed to persist decision record:",o)}}async listDecisionIds(){try{return(await ao(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 lo(Ie(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}captureGitDiff(e){return new Promise(n=>{io("git",["diff","HEAD"],{cwd:e,timeout:5e3,maxBuffer:1024*1024},(t,o)=>{if(t){n(null);return}n(o||null)})})}};import{mkdir as $e,readFile as on,writeFile as _e}from"fs/promises";import{join as Oe}from"path";var uo=80,po=24,rn=1e3,Ke=class{constructor(e){this.evalsDir=Oe(e,".popmelt","evals"),this.suitePath=Oe(this.evalsDir,"evals.json"),this.runsPath=Oe(this.evalsDir,"runs.json"),this.screenshotsDir=Oe(this.evalsDir,"screenshots")}async loadSuite(){try{let e=await on(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 on(this.runsPath,"utf-8"),n=JSON.parse(e);if(n?.version===1&&Array.isArray(n.runs))return n}catch{}return{version:1,updatedAt:0,runs:[]}}async loadSuiteWithRuns(){let[e,n]=await Promise.all([this.loadSuite(),this.loadRuns()]);return{...e,runs:n.runs}}async loadSuiteWithCurrentRuns(e){let n=await this.loadSuiteWithRuns();return e?{...n,runs:n.runs.filter(t=>t.codeFingerprint===e)}:n}async writeSynthesized(e){let n=await this.loadSuite(),t=new Map(n.cases.map(a=>[a.id,a])),o=new Set;for(let a of e){let l=t.get(a.id);l&&(l.title!==a.title||l.prompt!==a.prompt||JSON.stringify(l.assertions)!==JSON.stringify(a.assertions))&&o.add(a.id),t.set(a.id,a)}let i={version:1,updatedAt:Date.now(),cases:[...t.values()]};return await $e(this.evalsDir,{recursive:!0}),await _e(this.suitePath,JSON.stringify(i,null,2)),o.size>0&&await this.invalidateRunsForEvals(o),i}async updateCase(e,n){let t=await this.loadSuite(),o=n.title!==void 0||n.assertions!==void 0,i=t.cases.map(l=>l.id===e?{...l,...n.status?{status:n.status}:{},...n.title?{title:n.title}:{},...n.assertions?{assertions:n.assertions}:{}}:l),a=i.find(l=>l.id===e)??null;return a?(await $e(this.evalsDir,{recursive:!0}),await _e(this.suitePath,JSON.stringify({version:1,updatedAt:Date.now(),cases:i},null,2)),o&&await this.invalidateRunsForEvals(new Set([e])),a):null}async invalidateRunsForEvals(e){let t=(await this.loadRuns()).runs.filter(i=>!e.has(i.evalId)),o={version:1,updatedAt:Date.now(),runs:t};return await $e(this.evalsDir,{recursive:!0}),await _e(this.runsPath,JSON.stringify(o,null,2)),o}async writeRun(e){let n=await this.loadRuns(),t=[e,...n.runs.filter(i=>i.id!==e.id)].slice(0,200),o={version:1,updatedAt:Date.now(),runs:t};return await $e(this.evalsDir,{recursive:!0}),await _e(this.runsPath,JSON.stringify(o,null,2)),o}async writeRunScreenshot(e,n){return await $e(this.screenshotsDir,{recursive:!0}),await _e(Oe(this.screenshotsDir,`eval-${e}.webp`),n),`evals/screenshots/eval-${e}.webp`}async findCase(e){return(await this.loadSuite()).cases.find(t=>t.id===e)??null}};function an(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?dn(t):null}catch{return null}}function ln(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?dn(t,"pending"):null}catch{return null}}function cn(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=vo(t.assertionResults,e),i=wo(o);return{status:i,summary:ge(t.summary)||hn(i),assertionResults:o,tooling:So(t.tooling)}}catch{}return{status:"needs_review",summary:Ze(s.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function dn(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),y=Me(i.assertions);if(!a||!l||y.length===0)return;let v=mo(i.category),M=bo(ge(i.id))||`eval-${mn(a).slice(0,32)||o+1}`,B=go(i.status)??e;n.push({id:M,title:a,status:B,category:v,prompt:l,assertions:y,rationale:f||"Inferred from Popmelt design history.",sourceDecisionIds:Me(i.sourceDecisionIds),sourceThreadIds:Me(i.sourceThreadIds)})}),n}function un(s){let e=[...s.decisions].sort((t,o)=>o.createdAt-t.createdAt).slice(0,uo),n=Object.values(s.threads.threads).sort((t,o)=>o.updatedAt-t.updatedAt).slice(0,po);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(fo).join(`
49
-
50
- `)||"No decisions found."}
51
-
52
- ## Recent Threads
53
- ${n.map(ho).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 pn(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 zs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),qs=new Set(["default","flex","fast","priority"]);function ht(o){let e=typeof o.reasoningEffort=="string"&&zs.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&qs.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function un(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 Us}from"child_process";import{createInterface as Hs}from"readline";var Ws=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"]),Vo=1e5;function Gs(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ws.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>Vo?t.slice(0,Vo)+`
29
+ \u2026[truncated]`:t}function mn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:d="claude",resumeSessionId:c,model:l,reasoningEffort:h,timeoutMs:R=3e5,onEvent:w}=e,b=[];c?b.push("--resume",c,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(s)),l&&b.push("--model",l),h&&b.push("--effort",h);for(let y of i)b.push("--allowedTools",y);let g=Us(d,b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(y=>{let f,v=[],x=[],S=[],_=!1,J="",A,N,T=!1,B=setTimeout(()=>{T=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},R),H=Hs({input:g.stdout}),te=new Set;H.on("line",ne=>{if(ne.trim())try{let oe=JSON.parse(ne);oe.session_id&&!f&&(f=oe.session_id);let he=oe.type??(oe.event?.type?`event.${oe.event.type}`:"unknown");if(te.add(he),oe.type==="result"&&oe.result&&v.length===0){let Y=typeof oe.result=="string"?oe.result:"";Y&&(v.push(Y),w?.({type:"delta",jobId:o,text:Y},o))}if(oe.type==="assistant"&&Array.isArray(oe.message?.content)){typeof oe.error=="string"&&(A=oe.error);for(let Y of oe.message.content){if(Y.type==="text"&&Y.text&&(v.push(Y.text),w?.({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=Gs(Y);if(w?.({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&&w?.({type:"thinking",jobId:o,text:Y.thinking},o)}}oe.type==="result"&&oe.is_error===!0&&(_=!0,typeof oe.error=="string"&&(A=oe.error),typeof oe.result=="string"&&(N=oe.result)),oe.type==="user"&&oe.tool_use_result?.file?.filePath&&w?.({type:"tool_use",jobId:o,tool:"Read",file:oe.tool_use_result.file.filePath},o)}catch{}});let W=[];g.stderr?.on("data",ne=>{W.push(ne.toString())}),g.on("close",ne=>{if(clearTimeout(B),H.close(),v.length===0&&te.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...te].join(", ")}`),T)_=!0,J=`Timed out after ${Math.round(R/6e4)} minutes`;else if(ne!==0&&ne!==null){_=!0;let he=W.join("").trim(),Y=v.join("").trim(),G=v.length===0&&te.size>0?` (no text captured, event types: ${[...te].join(", ")})`:"";J=he||N||Y||`Claude process exited with code ${ne}${G}`}_&&!J&&N&&(J=N);let oe=Vs(J,A);y({sessionId:f,text:v.join(""),success:!_,error:_?oe.message:void 0,errorCode:_?oe.code:void 0,recoverableError:_?oe.recoverable:void 0,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})}),g.on("error",ne=>{clearTimeout(B),_=!0,J=ne.message,y({sessionId:f,text:v.join(""),success:!1,error:J,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})})});return{process:g,result:p}}function Vs(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 Ks,spawnSync as er}from"child_process";import{readFileSync as Qs,statSync as Xs}from"fs";import{basename as Ys,extname as Zs,isAbsolute as ei,relative as tr,resolve as ti}from"path";import{createInterface as ni}from"readline";function Ko(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Qo=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"]),io=2e5,oi=1e5,nr=2e5;function or(o){let e=Ys(o).toLowerCase(),n=Zs(o).toLowerCase();return Qo.has(n)||Qo.has(e)}function Ut(o,e){let n=ei(e)?e:ti(o,e),t=tr(o,n);return t===""||t.startsWith("..")?null:n}function fn(o,e){if(!or(e))return;let n=Ut(o,e);if(n)try{let t=Xs(n);return t.isFile()?t.size>io?{exists:!0,truncated:!0}:{exists:!0,content:Qs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function ri(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function si(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 Xo(o){return ri(o,["patch","diff","unifiedDiff","unified_diff"])}function ao(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Yo(o,e){let n=er("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:nr+65536});return n.status!==0?null:n.stdout??""}function ii(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 Zo(o){let e=Yo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Yo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=ao(n,nr);return{status:e,changedFiles:ii(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function ai(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function ci(o,e){if(!or(e))return;let n=Ut(o,e);if(!n)return;let t=tr(o,n);if(t===""||t.startsWith(".."))return;let r=er("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:io+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=ao(s,io);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function di(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):ci(o,t),s=fn(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function hn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:d,sandboxMode:c="workspace-write",configOverrides:l=[]}=e,h=[];if(s){h.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let b of l)h.push("-c",b);i&&h.push("-m",i),h.push(s),h.push(n),r&&h.push("--image",r)}else{h.push("exec","--skip-git-repo-check","--json","--sandbox",c);for(let b of l)h.push("-c",b);i&&h.push("-m",i),h.push(n),r&&h.push("--image",r)}let R=Ks("codex",h,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),w=new Promise(b=>{let g,p=[],y=[],f=[],v=new Map,x=new Map,S=!1,_="",J=ni({input:R.stdout}),A=new Set;J.on("line",T=>{if(T.trim())try{let B=JSON.parse(T),H=B.type??"unknown";if(A.add(H),H==="thread.started"&&B.thread_id&&!g&&(g=B.thread_id),(H==="item.agentMessage.delta"||H==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),d?.({type:"delta",jobId:o,text:B.delta.text},o)),(H==="item.reasoning.delta"||H==="item/reasoning/delta")&&B.delta?.text&&d?.({type:"thinking",jobId:o,text:B.delta.text},o),(H==="item.started"||H==="item/started")&&B.item){let te=B.item.type;if(te==="command_execution"){let W=B.item.command,ne=W?Ko(W):void 0,oe=Zo(t),he=new Map;for(let G of oe?.changedFiles??[])he.set(G,fn(t,G));typeof B.item.id=="string"&&x.set(B.item.id,{...W?{rawCommand:W}:{},...ne?{command:ne}:{},...oe?{beforeWorktree:oe}:{},beforeSnapshots:he});let Y=ne?`Bash: ${ne.split(`
31
+ `)[0].slice(0,80)}`:"Bash";y.push(Y),d?.({type:"tool_use",jobId:o,tool:"Bash",...ne?{content:ne}:{}},o)}else if(te==="file_change"){let W=B.item.filename||B.item.path;W&&!v.has(W)&&v.set(W,fn(t,W)),y.push(W?`Edit ${W.split("/").pop()}`:"Edit");let ne=W?Ut(t,W)??W:void 0;d?.({type:"tool_use",jobId:o,tool:"Edit",...ne?{file:ne}:{}},o)}else if(te==="file_read"){let W=B.item.filename||B.item.path;y.push(W?`Read ${W.split("/").pop()}`:"Read");let ne=W?Ut(t,W)??W:void 0;d?.({type:"tool_use",jobId:o,tool:"Read",...ne?{file:ne}:{}},o)}else if(te==="web_search")y.push("WebSearch"),d?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(te==="mcp_tool_call"){let W=B.item.tool_name||B.item.name||"MCP";y.push(W),d?.({type:"tool_use",jobId:o,tool:W},o)}}if((H==="item.completed"||H==="item/completed")&&B.item){if(B.item.type==="agent_message"){let te=B.item.text;typeof te=="string"&&te&&(p.push(te),d?.({type:"delta",jobId:o,text:te},o))}else if(B.item.type==="reasoning"){let te=B.item.text;typeof te=="string"&&te&&d?.({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 W=te.path||te.filename,ne=te.kind==="add"?"Write":"Edit";if(W){y.push(`${ne} ${W.split("/").pop()}`);let oe=Ut(t,W)??W;d?.({type:"tool_use",jobId:o,tool:ne,file:oe},o);let he=te,Y=typeof he.kind=="string"?he.kind:void 0,G=si(Y),q=v.get(W),fe=fn(t,W);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:W,...q?{before:q}:{},...fe?{after:fe}:{},...Xo(he)?{patch:Xo(he)}:{},...Y?{rawKind:Y}:{}}),v.set(W,fe)}}else if(B.item.type==="command_execution"){let te=typeof B.item.id=="string"?B.item.id:void 0,W=te?x.get(te):void 0,ne=typeof B.item.command=="string"?B.item.command:W?.rawCommand,oe=ne?Ko(ne):W?.command,he=Zo(t);if(ai(W?.beforeWorktree,he)){let Y=[...new Set([...W?.beforeWorktree?.changedFiles??[],...he?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?ao(B.item.aggregated_output,oi):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}:{},...W?.beforeWorktree?{beforeWorktree:W.beforeWorktree}:{},...he?{afterWorktree:he}:{},...Y.length>0?{touchedFiles:di(t,Y,W?.beforeSnapshots??new Map)}:{}})}te&&x.delete(te)}}H==="turn.failed"&&(S=!0,_=B.error?.message||B.message||"Turn failed")}catch{}});let N=[];R.stderr?.on("data",T=>{N.push(T.toString())}),R.on("close",T=>{J.close(),p.length===0&&A.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),T!==0&&T!==null&&(S=!0,_=N.join("")||`Codex process exited with code ${T}`),b({sessionId:g,text:p.join(""),success:!S,error:S?_:void 0,editEvents:f.length>0?f:void 0,toolsUsed:y.length>0?y:void 0})}),R.on("error",T=>{S=!0,_=T.message,b({sessionId:g,text:p.join(""),success:!1,error:_,editEvents:f.length>0?f:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:R,result:w}}import{spawn as li}from"child_process";import{createInterface as pi}from"readline";function rr(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 sr(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:s,timeoutMs:i=3e5,onEvent:d,copilotPath:c="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 h=li(c,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(w=>{let b,g=[],p=[],y=!1,f="",v=!1,x=setTimeout(()=>{v=!0,h.kill("SIGTERM"),setTimeout(()=>{try{h.kill("SIGKILL")}catch{}},5e3)},i),S=pi({input:h.stdout}),_=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Wt(T);_.add(B),J.length<5&&mi(B)&&J.push(N.slice(0,800));let H=Ht(T,["sessionId","session_id","id"],["session","conversation","thread"]);H&&!b&&(b=H);let te=ui(T,g.length===0);te&&(g.push(te),d?.({type:"delta",jobId:o,text:te},o));let W=fi(T);W&&d?.({type:"thinking",jobId:o,text:W},o);let ne=hi(T);ne&&(p.push(ne.label),d?.({type:"tool_use",jobId:o,tool:ne.tool,...ne.file?{file:ne.file}:{},...ne.content?{content:ne.content}:{}},o));let oe=gi(T);oe&&(y=!0,f=oe)}catch{}});let A=[];h.stderr?.on("data",N=>{A.push(N.toString())}),h.on("close",N=>{clearTimeout(x),S.close(),g.length===0&&_.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[..._].join(", ")}`),J.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${J.join(`
32
+ `)}`)),v?(y=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(y=!0,f=A.join("").trim()||f||`Copilot process exited with code ${N}`);let T=y?rr(f,s):null;w({sessionId:b,text:g.join(""),success:!y,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),h.on("error",N=>{clearTimeout(x);let T=rr(N.message,s);w({sessionId:b,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:h,result:R}}function Wt(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 ui(o,e=!1){let n=Wt(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Fe(o.delta)??Fe(o.content)??Fe(o.message);if(n==="assistant.message"&&e)return Fe(o.message)??Fe(o.content)??Fe(o);if(n==="result"&&e)return Fe(o.result)??Fe(o.output)??Fe(o.message)??Fe(o);let s=o.content;if(s?.type==="text"&&typeof s.text=="string")return s.text;if(typeof o.text=="string"&&co(o))return o.text;if(typeof o.message=="string"&&co(o))return o.message;if(typeof o.delta=="string"&&co(o))return o.delta}function Fe(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Fe).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Fe(e[n]);if(t)return t}}function mi(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function fi(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 hi(o){let e=Ht(o,["tool","toolName","tool_name","name"]),n=Ht(o,["command","cmd"]),t=Ht(o,["file","path","filename","filePath"]),r=Wt(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 gi(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"&&Wt(o).toLowerCase().includes("error"))return o.message}function Ht(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=Ht(r,e);if(s)return s}}function co(o){let e=Wt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as yi,readFile as vi}from"fs/promises";import{join as lo}from"path";var gn=class{constructor(e){let n=lo(e,".popmelt");this.decisionsDir=lo(n,"decisions")}async listDecisionIds(){try{return(await yi(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 vi(lo(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 ar(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=Ti(r);return{status:s,summary:et(t.summary)||pr(s),assertionResults:r,tooling:ji(t.tooling)}}catch{}return{status:"needs_review",summary:Ei(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 cr(o,e){let n=(o.selectedChanges??[]).flatMap(v=>Array.isArray(v.path)&&v.path.length?[v.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(v=>v.path),s=[...new Set(r.map(v=>v.map(String).join(".")).filter(Boolean))].map(v=>({kind:"model_path",value:v}));if(s.length===0||o.decisionIds.length===0)return[];let i=new Set(o.decisionIds),d=new Set(s.map(v=>v.value)),c=e.cases.find(v=>v.status!=="rejected"&&(v.sourceDecisionIds.some(x=>i.has(x))||(v.dependencies??[]).some(x=>x.kind==="model_path"&&d.has(x.value)))),l=(o.selectedChanges??[]).find(v=>v.label?.trim())?.label?.trim()??t.find(v=>v.label?.trim())?.label?.trim()??o.title,h=c?.id.startsWith("eval-model-")??!1,R=(o.selectedChanges??[]).flatMap(v=>Array.isArray(v.path)&&v.path.length>0?[{path:v.path,value:v.value,label:v.label,detail:v.detail}]:[]),b=(R.length>0?R:t.map(v=>({path:v.path,value:v.value,label:v.label,detail:v.rationale}))).flatMap(v=>wi(v,o.decisionIds)),g=vn(o.underlyingClaim??o.summary),p=[...new Set([...c&&!h?c.assertions:[],...b,...b.length===0&&g?[g]:[]])],y=s[0].value,f=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:c?.id??`eval-model-${o.id}`,title:c&&!h?c.title:l,status:"pending",category:c?.category??f,prompt:c&&!h?c.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:c&&!h?c.rationale:xi(y),sourceDecisionIds:[...new Set([...c?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...c?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...c?.dependencies??[],...s].map(v=>[`${v.kind}:${v.value}`,v])).values()]}]}function wi(o,e){let n=String(o.path[0]??"");if(n==="rules")return Ii(o.value,e);if(n==="components"){let i=dr(String(o.path[1]??o.label??"component")),d=yn(o.value),c=d?Vt(d.usage):[];if(c.length>0){let h=Si(c),R=c.length===1?"uses":"use";return[`The ${h} ${R} the same shared implementation for the ${i} pattern.`]}if(d?.shared===!0)return[`The product uses a shared implementation for the ${i} pattern.`];let l=d?et(d.constraint):"";if(l){let h=bi(l,i);if(h)return[h]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),d=yn(o.value),c=d&&"value"in d?d.value:o.value,l=Pi(c);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=yn(o.value),r=t?et(t.text)||et(t.constraint):typeof o.value=="string"?o.value:"",s=vn(r||o.detail||"");return s?[s]:[]}function Ii(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let d=yn(i),c=d?et(d.text):"";return c?[{text:c,sources:d?Vt(d.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(d=>n.has(d)));return(r.length>0?r:t.length===1?t:[]).map(i=>vn(i.text)).filter(i=>!!i)}function bi(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?Pt(`Wherever ${Gt(n[1])}, the shared ${e} implementation is used instead of ${Gt(n[2])}`):vn(o)}function po(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Pt(`${ir(n[1])} is ${Gt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Pt(ir(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Pt(`The product uses ${Gt(r[1])}`);let s=e.match(/^Do not (.+?)\.?$/i);return s?Pt(`The product does not ${Gt(s[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Pt(e)}var vn=po;function xi(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${dr(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 yn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function dr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function Si(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 Pi(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function Pt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function ir(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Gt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function lr(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 fn(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 Vt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Ri(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:Ri(s.status)??"needs_review",summary:et(s.summary)||pr("needs_review"),evidence:Vt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Ti(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function ji(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:Vt(e.evidenceTypes).length>0?Vt(e.evidenceTypes):["screenshot"]}}function pr(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 Ei(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Mi}from"crypto";import{mkdir as _i,writeFile as Ai}from"fs/promises";import{join as uo}from"path";var wn=class{constructor(e){this.root=uo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=uo(this.root,"eval-screenshots"),t=Mi("sha256").update(e).digest("hex"),r=uo(n,`${t}.webp`);return await _i(n,{recursive:!0}),await Ai(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as ur}from"crypto";import{mkdir as mo,readFile as fo,writeFile as In}from"fs/promises";import{dirname as ho,join as Rt}from"path";var He="[ProjectionWorker]",Ci={version:1,runs:[]},$i={version:1,updatedAt:0,proposals:[]},Oi=12;function Di(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 mr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${He} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${He} Rule count ${e.length} exceeds cap of 30`),e}function Ji(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ni(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 y of p)typeof y=="string"&&t.has(y)&&r.add(y)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},d=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},c=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,y=typeof p=="string"?c.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(g)}).length,h=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},w=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(h[g])).length,b=Object.keys(d).filter(g=>JSON.stringify(d[g])!==JSON.stringify(R[g])).length;return{ruleCount:l,tokenSectionCount:w,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function Bi(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Li(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 bn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Li(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=Bi(n)}function fr(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 Fi(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 zi(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 hr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Fi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?zi(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var xn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Rt(e,".popmelt");this.runsPath=Rt(t,"projection-runs.json"),this.legacyRunsPath=Rt(t,"materialization-runs.json"),this.proposalsPath=Rt(t,"projection-queue.json"),this.legacyProposalsPath=Rt(t,"model-proposals.json"),this.modelPath=Rt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await fo(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Di(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?fr(n,r):bn(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(Oi),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(`${He} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),d=Wi(r,i),c=Ji(r,t.totalCandidateDecisionCount,d);n=ur().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:c};await this.persistRun(l);let h=!0,R,w,b;try{let g=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(g,d,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await y;if(!f.success)h=!1,R=f.error,console.error(`${He} ${p} spawn error:`,R);else{let v=Hi(f.text,s);if(v){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of v)bn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=mr(x.rules));let S=Ni(x,s,i);if(v){let J=[...new Set(v.flatMap(A=>A.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(A=>!J.includes(A))}w=S;let _=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:w,changes:v});b=_.id,console.log(`${He} Created model proposal ${_.id} for ${s.length} decision(s)`)}else h=!1,R="No valid bounded <model-changes> block found in response",console.error(`${He} ${R}`)}}catch(g){h=!1,R=g instanceof Error?g.message:String(g),console.error(`${He} Error:`,R)}return await this.persistRun({...l,status:h?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:w,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:h,error:R}),{processedIds:s,success:h,error:R,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=mr(e.rules)),await In(this.modelPath,JSON.stringify(e,null,2)),console.log(`${He} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await mo(ho(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2)),n):{...Ci,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??[])bn(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 c of n)!Array.isArray(c.path)||c.path.length===0||(c.remove?fr(i,c.path):bn(i,c.path,c.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 d=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(d.evalId),s.set(d.evalId,d)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:ur().slice(0,8),status:"pending",title:qi(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"}.`:Ui(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 mo(ho(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await In(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await mo(ho(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await fo(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await fo(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?(d,c)=>this.options.onEvent?.(d):void 0;return s==="codex"?{provider:"codex",...hn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:un(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${He} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...mn(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 qi(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 Ui(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 Hi(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,d)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let c=i;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(R=>typeof R=="string"||typeof R=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let h=Array.isArray(c.decisionIds)?c.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return h.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${d+1}`,path:c.path,value:c.value,decisionIds:h,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Wi(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 fo(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
194
- `),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
195
- `),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
196
- Thread: ${s.threadId??"none"}
197
- Created: ${new Date(s.createdAt).toISOString()}
198
- URL: ${s.url||"unknown"}
199
- Instructions:
200
- ${Ze(o||"(none)",rn)}
201
- Resolutions:
202
- ${Ze(i||"(none)",rn)}
203
- Files: ${a.length>0?a.join(", "):"none"}`}function ho(s){let n=s.messages.slice(0,2).concat(s.messages.length>4?s.messages.slice(-2):s.messages.slice(2)).map(t=>{let o=t.feedbackSummary??t.replyToQuestion??t.question??t.responseText??"",i=t.resolutions?.map(a=>`${a.status}: ${a.summary}`).join("; ")??"";return`- ${t.role}: ${Ze(o||i||"(no text)",500)}`}).join(`
204
- `);return`### Thread ${s.id}
205
- Messages: ${s.messages.length}
206
- Updated: ${new Date(s.updatedAt).toISOString()}
207
- ${n}`}function ge(s){return typeof s=="string"?s.trim():""}function Me(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function mo(s){let e=ge(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function go(s){let e=ge(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function yo(s){let e=ge(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function vo(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:yo(i.status)??"needs_review",summary:ge(i.summary)||hn("needs_review"),evidence:Me(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 wo(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function So(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:Me(e.evidenceTypes).length>0?Me(e.evidenceTypes):["screenshot"]}}function hn(s){return s==="pass"?"The current page appears to satisfy this eval.":s==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function bo(s){return mn(s).slice(0,48)}function mn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ze(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as gn}from"crypto";import{mkdir as It,readFile as et,writeFile as xe}from"fs/promises";import{dirname as kt,join as De}from"path";var ae="[Materializer]",yn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},xo={version:1,runs:[]},Po={version:1,updatedAt:0,proposals:[]},Io=12;function ko(s){return Array.isArray(s)?s.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function Ne(s){let e=[];for(let n of s){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${ae} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${ae} Rule count ${e.length} exceeds cap of 30`),e}function Eo(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ro(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 y of f)typeof y=="string"&&n.has(y)&&t.add(y)}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 Mo(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function To(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 Ao(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=To(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=Mo(n)}function Co(s,e){let n=s;for(let o=0;o<e.length-1;o++){let i=n[String(e[o])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}var tt=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=De(e,".popmelt");this.indexPath=De(o,"materialized.json"),this.runsPath=De(o,"materialization-runs.json"),this.proposalsPath=De(o,"model-proposals.json"),this.modelPath=De(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await et(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=ko(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 xe(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let f=0;f<o.length-1;f++){let y=o[f];(!i[y]||typeof i[y]!="object")&&(i[y]={}),i=i[y]}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 xe(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ae} Updated token "${e}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=e.split("."),o=n;for(let a=0;a<t.length-1;a++){let l=t[a];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let i=t[t.length-1];return i in o?(delete o[i],await xe(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=n.components;return!t||!t[e]?{removed:!1}:(delete t[e],await xe(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(l=>{let f=e.decisions[l];return f?f.status==="applied"||f.status==="merged"||f.status==="rejected"||f.status==="running"||f.status==="queued"||f.status==="proposed"?!1:f.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(l=>l.resolutions.some(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern")),a=i.sort((l,f)=>f.createdAt-l.createdAt).slice(0,Io);return i.length>a.length&&console.log(`${ae} Selected ${a.length}/${i.length} pattern decision(s); remaining decisions stay pending for later runs.`),{decisions:a,totalCandidateDecisionCount:i.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnmaterializedPatternDecisions(),o=t.decisions;if(o.length===0)return{processedIds:[],success:!0};let i=o.map(W=>W.id);console.log(`${ae} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=Oo(o,a),f=Eo(o,t.totalCandidateDecisionCount,l);n=gn().slice(0,8);let y={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(y),await this.updateDecisionStates(i,"running",n);let v=!0,M,B,J;try{let W=`mat-${Date.now()}`,{provider:S,result:q}=this.spawnModelAgent(W,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});y={...y,provider:S},await this.persistRun(y);let V=await q;if(!V.success)v=!1,M=V.error,console.error(`${ae} ${S} spawn error:`,M);else{let Q=nt(V.text);if(Q){Array.isArray(Q.rules)&&(Q.rules=Ne(Q.rules)),B=Ro(Q,i);let K=await this.createModelProposal({decisionIds:i,proposedModel:Q,runId:n,threadId:e.threadId,provider:S,model:e.model??this.options.model});J=K.id,console.log(`${ae} Created model proposal ${K.id} for ${i.length} decision(s)`)}else v=!1,M="No <model> block found in response",console.error(`${ae} ${M}`)}}catch(W){v=!1,M=W instanceof Error?W.message:String(W),console.error(`${ae} Error:`,M)}let U=await this.loadIndex();return U.lastRunAt=Date.now(),U.lastRunDecisionIds=i,U.lastRunError=M??null,await this.persistIndex(U),await this.updateDecisionStates(i,v?"proposed":"failed",n,M),await this.persistRun({...y,status:v?"proposed":"failed",completedAt:Date.now(),error:M,outputStats:B,proposalId:J}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:v,error:M}),{processedIds:i,success:v,error:M,runId:n,proposalId:J}}finally{this.running=!1}}async consolidate(e={}){if(this.running)return{success:!1,error:"Already running"};this.running=!0;try{let n=await this.loadModel();if(!n)return{success:!1,error:"No model exists"};let t=Do(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,t,e,{maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[]}),a=await i;if(!a.success)return console.error(`${ae} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=nt(a.text);return l?(Array.isArray(l.rules)&&(l.rules=Ne(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await xe(this.modelPath,JSON.stringify(l,null,2)),console.log(`${ae} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${ae} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(n){let t=n instanceof Error?n.message:String(n);return console.error(`${ae} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ne(e.rules)),await xe(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ae} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await et(this.indexPath,"utf-8"),n=JSON.parse(e);if(n.version===2&&n.decisions)return this.cachedIndex=n,this.cachedIndex;if(n.version===1&&Array.isArray(n.materializedIds)){let t=Date.now(),o=Object.fromEntries(n.materializedIds.map(i=>[i,{status:"applied",runIds:[],attemptCount:1,updatedAt:t}]));return this.cachedIndex={version:2,decisions:o,lastRunAt:n.lastRunAt??null,lastRunDecisionIds:n.lastRunDecisionIds??[],lastRunError:n.lastRunError??null,materializedIds:n.materializedIds},this.cachedIndex}}catch{return this.cachedIndex={...yn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...yn,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 It(kt(this.indexPath),{recursive:!0}),await xe(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write index:`,n)}}async loadRuns(){try{let e=await et(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...xo,runs:[]}}async loadModelProposals(){try{let e=await et(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...Po,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?Co(i,l.path):Ao(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:gn().slice(0,8),status:"pending",title:$o(e.proposedModel),summary:_o(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 It(kt(this.proposalsPath),{recursive:!0}),await xe(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(o=>o.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await It(kt(this.runsPath),{recursive:!0}),await xe(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${ae} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let l of e){let f=i.decisions[l],y=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[l]={status:n,runIds:y,error:o,attemptCount:n==="running"?f?.attemptCount??0:(f?.attemptCount??0)+1,updatedAt:a}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",a=this.options.onEvent?(l,f)=>this.options.onEvent?.(l):void 0;return i==="codex"?{provider:"codex",...Ye(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:qe(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${ae} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Qe(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function $o(s){let n=(Array.isArray(s.rules)?s.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function _o(s,e){let n=Array.isArray(s.rules)?s.rules.length:0,t=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?Object.keys(s.tokens).length:0,o=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function nt(s){let e=s.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function Oo(s,e){let n=s.map(i=>{let l=i.resolutions.filter(v=>(v.finalScope??v.inferredScope)?.breadth==="pattern").map(v=>{let B=(v.finalScope??v.inferredScope)?.target??"unknown",J=v.filesModified?.join(", ")??"none";return`- **${v.summary}** [scope: pattern/${B}]
208
- Files modified: ${J}`}).join(`
209
- `),f=i.annotations.map(v=>v.instruction).filter(Boolean).join(`
210
- `),y=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
- ${y}
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,162 +141,101 @@ 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 Do(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 vn(s){return`You are a design system curator reviewing a project's design model. Your job is to propose improvements to the rules \u2014 merging duplicates, filling gaps, removing noise.
333
-
334
- ## Current Model
335
- \`\`\`json
336
- ${JSON.stringify(s,null,2)}
337
- \`\`\`
338
-
339
- ## Instructions
340
- 1. Review all current rules, tokens, and components.
341
- 2. Propose specific changes \u2014 additions, merges, removals \u2014 with brief reasoning for each.
342
- 3. Present your proposals as clear text so the developer can review them.
343
- 4. Do NOT output a <model> block yet. First get the developer's approval.
344
-
345
- ## Output format
346
- - List each proposed change as a numbered item with a short rationale.
347
- - Group by action: **Merge**, **Add**, **Remove**, **Reword**.
348
- - After your proposals, output a <question> block asking the developer to approve, adjust, or reject.
349
-
350
- Example:
351
- **Merge**
352
- 1. Rules "Body text uses Inter 16px" and "Paragraph text is Inter 16/1.5" \u2192 "Body/paragraph text uses Inter at 16px/1.5" (they say the same thing)
353
-
354
- **Remove**
355
- 2. "After fixing SSR, re-verify headless output" \u2014 workflow advice, not a design constraint
356
-
357
- **Add**
358
- 3. "Primary actions use the primary color token; secondary actions use gray-500" \u2014 implied by token usage but not codified
359
-
360
- <question>
361
- These are my proposed rule changes. Would you like to approve all of them, adjust specific items, or add more? Once you're happy I'll output the final model.
362
- </question>
363
-
364
- ## After approval
365
- When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var st=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let o of this.listeners)o(e,n,t)}cancelJob(e){let n=this.queue.findIndex(o=>o.id===e);if(n>=0){let[o]=this.queue.splice(n,1);return o?(o.status="cancelled",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),o):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"materialize_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as No}from"child_process";import{readFile as Rt}from"fs/promises";import{homedir as rt}from"os";import{join as he}from"path";var Mt=/popmelt/i,Jo=/chrome|devtools/i;function ke(){return{found:!1,name:null,scope:null,disabled:!1}}function Te(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function Je(s){for(let e of Object.keys(s))if(Mt.test(e))return e;return null}async function ot(s){try{let e=await Rt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function Tt(s){let e=rt(),n=await ot(he(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=Je(o.mcpServers);if(i)return Te(i,"user")}if(o.projects&&typeof o.projects=="object"){let a=o.projects[s];if(a&&typeof a=="object"){let l=a;if(l.mcpServers&&typeof l.mcpServers=="object"){let f=Je(l.mcpServers);if(f){let y=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(v=>Mt.test(v));return Te(f,"project",y)}}}}}let t=await ot(he(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=Je(o.mcpServers);if(a){let l=await wn(s,a);return Te(a,"mcp.json",l)}}let i=Je(o);if(i&&i!=="mcpServers"){let a=await wn(s,i);return Te(i,"mcp.json",a)}}return ke()}async function wn(s,e){let n=he(s,".claude","settings.local.json"),t=await ot(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var zo=/^\[mcp_servers\.([^\]]+)\]/;function Bo(s){return s.replace(/^"(.+)"$/,"$1")}function Lo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function bn(s){let e=s.split(`
366
- `),n=[],t=null;for(let o of e){let i=o.match(zo);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 xn(s){return/enabled\s*=\s*false/i.test(s)}async function At(s){let e=process.env.CODEX_HOME||he(rt(),".codex"),n=await Sn(he(e,"config.toml"),"user");if(n.found)return n;let t=await Sn(he(s,".codex","config.toml"),"project");return t.found?t:ke()}async function jo(s,e){let n=process.env.CODEX_HOME||he(rt(),".codex"),t=new Set;for(let o of[he(n,"config.toml"),he(s,".codex","config.toml")])try{let i=await Rt(o,"utf-8");for(let a of bn(i)){if(Lo(a.name)||xn(a.body))continue;let l=Bo(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function Pn(s){return jo(s,Jo)}async function Ct(s,e="copilot"){let n=await Fo(e);if(n.found)return n;let t=process.env.COPILOT_HOME||he(rt(),".copilot"),o=await Et(he(t,"mcp-config.json"),"user");if(o.found)return o;let i=await Et(he(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await Et(he(s,".github","mcp.json"),"mcp.json");return a.found?a:ke()}async function Fo(s){try{let e=await new Promise((n,t)=>{No(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return In(JSON.parse(e),"user")}catch{return ke()}}async function Et(s,e){let n=await ot(s);return In(n,e)}function In(s,e){if(!s||typeof s!="object")return ke();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=Je(t);return o?Te(o,e):ke()}async function Sn(s,e){try{let n=await Rt(s,"utf-8"),t=bn(n);for(let o of t)if(Mt.test(o.name)){let i=xn(o.body);return Te(o.name,e,i)}}catch{}return ke()}import{execFile as kn}from"child_process";import{mkdir as Uo,readFile as En,writeFile as Rn}from"fs/promises";import{homedir as Mn}from"os";import{dirname as Wo,join as $t}from"path";var _t="https://mcp.popmelt.com/mcp";async function Tn(s=_t){let e=$t(Mn(),".claude.json"),n;try{let o=await En(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 Rn(e,JSON.stringify(n,null,2)+`
370
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function An(s=_t){let e=process.env.CODEX_HOME||$t(Mn(),".codex"),n=$t(e,"config.toml"),t;try{t=await En(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Uo(Wo(n),{recursive:!0});let o=`
168
+ Include property and bindings when the decision context has class-level evidence.`}var Sn=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 Gi}from"child_process";import{readFile as yo}from"fs/promises";import{homedir as Rn}from"os";import{join as Le}from"path";var vo=/popmelt/i,Vi=/chrome|devtools/i;function gt(){return{found:!1,name:null,scope:null,disabled:!1}}function kt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Kt(o){for(let e of Object.keys(o))if(vo.test(e))return e;return null}async function Pn(o){try{let e=await yo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function wo(o){let e=Rn(),n=await Pn(Le(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Kt(r.mcpServers);if(s)return kt(s,"user")}if(r.projects&&typeof r.projects=="object"){let i=r.projects[o];if(i&&typeof i=="object"){let d=i;if(d.mcpServers&&typeof d.mcpServers=="object"){let c=Kt(d.mcpServers);if(c){let l=Array.isArray(d.disabledMcpjsonServers)&&d.disabledMcpjsonServers.some(h=>vo.test(h));return kt(c,"project",l)}}}}}let t=await Pn(Le(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Kt(r.mcpServers);if(i){let d=await gr(o,i);return kt(i,"mcp.json",d)}}let s=Kt(r);if(s&&s!=="mcpServers"){let i=await gr(o,s);return kt(s,"mcp.json",i)}}return gt()}async function gr(o,e){let n=Le(o,".claude","settings.local.json"),t=await Pn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(s=>s===e)}return!1}var Ki=/^\[mcp_servers\.([^\]]+)\]/;function Qi(o){return o.replace(/^"(.+)"$/,"$1")}function Xi(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function vr(o){let e=o.split(`
169
+ `),n=[],t=null;for(let r of e){let s=r.match(Ki);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 wr(o){return/enabled\s*=\s*false/i.test(o)}async function Io(o){let e=process.env.CODEX_HOME||Le(Rn(),".codex"),n=await yr(Le(e,"config.toml"),"user");if(n.found)return n;let t=await yr(Le(o,".codex","config.toml"),"project");return t.found?t:gt()}async function Yi(o,e){let n=process.env.CODEX_HOME||Le(Rn(),".codex"),t=new Set;for(let r of[Le(n,"config.toml"),Le(o,".codex","config.toml")])try{let s=await yo(r,"utf-8");for(let i of vr(s)){if(Xi(i.name)||wr(i.body))continue;let d=Qi(i.name);e.test(d)&&t.add(d)}}catch{}return[...t]}async function Ir(o){return Yi(o,Vi)}async function bo(o,e="copilot"){let n=await Zi(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Le(Rn(),".copilot"),r=await go(Le(t,"mcp-config.json"),"user");if(r.found)return r;let s=await go(Le(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await go(Le(o,".github","mcp.json"),"mcp.json");return i.found?i:gt()}async function Zi(o){try{let e=await new Promise((n,t)=>{Gi(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return br(JSON.parse(e),"user")}catch{return gt()}}async function go(o,e){let n=await Pn(o);return br(n,e)}function br(o,e){if(!o||typeof o!="object")return gt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Kt(t);return r?kt(r,e):gt()}async function yr(o,e){try{let n=await yo(o,"utf-8"),t=vr(n);for(let r of t)if(vo.test(r.name)){let s=wr(r.body);return kt(r.name,e,s)}}catch{}return gt()}import{execFile as xr}from"child_process";import{mkdir as ea,readFile as Sr,writeFile as Pr}from"fs/promises";import{homedir as Rr}from"os";import{dirname as ta,join as xo}from"path";var So="https://mcp.popmelt.com/mcp";async function kr(o=So){let e=xo(Rr(),".claude.json"),n;try{let r=await Sr(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 Pr(e,JSON.stringify(n,null,2)+`
173
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Tr(o=So){let e=process.env.CODEX_HOME||xo(Rr(),".codex"),n=xo(e,"config.toml"),t;try{t=await Sr(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await ea(ta(n),{recursive:!0});let r=`
371
174
  [mcp_servers.popmelt]
372
- url = "${s}"
373
- `;return await Rn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Cn(s=_t,e="copilot"){let n=await Ho(e);if(Go(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{kn(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 Ho(s){try{let e=await new Promise((n,t)=>{kn(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 Go(s){if(!s||typeof s!="object")return!1;let e=s,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var it=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let o=this.leases.get(e),i={id:e,ownerPid:n,createdAt:o?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,o]of this.leases)o.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};async function at(s){let n=(s.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],o=await qo(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),l,f,y,v,M,B,J,U,W,S,q,V,Q,K,z=[],Z=[],O=0,A=[];for(;O<o.length;){let k=o.indexOf(i,O);if(k===-1)break;let E=k+i.length;if(o.slice(k,k+a.length).equals(a))break;let N=E;o[N]===13&&o[N+1]===10&&(N+=2);let $=o.indexOf(`\r
175
+ url = "${o}"
176
+ `;return await Pr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function jr(o=So,e="copilot"){let n=await na(e);if(oa(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{xr(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 na(o){try{let e=await new Promise((n,t)=>{xr(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 oa(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 Ao,readFile as Mt,writeFile as Co}from"fs/promises";import{join as lt}from"path";var ra=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Po(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Tn(o){return new Set(Po(o).split(" ").filter(e=>e.length>2&&!ra.has(e)))}function Er(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function sa(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function ia(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Po).filter(Boolean),s=Tn([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 d;for(let c of sa(i)){let l=Po(c.value);for(let w of r){let b=l===w?95:l.includes(w)||w.includes(l)?75:0;b>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:b>=90?"exact":"strong",matchedBy:c.by,score:b})}let R=["/","#","[","]","="].some(w=>c.value.includes(w))?0:Math.round(Er(Tn(l),s)*55);R>=30&&R>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}d&&n.set(i.id,d)}return n}function aa(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(d=>n.has(d))||i.sourceRefs.some(d=>d.kind==="thread"&&t.has(d.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 ca(o){return Math.ceil(JSON.stringify(o).length/4)}function Ro(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let f=[...o.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===y.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(y=>y.recordType==="implementation_attempt"),d=ia(n,e),c=[...d.values()].sort((y,f)=>f.score-y.score),l=Tn([e.action,e.text].filter(Boolean).join(" ")),h=s.flatMap(y=>{let f=y.subjects.map(_=>d.get(_.subjectId)).filter(_=>!!_),v=Math.max(0,...f.map(_=>_.score)),x=Math.round(Er(Tn(y.claim),l)*35),S=v+x;return S>=50?[{proposal:y,proposalMatches:f,score:S}]:[]}).sort((y,f)=>f.score-y.score||y.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),w=Math.max(200,e.maxEstimatedTokens??1200),b=[],g=0;for(let y of h){if(b.length>=R)break;let f=y.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:S,..._})=>_)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(S=>S.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:aa(y.proposal,i),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...f]},x={...v,estimatedTokens:ca(v)};if(g+x.estimatedTokens>w)break;b.push(x),g+=x.estimatedTokens}let p=Math.max(0,h.length-b.length);return{packets:b,subjectMatches:c.map(({score:y,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:h.length,omittedPacketCount:p,maxEstimatedTokens:w,estimatedTokens:g},uncertainty:d.size===0?"subject_unresolved":h.length===0?"no_relevant_pending_proposal":void 0}}var da=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ko(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function jn(o){return new Set(ko(o).split(" ").filter(e=>e.length>2&&!da.has(e)))}function Mr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function la(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(ko).filter(Boolean),r=jn([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 d,c=[{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 c){let h=ko(l.value);for(let b of t){let g=h===b?95:h.includes(b)||b.includes(h)?75:0;g>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let w=["/","#","[","]","="].some(b=>l.value.includes(b))?0:Math.round(Mr(jn(h),r)*55);w>=30&&w>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:w>=45?"strong":"weak",matchedBy:"semantic",score:w})}d&&s.push(d)}return s.sort((i,d)=>d.score-i.score||i.subjectId.localeCompare(d.subjectId))}function pa(o){return Math.ceil(JSON.stringify(o).length/4)}function Tt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ua(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 ma(o,e,n){let t=e.filter(d=>d.targets.some(c=>c.entityType==="decision"&&c.entityId===o)).sort((d,c)=>c.createdAt.localeCompare(d.createdAt)),r=n.some(d=>d.signalType==="verification_expired"&&d.target.entityType==="decision"&&d.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(d=>d.id)}}function _r(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(A=>A.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(A=>A.recordType==="decision"&&A.state==="active"),d=s?i.filter(A=>s.has(A.id)):i,c=o.records.filter(A=>A.recordType==="implementation_attempt"),l=o.records.filter(A=>A.recordType==="verification_attempt"),h=o.records.filter(A=>A.recordType==="freshness_signal"&&A.state==="open"),R=o.records.filter(A=>A.recordType==="evidence"),w=o.records.filter(A=>A.recordType==="model_entry"),b=[...o.records].reverse().filter(A=>A.recordType==="eval_spec").filter((A,N,T)=>T.findIndex(B=>B.legacyId===A.legacyId)===N),g=la(r,e),p=new Map(g.map(A=>[A.subjectId,A.score])),y=jn([e.action,e.text].filter(Boolean).join(" ")),f=d.flatMap(A=>{let N=Math.max(0,...A.subjects.map(H=>p.get(H.subjectId)??0)),T=Math.round(Mr(jn(A.claim),y)*35),B=N+T;return B>=50?[{decision:A,score:B}]:[]}).sort((A,N)=>N.score-A.score||A.decision.id.localeCompare(N.decision.id)),v=new Map;for(let A of f.slice(0,t))v.set(A.decision.id,A.decision);for(let A of o.relationships){if(!Tt(A,"excepts")&&!Tt(A,"contradicts"))continue;let N=i.find(B=>B.id===A.from.entityId),T=i.find(B=>B.id===A.to.entityId);!N||!T||!v.has(N.id)&&!v.has(T.id)||(v.size<t&&v.set(N.id,N),v.size<t&&v.set(T.id,T))}let x=[...v.values()],S=A=>A.from.entityType==="decision"&&A.to.entityType==="decision"&&v.has(A.from.entityId)&&v.has(A.to.entityId),_=(A,N=!1)=>{let T=new Set(A.map(E=>E.id)),B=h.filter(E=>E.target.entityType==="decision"&&T.has(E.target.entityId)),H=new Set(o.relationships.filter(E=>Tt(E,"excepts")&&T.has(E.from.entityId)&&T.has(E.to.entityId)).flatMap(E=>[E.from.entityId,E.to.entityId])),W=o.relationships.filter(E=>Tt(E,"contradicts")&&T.has(E.from.entityId)&&T.has(E.to.entityId)).map(E=>({id:E.id,decisionIds:[E.from.entityId,E.to.entityId],unresolvedQuestion:E.reason,expansionRefs:[{kind:"record",id:E.id}]})),ne=new Set(W.flatMap(E=>E.decisionIds)),oe=R.filter(E=>E.sourceRefs.some(Z=>Z.kind==="record"&&T.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===E.id&&Z.to.entityType==="decision"&&T.has(Z.to.entityId))),he=Math.max(0,f.length-A.length),Y=o.relationships.some(E=>Tt(E,"contradicts")&&S(E)&&(!T.has(E.from.entityId)||!T.has(E.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:[]}):A.length===0&&q.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),W.length&&q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:W.flatMap(E=>E.expansionRefs)}),oe.some(E=>E.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map(E=>({kind:"record",id:E.id}))}),G&&q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let fe={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:g.map(({score:E,...Z})=>Z),modelEntries:w.filter(E=>E.decisionIds.some(Z=>T.has(Z))).map(E=>({id:E.id,key:E.key,value:E.value,decisionIds:E.decisionIds})),evalSpecs:b.filter(E=>E.decisionIds.some(Z=>T.has(Z))).map(E=>({id:E.id,legacyId:E.legacyId,state:E.state,title:E.title,assertionCount:E.assertions.length,decisionIds:E.decisionIds,expansionRef:{kind:"record",id:E.id}})),decisions:A.map(E=>({id:E.id,kind:E.kind,claim:E.claim,subjectIds:E.subjects.map(Z=>Z.subjectId),authority:E.authority,effectiveState:ne.has(E.id)?"conflicted":H.has(E.id)?"excepted":"active",freshness:B.filter(Z=>Z.target.entityId===E.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:E.id}})),conflicts:W,uncertainties:q,implementation:A.map(E=>ua(E.id,c)),verification:A.map(E=>ma(E.id,l,B)),evidence:oe.map(E=>({evidenceId:E.id,summary:E.summary,availability:E.availability,sourceRefs:E.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:he,omittedEvidenceCount:0,conflictsComplete:!Y}};return fe.budget.estimatedTokens=pa(fe),fe},J=_(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let A=x.pop(),N=o.relationships.filter(T=>Tt(T,"contradicts")&&(T.from.entityId===A.id||T.to.entityId===A.id)).flatMap(T=>[T.from.entityId,T.to.entityId]);x=x.filter(T=>!N.includes(T.id)),J=_(x,!0)}return J}var fa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function jt(o){return fa.test(o)}function ha(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 To(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){jt(n)||ce(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function dt(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ce(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function yt(o,e,n,t=!1){t&&n.level==="contributor"&&ce(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ce(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ga={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"])},ya=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);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}.entity.entityId`,e.entity.entityId),dt(o,`${n}.createdAt`,e.createdAt),yt(o,`${n}.authority`,e.authority);let t=ga[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(ya.has(s)&&(yt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ce(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let i=e.transitionContext;(i?.kind!=="proposal_deferral"||i.resurfaceWhen.length===0)&&ce(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),i?.resurfaceWhen.includes("after_date")&&!i.revisitAfter&&ce(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),i?.revisitAfter&&dt(o,`${n}.transitionContext.revisitAfter`,i.revisitAfter)}}function wa(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),dt(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ce(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ce(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ce(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ce(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(yt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ce(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&To(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ce(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(dt(o,`${n}.appliedAt`,e.appliedAt),yt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ce(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&ce(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ce(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&To(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&To(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ia(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),dt(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ce(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)&&((e.from.entityType!=="decision"||e.to.entityType!=="decision")&&ce(o,n,"invalid_normative_relationship","Normative relationships connect decisions to decisions."),e.authority?yt(o,`${n}.authority`,e.authority,!0):ce(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context.")),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ce(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&ce(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ce(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function vt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),dt(e,"manifest.createdAt",o.manifest.createdAt),dt(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,y)=>{let f=n.get(p);f?ce(e,y,"duplicate_id",`ID is already used at ${f}.`):n.set(p,y)};o.records.forEach((p,y)=>{let f=`records[${y}]`;t(p.id,f),wa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,y)=>{let f=`events[${y}]`;t(p.id,f),va(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let f=`relationships[${y}]`;t(p.id,f),Ia(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let f=`tombstones[${y}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),dt(e,`${f}.deletedAt`,p.deletedAt),yt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,y)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,y,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,y)=>i(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{i(p.from,`relationships[${y}].from`),i(p.to,`relationships[${y}].to`)});let d=new Set(o.artifacts.map(p=>p.id)),c=(p,y)=>{d.has(p)||ce(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,f)=>{!r.has(`${p}:${y}`)&&!s.has(`${p}:${y}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let f=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((v,x)=>l("subject",v,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((v,x)=>c(v,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((v,x)=>l("subject",v.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((v,x)=>c(v,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((v,x)=>i(v,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((v,x)=>l("thread",v,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((v,x)=>l("iteration",v,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((v,x)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((v,x)=>{v.subjectIds?.forEach((S,_)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${_}]`))}),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`));break;case"model_projection":yt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((v,x)=>l("model_entry",v,`${f}.entryIds[${x}]`)),p.coverage.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;default:break}});let h=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),w=new Map;o.events.forEach((p,y)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,v=w.get(f)??new Set;v.add(p.toState),w.set(f,v),v.size>1&&ce(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,y,f,v,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=b.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==y||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let _=Date.parse(f);(_<Date.parse(S.startsAt)||S.endsAt&&_>Date.parse(S.endsAt)||S.revokedAt&&_>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&v.length&&!v.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(y=>y.subjectId),`records:${p.id}.authority`);o.events.forEach((p,y)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),v=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,v,`events[${y}].authority`)}),o.relationships.forEach((p,y)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(v=>{let x=R.get(`${v.entityType}:${v.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${y}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let y=h.get(p.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==p.proposalId||y.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===p.id&&v.toState==="revoked"&&!!v.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return ha(e)}function Qt(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 Ar(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 ba(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 En(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),jt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of ba(e))jt(s)||n.push({code:"invalid_generated_id",message:`${s} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let s={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=Ar(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={...Qt(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."},d={...Qt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Ar(o,s,e,d.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,c],events:[i,d],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Qt(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={...Qt(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 xa}from"crypto";import{readFile as Sa,readdir as Pa,realpath as Ra}from"fs/promises";import{join as Xt,relative as ka}from"path";var Ta=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Et(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function ze(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Cr(...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=xa("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),d=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${d}${i.slice(4,7)}-${i.slice(7,19)}`}async function jo(o,e){try{return JSON.parse(await Sa(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function ja(o){let e=Et(o);if(!e)return 0;let n=0,t=r=>{let s=Et(r);if(!s){n+=1;return}for(let i of Object.values(s))t(i)};for(let r of Object.values(e))t(r);return n}function Ea(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Yt(o){let e=[],n=await Ra(o.projectRoot).catch(()=>o.projectRoot),t=Xt(n,".popmelt"),r=await jo(Xt(t,"threads.json"),e),s=await jo(Xt(t,"model.json"),e),i=Et(r),d=Et(i?.threads)??{},c=Object.entries(d).map(([E,Z])=>({key:E,value:Et(Z)})).filter(E=>!!E.value),l=Xt(t,"decisions"),h=await Pa(l).catch(()=>[]),R=[];for(let E of h.filter(Z=>Z.endsWith(".json")).sort()){let Z=Et(await jo(Xt(l,E),e));Z&&R.push({file:E,value:Z})}let w=c.flatMap(({value:E})=>[E.createdAt,E.updatedAt]).filter(E=>typeof E=="number"&&Number.isFinite(E)),b=w.length?Math.min(...w):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,b),y=ge(g,"participant","legacy-owner",b),f=ge(g,"participant","legacy-agent",b),v=ge(g,"subject","project",b),x=ze(Math.max(b,...w)),S=[],_=[],J=new Map,A=new Map,N=new Map(R.map(E=>[E.value.id??E.file.replace(/^d-|\.json$/g,""),E.value])),T=new Map,B=(E,Z,V,ke,Me)=>{let Ie=J.get(V);if(Ie)return Ie;let _e=ge(g,"artifact",E,ke);return _.push({id:_e,kind:Z,mediaType:Me,location:V,availability:"available"}),J.set(V,_e),_e};for(let{file:E,value:Z}of R){let V=Z.id??E.replace(/^d-|\.json$/g,""),ke=Z.createdAt??b,Me=[B(`${V}:envelope`,"other",`.popmelt/decisions/${E}`,ke,"application/json")];Z.screenshotPath&&Me.push(B(`${V}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ie,_e]of(Z.pastedImagePaths??[]).entries())Me.push(B(`${V}:image:${Ie}`,"image",_e,ke));T.set(V,Me)}let H=(E,Z,V)=>({id:E,schemaVersion:1,projectId:p,createdAt:x,participantId:Z,sourceRefs:V}),te=(E,Z)=>{S.push(Z);let V=A.get(E)??[];V.push(Z.id),A.set(E,V)},W=[{...H(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...H(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...W),S.push({...H(v,y,[]),recordType:"subject",subjectType:"project",label:ka(process.cwd(),n)||n,aliases:[],locators:[{id:ge(g,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:ze(b),sourceRefs:[]}]});let ne=new Map,oe=(E,Z)=>{let V=ne.get(E);if(V)return V;let ke=ge(g,"subject",E,Z),Me={...H(ke,y,[{kind:"external",id:E}]),createdAt:ze(Z),recordType:"subject",subjectType:"element",label:E,aliases:[],locators:[{id:ge(g,"locator",E,Z),kind:"dom_selector",value:E,status:"current",validFrom:ze(Z),sourceRefs:[{kind:"external",id:E}]}]};return S.push(Me),ne.set(E,ke),ke};for(let{key:E,value:Z}of c){let V=Z.id??E,ke=Z.createdAt??b,Me=ge(g,"thread",V,ke),Ie={kind:"thread",id:V},_e=[],Je=[],Bt=Array.isArray(Z.messages)?Z.messages:[],qe,rt,Lt=0;Bt.forEach((ve,st)=>{let Ae=ve.timestamp??ke,Ye=ge(g,"artifact",`${V}:message:${st}`,Ae);if(_e.push(Ye),_.push({id:Ye,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${V}/messages/${st}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${V}/messages/${st}`,Ye),ve.screenshotPath&&B(`${V}:message:${st}:screenshot`,"screenshot",ve.screenshotPath,Ae),ve.role==="human"){qe=ve;let Ne=ve.feedbackSummary??ve.replyToQuestion;if(Ne?.trim()){let Be=ge(g,"observation",`${V}:${st}`,Ae),ct=Z.elementIdentifiers??[],St={...H(Be,y,[Ie,{kind:"message",id:Ye}]),createdAt:ze(Ae),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:ct.map(mt=>oe(mt,ke)),artifactIds:[Ye]},resolvedByIds:[]};te(V,St),rt=Be,Je.push({entityType:"observation",entityId:Be})}return}if(ve.role!=="assistant")return;let it=ve.jobId??`${V}:${st}`,at=ge(g,"iteration",it,Ae),ut=N.get(it),Ft=ve.cancelled?"cancelled":ve.error?"failed":ve.question?"question_asked":(ve.resolutions?.length??0)>0?"completed":"no_change",ro={...H(at,f,[Ie,{kind:"message",id:Ye},...(T.get(it)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:ze(Ae),recordType:"iteration",threadIds:[Me],startedAt:ze(qe?.timestamp,Ae),completedAt:ze(Ae),requestSummary:Cr(qe?.feedbackSummary,qe?.replyToQuestion)??"[legacy request unavailable]",responseSummary:ve.question??ve.error??ve.responseText?.slice(0,1e3),outcome:Ft,execution:{provider:ve.provider??ut?.provider,model:ve.model??ut?.model,sessionId:ve.sessionId??ut?.sessionId},artifactIds:[Ye,...T.get(it)??[]]};te(V,ro),Je.push({entityType:"iteration",entityId:at});let zt=ve.resolutions??ut?.resolutions??[];for(let[Ne,Be]of zt.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let ct=Z.elementIdentifiers??[],St=(ct.length?ct:[n]).map(ln=>({subjectId:ln===n?v:oe(ln,ke),role:"governed"})),mt=ge(g,"proposal",`${it}:${Be.annotationId??"resolution"}:${Ne}`,Ae),so={...H(mt,f,[Ie,{kind:"iteration",id:at}]),createdAt:ze(Ae),recordType:"proposal",state:"pending",claim:Be.summary,subjects:St,subjectSemantics:St.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Cr(qe?.feedbackSummary,qe?.replyToQuestion,Be.summary),iterationId:at,inferredById:f}};te(V,so),Je.push({entityType:"proposal",entityId:mt}),e.push({severity:"warning",code:"acceptance_unresolved",source:V,message:`Proposal ${mt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(zt.some(Ne=>Ne.status==="resolved")||ut?.gitDiff){let Ne=ge(g,"implementation",it,Ae),Be={...H(Ne,f,[Ie,{kind:"iteration",id:at}]),createdAt:ze(Ae),recordType:"implementation_attempt",state:"completed",iterationIds:[at],coverageClaims:[],summary:zt.map(ct=>ct.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};te(V,Be),Je.push({entityType:"implementation_attempt",entityId:Ne}),Lt+=1}rt&&(rt=void 0)});let xt=Bt.at(-1),oo={...H(Me,y,[Ie]),createdAt:ze(ke),recordType:"thread",state:xt?.question?"open":"resolved",messageArtifactIds:_e,outcome:xt?.question?"question_unresolved":Lt?"implementation_only":"no_outcome",resultRefs:Je};S.push(oo),A.set(V,[Me,...A.get(V)??[]])}let he=ja(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(b),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:_,tombstones:[]},G=vt(Y),fe=(o.proofCaseIds??Ta).map(E=>({legacyId:E,threadFound:c.some(({key:Z,value:V})=>(V.id??Z)===E),decisionEnvelopeFound:N.has(E),recordIds:A.get(E)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:c.length,messages:c.reduce((E,Z)=>E+(Z.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:he,artifactsReferenced:_.length},imported:Ea(S),unresolvedAcceptance:e.filter(E=>E.code==="acceptance_unresolved").length,deferredModelEntries:he,proofCases:fe,issues:e,schemaIssues:G.issues}}}import{createHash as Ma}from"crypto";import{mkdir as $r,open as Eo,readFile as Mo,readdir as _a,rename as Aa,unlink as _o}from"fs/promises";import{join as tt}from"path";var Ca={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function _n(o){return Ma("sha256").update(JSON.stringify(o)).digest("hex")}function Or(o){return _n(o)}function Dr(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 Dr(structuredClone(o),e,n)}async function wt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Eo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
177
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Aa(n,o)}catch(r){throw await _o(n).catch(()=>{}),r}}async function Mn(o){return JSON.parse(await Mo(o,"utf8"))}var An=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=vt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await $r(this.journalDir,{recursive:!0});try{throw await Mo(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 Mo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}let t=_n(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},s={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await wt(this.checkpointPath,r),await wt(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 wt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=_n(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await wt(tt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await wt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!jt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,s={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},i={...s,hash:Or(s)},d=$a(t.bundle,e,n.committedAt),c=vt(d);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await wt(tt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await wt(this.manifestPath,t.manifest),{bundle:d,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({...Ca,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Mn(this.manifestPath),n=await Mn(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!==_n(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await _a(this.journalDir),r=t.filter(w=>w.endsWith(".tmp")),i=t.filter(w=>/^\d{12}-[0-9a-f-]+\.json$/i.test(w)).sort().filter(w=>Number(w.slice(0,12))>n.sequence),d=structuredClone(n.bundle),c=n.sequence,l=n.journalHash??null,h=new Set;for(let w of i){let b=await Mn(tt(this.journalDir,w)),{hash:g,...p}=b;if(g!==Or(p))throw new Error(`Journal hash mismatch: ${w}`);if(b.sequence!==c+1)throw new Error(`Journal sequence gap at ${w}`);if(b.previousHash!==l)throw new Error(`Journal chain mismatch at ${w}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${w}`);if(h.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);Dr(d,b.mutation,b.committedAt),c=b.sequence,l=b.hash,h.add(b.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=vt(d);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:d,manifest:e,transactionIds:h,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:c,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await $r(this.memoryDir,{recursive:!0});let n;try{n=await Eo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Mn(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 _o(this.lockPath),n=await Eo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await _o(this.lockPath).catch(()=>{})}}};import{randomBytes as Oa}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Oa(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 Da=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Jr(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(),d=new Date(e.completedAt).toISOString(),c=Da(),l=c.records,h=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));h||(h={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(h));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(_=>_.recordType==="subject"&&_.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)),R.push(S)}for(let x of[...new Set((e.filePaths??[]).filter(Boolean))]){let S=o.records.find(_=>_.recordType==="subject"&&_.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)),R.push(S)}let w=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),b;if(w.length>0){b=ge(r,"live-observation",s,e.createdAt);let x={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:w.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds:R.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},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[h.id],startedAt:i,completedAt:d,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let y=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),v=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(w.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of w.entries()){let _=ge(r,"live-proposal",`${s}:${x}`,e.completedAt),J=v.map(N=>({subjectId:N.id,role:"governed"})),A={id:_,schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,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(A),y.push(_)}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)),_={id:ge(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,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(A=>A.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(_)}return{mutation:c,iterationId:g,proposalIds:y,observationId:b}}import{createHash as Ja}from"crypto";import{mkdir as Na,open as Ba,readFile as La,rename as Fa,unlink as za}from"fs/promises";import{join as Nr}from"path";function Br(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Lr(o){return Ja("sha256").update(JSON.stringify(o)).digest("hex")}async function qa(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ba(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Fa(n,o)}catch(r){throw await za(n).catch(()=>{}),r}}function Ua(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(c,l,h)=>{let R=c[l]??=[];R.includes(h)||R.push(h)};for(let c of o.records)if(c.recordType==="subject"){let l=c;for(let h of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Br(h);R&&i(t,R,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)i(r,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)i(s,l.subjectId,c.id);let d={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...d,checksum:Lr(d)}}function Fr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Br(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var Cn=class{constructor(e){this.indexDir=Nr(e,".popmelt","memory","indexes"),this.indexPath=Nr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await La(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===Lr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ua(e,n);return await Na(this.indexDir,{recursive:!0}),await qa(this.indexPath,t),t}};var $n=class{constructor(e){this.projectRoot=e;this.store=new An(e),this.indexStore=new Cn(e),this.manifestPath=lt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Mt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Yt({...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 Yt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"legacy-evals-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(s.runs)?s.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await Ao(e,{recursive:!0}),await Co(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:r.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:r.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"imprint-evidence-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Ao(e,{recursive:!0}),await Co(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 d of i){let c=d.kind==="confirmation"?"confirm":d.kind==="correction"||d.kind==="rejection"?"reason_wrong":d.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:d.id,kind:c?"strengthened":"added",title:s.statement.slice(0,120),detail:d.summary,changes:[{explanationId:s.id,action:c==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:d.threadId,jobId:d.jobId,action:c,occurredAt:d.createdAt}),r+=1}}return await Ao(e,{recursive:!0}),await Co(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:Ro(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:_r(t.bundle,r),reviewSelection:Ro(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:En(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 Yt({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=En(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(w=>w.recordType==="proposal"&&w.id===e.proposalId),r=n.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.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(),d={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},c=e.action==="accept"?{...d,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...d,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"?{...d,action:"reject",eventId:le(s),reason:e.reason}:{...d,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(w=>w.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=En(n.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(w=>w.message).join(" ")};let h=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(h);let R=l.plan.resultRefs.find(w=>w.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:h.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=Jr(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(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active"),r=n.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="ai"&&w.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!s||!i)return;let d=e.occurredAt??new Date().toISOString(),c=Date.parse(d),l=[],h=[];for(let w of e.summary.changes){let b={kind:"external",id:w.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(y=>y.recordType==="observation"&&y.sourceRefs.some(f=>f.kind==="external"&&f.id===w.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:w.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{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),h.push({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ge(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,c);try{let w=await this.store.commit({records:l,events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:d});await this.refreshIndex(w)}catch(w){if(!(w instanceof Error)||!w.message.includes("Transaction already exists"))throw w}}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(d=>d.status==="projected").map(d=>d.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,d)=>d.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(d=>d.recordType==="decision"&&d.state==="active"?[d.id]:[])),t=new Map;for(let d of e.records.filter(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))d.decisionIds.some(c=>n.has(c))&&t.set(d.key,d);let r=[...t.values()],s=e.records.filter(d=>d.recordType==="verification_attempt");return{decisions:e.records.filter(d=>d.recordType==="decision"&&d.state==="active").map(d=>{let c=s.filter(l=>l.targets.some(h=>h.entityType==="decision"&&h.entityId===d.id)).sort((l,h)=>h.createdAt.localeCompare(l.createdAt))[0];return{id:d.id,kind:d.kind,claim:d.claim,projected:r.some(l=>l.decisionIds.includes(d.id)),verification:c?c.state:"unverified"}}),entries:r.map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.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(d=>d.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(),d=le(s),c=le(s),l=le(s),h=le(s),R=le(s),w=new Set(n.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),b=n.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&w.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"}],y={...g,id:d,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:c,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:d},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...g,id:l,recordType:"decision",proposalId:d,acceptanceEventId:c,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:h,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${s}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:i,decisionIds:[l],entryIds:[h],coverage:[{decisionId:l,status:"projected"}]},_={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=b.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}.`})),A=b.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[y,v,x,S],events:[f,...J],relationships:[_,...A],artifacts:[],tombstones:[],projectionUpdates:b.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:h}}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(y=>y.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):[]))],c={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(c))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 h=Date.now(),R=new Date(h).toISOString(),w={id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...c,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},b=r?[{id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:w.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:w.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[w],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(h),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(i=>i.objectType==="eval_spec").map(i=>i.objectId)),t=e.records.filter(i=>i.recordType==="eval_spec").reverse().filter((i,d,c)=>c.findIndex(l=>l.legacyId===i.legacyId)===d).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 d=r.filter(h=>h.evalSpecId===i.id).sort((h,R)=>R.createdAt.localeCompare(h.createdAt))[0],c=d&&s.some(h=>h.target.entityType==="verification_attempt"&&h.target.entityId===d.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":d?c?"stale":d.state==="passed"?"passing":d.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:d?.scopeFingerprint,verificationAttemptId:d?.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(d=>({assertion:d,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(w=>w.recordType==="verification_attempt"&&w.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(w=>w.recordType==="participant"&&w.status==="active"&&w.kind==="ai")??t.bundle.records.find(w=>w.recordType==="participant"&&w.status==="active");if(!s)return;let i=n.completedAt,d=new Date(i).toISOString(),c={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,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:d,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:[c.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}},h=r.targets.map(w=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:c.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:w,reason:n.summary})),R=await this.store.commit({records:[c,l],events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),d={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},c=await this.store.commit({records:[d],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(c)}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(c=>c.recordType==="decision"&&c.state==="active"?[c.id,...c.sourceRefs.map(l=>l.id)]:[])),r=e.filter(c=>(c.dependencies?.length??0)>0||c.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(c=>!r.includes(c)).map(c=>c.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(c=>c.recordType==="participant"&&c.kind==="human"&&c.status==="active");if(!i)return{valid:r,discardedIds:s};let d=s.flatMap(c=>{let l=this.latestEvalSpec(n.bundle,c);return l?[l]:[]}).filter(c=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===c.id));if(d.length>0){let c=Date.now(),l=new Date(c).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:d.map(h=>({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:h.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(c),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(),d=new Date(i).toISOString(),c=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(v=>e.decisionIds.includes(v)),y=p?.length?p:e.decisionIds,f=[...new Set(r.filter(v=>y.includes(v.id)).flatMap(v=>v.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:y.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:y,value:g.value}}),h=new Set(l.flatMap(g=>g.decisionIds)),R={id:c,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,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:d,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:h.has(g)?"projected":"unprojected"})},w=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...l,R],events:[],relationships:w,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});return await this.refreshIndex(b),{projectionId:c,entryIds:l.map(g=>g.id),headSequence:b.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 Yt({...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=Fr(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 _t(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function $o(o){let e=At(o),n=At(e.authority),t=n.level,r=n.mode,s=_t(t,"authority.level",["owner","delegate","contributor"]),i=_t(r,"authority.mode",["local_trusted","hosted"]),d={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{...d,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...d,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let c=At(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...d,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>_t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...d,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:_t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=At(c);return{subjectId:Se(l.subjectId,"subjectId"),role:_t(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Oo(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(d=>Se(d,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 On(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
179
+ `)}async function zr(o,e,n,t){let r=On(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(c=>[c.decisionId,c.state])),d=new Map(s.actionPacket.verification.map(c=>[c.target.entityId,c.state]));return{source:s.source,...s.actionPacket.decisions.length>0?{acceptedTruth:{decisions:s.actionPacket.decisions.map(c=>({...c,implementation:i.get(c.id)??"unknown",verification:d.get(c.id)??"unverified"})),conflicts:s.actionPacket.conflicts,truncated:s.actionPacket.completeness.status==="truncated"}}:{},packets:s.reviewSelection.packets.map(c=>({packetId:c.packetId,proposalId:c.proposal.id,claim:c.proposal.claim,proposedKind:c.proposal.proposedKind,authority:c.authority,presentation:c.presentation,subjectLabels:c.trigger.subjectMatches.map(l=>l.label),evidenceCount:c.evidence.sourceCount,expansionRefs:c.expansionRefs})),truncated:s.reviewSelection.completeness.status==="truncated",estimatedTokens:s.actionPacket.budget.estimatedTokens+s.reviewSelection.completeness.estimatedTokens}}catch(s){t?.(s);return}}function qr(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 Ur(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(d=>typeof d=="string"&&s.has(d)):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 Hr(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 Dn(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 Ha(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),d,c,l,h,R,w,b,g,p,y,f,v,x,S,_=[],J=[],A=0,N=[];for(;A<r.length;){let T=r.indexOf(s,A);if(T===-1)break;let B=T+s.length;if(r.slice(T,T+i.length).equals(i))break;let H=B;r[H]===13&&r[H+1]===10&&(H+=2);let te=r.indexOf(`\r
374
181
  \r
375
- `,N);if($===-1)break;let T=o.slice(N,$).toString("utf-8"),F=$+4,_=o.indexOf(i,F),ee=_!==-1?_-2:o.length;A.push({headers:T,body:o.slice(F,ee)}),O=_!==-1?_:o.length}for(let k of A){let E=k.headers.match(/name="([^"]+)"/);if(!E)continue;let N=E[1];if(N==="screenshot")l=k.body;else if(N==="feedback")f=k.body.toString("utf-8");else if(N==="color")y=k.body.toString("utf-8");else if(N==="provider")v=k.body.toString("utf-8");else if(N==="model")M=k.body.toString("utf-8");else if(N==="reasoningEffort")B=k.body.toString("utf-8");else if(N==="serviceTier")J=k.body.toString("utf-8");else if(N==="goal")U=k.body.toString("utf-8");else if(N==="pageUrl")W=k.body.toString("utf-8");else if(N==="viewport")S=k.body.toString("utf-8");else if(N==="planId")q=k.body.toString("utf-8");else if(N==="manifest")V=k.body.toString("utf-8");else if(N==="tasks")Q=k.body.toString("utf-8");else if(N==="sourceId")K=k.body.toString("utf-8");else if(N.startsWith("screenshot-")){let $=N.slice(11);try{let T=decodeURIComponent($);Z.push({pathname:T,data:k.body})}catch{}}else if(N.startsWith("image-")){let $=N.split("-"),T=parseInt($[$.length-1],10),F=$.slice(1,-1).join("-");F&&!isNaN(T)&&z.push({annotationId:F,index:T,data:k.body})}}if(!l)throw new Error("Missing screenshot field");return f||(f=""),{screenshot:l,feedback:f,color:y,provider:v,model:M,reasoningEffort:B,serviceTier:J,goal:U,pageUrl:W,viewport:S,planId:q,manifest:V,tasks:Q,sourceId:K,pastedImages:z,pageScreenshots:Z}}function qo(s){return new Promise((e,n)=>{let t=[];s.on("data",o=>t.push(o)),s.on("end",()=>e(Buffer.concat(t))),s.on("error",n)})}function ze(s,e){let n=[];if(s.annotations.length>0){n.push("## Annotations");for(let t of s.annotations){let o=t.elements.map(l=>{let f=[l.selector];return l.reactComponent&&f.push(`(${l.reactComponent})`),f.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${o||"none"}`);let a=e?.[t.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`)}}if(s.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of s.styleModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${o}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(s.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of s.textModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=JSON.stringify(t.original),a=JSON.stringify(t.modified),l=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${o}${l}: ${i} \u2192 ${a}`)}}if(s.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of s.domModifications){let o=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",a=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${o}${i} \u2192 ${t.targetParentSelector}${a}`)}}if(s.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of s.spacingTokenChanges){n.push(`
376
- ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let o of t.affectedElements){let i=o.reactComponent?` (${o.reactComponent})`:"";o.matchedClass&&o.suggestedClass?n.push(`- ${o.selector}${i}: \`${o.matchedClass}\` \u2192 \`${o.suggestedClass}\``):n.push(`- ${o.selector}${i}: ${o.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${o.className}"`)}}}if(s.inspectedElement){let t=s.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let o=[t.selector];t.reactComponent&&o.push(`(${t.reactComponent})`),t.context&&o.push(`in ${t.context}`),t.textContent&&o.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${o.join(" ")}`)}return n.join(`
377
- `)}function $n(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 y=f.finalScope??f.inferredScope,v=y?` [${y.breadth} ${y.target}]`:"";t.push(`- ${f.annotationId}: ${f.status}${v} \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 v=new Map;for(let M of a)if(typeof M=="object"&&M!==null&&"text"in M){let B=M,J=B.scope||"general";v.has(J)||v.set(J,[]),v.get(J).push(B.text)}for(let[M,B]of v){t.push(`**${M.charAt(0).toUpperCase()+M.slice(1)}**`);for(let J of B)t.push(`- ${J}`)}}else for(let v of a)typeof v=="string"&&t.push(`- ${v}`);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 y=f.pathname||new URL(e.url).pathname;l.has(y)||l.set(y,[]),l.get(y).push(f)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[f,y]of l){t.push(""),t.push(`## Page: ${f}`);let v=a[f];v&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&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 M={...e,annotations:y,styleModifications:e.styleModifications},B=ze(M,n?.imagePaths);B&&(t.push(""),t.push(B))}}else{let a=ze(e,n?.imagePaths);a&&(t.push(""),t.push(a))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
378
- `)}function _n(s){return s.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ot(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 Qo(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 Xo(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&&!Qo(e[n]))return!1;return!0}function On(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(Xo):[]}catch{return[]}}function Dn(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 Yo}from"child_process";import{readdir as Vo,readFile as Ko,stat as Zo}from"fs/promises";import{homedir as Be}from"os";import{join as Se}from"path";var ct=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Nn()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Nn()}],Le=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],je={id:"",label:"Default",source:"cli"},er=/^\s*-\s+"([^"]+)"/;function tr(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(er);if(!o?.[1])continue;let i=o[1];e.push({id:i,label:Dt(i),source:"cli"})}return dt([je,...e])}function nr(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():Dt(o),a=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(f=>{if(!f||typeof f!="object")return[];let y=f;return typeof y.effort!="string"?[]:[{effort:y.effort,...typeof y.description=="string"?{description:y.description}:{}}]}):void 0,l=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(f=>{if(!f||typeof f!="object")return[];let y=f;return typeof y.id!="string"?[]:[{id:y.id,label:typeof y.name=="string"?y.name:y.id,...typeof y.description=="string"?{description:y.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 Nn(){return["low","medium","high","xhigh","max"].map(s=>({effort:s}))}function sr(s){let e=s.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return dt(e.map(n=>({id:n,label:Dt(n),source:"cli"})))}function Dt(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":ar(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 Jn(s="copilot"){let e=await lt(s,["help","config"]),n=tr(e);return n.length>1?n:[je]}async function zn(s="codex"){let e=await lt(s,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Se(Be(),".codex");return Ln(Se(t,"models_cache.json"))}),n=nr(e);return n.length>0?dt([...n,...Le]):Le}async function Bn(s="claude"){let e=Se(Be(),".claude"),n=[Se(Be(),".claude","stats-cache.json"),Se(Be(),".claude","settings.json"),Se(Be(),".claude.json"),Se(e,"cache","changelog.md")],[t,o,i]=await Promise.all([lt(s,["--help"]).catch(()=>""),lt(s,["--version"]).catch(()=>""),or(e).catch(()=>[])]),a=ir([...n,...i]),l=await Promise.all(a.map(y=>Ln(y).catch(()=>""))),f=sr([t,o,...l].join(`
381
- `));return dt([...ct,...f])}function lt(s,e,n=5e3){return new Promise((t,o)=>{Yo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function Ln(s){return Ko(s,"utf-8")}async function or(s){let e=[Se(s,"projects"),Se(s,"telemetry")],n=[];for(let t of e)await jn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function jn(s,e,n){if(n<0)return;let t;try{t=await Vo(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=Se(s,o.name);if(o.isDirectory()){await jn(i,e,n-1);return}if(!(!o.isFile()||!rr(o.name)))try{let a=await Zo(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function rr(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function dt(s){let e=new Set,n=[];for(let t of s)e.has(t.id)||(e.add(t.id),n.push(t));return n}function ir(s){return[...new Set(s)]}function ar(s){return s.charAt(0).toUpperCase()+s.slice(1)}var ut=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,o=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),o}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let o=this.bufferEvent(n,e);for(let i of this.listeners)i(o,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let o={...n,seq:t.nextSeq++};return t.events.push(o),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),o}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let a=n<0?t.events:t.events.filter(l=>l.seq>n);return{jobId:e,events:a,currentSeq:t.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(e,n,t){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(o=>{let i=!1,a=()=>{i||(i=!0,o())};t.on("exit",a),t.on("error",a),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(a,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="materialize_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{mkdir as lr,readFile as cr,writeFile as dr}from"fs/promises";import{dirname as ur,join as pr}from"path";var fr={version:1,threads:{}},pt=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=pr(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await cr(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={...fr,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 lr(ur(this.filePath),{recursive:!0}),await dr(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function ft(s){return mr(s).slice(0,12)}var hr=[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 mr(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):gr(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let B=7;B>=0;B--)e.push(n/Math.pow(2,B*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,l=1359893119,f=2600822924,y=528734635,v=1541459225,M=new Array(64);for(let B=0;B<e.length;B+=64){for(let z=0;z<16;z++){let Z=B+z*4;M[z]=(e[Z]<<24|e[Z+1]<<16|e[Z+2]<<8|e[Z+3])>>>0}for(let z=16;z<64;z++){let Z=be(M[z-15],7)^be(M[z-15],18)^M[z-15]>>>3,O=be(M[z-2],17)^be(M[z-2],19)^M[z-2]>>>10;M[z]=M[z-16]+Z+M[z-7]+O>>>0}let J=t,U=o,W=i,S=a,q=l,V=f,Q=y,K=v;for(let z=0;z<64;z++){let Z=be(q,6)^be(q,11)^be(q,25),O=q&V^~q&Q,A=K+Z+O+hr[z]+M[z]>>>0,k=be(J,2)^be(J,13)^be(J,22),E=J&U^J&W^U&W,N=k+E>>>0;K=Q,Q=V,V=q,q=S+A>>>0,S=W,W=U,U=J,J=A+N>>>0}t=t+J>>>0,o=o+U>>>0,i=i+W>>>0,a=a+S>>>0,l=l+q>>>0,f=f+V>>>0,y=y+Q>>>0,v=v+K>>>0}return[t,o,i,a,l,f,y,v].map(B=>B.toString(16).padStart(8,"0")).join("")}function be(s,e){return s>>>e|s<<32-e}function gr(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 Fn={name:"@popmelt.com/core",version:"0.8.4",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var ht=Fn.version;var Mr=1111,Tr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Ar=1800*1e3,Cr=3600*1e3,Hn=45e3,$r=5e3,_r=1e4;function Gn(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 Yn(s){if(!s)return!1;try{let e=new URL(s);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Or(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,y=e[e.length-1];y&&y.kind==="tool_group"&&y.tool===t?y.items.push({label:l,detail:f}):e.push({kind:"tool_group",tool:t,items:[{label:l,detail:f}]})}return e}function Dr(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 Nr(s,e=96){let n=s.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function qn(s){let e=s.styleModifications.flatMap(a=>{let l=a.element?.reactComponent||a.element?.tagName||a.selector;return a.changes.map(f=>`${l}: ${f.property} ${f.original||"unset"} -> ${f.modified||"unset"}`)}),n=(s.spacingTokenChanges??[]).map(a=>`${a.tokenName}: ${a.originalPx}px -> ${a.newPx}px`),t=(s.textModifications??[]).map(a=>`${a.element?.reactComponent||a.element?.tagName||a.selector}: text ${a.original||"empty"} -> ${a.modified||"empty"}`),o=s.annotations.map(a=>{let l=a.instruction?.trim();if(l)return l;if(a.imageCount&&a.imageCount>0)return`${a.imageCount} image${a.imageCount===1?"":"s"}`;let f=a.elements?.[0]?.reactComponent||a.elements?.[0]?.selector||a.linkedSelector||a.type;return`${a.type==="annotation"?"Annotation":`${a.type} annotation`} on ${f}`}),i=[...e,...t,...n,...o].map(a=>Nr(a)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Jr(s,e){let n=s.headers.origin;Yn(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function m(s,e,n){s.writeHead(e,{"Content-Type":"application/json"}),s.end(JSON.stringify(n))}async function zr(s){let e=[],n=0;for await(let o of s){let i=typeof o=="string"?Buffer.from(o):o;if(n+=i.length,n>16384)throw new Error("Request body too large");e.push(i)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Br(s,e){let n=s.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function Lr(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 gt(s,e){try{s.res.write(`event: ${e.type}
182
+ `,H);if(te===-1)break;let W=r.slice(H,te).toString("utf-8"),ne=te+4,oe=r.indexOf(s,ne),he=oe!==-1?oe-2:r.length;N.push({headers:W,body:r.slice(ne,he)}),A=oe!==-1?oe:r.length}for(let T of N){let B=T.headers.match(/name="([^"]+)"/);if(!B)continue;let H=B[1];if(H==="screenshot")d=T.body;else if(H==="feedback")c=T.body.toString("utf-8");else if(H==="color")l=T.body.toString("utf-8");else if(H==="provider")h=T.body.toString("utf-8");else if(H==="model")R=T.body.toString("utf-8");else if(H==="reasoningEffort")w=T.body.toString("utf-8");else if(H==="serviceTier")b=T.body.toString("utf-8");else if(H==="goal")g=T.body.toString("utf-8");else if(H==="pageUrl")p=T.body.toString("utf-8");else if(H==="viewport")y=T.body.toString("utf-8");else if(H==="planId")f=T.body.toString("utf-8");else if(H==="manifest")v=T.body.toString("utf-8");else if(H==="tasks")x=T.body.toString("utf-8");else if(H==="sourceId")S=T.body.toString("utf-8");else if(H.startsWith("screenshot-")){let te=H.slice(11);try{let W=decodeURIComponent(te);J.push({pathname:W,data:T.body})}catch{}}else if(H.startsWith("image-")){let te=H.split("-"),W=parseInt(te[te.length-1],10),ne=te.slice(1,-1).join("-");ne&&!isNaN(W)&&_.push({annotationId:ne,index:W,data:T.body})}}if(!d)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:d,feedback:c,color:l,provider:h,model:R,reasoningEffort:w,serviceTier:b,goal:g,pageUrl:p,viewport:y,planId:f,manifest:v,tasks:x,sourceId:S,pastedImages:_,pageScreenshots:J}}function Ha(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 Wa}from"crypto";var Ga=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,Va=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Ka=new Set(["strengthened","weakened","mixed","unknown"]);function Zt(o,e=180){if(typeof o!="string")return;let n=o.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function Qa(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Wr(o,e,n,t=Date.now()){let r=Qa(o);if(!r)return null;let s=typeof r.transition=="string"&&Va.has(r.transition)?r.transition:null,i=Zt(r.focus);if(!s||!i)return null;let d=typeof r.evidencePosture=="string"&&Ka.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Wa(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Zt(r.seeking),workingHypothesis:Zt(r.workingHypothesis),evidencePosture:d,update:Zt(r.update),nextObservation:Zt(r.nextObservation)},contextPolicy:"exclude"}}function Do(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Xa(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(Ga,(d,c)=>{try{let l=Wr(JSON.parse(c),e,s);if(!l)return"";let h=Do(l);if(r.has(h))return"";r.add(h),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
183
+
184
+ `).trim(),orientations:t}}function Ya(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 Jn=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 d=Ya(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";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 d=Wr(JSON.parse(i),this.jobId,this.sequence);if(!d)continue;let c=Do(d);if(this.signatures.has(c))continue;this.signatures.add(c),t.push(d),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=Xa(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=Do(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Gr=`## 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 en(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(d=>{let c=[d.selector];return d.reactComponent&&c.push(`(${d.reactComponent})`),c.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 d of i)n.push(` Attached image: use the Read tool to view ${d}`)}}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),d=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${d}: ${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 Vr(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 d of n.threadHistory)if(d.role==="human")i++,d.replyToQuestion?(t.push(`### Round ${i} (human) \u2014 reply`),t.push(`"${d.replyToQuestion}"`)):(t.push(`### Round ${i} (human)`),d.feedbackSummary&&t.push(`Annotations: ${d.feedbackSummary}`),d.annotationIds&&d.annotationIds.length>0&&t.push(`Annotation IDs: ${d.annotationIds.join(", ")}`));else if(d.question)t.push(`### Round ${i} (assistant) \u2014 question`),t.push(`"${d.question}"`);else{if(t.push(`### Round ${i} (assistant)`),d.responseText&&t.push(`Response: ${d.responseText}`),d.resolutions&&d.resolutions.length>0)for(let c of d.resolutions){let l=c.finalScope??c.inferredScope,h=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${c.annotationId}: ${c.status}${h} \u2014 ${c.summary}`),c.filesModified&&c.filesModified.length>0&&t.push(` Files: ${c.filesModified.join(", ")}`)}d.toolsUsed&&d.toolsUsed.length>0&&t.push(`Tools used: ${d.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 h=new Map;for(let R of i)if(typeof R=="object"&&R!==null&&"text"in R){let w=R,b=w.scope||"general";h.has(b)||h.set(b,[]),h.get(b).push(w.text)}for(let[R,w]of h){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let b of w)t.push(`- ${b}`)}}else for(let h of i)typeof h=="string"&&t.push(`- ${h}`);let d=n.designModel.tokens;d&&typeof d=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```"));let c=n.designModel.components;c&&typeof c=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(c,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??{},d=new Map;for(let c of e.annotations){let l=c.pathname||new URL(e.url).pathname;d.has(l)||d.set(l,[]),d.get(l).push(c)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,l]of d){t.push(""),t.push(`## Page: ${c}`);let h=i[c];h&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${h}`):!h&&n?.provider!=="codex"&&(Object.keys(i).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:l,styleModifications:e.styleModifications},w=en(R,n?.imagePaths);w&&(t.push(""),t.push(w))}}else{let i=en(e,n?.imagePaths);i&&(t.push(""),t.push(i))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
194
+ `)}function Kr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Qr(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 d of e)d.role==="human"?(i++,d.replyToQuestion?(r.push(`### Round ${i} (human) \u2014 reply`),r.push(`"${d.replyToQuestion}"`)):(r.push(`### Round ${i} (human)`),d.feedbackSummary&&r.push(`Annotations: ${d.feedbackSummary}`))):d.question?(r.push(`### Round ${i} (assistant) \u2014 question`),r.push(`"${d.question}"`)):(r.push(`### Round ${i} (assistant)`),d.responseText&&r.push(`Response: ${d.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 Za(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 ec(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&&!Za(e[n]))return!1;return!0}function Xr(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(ec):[]}catch{return[]}}function Yr(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 tc}from"child_process";import{readdir as nc,readFile as oc,stat as rc}from"fs/promises";import{homedir as tn}from"os";import{join as Qe}from"path";var Bn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Zr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Zr()}],nn=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],on={id:"",label:"Default",source:"cli"},sc=/^\s*-\s+"([^"]+)"/;function ic(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(sc);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:Jo(s),source:"cli"})}return Ln([on,...e])}function ac(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():Jo(r),i=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,d=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;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}:{},...d&&d.length>0?{speedTiers:d}:{}}]})}function Zr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function cc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ln(e.map(n=>({id:n,label:Jo(n),source:"cli"})))}function Jo(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":uc(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 es(o="copilot"){let e=await Nn(o,["help","config"]),n=ic(e);return n.length>1?n:[on]}async function ts(o="codex"){let e=await Nn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(tn(),".codex");return os(Qe(t,"models_cache.json"))}),n=ac(e);return n.length>0?Ln([...n,...nn]):nn}async function ns(o="claude"){let e=Qe(tn(),".claude"),n=[Qe(tn(),".claude","stats-cache.json"),Qe(tn(),".claude","settings.json"),Qe(tn(),".claude.json"),Qe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Nn(o,["--help"]).catch(()=>""),Nn(o,["--version"]).catch(()=>""),dc(e).catch(()=>[])]),i=pc([...n,...s]),d=await Promise.all(i.map(l=>os(l).catch(()=>""))),c=cc([t,r,...d].join(`
197
+ `));return Ln([...Bn,...c])}function Nn(o,e,n=5e3){return new Promise((t,r)=>{tc(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function os(o){return oc(o,"utf-8")}async function dc(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await rs(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function rs(o,e,n){if(n<0)return;let t;try{t=await nc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Qe(o,r.name);if(r.isDirectory()){await rs(s,e,n-1);return}if(!(!r.isFile()||!lc(r.name)))try{let i=await rc(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function lc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Ln(o){let e=new Set,n=[];for(let t of o)e.has(t.id)||(e.add(t.id),n.push(t));return n}function pc(o){return[...new Set(o)]}function uc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Fn=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(d=>d.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 We}from"crypto";import{createHash as mc}from"crypto";import{mkdir as fc,open as hc,readFile as ss,readdir as gc,rename as yc,unlink as vc}from"fs/promises";import{dirname as wc,join as Ct}from"path";function Oe(o){return structuredClone(o)}function is(o){return mc("sha256").update(JSON.stringify(o)).digest("hex")}async function rn(o,e){await fc(wc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await hc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
198
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await yc(n,o)}catch(r){throw await vc(n).catch(()=>{}),r}}function Ic(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function bc(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 zn(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")bc(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 xc(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(d=>d.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=zn(t,[r])}return n}function as(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 $t=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ct(e,".popmelt","imprint"),this.manifestPath=Ct(this.imprintDir,"manifest.json"),this.graphPath=Ct(this.imprintDir,"graph.json"),this.journalDir=Ct(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ss(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 gc(this.journalDir).catch(d=>{if(d.code==="ENOENT")return[];throw d})).filter(d=>/^\d{12}-.+\.json$/.test(d)).sort(),r=Ic(this.projectId,e.createdAt),s=[],i=null;for(let d=0;d<t.length;d++){let c=JSON.parse(await ss(Ct(this.journalDir,t[d]),"utf8")),{hash:l,...h}=c;if(c.sequence!==d+1||c.previousHash!==i||l!==is(h))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);r=zn(r,c.mutations),r.updatedAt=c.committedAt,r.head={sequence:c.sequence,hash:c.hash},s.push(c),i=c.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=xc(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}:{}},d={...i,hash:is(i)},c=zn(t.graph,d.mutations);c.updatedAt=e.committedAt,c.head={sequence:r,hash:d.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await rn(Ct(this.journalDir,l),d);let h={version:1,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await rn(this.graphPath,c),await rn(this.manifestPath,h),n={graph:c,transaction:d}}),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 d=new Set(i.mutations.flatMap(as));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(h=>as(h).some(R=>d.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await rn(this.graphPath,e.graph),await rn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Sc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Pc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Rc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function qn(o){return new Set(Rc(o).split(" ").filter(e=>e.length>2&&!Pc.has(e)))}function Un(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 No(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:We(),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 cs(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 Hn(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 w=String(r.reason);if(!Sc.has(w))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:w},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 d={kind:i,title:je(s?.title,120),detail:je(s?.detail,500)};if(!d.title||!d.detail)throw new Error("summary title and detail are required");let c=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(w=>typeof w=="string"&&!!w.trim()):[],l=[];for(let w of Array.isArray(r.mutations)?r.mutations:[]){if(!w||typeof w!="object")continue;let b=w;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let g=je(b.statement),p=je(b.rationale);if(!g||!p)continue;l.push({op:"add",clientId:je(b.clientId,100)||void 0,kind:b.kind,statement:g,rationale:p,scope:cs(b.scope)})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let g={op:"revise",explanationId:b.explanationId,statement:je(b.statement)||void 0,rationale:je(b.rationale)||void 0,scope:cs(b.scope),reopenGrounding:b.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let g=je(b.summary);g&&l.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:g})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type)))l.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:je(b.rationale)});else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let g=je(b.reason);g&&l.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:g})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let g=je(b.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:g,rationale:je(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&l.push({op:"retire",explanationId:b.explanationId,reason:je(b.reason)})}let h=r.grounding,R=h&&typeof h.explanationId=="string"&&je(h.question)?{explanationId:h.explanationId,question:je(h.question,300)}:void 0;return{draft:{decision:"mutate",summary:d,appliedExplanationIds:c,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Wn(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 Ot=class{constructor(e,n){this.noopCounts=new Map;this.store=new $t(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=qn(e.text??""),t=qn((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(c=>c.state!=="retired"&&c.state!=="challenged").map(c=>{let l=qn([c.statement,c.rationale].join(" ")),h=qn(c.scope.values.join(" ")),R=Un(l,n),w=Un(h,n),b=Un(h,t),g=Un(l,t),p=R+w*.2+b*.25+g*.1+(c.state==="grounded"?.08:0)+(r.has(c.id)?1:0),y=r.has(c.id)||(n.size?R>=.12||w>=.5:b>=.2||g>=.2);return{item:c,score:p,relevant:y}}).filter(c=>c.relevant&&c.score>=.18).sort((c,l)=>l.score-c.score||l.item.updatedAt.localeCompare(c.item.updatedAt)),d=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,d).map(({item:c})=>{let l=new Set(s.relations.filter(h=>h.fromId===c.id&&h.type==="instantiates").map(h=>h.toId));return{id:c.id,kind:c.kind,statement:c.statement,rationale:c.rationale,scope:c.scope,state:c.state,concrete:s.concrete.filter(h=>l.has(h.id)).map(h=>({id:h.id,modelPath:h.modelPath,value:h.value}))}}),truncated:i.length>d,...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,d=new Map,c=[],l=new Set,h=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let _=We();S.clientId&&i.set(S.clientId,_);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,A={id:_,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:No(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[nt(n,"supports",e.summary.detail)]};s.set(_,A),l.add(_),c.push({op:"add_explanation",explanation:A})}let R=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let _=R(S.explanationId),J=s.get(_);if(J?.state!=="grounded")continue;let A=We(),N={id:A,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?No(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[nt(n,"supports",e.summary.detail)]};s.set(A,N),d.set(_,A),l.add(A),c.push({op:"add_explanation",explanation:N}),c.push({op:"add_relation",relation:{id:We(),type:"refines",fromId:A,toId:_,rationale:S.rationale??e.summary.detail,createdAt:t}})}let w=S=>{let _=R(S);return d.get(_)??_};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=w(S.explanationId);if(!s.has(J))continue;let A=kc(n.concreteModel,S.modelPath);if(!A.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(A.value));N||(N={id:We(),modelPath:S.modelPath,value:structuredClone(A.value),createdAt:t,updatedAt:t},c.push({op:"add_concrete",concrete:N})),c.push({op:"add_relation",relation:{id:We(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=w(S.fromId),A=w(S.toId);if(!s.has(J)||!s.has(A)||J===A)continue;c.push({op:"add_relation",relation:{id:We(),type:S.type,fromId:J,toId:A,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(A);continue}if(S.op==="supersede"){let J=w(S.explanationId),A=w(S.replacementId);if(!s.has(J)||!s.has(A)||J===A)continue;c.push({op:"add_evidence",explanationId:J,evidence:nt(n,"challenges",S.reason)}),c.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:A},updatedAt:t}),c.push({op:"add_relation",relation:{id:We(),type:"contradicts",fromId:A,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(A);continue}let _=w(S.explanationId);if(s.has(_))if(l.add(_),S.op==="revise"){if(d.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:No(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};c.push({op:"revise_explanation",explanationId:_,patch:J,updatedAt:t})}else S.op==="evidence"?(c.push({op:"add_evidence",explanationId:_,evidence:nt(n,S.stance,S.summary)}),S.stance==="challenges"&&c.push({op:"revise_explanation",explanationId:_,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(c.push({op:"add_evidence",explanationId:_,evidence:nt(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),c.push({op:"revise_explanation",explanationId:_,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let _=w(S),J=s.get(_);!J||J.state==="grounded"||J.state==="retired"||h.has(_)&&!l.has(_)||(l.has(_)||(l.add(_),c.push({op:"add_evidence",explanationId:_,evidence:{...nt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&c.push({op:"revise_explanation",explanationId:_,patch:{state:"testing"},updatedAt:t}))}if(!c.length)return;let b=We(),g=await this.store.commit({transactionId:b,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:c}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),y=[...l].flatMap(S=>{let _=p.get(S);if(!_)return[];let J=!r.graph.explanations.some(N=>N.id===S),A=_.state==="challenged"||_.state==="retired";return[{explanationId:S,action:J?"added":A?"challenged":"revised",statement:_.statement,state:_.state}]}),f=e.grounding?w(e.grounding.explanationId):void 0,v=f?p.get(f):void 0,x=v?.state==="testing"&&!h.has(v.id)?{explanationId:v.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:b,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:y,...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 h of l)await this.store.undo(h,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,We());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},d=[],c="";if(e.action==="confirm")d.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),c=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")d.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"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),c=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(h=>h.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");d.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),c=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")d.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),c=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");d.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),c=`Edited: ${l}`}if(!d.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:We(),committedAt:n,source:i,summary:c,mutations:d})}};function sn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Gn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Bo(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 ds(o){let e=Bo(Gn(o.origin));if(e)return e;let n=Bo(Gn(o.referer));if(n)return n;let t=Gn(o["x-forwarded-host"]);if(!t)return null;let r=Gn(o["x-forwarded-proto"])==="https"?"https":"http";return Bo(`${r}://${t}`)}function ls(o,e,n=5){let t=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(c=>c.status==="applied"||c.status==="failed").sort(t).slice(0,n),i=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),d=i.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:d,actionableProposals:i}}import{createHash as Vn}from"crypto";import{mkdir as an,readFile as It,unlink as Ec,writeFile as Jt}from"fs/promises";import{dirname as Kn,extname as Mc,join as De}from"path";var Tc={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 jc(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 ps(o,e){let n=e??jc(o);return{kind:n,...Tc[n]}}function Dt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function us(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 _c={version:1,threads:{}},ms=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],cn={version:2,updatedAt:0,files:{}};function Ac(o){return JSON.stringify(o,null,2)}function Cc(o){return Object.fromEntries(ms.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function $c(o){let e={...o};for(let n of ms)delete e[n];return e}function Nt(o){let e=o;if(o.error){let n=ps(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=Dt(e.result,!1),t=Dt(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 Qn=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 It(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 It(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(Nt)}]))},this.index={...cn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={..._c,threads:{}},this.index={...cn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Nt(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,Nt(n)):r.messages.push(Nt(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(d=>d.jobId===n);if(i.length===0)return!1;for(let d of i)if(Object.assign(d,t),d.error){let c=Nt(d);Object.assign(d,c),delete d.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(d=>d.role==="assistant"&&d.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(y=>y.role==="human")?.feedbackSummary||"[thread]",d=r.messages.filter(y=>y.role==="assistant"),c=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let f=y.imprintSummary?.grounding;if(f?.question&&!y.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(y=>!!c(y)),h=r.messages.findLastIndex(y=>y.role==="human"),R=l>h?c(r.messages[l]):void 0,w=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,h)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),g=d.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=d.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:w,pendingQuestion:R,acknowledgedJobIds:b,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 It(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 d=await It(De(Kn(this.legacyFilePath),r.path),"utf8");Vn("sha256").update(d).digest("hex")===r.sha256&&(i=JSON.parse(d))}catch{}return Nt({...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=Cc(e),t=$c(e);if(Object.keys(n).length===0)return t;let r=Ac(n),s=Vn("sha256").update(r).digest("hex"),i=De("artifacts","thread-messages",`${s}.json`);await an(this.artifactsDir,{recursive:!0});try{await It(De(Kn(this.legacyFilePath),i),"utf8")}catch{await Jt(De(Kn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Kn(t)===this.mediaDir)return t;try{let r=await It(t),s=Vn("sha256").update(r).digest("hex"),i=De(this.mediaDir,`${s}${Mc(t)||".bin"}`);await an(this.mediaDir,{recursive:!0});try{await It(i)}catch{await Jt(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await an(this.threadsDir,{recursive:!0});let n=this.index??{...cn,files:{}},t=n.files[e.id]??`${Vn("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 Jt(De(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Jt(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await an(this.threadsDir,{recursive:!0}),this.index=this.index??{...cn,files:{}},await Jt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...cn,files:{}},t=n.files[e];t&&await Ec(De(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await an(this.threadsDir,{recursive:!0}),await Jt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};function Xn(o){return Dc(o).slice(0,12)}var Oc=[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 Dc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Jc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let w=7;w>=0;w--)e.push(n/Math.pow(2,w*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,d=1359893119,c=2600822924,l=528734635,h=1541459225,R=new Array(64);for(let w=0;w<e.length;w+=64){for(let _=0;_<16;_++){let J=w+_*4;R[_]=(e[J]<<24|e[J+1]<<16|e[J+2]<<8|e[J+3])>>>0}for(let _=16;_<64;_++){let J=Xe(R[_-15],7)^Xe(R[_-15],18)^R[_-15]>>>3,A=Xe(R[_-2],17)^Xe(R[_-2],19)^R[_-2]>>>10;R[_]=R[_-16]+J+R[_-7]+A>>>0}let b=t,g=r,p=s,y=i,f=d,v=c,x=l,S=h;for(let _=0;_<64;_++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),A=f&v^~f&x,N=S+J+A+Oc[_]+R[_]>>>0,T=Xe(b,2)^Xe(b,13)^Xe(b,22),B=b&g^b&p^g&p,H=T+B>>>0;S=x,x=v,v=f,f=y+N>>>0,y=p,p=g,g=b,b=N+H>>>0}t=t+b>>>0,r=r+g>>>0,s=s+p>>>0,i=i+y>>>0,d=d+f>>>0,c=c+v>>>0,l=l+x>>>0,h=h+S>>>0}return[t,r,s,i,d,c,l,h].map(w=>w.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Jc(o){let e=[];for(let n=0;n<o.length;n++){let t=o.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var fs={name:"@popmelt.com/core",version:"0.8.5",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var ot=fs.version;var Vc=1111,Kc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Qc=1800*1e3,Xc=3600*1e3,ys=45e3,Yc=5e3,Zc=1e4;function vs(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
201
+ `)}function Zn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function ed(o,e){if(e.size===1)return[...o].reverse().find(n=>{let t=n.imprintSummary;return n.role==="assistant"&&!!t?.grounding&&!t?.resolvedAction&&e.has(t.grounding.explanationId)})}function Rs(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function td(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,d=s?s.split("/").pop()??s:void 0,c;switch(r){case"Read":c=d?`Reading ${d}`:"Reading file";break;case"Edit":c=d?`Editing ${d}`:"Editing file";break;case"Write":c=d?`Writing ${d}`:"Writing file";break;case"Bash":c=i?i.split(`
202
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=r?`Using ${r}`:"tool";break}let l=s??i??void 0,h=s?Fo(s)?s:Ps(e,s):void 0,R=n[n.length-1];R&&R.kind==="tool_group"&&R.tool===r?R.items.push({label:c,detail:l,...h?{filePath:h}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:c,detail:l,...h?{filePath:h}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function nd(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 od(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function ws(o){let e=o.styleModifications.flatMap(i=>{let d=i.element?.reactComponent||i.element?.tagName||i.selector;return i.changes.map(c=>`${d}: ${c.property} ${c.original||"unset"} -> ${c.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 d=i.instruction?.trim();if(d)return d;if(i.imageCount&&i.imageCount>0)return`${i.imageCount} image${i.imageCount===1?"":"s"}`;let c=i.elements?.[0]?.reactComponent||i.elements?.[0]?.selector||i.linkedSelector||i.type;return`${i.type==="annotation"?"Annotation":`${i.type} annotation`} on ${c}`}),s=[...e,...t,...n,...r].map(i=>od(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function rd(o,e){let n=o.headers.origin;Rs(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function M(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function 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 sd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function id(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 eo(o,e){try{o.res.write(`event: ${e.type}
385
204
  data: ${JSON.stringify(e)}
386
205
 
387
- `)}catch{}}function Ue(s){return s==="claude"||s==="codex"||s==="copilot"?s:void 0}async function vt(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 jr(s,e){return new Promise((n,t)=>{let o=a=>{s.removeListener("listening",i),t(a)},i=()=>{s.removeListener("error",o),n()};s.once("error",o),s.once("listening",i),s.listen(e,"127.0.0.1")})}function Qn(s){try{let e=yt("git",["rev-parse","HEAD"],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=yt("git",["status","--porcelain","--untracked-files=all",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),o=yt("git",["diff","HEAD",...n],{cwd:s,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return vr("sha256").update(`${e}
206
+ `)}catch{}}function bt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function no(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 ad(o,e){return new Promise((n,t)=>{let r=i=>{o.removeListener("listening",s),t(i)},s=()=>{o.removeListener("error",r),n()};o.once("error",r),o.once("listening",s),o.listen(e,"127.0.0.1")})}function Is(o){try{let e=to("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=to("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=to("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Ss("sha256").update(`${e}
388
207
  ${t}
389
- ${o}`).digest("hex").slice(0,16)}catch{return}}async function Vn(s={}){let e=s.port??Mr,n=s.projectRoot??process.cwd(),t=await br(n).catch(()=>n),o=ft(t),i=s.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),a=s.tempDir??ye(kr(),"popmelt-bridge"),l=s.maxTurns??40,f=s.maxBudgetUsd??1,y=[...s.allowedTools??Tr],v=s.claudePath??"claude",M=s.copilotPath??"copilot",B=s.provider??"claude",J=s.timeoutMs,U=s.restartMode??"embedded",W=e,S={},q={claude:v,codex:"codex",copilot:M};for(let[r,c]of Object.entries(q))try{let u=c.includes("/")?c:yt("which",[c],{encoding:"utf-8"}).trim();S[r]={available:!0,path:u}}catch{S[r]={available:!1,path:null}}function V(r,c){return new Promise(u=>{let p=Un(c,["--version"],{stdio:["ignore","ignore","ignore"]}),h=!1,d=g=>{h||(h=!0,u(g))},P=setTimeout(()=>{p.kill("SIGTERM"),d(!0)},5e3);p.on("error",()=>{clearTimeout(P),d(!1)}),p.on("close",g=>{clearTimeout(P),d(g===0)})})}await Promise.all([(async()=>{S.claude&&(S.claude.models=S.claude.available&&S.claude.path?await Bn(S.claude.path).catch(()=>ct):ct)})(),(async()=>{S.codex&&(S.codex.models=S.codex.available&&S.codex.path?await zn(S.codex.path).catch(()=>Le):Le)})(),(async()=>{S.copilot&&(S.copilot.models=S.copilot.available&&S.copilot.path?await Jn(S.copilot.path).catch(()=>[je]):[je])})()]);let[Q,K,z]=await Promise.all([Tt(t),At(t),Ct(t,S.copilot?.path??M)]),Z=await Pn(t);S.claude&&(S.claude.mcp=Q),S.codex&&(S.codex.mcp=K),S.copilot&&(S.copilot.mcp=z),Q.found&&Q.name&&y.push(`mcp__${Q.name}__*`),await wr(a,{recursive:!0}),Xn(a).catch(()=>{});let O=new ut(1),A=new st,k=new it(Hn),E=null,N=0,$=!1,T=()=>{N+=1,$=!1,E&&clearTimeout(E),E=null},F=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},_=()=>{if(U!=="detached"||k.size>0||$)return;$=!0;let r=++N,c=Date.now()+_r,u=()=>{if(r!==N)return;if(k.size>0){T();return}if(!(O.isRunning||O.depth>0||A.isRunning||A.depth>0)||Date.now()>=c){$=!1,E=setTimeout(F,50),E.unref?.();return}E=setTimeout(u,250),E.unref?.()};u()},ee=new Set,w=new pt(t),le=new Ve(t),ie=new Ke(t),G=new tt(t,le,{claudePath:v,provider:B,timeoutMs:J,onEvent:r=>{for(let c of ee)gt(c,r)}}),es=20,ts=300*1e3,ve=[];function We(){let r=Date.now()-ts;for(;ve.length>0&&(ve[0].completedAt<r||ve.length>es);)ve.shift()}let we=new Map,He=null,Jt;O.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&gt(p,r)}),A.addListener((r,c,u)=>{for(let p of ee)(!u||!p.sourceId||p.sourceId===u)&&gt(p,r)}),A.setProcessor(async r=>{let c=r.provider??B;try{let u=await G.run({provider:c,model:r.model,threadId:r.threadId,agentSettings:r.agentSettings});if(r.status==="cancelled")return;let p=await G.loadRuns(),h=u.runId?p.runs.find(P=>P.id===u.runId):void 0,d=Dr(u,h);if(r.threadId&&(await w.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})||await w.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:d,model:r.model,provider:c})),u.success)r.status="done",r.result=d,A.broadcast({type:"done",jobId:r.id,success:!0,responseText:d,threadId:r.threadId},r.id,r.sourceId),ve.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We();else{if(r.status="error",r.error=u.error??"Materialization failed",r.threadId){let P=`Model materialization failed.
208
+ ${r}`).digest("hex").slice(0,16)}catch{return}}function cd(o,e){let n=o;for(let t of e.split(".").filter(Boolean)){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[t]}return n}async function bs(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let s of[...t].sort((i,d)=>`${i.kind}:${i.value}`.localeCompare(`${d.kind}:${d.value}`)))if(s.kind==="model_path")r.push([s.kind,s.value,cd(n,s.value)]);else if(s.kind==="source_file"){let i=Ps(o,s.value),c=i===o||i.startsWith(`${o}/`)?await Lo(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,c])}else r.push([s.kind,s.value]);return Ss("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function ks(o={}){let e=new Date().toISOString(),n=o.port??Vc,t=o.projectRoot??process.cwd(),r=await Fc(t).catch(()=>t),s=Xn(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=o.tempDir??Ee(Hc(),"popmelt-bridge"),c=o.maxTurns??40,l=o.maxBudgetUsd??1,h=[...o.allowedTools??Kc],R=o.claudePath??"claude",w=o.copilotPath??"copilot",b=o.provider??"claude",g=o.timeoutMs,p=o.restartMode??"embedded",y=n,f={},v={claude:R,codex:"codex",copilot:w};for(let[a,u]of Object.entries(v))try{let k=u.includes("/")?u:to("which",[u],{encoding:"utf-8"}).trim();f[a]={available:!0,path:k}}catch{f[a]={available:!1,path:null}}function x(a,u){return new Promise(k=>{let m=hs(u,["--version"],{stdio:["ignore","ignore","ignore"]}),P=!1,I=$=>{P||(P=!0,k($))},j=setTimeout(()=>{m.kill("SIGTERM"),I(!0)},5e3);m.on("error",()=>{clearTimeout(j),I(!1)}),m.on("close",$=>{clearTimeout(j),I($===0)})})}await Promise.all([(async()=>{f.claude&&(f.claude.models=f.claude.available&&f.claude.path?await ns(f.claude.path).catch(()=>Bn):Bn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await ts(f.codex.path).catch(()=>nn):nn)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await es(f.copilot.path).catch(()=>[on]):[on])})()]);let[S,_,J]=await Promise.all([wo(r),Io(r),bo(r,f.copilot?.path??w)]),A=await Ir(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=_),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&h.push(`mcp__${S.name}__*`),await Bc(d,{recursive:!0}),xs(d).catch(()=>{});let N=new Fn(1),T=new Sn,B=new kn(ys),H=null,te=0,W=!1,ne=()=>{te+=1,W=!1,H&&clearTimeout(H),H=null},oe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},he=()=>{if(p!=="detached"||B.size>0||W)return;W=!0;let a=++te,u=Date.now()+Zc,k=()=>{if(a!==te)return;if(B.size>0){ne();return}if(!(N.isRunning||N.depth>0||T.isRunning||T.depth>0)||Date.now()>=u){W=!1,H=setTimeout(oe,50),H.unref?.();return}H=setTimeout(k,250),H.unref?.()};k()},Y=new Set,G=new Qn(r),q=new $n(r),fe=new Ot(r,s),E=new gn(r),Z=new wn(r),V=new xn(r,{claudePath:R,provider:b,timeoutMs:g,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let u of Y)eo(u,a)}});q.beginAutomaticInitialization({writerVersion:ot}).then(async a=>{a.state==="ready"?(await q.migrateLegacyEvals(),await q.migrateImprintSnapshot(),await V.applyCanonicalEntries(await q.getCanonicalModelEntries()),b!=="copilot"&&(await V.getUnprojectedPatternDecisions()).length>0&&await Ft({provider:b,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let ke=20,Me=300*1e3,Ie=[];function _e(){let a=Date.now()-Me;for(;Ie.length>0&&(Ie[0].completedAt<a||Ie.length>ke);)Ie.shift()}let Je=new Map;async function Bt(a){if(a.status!=="applied")return[];let u={version:1,updatedAt:Date.now(),cases:await q.getJournalEvalCases()},k=cr(a,u);if(k.length===0)return[];let m=await q.getEvalDependenciesForDecisions(a.decisionIds),P=a.threadId?await G.getThread(a.threadId):null,I=[...new Set((P?.messages??[]).flatMap(D=>(D.editEvents??[]).flatMap(F=>F.filePath?[F.filePath]:[])).map(D=>Fo(D)?gs(r,D):D))].map(D=>({kind:"source_file",value:D})),j=k.map(D=>{let F=[...new Map([...D.dependencies??[],...m,...I].map(U=>[`${U.kind}:${U.value}:${"subjectId"in U?U.subjectId??"":""}`,U])).values()],L=F.filter(U=>U.kind==="route"),C=F.flatMap(U=>U.kind==="model_path"&&U.value.startsWith("components.")?[U.value.slice(11).split(".")[0]]:[]),O=[...new Set(F.flatMap(U=>"subjectId"in U&&U.subjectId?[U.subjectId]:[]))],Q=L.length>0?L.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:F,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(F=>F.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",k=po(a.claim)||"The product satisfies the declared model constraint.",m={id:`eval-decision-${a.decisionId}`,title:u.charAt(0).toUpperCase()+u.slice(1),status:"pending",category:a.modelPath.startsWith("components.")?"component":a.modelPath.startsWith("tokens.")?"visual":"workflow",prompt:"Verify this product expectation across the declared scenarios.",assertions:[k],rationale:`Protects the ${a.modelPath} constraint from implementation drift.`,sourceDecisionIds:[a.decisionId],sourceThreadIds:[],dependencies:[{kind:"model_path",value:a.modelPath}],scenarios:[{id:a.modelPath.startsWith("components.")?`component-${u.replace(/\s+/g,"-")}`:"current-page",components:a.modelPath.startsWith("components.")?[{name:a.modelPath.slice(11).split(".")[0]}]:void 0}]};return await q.syncEvalSpecs([m]),m.id}let rt=null,Lt;N.addListener((a,u,k)=>{for(let m of Y)(!k||!m.sourceId||m.sourceId===k)&&eo(m,a)}),T.addListener((a,u,k)=>{for(let m of Y)(!k||!m.sourceId||m.sourceId===k)&&eo(m,a)}),T.setProcessor(async a=>{let u=a.provider??b;try{let k=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(),P=k.runId?m.runs.find(j=>j.id===k.runId):void 0;if(k.success&&k.proposalId){let j=await V.findModelProposal(k.proposalId),$=await V.loadModel(),D=j?hr(j,$):null;if(j&&D){let F=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:F});let L=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");L&&await Bt(L)}}let I=nd(k,P);if(a.threadId&&(await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:I,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:I,model:a.model,provider:u})),k.success)a.status="done",a.result=I,T.broadcast({type:"done",jobId:a.id,success:!0,responseText:I,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"}),_e();else{if(a.status="error",a.error=k.error??"Projection failed",a.threadId){let j=`Model projection failed.
390
209
 
391
- ${r.error}`;await w.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})||await w.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:P,error:r.error,model:r.model,provider:c})}A.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We()}}catch(u){if(r.status==="cancelled")return;if(r.status="error",r.error=u instanceof Error?u.message:String(u),r.threadId){let p=`Model materialization failed.
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"}),_e()}}catch(k){if(a.status==="cancelled")return;if(a.status="error",a.error=k instanceof Error?k.message:String(k),a.threadId){let m=`Model projection failed.
392
211
 
393
- ${r.error}`;await w.updateMessage(r.threadId,r.id,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})||await w.appendMessage(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:p,error:r.error,model:r.model,provider:c})}A.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,provider:c,model:r.model},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:r.error,threadId:r.threadId,annotationIds:r.annotationIds,color:"#000000",kind:"materialize_model"}),We()}}),O.setProcessor(async r=>{let c=r,u=c._replyPrompt,p=c._replyText,h=c._replyImagePaths,d=r.provider??B;r.threadId&&p!==void 0&&await w.updateMessage(r.threadId,r.id,{queued:!1});let P;if(r.threadId){let D=await w.getThread(r.threadId);if(D){for(let H=D.messages.length-1;H>=0;H--)if(D.messages[H].sessionId){P=D.messages[H].sessionId;break}}}let g;if(P&&u){if(g=p??u,h&&h.length>0){g+=`
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"}),_e()}}),N.setProcessor(async a=>{let u=a,k=u._replyPrompt,m=u._replyText,P=u._replyImagePaths,I=a.provider??b,j=!!(a.surfacedProposalIds?.length&&k),$=!!u._evalRemediation,D=!j&&!["run_eval","synthesize_evals","synthesize","project_model"].includes(a.kind??"");a.threadId&&m!==void 0&&await G.updateMessage(a.threadId,a.id,{queued:!1});let F;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){F=de.messages[pe].sessionId;break}}}(j||$)&&(F=void 0);let L;if(F&&k){if(L=m??k,P&&P.length>0){L+=`
394
213
 
395
- The developer attached reference images with their reply:`;for(let D of h)g+=`
396
- Attached image: use the Read tool to view the image at: ${D}`}r.kind==="synthesize"||r.kind==="synthesize_evals"||r.kind==="run_eval"?g+=`
214
+ The developer attached reference images with their reply:`;for(let de of P)L+=`
215
+ Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?L+=`
397
216
 
398
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:g+=`
217
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:L+=`
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)g=ze(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(F)L=en(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.`+(I!=="codex"?`
405
224
 
406
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let D=!u&&r.threadId?await w.getThreadHistory(r.threadId):void 0,H=u?null:await G.loadModel();g=u??$n(r.screenshotPath,r.feedback,{threadHistory:D&&D.length>0?D:void 0,provider:d,imagePaths:r.imagePaths,designModel:H??void 0,screenshotPaths:r.screenshotPaths})}let x=Lr(r.color,`[\u22B9 ${W}:${r.id}]`),I=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${x} Reviewing ${I} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${P?` (resuming: ${P.slice(0,8)})`:""}`);let C=(D,H)=>{D.type==="delta"&&"text"in D?O.accumulateText(H,"response",D.text):D.type==="thinking"&&"text"in D&&O.accumulateText(H,"thinking",D.text),O.broadcast(D,H,r.sourceId)},{process:te,result:X}=d==="codex"?Ye(r.id,{prompt:g,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:P,model:r.model,configOverrides:qe(r.agentSettings),onEvent:C}):d==="copilot"?tn(r.id,{prompt:g,projectRoot:t,resumeSessionId:P,model:r.model,timeoutMs:J,copilotPath:S.copilot?.path??M,onEvent:C}):Qe(r.id,{prompt:g,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:y,claudePath:v,resumeSessionId:P,model:r.model,reasoningEffort:r.agentSettings?.reasoningEffort,timeoutMs:J,onEvent:C});O.setActiveProcess(r.id,te);let b=await X;if(r.result=b.text,b.success){console.log(`${x} Iteration complete`),b.fileEdits&&b.fileEdits.length>0&&console.log(`${x} Captured ${b.fileEdits.length} file edit(s): ${b.fileEdits.map(L=>`${L.tool} ${L.file_path}`).join(", ")}`),b.editEvents&&b.editEvents.length>0&&console.log(`${x} Captured ${b.editEvents.length} edit event(s): ${b.editEvents.map(L=>`${L.operation} ${L.filePath}`).join(", ")}`),r.status="done";let D=_n(b.text),H=On(b.text),se=H.some(L=>(L.finalScope??L.inferredScope)?.breadth==="pattern");if(H.length>0&&r.annotationIds&&r.annotationIds.length>0){let L=new Set(r.annotationIds);H.every(ne=>L.has(ne.annotationId))||(H=H.map((ne,fe)=>({...ne,annotationId:r.annotationIds[fe%r.annotationIds.length]})))}let ce=b.fileEdits&&b.fileEdits.length>0?b.fileEdits.map(L=>`${L.tool} ${L.file_path.split("/").pop()}`):b.toolsUsed,ue=O.getBufferedEvents(r.id),pe=ue?Or(ue.events):void 0;if(r.threadId&&await w.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:b.text,resolutions:H.length>0?H:void 0,question:D??void 0,sessionId:b.sessionId,toolsUsed:ce,editEvents:b.editEvents&&b.editEvents.length>0?b.editEvents:void 0,segments:pe&&pe.length>0?pe:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&le.captureGitDiff(t).then(async L=>{let oe=Date.now(),ne=r.imagePaths?Object.values(r.imagePaths).flat():[],fe=[];if(r.imagePaths)for(let[j,R]of Object.entries(r.imagePaths))for(let Y=0;Y<R.length;Y++)fe.push(`screenshots/p-${r.id}-${j}-${Y}.webp`);await le.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:oe,durationMs:oe-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:fe,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:b.sessionId,threadId:r.threadId,responseText:b.text,resolutions:H.length>0?H:[],question:D??void 0,fileEdits:b.fileEdits??[],editEvents:b.editEvents??[],toolsUsed:ce,gitDiff:L},r.screenshotPath,ne),se&&d!=="copilot"?await zt({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(`${x} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&b.text){let L=nt(b.text);if(L){Array.isArray(L.rules)&&(L.rules=Ne(L.rules));let oe=await G.loadModel();oe&&(!L.tokens&&oe.tokens&&(L.tokens=oe.tokens),!L.components&&oe.components&&(L.components=oe.components)),await G.writeModel(L),console.log(`${x} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&b.text){let L=an(b.text),oe=ln(b.text),ne=L??oe;if(ne&&ne.length>0){let fe=await ie.writeSynthesized(ne),j=r._proposalId;j&&await G.attachGeneratedEvals(j,ne.map(R=>R.id)),console.log(`${x} Eval synthesis: wrote ${ne.length} ${L?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${fe.cases.length} total)`)}}else if(r.kind==="run_eval"&&b.text&&r.evalId&&r.evalRunId){let L=await ie.findCase(r.evalId),oe=r._evalRunScope;if(L&&oe){let ne=cn(b.text,L.assertions),fe=Date.now();await ie.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:fe,durationMs:fe-r.createdAt,scope:oe,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:Qn(t),rawResponse:b.text,...ne}),console.log(`${x} Eval run: ${L.title} \u2192 ${ne.status}`)}}D&&(console.log(`${x} \u{1F4AC} Question detected: "${D.slice(0,120)}" \u2192 broadcasting to ${ee.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),O.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:D,annotationIds:r.annotationIds},r.id,r.sourceId));let de=Dn(b.text);de.length>0&&(console.log(`${x} Novel pattern(s): ${de.map(L=>`${L.category}/${L.element}`).join(", ")}`),O.broadcast({type:"novel_patterns",jobId:r.id,patterns:de,threadId:r.threadId},r.id,r.sourceId)),O.broadcast({type:"done",jobId:r.id,success:!0,resolutions:H.length>0?H:void 0,responseText:b.text,threadId:r.threadId},r.id,r.sourceId),ve.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${x} Error: ${b.error}`),r.status="error",r.error=b.error,r.threadId&&await w.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:b.error||"Unknown error",model:r.model,provider:d}),O.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:b.error||"Unknown error",provider:d,model:r.model,recoverable:b.recoverableError,code:b.errorCode},r.id,r.sourceId),ve.push({id:r.id,status:"error",completedAt:Date.now(),error:b.error,threadId:r.threadId,annotationIds:r.annotationIds});We()});let wt=Ir(async(r,c)=>{if(Jr(r,c),r.method==="OPTIONS"){c.writeHead(204),c.end();return}let u=r.url||"/",p=u.split("?")[0],h=new URL(u,`http://127.0.0.1:${W}`),d=h.pathname,P=Br(r,h);if(P&&P!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:mt(t)});return}if(r.headers.origin){if(!Yn(r.headers.origin)){m(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(P!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:P,projectName:mt(t)});return}}try{if(r.method==="POST"&&d==="/send")await ns(r,c);else if(r.method==="GET"&&d==="/events")os(r,c);else if(r.method==="GET"&&d==="/status")await rs(c,P);else if(r.method==="PATCH"&&d==="/config")await is(r,c);else if(r.method==="POST"&&d==="/leases"){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}try{let g=await zr(r),x=typeof g.leaseId=="string"?g.leaseId.trim():"",I=typeof g.ownerPid=="number"&&Number.isInteger(g.ownerPid)&&g.ownerPid>0?g.ownerPid:void 0;if(!x||x.length>128){m(c,400,{error:"A valid leaseId is required."});return}T();let C=k.acquire(x,I);m(c,201,{ok:!0,lease:C,ttlMs:Hn})}catch{m(c,400,{error:"Invalid lease request."})}}else if(d.startsWith("/leases/")&&(r.method==="PATCH"||r.method==="DELETE")){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}let g="";try{g=decodeURIComponent(d.slice(8))}catch{m(c,400,{error:"Invalid lease id."});return}if(!g){m(c,400,{error:"A lease id is required."});return}if(r.method==="PATCH"){let x=k.heartbeat(g);if(!x){m(c,404,{error:"Lease not found."});return}m(c,200,{ok:!0,lease:x})}else{let x=k.release(g);m(c,x.found?200:404,{ok:x.found}),x.becameEmpty&&_()}}else if(r.method==="POST"&&d==="/shutdown"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0}),setTimeout(F,100)}else if(r.method==="POST"&&d==="/restart"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let g of ee)try{g.res.end()}catch{}wt.close(()=>{Un(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(r.method==="GET"&&d==="/capabilities")m(c,200,{providers:S});else if(r.method==="POST"&&d==="/mcp/install")await vs(r,c);else if(r.method==="POST"&&d==="/reply")await ss(r,c);else if(r.method==="POST"&&d==="/cancel")as(r,c);else if(r.method==="POST"&&d==="/materialize")await ls(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let g=await G.loadRuns();m(c,200,g)}else if(r.method==="GET"&&d==="/model/proposals"){let g=await G.loadModelProposals();m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let g=d.slice(17,-15);await ds(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let g=d.slice(17,-6);await cs(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let g=d.slice(17,-8);await us(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let g=d.slice(17,-14);await ps(g,r,c)}else if(r.method==="POST"&&d==="/model/component")await ws(r,c);else if(r.method==="DELETE"&&d==="/model/component")await Ss(r,c);else if(r.method==="PATCH"&&d==="/model/token")await bs(r,c);else if(r.method==="DELETE"&&d==="/model/token")await xs(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:g,model:x,agentSettings:I}=await Ee(r);if(g==="copilot"){m(c,400,{error:"Model consolidation is not available for Copilot yet."});return}G.consolidate({provider:g,model:x,agentSettings:I}).catch(C=>console.error("[Bridge] Consolidation error:",C)),m(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await fs(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await hs(r,c);else if(r.method==="GET"&&d==="/evals"){let g=await ie.loadSuiteWithCurrentRuns(Qn(t));m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let g=d.slice(7,-4);await ms(g,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await gs(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let g=await G.loadModel();m(c,200,{model:g})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let g=d.slice(6,d.length-7),x=parseInt(h.searchParams.get("afterSeq")??"-1",10),I=O.getBufferedEvents(g,isNaN(x)?-1:x);I?m(c,200,I):m(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await Es(p.slice(7),c);else if(r.method==="GET"&&d==="/threads/recent"){let g=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),x=await w.listRecent(g);m(c,200,x)}else if(r.method==="GET"&&d.startsWith("/thread/")){let g=d.slice(8);await Rs(g,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let g=d.slice(8);await Ms(g,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?Ps(r,c):r.method==="GET"&&d==="/canvas/manifest"?await Is(c):r.method==="GET"&&d==="/canvas/app.mjs"?await ks(c):m(c,404,{error:"Not found"})}catch(g){console.error("[Bridge] Request error:",g),m(c,500,{error:g instanceof Error?g.message:"Internal error"})}});async function ns(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:P,reasoningEffort:g,serviceTier:x,sourceId:I,pastedImages:C,pageScreenshots:te}=await at(r),X;try{X=JSON.parse(p)}catch{m(c,400,{error:"Invalid feedback JSON"});return}let b=Pe().slice(0,8),D={};if(te.length>0)for(let R of te){let Y=encodeURIComponent(R.pathname),re=ye(a,`screenshot-${b}-${Y}.webp`);await Fe(re,R.data),D[R.pathname]=re}let H=ye(a,`screenshot-${b}.webp`);await Fe(H,u);let se={};if(C.length>0)for(let R of C){let Y=ye(a,`pasted-${b}-${R.annotationId}-${R.index}.webp`);await Fe(Y,R.data),se[R.annotationId]||(se[R.annotationId]=[]),se[R.annotationId].push(Y)}let ce=X.annotations.map(R=>R.linkedSelector?R.pathname?`${R.pathname}:${R.linkedSelector}`:R.linkedSelector:null).filter(R=>!!R),ue;if(ce.length>0){let R=await w.findContinuationThread(ce);R?(ue=R.id,await w.addElementIdentifiers(ue,ce)):ue=(await w.createThread(b,ce)).id}else ue=(await w.createThread(b,[])).id;let pe=X.annotations.map(R=>R.id),de=Object.keys(D).length>0,L={id:b,status:"queued",screenshotPath:H,feedback:X,createdAt:Date.now(),color:h,threadId:ue,annotationIds:pe,provider:Ue(d),model:P||void 0,agentSettings:Re({reasoningEffort:g,serviceTier:x}),...Object.keys(se).length>0?{imagePaths:se}:{},sourceId:I||void 0,...de?{screenshotPaths:D}:{}},oe=new Set(X.annotations.map(R=>R.pathname).filter(Boolean)),ne;if(oe.size>1){let R=new Map;for(let Y of X.annotations){let re=Y.pathname||"(unknown)";R.has(re)||R.set(re,[]),R.get(re).push(Y.instruction||qn({...X,annotations:[Y]}))}ne=[...R.entries()].map(([Y,re])=>`\`${Y}\`
407
- ${re.map(St=>`- ${St}`).join(`
225
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!k&&a.threadId?await G.getThreadHistory(a.threadId):void 0,pe=k?null:await V.loadModel();L=k??Vr(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:I,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}L+=qr(a.memoryReview),D&&(L+=Wn(a.imprintContext)),L+=`
226
+
227
+ ${Gr}`;let C=id(a.color,`[\u22B9 ${y}:${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: ${I})${a.threadId?` (thread: ${a.threadId})`:""}${F?` (resuming: ${F.slice(0,8)})`:""}`);let Q=new Jn(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}=I==="codex"?hn(a.id,{prompt:L,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:F,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:un(a.agentSettings),onEvent:U}):I==="copilot"?sr(a.id,{prompt:L,projectRoot:r,resumeSessionId:F,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??w,onEvent:U}):mn(a.id,{prompt:L,projectRoot:r,maxTurns:c,maxBudgetUsd:l,allowedTools:j?["Read"]:h,claudePath:R,resumeSessionId:F,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?Hn(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=Kr(ye),pe=Xr(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?td($e.events,r):void 0,Pe,ee=Hr(ye),me=Ur(ye);if(me)if(!(a.memoryReview?.packets.some(se=>se.proposalId===me.proposalId)||a.surfacedProposalIds?.includes(me.proposalId)))Pe={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{Pe=await q.commitConversationalReview(me)}catch(se){Pe={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,ft=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:ft}),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?ed(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 qt=us({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:qt},result:qt,memoryReviewCard:ee??void 0,memoryReceipt:Pe,imprintSummary:xe,model:a.model,provider:I})}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??(On(a.feedback)||"[request unavailable]"),responseSummary:de??we,outcome:de?"question_asked":pe.some(se=>se.status==="resolved")?"completed":"no_change",execution:{provider:I,model:a.model,sessionId:re.sessionId},subjectHints:z,filePaths:[...(re.fileEdits??[]).map(se=>se.file_path),...(re.editEvents??[]).flatMap(se=>se.filePath?[se.filePath]:[])].map(se=>Fo(se)?gs(r,se):se),resolutions:pe.map(se=>({status:se.status,summary:se.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(se=>se.id)})}catch(se){console.warn(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,se instanceof Error?se.message:String(se))}}if(Pe?.status==="committed"&&Pe.decisionId&&I!=="copilot"&&await Ft({provider:I,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Pe.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=ar(ye,z.assertions),Ke=Date.now(),Fs={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:se,provider:I,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:Is(r),rawResponse:ye,scopeFingerprint:a._evalScopeFingerprint,...Ve};await q.recordEvalVerification(z,Fs),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=Yr(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:qt},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:I}),N.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:re.error||"Unknown error",provider:I,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});_e()});let xt=Uc(async(a,u)=>{if(rd(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let k=a.url||"/",m=k.split("?")[0],P=new URL(k,`http://127.0.0.1:${y}`),I=P.pathname,j=sd(a,P);if(j&&j!==s){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Yn(r)});return}if(a.headers.origin){if(!Rs(a.headers.origin)){M(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Yn(r)});return}}try{if(a.method==="POST"&&I==="/send")await st(a,u);else if(a.method==="GET"&&I==="/events")Ye(a,u);else if(a.method==="GET"&&I==="/status")await it(a,u,j);else if(a.method==="PATCH"&&I==="/config")await at(a,u);else if(a.method==="POST"&&I==="/leases"){if(p!=="detached"){M(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Ge(a),D=typeof $.leaseId=="string"?$.leaseId.trim():"",F=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){M(u,400,{error:"A valid leaseId is required."});return}ne();let L=B.acquire(D,F);M(u,201,{ok:!0,lease:L,ttlMs:ys})}catch{M(u,400,{error:"Invalid lease request."})}}else if(I.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){M(u,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(I.slice(8))}catch{M(u,400,{error:"Invalid lease id."});return}if(!$){M(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat($);if(!D){M(u,404,{error:"Lease not found."});return}M(u,200,{ok:!0,lease:D})}else{let D=B.release($);M(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&he()}}else if(a.method==="POST"&&I==="/shutdown"){if(p!=="detached"){M(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}M(u,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&I==="/restart"){if(p!=="detached"){M(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}M(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of Y)try{$.res.end()}catch{}xt.close(()=>{hs(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&I==="/capabilities")M(u,200,{providers:f});else if(I.startsWith("/imprint/"))await ve(a,u,I);else if(I.startsWith("/memory/"))await oo(a,u,I);else if(a.method==="POST"&&I==="/mcp/install")await so(a,u);else if(a.method==="POST"&&I==="/reply")await Ae(a,u);else if(a.method==="POST"&&I==="/cancel")ut(a,u);else if(a.method==="POST"&&I==="/materialize")M(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&I==="/materialization-runs")M(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&I==="/projection-runs"){let $=await V.loadRuns();M(u,200,$)}else if(a.method==="GET"&&I==="/projection/proposals"){let $=await V.loadModelProposals();M(u,200,$)}else if(a.method==="POST"&&I.startsWith("/projection/proposals/")&&I.endsWith("/apply-selected")){let $=I.slice(22,-15);await zt($,a,u)}else if(a.method==="POST"&&I.startsWith("/projection/proposals/")&&I.endsWith("/apply")){let $=I.slice(22,-6);await ro($,u)}else if(a.method==="POST"&&I.startsWith("/projection/proposals/")&&I.endsWith("/dismiss")){let $=I.slice(22,-8);await Ne($,a,u)}else if(I.startsWith("/model/proposals/"))M(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&I==="/model/component")await ln(a,u);else if(a.method==="DELETE"&&I==="/model/component")await _s(a,u);else if(a.method==="PATCH"&&I==="/model/token")await As(a,u);else if(a.method==="DELETE"&&I==="/model/token")await Cs(a,u);else if(a.method==="POST"&&I==="/model/consolidate")M(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&I==="/model/synthesize")M(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&I==="/evals/synthesize")M(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&I==="/evals"){let $=await V.loadModel(),D=await Promise.all((await q.getJournalEvalCases()).map(async C=>{let O=await bs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),F=Is(r),L=(await q.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===F);M(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:L,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&I.startsWith("/evals/")&&I.endsWith("/run")){let $=I.slice(7,-4);await ct($,a,u)}else if(a.method==="PATCH"&&I.startsWith("/evals/"))await St(I.slice(7),a,u);else if(a.method==="GET"&&I==="/model"){let $=await V.loadModel();M(u,200,{model:$})}else if(a.method==="GET"&&I.startsWith("/jobs/")&&I.endsWith("/events")){let $=I.slice(6,I.length-7),D=parseInt(P.searchParams.get("afterSeq")??"-1",10),F=N.getBufferedEvents($,isNaN(D)?-1:D);F?M(u,200,F):M(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await Js(m.slice(7),u);else if(a.method==="GET"&&I==="/threads/recent"){let $=Math.min(Math.max(parseInt(P.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent($);M(u,200,D)}else if(a.method==="GET"&&I.startsWith("/decision/")){let $=I.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))M(u,400,{error:"Invalid decision id"});else{let D=await G.getThread($),F=[...D?.messages??[]].reverse().find(L=>L.annotationSnapshot);if(D&&F?.annotationSnapshot){let L=[...D.messages].reverse().find(C=>C.resolutions?.length);M(u,200,{decision:{id:D.id,createdAt:F.timestamp,url:F.annotationSnapshot.url,viewport:F.annotationSnapshot.viewport,color:F.annotationSnapshot.color,annotations:F.annotationSnapshot.annotations,resolutions:L?.resolutions??[]},authority:"thread_snapshot"})}else{let L=await E.loadDecision($);L?M(u,200,{decision:L,authority:"legacy_archive"}):M(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&I.startsWith("/thread/")){let $=I.slice(8);await Ns($,u)}else if(a.method==="DELETE"&&I.startsWith("/thread/")){let $=I.slice(8);await Bs($,u)}else a.method==="GET"&&(I==="/canvas"||I==="/canvas/")?$s(a,u):a.method==="GET"&&I==="/canvas/manifest"?await Os(u):a.method==="GET"&&I==="/canvas/app.mjs"?await Ds(u):M(u,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),M(u,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function oo(a,u,k){try{if(a.method==="GET"&&k==="/memory/status"){M(u,200,await q.status());return}if(a.method==="GET"&&k==="/memory/diagnostics"){M(u,200,await q.diagnostics());return}if(a.method==="GET"&&k==="/memory/model-view"){M(u,200,await q.getModelView());return}if(a.method==="POST"&&k==="/memory/constraints"){let m=await Ge(a),P=typeof m.reactComponent=="string"?m.reactComponent.trim():"",I=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",$=await q.getModelView(),D=P?$.entries.filter(C=>C.key===`components.${P}`||C.key.startsWith(`components.${P}.`)):[],F=(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)},L=(await q.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(U=>U.kind==="route"&&F(U.value,I)||U.kind==="subject"&&U.value===j),Q=(C.scenarios??[]).some(U=>!!P&&(U.components??[]).some(ie=>ie.name===P||ie.exportName===P)||!!I&&!!U.route&&U.route===I||!!I&&!!U.routePattern&&F(U.routePattern,I));return O||Q}).map(C=>({id:C.id,title:C.title,verificationState:C.verificationState,assertions:C.assertions}));M(u,200,{modelEntries:D,evals:L});return}if(a.method==="POST"&&k==="/memory/conversation-action"){let m=await Ge(a),P=typeof m.threadId=="string"?m.threadId:"",I=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!P||!I||!["accept","edit_and_accept","reject","defer"].includes(j)){M(u,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await G.getThread(P),D=$?.messages.find(ae=>ae.memoryReviewCard?.proposalId===I)?.memoryReviewCard;if(!$||!D){M(u,409,{error:"This decision review card is not available in the thread."});return}let F=await V.findModelProposalsByThread(P),L=(await Promise.all(F.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(re=>q.findPendingProposalForLegacyDecision(re)))).some(re=>re?.proposalId===I)})))).find(ae=>ae.matches)?.proposal,C={proposalId:I,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){M(u,400,{error:"Edited decision wording is required."});return}let O=await q.commitConversationalReview(C),Q=`memory-${pt().slice(0,8)}`,U=j==="accept"?"> Accepted decision":j==="edit_and_accept"?"> Edited and accepted decision":j==="reject"?"> Rejected decision":"> Deferred decision";await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:Q,replyToQuestion:U}),await G.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:Q,responseText:"",memoryReceipt:O,provider:bt(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&L&&await V.dismissModelProposal(L.id);let ie=bt(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&ie!=="copilot"&&await Ft({provider:ie,model:typeof m.model=="string"?m.model:void 0,agentSettings:ht(m),threadId:P,reason:`Project accepted decision ${O.decisionId}`}),M(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&k==="/memory/analyze"){let m=await Ge(a),P=await q.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),I=Object.fromEntries([...new Set(P.issues.map(j=>j.code))].map(j=>[j,P.issues.filter($=>$.code===j).length]));M(u,200,{...P,issues:void 0,issueCounts:I});return}if(a.method==="POST"&&k==="/memory/review"){let m=await Ge(a),P=await q.review(Oo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,200,P);return}if(a.method==="POST"&&k==="/memory/context"){let m=await Ge(a),P=await q.contextualize(Oo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,200,P);return}if(a.method==="POST"&&k==="/memory/initialize"){let m=await Ge(a),P=await q.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:ot});M(u,201,{status:P.status,report:{source:P.report.source,imported:P.report.imported,unresolvedAcceptance:P.report.unresolvedAcceptance,deferredModelEntries:P.report.deferredModelEntries,proofCases:P.report.proofCases,schemaIssues:P.report.schemaIssues}});return}if(a.method==="POST"&&k==="/memory/plan"){let m=await Ge(a),P=await q.planReview($o(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,P.result.ok?200:422,P);return}if(a.method==="POST"&&k==="/memory/commit"){let m=await Ge(a),P=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},I=await q.commitReview($o(m.command),{transactionId:typeof P.transactionId=="string"?P.transactionId:"",committedAt:typeof P.committedAt=="string"?P.committedAt:""});M(u,200,{status:await q.status(),journal:I.report});return}if(a.method==="POST"&&k==="/memory/recover"){let m=await Ge(a),P=await q.recover(m.confirm===!0);M(u,200,{status:await q.status(),journal:P.report});return}M(u,404,{error:"Memory endpoint not found."})}catch(m){let P=m instanceof Error?m.message:String(m),I=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(P),j=/required|invalid|unsupported|expected|must be|confirmation/i.test(P);if(I||j){M(u,I?409:400,{error:P});return}throw m}}async function ve(a,u,k){if(a.method==="GET"&&k==="/imprint/status"){let[m,P]=await Promise.all([fe.store.load(),G.load()]),I=[...new Set(Object.values(P.threads).flatMap(j=>Zn(j.messages)))];M(u,200,{state:"ready",head:m.graph.head,updatedAt:m.graph.updatedAt,explanationCount:m.graph.explanations.filter(j=>j.state!=="retired").length,concreteCount:m.graph.concrete.length,relationCount:m.graph.relations.length,pendingGroundingCount:I.length,recoveredTransactions:m.recoveredTransactions,admission:fe.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&k==="/imprint/action"){let m=await Ge(a),P=typeof m.threadId=="string"?m.threadId:"",I=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!P||!I||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(j)){M(u,400,{error:"A valid thread, imprint update, and action are required."});return}let D=await G.getThread(P),F=[...D?.messages??[]].reverse().find(ie=>ie.role==="assistant"&&ie.imprintSummary?.transactionId===I),L=F?.imprintSummary;if(!D||!F||!L){M(u,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){M(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${pt().slice(0,8)}`;await fe.applyGroundingAction({summary:L,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:P,jobId:C}),await q.recordImprintEvidence({summary:L,action:j,threadId:P,jobId:C}).catch(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let O=Dt(F.result,!!F.question),Q=F.turn?{...F.turn,result:Dt(F.turn.result,!!F.question)}:void 0;await G.updateAssistantMessage(P,F.jobId,{imprintSummary:{...L,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(P,{role:"human",timestamp:Date.now(),jobId:C,replyToQuestion:U[j]}),M(u,200,{ok:!0,action:j});return}M(u,404,{error:"Imprint endpoint not found."})}async function st(a,u){let{screenshot:k,feedback:m,color:P,provider:I,model:j,reasoningEffort:$,serviceTier:D,sourceId:F,pastedImages:L,pageScreenshots:C}=await Dn(a),O;try{O=JSON.parse(m)}catch{M(u,400,{error:"Invalid feedback JSON"});return}let Q=pt().slice(0,8),U={};if(C.length>0)for(let ee of C){let me=encodeURIComponent(ee.pathname),Re=Ee(d,`screenshot-${Q}-${me}.webp`);await dn(Re,ee.data),U[ee.pathname]=Re}let ie=Ee(d,`screenshot-${Q}.webp`);await dn(ie,k);let ae={};if(L.length>0)for(let ee of L){let me=Ee(d,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await dn(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 zr(q,O,re,ee=>console.warn(`[\u22B9 ${y}:${Q}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),de=await fe.contextualize({text:On(O),subjectHints:[...re,...O.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(me=>!!me))],pendingGroundingExplanationIds:Zn((await G.getThread(be))?.messages??[])}).catch(ee=>{console.warn(`[\u22B9 ${y}:${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:P,threadId:be,annotationIds:ye,provider:bt(I),model:j||void 0,agentSettings:ht({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:F||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||ws({...O,annotations:[me]}))}$e=[...ee.entries()].map(([me,Re])=>`\`${me}\`
228
+ ${Re.map(xe=>`- ${xe}`).join(`
408
229
  `)}`).join(`
409
- `)}else ne=qn(X);let fe=ze(X,Object.keys(se).length>0?se:void 0);await w.appendMessage(ue,{role:"human",timestamp:Date.now(),jobId:b,screenshotPath:H,...de?{screenshotPaths:D}:{},...Object.keys(se).length>0?{imagePaths:se}:{},annotationIds:pe,feedbackSummary:ne,feedbackContext:fe||void 0});let j=O.enqueue(L);m(c,200,{jobId:b,position:j,threadId:ue})}async function ss(r,c){let u=r.headers["content-type"]||"",p,h,d,P,g,x,I,C=[];if(u.includes("multipart/form-data")){let j=await at(r),R=j.feedback?JSON.parse(j.feedback):{};p=R.threadId,h=R.reply,d=R.color,P=R.provider,g=R.model,x=Re(R),I=R.sourceId||j.sourceId;for(let Y of j.pastedImages)C.push(Y.data)}else{let j=[];for await(let re of r)j.push(typeof re=="string"?Buffer.from(re):re);let R=Buffer.concat(j).toString("utf-8"),Y;try{Y=JSON.parse(R)}catch{m(c,400,{error:"Invalid JSON"});return}p=Y.threadId,h=Y.reply,d=Y.color,P=Y.provider,g=Y.model,x=Re(Y),I=Y.sourceId}if(!p||!h){m(c,400,{error:"Missing threadId or reply"});return}if(!await w.getThread(p)){m(c,404,{error:"Thread not found"});return}let X="";{let j=await w.getThreadHistory(p);for(let R=j.length-1;R>=0;R--)if(j[R].screenshotPath){X=j[R].screenshotPath;break}}let b=await ys(p);if(!X&&!b){m(c,400,{error:"No screenshot available"});return}let D=O.hasActiveThread(p),H=D?O.getQueuedThreadJob(p,j=>j._replyText!==void 0||j._replyPrompt!==void 0):null,se=H?.id??Pe().slice(0,8),ce=[],ue=`${se}-${Date.now()}`;for(let j=0;j<C.length;j++){let R=ye(a,`reply-${ue}-${j}.webp`);await Fe(R,C[j]),ce.push(R)}await w.appendMessage(p,{role:"human",timestamp:Date.now(),jobId:se,replyToQuestion:h,screenshotPath:X,...D?{queued:!0}:{},...ce.length>0?{replyImagePaths:ce}:{}});let pe=await w.getThreadHistory(p),de=[];for(let j of pe)if(j.annotationIds)for(let R of j.annotationIds)de.includes(R)||de.push(R);let L=Ue(P),oe=Ot(X,pe,L,ce.length>0?ce:void 0);if(H){let j=H,Y=[...j._replyTexts??(j._replyText?[j._replyText]:[]),h],re=[...j._replyImagePaths??[],...ce];j._replyTexts=Y,j._replyText=Gn(Y),j._replyImagePaths=re.length>0?re:void 0,j._replyPrompt=Ot(X,pe,L,re.length>0?re:void 0),j.annotationIds=de.length>0?de:j.annotationIds,j.agentSettings=x??j.agentSettings,m(c,200,{jobId:se,position:1,threadId:p,bundled:!0});return}let ne={id:se,status:"queued",screenshotPath:X,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:d,threadId:p,annotationIds:de.length>0?de:void 0,provider:L,model:g||void 0,agentSettings:x,sourceId:I||void 0};b&&(ne.kind=b),ne._replyPrompt=oe,ne._replyTexts=[h],ne._replyText=Gn([h]),ce.length>0&&(ne._replyImagePaths=ce);let fe=D?O.enqueueNext(ne):O.enqueue(ne);m(c,200,{jobId:se,position:fe,threadId:p})}function os(r,c){c.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),c.write(`event: connected
230
+ `)}else $e=ws(O);let Ze=en(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:P||void 0},feedbackSummary:$e,feedbackContext:Ze||void 0,...we?{memoryReview:we}:{},...de?{imprintContext:de}:{}});let Pe=N.enqueue(pe);M(u,200,{jobId:Q,position:Pe,threadId:be})}async function Ae(a,u){let k=a.headers["content-type"]||"",m,P,I,j,$,D,F,L,C,O=[];if(k.includes("multipart/form-data")){let X=await Dn(a),ue=X.feedback?JSON.parse(X.feedback):{};m=ue.threadId,P=ue.reply,I=ue.color,j=ue.provider,$=ue.model,D=ht(ue),F=ue.sourceId||X.sourceId,L=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{M(u,400,{error:"Invalid JSON"});return}m=z.threadId,P=z.reply,I=z.color,j=z.provider,$=z.model,D=ht(z),F=z.sourceId,L=z.memoryReviewProposalId,C=z.evalRemediation?.action==="resolve"&&typeof z.evalRemediation.evalId=="string"?{evalId:z.evalRemediation.evalId,action:"resolve"}:void 0}if(!m||!P){M(u,400,{error:"Missing threadId or reply"});return}let Q=await G.getThread(m);if(!Q){M(u,404,{error:"Thread not found"});return}let U,ie;if(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){M(u,409,{error:"The failed eval run is not available in this thread."});return}if(ue.status!=="fail"){M(u,409,{error:"Only a failed eval can start remediation."});return}ie={evalCase:X,run:ue}}if(L){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===L),!U){M(u,409,{error:"The requested memory decision is not pending in this thread."});return}}let ae="";{let X=await G.getThreadHistory(m);for(let ue=X.length-1;ue>=0;ue--)if(X[ue].screenshotPath){ae=X[ue].screenshotPath;break}}let re=await mt(m);if(!ae&&!re){M(u,400,{error:"No screenshot available"});return}let be=N.hasActiveThread(m),ye=be?N.getQueuedThreadJob(m,X=>X._replyText!==void 0||X._replyPrompt!==void 0):null,K=ye?.id??pt().slice(0,8),we=[],de=`${K}-${Date.now()}`;for(let X=0;X<O.length;X++){let ue=Ee(d,`reply-${de}-${X}.webp`);await dn(ue,O[X]),we.push(ue)}await G.appendMessage(m,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:P,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:P,subjectHints:Q.elementIdentifiers,pendingGroundingExplanationIds:Zn(pe)}).catch(X=>{console.warn(`[\u22B9 ${y}:${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]:[])),Pe=[...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=bt(j),Re=U,xe=Re?[Re.underlying.proposalId]:Pe?[Pe.proposalId]:[],ft=Qr(ae,pe,me,we.length>0?we:void 0);if(ie?ft+=["","## Failed eval remediation","This is a new implementation goal based on a failed Popmelt eval. Fix the product gaps identified by the evaluator.","Do not weaken, rewrite, approve, retire, or otherwise modify the eval specification unless the developer explicitly asks.","Treat the accepted product decision as governing truth; the failed implementation is what should change.",`Eval: ${JSON.stringify(ie.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:ie.run.summary,assertionResults:ie.run.assertionResults,scope:ie.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
231
+ `):Re?ft+=["","## 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
+ `):Pe&&(ft+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Pe)}`,"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]:[]),P],se=[...X._replyImagePaths??[],...we];X._replyTexts=z,X._replyText=vs(z),X._replyImagePaths=se.length>0?se:void 0,X._replyPrompt=ft,X.annotationIds=ee.length>0?ee:X.annotationIds,X.agentSettings=D??X.agentSettings,X.memoryReview=Ce??X.memoryReview,X.imprintContext=$e??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...xe])],M(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:I,threadId:m,annotationIds:ee.length>0?ee:void 0,provider:me,model:$||void 0,agentSettings:D,sourceId:F||void 0,...Ce?{memoryReview:Ce}:{},...$e?{imprintContext:$e}:{},...xe.length?{surfacedProposalIds:xe}:{}};ie?Ue.kind="resolve_eval":re&&(Ue.kind=re),Ue._replyPrompt=ft,Ue._evalRemediation=!!ie,Ue._replyTexts=[P],Ue._replyText=vs([P]),we.length>0&&(Ue._replyImagePaths=we);let qt=be?N.enqueueNext(Ue):N.enqueue(Ue);M(u,200,{jobId:K,position:qt,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:${W}`).searchParams.get("sourceId")||void 0,h={id:Pe().slice(0,8),res:c,sourceId:p};ee.add(h),r.on("close",()=>{ee.delete(h)})}async function rs(r,c){let u=[...O.allActive,...A.allActive.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds??[],color:"#000000",kind:"materialize_model",standalone:d.standalone}))],[p,h]=await Promise.all([G.loadRuns(),G.loadModelProposals()]);m(r,200,{ok:!0,version:ht,restartMode:U,projectId:o,projectName:mt(t),projectRoot:t,requestProjectId:c,projectIdVerified:c===o,devOrigin:i,activeJob:u[0]?{id:u[0].id,status:u[0].status}:null,activeJobs:u.map(d=>({id:d.id,status:d.status,threadId:d.threadId,annotationIds:d.annotationIds,color:d.color,kind:d.kind,standalone:"standalone"in d?d.standalone:void 0})),queueDepth:O.depth+A.depth,materializerQueueDepth:A.depth,leases:{active:k.isActivated,count:k.size,nextExpiryAt:k.nextExpiryAt,shutdownPending:$},materialization:{activeJob:A.active?{id:A.active.id,status:A.active.status,threadId:A.active.threadId,annotationIds:A.active.annotationIds??[],provider:A.active.provider,model:A.active.model}:null,queueDepth:A.depth,recentRuns:[...p.runs].sort((d,P)=>(P.completedAt??P.startedAt)-(d.completedAt??d.startedAt)).slice(0,10),proposals:h.proposals.slice(0,20).map(d=>({id:d.id,status:d.status,title:d.title,summary:d.summary,decisionIds:d.decisionIds,threadId:d.threadId,runId:d.runId,createdAt:d.createdAt,updatedAt:d.updatedAt,appliedAt:d.appliedAt,dismissedAt:d.dismissedAt,generatedEvalIds:d.generatedEvalIds,error:d.error}))},recentJobs:ve})}async function is(r,c){let u=await new Promise(p=>{let h="";r.on("data",d=>{h+=d.toString()}),r.on("end",()=>p(h))});try{let p=JSON.parse(u);typeof p.devOrigin=="string"&&(i=p.devOrigin||null),m(c,200,{ok:!0,devOrigin:i})}catch{m(c,400,{error:"Invalid JSON"})}}async function as(r,c){let p=new URL(r.url||"/",`http://127.0.0.1:${W}`).searchParams.get("jobId"),h=p?O.allActive.filter(C=>C.id===p):O.allActive,d=p?A.allActive.filter(C=>C.id===p):A.allActive,P=[...h.map(C=>C.threadId),...d.map(C=>C.threadId)].filter(Boolean),g=p?O.cancelJob(p):O.cancelActive(),x=p?A.cancelJob(p):A.cancelActive(),I=!!(g||x);for(let C of P)await w.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:p||x?.id||"",cancelled:!0});m(c,200,{cancelled:I})}async function zt(r){let c=Pe().slice(0,8),u=r.threadId,p=!u;u||(u=(await w.createThread(c,[])).id,we.set(u,"materialize_model")),p&&await w.appendMessage(u,{role:"human",timestamp:Date.now(),jobId:c,feedbackSummary:r.reason}),await w.appendMessage(u,{role:"assistant",timestamp:Date.now(),jobId:c,responseText:p?"Materializing model suggestions...":"Thinking through model suggestions from this decision...",model:r.model,provider:r.provider});let h={id:c,status:"queued",createdAt:Date.now(),provider:r.provider,model:r.model,agentSettings:r.agentSettings,threadId:u,annotationIds:r.annotationIds,sourceId:r.sourceId,standalone:p},d=A.enqueue(h);return{jobId:c,position:d,threadId:u}}async function ls(r,c){if(A.isRunning){m(c,200,{skipped:!0,reason:"Already running"});return}let{provider:u,model:p,agentSettings:h}=await Ee(r);if(u==="copilot"){m(c,400,{error:"Materialization is not available for Copilot yet."});return}let d=await G.getUnmaterializedPatternDecisions();if(d.length===0){m(c,200,{skipped:!0,reason:"No unmaterialized pattern decisions"});return}let P=await zt({provider:u,model:p,agentSettings:h,reason:"Materialize model \u2014 promote pattern decisions into the local taste model"});m(c,200,{started:!0,decisionCount:d.length,decisionIds:d.map(g=>g.id),...P})}async function cs(r,c){let u=decodeURIComponent(r),p=await G.applyModelProposal(u);if(!p){m(c,404,{error:"Model proposal not found"});return}p.threadId&&await w.appendMessage(p.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${p.id}`,responseText:`Model proposal applied.
413
-
414
- ${p.title}
415
- ${p.summary}`}),m(c,200,{proposal:p})}async function ds(r,c,u){let p=decodeURIComponent(r),h=[];for await(let I of c)h.push(typeof I=="string"?Buffer.from(I):I);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{m(u,400,{error:"Invalid JSON"});return}let P=(d.changes??[]).flatMap(I=>{if(!Array.isArray(I.path)||I.path.length===0)return[];let C=I.path.filter(te=>typeof te=="string"||typeof te=="number");return C.length!==I.path.length?[]:[{path:C,value:I.value,remove:I.remove===!0}]});if(P.length===0){m(u,400,{error:"No selected model changes"});return}let g=(d.changeSummaries??[]).flatMap(I=>{if(!I||typeof I!="object")return[];let C=Array.isArray(I.path)?I.path.filter(te=>typeof te=="string"||typeof te=="number"):void 0;return Array.isArray(I.path)&&C?.length!==I.path.length?[]:[{group:typeof I.group=="string"?I.group:void 0,label:typeof I.label=="string"?I.label:void 0,detail:typeof I.detail=="string"?I.detail:void 0,path:C,value:I.value,currentValue:I.currentValue}]}),x=await G.applySelectedModelProposal(p,P,g);if(!x){m(u,404,{error:"Model proposal not found"});return}if(x.threadId){let I=Ue(d.provider),C=typeof d.model=="string"&&d.model?d.model:void 0;await w.appendMessage(x.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${x.id}`,responseText:`Model proposal applied with ${P.length} selected change${P.length===1?"":"s"}.
416
-
417
- ${x.title}`,provider:I,model:C})}m(u,200,{proposal:x})}async function us(r,c,u){let p=decodeURIComponent(r),{provider:h,model:d}=await Ee(c),P=await G.dismissModelProposal(p);if(!P){m(u,404,{error:"Model proposal not found"});return}P.threadId&&await w.appendMessage(P.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${P.id}`,responseText:`Model proposal dismissed.
418
-
419
- ${P.title}`,provider:h,model:d}),m(u,200,{proposal:P})}async function ps(r,c,u){let p=decodeURIComponent(r),h=await G.findModelProposal(p);if(!h){m(u,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){m(u,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:P,agentSettings:g}=await Ee(c),x=d??h.provider??B;if(x==="copilot"){m(u,400,{error:"Eval projection is not available for Copilot yet."});return}let I=await G.loadModel(),C=await ie.loadSuite(),te=fn({proposal:h,currentModel:I,existingSuite:C}),X=Pe().slice(0,8),b=h.threadId??(await w.createThread(X,[])).id;we.set(b,"synthesize_evals"),await w.appendMessage(b,{role:"human",timestamp:Date.now(),jobId:X,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
420
- `)});let D={id:X,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#111827",threadId:b,kind:"synthesize_evals",provider:x,model:P??h.model,agentSettings:g};D._replyPrompt=te,D._proposalId=h.id;let H=O.enqueue(D);m(u,200,{jobId:X,position:H,threadId:b})}async function Ee(r){try{let c=[];for await(let p of r)c.push(typeof p=="string"?Buffer.from(p):p);if(c.length===0)return{};let u=JSON.parse(Buffer.concat(c).toString());return{provider:Ue(typeof u.provider=="string"?u.provider:void 0),model:typeof u.model=="string"&&u.model?u.model:void 0,agentSettings:Re(u)}}catch{return{}}}async function fs(r,c){let u=await G.loadModel();if(!u){m(c,400,{error:"No model exists yet"});return}let{provider:p,model:h,agentSettings:d}=await Ee(r);if(p==="copilot"){m(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let P=vn(u),g=Pe().slice(0,8),I=(await w.createThread(g,[])).id;we.set(I,"synthesize"),await w.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let C={id:g,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:I,kind:"synthesize",provider:p,model:h,agentSettings:d};C._replyPrompt=P;let te=O.enqueue(C);m(c,200,{jobId:g,position:te,threadId:I})}async function hs(r,c){let{provider:u,model:p,agentSettings:h}=await Ee(r);if(u==="copilot"){m(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let d=await le.listDecisionIds(),P=await le.loadDecisions(d),g=await w.load(),x=await G.loadModel(),I=await ie.loadSuite(),C=un({decisions:P,threads:g,model:x,existingSuite:I}),te=Pe().slice(0,8),b=(await w.createThread(te,[])).id;we.set(b,"synthesize_evals"),await w.appendMessage(b,{role:"human",timestamp:Date.now(),jobId:te,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let D={id:te,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#6b7280",threadId:b,kind:"synthesize_evals",provider:u,model:p||void 0,agentSettings:h};D._replyPrompt=C;let H=O.enqueue(D);m(c,200,{jobId:te,position:H,threadId:b})}async function ms(r,c,u){let p=decodeURIComponent(r),h=await ie.findCase(p);if(!h){m(u,404,{error:"Eval not found"});return}if(h.status!=="approved"){m(u,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:P,provider:g,model:x,reasoningEffort:I,serviceTier:C,sourceId:te}=await at(c),X=Ue(g)??B;if(X==="copilot"){m(u,400,{error:"Eval runs are not available for Copilot yet."});return}let b={};try{b=P?JSON.parse(P):{}}catch{m(u,400,{error:"Invalid eval run context JSON"});return}let D=Pe().slice(0,8),H=Pe().slice(0,8),se=ye(a,`eval-run-${D}.webp`);await Fe(se,d);let ce=await ie.writeRunScreenshot(D,d),ue=b.viewport,pe=ue&&typeof ue=="object"?ue:{},de={type:"current_page",url:typeof b.url=="string"?b.url:"",viewport:{width:typeof pe.width=="number"?pe.width:0,height:typeof pe.height=="number"?pe.height:0}},L=await G.loadModel(),oe=X==="claude"?Q.name:X==="codex"?K.name:null,ne=X==="codex"?Z.length>0:typeof oe=="string"&&/chrome|devtools/i.test(oe),fe=pn({evalCase:h,scope:de,model:L,screenshotPath:se,chromeDevtoolsAvailable:ne}),R=(await w.createThread(H,[])).id;we.set(R,"run_eval");let Y={timestamp:new Date().toISOString(),url:de.url,viewport:de.viewport,scrollPosition:{x:typeof b.scrollX=="number"?b.scrollX:0,y:typeof b.scrollY=="number"?b.scrollY:0},annotations:[],styleModifications:[]};await w.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:H,screenshotPath:se,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${de.url||"unknown"}`,"Assertions:",...h.assertions.map(As=>`- ${As}`)].join(`
421
- `)});let re={id:H,status:"queued",screenshotPath:se,feedback:Y,createdAt:Date.now(),color:"#111827",threadId:R,kind:"run_eval",evalId:p,evalRunId:D,provider:X,model:x||void 0,agentSettings:Re({reasoningEffort:I,serviceTier:C}),sourceId:te||void 0};re._replyPrompt=fe,re._evalRunScope=de,re._evalScreenshotPath=ce;let St=O.enqueue(re);m(u,200,{jobId:H,runId:D,position:St,threadId:R,screenshotPath:ce})}async function gs(r,c,u){let p=decodeURIComponent(r),h={},d,P,g;try{let I=[];for await(let te of c)I.push(typeof te=="string"?Buffer.from(te):te);let C=JSON.parse(Buffer.concat(I).toString());d=C.status,P=C.title,g=C.assertions}catch{m(u,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){m(u,400,{error:"Invalid status"});return}if(d&&(h.status=d),P!==void 0){if(typeof P!="string"||P.trim().length===0){m(u,400,{error:"Invalid title"});return}h.title=P.trim()}if(g!==void 0){if(!Array.isArray(g)){m(u,400,{error:"Invalid assertions"});return}let I=g.filter(C=>typeof C=="string").map(C=>C.trim()).filter(Boolean);if(I.length===0){m(u,400,{error:"Invalid assertions"});return}h.assertions=I}if(!h.status&&!h.title&&!h.assertions){m(u,400,{error:"No eval changes provided"});return}let x=await ie.updateCase(p,h);if(!x){m(u,404,{error:"Eval not found"});return}m(u,200,{eval:x})}async function ys(r){let c=we.get(r);if(c)return c;let h=(await w.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return we.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return we.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return we.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return we.set(r,"materialize_model"),"materialize_model"}async function vs(r,c){let u=[];for await(let x of r)u.push(typeof x=="string"?Buffer.from(x):x);let p;if(u.length>0)try{p=JSON.parse(Buffer.concat(u).toString("utf-8")).serverUrl}catch{}let h=[];S.claude?.available&&S.claude.mcp&&!S.claude.mcp.found&&h.push(await Tn(p)),S.codex?.available&&S.codex.mcp&&!S.codex.mcp.found&&h.push(await An(p)),S.copilot?.available&&S.copilot.mcp&&!S.copilot.mcp.found&&h.push(await Cn(p,S.copilot.path??M));let[d,P,g]=await Promise.all([Tt(t),At(t),Ct(t,S.copilot?.path??M)]);S.claude&&(S.claude.mcp=d),S.codex&&(S.codex.mcp=P),S.copilot&&(S.copilot.mcp=g),m(c,200,{results:h,capabilities:{providers:S}})}async function ws(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await G.addComponent(p.name);m(c,200,h)}async function Ss(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await G.removeComponent(p.name);m(c,200,h)}async function bs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"||typeof p.value!="string"){m(c,400,{error:"Missing or invalid path/value"});return}let h=await G.updateToken(p.path,p.value);m(c,200,h)}async function xs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"){m(c,400,{error:"Missing or invalid path"});return}let h=await G.removeToken(p.path);m(c,200,h)}function Ps(r,c){let u=i??"http://localhost:3000";if(!i){let h=r.headers.referer||r.headers.origin;if(h)try{let d=new URL(typeof h=="string"?h:h[0]||"");(d.hostname==="localhost"||d.hostname==="127.0.0.1")&&(u=d.origin)}catch{}}let p=Ft(W,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(p)}async function Is(r){let c=Date.now();if(He&&c<He.expires){m(r,200,He.data);return}try{let{scanForComponents:u}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:p}=await import("./render-generator-HWFLZYC3.mjs"),h=await u(t);He={data:h,expires:c+5e3},p(h,t,Jt).then(d=>{Jt=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),m(r,200,h)}catch(u){console.error("[Bridge] Scanner error:",u),m(r,500,{error:"Failed to scan components"})}}async function ks(r){let c=[ye(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ye(t,"packages","popmelt","dist","canvas.mjs")];try{let u=Rr(import.meta.url);c.unshift(ye(Er(u),"canvas.mjs"))}catch{}for(let u of c)try{let p=await Wn(u,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(p);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),m(r,404,{error:"Canvas bundle not found"})}async function Es(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){m(c,400,{error:"Invalid filename"});return}try{let u=await Wn(ye(a,r)),p=r.split(".").pop()?.toLowerCase(),h=p==="png"?"image/png":p==="webp"?"image/webp":p==="jpg"||p==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(u)}catch{m(c,404,{error:"File not found"})}}function Ge(r){return`/files/${mt(r)}`}async function Rs(r,c){let u=await w.getThread(r);if(!u){m(c,404,{error:"Thread not found"});return}let p=(await ie.loadRuns()).runs.filter(x=>x.threadId===r).sort((x,I)=>I.completedAt-x.completedAt)[0],h=p?await ie.findCase(p.evalId):null,d=await G.findModelProposalsByThread(r),P=[...d].sort((x,I)=>I.updatedAt-x.updatedAt)[0]??null,g=u.messages.map(({screenshotPath:x,screenshotPaths:I,imagePaths:C,replyImagePaths:te,...X})=>({...X,...X.role==="assistant"&&p?{evalRun:{...p,title:h?.title}}:{},...x?{screenshotUrl:Ge(x)}:{},...I?{screenshotUrls:Object.fromEntries(Object.entries(I).map(([b,D])=>[b,Ge(D)]))}:{},...C?{imageUrls:Object.fromEntries(Object.entries(C).map(([b,D])=>[b,D.map(Ge)]))}:{},...te?{replyImageUrls:te.map(Ge)}:{}}));m(c,200,{id:u.id,createdAt:u.createdAt,messages:g,modelProposal:P,modelProposals:d})}async function Ms(r,c){let u=decodeURIComponent(r);if(!await w.deleteThread(u)){m(c,404,{deleted:!1,error:"Thread not found"});return}m(c,200,{deleted:!0})}let Bt=9,Lt=!1;for(let r=e;r<e+Bt;r++)try{await jr(wt,r),W=r,Lt=!0,console.log(`[\u22B9 is watching :${W}]`);break}catch(c){if(c.code==="EADDRINUSE"){let u=await vt(r);if(u&&u.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!Lt)throw new Error(`[Bridge] All ports ${e}\u2013${e+Bt-1} in use`);for(let[r,c]of Object.entries(S))!c.available||!c.path||V(r,c.path).then(u=>{if(u)console.log(`[Bridge] ${r} warmed up`);else{console.warn(`[Bridge] ${r} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let p of ee)gt(p,{type:"capabilities_changed",data:{}})}});let Ts=setInterval(()=>{Xn(a).catch(()=>{})},Ar),jt=setInterval(()=>{k.expireStale().becameEmpty&&_()},$r);return jt.unref?.(),{port:W,projectId:o,close:async()=>{clearInterval(Ts),clearInterval(jt),T(),k.clear(),await O.destroyAsync(),A.destroy();for(let r of ee)try{r.res.end()}catch{}return ee.clear(),new Promise(r=>{wt.close(()=>r())})}}}async function Xn(s){try{let e=await Sr(s),n=Date.now();for(let t of e){let o=ye(s,t);try{let i=await xr(o);n-i.mtimeMs>Cr&&await Pr(o)}catch{}}}catch{}}import{randomUUID as Fr}from"crypto";var Ur=5e3,Wr=250;function Nt(s){return{"Content-Type":"application/json",...s.projectId?{"X-Popmelt-Project-Id":s.projectId}:{}}}async function Kn(s,e=fetch){let n=`${process.pid}-${Fr()}`,t=`http://127.0.0.1:${s.port}`,o=!1,i=!1,a=async()=>(await e(`${t}/leases`,{method:"POST",headers:Nt(s),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await a())return null}catch(v){return console.warn("[popmelt] failed to register bridge lease:",v instanceof Error?v.message:String(v)),null}let l=async()=>{if(!(o||i)){i=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:Nt(s)})).status===404&&!o&&await a()}catch{}finally{i=!1}}},f=setInterval(()=>{l()},Ur);return f.unref?.(),{id:n,release:async()=>{if(!o){o=!0,clearInterval(f);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:Nt(s),keepalive:!0})}catch{}}}}}function Zn(s,e=process){let n=!1,t=new Map,o=()=>{s.release()},i=()=>{if(!n){n=!0,e.removeListener("beforeExit",o);for(let[a,l]of t)e.removeListener(a,l);t.clear()}};for(let a of["SIGINT","SIGTERM"]){let l=()=>{let f=e.listenerCount(a),y=s.release();if(f>0)return;let v=new Promise(M=>{setTimeout(M,Wr)});Promise.race([y,v]).finally(()=>{i(),e.kill(e.pid,a)})};t.set(a,l),e.prependOnceListener(a,l)}return e.once("beforeExit",o),i}var Yr=1111;async function Vr(s){return Gr(s).catch(()=>s)}async function Na(s){if(process.env.NODE_ENV==="production"&&!s?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(s?.detached){let n=await Kr(s);if(s.manageLease===!1)return n;let t=await Kn({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let o=Zn(t);return{...n,close:async()=>{o(),await t.release()}}}let e=await Vn(s);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Kr(s){let e=s.port??Yr,n=await Vr(s.projectRoot??process.cwd()),t=ft(n);for(let f=e;f<e+10;f++){let y=await vt(f);if(y&&y.projectId===t){if(y.version&&y.version!==ht){try{await fetch(`http://127.0.0.1:${f}/shutdown`,{method:"POST"})}catch{}await new Promise(M=>setTimeout(M,500));break}let v=s.devOrigin;if(v&&y.devOrigin!==v)try{await fetch(`http://127.0.0.1:${f}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:v})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(f),process.env.POPMELT_PROJECT_ID=t,{port:f,projectId:t,close:async()=>{}}}}let o=Qr(qr(Xr(import.meta.url)),"bridge-entry.mjs"),i=Hr(process.execPath,[o],{detached:!0,stdio:"ignore",env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:s.devOrigin??"",POPMELT_COPILOT_PATH:s.copilotPath??""}});i.unref();let a=1e4,l=Date.now()+a;for(;Date.now()<l;){await new Promise(f=>setTimeout(f,100));for(let f=e;f<e+10;f++){let y=await vt(f);if(y&&y.projectId===t)return process.env.POPMELT_BRIDGE_PORT=String(f),process.env.POPMELT_PROJECT_ID=t,{port:f,projectId:t,close:async()=>{}}}}throw i.kill("SIGTERM"),new Error(`[Bridge] Detached bridge failed to start within ${a/1e3}s (port ${e})`)}export{Na as startPopmelt};
236
+ `);let m=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,P={id:pt().slice(0,8),res:u,sourceId:m};Y.add(P),a.on("close",()=>{Y.delete(P)})}async function it(a,u,k){i??=ds(a.headers),_e();let m=[...N.allActive,...T.allActive.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds??[],color:"#000000",kind:"project_model",standalone:K.standalone}))],[P,I,j,$,D]=await Promise.allSettled([V.loadRuns(),V.loadModelProposals(),q.status(),fe.store.load(),G.load()]),F=[],L=K=>K.reason instanceof Error?K.reason.message:String(K.reason);P.status==="rejected"&&F.push({subsystem:"projection",message:L(P)}),I.status==="rejected"&&F.push({subsystem:"projection",message:L(I)}),j.status==="rejected"?F.push({subsystem:"memory",message:L(j)}):j.value.state==="degraded"&&F.push({subsystem:"memory",message:j.value.error??"Product memory is degraded."}),$.status==="rejected"&&F.push({subsystem:"imprint",message:L($)}),D.status==="rejected"&&F.push({subsystem:"threads",message:L(D)});let C=P.status==="fulfilled"?P.value.runs:[],O=I.status==="fulfilled"?I.value.proposals:[],Q=ls(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:L(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(K=>Zn(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:L($),pendingGroundingCount:ae.length,admission:fe.diagnostics(),admissionWindowStartedAt:e},be=F.length>0?"degraded":ie.state==="absent"||ie.state==="initializing"?"initializing":"healthy",ye=new Date().toISOString();M(u,200,{ok:!0,schemaVersion:3,generatedAt:ye,serverStartedAt:e,health:{state:be,issues:F},version:ot,restartMode:p,projectId:s,projectName:Yn(r),projectRoot:r,requestProjectId:k,projectIdVerified:k===s,devOrigin:i,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(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:W},projection:{state:P.status==="fulfilled"&&I.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:Me,recentJobs:Ie})}async function at(a,u){let k=await new Promise(m=>{let P="";a.on("data",I=>{P+=I.toString()}),a.on("end",()=>m(P))});try{let m=JSON.parse(k);typeof m.devOrigin=="string"&&(i=m.devOrigin||null),M(u,200,{ok:!0,devOrigin:i})}catch{M(u,400,{error:"Invalid JSON"})}}async function ut(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),P=m?N.allActive.filter(L=>L.id===m):N.allActive,I=m?T.allActive.filter(L=>L.id===m):T.allActive,j=[...P.map(L=>L.threadId),...I.map(L=>L.threadId)].filter(Boolean),$=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),F=!!($||D);for(let L of j)await G.appendMessage(L,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});M(u,200,{cancelled:F})}async function Ft(a){let u=pt().slice(0,8),k=a.threadId,m=!k;k||(k=(await G.createThread(u,[])).id,Je.set(k,"project_model")),m&&await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:u,feedbackSummary:a.reason}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:u,responseText:m?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let P={id:u,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:k,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:m},I=T.enqueue(P);return{jobId:u,position:I,threadId:k}}async function ro(a,u){let k=decodeURIComponent(a),m=await V.findModelProposal(k);if(!m){M(u,404,{error:"Model proposal not found"});return}M(u,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:m})}async function zt(a,u,k){let m=decodeURIComponent(a),P=[];for await(let O of u)P.push(typeof O=="string"?Buffer.from(O):O);let I;try{I=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{M(k,400,{error:"Invalid JSON"});return}let j=(I.changes??[]).flatMap(O=>{if(!Array.isArray(O.path)||O.path.length===0)return[];let Q=O.path.filter(ie=>typeof ie=="string"||typeof ie=="number");if(Q.length!==O.path.length)return[];let U=Array.isArray(O.decisionIds)?O.decisionIds.filter(ie=>typeof ie=="string"):void 0;return[{path:Q,value:O.value,remove:O.remove===!0,decisionIds:U}]});if(j.length===0){M(k,400,{error:"No selected model changes"});return}let $=(I.changeSummaries??[]).flatMap(O=>{if(!O||typeof O!="object")return[];let Q=Array.isArray(O.path)?O.path.filter(U=>typeof U=="string"||typeof U=="number"):void 0;return Array.isArray(O.path)&&Q?.length!==O.path.length?[]:[{group:typeof O.group=="string"?O.group:void 0,label:typeof O.label=="string"?O.label:void 0,detail:typeof O.detail=="string"?O.detail:void 0,path:Q,value:O.value,currentValue:O.currentValue}]}),D=await V.findModelProposal(m);if(!D){M(k,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){M(k,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){M(k,409,{error:`Model proposal is already ${D.status}.`});return}let F=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}}),L=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:F}),C=await V.applySelectedModelProposal(m,j,$);if(!C){M(k,404,{error:"Model proposal not found"});return}if(await Bt(C),C.threadId){let O=bt(I.provider),Q=typeof I.model=="string"&&I.model?I.model:void 0;await G.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${C.id}`,responseText:"",provider:O,model:Q})}M(k,200,{proposal:C,projection:L})}async function Ne(a,u,k){let m=decodeURIComponent(a),{provider:P,model:I}=await Be(u),j=await V.dismissModelProposal(m);if(!j){M(k,404,{error:"Model proposal not found"});return}j.threadId&&await G.appendMessage(j.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${j.id}`,responseText:"",provider:P,model:I}),M(k,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 k=JSON.parse(Buffer.concat(u).toString());return{provider:bt(typeof k.provider=="string"?k.provider:void 0),model:typeof k.model=="string"&&k.model?k.model:void 0,agentSettings:ht(k)}}catch{return{}}}async function ct(a,u,k){let m=decodeURIComponent(a),P=await q.findJournalEvalCase(m);if(!P){M(k,404,{error:"Eval not found"});return}if(P.status!=="approved"){M(k,400,{error:"Only approved evals can be run"});return}let{screenshot:I,feedback:j,provider:$,model:D,reasoningEffort:F,serviceTier:L,sourceId:C}=await Dn(u),O=bt($)??b;if(O==="copilot"){M(k,400,{error:"Eval runs are not available for Copilot yet."});return}let Q={};try{Q=j?JSON.parse(j):{}}catch{M(k,400,{error:"Invalid eval run context JSON"});return}let U=pt().slice(0,8),ie=pt().slice(0,8),ae=Ee(d,`eval-run-${U}.webp`);await dn(ae,I);let re=await Z.persistEvalScreenshot(I),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 bs(r,P,we),pe=O==="claude"?S.name:O==="codex"?_.name:null,Ce=O==="codex"?A.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),$e=lr({evalCase:P,scope:K,model:we,screenshotPath:ae,chromeDevtoolsAvailable:Ce}),Pe=(await G.createThread(ie,[])).id;Je.set(Pe,"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(Pe,{role:"human",timestamp:Date.now(),jobId:ie,screenshotPath:ae,feedbackSummary:`Run eval \u2014 ${P.title}`,feedbackContext:[`Eval: ${P.title}`,"Scope: current page",`URL: ${K.url||"unknown"}`,"Assertions:",...P.assertions.map(xe=>`- ${xe}`)].join(`
237
+ `)});let me={id:ie,status:"queued",screenshotPath:ae,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:Pe,kind:"run_eval",evalId:m,evalRunId:U,provider:O,model:D||void 0,agentSettings:ht({reasoningEffort:F,serviceTier:L}),sourceId:C||void 0};me._replyPrompt=$e,me._evalRunScope=K,me._evalScreenshotPath=re,me._evalScopeFingerprint=de;let Re=N.enqueue(me);M(k,200,{jobId:ie,runId:U,position:Re,threadId:Pe,screenshotPath:re})}async function St(a,u,k){let m=decodeURIComponent(a),P={},I,j,$;try{let F=[];for await(let C of u)F.push(typeof C=="string"?Buffer.from(C):C);let L=JSON.parse(Buffer.concat(F).toString());I=L.status,j=L.title,$=L.assertions}catch{M(k,400,{error:"Invalid JSON"});return}if(I!==void 0&&I!=="pending"&&I!=="approved"&&I!=="rejected"){M(k,400,{error:"Invalid status"});return}if(I&&(P.status=I),j!==void 0){if(typeof j!="string"||j.trim().length===0){M(k,400,{error:"Invalid title"});return}P.title=j.trim()}if($!==void 0){if(!Array.isArray($)){M(k,400,{error:"Invalid assertions"});return}let F=$.filter(L=>typeof L=="string").map(L=>L.trim()).filter(Boolean);if(F.length===0){M(k,400,{error:"Invalid assertions"});return}P.assertions=F}if(!P.status&&!P.title&&!P.assertions){M(k,400,{error:"No eval changes provided"});return}let D=await q.updateJournalEvalCase(m,P);if(!D){M(k,404,{error:"Eval not found"});return}M(k,200,{eval:D})}async function mt(a){let u=Je.get(a);if(u)return u;let P=(await G.getThread(a))?.messages.find(I=>I.role==="human")?.feedbackSummary??"";if(P.startsWith("Synthesize evals"))return Je.set(a,"synthesize_evals"),"synthesize_evals";if(P.startsWith("Synthesize rules"))return Je.set(a,"synthesize"),"synthesize";if(P.startsWith("Run eval"))return Je.set(a,"run_eval"),"run_eval";if(P.startsWith("Materialize model")||P.startsWith("Project model"))return Je.set(a,"project_model"),"project_model"}async function so(a,u){let k=[];for await(let D of a)k.push(typeof D=="string"?Buffer.from(D):D);let m;if(k.length>0)try{m=JSON.parse(Buffer.concat(k).toString("utf-8")).serverUrl}catch{}let P=[];f.claude?.available&&f.claude.mcp&&!f.claude.mcp.found&&P.push(await kr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&P.push(await Tr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&P.push(await jr(m,f.copilot.path??w));let[I,j,$]=await Promise.all([wo(r),Io(r),bo(r,f.copilot?.path??w)]);f.claude&&(f.claude.mcp=I),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),M(u,200,{results:P,capabilities:{providers:f}})}async function ln(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){M(u,400,{error:"Missing or invalid name"});return}let P=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 I=await qe({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});M(u,200,{added:!0,alreadyExists:!1,...P,evalId:I})}async function _s(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){M(u,400,{error:"Missing or invalid name"});return}let P=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 I=await qe({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});M(u,200,{removed:!0,...P,evalId:I})}async function As(a,u){let k=[];for await(let $ of a)k.push(typeof $=="string"?Buffer.from($):$);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){M(u,400,{error:"Missing or invalid path/value"});return}let P=m.value;try{let $=JSON.parse(m.value);$&&typeof $=="object"&&(P=$)}catch{}let I=await q.recordDirectModelMutation({key:`tokens.${m.path}`,value:P,claim:`${m.path} uses ${m.value} in the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let j=await qe({decisionId:I.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});M(u,200,{updated:!0,...I,evalId:j})}async function Cs(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{M(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){M(u,400,{error:"Missing or invalid path"});return}let P=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 I=await qe({decisionId:P.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});M(u,200,{removed:!0,...P,evalId:I})}function $s(a,u){let k=i??"http://localhost:3000";if(!i){let P=a.headers.referer||a.headers.origin;if(P)try{let I=new URL(typeof P=="string"?P:P[0]||"");(I.hostname==="localhost"||I.hostname==="127.0.0.1")&&(k=I.origin)}catch{}}let m=Go(y,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Os(a){let u=Date.now();if(rt&&u<rt.expires){M(a,200,rt.data);return}try{let{scanForComponents:k}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),P=await k(r);rt={data:P,expires:u+5e3},m(P,r,Lt).then(I=>{Lt=I}).catch(I=>console.warn("[Bridge] Render generation failed:",I)),M(a,200,P)}catch(k){console.error("[Bridge] Scanner error:",k),M(a,500,{error:"Failed to scan components"})}}async function Ds(a){let u=[Ee(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ee(r,"packages","popmelt","dist","canvas.mjs")];try{let k=Gc(import.meta.url);u.unshift(Ee(Wc(k),"canvas.mjs"))}catch{}for(let k of u)try{let m=await Lo(k,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(m);return}catch{}console.error("[Bridge] Canvas bundle not found in:",u),M(a,404,{error:"Canvas bundle not found"})}async function Js(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){M(u,400,{error:"Invalid filename"});return}try{let k=[Ee(d,a),Ee(r,".popmelt","artifacts","thread-media",a),Ee(r,".popmelt","artifacts","eval-screenshots",a),Ee(r,".popmelt","evals","screenshots",a),Ee(r,".popmelt","screenshots",a)],m;for(let j of k)try{m=await Lo(j);break}catch{}if(!m)throw new Error("File not found");let P=a.split(".").pop()?.toLowerCase(),I=P==="png"?"image/png":P==="webp"?"image/webp":P==="jpg"||P==="jpeg"?"image/jpeg":"application/octet-stream";u.writeHead(200,{"Content-Type":I,"Cache-Control":"public, max-age=3600"}),u.end(m)}catch{M(u,404,{error:"File not found"})}}function pn(a){return`/files/${Yn(a)}`}async function Ns(a,u){let k=await G.getThread(a);if(!k){M(u,404,{error:"Thread not found"});return}let m=k.messages.some(C=>C.role==="assistant"&&C.responseText?.includes("<eval_run_result>")),P=k.messages.filter(C=>C.role==="assistant"&&C.responseText?.includes("Model suggestion ready")),[I,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),P.length>0?V.findModelProposalsByThread(a):Promise.resolve([])]),$=I?await q.findJournalEvalCase(I.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??P[O]?.jobId??P.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),F=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,L=k.messages.map(({screenshotPath:C,screenshotPaths:O,imagePaths:Q,replyImagePaths:U,...ie})=>({...ie,...ie.role==="assistant"&&I&&ie.responseText?.includes("<eval_run_result>")?{evalRun:{...I,title:$?.title}}:{},...C?{screenshotUrl:pn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,re])=>[ae,pn(re)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ae,re])=>[ae,re.map(pn)]))}:{},...U?{replyImageUrls:U.map(pn)}:{}}));M(u,200,{id:k.id,createdAt:k.createdAt,messages:L,modelProposal:F,modelProposals:D})}async function Bs(a,u){let k=decodeURIComponent(a);if(!await G.deleteThread(k)){M(u,404,{deleted:!1,error:"Thread not found"});return}M(u,200,{deleted:!0})}let Uo=9,Ho=!1;for(let a=n;a<n+Uo;a++)try{await ad(xt,a),y=a,Ho=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await no(a);if(sn(k,{projectId:s,version:ot,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Ho)throw new Error(`[Bridge] All ports ${n}\u2013${n+Uo-1} in use`);for(let[a,u]of Object.entries(f))!u.available||!u.path||x(a,u.path).then(k=>{if(k)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),u.available=!1,u.path=null;for(let m of Y)eo(m,{type:"capabilities_changed",data:{}})}});let Ls=setInterval(()=>{xs(d).catch(()=>{})},Qc),Wo=setInterval(()=>{B.expireStale().becameEmpty&&he()},Yc);return Wo.unref?.(),{port:y,projectId:s,close:async()=>{clearInterval(Ls),clearInterval(Wo),ne(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{xt.close(()=>a())})}}}async function xs(o){try{let e=await Lc(o),n=Date.now();for(let t of e){let r=Ee(o,t);try{let s=await zc(r);n-s.mtimeMs>Xc&&await qc(r)}catch{}}}catch{}}import{randomUUID as dd}from"crypto";var ld=5e3,pd=250;function zo(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function Ts(o,e=fetch){let n=`${process.pid}-${dd()}`,t=`http://127.0.0.1:${o.port}`,r=!1,s=!1,i=async()=>(await e(`${t}/leases`,{method:"POST",headers:zo(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await i())return null}catch(h){return console.warn("[popmelt] failed to register bridge lease:",h instanceof Error?h.message:String(h)),null}let d=async()=>{if(!(r||s)){s=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:zo(o)})).status===404&&!r&&await i()}catch{}finally{s=!1}}},c=setInterval(()=>{d()},ld);return c.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(c);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:zo(o),keepalive:!0})}catch{}}}}}function js(o,e=process){let n=!1,t=new Map,r=()=>{if(!n){n=!0;for(let[s,i]of t)e.removeListener(s,i);t.clear()}};for(let s of["SIGINT","SIGTERM"]){let i=()=>{let d=e.listenerCount(s),c=o.release();if(d>0)return;let l=new Promise(h=>{setTimeout(h,pd)});Promise.race([c,l]).finally(()=>{r(),e.kill(e.pid,s)})};t.set(s,i),e.prependOnceListener(s,i)}return r}var bd=1111,Es=3e4,xd=8e3;async function Sd(o){return vd(o).catch(()=>o)}async function Ms(o,e){let t=(await yd(e,"utf8").catch(()=>"")).slice(-xd).trim();return new Error(t?`${o}
238
+ Bridge log (${e}):
239
+ ${t}`:o)}async function wu(o){if(process.env.NODE_ENV==="production"&&!o?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(o?.detached){let n=await Pd(o);if(o.manageLease===!1)return n;let t=await Ts({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let r=js(t);return{...n,close:async()=>{r(),await t.release()}}}let e=await ks(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Pd(o){let e=o.port??bd,n=await Sd(o.projectRoot??process.cwd()),t=Xn(n);for(let R=e;R<e+10;R++){let w=await no(R);if(w&&w.projectId===t){if(w.version&&w.version!==ot){if(w.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${R}/shutdown`,{method:"POST"})}catch{}await new Promise(g=>setTimeout(g,500));break}continue}if(!sn(w,{projectId:t,version:ot,restartMode:"detached"}))continue;let b=o.devOrigin;if(b&&w.devOrigin!==b)try{await fetch(`http://127.0.0.1:${R}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:b})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(R),process.env.POPMELT_PROJECT_ID=t,{port:R,projectId:t,close:async()=>{}}}}let r=qo(wd(Id(import.meta.url)),"bridge-entry.mjs"),s=qo(n,".popmelt"),i=qo(s,"bridge.log");await gd(s,{recursive:!0}),await hd(i,`
240
+ [${new Date().toISOString()}] Starting detached bridge
241
+ `);let d=fd(i,"a"),c;try{c=ud(process.execPath,[r],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{md(d)}let l=null;c.once("error",R=>{l=`spawn error: ${R.message}`}),c.once("exit",(R,w)=>{l=`child exited before becoming healthy (${w?`signal ${w}`:`code ${R??"unknown"}`})`}),c.unref();let h=Date.now()+Es;for(;Date.now()<h;){if(await new Promise(R=>setTimeout(R,100)),l)throw await Ms(`[Bridge] Detached bridge ${l}`,i);for(let R=e;R<e+10;R++){let w=await no(R);if(sn(w,{projectId:t,version:ot,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(R),process.env.POPMELT_PROJECT_ID=t,{port:R,projectId:t,close:async()=>{}}}}throw c.kill("SIGTERM"),await Ms(`[Bridge] Detached bridge failed to start within ${Es/1e3}s (port ${e})`,i)}export{Ot as ImprintService,$t as ImprintStore,Wn as formatImprintPrompt,Hn as parseImprintDraft,wu as startPopmelt};