@popmelt.com/core 0.8.5 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,241 +0,0 @@
1
- import{a as Ho,b as Go}from"./chunk-NOHXTT24.mjs";import{spawn as cd}from"child_process";import{closeSync as dd,openSync as ld}from"fs";import{appendFile as pd,mkdir as ud,readFile as md,realpath as fd}from"fs/promises";import{dirname as hd,join as zo}from"path";import{fileURLToPath as gd}from"url";import{execFileSync as to,spawn as gi}from"child_process";import{createHash as Pi,randomUUID as pt}from"crypto";import{mkdir as Nc,readFile as Lo,readdir as Bc,realpath as Lc,stat as Fc,unlink as zc,writeFile as dn}from"fs/promises";import{createServer as qc}from"http";import{tmpdir as Uc}from"os";import{basename as Yn,dirname as Wc,isAbsolute as Fo,join as Ee,relative as yi,resolve as Ri}from"path";import{fileURLToPath as Hc}from"url";function Vo(o,e){return`<!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>Popmelt Canvas</title>
6
- <link rel="preconnect" href="https://fonts.googleapis.com">
7
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
8
- <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
9
- <style>*{margin:0;padding:0;box-sizing:border-box}html,body,#root{height:100%;overflow:hidden}</style>
10
- </head>
11
- <body>
12
- <div id="root"></div>
13
- <script type="importmap">
14
- {"imports":{
15
- "react":"https://esm.sh/react@19?dev",
16
- "react-dom/client":"https://esm.sh/react-dom@19/client?dev",
17
- "react/jsx-runtime":"https://esm.sh/react@19/jsx-runtime?dev"
18
- }}
19
- </script>
20
- <script type="module">
21
- import { mountCanvas } from 'http://localhost:${o}/canvas/app.mjs';
22
- mountCanvas(document.getElementById('root'), {
23
- devOrigin: '${e}',
24
- bridgeOrigin: 'http://localhost:${o}',
25
- });
26
- </script>
27
- </body>
28
- </html>`}var Fi=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),zi=new Set(["default","flex","fast","priority"]);function ht(o){let e=typeof o.reasoningEffort=="string"&&Fi.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&zi.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 qi}from"child_process";import{createInterface as Ui}from"readline";var Wi=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"]),Ko=1e5;function Hi(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Wi.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>Ko?t.slice(0,Ko)+`
29
- \u2026[truncated]`:t}function mn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:v,timeoutMs:R=3e5,onEvent:w}=e,b=[];d?b.push("--resume",d,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),l&&b.push("--model",l),v&&b.push("--effort",v);for(let g of s)b.push("--allowedTools",g);let h=qi(c,b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(g=>{let f,y=[],x=[],S=[],_=!1,J="",A,N,T=!1,B=setTimeout(()=>{T=!0,h.kill("SIGTERM"),setTimeout(()=>{try{h.kill("SIGKILL")}catch{}},5e3)},R),W=Ui({input:h.stdout}),te=new Set;W.on("line",ne=>{if(ne.trim())try{let oe=JSON.parse(ne);oe.session_id&&!f&&(f=oe.session_id);let he=oe.type??(oe.event?.type?`event.${oe.event.type}`:"unknown");if(te.add(he),oe.type==="result"&&oe.result&&y.length===0){let Y=typeof oe.result=="string"?oe.result:"";Y&&(y.push(Y),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&&(y.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=Hi(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 H=[];h.stderr?.on("data",ne=>{H.push(ne.toString())}),h.on("close",ne=>{if(clearTimeout(B),W.close(),y.length===0&&te.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...te].join(", ")}`),T)_=!0,J=`Timed out after ${Math.round(R/6e4)} minutes`;else if(ne!==0&&ne!==null){_=!0;let he=H.join("").trim(),Y=y.join("").trim(),G=y.length===0&&te.size>0?` (no text captured, event types: ${[...te].join(", ")})`:"";J=he||N||Y||`Claude process exited with code ${ne}${G}`}_&&!J&&N&&(J=N);let oe=Gi(J,A);g({sessionId:f,text:y.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})}),h.on("error",ne=>{clearTimeout(B),_=!0,J=ne.message,g({sessionId:f,text:y.join(""),success:!1,error:J,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})})});return{process:h,result:p}}function Gi(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 Vi,spawnSync as tr}from"child_process";import{readFileSync as Ki,statSync as Qi}from"fs";import{basename as Xi,extname as Yi,isAbsolute as Zi,relative as nr,resolve as es}from"path";import{createInterface as ts}from"readline";function Qo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Xo=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"]),so=2e5,ns=1e5,or=2e5;function rr(o){let e=Xi(o).toLowerCase(),n=Yi(o).toLowerCase();return Xo.has(n)||Xo.has(e)}function Ut(o,e){let n=Zi(e)?e:es(o,e),t=nr(o,n);return t===""||t.startsWith("..")?null:n}function fn(o,e){if(!rr(e))return;let n=Ut(o,e);if(n)try{let t=Qi(n);return t.isFile()?t.size>so?{exists:!0,truncated:!0}:{exists:!0,content:Ki(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function os(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function rs(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 Yo(o){return os(o,["patch","diff","unifiedDiff","unified_diff"])}function ao(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Zo(o,e){let n=tr("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:or+65536});return n.status!==0?null:n.stdout??""}function is(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 i of r)i&&e.add(i)}return[...e]}function er(o){let e=Zo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Zo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=ao(n,or);return{status:e,changedFiles:is(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function ss(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function as(o,e){if(!rr(e))return;let n=Ut(o,e);if(!n)return;let t=nr(o,n);if(t===""||t.startsWith(".."))return;let r=tr("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:so+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=ao(i,so);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function cs(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):as(o,t),i=fn(o,t);return{filePath:t,...r?{before:r}:{},...i?{after:i}:{}}})}function hn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:i,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,v=[];if(i){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let b of l)v.push("-c",b);s&&v.push("-m",s),v.push(i),v.push(n),r&&v.push("--image",r)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let b of l)v.push("-c",b);s&&v.push("-m",s),v.push(n),r&&v.push("--image",r)}let R=Vi("codex",v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),w=new Promise(b=>{let h,p=[],g=[],f=[],y=new Map,x=new Map,S=!1,_="",J=ts({input:R.stdout}),A=new Set;J.on("line",T=>{if(T.trim())try{let B=JSON.parse(T),W=B.type??"unknown";if(A.add(W),W==="thread.started"&&B.thread_id&&!h&&(h=B.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),c?.({type:"delta",jobId:o,text:B.delta.text},o)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&B.delta?.text&&c?.({type:"thinking",jobId:o,text:B.delta.text},o),(W==="item.started"||W==="item/started")&&B.item){let te=B.item.type;if(te==="command_execution"){let H=B.item.command,ne=H?Qo(H):void 0,oe=er(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,{...H?{rawCommand:H}:{},...ne?{command:ne}:{},...oe?{beforeWorktree:oe}:{},beforeSnapshots:he});let Y=ne?`Bash: ${ne.split(`
31
- `)[0].slice(0,80)}`:"Bash";g.push(Y),c?.({type:"tool_use",jobId:o,tool:"Bash",...ne?{content:ne}:{}},o)}else if(te==="file_change"){let H=B.item.filename||B.item.path;H&&!y.has(H)&&y.set(H,fn(t,H)),g.push(H?`Edit ${H.split("/").pop()}`:"Edit");let ne=H?Ut(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...ne?{file:ne}:{}},o)}else if(te==="file_read"){let H=B.item.filename||B.item.path;g.push(H?`Read ${H.split("/").pop()}`:"Read");let ne=H?Ut(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...ne?{file:ne}:{}},o)}else if(te==="web_search")g.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(te==="mcp_tool_call"){let H=B.item.tool_name||B.item.name||"MCP";g.push(H),c?.({type:"tool_use",jobId:o,tool:H},o)}}if((W==="item.completed"||W==="item/completed")&&B.item){if(B.item.type==="agent_message"){let te=B.item.text;typeof te=="string"&&te&&(p.push(te),c?.({type:"delta",jobId:o,text:te},o))}else if(B.item.type==="reasoning"){let te=B.item.text;typeof te=="string"&&te&&c?.({type:"thinking",jobId:o,text:te},o)}else if(B.item.type==="file_change"&&Array.isArray(B.item.changes))for(let te of B.item.changes){let H=te.path||te.filename,ne=te.kind==="add"?"Write":"Edit";if(H){g.push(`${ne} ${H.split("/").pop()}`);let oe=Ut(t,H)??H;c?.({type:"tool_use",jobId:o,tool:ne,file:oe},o);let he=te,Y=typeof he.kind=="string"?he.kind:void 0,G=rs(Y),q=y.get(H),fe=fn(t,H);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:H,...q?{before:q}:{},...fe?{after:fe}:{},...Yo(he)?{patch:Yo(he)}:{},...Y?{rawKind:Y}:{}}),y.set(H,fe)}}else if(B.item.type==="command_execution"){let te=typeof B.item.id=="string"?B.item.id:void 0,H=te?x.get(te):void 0,ne=typeof B.item.command=="string"?B.item.command:H?.rawCommand,oe=ne?Qo(ne):H?.command,he=er(t);if(ss(H?.beforeWorktree,he)){let Y=[...new Set([...H?.beforeWorktree?.changedFiles??[],...he?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?ao(B.item.aggregated_output,ns):void 0,q=typeof B.item.exit_code=="number"?B.item.exit_code:B.item.exit_code===null?null:void 0,fe=typeof B.item.status=="string"?B.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...ne?{rawCommand:ne}:{},...oe?{command:oe}:{},...q!==void 0?{exitCode:q}:{},...fe?{status:fe}:{},...G?{output:G.text}:{},...G?.truncated?{outputTruncated:!0}:{},...H?.beforeWorktree?{beforeWorktree:H.beforeWorktree}:{},...he?{afterWorktree:he}:{},...Y.length>0?{touchedFiles:cs(t,Y,H?.beforeSnapshots??new Map)}:{}})}te&&x.delete(te)}}W==="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:h,text:p.join(""),success:!S,error:S?_:void 0,editEvents:f.length>0?f:void 0,toolsUsed:g.length>0?g:void 0})}),R.on("error",T=>{S=!0,_=T.message,b({sessionId:h,text:p.join(""),success:!1,error:_,editEvents:f.length>0?f:void 0,toolsUsed:g.length>0?g:void 0})})});return{process:R,result:w}}import{spawn as ds}from"child_process";import{createInterface as ls}from"readline";function ir(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:i,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),i&&l.push("--model",i),l.push("-p",n);let v=ds(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(w=>{let b,h=[],p=[],g=!1,f="",y=!1,x=setTimeout(()=>{y=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},s),S=ls({input:v.stdout}),_=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Ht(T);_.add(B),J.length<5&&us(B)&&J.push(N.slice(0,800));let W=Wt(T,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!b&&(b=W);let te=ps(T,h.length===0);te&&(h.push(te),c?.({type:"delta",jobId:o,text:te},o));let H=ms(T);H&&c?.({type:"thinking",jobId:o,text:H},o);let ne=fs(T);ne&&(p.push(ne.label),c?.({type:"tool_use",jobId:o,tool:ne.tool,...ne.file?{file:ne.file}:{},...ne.content?{content:ne.content}:{}},o));let oe=hs(T);oe&&(g=!0,f=oe)}catch{}});let A=[];v.stderr?.on("data",N=>{A.push(N.toString())}),v.on("close",N=>{clearTimeout(x),S.close(),h.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
- `)}`)),y?(g=!0,f=`Timed out after ${Math.round(s/6e4)} minutes`):N!==0&&N!==null&&(g=!0,f=A.join("").trim()||f||`Copilot process exited with code ${N}`);let T=g?ir(f,i):null;w({sessionId:b,text:h.join(""),success:!g,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),v.on("error",N=>{clearTimeout(x);let T=ir(N.message,i);w({sessionId:b,text:h.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:v,result:R}}function Ht(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function ps(o,e=!1){let n=Ht(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return 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 i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.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 us(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function ms(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 fs(o){let e=Wt(o,["tool","toolName","tool_name","name"]),n=Wt(o,["command","cmd"]),t=Wt(o,["file","path","filename","filePath"]),r=Ht(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
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 i=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function hs(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&Ht(o).toLowerCase().includes("error"))return o.message}function Wt(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let i=Wt(r,e);if(i)return i}}function co(o){let e=Ht(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as gs,readFile as ys}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 gs(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await ys(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 cr(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=Rs(t.assertionResults,e),i=ks(r);return{status:i,summary:et(t.summary)||ur(i),assertionResults:r,tooling:Ts(t.tooling)}}catch{}return{status:"needs_review",summary:js(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 dr(o,e){let n=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length?[y.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(y=>y.path),i=[...new Set(r.map(y=>y.map(String).join(".")).filter(Boolean))].map(y=>({kind:"model_path",value:y}));if(i.length===0||o.decisionIds.length===0)return[];let s=new Set(o.decisionIds),c=new Set(i.map(y=>y.value)),d=e.cases.find(y=>y.status!=="rejected"&&(y.sourceDecisionIds.some(x=>s.has(x))||(y.dependencies??[]).some(x=>x.kind==="model_path"&&c.has(x.value)))),l=(o.selectedChanges??[]).find(y=>y.label?.trim())?.label?.trim()??t.find(y=>y.label?.trim())?.label?.trim()??o.title,v=d?.id.startsWith("eval-model-")??!1,R=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length>0?[{path:y.path,value:y.value,label:y.label,detail:y.detail}]:[]),b=(R.length>0?R:t.map(y=>({path:y.path,value:y.value,label:y.label,detail:y.rationale}))).flatMap(y=>vs(y,o.decisionIds)),h=vn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!v?d.assertions:[],...b,...b.length===0&&h?[h]:[]])],g=i[0].value,f=g.startsWith("components.")?"component":g.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!v?d.title:l,status:"pending",category:d?.category??f,prompt:d&&!v?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!v?d.rationale:bs(g),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...i].map(y=>[`${y.kind}:${y.value}`,y])).values()]}]}function vs(o,e){let n=String(o.path[0]??"");if(n==="rules")return ws(o.value,e);if(n==="components"){let s=lr(String(o.path[1]??o.label??"component")),c=yn(o.value),d=c?Vt(c.usage):[];if(d.length>0){let v=xs(d),R=d.length===1?"uses":"use";return[`The ${v} ${R} the same shared implementation for the ${s} pattern.`]}if(c?.shared===!0)return[`The product uses a shared implementation for the ${s} pattern.`];let l=c?et(c.constraint):"";if(l){let v=Is(l,s);if(v)return[v]}}if(n==="tokens"){let s=o.path.slice(1).map(String).join("."),c=yn(o.value),d=c&&"value"in c?c.value:o.value,l=Ss(d);if(s&&l)return[`The ${s} token resolves to ${l}.`]}let t=yn(o.value),r=t?et(t.text)||et(t.constraint):typeof o.value=="string"?o.value:"",i=vn(r||o.detail||"");return i?[i]:[]}function ws(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(s=>{let c=yn(s),d=c?et(c.text):"";return d?[{text:d,sources:c?Vt(c.sources):[]}]:[]}),r=t.filter(s=>s.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(s=>vn(s.text)).filter(s=>!!s)}function Is(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(`${ar(n[1])} is ${Gt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Pt(ar(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Pt(`The product uses ${Gt(r[1])}`);let i=e.match(/^Do not (.+?)\.?$/i);return i?Pt(`The product does not ${Gt(i[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Pt(e)}var vn=po;function bs(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${lr(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 lr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function xs(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 Ss(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 ar(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 pr(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.
34
-
35
- ## Eval
36
- \`\`\`json
37
- ${JSON.stringify(o.evalCase,null,2)}
38
- \`\`\`
39
-
40
- ## Scope
41
- \`\`\`json
42
- ${JSON.stringify(o.scope,null,2)}
43
- \`\`\`
44
-
45
- ## Current Design Model
46
- \`\`\`json
47
- ${JSON.stringify(o.model??null,null,2)}
48
- \`\`\`
49
-
50
- ## Evidence
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"}.
53
-
54
- ## Instructions
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.
65
-
66
- The block must be valid JSON with this shape:
67
-
68
- \`\`\`json
69
- {
70
- "status": "pass",
71
- "summary": "Short run summary.",
72
- "assertionResults": [
73
- {
74
- "assertion": "Original assertion text",
75
- "status": "pass",
76
- "summary": "What was observed.",
77
- "evidence": ["Screenshot shows ...", "DOM selector ..."]
78
- }
79
- ],
80
- "tooling": {
81
- "chromeDevtools": "available",
82
- "evidenceTypes": ["screenshot", "dom", "computed_styles"]
83
- }
84
- }
85
-
86
- \`\`\`
87
-
88
- Allowed statuses: pass, fail, needs_review.
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 Ps(o){let e=et(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Rs(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let i=r,s=et(i.assertion);return s?{assertion:s,status:Ps(i.status)??"needs_review",summary:et(i.summary)||ur("needs_review"),evidence:Vt(i.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 ks(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Ts(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 ur(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 js(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Es}from"crypto";import{mkdir as Ms,writeFile as _s}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=Es("sha256").update(e).digest("hex"),r=uo(n,`${t}.webp`);return await Ms(n,{recursive:!0}),await _s(r,e,{flag:"wx"}).catch(i=>{if(i.code!=="EEXIST")throw i}),r}};import{randomUUID as mr}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 We="[ProjectionWorker]",As={version:1,runs:[]},Cs={version:1,updatedAt:0,proposals:[]},$s=12;function Os(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 fr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function Ds(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Js(o,e,n){let t=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let h of i){if(!h||typeof h!="object")continue;let p=h.sources;if(Array.isArray(p))for(let g of p)typeof g=="string"&&t.has(g)&&r.add(g)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=i.filter(h=>{if(!h||typeof h!="object")return!1;let p=h.id,g=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(g)!==JSON.stringify(h)}).length,v=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},w=Object.keys(s).filter(h=>JSON.stringify(s[h])!==JSON.stringify(v[h])).length,b=Object.keys(c).filter(h=>JSON.stringify(c[h])!==JSON.stringify(R[h])).length;return{ruleCount:l,tokenSectionCount:w,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(h=>!r.has(h))}}function Ns(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Bs(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 i=0;i<e.length-1;i++)t=Bs(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=Ns(n)}function hr(o,e){let n=o;for(let r=0;r<e.length-1;r++){let i=n[String(e[r])];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)]}function Ls(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 Fs(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 gr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Ls(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Fs(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=Os(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?hr(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($s),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 i=r.map(h=>h.id);console.log(`${We} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=Ws(r,s),d=Ds(r,t.totalCandidateDecisionCount,c);n=mr().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:i,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let v=!0,R,w,b;try{let h=`projection-${Date.now()}`,{provider:p,result:g}=this.spawnModelAgent(h,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await g;if(!f.success)v=!1,R=f.error,console.error(`${We} ${p} spawn error:`,R);else{let y=Us(f.text,i);if(y){let x=structuredClone(s??{tokens:{},components:{},rules:[]});for(let J of y)bn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=fr(x.rules));let S=Js(x,i,s);if(y){let J=[...new Set(y.flatMap(A=>A.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=i.filter(A=>!J.includes(A))}w=S;let _=await this.createModelProposal({decisionIds:i,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:w,changes:y});b=_.id,console.log(`${We} Created model proposal ${_.id} for ${i.length} decision(s)`)}else v=!1,R="No valid bounded <model-changes> block found in response",console.error(`${We} ${R}`)}}catch(h){v=!1,R=h instanceof Error?h.message:String(h),console.error(`${We} Error:`,R)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:w,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:v,error:R}),{processedIds:i,success:v,error:R,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=fr(e.rules)),await In(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await mo(ho(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2)),n):{...As,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(i=>i.authorityStatus==="accepted"&&Array.isArray(i.changes)&&i.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Cs,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(t);for(let s of r.changes??[])bn(i,s.path,s.value);return{...r,proposedModel:i}})}}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 i=await this.findModelProposal(e);if(!i)return null;if(i.status==="dismissed")return i;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?hr(s,d.path):bn(s,d.path,d.value));return await this.writeModel(s),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??[]),i=new Map((t.evalProjections??[]).map(s=>[s.evalId,s]));for(let s of n){let c=typeof s=="string"?{evalId:s,title:s,action:"created"}:s;r.add(c.evalId),i.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...i.values()]})}async createModelProposal(e){let n={id:mr().slice(0,8),status:"pending",title:zs(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"}.`:qs(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(i=>i.id!==e?i:(r={...i,...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(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await mo(ho(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await 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 i=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return i==="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:s})}:(i==="copilot"&&console.warn(`${We} 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:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function zs(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 qs(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 Us(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),i=t.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(R=>typeof R=="string"||typeof R=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let v=Array.isArray(d.decisionIds)?d.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===t.length?i:null}catch{return null}}function Ws(o,e){let n=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
90
- Kind: ${i.kind}
91
- Claim: ${i.claim}
92
- ${i.rationale?`Rationale: ${i.rationale}`:""}
93
- Subjects: ${i.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
94
- Authority: ${i.authority.level}/${i.authority.mode}`).join(`
95
-
96
- `),t=o.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
97
-
98
- ## Instructions
99
- 1. Review the current model (if any) and the new decisions below.
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.
104
-
105
- ${e?`## Current Model
106
- \`\`\`json
107
- ${JSON.stringify(e,null,2)}
108
- \`\`\`
109
-
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."}
111
-
112
- ## Accepted Decisions to Project
113
- ${n}
114
-
115
- ## Output Format
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.
125
-
126
- ### Rule format
127
- Each rule is a JSON object:
128
- \`\`\`json
129
- { "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] }
130
- \`\`\`
131
-
132
- Fields:
133
- - \`id\`: 8-character hex string. Preserve IDs for unchanged rules. Generate new IDs for new or merged rules.
134
- - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
135
- - \`text\`: A clear, enforceable design rule
136
- - \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(t)}
137
-
138
- ### Rule guidelines
139
- - **Hard cap: 30 rules maximum.** Merge rules covering the same concern into one.
140
- - **Reject:** workflow advice ("After fixing X, verify Y"), instance-level observations ("The hero section uses 32px gap"), rules that merely restate a token or component already in the model.
141
- - **Keep:** Enforceable patterns, constraints, relationships between elements, accessibility requirements.
142
-
143
- Example:
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>
156
-
157
- ## Guidelines
158
- - Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
159
- - Extract clear, enforceable rules into the \`rules\` array as structured objects.
160
- - Do not silently override conflicting existing values; propose the explicit change for owner review.
161
- - Keep the model concise \u2014 only include patterns with clear evidence from decisions.
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.
164
- - Spacing tokens can be plain strings ("8px") or objects with code bindings:
165
- { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
166
- - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
167
- - bindings: Tailwind class names (without responsive prefixes) that use this token
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 Hs}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,Gs=/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 i=Kt(r.mcpServers);if(i)return kt(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[o];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Kt(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(v=>vo.test(v));return kt(d,"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 s=Kt(r.mcpServers);if(s){let c=await yr(o,s);return kt(s,"mcp.json",c)}}let i=Kt(r);if(i&&i!=="mcpServers"){let s=await yr(o,i);return kt(i,"mcp.json",s)}}return gt()}async function yr(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(i=>i===e)}return!1}var Vs=/^\[mcp_servers\.([^\]]+)\]/;function Ks(o){return o.replace(/^"(.+)"$/,"$1")}function Qs(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function wr(o){let e=o.split(`
169
- `),n=[],t=null;for(let r of e){let i=r.match(Vs);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
170
- `)}),t={name:i[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 Ir(o){return/enabled\s*=\s*false/i.test(o)}async function Io(o){let e=process.env.CODEX_HOME||Le(Rn(),".codex"),n=await vr(Le(e,"config.toml"),"user");if(n.found)return n;let t=await vr(Le(o,".codex","config.toml"),"project");return t.found?t:gt()}async function Xs(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 i=await yo(r,"utf-8");for(let s of wr(i)){if(Qs(s.name)||Ir(s.body))continue;let c=Ks(s.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function br(o){return Xs(o,Gs)}async function bo(o,e="copilot"){let n=await Ys(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 i=await go(Le(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await go(Le(o,".github","mcp.json"),"mcp.json");return s.found?s:gt()}async function Ys(o){try{let e=await new Promise((n,t)=>{Hs(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return xr(JSON.parse(e),"user")}catch{return gt()}}async function go(o,e){let n=await Pn(o);return xr(n,e)}function xr(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 vr(o,e){try{let n=await yo(o,"utf-8"),t=wr(n);for(let r of t)if(vo.test(r.name)){let i=Ir(r.body);return kt(r.name,e,i)}}catch{}return gt()}import{execFile as Sr}from"child_process";import{mkdir as Zs,readFile as Pr,writeFile as Rr}from"fs/promises";import{homedir as kr}from"os";import{dirname as ea,join as xo}from"path";var So="https://mcp.popmelt.com/mcp";async function Tr(o=So){let e=xo(kr(),".claude.json"),n;try{let r=await Pr(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 Rr(e,JSON.stringify(n,null,2)+`
173
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function jr(o=So){let e=process.env.CODEX_HOME||xo(kr(),".codex"),n=xo(e,"config.toml"),t;try{t=await Pr(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Zs(ea(n),{recursive:!0});let r=`
174
- [mcp_servers.popmelt]
175
- url = "${o}"
176
- `;return await Rr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Er(o=So,e="copilot"){let n=await ta(e);if(na(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{Sr(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(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 ta(o){try{let e=await new Promise((n,t)=>{Sr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return JSON.parse(e)}catch{return null}}function na(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),i={id:e,ownerPid:n,createdAt:r?.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,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 oa=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&&!oa.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 ra(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),i=Tn([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(t.has(s.id)){n.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of ra(s)){let l=Po(d.value);for(let w of r){let b=l===w?95:l.includes(w)||w.includes(l)?75:0;b>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:d.by,score:b})}let R=["/","#","[","]","="].some(w=>d.value.includes(w))?0:Math.round(Mr(Tn(l),i)*55);R>=30&&R>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}c&&n.set(s.id,c)}return n}function sa(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let i=new Set(r.map(s=>s.state));return{state:i.size>1?"mixed":i.has("completed")?"completed":"attempted",attemptIds:r.map(s=>s.id)}}function aa(o){return Math.ceil(JSON.stringify(o).length/4)}function Ro(o,e){let n=o.records.filter(g=>g.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(g=>{if(g.recordType!=="proposal"||r&&!r.has(g.id))return!1;if(g.state==="pending")return!0;if(g.state!=="deferred")return!1;let f=[...o.events].reverse().find(y=>y.entity.entityType==="proposal"&&y.entity.entityId===g.id&&y.toState==="deferred"&&y.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),s=o.records.filter(g=>g.recordType==="implementation_attempt"),c=ia(n,e),d=[...c.values()].sort((g,f)=>f.score-g.score),l=Tn([e.action,e.text].filter(Boolean).join(" ")),v=i.flatMap(g=>{let f=g.subjects.map(_=>c.get(_.subjectId)).filter(_=>!!_),y=Math.max(0,...f.map(_=>_.score)),x=Math.round(Mr(Tn(g.claim),l)*35),S=y+x;return S>=50?[{proposal:g,proposalMatches:f,score:S}]:[]}).sort((g,f)=>f.score-g.score||g.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),w=Math.max(200,e.maxEstimatedTokens??1200),b=[],h=0;for(let g of v){if(b.length>=R)break;let f=g.proposal.sourceRefs.slice(0,4),y={contractVersion:1,packetId:`review:${g.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:g.proposalMatches.length?`Historical proposal intersects ${g.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:g.proposalMatches.map(({score:S,..._})=>_)},proposal:{id:g.proposal.id,claim:g.proposal.claim,state:g.proposal.state,proposedKind:g.proposal.proposedKind,subjectIds:g.proposal.subjects.map(S=>S.subjectId),origin:g.proposal.origin.mode},authority:"unaccepted",presentation:g.score>=100&&["constraint","rule"].includes(g.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:sa(g.proposal,s),evidence:{sourceCount:g.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:g.proposal.id},...f]},x={...y,estimatedTokens:aa(y)};if(h+x.estimatedTokens>w)break;b.push(x),h+=x.estimatedTokens}let p=Math.max(0,v.length-b.length);return{packets:b,subjectMatches:d.map(({score:g,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:p,maxEstimatedTokens:w,estimatedTokens:h},uncertainty:c.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var ca=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&&!ca.has(e)))}function _r(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 da(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(ko).filter(Boolean),r=jn([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of o){if(n.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=ko(l.value);for(let b of t){let h=v===b?95:v.includes(b)||b.includes(v)?75:0;h>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:h>=90?"exact":"strong",matchedBy:l.by,score:h})}let w=["/","#","[","]","="].some(b=>l.value.includes(b))?0:Math.round(_r(jn(v),r)*55);w>=30&&w>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:w>=45?"strong":"weak",matchedBy:"semantic",score:w})}c&&i.push(c)}return i.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function la(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 pa(o,e){let n=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(i=>i.state==="completed"),r=t.some(i=>i.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(i=>i.id)}}function ua(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),i=t[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function Ar(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"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(A=>A.recordType==="decision"&&A.state==="active"),c=i?s.filter(A=>i.has(A.id)):s,d=o.records.filter(A=>A.recordType==="implementation_attempt"),l=o.records.filter(A=>A.recordType==="verification_attempt"),v=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),h=da(r,e),p=new Map(h.map(A=>[A.subjectId,A.score])),g=jn([e.action,e.text].filter(Boolean).join(" ")),f=c.flatMap(A=>{let N=Math.max(0,...A.subjects.map(W=>p.get(W.subjectId)??0)),T=Math.round(_r(jn(A.claim),g)*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)),y=new Map;for(let A of f.slice(0,t))y.set(A.decision.id,A.decision);for(let A of o.relationships){if(!Tt(A,"excepts")&&!Tt(A,"contradicts"))continue;let N=s.find(B=>B.id===A.from.entityId),T=s.find(B=>B.id===A.to.entityId);!N||!T||!y.has(N.id)&&!y.has(T.id)||(y.size<t&&y.set(N.id,N),y.size<t&&y.set(T.id,T))}let x=[...y.values()],S=A=>A.from.entityType==="decision"&&A.to.entityType==="decision"&&y.has(A.from.entityId)&&y.has(A.to.entityId),_=(A,N=!1)=>{let T=new Set(A.map(E=>E.id)),B=v.filter(E=>E.target.entityType==="decision"&&T.has(E.target.entityId)),W=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])),H=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(H.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=[];h.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:[]}),H.length&&q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.flatMap(E=>E.expansionRefs)}),oe.some(E=>E.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map(E=>({kind:"record",id:E.id}))}),G&&q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let fe={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:h.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":W.has(E.id)?"excepted":"active",freshness:B.filter(Z=>Z.target.entityId===E.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:E.id}})),conflicts:H,uncertainties:q,implementation:A.map(E=>pa(E.id,d)),verification:A.map(E=>ua(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=la(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 ma=/^[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 ma.test(o)}function fa(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 ha={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"])},ga=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function ya(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=ha[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 i=`${e.entity.entityType}:${e.toState}`;if(ga.has(i)&&(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 s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&ce(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ce(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&dt(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function va(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 wa(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,g)=>{let f=n.get(p);f?ce(e,g,"duplicate_id",`ID is already used at ${f}.`):n.set(p,g)};o.records.forEach((p,g)=>{let f=`records[${g}]`;t(p.id,f),va(e,p,f,o.manifest.projectId)}),o.events.forEach((p,g)=>{let f=`events[${g}]`;t(p.id,f),ya(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,g)=>{let f=`relationships[${g}]`;t(p.id,f),wa(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,g)=>{t(p.id,`artifacts[${g}]`),Te(e,`artifacts[${g}].id`,p.id)}),o.tombstones.forEach((p,g)=>{let f=`tombstones[${g}]`;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}`)),i=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,g)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!i.has(f)&&ce(e,g,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,g)=>s(p.entity,`events[${g}].entity`)),o.relationships.forEach((p,g)=>{s(p.from,`relationships[${g}].from`),s(p.to,`relationships[${g}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,g)=>{c.has(p)||ce(e,g,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,g,f)=>{!r.has(`${p}:${g}`)&&!i.has(`${p}:${g}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,g)=>{let f=`records[${g}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((y,x)=>l("subject",y,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((y,x)=>d(y,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((y,x)=>l("subject",y.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((y,x)=>d(y,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((y,x)=>s(y,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((y,x)=>l("thread",y,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((y,x)=>l("iteration",y,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((y,x)=>{y.kind==="subject"&&y.subjectId&&l("subject",y.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((y,x)=>{y.subjectIds?.forEach((S,_)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${_}]`))}),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`));break;case"model_projection":yt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((y,x)=>l("model_entry",y,`${f}.entryIds[${x}]`)),p.coverage.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":s(p.target,`${f}.target`),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;default:break}});let v=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),w=new Map;o.events.forEach((p,g)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,y=w.get(f)??new Set;y.add(p.toState),w.set(f,y),y.size>1&&ce(e,`events[${g}]`,"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]]:[])),h=(p,g,f,y,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!==g||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&&y.length&&!y.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&h(p.authority,p.acceptedById,p.createdAt,p.subjects.map(g=>g.subjectId),`records:${p.id}.authority`);o.events.forEach((p,g)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),y=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];h(p.authority,p.participantId,p.createdAt,y,`events[${g}].authority`)}),o.relationships.forEach((p,g)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(y=>{let x=R.get(`${y.entityType}:${y.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});h(p.authority,p.participantId,p.createdAt,f,`relationships[${g}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let g=v.get(p.acceptanceEventId);(!g||g.entity.entityType!=="proposal"||g.entity.entityId!==p.proposalId||g.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),g&&g.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(y=>y.relationshipType==="supersedes"&&y.to.entityType==="decision"&&y.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(y=>y.entity.entityType==="decision"&&y.entity.entityId===p.id&&y.toState==="revoked"&&!!y.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return fa(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 Cr(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 Ia(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(i=>i.recordType==="proposal"&&i.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 i of Ia(e))jt(i)||n.push({code:"invalid_generated_id",message:`${i} 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 i={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Cr(o,t,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.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 i={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"}},s={...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."},c={...Qt(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Cr(o,i,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.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:[i,d],events:[s,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...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:[i],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 ba}from"crypto";import{readFile as xa,readdir as Sa,realpath as Pa}from"fs/promises";import{join as Xt,relative as Ra}from"path";var ka=["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 $r(...o){return o.find(e=>!!e?.trim())?.trim()}function ge(o,e,n,t){let i=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=ba("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function jo(o,e){try{return JSON.parse(await xa(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Ta(o){let e=Et(o);if(!e)return 0;let n=0,t=r=>{let i=Et(r);if(!i){n+=1;return}for(let s of Object.values(i))t(s)};for(let r of Object.values(e))t(r);return n}function ja(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 Pa(o.projectRoot).catch(()=>o.projectRoot),t=Xt(n,".popmelt"),r=await jo(Xt(t,"threads.json"),e),i=await jo(Xt(t,"model.json"),e),s=Et(r),c=Et(s?.threads)??{},d=Object.entries(c).map(([E,Z])=>({key:E,value:Et(Z)})).filter(E=>!!E.value),l=Xt(t,"decisions"),v=await Sa(l).catch(()=>[]),R=[];for(let E of v.filter(Z=>Z.endsWith(".json")).sort()){let Z=Et(await jo(Xt(l,E),e));Z&&R.push({file:E,value:Z})}let w=d.flatMap(({value:E})=>[E.createdAt,E.updatedAt]).filter(E=>typeof E=="number"&&Number.isFinite(E)),b=w.length?Math.min(...w):0,h=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(h,"project",h,b),g=ge(h,"participant","legacy-owner",b),f=ge(h,"participant","legacy-agent",b),y=ge(h,"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(h,"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 W=(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)},H=[{...W(g,g,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...W(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...H),S.push({...W(y,g,[]),recordType:"subject",subjectType:"project",label:Ra(process.cwd(),n)||n,aliases:[],locators:[{id:ge(h,"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(h,"subject",E,Z),Me={...W(ke,g,[{kind:"external",id:E}]),createdAt:ze(Z),recordType:"subject",subjectType:"element",label:E,aliases:[],locators:[{id:ge(h,"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 d){let V=Z.id??E,ke=Z.createdAt??b,Me=ge(h,"thread",V,ke),Ie={kind:"thread",id:V},_e=[],Je=[],Bt=Array.isArray(Z.messages)?Z.messages:[],qe,rt,Lt=0;Bt.forEach((ve,it)=>{let Ae=ve.timestamp??ke,Ye=ge(h,"artifact",`${V}:message:${it}`,Ae);if(_e.push(Ye),_.push({id:Ye,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${V}/messages/${it}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${V}/messages/${it}`,Ye),ve.screenshotPath&&B(`${V}:message:${it}:screenshot`,"screenshot",ve.screenshotPath,Ae),ve.role==="human"){qe=ve;let Ne=ve.feedbackSummary??ve.replyToQuestion;if(Ne?.trim()){let Be=ge(h,"observation",`${V}:${it}`,Ae),ct=Z.elementIdentifiers??[],St={...W(Be,g,[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 st=ve.jobId??`${V}:${it}`,at=ge(h,"iteration",st,Ae),ut=N.get(st),Ft=ve.cancelled?"cancelled":ve.error?"failed":ve.question?"question_asked":(ve.resolutions?.length??0)>0?"completed":"no_change",ro={...W(at,f,[Ie,{kind:"message",id:Ye},...(T.get(st)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:ze(Ae),recordType:"iteration",threadIds:[Me],startedAt:ze(qe?.timestamp,Ae),completedAt:ze(Ae),requestSummary:$r(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(st)??[]]};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?y:oe(ln,ke),role:"governed"})),mt=ge(h,"proposal",`${st}:${Be.annotationId??"resolution"}:${Ne}`,Ae),io={...W(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:$r(qe?.feedbackSummary,qe?.replyToQuestion,Be.summary),iterationId:at,inferredById:f}};te(V,io),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(h,"implementation",st,Ae),Be={...W(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={...W(Me,g,[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=Ta(i);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??ka).map(E=>({legacyId:E,threadFound:d.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:d.length,messages:d.reduce((E,Z)=>E+(Z.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:he,artifactsReferenced:_.length},imported:ja(S),unresolvedAcceptance:e.filter(E=>E.code==="acceptance_unresolved").length,deferredModelEntries:he,proofCases:fe,issues:e,schemaIssues:G.issues}}}import{createHash as Ea}from"crypto";import{mkdir as Or,open as Eo,readFile as Mo,readdir as Ma,rename as _a,unlink as _o}from"fs/promises";import{join as tt}from"path";var Aa={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function _n(o){return Ea("sha256").update(JSON.stringify(o)).digest("hex")}function Dr(o){return _n(o)}function Jr(o,e,n){for(let t of e.projectionUpdates){let r=o.records.find(i=>i.recordType===t.entityType&&i.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 Ca(o,e,n){return Jr(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 _a(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 Or(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(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=_n(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},i={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,i)})}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,i={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...i,hash:Dr(i)},c=Ca(t.bundle,e,n.committedAt),d=vt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await wt(tt(this.journalDir,l),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await wt(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Aa,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await 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 Ma(this.journalDir),r=t.filter(w=>w.endsWith(".tmp")),s=t.filter(w=>/^\d{12}-[0-9a-f-]+\.json$/i.test(w)).sort().filter(w=>Number(w.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,v=new Set;for(let w of s){let b=await Mn(tt(this.journalDir,w)),{hash:h,...p}=b;if(h!==Dr(p))throw new Error(`Journal hash mismatch: ${w}`);if(b.sequence!==d+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(v.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);Jr(c,b.mutation,b.committedAt),d=b.sequence,l=b.hash,v.add(b.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=vt(c);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:c,manifest:e,transactionIds:v,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Or(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(()=>({})),i=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(s){i=s.code!=="ESRCH"}if(i)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 $a}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=$a(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 Oa=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Nr(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,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Oa(),l=d.records,v=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));v||(v={id:ge(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(x=>x.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(v));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(_=>_.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:s,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:s,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:s,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:s,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",i,e.createdAt);let x={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,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 h=ge(r,"live-iteration",i,e.completedAt),p={id:h,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[v.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let g=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),y=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(w.length>0&&y.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",`${i}:${x}`,e.completedAt),J=y.map(N=>({subjectId:N.id,role:"governed"})),A={id:_,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:h},{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:h,inferredById:t.id}};l.push(A),g.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",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:h}],recordType:"implementation_attempt",state:"completed",iterationIds:[h],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:h}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(_)}return{mutation:d,iterationId:h,proposalIds:g,observationId:b}}import{createHash as Da}from"crypto";import{mkdir as Ja,open as Na,readFile as Ba,rename as La,unlink as Fa}from"fs/promises";import{join as Br}from"path";function Lr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Fr(o){return Da("sha256").update(JSON.stringify(o)).digest("hex")}async function za(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Na(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
- `,"utf8"),await t.sync()}finally{await t.close()}try{await La(n,o)}catch(r){throw await Fa(n).catch(()=>{}),r}}function qa(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,l,v)=>{let R=d[l]??=[];R.includes(v)||R.push(v)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Lr(v);R&&s(t,R,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...c,checksum:Fr(c)}}function zr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Lr(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=Br(e,".popmelt","memory","indexes"),this.indexPath=Br(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Ba(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&i===Fr(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=qa(e,n);return await Ja(this.indexDir,{recursive:!0}),await za(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 i=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,specs:i.specs??0,runs:i.runs??0}}catch{}let t=[],r=[];try{let i=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(i.cases)?i.cases:[]}catch{}try{let i=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(i.runs)?i.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 i=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,explanations:i.explanations??0,evidence:i.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 i of t.explanations){let s=i.evidence.length?i.evidence:[{id:i.id,kind:"observation",stance:"supports",summary:i.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:i.createdAt}];for(let c of s){let d=c.kind==="confirmation"?"confirm":c.kind==="correction"||c.kind==="rejection"?"reason_wrong":c.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:c.id,kind:d?"strengthened":"added",title:i.statement.slice(0,120),detail:c.summary,changes:[{explanationId:i.id,action:d==="reason_wrong"?"challenged":"supported",statement:i.statement,state:i.state}]},threadId:c.threadId,jobId:c.jobId,action:d,occurredAt:c.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:Ar(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 i=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(i),i}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 i=Date.now(),s=new Date(i).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:le(i),decisionId:le(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:le(i),replacementProposalId:le(i),acceptanceEventId:le(i),decisionId:le(i),relationshipId:le(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:le(i),reason:e.reason}:{...c,action:"defer",eventId:le(i),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,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(w=>w.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:le(i),committedAt:s});await this.refreshIndex(v);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:v.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Nr(n.bundle,e),r=ge(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw i}}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"),i=e.action?t:r??t,s=n.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!i||!s)return;let c=e.occurredAt??new Date().toISOString(),d=Date.parse(c),l=[],v=[];for(let w of e.summary.changes){let b={kind:"external",id:w.explanationId,uri:"popmelt:imprint"},h=n.bundle.records.find(g=>g.recordType==="observation"&&g.sourceRefs.some(f=>f.kind==="external"&&f.id===w.explanationId&&f.uri==="popmelt:imprint"));h||(h={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:w.statement,captureContext:{subjectIds:[s.id],artifactIds:[]},resolvedByIds:[]},l.push(h));let p={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.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),v.push({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[b],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:h.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"}`,d);try{let w=await this.store.commit({records:l,events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:c});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(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.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(i=>i.recordType==="model_entry").sort((i,s)=>i.createdAt.localeCompare(s.createdAt)))r.decisionIds.some(i=>n.has(i))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let r=[...t.values()],i=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=i.filter(l=>l.targets.some(v=>v.entityType==="decision"&&v.entityId===c.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="decision"&&e.includes(i.id)?i.subjects.map(s=>s.subjectId):[])),r=[];for(let i of n.records)if(!(i.recordType!=="subject"||!t.has(i.id)))for(let s of i.locators.filter(c=>c.status==="current"))s.kind==="source_file"?r.push({kind:"source_file",value:s.value,subjectId:i.id}):s.kind==="route_pattern"?r.push({kind:"route",value:s.value,subjectId:i.id}):s.kind==="token_path"?r.push({kind:"model_path",value:s.value,subjectId:i.id}):(s.kind==="dom_selector"||s.kind==="file_export"||s.kind==="source_span")&&r.push({kind:"subject",value:s.value,subjectId:i.id});return[...new Map(r.map(i=>[`${i.kind}:${i.value}:${i.subjectId??""}`,i])).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 i=Date.now(),s=new Date(i).toISOString(),c=le(i),d=le(i),l=le(i),v=le(i),R=le(i),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)),h={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],g={...h,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...h,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},y={...h,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:s},x={...h,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...h,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[v],coverage:[{decisionId:l,status:"projected"}]},_={...h,id:le(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=b.map(T=>({...h,id:le(i),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=>({...h,id:le(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:y.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[g,y,x,S],events:[f,...J],relationships:[_,...A],artifacts:[],tombstones:[],projectionUpdates:b.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(i),committedAt:s});return await this.refreshIndex(N),{decisionId:l,entryId:v}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),i=n.bundle.records.flatMap(h=>h.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===h.id||h.sourceRefs.some(g=>g.id===p))?[h.id]:[]),s=[...new Set(n.bundle.records.flatMap(h=>h.recordType==="decision"&&i.includes(h.id)?h.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:i,subjectIds:s,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active");if(!l)throw new Error("No active local owner participant is available.");let v=Date.now(),R=new Date(v).toISOString(),w={id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...i.map(h=>({kind:"record",id:h}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:i.map(h=>({entityType:"decision",entityId:h})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},b=r?[{id:le(v),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(v),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(s=>s.objectType==="eval_spec").map(s=>s.objectId)),t=e.records.filter(s=>s.recordType==="eval_spec").reverse().filter((s,c,d)=>d.findIndex(l=>l.legacyId===s.legacyId)===c).filter(s=>!n.has(s.id)),r=e.records.filter(s=>s.recordType==="verification_attempt"),i=e.records.filter(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.targetKind==="verification_result");return t.map(s=>{let c=r.filter(v=>v.evalSpecId===s.id).sort((v,R)=>R.createdAt.localeCompare(v.createdAt))[0],d=c&&i.some(v=>v.target.entityType==="verification_attempt"&&v.target.entityId===c.id),l=s.state==="draft"?"draft":s.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:s.legacyId,canonicalSpecId:s.id,verificationState:l,title:s.title,status:s.state==="draft"?"pending":s.state==="active"?"approved":"rejected",category:s.category,prompt:s.prompt,assertions:s.assertions,rationale:s.rationale,sourceDecisionIds:s.decisionIds,sourceThreadIds:s.threadRefs,dependencies:s.dependencies??[],scenarios:s.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let i=t.evalRun,s=Date.parse(t.createdAt);return[{id:i?.id??t.id,evalId:r.legacyId,threadId:i?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:i?.createdAt??s,completedAt:i?.completedAt??s,durationMs:i?.durationMs??0,scope:i?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:i?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:i?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:i?.provider,model:i?.model,screenshotPath:i?.screenshotPath,codeFingerprint:i?.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 i=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(!i)return;let s=n.completedAt,c=new Date(s).toISOString(),d={id:le(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.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(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.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:i.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},v=r.targets.map(w=>({id:le(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:w,reason:n.summary})),R=await this.store.commit({records:[d,l],events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:c});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((i,s)=>i.completedAt-s.completedAt)){let i=t.get(r.evalId);i&&await this.recordEvalVerification(i,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 i=Date.now(),s=new Date(i).toISOString(),c={id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:s});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),r=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),i=e.filter(d=>!r.includes(d)).map(d=>d.id);if(i.length===0)return{valid:r,discardedIds:i};let s=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!s)return{valid:r,discardedIds:i};let c=i.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(v=>({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:v.id,objectType:"eval_spec",deletedAt:l,deletedById:s.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:i}}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(i=>i.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(h=>h.recordType==="model_projection"&&h.state==="applied"&&h.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(h=>h.recordType==="decision"&&e.decisionIds.includes(h.id)&&h.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=n.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=le(s),l=e.changes.map(h=>{let p=h.decisionIds?.filter(y=>e.decisionIds.includes(y)),g=p?.length?p:e.decisionIds,f=[...new Set(r.filter(y=>g.includes(y.id)).flatMap(y=>y.subjects.map(x=>x.subjectId)))];return{id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:g.map(y=>({kind:"record",id:y})),recordType:"model_entry",key:h.path.map(String).join("."),subjectIds:f,decisionIds:g,value:h.value}}),v=new Set(l.flatMap(h=>h.decisionIds)),R={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:e.decisionIds.map(h=>({kind:"record",id:h})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(h=>h.id),coverage:e.decisionIds.map(h=>e.coverage?.find(p=>p.decisionId===h)??{decisionId:h,status:v.has(h)?"projected":"unprojected"})},w=l.flatMap(h=>h.decisionIds.map(p=>({id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h.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(s),committedAt:c});return await this.refreshIndex(b),{projectionId:d,entryIds:l.map(h=>h.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=zr(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,i=_t(t,"authority.level",["owner","delegate","contributor"]),s=_t(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:_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{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=At(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>_t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId: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(d=>{let l=At(d);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=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(c=>Se(c,s))}},t=(i,s)=>{if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<=0)throw new Error(`${s} must be a positive number.`);return i}},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 qr(o,e,n,t){let r=On(e);if(!(!r&&n.length===0))try{let i=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(i.actionPacket.decisions.length===0&&i.reviewSelection.packets.length===0)return;let s=new Map(i.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(i.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:i.source,...i.actionPacket.decisions.length>0?{acceptedTruth:{decisions:i.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:i.actionPacket.conflicts,truncated:i.actionPacket.completeness.status==="truncated"}}:{},packets:i.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:i.reviewSelection.completeness.status==="truncated",estimatedTokens:i.actionPacket.budget.estimatedTokens+i.reviewSelection.completeness.estimatedTokens}}catch(i){t?.(i);return}}function Ur(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 Wr(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 i=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&i.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}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 Ua(o),i=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,l,v,R,w,b,h,p,g,f,y,x,S,_=[],J=[],A=0,N=[];for(;A<r.length;){let T=r.indexOf(i,A);if(T===-1)break;let B=T+i.length;if(r.slice(T,T+s.length).equals(s))break;let W=B;r[W]===13&&r[W+1]===10&&(W+=2);let te=r.indexOf(`\r
181
- \r
182
- `,W);if(te===-1)break;let H=r.slice(W,te).toString("utf-8"),ne=te+4,oe=r.indexOf(i,ne),he=oe!==-1?oe-2:r.length;N.push({headers:H,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 W=B[1];if(W==="screenshot")c=T.body;else if(W==="feedback")d=T.body.toString("utf-8");else if(W==="color")l=T.body.toString("utf-8");else if(W==="provider")v=T.body.toString("utf-8");else if(W==="model")R=T.body.toString("utf-8");else if(W==="reasoningEffort")w=T.body.toString("utf-8");else if(W==="serviceTier")b=T.body.toString("utf-8");else if(W==="goal")h=T.body.toString("utf-8");else if(W==="pageUrl")p=T.body.toString("utf-8");else if(W==="viewport")g=T.body.toString("utf-8");else if(W==="planId")f=T.body.toString("utf-8");else if(W==="manifest")y=T.body.toString("utf-8");else if(W==="tasks")x=T.body.toString("utf-8");else if(W==="sourceId")S=T.body.toString("utf-8");else if(W.startsWith("screenshot-")){let te=W.slice(11);try{let H=decodeURIComponent(te);J.push({pathname:H,data:T.body})}catch{}}else if(W.startsWith("image-")){let te=W.split("-"),H=parseInt(te[te.length-1],10),ne=te.slice(1,-1).join("-");ne&&!isNaN(H)&&_.push({annotationId:ne,index:H,data:T.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:v,model:R,reasoningEffort:w,serviceTier:b,goal:h,pageUrl:p,viewport:g,planId:f,manifest:y,tasks:x,sourceId:S,pastedImages:_,pageScreenshots:J}}function Ua(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 Ha=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,Ga=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Va=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 Ka(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Gr(o,e,n,t=Date.now()){let r=Ka(o);if(!r)return null;let i=typeof r.transition=="string"&&Ga.has(r.transition)?r.transition:null,s=Zt(r.focus);if(!i||!s)return null;let c=typeof r.evidencePosture=="string"&&Va.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Wa(),jobId:e,sequence:n,timestamp:t,transition:i,snapshot:{focus:s,seeking:Zt(r.seeking),workingHypothesis:Zt(r.workingHypothesis),evidencePosture:c,update:Zt(r.update),nextObservation:Zt(r.nextObservation)},contextPolicy:"exclude"}}function Do(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Qa(o,e,n=0){let t=[],r=new Set,i=n;return{visibleText:o.replace(Ha,(c,d)=>{try{let l=Gr(JSON.parse(d),e,i);if(!l)return"";let v=Do(l);if(r.has(v))return"";r.add(v),t.push(l),i++}catch{}return""}).replace(/\n{3,}/g,`
183
-
184
- `).trim(),orientations:t}}function Xa(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 c=Xa(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,r);let i=this.buffer.indexOf("</orientation>",r+13);if(i<0){this.buffer=this.buffer.slice(r);break}let s=this.buffer.slice(r+13,i).trim();this.buffer=this.buffer.slice(i+14);try{let c=Gr(JSON.parse(s),this.jobId,this.sequence);if(!c)continue;let d=Do(c);if(this.signatures.has(d))continue;this.signatures.add(d),t.push(c),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=Qa(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let i=Do(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Vr=`## 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(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${r||"none"}`);let s=e?.[t.id];if(s&&s.length>0)for(let c of s)n.push(` Attached image: use the Read tool to view ${c}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${r}: ${i.property} ${i.original} \u2192 ${i.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})`:"",i=JSON.stringify(t.original),s=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${c}: ${i} \u2192 ${s}`)}}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})`:"",i=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",s=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${i} \u2192 ${t.targetParentSelector}${s}`)}}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 i=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${i}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${i}: ${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 Kr(o,e,n){let t=[],i=new Set(e.annotations.map(s=>s.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: ${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 s=0;for(let c of n.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(t.push(`### Round ${s} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${s} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${s} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${s} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,v=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${v} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=n.designModel.rules;if(Array.isArray(s)&&s.length>0)if(t.push(""),t.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let v=new Map;for(let R of s)if(typeof R=="object"&&R!==null&&"text"in R){let w=R,b=w.scope||"general";v.has(b)||v.set(b,[]),v.get(b).push(w.text)}for(let[R,w]of v){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let b of w)t.push(`- ${b}`)}}else for(let v of s)typeof v=="string"&&t.push(`- ${v}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;c.has(l)||c.set(l,[]),c.get(l).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of c){t.push(""),t.push(`## Page: ${d}`);let v=s[d];v&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&n?.provider!=="codex"&&(Object.keys(s).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 s=en(e,n?.imagePaths);s&&(t.push(""),t.push(s))}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 Qr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Xr(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 i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${c.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),c.feedbackSummary&&r.push(`Annotations: ${c.feedbackSummary}`))):c.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${c.question}"`)):(r.push(`### Round ${s} (assistant)`),c.responseText&&r.push(`Response: ${c.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of t)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}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 Ya(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 Za(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&&!Ya(e[n]))return!1;return!0}function Yr(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(Za):[]}catch{return[]}}function Zr(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 ec}from"child_process";import{readdir as tc,readFile as nc,stat as oc}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:ei()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:ei()}],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"},rc=/^\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(rc);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Jo(i),source:"cli"})}return Ln([on,...e])}function sc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,r)=>{let i=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(t=>{let r=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!r)return[];let i=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Jo(r),s=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function ei(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function ac(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 i=t[1]==="sonnet"?"Sonn":pc(t[1]),s=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${s}${t[4]?" Fast":""}`}let r=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let i=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${i}`:r[3]==="codex"?`Codex ${i}`:r[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function ti(o="copilot"){let e=await Nn(o,["help","config"]),n=ic(e);return n.length>1?n:[on]}async function ni(o="codex"){let e=await Nn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(tn(),".codex");return ri(Qe(t,"models_cache.json"))}),n=sc(e);return n.length>0?Ln([...n,...nn]):nn}async function oi(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,i]=await Promise.all([Nn(o,["--help"]).catch(()=>""),Nn(o,["--version"]).catch(()=>""),cc(e).catch(()=>[])]),s=lc([...n,...i]),c=await Promise.all(s.map(l=>ri(l).catch(()=>""))),d=ac([t,r,...c].join(`
197
- `));return Ln([...Bn,...d])}function Nn(o,e,n=5e3){return new Promise((t,r)=>{ec(o,e,{encoding:"utf-8",timeout:n},(i,s)=>{if(i){r(i);return}t(s)})})}async function ri(o){return nc(o,"utf-8")}async function cc(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await ii(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function ii(o,e,n){if(n<0)return;let t;try{t=await tc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let i=Qe(o,r.name);if(r.isDirectory()){await ii(i,e,n-1);return}if(!(!r.isFile()||!dc(r.name)))try{let s=await oc(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function dc(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 lc(o){return[...new Set(o)]}function pc(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 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,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 i of this.listeners)i(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:""},i=this.activeJobs.has(e);if(!t)return null;let s=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:s,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:i}}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 i=!1,s=()=>{i||(i=!0,r())};t.on("exit",s),t.on("error",s),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as He}from"crypto";import{createHash as uc}from"crypto";import{mkdir as mc,open as fc,readFile as si,readdir as hc,rename as gc,unlink as yc}from"fs/promises";import{dirname as vc,join as Ct}from"path";function Oe(o){return structuredClone(o)}function ai(o){return uc("sha256").update(JSON.stringify(o)).digest("hex")}async function rn(o,e){await mc(vc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await fc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
198
- `,"utf8"),await t.sync()}finally{await t.close()}try{await gc(n,o)}catch(r){throw await yc(n).catch(()=>{}),r}}function wc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Ic(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")Ic(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(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(i=>i.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(i=>i.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(s=>s.id===t.relation.fromId),i=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!r||!i)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(s=>s.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 bc(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 i=t.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:Oe(i)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=t.concrete.find(s=>s.id===r.concreteId);i&&n.unshift({op:"add_concrete",concrete:Oe(i)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let i=r.op==="replace_explanation"?r.explanation.id:r.explanationId,s=t.explanations.find(c=>c.id===i);s&&n.unshift({op:"replace_explanation",explanation:Oe(s)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=t.relations.find(s=>s.id===r.relationId);i&&n.unshift({op:"add_relation",relation:Oe(i)})}t=zn(t,[r])}return n}function ci(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 si(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 hc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=wc(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await si(Ct(this.journalDir,t[c]),"utf8")),{hash:l,...v}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==ai(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=zn(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},i.push(d),s=d.hash}return{graph:r,transactions:i,recoveredTransactions:Math.max(0,i.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,i=bc(t.graph,e.mutations),s={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:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:ai(s)},d=zn(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await rn(Ct(this.journalDir,l),c);let v={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await rn(this.graphPath,d),await rn(this.manifestPath,v),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(ci));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(v=>ci(v).some(R=>c.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.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 xc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Sc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Pc(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(Pc(o).split(" ").filter(e=>e.length>2&&!Sc.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:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function di(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 Rc(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 Wn(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(!xc.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 i=r.summary,s=i?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:je(i?.title,120),detail:je(i?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(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 h=je(b.statement),p=je(b.rationale);if(!h||!p)continue;l.push({op:"add",clientId:je(b.clientId,100)||void 0,kind:b.kind,statement:h,rationale:p,scope:di(b.scope)})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let h={op:"revise",explanationId:b.explanationId,statement:je(b.statement)||void 0,rationale:je(b.rationale)||void 0,scope:di(b.scope),reopenGrounding:b.reopenGrounding===!0};(h.statement||h.rationale||h.scope||h.reopenGrounding)&&l.push(h)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let h=je(b.summary);h&&l.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:h})}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 h=je(b.reason);h&&l.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:h})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let h=je(b.modelPath,300);h&&l.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:h,rationale:je(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&l.push({op:"retire",explanationId:b.explanationId,reason:je(b.reason)})}let v=r.grounding,R=v&&typeof v.explanationId=="string"&&je(v.question)?{explanationId:v.explanationId,question:je(v.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Hn(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(i=>` - Concrete terminal: ${i.modelPath} = ${JSON.stringify(i.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:i}=await this.store.load(),s=i.explanations.filter(d=>d.state!=="retired"&&d.state!=="challenged").map(d=>{let l=qn([d.statement,d.rationale].join(" ")),v=qn(d.scope.values.join(" ")),R=Un(l,n),w=Un(v,n),b=Un(v,t),h=Un(l,t),p=R+w*.2+b*.25+h*.1+(d.state==="grounded"?.08:0)+(r.has(d.id)?1:0),g=r.has(d.id)||(n.size?R>=.12||w>=.5:b>=.2||h>=.2);return{item:d,score:p,relevant:g}}).filter(d=>d.relevant&&d.score>=.18).sort((d,l)=>l.score-d.score||l.item.updatedAt.localeCompare(d.item.updatedAt)),c=Math.max(1,e.maxExplanations??4);if(s.length)return{explanations:s.slice(0,c).map(({item:d})=>{let l=new Set(i.relations.filter(v=>v.fromId===d.id&&v.type==="instantiates").map(v=>v.toId));return{id:d.id,kind:d.kind,statement:d.statement,rationale:d.rationale,scope:d.scope,state:d.state,concrete:i.concrete.filter(v=>l.has(v.id)).map(v=>({id:v.id,modelPath:v.modelPath,value:v.value}))}}),truncated:s.length>c,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),i=new Map(r.graph.explanations.map(S=>[S.id,S])),s=new Map,c=new Map,d=[],l=new Set,v=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let _=He();S.clientId&&s.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)]};i.set(_,A),l.add(_),d.push({op:"add_explanation",explanation:A})}let R=S=>s.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let _=R(S.explanationId),J=i.get(_);if(J?.state!=="grounded")continue;let A=He(),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)]};i.set(A,N),c.set(_,A),l.add(A),d.push({op:"add_explanation",explanation:N}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:A,toId:_,rationale:S.rationale??e.summary.detail,createdAt:t}})}let w=S=>{let _=R(S);return c.get(_)??_};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=w(S.explanationId);if(!i.has(J))continue;let A=Rc(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:He(),modelPath:S.modelPath,value:structuredClone(A.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:N})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=w(S.fromId),A=w(S.toId);if(!i.has(J)||!i.has(A)||J===A)continue;d.push({op:"add_relation",relation:{id:He(),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(!i.has(J)||!i.has(A)||J===A)continue;d.push({op:"add_evidence",explanationId:J,evidence:nt(n,"challenges",S.reason)}),d.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:A},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"contradicts",fromId:A,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(A);continue}let _=w(S.explanationId);if(i.has(_))if(l.add(_),S.op==="revise"){if(c.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:No(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:_,patch:J,updatedAt:t})}else S.op==="evidence"?(d.push({op:"add_evidence",explanationId:_,evidence:nt(n,S.stance,S.summary)}),S.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:_,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(d.push({op:"add_evidence",explanationId:_,evidence:nt(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:_,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let _=w(S),J=i.get(_);!J||J.state==="grounded"||J.state==="retired"||v.has(_)&&!l.has(_)||(l.has(_)||(l.add(_),d.push({op:"add_evidence",explanationId:_,evidence:{...nt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&d.push({op:"revise_explanation",explanationId:_,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let b=He(),h=await this.store.commit({transactionId:b,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),p=new Map(h.graph.explanations.map(S=>[S.id,S])),g=[...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,y=f?p.get(f):void 0,x=y?.state==="testing"&&!v.has(y.id)?{explanationId:y.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:b,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:g,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let v of l)await this.store.undo(v,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${i.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${i.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(v=>v.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:i.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${i.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${i.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:s,summary:d,mutations:c})}};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 li(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 pi(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),i=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Vn}from"crypto";import{mkdir as an,readFile as It,unlink as jc,writeFile as Jt}from"fs/promises";import{dirname as Kn,extname as Ec,join as De}from"path";var kc={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 Tc(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 ui(o,e){let n=e??Tc(o);return{kind:n,...kc[n]}}function Dt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function mi(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Mc={version:1,threads:{}},fi=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],cn={version:2,updatedAt:0,files:{}};function _c(o){return JSON.stringify(o,null,2)}function Ac(o){return Object.fromEntries(fi.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Cc(o){let e={...o};for(let n of fi)delete e[n];return e}function Nt(o){let e=o;if(o.error){let n=ui(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 i=await this.readThread(De(this.threadsDir,r));i&&(n[t]=i)}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={...Mc,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(s=>t.has(s)))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 i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,Nt(n)):r.messages.push(Nt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=Nt(c);Object.assign(c,d),delete c.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of n)i.has(s)||r.elementIdentifiers.push(s);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,i)=>i.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let s=r.messages.find(g=>g.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(g=>g.role==="assistant"),d=g=>{if(g.role!=="assistant")return;if(g.question)return g.question;let f=g.imprintSummary?.grounding;if(f?.question&&!g.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(g=>!!d(g)),v=r.messages.findLastIndex(g=>g.role==="human"),R=l>v?d(r.messages[l]):void 0,w=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,v)).filter(g=>g.role==="assistant"&&!!g.jobId).map(g=>g.jobId))),h=c.some(g=>!!g.responseText||!!g.question||!!g.result||!!g.memoryReviewCard||!!g.memoryReceipt),p=c.some(g=>!!g.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:h,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,...i})=>{let s={};if(r?.path)try{let c=await It(De(Kn(this.legacyFilePath),r.path),"utf8");Vn("sha256").update(c).digest("hex")===r.sha256&&(s=JSON.parse(c))}catch{}return Nt({...i,...s})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Ac(e),t=Cc(e);if(Object.keys(n).length===0)return t;let r=_c(n),i=Vn("sha256").update(r).digest("hex"),s=De("artifacts","thread-messages",`${i}.json`);await an(this.artifactsDir,{recursive:!0});try{await It(De(Kn(this.legacyFilePath),s),"utf8")}catch{await Jt(De(Kn(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(Kn(t)===this.mediaDir)return t;try{let r=await It(t),i=Vn("sha256").update(r).digest("hex"),s=De(this.mediaDir,`${i}${Ec(t)||".bin"}`);await an(this.mediaDir,{recursive:!0});try{await It(s)}catch{await Jt(s,r)}return s}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(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await Jt(De(this.threadsDir,t),JSON.stringify(i,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 jc(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 Oc(o).slice(0,12)}var $c=[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 Oc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Dc(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,i=1013904242,s=2773480762,c=1359893119,d=2600822924,l=528734635,v=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,h=r,p=i,g=s,f=c,y=d,x=l,S=v;for(let _=0;_<64;_++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),A=f&y^~f&x,N=S+J+A+$c[_]+R[_]>>>0,T=Xe(b,2)^Xe(b,13)^Xe(b,22),B=b&h^b&p^h&p,W=T+B>>>0;S=x,x=y,y=f,f=g+N>>>0,g=p,p=h,h=b,b=N+W>>>0}t=t+b>>>0,r=r+h>>>0,i=i+p>>>0,s=s+g>>>0,c=c+f>>>0,d=d+y>>>0,l=l+x>>>0,v=v+S>>>0}return[t,r,i,s,c,d,l,v].map(w=>w.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Dc(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 hi={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=hi.version;var Gc=1111,Vc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Kc=1800*1e3,Qc=3600*1e3,vi=45e3,Xc=5e3,Yc=1e4;function wi(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 Zc(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 ki(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 ed(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let i=n[n.length-1];i&&i.kind==="text"?i.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",i=t.file??void 0,s=t.content??void 0,c=i?i.split("/").pop()??i:void 0,d;switch(r){case"Read":d=c?`Reading ${c}`:"Reading file";break;case"Edit":d=c?`Editing ${c}`:"Editing file";break;case"Write":d=c?`Writing ${c}`:"Writing file";break;case"Bash":d=s?s.split(`
202
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let l=i??s??void 0,v=i?Fo(i)?i:Ri(e,i):void 0,R=n[n.length-1];R&&R.kind==="tool_group"&&R.tool===r?R.items.push({label:d,detail:l,...v?{filePath:v}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...v?{filePath:v}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function td(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 nd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Ii(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),t=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),i=[...e,...t,...n,...r].map(s=>nd(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function od(o,e){let n=o.headers.origin;ki(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 i=typeof r=="string"?Buffer.from(r):r;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 rd(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,i]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function eo(o,e){try{o.res.write(`event: ${e.type}
204
- data: ${JSON.stringify(e)}
205
-
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 sd(o,e){return new Promise((n,t)=>{let r=s=>{o.removeListener("listening",i),t(s)},i=()=>{o.removeListener("error",r),n()};o.once("error",r),o.once("listening",i),o.listen(e,"127.0.0.1")})}function bi(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 Pi("sha256").update(`${e}
207
- ${t}
208
- ${r}`).digest("hex").slice(0,16)}catch{return}}function ad(o,e){let n=o;for(let t of e.split(".").filter(Boolean)){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[t]}return n}async function xi(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let i of[...t].sort((s,c)=>`${s.kind}:${s.value}`.localeCompare(`${c.kind}:${c.value}`)))if(i.kind==="model_path")r.push([i.kind,i.value,ad(n,i.value)]);else if(i.kind==="source_file"){let s=Ri(o,i.value),d=s===o||s.startsWith(`${o}/`)?await Lo(s,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([i.kind,i.value,d])}else r.push([i.kind,i.value]);return Pi("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ti(o={}){let e=new Date().toISOString(),n=o.port??Gc,t=o.projectRoot??process.cwd(),r=await Lc(t).catch(()=>t),i=Xn(r),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ee(Uc(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,v=[...o.allowedTools??Vc],R=o.claudePath??"claude",w=o.copilotPath??"copilot",b=o.provider??"claude",h=o.timeoutMs,p=o.restartMode??"embedded",g=n,f={},y={claude:R,codex:"codex",copilot:w};for(let[a,u]of Object.entries(y))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=gi(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 oi(f.claude.path).catch(()=>Bn):Bn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await ni(f.codex.path).catch(()=>nn):nn)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await ti(f.copilot.path).catch(()=>[on]):[on])})()]);let[S,_,J]=await Promise.all([wo(r),Io(r),bo(r,f.copilot?.path??w)]),A=await br(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=_),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&v.push(`mcp__${S.name}__*`),await Nc(c,{recursive:!0}),Si(c).catch(()=>{});let N=new Fn(1),T=new Sn,B=new kn(vi),W=null,te=0,H=!1,ne=()=>{te+=1,H=!1,W&&clearTimeout(W),W=null},oe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},he=()=>{if(p!=="detached"||B.size>0||H)return;H=!0;let a=++te,u=Date.now()+Yc,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){H=!1,W=setTimeout(oe,50),W.unref?.();return}W=setTimeout(k,250),W.unref?.()};k()},Y=new Set,G=new Qn(r),q=new $n(r),fe=new Ot(r,i),E=new gn(r),Z=new wn(r),V=new xn(r,{claudePath:R,provider:b,timeoutMs:h,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 ${g}] 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=dr(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)?yi(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,se)=>({id:`route-${se+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?gr(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=td(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.
209
-
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.
211
-
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+=`
213
-
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+=`
216
-
217
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:L+=`
218
-
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)+`
220
-
221
- Follow the developer's instructions. If they ask for changes, apply them to the source files.
222
-
223
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(I!=="codex"?`
224
-
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??Kr(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+=Ur(a.memoryReview),D&&(L+=Hn(a.imprintContext)),L+=`
226
-
227
- ${Vr}`;let C=id(a.color,`[\u22B9 ${g}:${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:se,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:h,copilotPath:f.copilot?.path??w,onEvent:U}):mn(a.id,{prompt:L,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:j?["Read"]:v,claudePath:R,resumeSessionId:F,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:h,onEvent:U});N.setActiveProcess(a.id,se);let re=await ae,be=Q.finalize(re.text),ye=be.visibleText,K=D?Wn(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=Qr(ye),pe=Yr(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?ed($e.events,r):void 0,Pe,ee=Hr(ye),me=Wr(ye);if(me)if(!(a.memoryReview?.packets.some(ie=>ie.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(ie){Pe={status:"rejected",action:me.action,proposalId:me.proposalId,message:ie instanceof Error?ie.message:String(ie)}}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),ie=new Set(xe.changes.map(Ke=>Ke.explanationId)),Ve=z?Zc(z.messages,ie):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=mi({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(ie=>ie.linkedSelector?[ie.pathname?`${ie.pathname}:${ie.linkedSelector}`:ie.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(ie=>ie.status==="resolved")?"completed":"no_change",execution:{provider:I,model:a.model,sessionId:re.sessionId},subjectHints:z,filePaths:[...(re.fileEdits??[]).map(ie=>ie.file_path),...(re.editEvents??[]).flatMap(ie=>ie.filePath?[ie.filePath]:[])].map(ie=>Fo(ie)?yi(r,ie):ie),resolutions:pe.map(ie=>({status:ie.status,summary:ie.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ie=>ie.id)})}catch(ie){console.warn(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,ie instanceof Error?ie.message:String(ie))}}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),ie=a._evalRunScope;if(z&&ie){let Ve=cr(ye,z.assertions),Ke=Date.now(),Li={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:ie,provider:I,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:bi(r),rawResponse:ye,scopeFingerprint:a._evalScopeFingerprint,...Ve};await q.recordEvalVerification(z,Li),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=Zr(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=qc(async(a,u)=>{if(od(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:${g}`),I=P.pathname,j=rd(a,P);if(j&&j!==i){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:j,projectName:Yn(r)});return}if(a.headers.origin){if(!ki(a.headers.origin)){M(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==i){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:j,projectName:Yn(r)});return}}try{if(a.method==="POST"&&I==="/send")await it(a,u);else if(a.method==="GET"&&I==="/events")Ye(a,u);else if(a.method==="GET"&&I==="/status")await st(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:vi})}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(()=>{gi(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 io(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 Mi(a,u);else if(a.method==="PATCH"&&I==="/model/token")await _i(a,u);else if(a.method==="DELETE"&&I==="/model/token")await Ai(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 xi(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),F=bi(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 Di(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 Ji($,u)}else if(a.method==="DELETE"&&I.startsWith("/thread/")){let $=I.slice(8);await Ni($,u)}else a.method==="GET"&&(I==="/canvas"||I==="/canvas/")?Ci(a,u):a.method==="GET"&&I==="/canvas/manifest"?await $i(u):a.method==="GET"&&I==="/canvas/app.mjs"?await Oi(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(se=>se.name===P||se.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 se=bt(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&se!=="copilot"&&await Ft({provider:se,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(se=>se.role==="assistant"&&se.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(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));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 it(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(c,`screenshot-${Q}-${me}.webp`);await dn(Re,ee.data),U[ee.pathname]=Re}let se=Ee(c,`screenshot-${Q}.webp`);await dn(se,k);let ae={};if(L.length>0)for(let ee of L){let me=Ee(c,`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 qr(q,O,re,ee=>console.warn(`[\u22B9 ${g}:${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 ${g}:${Q}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),pe={id:Q,status:"queued",screenshotPath:se,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||Ii({...O,annotations:[me]}))}$e=[...ee.entries()].map(([me,Re])=>`\`${me}\`
228
- ${Re.map(xe=>`- ${xe}`).join(`
229
- `)}`).join(`
230
- `)}else $e=Ii(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:se,...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 ie of a)X.push(typeof ie=="string"?Buffer.from(ie):ie);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,se;if(C){let X=await q.findJournalEvalCase(C.evalId),ue=(await q.getJournalEvalRuns()).filter(z=>z.evalId===C.evalId&&z.threadId===m).sort((z,ie)=>ie.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}se={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 ie=>({modelProposalId:z.id,underlying:await q.findPendingProposalForLegacyDecision(ie)}))))).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(c,`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 ${g}:${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=Xr(ae,pe,me,we.length>0?we:void 0);if(se?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(se.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:se.run.summary,assertionResults:se.run.assertionResults,scope:se.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
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],ie=[...X._replyImagePaths??[],...we];X._replyTexts=z,X._replyText=wi(z),X._replyImagePaths=ie.length>0?ie: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}:{}};se?Ue.kind="resolve_eval":re&&(Ue.kind=re),Ue._replyPrompt=ft,Ue._evalRemediation=!!se,Ue._replyTexts=[P],Ue._replyText=wi([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
234
- data: {"status":"connected"}
235
-
236
- `);let m=new URL(a.url||"/",`http://127.0.0.1:${g}`).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 st(a,u,k){s??=li(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=pi(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})),se=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":se.state==="absent"||se.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:i,projectName:Yn(r),projectRoot:r,requestProjectId:k,projectIdVerified:k===i,devOrigin:s,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds,color:K.color,kind:K.kind,standalone:"standalone"in K?K.standalone:void 0})),queueDepth:N.depth+T.depth,projectionQueueDepth:T.depth,leases:{active:B.isActivated,count:B.size,nextExpiryAt:B.nextExpiryAt,shutdownPending:H},projection:{state: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:se,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"&&(s=m.devOrigin||null),M(u,200,{ok:!0,devOrigin:s})}catch{M(u,400,{error:"Invalid JSON"})}}async function ut(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${g}`).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(se=>typeof se=="string"||typeof se=="number");if(Q.length!==O.path.length)return[];let U=Array.isArray(O.decisionIds)?O.decisionIds.filter(se=>typeof se=="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,se=U===0?"unprojected":Q>U?"partially_projected":"projected";return{decisionId:O,status:se}}),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),se=pt().slice(0,8),ae=Ee(c,`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 xi(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=pr({evalCase:P,scope:K,model:we,screenshotPath:ae,chromeDevtoolsAvailable:Ce}),Pe=(await G.createThread(se,[])).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:se,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:se,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:se,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 io(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 Tr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&P.push(await jr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&P.push(await Er(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 Mi(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 _i(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 Ai(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 Ci(a,u){let k=s??"http://localhost:3000";if(!s){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=Vo(g,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function $i(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 Oi(a){let u=[Ee(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ee(r,"packages","popmelt","dist","canvas.mjs")];try{let k=Hc(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 Di(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){M(u,400,{error:"Invalid filename"});return}try{let k=[Ee(c,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 Ji(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,...se})=>({...se,...se.role==="assistant"&&I&&se.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 Ni(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 qo=9,Uo=!1;for(let a=n;a<n+qo;a++)try{await sd(xt,a),g=a,Uo=!0,console.log(`[\u22B9 is watching :${g}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await no(a);if(sn(k,{projectId:i,version:ot,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw u}if(!Uo)throw new Error(`[Bridge] All ports ${n}\u2013${n+qo-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 Bi=setInterval(()=>{Si(c).catch(()=>{})},Kc),Wo=setInterval(()=>{B.expireStale().becameEmpty&&he()},Xc);return Wo.unref?.(),{port:g,projectId:i,close:async()=>{clearInterval(Bi),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 Si(o){try{let e=await Bc(o),n=Date.now();for(let t of e){let r=Ee(o,t);try{let i=await Fc(r);n-i.mtimeMs>Qc&&await zc(r)}catch{}}}catch{}}var yd=1111,ji=3e4,vd=8e3;async function wd(o){return fd(o).catch(()=>o)}async function Ei(o,e){let t=(await md(e,"utf8").catch(()=>"")).slice(-vd).trim();return new Error(t?`${o}
238
- Bridge log (${e}):
239
- ${t}`:o)}async function mu(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 Id(o);if(o.manageLease===!1)return n;let t=await Ho({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let r=Go(t);return{...n,close:async()=>{r(),await t.release()}}}let e=await Ti(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Id(o){let e=o.port??yd,n=await wd(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(h=>setTimeout(h,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=zo(hd(gd(import.meta.url)),"bridge-entry.mjs"),i=zo(n,".popmelt"),s=zo(i,"bridge.log");await ud(i,{recursive:!0}),await pd(s,`
240
- [${new Date().toISOString()}] Starting detached bridge
241
- `);let c=ld(s,"a"),d;try{d=cd(process.execPath,[r],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{dd(c)}let l=null;d.once("error",R=>{l=`spawn error: ${R.message}`}),d.once("exit",(R,w)=>{l=`child exited before becoming healthy (${w?`signal ${w}`:`code ${R??"unknown"}`})`}),d.unref();let v=Date.now()+ji;for(;Date.now()<v;){if(await new Promise(R=>setTimeout(R,100)),l)throw await Ei(`[Bridge] Detached bridge ${l}`,s);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 d.kill("SIGTERM"),await Ei(`[Bridge] Detached bridge failed to start within ${ji/1e3}s (port ${e})`,s)}export{Ot as ImprintService,$t as ImprintStore,Hn as formatImprintPrompt,Wn as parseImprintDraft,mu as startPopmelt};