@popmelt.com/core 0.8.6 → 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.
package/dist/server.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{spawn as Td}from"child_process";import{closeSync as jd,openSync as Ed}from"fs";import{appendFile as Md,mkdir as Ad,readFile as _d,realpath as Cd}from"fs/promises";import{dirname as $d,join as qo}from"path";import{fileURLToPath as Od}from"url";import{execFileSync as no,spawn as ws}from"child_process";import{createHash as Ts,randomUUID as ut}from"crypto";import{mkdir as ed,readFile as Fo,readdir as td,realpath as nd,stat as od,unlink as rd,writeFile as dn}from"fs/promises";import{createServer as sd}from"http";import{tmpdir as id}from"os";import{basename as Zn,dirname as ad,isAbsolute as zo,join as Me,relative as Is,resolve as js}from"path";import{fileURLToPath as cd}from"url";function Vo(o,e){return`<!DOCTYPE html>
1
+ import{spawn as Cd}from"child_process";import{closeSync as $d,openSync as Od}from"fs";import{appendFile as Dd,mkdir as Jd,readFile as Nd,realpath as Bd}from"fs/promises";import{dirname as Ld,join as Ko}from"path";import{fileURLToPath as Fd}from"url";import{execFileSync as so,spawn as ki}from"child_process";import{createHash as $i,randomUUID as mt}from"crypto";import{mkdir as sd,readFile as Wo,readdir as ad,realpath as cd,stat as dd,unlink as ld,writeFile as pn}from"fs/promises";import{createServer as pd}from"http";import{tmpdir as ud}from"os";import{basename as ro,dirname as md,isAbsolute as Go,join as Ae,relative as Ti,resolve as Oi}from"path";import{fileURLToPath as fd}from"url";function Zo(o,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -25,12 +25,12 @@ import{spawn as Td}from"child_process";import{closeSync as jd,openSync as Ed}fro
25
25
  });
26
26
  </script>
27
27
  </body>
28
- </html>`}var Ks=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Qs=new Set(["default","flex","fast","priority"]);function yt(o){let e=typeof o.reasoningEffort=="string"&&Ks.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Qs.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function un(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as Xs}from"child_process";import{createInterface as Ys}from"readline";var Zs=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 ei(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Zs.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:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:d="claude",resumeSessionId:c,model:l,reasoningEffort:h,timeoutMs:R=3e5,onEvent:I}=e,b=[];c?b.push("--resume",c,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(s)),l&&b.push("--model",l),h&&b.push("--effort",h);for(let y of i)b.push("--allowedTools",y);let g=Xs(d,b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(y=>{let f,v=[],x=[],S=[],A=!1,J="",_,N,T=!1,B=setTimeout(()=>{T=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},R),H=Ys({input:g.stdout}),ee=new Set;H.on("line",te=>{if(te.trim())try{let ne=JSON.parse(te);ne.session_id&&!f&&(f=ne.session_id);let ge=ne.type??(ne.event?.type?`event.${ne.event.type}`:"unknown");if(ee.add(ge),ne.type==="result"&&ne.result&&v.length===0){let X=typeof ne.result=="string"?ne.result:"";X&&(v.push(X),I?.({type:"delta",jobId:o,text:X},o))}if(ne.type==="assistant"&&Array.isArray(ne.message?.content)){typeof ne.error=="string"&&(_=ne.error);for(let X of ne.message.content){if(X.type==="text"&&X.text&&(v.push(X.text),I?.({type:"delta",jobId:o,text:X.text},o)),X.type==="tool_use"&&X.name){let G=X.input?.file_path||X.input?.path||void 0,U=ei(X);if(I?.({type:"tool_use",jobId:o,tool:X.name,...G?{file:G}:{},...U?{content:U}:{}},o),X.name==="Edit"&&X.input?.file_path){let he={tool:"Edit",file_path:X.input.file_path,old_string:X.input.old_string,new_string:X.input.new_string,replace_all:X.input.replace_all};x.push(he),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:he.file_path,oldString:typeof he.old_string=="string"?he.old_string:void 0,newString:typeof he.new_string=="string"?he.new_string:void 0,replaceAll:typeof he.replace_all=="boolean"?he.replace_all:void 0})}else X.name==="Write"&&X.input?.file_path&&(x.push({tool:"Write",file_path:X.input.file_path,content:X.input.content}),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:X.input.file_path,content:typeof X.input.content=="string"?X.input.content:void 0}))}X.type==="thinking"&&X.thinking&&I?.({type:"thinking",jobId:o,text:X.thinking},o)}}ne.type==="result"&&ne.is_error===!0&&(A=!0,typeof ne.error=="string"&&(_=ne.error),typeof ne.result=="string"&&(N=ne.result)),ne.type==="user"&&ne.tool_use_result?.file?.filePath&&I?.({type:"tool_use",jobId:o,tool:"Read",file:ne.tool_use_result.file.filePath},o)}catch{}});let W=[];g.stderr?.on("data",te=>{W.push(te.toString())}),g.on("close",te=>{if(clearTimeout(B),H.close(),v.length===0&&ee.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...ee].join(", ")}`),T)A=!0,J=`Timed out after ${Math.round(R/6e4)} minutes`;else if(te!==0&&te!==null){A=!0;let ge=W.join("").trim(),X=v.join("").trim(),G=v.length===0&&ee.size>0?` (no text captured, event types: ${[...ee].join(", ")})`:"";J=ge||N||X||`Claude process exited with code ${te}${G}`}A&&!J&&N&&(J=N);let ne=ti(J,_);y({sessionId:f,text:v.join(""),success:!A,error:A?ne.message:void 0,errorCode:A?ne.code:void 0,recoverableError:A?ne.recoverable:void 0,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})}),g.on("error",te=>{clearTimeout(B),A=!0,J=te.message,y({sessionId:f,text:v.join(""),success:!1,error:J,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})})});return{process:g,result:p}}function ti(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 ni,spawnSync as tr}from"child_process";import{readFileSync as oi,statSync as ri}from"fs";import{basename as si,extname as ii,isAbsolute as ai,relative as nr,resolve as ci}from"path";import{createInterface as di}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"]),ao=2e5,li=1e5,or=2e5;function rr(o){let e=si(o).toLowerCase(),n=ii(o).toLowerCase();return Xo.has(n)||Xo.has(e)}function qt(o,e){let n=ai(e)?e:ci(o,e),t=nr(o,n);return t===""||t.startsWith("..")?null:n}function fn(o,e){if(!rr(e))return;let n=qt(o,e);if(n)try{let t=ri(n);return t.isFile()?t.size>ao?{exists:!0,truncated:!0}:{exists:!0,content:oi(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function pi(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function ui(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 pi(o,["patch","diff","unifiedDiff","unified_diff"])}function co(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 mi(o){let e=new Set;for(let n of o.split(`
30
- `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let s of r)s&&e.add(s)}return[...e]}function er(o){let e=Zo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Zo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=co(n,or);return{status:e,changedFiles:mi(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function fi(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function hi(o,e){if(!rr(e))return;let n=qt(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:ao+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=co(s,ao);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function gi(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):hi(o,t),s=fn(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function hn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:d,sandboxMode:c="workspace-write",configOverrides:l=[]}=e,h=[];if(s){h.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let b of l)h.push("-c",b);i&&h.push("-m",i),h.push(s),h.push(n),r&&h.push("--image",r)}else{h.push("exec","--skip-git-repo-check","--json","--sandbox",c);for(let b of l)h.push("-c",b);i&&h.push("-m",i),h.push(n),r&&h.push("--image",r)}let R=ni("codex",h,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),I=new Promise(b=>{let g,p=[],y=[],f=[],v=new Map,x=new Map,S=!1,A="",J=di({input:R.stdout}),_=new Set;J.on("line",T=>{if(T.trim())try{let B=JSON.parse(T),H=B.type??"unknown";if(_.add(H),H==="thread.started"&&B.thread_id&&!g&&(g=B.thread_id),(H==="item.agentMessage.delta"||H==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),d?.({type:"delta",jobId:o,text:B.delta.text},o)),(H==="item.reasoning.delta"||H==="item/reasoning/delta")&&B.delta?.text&&d?.({type:"thinking",jobId:o,text:B.delta.text},o),(H==="item.started"||H==="item/started")&&B.item){let ee=B.item.type;if(ee==="command_execution"){let W=B.item.command,te=W?Qo(W):void 0,ne=er(t),ge=new Map;for(let G of ne?.changedFiles??[])ge.set(G,fn(t,G));typeof B.item.id=="string"&&x.set(B.item.id,{...W?{rawCommand:W}:{},...te?{command:te}:{},...ne?{beforeWorktree:ne}:{},beforeSnapshots:ge});let X=te?`Bash: ${te.split(`
31
- `)[0].slice(0,80)}`:"Bash";y.push(X),d?.({type:"tool_use",jobId:o,tool:"Bash",...te?{content:te}:{}},o)}else if(ee==="file_change"){let W=B.item.filename||B.item.path;W&&!v.has(W)&&v.set(W,fn(t,W)),y.push(W?`Edit ${W.split("/").pop()}`:"Edit");let te=W?qt(t,W)??W:void 0;d?.({type:"tool_use",jobId:o,tool:"Edit",...te?{file:te}:{}},o)}else if(ee==="file_read"){let W=B.item.filename||B.item.path;y.push(W?`Read ${W.split("/").pop()}`:"Read");let te=W?qt(t,W)??W:void 0;d?.({type:"tool_use",jobId:o,tool:"Read",...te?{file:te}:{}},o)}else if(ee==="web_search")y.push("WebSearch"),d?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(ee==="mcp_tool_call"){let W=B.item.tool_name||B.item.name||"MCP";y.push(W),d?.({type:"tool_use",jobId:o,tool:W},o)}}if((H==="item.completed"||H==="item/completed")&&B.item){if(B.item.type==="agent_message"){let ee=B.item.text;typeof ee=="string"&&ee&&(p.push(ee),d?.({type:"delta",jobId:o,text:ee},o))}else if(B.item.type==="reasoning"){let ee=B.item.text;typeof ee=="string"&&ee&&d?.({type:"thinking",jobId:o,text:ee},o)}else if(B.item.type==="file_change"&&Array.isArray(B.item.changes))for(let ee of B.item.changes){let W=ee.path||ee.filename,te=ee.kind==="add"?"Write":"Edit";if(W){y.push(`${te} ${W.split("/").pop()}`);let ne=qt(t,W)??W;d?.({type:"tool_use",jobId:o,tool:te,file:ne},o);let ge=ee,X=typeof ge.kind=="string"?ge.kind:void 0,G=ui(X),U=v.get(W),he=fn(t,W);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:W,...U?{before:U}:{},...he?{after:he}:{},...Yo(ge)?{patch:Yo(ge)}:{},...X?{rawKind:X}:{}}),v.set(W,he)}}else if(B.item.type==="command_execution"){let ee=typeof B.item.id=="string"?B.item.id:void 0,W=ee?x.get(ee):void 0,te=typeof B.item.command=="string"?B.item.command:W?.rawCommand,ne=te?Qo(te):W?.command,ge=er(t);if(fi(W?.beforeWorktree,ge)){let X=[...new Set([...W?.beforeWorktree?.changedFiles??[],...ge?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?co(B.item.aggregated_output,li):void 0,U=typeof B.item.exit_code=="number"?B.item.exit_code:B.item.exit_code===null?null:void 0,he=typeof B.item.status=="string"?B.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...te?{rawCommand:te}:{},...ne?{command:ne}:{},...U!==void 0?{exitCode:U}:{},...he?{status:he}:{},...G?{output:G.text}:{},...G?.truncated?{outputTruncated:!0}:{},...W?.beforeWorktree?{beforeWorktree:W.beforeWorktree}:{},...ge?{afterWorktree:ge}:{},...X.length>0?{touchedFiles:gi(t,X,W?.beforeSnapshots??new Map)}:{}})}ee&&x.delete(ee)}}H==="turn.failed"&&(S=!0,A=B.error?.message||B.message||"Turn failed")}catch{}});let N=[];R.stderr?.on("data",T=>{N.push(T.toString())}),R.on("close",T=>{J.close(),p.length===0&&_.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[..._].join(", ")}`),T!==0&&T!==null&&(S=!0,A=N.join("")||`Codex process exited with code ${T}`),b({sessionId:g,text:p.join(""),success:!S,error:S?A:void 0,editEvents:f.length>0?f:void 0,toolsUsed:y.length>0?y:void 0})}),R.on("error",T=>{S=!0,A=T.message,b({sessionId:g,text:p.join(""),success:!1,error:A,editEvents:f.length>0?f:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:R,result:I}}import{spawn as yi}from"child_process";import{createInterface as vi}from"readline";function sr(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 ir(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:s,timeoutMs:i=3e5,onEvent:d,copilotPath:c="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),s&&l.push("--model",s),l.push("-p",n);let h=yi(c,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(I=>{let b,g=[],p=[],y=!1,f="",v=!1,x=setTimeout(()=>{v=!0,h.kill("SIGTERM"),setTimeout(()=>{try{h.kill("SIGKILL")}catch{}},5e3)},i),S=vi({input:h.stdout}),A=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Wt(T);A.add(B),J.length<5&&Ii(B)&&J.push(N.slice(0,800));let H=Ht(T,["sessionId","session_id","id"],["session","conversation","thread"]);H&&!b&&(b=H);let ee=wi(T,g.length===0);ee&&(g.push(ee),d?.({type:"delta",jobId:o,text:ee},o));let W=bi(T);W&&d?.({type:"thinking",jobId:o,text:W},o);let te=xi(T);te&&(p.push(te.label),d?.({type:"tool_use",jobId:o,tool:te.tool,...te.file?{file:te.file}:{},...te.content?{content:te.content}:{}},o));let ne=Si(T);ne&&(y=!0,f=ne)}catch{}});let _=[];h.stderr?.on("data",N=>{_.push(N.toString())}),h.on("close",N=>{clearTimeout(x),S.close(),g.length===0&&A.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),J.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${J.join(`
32
- `)}`)),v?(y=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(y=!0,f=_.join("").trim()||f||`Copilot process exited with code ${N}`);let T=y?sr(f,s):null;I({sessionId:b,text:g.join(""),success:!y,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),h.on("error",N=>{clearTimeout(x);let T=sr(N.message,s);I({sessionId:b,text:g.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:h,result:R}}function Wt(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function wi(o,e=!1){let n=Wt(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Le(o.delta)??Le(o.content)??Le(o.message);if(n==="assistant.message"&&e)return Le(o.message)??Le(o.content)??Le(o);if(n==="result"&&e)return Le(o.result)??Le(o.output)??Le(o.message)??Le(o);let s=o.content;if(s?.type==="text"&&typeof s.text=="string")return s.text;if(typeof o.text=="string"&&lo(o))return o.text;if(typeof o.message=="string"&&lo(o))return o.message;if(typeof o.delta=="string"&&lo(o))return o.delta}function Le(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Le).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Le(e[n]);if(t)return t}}function Ii(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function bi(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 xi(o){let e=Ht(o,["tool","toolName","tool_name","name"]),n=Ht(o,["command","cmd"]),t=Ht(o,["file","path","filename","filePath"]),r=Wt(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
33
- `)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let s=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:s,label:`${s} ${t.split("/").pop()}`,file:t}}}function Si(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&Wt(o).toLowerCase().includes("error"))return o.message}function Ht(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(i=>t.toLowerCase().includes(i)))continue;let s=Ht(r,e);if(s)return s}}function lo(o){let e=Wt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as Pi,readFile as Ri}from"fs/promises";import{join as po}from"path";var gn=class{constructor(e){let n=po(e,".popmelt");this.decisionsDir=po(n,"decisions")}async listDecisionIds(){try{return(await Pi(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 Ri(po(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=Ci(t.assertionResults,e),s=$i(r);return{status:s,summary:tt(t.summary)||ur(s),assertionResults:r,tooling:Oi(t.tooling)}}catch{}return{status:"needs_review",summary:Di(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(v=>Array.isArray(v.path)&&v.path.length?[v.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(v=>v.path),s=[...new Set(r.map(v=>v.map(String).join(".")).filter(Boolean))].map(v=>({kind:"model_path",value:v}));if(s.length===0||o.decisionIds.length===0)return[];let i=new Set(o.decisionIds),d=new Set(s.map(v=>v.value)),c=e.cases.find(v=>v.status!=="rejected"&&(v.sourceDecisionIds.some(x=>i.has(x))||(v.dependencies??[]).some(x=>x.kind==="model_path"&&d.has(x.value)))),l=(o.selectedChanges??[]).find(v=>v.label?.trim())?.label?.trim()??t.find(v=>v.label?.trim())?.label?.trim()??o.title,h=c?.id.startsWith("eval-model-")??!1,R=(o.selectedChanges??[]).flatMap(v=>Array.isArray(v.path)&&v.path.length>0?[{path:v.path,value:v.value,label:v.label,detail:v.detail}]:[]),b=(R.length>0?R:t.map(v=>({path:v.path,value:v.value,label:v.label,detail:v.rationale}))).flatMap(v=>ki(v,o.decisionIds)),g=vn(o.underlyingClaim??o.summary),p=[...new Set([...c&&!h?c.assertions:[],...b,...b.length===0&&g?[g]:[]])],y=s[0].value,f=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:c?.id??`eval-model-${o.id}`,title:c&&!h?c.title:l,status:"pending",category:c?.category??f,prompt:c&&!h?c.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:c&&!h?c.rationale:Ei(y),sourceDecisionIds:[...new Set([...c?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...c?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...c?.dependencies??[],...s].map(v=>[`${v.kind}:${v.value}`,v])).values()]}]}function ki(o,e){let n=String(o.path[0]??"");if(n==="rules")return Ti(o.value,e);if(n==="components"){let i=lr(String(o.path[1]??o.label??"component")),d=yn(o.value),c=d?Vt(d.usage):[];if(c.length>0){let h=Mi(c),R=c.length===1?"uses":"use";return[`The ${h} ${R} the same shared implementation for the ${i} pattern.`]}if(d?.shared===!0)return[`The product uses a shared implementation for the ${i} pattern.`];let l=d?tt(d.constraint):"";if(l){let h=ji(l,i);if(h)return[h]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),d=yn(o.value),c=d&&"value"in d?d.value:o.value,l=Ai(c);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=yn(o.value),r=t?tt(t.text)||tt(t.constraint):typeof o.value=="string"?o.value:"",s=vn(r||o.detail||"");return s?[s]:[]}function Ti(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let d=yn(i),c=d?tt(d.text):"";return c?[{text:c,sources:d?Vt(d.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(d=>n.has(d)));return(r.length>0?r:t.length===1?t:[]).map(i=>vn(i.text)).filter(i=>!!i)}function ji(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?Rt(`Wherever ${Gt(n[1])}, the shared ${e} implementation is used instead of ${Gt(n[2])}`):vn(o)}function uo(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Rt(`${ar(n[1])} is ${Gt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Rt(ar(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Rt(`The product uses ${Gt(r[1])}`);let s=e.match(/^Do not (.+?)\.?$/i);return s?Rt(`The product does not ${Gt(s[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Rt(e)}var vn=uo;function Ei(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 Mi(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 Ai(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function Rt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function 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.
28
+ </html>`}var ns=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),os=new Set(["default","flex","fast","priority"]);function vt(o){let e=typeof o.reasoningEffort=="string"&&ns.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&os.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function hn(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 rs}from"child_process";import{createInterface as is}from"readline";var ss=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"]),er=1e5;function as(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!ss.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>er?t.slice(0,er)+`
29
+ \u2026[truncated]`:t}function gn(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:w,timeoutMs:k=3e5,onEvent:P}=e,x=[];d?x.push("--resume",d,"-p",n):x.push("-p",n),x.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),l&&x.push("--model",l),w&&x.push("--effort",w);for(let y of s)x.push("--allowedTools",y);let m=rs(c,x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(y=>{let h,f=[],u=[],E=[],O=!1,R="",C,I,b=!1,M=setTimeout(()=>{b=!0,m.kill("SIGTERM"),setTimeout(()=>{try{m.kill("SIGKILL")}catch{}},5e3)},k),L=is({input:m.stdout}),G=new Set;L.on("line",ne=>{if(ne.trim())try{let oe=JSON.parse(ne);oe.session_id&&!h&&(h=oe.session_id);let ye=oe.type??(oe.event?.type?`event.${oe.event.type}`:"unknown");if(G.add(ye),oe.type==="result"&&oe.result&&f.length===0){let Y=typeof oe.result=="string"?oe.result:"";Y&&(f.push(Y),P?.({type:"delta",jobId:o,text:Y},o))}if(oe.type==="assistant"&&Array.isArray(oe.message?.content)){typeof oe.error=="string"&&(C=oe.error);for(let Y of oe.message.content){if(Y.type==="text"&&Y.text&&(f.push(Y.text),P?.({type:"delta",jobId:o,text:Y.text},o)),Y.type==="tool_use"&&Y.name){let V=Y.input?.file_path||Y.input?.path||void 0,q=as(Y);if(P?.({type:"tool_use",jobId:o,tool:Y.name,...V?{file:V}:{},...q?{content:q}:{}},o),Y.name==="Edit"&&Y.input?.file_path){let ge={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};u.push(ge),E.push({sequence:E.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:ge.file_path,oldString:typeof ge.old_string=="string"?ge.old_string:void 0,newString:typeof ge.new_string=="string"?ge.new_string:void 0,replaceAll:typeof ge.replace_all=="boolean"?ge.replace_all:void 0})}else Y.name==="Write"&&Y.input?.file_path&&(u.push({tool:"Write",file_path:Y.input.file_path,content:Y.input.content}),E.push({sequence:E.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&&P?.({type:"thinking",jobId:o,text:Y.thinking},o)}}oe.type==="result"&&oe.is_error===!0&&(O=!0,typeof oe.error=="string"&&(C=oe.error),typeof oe.result=="string"&&(I=oe.result)),oe.type==="user"&&oe.tool_use_result?.file?.filePath&&P?.({type:"tool_use",jobId:o,tool:"Read",file:oe.tool_use_result.file.filePath},o)}catch{}});let U=[];m.stderr?.on("data",ne=>{U.push(ne.toString())}),m.on("close",ne=>{if(clearTimeout(M),L.close(),f.length===0&&G.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...G].join(", ")}`),b)O=!0,R=`Timed out after ${Math.round(k/6e4)} minutes`;else if(ne!==0&&ne!==null){O=!0;let ye=U.join("").trim(),Y=f.join("").trim(),V=f.length===0&&G.size>0?` (no text captured, event types: ${[...G].join(", ")})`:"";R=ye||I||Y||`Claude process exited with code ${ne}${V}`}O&&!R&&I&&(R=I);let oe=cs(R,C);y({sessionId:h,text:f.join(""),success:!O,error:O?oe.message:void 0,errorCode:O?oe.code:void 0,recoverableError:O?oe.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:E.length>0?E:void 0})}),m.on("error",ne=>{clearTimeout(M),O=!0,R=ne.message,y({sessionId:h,text:f.join(""),success:!1,error:R,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:u.length>0?u:void 0,editEvents:E.length>0?E:void 0})})});return{process:m,result:p}}function cs(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 ds,spawnSync as sr}from"child_process";import{readFileSync as ls,statSync as ps}from"fs";import{basename as us,extname as ms,isAbsolute as fs,relative as ar,resolve as hs}from"path";import{createInterface as gs}from"readline";function tr(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var nr=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"]),uo=2e5,ys=1e5,cr=2e5;function dr(o){let e=us(o).toLowerCase(),n=ms(o).toLowerCase();return nr.has(n)||nr.has(e)}function Ht(o,e){let n=fs(e)?e:hs(o,e),t=ar(o,n);return t===""||t.startsWith("..")?null:n}function yn(o,e){if(!dr(e))return;let n=Ht(o,e);if(n)try{let t=ps(n);return t.isFile()?t.size>uo?{exists:!0,truncated:!0}:{exists:!0,content:ls(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function vs(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function Is(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 or(o){return vs(o,["patch","diff","unifiedDiff","unified_diff"])}function mo(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function rr(o,e){let n=sr("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:cr+65536});return n.status!==0?null:n.stdout??""}function ws(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 ir(o){let e=rr(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=rr(o,["diff","--no-ext-diff","HEAD","--"])??"",t=mo(n,cr);return{status:e,changedFiles:ws(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function bs(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function xs(o,e){if(!dr(e))return;let n=Ht(o,e);if(!n)return;let t=ar(o,n);if(t===""||t.startsWith(".."))return;let r=sr("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:uo+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=mo(i,uo);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Ss(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):xs(o,t),i=yn(o,t);return{filePath:t,...r?{before:r}:{},...i?{after:i}:{}}})}function vn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:i,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,w=[];if(i){w.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let x of l)w.push("-c",x);s&&w.push("-m",s),w.push(i),w.push(n),r&&w.push("--image",r)}else{w.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let x of l)w.push("-c",x);s&&w.push("-m",s),w.push(n),r&&w.push("--image",r)}let k=ds("codex",w,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),P=new Promise(x=>{let m,p=[],y=[],h=[],f=new Map,u=new Map,E=!1,O="",R=gs({input:k.stdout}),C=new Set;R.on("line",b=>{if(b.trim())try{let M=JSON.parse(b),L=M.type??"unknown";if(C.add(L),L==="thread.started"&&M.thread_id&&!m&&(m=M.thread_id),(L==="item.agentMessage.delta"||L==="item/agentMessage/delta")&&M.delta?.text&&(p.push(M.delta.text),c?.({type:"delta",jobId:o,text:M.delta.text},o)),(L==="item.reasoning.delta"||L==="item/reasoning/delta")&&M.delta?.text&&c?.({type:"thinking",jobId:o,text:M.delta.text},o),(L==="item.started"||L==="item/started")&&M.item){let G=M.item.type;if(G==="command_execution"){let U=M.item.command,ne=U?tr(U):void 0,oe=ir(t),ye=new Map;for(let V of oe?.changedFiles??[])ye.set(V,yn(t,V));typeof M.item.id=="string"&&u.set(M.item.id,{...U?{rawCommand:U}:{},...ne?{command:ne}:{},...oe?{beforeWorktree:oe}:{},beforeSnapshots:ye});let Y=ne?`Bash: ${ne.split(`
31
+ `)[0].slice(0,80)}`:"Bash";y.push(Y),c?.({type:"tool_use",jobId:o,tool:"Bash",...ne?{content:ne}:{}},o)}else if(G==="file_change"){let U=M.item.filename||M.item.path;U&&!f.has(U)&&f.set(U,yn(t,U)),y.push(U?`Edit ${U.split("/").pop()}`:"Edit");let ne=U?Ht(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...ne?{file:ne}:{}},o)}else if(G==="file_read"){let U=M.item.filename||M.item.path;y.push(U?`Read ${U.split("/").pop()}`:"Read");let ne=U?Ht(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...ne?{file:ne}:{}},o)}else if(G==="web_search")y.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(G==="mcp_tool_call"){let U=M.item.tool_name||M.item.name||"MCP";y.push(U),c?.({type:"tool_use",jobId:o,tool:U},o)}}if((L==="item.completed"||L==="item/completed")&&M.item){if(M.item.type==="agent_message"){let G=M.item.text;typeof G=="string"&&G&&(p.push(G),c?.({type:"delta",jobId:o,text:G},o))}else if(M.item.type==="reasoning"){let G=M.item.text;typeof G=="string"&&G&&c?.({type:"thinking",jobId:o,text:G},o)}else if(M.item.type==="file_change"&&Array.isArray(M.item.changes))for(let G of M.item.changes){let U=G.path||G.filename,ne=G.kind==="add"?"Write":"Edit";if(U){y.push(`${ne} ${U.split("/").pop()}`);let oe=Ht(t,U)??U;c?.({type:"tool_use",jobId:o,tool:ne,file:oe},o);let ye=G,Y=typeof ye.kind=="string"?ye.kind:void 0,V=Is(Y),q=f.get(U),ge=yn(t,U);h.push({sequence:h.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:V,filePath:U,...q?{before:q}:{},...ge?{after:ge}:{},...or(ye)?{patch:or(ye)}:{},...Y?{rawKind:Y}:{}}),f.set(U,ge)}}else if(M.item.type==="command_execution"){let G=typeof M.item.id=="string"?M.item.id:void 0,U=G?u.get(G):void 0,ne=typeof M.item.command=="string"?M.item.command:U?.rawCommand,oe=ne?tr(ne):U?.command,ye=ir(t);if(bs(U?.beforeWorktree,ye)){let Y=[...new Set([...U?.beforeWorktree?.changedFiles??[],...ye?.changedFiles??[]])],V=typeof M.item.aggregated_output=="string"?mo(M.item.aggregated_output,ys):void 0,q=typeof M.item.exit_code=="number"?M.item.exit_code:M.item.exit_code===null?null:void 0,ge=typeof M.item.status=="string"?M.item.status:void 0;h.push({sequence:h.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}:{},...ge?{status:ge}:{},...V?{output:V.text}:{},...V?.truncated?{outputTruncated:!0}:{},...U?.beforeWorktree?{beforeWorktree:U.beforeWorktree}:{},...ye?{afterWorktree:ye}:{},...Y.length>0?{touchedFiles:Ss(t,Y,U?.beforeSnapshots??new Map)}:{}})}G&&u.delete(G)}}L==="turn.failed"&&(E=!0,O=M.error?.message||M.message||"Turn failed")}catch{}});let I=[];k.stderr?.on("data",b=>{I.push(b.toString())}),k.on("close",b=>{R.close(),p.length===0&&C.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...C].join(", ")}`),b!==0&&b!==null&&(E=!0,O=I.join("")||`Codex process exited with code ${b}`),x({sessionId:m,text:p.join(""),success:!E,error:E?O:void 0,editEvents:h.length>0?h:void 0,toolsUsed:y.length>0?y:void 0})}),k.on("error",b=>{E=!0,O=b.message,x({sessionId:m,text:p.join(""),success:!1,error:O,editEvents:h.length>0?h:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:k,result:P}}import{spawn as Rs}from"child_process";import{createInterface as Ps}from"readline";function lr(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 pr(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 w=Rs(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),k=new Promise(P=>{let x,m=[],p=[],y=!1,h="",f=!1,u=setTimeout(()=>{f=!0,w.kill("SIGTERM"),setTimeout(()=>{try{w.kill("SIGKILL")}catch{}},5e3)},s),E=Ps({input:w.stdout}),O=new Set,R=[];E.on("line",I=>{if(I.trim())try{let b=JSON.parse(I),M=Gt(b);O.add(M),R.length<5&&Ts(M)&&R.push(I.slice(0,800));let L=Wt(b,["sessionId","session_id","id"],["session","conversation","thread"]);L&&!x&&(x=L);let G=ks(b,m.length===0);G&&(m.push(G),c?.({type:"delta",jobId:o,text:G},o));let U=js(b);U&&c?.({type:"thinking",jobId:o,text:U},o);let ne=Es(b);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=As(b);oe&&(y=!0,h=oe)}catch{}});let C=[];w.stderr?.on("data",I=>{C.push(I.toString())}),w.on("close",I=>{clearTimeout(u),E.close(),m.length===0&&O.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...O].join(", ")}`),R.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${R.join(`
32
+ `)}`)),f?(y=!0,h=`Timed out after ${Math.round(s/6e4)} minutes`):I!==0&&I!==null&&(y=!0,h=C.join("").trim()||h||`Copilot process exited with code ${I}`);let b=y?lr(h,i):null;P({sessionId:x,text:m.join(""),success:!y,error:b?.message,errorCode:b?.code,recoverableError:b?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),w.on("error",I=>{clearTimeout(u);let b=lr(I.message,i);P({sessionId:x,text:m.join(""),success:!1,error:b.message,errorCode:b.code,recoverableError:b.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:w,result:k}}function Gt(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 ks(o,e=!1){let n=Gt(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Le(o.delta)??Le(o.content)??Le(o.message);if(n==="assistant.message"&&e)return Le(o.message)??Le(o.content)??Le(o);if(n==="result"&&e)return Le(o.result)??Le(o.output)??Le(o.message)??Le(o);let i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof o.text=="string"&&fo(o))return o.text;if(typeof o.message=="string"&&fo(o))return o.message;if(typeof o.delta=="string"&&fo(o))return o.delta}function Le(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Le).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Le(e[n]);if(t)return t}}function Ts(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function js(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 Es(o){let e=Wt(o,["tool","toolName","tool_name","name"]),n=Wt(o,["command","cmd"]),t=Wt(o,["file","path","filename","filePath"]),r=Gt(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 As(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"&&Gt(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 fo(o){let e=Gt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as Ms,readFile as _s}from"fs/promises";import{join as ho}from"path";var In=class{constructor(e){let n=ho(e,".popmelt");this.decisionsDir=ho(n,"decisions")}async listDecisionIds(){try{return(await Ms(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 _s(ho(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 mr(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=Ls(t.assertionResults,e),i=Fs(r);return{status:i,summary:ot(t.summary)||yr(i),assertionResults:r,tooling:zs(t.tooling)}}catch{}return{status:"needs_review",summary:Us(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 fr(o,e){let n=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length?[f.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(f=>f.path),i=[...new Set(r.map(f=>f.map(String).join(".")).filter(Boolean))].map(f=>({kind:"model_path",value:f}));if(i.length===0||o.decisionIds.length===0)return[];let s=new Set(o.decisionIds),c=new Set(i.map(f=>f.value)),d=e.cases.find(f=>f.status!=="rejected"&&(f.sourceDecisionIds.some(u=>s.has(u))||(f.dependencies??[]).some(u=>u.kind==="model_path"&&c.has(u.value)))),l=(o.selectedChanges??[]).find(f=>f.label?.trim())?.label?.trim()??t.find(f=>f.label?.trim())?.label?.trim()??o.title,w=d?.id.startsWith("eval-model-")??!1,k=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length>0?[{path:f.path,value:f.value,label:f.label,detail:f.detail}]:[]),x=(k.length>0?k:t.map(f=>({path:f.path,value:f.value,label:f.label,detail:f.rationale}))).flatMap(f=>Cs(f,o.decisionIds)),m=bn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!w?d.assertions:[],...x,...x.length===0&&m?[m]:[]])],y=i[0].value,h=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!w?d.title:l,status:"pending",category:d?.category??h,prompt:d&&!w?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!w?d.rationale:Ds(y),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...i].map(f=>[`${f.kind}:${f.value}`,f])).values()]}]}function Cs(o,e){let n=String(o.path[0]??"");if(n==="rules")return $s(o.value,e);if(n==="components"){let s=hr(String(o.path[1]??o.label??"component")),c=wn(o.value),d=c?Kt(c.usage):[];if(d.length>0){let w=Js(d),k=d.length===1?"uses":"use";return[`The ${w} ${k} 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?ot(c.constraint):"";if(l){let w=Os(l,s);if(w)return[w]}}if(n==="tokens"){let s=o.path.slice(1).map(String).join("."),c=wn(o.value),d=c&&"value"in c?c.value:o.value,l=Ns(d);if(s&&l)return[`The ${s} token resolves to ${l}.`]}let t=wn(o.value),r=t?ot(t.text)||ot(t.constraint):typeof o.value=="string"?o.value:"",i=bn(r||o.detail||"");return i?[i]:[]}function $s(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(s=>{let c=wn(s),d=c?ot(c.text):"";return d?[{text:d,sources:c?Kt(c.sources):[]}]:[]}),r=t.filter(s=>s.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(s=>bn(s.text)).filter(s=>!!s)}function Os(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?kt(`Wherever ${Vt(n[1])}, the shared ${e} implementation is used instead of ${Vt(n[2])}`):bn(o)}function go(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return kt(`${ur(n[1])} is ${Vt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return kt(ur(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return kt(`The product uses ${Vt(r[1])}`);let i=e.match(/^Do not (.+?)\.?$/i);return i?kt(`The product does not ${Vt(i[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":kt(e)}var bn=go;function Ds(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${hr(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 wn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function hr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function Js(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 Ns(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function kt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function ur(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Vt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function gr(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
34
 
35
35
  ## Eval
36
36
  \`\`\`json
@@ -86,14 +86,14 @@ The block must be valid JSON with this shape:
86
86
  \`\`\`
87
87
 
88
88
  Allowed statuses: pass, fail, needs_review.
89
- Allowed chromeDevtools values: available, unavailable, unknown.`}function tt(o){return typeof o=="string"?o.trim():""}function Vt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function _i(o){let e=tt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ci(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let s=r,i=tt(s.assertion);return i?{assertion:i,status:_i(s.status)??"needs_review",summary:tt(s.summary)||ur("needs_review"),evidence:Vt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function $i(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Oi(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=tt(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Vt(e.evidenceTypes).length>0?Vt(e.evidenceTypes):["screenshot"]}}function 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 Di(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Ji}from"crypto";import{mkdir as Ni,writeFile as Bi}from"fs/promises";import{join as mo}from"path";var wn=class{constructor(e){this.root=mo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=mo(this.root,"eval-screenshots"),t=Ji("sha256").update(e).digest("hex"),r=mo(n,`${t}.webp`);return await Ni(n,{recursive:!0}),await Bi(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as mr}from"crypto";import{mkdir as fo,readFile as ho,writeFile as In}from"fs/promises";import{dirname as go,join as kt}from"path";var He="[ProjectionWorker]",Li={version:1,runs:[]},Fi={version:1,updatedAt:0,proposals:[]},zi=12;function Ui(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(`${He} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${He} Rule count ${e.length} exceeds cap of 30`),e}function qi(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Hi(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let g of s){if(!g||typeof g!="object")continue;let p=g.sources;if(Array.isArray(p))for(let y of p)typeof y=="string"&&t.has(y)&&r.add(y)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},d=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},c=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,y=typeof p=="string"?c.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(g)}).length,h=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},I=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(h[g])).length,b=Object.keys(d).filter(g=>JSON.stringify(d[g])!==JSON.stringify(R[g])).length;return{ruleCount:l,tokenSectionCount:I,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function Wi(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Gi(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function bn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Gi(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=Wi(n)}function hr(o,e){let n=o;for(let r=0;r<e.length-1;r++){let s=n[String(e[r])];if(!s||typeof s!="object")return;n=s}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Vi(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 Ki(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=Vi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Ki(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=kt(e,".popmelt");this.runsPath=kt(t,"projection-runs.json"),this.legacyRunsPath=kt(t,"materialization-runs.json"),this.proposalsPath=kt(t,"projection-queue.json"),this.legacyProposalsPath=kt(t,"model-proposals.json"),this.modelPath=kt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ho(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Ui(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(zi),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let s=r.map(g=>g.id);console.log(`${He} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),d=Zi(r,i),c=qi(r,t.totalCandidateDecisionCount,d);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:s,startedAt:Date.now(),promptStats:c};await this.persistRun(l);let h=!0,R,I,b;try{let g=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(g,d,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await y;if(!f.success)h=!1,R=f.error,console.error(`${He} ${p} spawn error:`,R);else{let v=Yi(f.text,s);if(v){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of v)bn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=fr(x.rules));let S=Hi(x,s,i);if(v){let J=[...new Set(v.flatMap(_=>_.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(_=>!J.includes(_))}I=S;let A=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:I,changes:v});b=A.id,console.log(`${He} Created model proposal ${A.id} for ${s.length} decision(s)`)}else h=!1,R="No valid bounded <model-changes> block found in response",console.error(`${He} ${R}`)}}catch(g){h=!1,R=g instanceof Error?g.message:String(g),console.error(`${He} Error:`,R)}return await this.persistRun({...l,status:h?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:I,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:h,error:R}),{processedIds:s,success:h,error:R,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=fr(e.rules)),await In(this.modelPath,JSON.stringify(e,null,2)),console.log(`${He} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await fo(go(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2)),n):{...Li,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(s=>s.authorityStatus==="accepted"&&Array.isArray(s.changes)&&s.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Fi,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let s=structuredClone(t);for(let i of r.changes??[])bn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let c of n)!Array.isArray(c.path)||c.path.length===0||(c.remove?hr(i,c.path):bn(i,c.path,c.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let d=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(d.evalId),s.set(d.evalId,d)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:mr().slice(0,8),status:"pending",title:Qi(e.proposedModel),summary:e.outputStats?`Proposes ${e.outputStats.ruleCount} rule, ${e.outputStats.componentCount} component, and ${e.outputStats.tokenSectionCount} token change${e.outputStats.ruleCount+e.outputStats.componentCount+e.outputStats.tokenSectionCount===1?"":"s"} from ${e.decisionIds.length} accepted decision${e.decisionIds.length===1?"":"s"}.`:Xi(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(s=>s.id!==e?s:(r={...s,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await fo(go(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await In(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await fo(go(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await ho(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await ho(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(d,c)=>this.options.onEvent?.(d):void 0;return s==="codex"?{provider:"codex",...hn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:un(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${He} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...mn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:s==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:i})})}};function Qi(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Xi(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 Yi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,d)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let c=i;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(R=>typeof R=="string"||typeof R=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let h=Array.isArray(c.decisionIds)?c.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return h.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${d+1}`,path:c.path,value:c.value,decisionIds:h,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Zi(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
90
- Kind: ${s.kind}
91
- Claim: ${s.claim}
92
- ${s.rationale?`Rationale: ${s.rationale}`:""}
93
- Subjects: ${s.subjects.map(i=>`${i.role}:${i.subjectId}`).join(", ")}
94
- Authority: ${s.authority.level}/${s.authority.mode}`).join(`
89
+ Allowed chromeDevtools values: available, unavailable, unknown.`}function ot(o){return typeof o=="string"?o.trim():""}function Kt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Bs(o){let e=ot(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ls(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let i=r,s=ot(i.assertion);return s?{assertion:s,status:Bs(i.status)??"needs_review",summary:ot(i.summary)||yr("needs_review"),evidence:Kt(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 Fs(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function zs(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=ot(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Kt(e.evidenceTypes).length>0?Kt(e.evidenceTypes):["screenshot"]}}function yr(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 Us(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as qs}from"crypto";import{mkdir as Hs,writeFile as Ws}from"fs/promises";import{join as yo}from"path";var xn=class{constructor(e){this.root=yo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=yo(this.root,"eval-screenshots"),t=qs("sha256").update(e).digest("hex"),r=yo(n,`${t}.webp`);return await Hs(n,{recursive:!0}),await Ws(r,e,{flag:"wx"}).catch(i=>{if(i.code!=="EEXIST")throw i}),r}};import{randomUUID as vr}from"crypto";import{mkdir as vo,readFile as Io,writeFile as Sn}from"fs/promises";import{dirname as wo,join as Tt}from"path";var He="[ProjectionWorker]",Gs={version:1,runs:[]},Vs={version:1,updatedAt:0,proposals:[]},Ks=12;function Qs(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 Ir(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${He} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${He} Rule count ${e.length} exceeds cap of 30`),e}function Xs(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ys(o,e,n){let t=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let m of i){if(!m||typeof m!="object")continue;let p=m.sources;if(Array.isArray(p))for(let y of p)typeof y=="string"&&t.has(y)&&r.add(y)}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(m=>{if(!m||typeof m!="object")return!1;let p=m.id,y=typeof p=="string"?d.find(h=>h&&typeof h=="object"&&h.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(m)}).length,w=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},k=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},P=Object.keys(s).filter(m=>JSON.stringify(s[m])!==JSON.stringify(w[m])).length,x=Object.keys(c).filter(m=>JSON.stringify(c[m])!==JSON.stringify(k[m])).length;return{ruleCount:l,tokenSectionCount:P,componentCount:x,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(m=>!r.has(m))}}function Zs(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function ea(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 Rn(o,e,n){let t=o;for(let i=0;i<e.length-1;i++)t=ea(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=Zs(n)}function wr(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 ta(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 na(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 br(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=ta(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?na(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Pn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Tt(e,".popmelt");this.runsPath=Tt(t,"projection-runs.json"),this.legacyRunsPath=Tt(t,"materialization-runs.json"),this.proposalsPath=Tt(t,"projection-queue.json"),this.legacyProposalsPath=Tt(t,"model-proposals.json"),this.modelPath=Tt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Io(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Qs(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?wr(n,r):Rn(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(Ks),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(m=>m.id);console.log(`${He} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=sa(r,s),d=Xs(r,t.totalCandidateDecisionCount,c);n=vr().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 w=!0,k,P,x;try{let m=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(m,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let h=await y;if(!h.success)w=!1,k=h.error,console.error(`${He} ${p} spawn error:`,k);else{let f=ia(h.text,i);if(f){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let R of f)Rn(u,R.path,R.value);Array.isArray(u.rules)&&(u.rules=Ir(u.rules));let E=Ys(u,i,s);if(f){let R=[...new Set(f.flatMap(C=>C.decisionIds))];E.coveredDecisionIds=R,E.uncoveredDecisionIds=i.filter(C=>!R.includes(C))}P=E;let O=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:P,changes:f});x=O.id,console.log(`${He} Created model proposal ${O.id} for ${i.length} decision(s)`)}else w=!1,k="No valid bounded <model-changes> block found in response",console.error(`${He} ${k}`)}}catch(m){w=!1,k=m instanceof Error?m.message:String(m),console.error(`${He} Error:`,k)}return await this.persistRun({...l,status:w?"proposed":"failed",completedAt:Date.now(),error:k,outputStats:P,proposalId:x}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:w,error:k}),{processedIds:i,success:w,error:k,runId:n,proposalId:x}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ir(e.rules)),await Sn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${He} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await vo(wo(this.runsPath),{recursive:!0}),await Sn(this.runsPath,JSON.stringify(n,null,2)),n):{...Gs,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??{...Vs,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??[])Rn(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?wr(s,d.path):Rn(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:vr().slice(0,8),status:"pending",title:oa(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"}.`:ra(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 vo(wo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await Sn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await vo(wo(this.runsPath),{recursive:!0}),await Sn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await Io(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await Io(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",...vn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:hn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${He} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...gn(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 oa(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 ra(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 ia(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(k=>typeof k=="string"||typeof k=="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 w=Array.isArray(d.decisionIds)?d.decisionIds.filter(k=>typeof k=="string"&&r.has(k)):[];return w.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:w,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===t.length?i:null}catch{return null}}function sa(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
95
 
96
- `),t=o.map(s=>s.id);return`You are extracting a local design model from accumulated design decisions.
96
+ `),t=o.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
97
97
 
98
98
  ## Instructions
99
99
  1. Review the current model (if any) and the new decisions below.
@@ -165,78 +165,78 @@ Example:
165
165
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
166
166
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
167
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 ea}from"child_process";import{readFile as vo}from"fs/promises";import{homedir as Rn}from"os";import{join as Be}from"path";var wo=/popmelt/i,ta=/chrome|devtools/i;function vt(){return{found:!1,name:null,scope:null,disabled:!1}}function Tt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Kt(o){for(let e of Object.keys(o))if(wo.test(e))return e;return null}async function Pn(o){try{let e=await vo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function Io(o){let e=Rn(),n=await Pn(Be(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Kt(r.mcpServers);if(s)return Tt(s,"user")}if(r.projects&&typeof r.projects=="object"){let i=r.projects[o];if(i&&typeof i=="object"){let d=i;if(d.mcpServers&&typeof d.mcpServers=="object"){let c=Kt(d.mcpServers);if(c){let l=Array.isArray(d.disabledMcpjsonServers)&&d.disabledMcpjsonServers.some(h=>wo.test(h));return Tt(c,"project",l)}}}}}let t=await Pn(Be(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Kt(r.mcpServers);if(i){let d=await yr(o,i);return Tt(i,"mcp.json",d)}}let s=Kt(r);if(s&&s!=="mcpServers"){let i=await yr(o,s);return Tt(s,"mcp.json",i)}}return vt()}async function yr(o,e){let n=Be(o,".claude","settings.local.json"),t=await Pn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(s=>s===e)}return!1}var na=/^\[mcp_servers\.([^\]]+)\]/;function oa(o){return o.replace(/^"(.+)"$/,"$1")}function ra(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 s=r.match(na);s?(t&&n.push({name:t.name,body:t.bodyLines.join(`
170
- `)}),t={name:s[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
168
+ Include property and bindings when the decision context has class-level evidence.`}var kn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as aa}from"child_process";import{readFile as xo}from"fs/promises";import{homedir as jn}from"os";import{join as Be}from"path";var So=/popmelt/i,ca=/chrome|devtools/i;function It(){return{found:!1,name:null,scope:null,disabled:!1}}function jt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Qt(o){for(let e of Object.keys(o))if(So.test(e))return e;return null}async function Tn(o){try{let e=await xo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function Ro(o){let e=jn(),n=await Tn(Be(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Qt(r.mcpServers);if(i)return jt(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=Qt(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(w=>So.test(w));return jt(d,"project",l)}}}}}let t=await Tn(Be(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Qt(r.mcpServers);if(s){let c=await xr(o,s);return jt(s,"mcp.json",c)}}let i=Qt(r);if(i&&i!=="mcpServers"){let s=await xr(o,i);return jt(i,"mcp.json",s)}}return It()}async function xr(o,e){let n=Be(o,".claude","settings.local.json"),t=await Tn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var da=/^\[mcp_servers\.([^\]]+)\]/;function la(o){return o.replace(/^"(.+)"$/,"$1")}function pa(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function Rr(o){let e=o.split(`
169
+ `),n=[],t=null;for(let r of e){let i=r.match(da);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
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 bo(o){let e=process.env.CODEX_HOME||Be(Rn(),".codex"),n=await vr(Be(e,"config.toml"),"user");if(n.found)return n;let t=await vr(Be(o,".codex","config.toml"),"project");return t.found?t:vt()}async function sa(o,e){let n=process.env.CODEX_HOME||Be(Rn(),".codex"),t=new Set;for(let r of[Be(n,"config.toml"),Be(o,".codex","config.toml")])try{let s=await vo(r,"utf-8");for(let i of wr(s)){if(ra(i.name)||Ir(i.body))continue;let d=oa(i.name);e.test(d)&&t.add(d)}}catch{}return[...t]}async function br(o){return sa(o,ta)}async function xo(o,e="copilot"){let n=await ia(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Be(Rn(),".copilot"),r=await yo(Be(t,"mcp-config.json"),"user");if(r.found)return r;let s=await yo(Be(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await yo(Be(o,".github","mcp.json"),"mcp.json");return i.found?i:vt()}async function ia(o){try{let e=await new Promise((n,t)=>{ea(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return xr(JSON.parse(e),"user")}catch{return vt()}}async function yo(o,e){let n=await Pn(o);return xr(n,e)}function xr(o,e){if(!o||typeof o!="object")return vt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Kt(t);return r?Tt(r,e):vt()}async function vr(o,e){try{let n=await vo(o,"utf-8"),t=wr(n);for(let r of t)if(wo.test(r.name)){let s=Ir(r.body);return Tt(r.name,e,s)}}catch{}return vt()}import{execFile as Sr}from"child_process";import{mkdir as aa,readFile as Pr,writeFile as Rr}from"fs/promises";import{homedir as kr}from"os";import{dirname as ca,join as So}from"path";var Po="https://mcp.popmelt.com/mcp";async function Tr(o=Po){let e=So(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=Po){let e=process.env.CODEX_HOME||So(kr(),".codex"),n=So(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 aa(ca(n),{recursive:!0});let r=`
172
+ `)}),n}function Pr(o){return/enabled\s*=\s*false/i.test(o)}async function Po(o){let e=process.env.CODEX_HOME||Be(jn(),".codex"),n=await Sr(Be(e,"config.toml"),"user");if(n.found)return n;let t=await Sr(Be(o,".codex","config.toml"),"project");return t.found?t:It()}async function ua(o,e){let n=process.env.CODEX_HOME||Be(jn(),".codex"),t=new Set;for(let r of[Be(n,"config.toml"),Be(o,".codex","config.toml")])try{let i=await xo(r,"utf-8");for(let s of Rr(i)){if(pa(s.name)||Pr(s.body))continue;let c=la(s.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function kr(o){return ua(o,ca)}async function ko(o,e="copilot"){let n=await ma(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Be(jn(),".copilot"),r=await bo(Be(t,"mcp-config.json"),"user");if(r.found)return r;let i=await bo(Be(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await bo(Be(o,".github","mcp.json"),"mcp.json");return s.found?s:It()}async function ma(o){try{let e=await new Promise((n,t)=>{aa(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return Tr(JSON.parse(e),"user")}catch{return It()}}async function bo(o,e){let n=await Tn(o);return Tr(n,e)}function Tr(o,e){if(!o||typeof o!="object")return It();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Qt(t);return r?jt(r,e):It()}async function Sr(o,e){try{let n=await xo(o,"utf-8"),t=Rr(n);for(let r of t)if(So.test(r.name)){let i=Pr(r.body);return jt(r.name,e,i)}}catch{}return It()}import{execFile as jr}from"child_process";import{mkdir as fa,readFile as Er,writeFile as Ar}from"fs/promises";import{homedir as Mr}from"os";import{dirname as ha,join as To}from"path";var jo="https://mcp.popmelt.com/mcp";async function _r(o=jo){let e=To(Mr(),".claude.json"),n;try{let r=await Er(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 Ar(e,JSON.stringify(n,null,2)+`
173
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Cr(o=jo){let e=process.env.CODEX_HOME||To(Mr(),".codex"),n=To(e,"config.toml"),t;try{t=await Er(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await fa(ha(n),{recursive:!0});let r=`
174
174
  [mcp_servers.popmelt]
175
175
  url = "${o}"
176
- `;return await Rr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Er(o=Po,e="copilot"){let n=await da(e);if(la(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},s=>{if(s){r(s);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function da(o){try{let e=await new Promise((n,t)=>{Sr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return JSON.parse(e)}catch{return null}}function la(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var kn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),s={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,s),s}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as Co,readFile as At,writeFile as $o}from"fs/promises";import{join as pt}from"path";var pa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Ro(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Tn(o){return new Set(Ro(o).split(" ").filter(e=>e.length>2&&!pa.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 ua(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 ma(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Ro).filter(Boolean),s=Tn([e.action,e.text].filter(Boolean).join(" "));for(let i of o){if(t.has(i.id)){n.set(i.id,{subjectId:i.id,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let d;for(let c of ua(i)){let l=Ro(c.value);for(let I of r){let b=l===I?95:l.includes(I)||I.includes(l)?75:0;b>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:b>=90?"exact":"strong",matchedBy:c.by,score:b})}let R=["/","#","[","]","="].some(I=>c.value.includes(I))?0:Math.round(Mr(Tn(l),s)*55);R>=30&&R>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}d&&n.set(i.id,d)}return n}function fa(o,e){let n=new Set(o.sourceRefs.filter(i=>i.kind==="iteration").map(i=>i.id)),t=new Set(o.sourceRefs.filter(i=>i.kind==="thread").map(i=>i.id)),r=e.filter(i=>i.iterationIds.some(d=>n.has(d))||i.sourceRefs.some(d=>d.kind==="thread"&&t.has(d.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let s=new Set(r.map(i=>i.state));return{state:s.size>1?"mixed":s.has("completed")?"completed":"attempted",attemptIds:r.map(i=>i.id)}}function ha(o){return Math.ceil(JSON.stringify(o).length/4)}function ko(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let f=[...o.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===y.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(y=>y.recordType==="implementation_attempt"),d=ma(n,e),c=[...d.values()].sort((y,f)=>f.score-y.score),l=Tn([e.action,e.text].filter(Boolean).join(" ")),h=s.flatMap(y=>{let f=y.subjects.map(A=>d.get(A.subjectId)).filter(A=>!!A),v=Math.max(0,...f.map(A=>A.score)),x=Math.round(Mr(Tn(y.claim),l)*35),S=v+x;return S>=50?[{proposal:y,proposalMatches:f,score:S}]:[]}).sort((y,f)=>f.score-y.score||y.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),I=Math.max(200,e.maxEstimatedTokens??1200),b=[],g=0;for(let y of h){if(b.length>=R)break;let f=y.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:S,...A})=>A)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(S=>S.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:fa(y.proposal,i),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...f]},x={...v,estimatedTokens:ha(v)};if(g+x.estimatedTokens>I)break;b.push(x),g+=x.estimatedTokens}let p=Math.max(0,h.length-b.length);return{packets:b,subjectMatches:c.map(({score:y,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:h.length,omittedPacketCount:p,maxEstimatedTokens:I,estimatedTokens:g},uncertainty:d.size===0?"subject_unresolved":h.length===0?"no_relevant_pending_proposal":void 0}}var ga=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function To(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function jn(o){return new Set(To(o).split(" ").filter(e=>e.length>2&&!ga.has(e)))}function Ar(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 ya(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(To).filter(Boolean),r=jn([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let d,c=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of c){let h=To(l.value);for(let b of t){let g=h===b?95:h.includes(b)||b.includes(h)?75:0;g>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let I=["/","#","[","]","="].some(b=>l.value.includes(b))?0:Math.round(Ar(jn(h),r)*55);I>=30&&I>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:I>=45?"strong":"weak",matchedBy:"semantic",score:I})}d&&s.push(d)}return s.sort((i,d)=>d.score-i.score||i.subjectId.localeCompare(d.subjectId))}function va(o){return Math.ceil(JSON.stringify(o).length/4)}function jt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function wa(o,e){let n=e.filter(s=>s.coverageClaims.some(i=>i.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(s=>s.state==="completed"),r=t.some(s=>s.coverageClaims.some(i=>i.decisionId===o&&i.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(s=>s.id)}}function Ia(o,e,n){let t=e.filter(d=>d.targets.some(c=>c.entityType==="decision"&&c.entityId===o)).sort((d,c)=>c.createdAt.localeCompare(d.createdAt)),r=n.some(d=>d.signalType==="verification_expired"&&d.target.entityType==="decision"&&d.target.entityId===o),s=t[0],i=r?"stale":s?s.state==="passed"?"passing":s.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(s.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:i,attemptIds:t.map(d=>d.id)}}function _r(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(_=>_.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(_=>_.recordType==="decision"&&_.state==="active"),d=s?i.filter(_=>s.has(_.id)):i,c=o.records.filter(_=>_.recordType==="implementation_attempt"),l=o.records.filter(_=>_.recordType==="verification_attempt"),h=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),R=o.records.filter(_=>_.recordType==="evidence"),I=o.records.filter(_=>_.recordType==="model_entry"),b=[...o.records].reverse().filter(_=>_.recordType==="eval_spec").filter((_,N,T)=>T.findIndex(B=>B.legacyId===_.legacyId)===N),g=ya(r,e),p=new Map(g.map(_=>[_.subjectId,_.score])),y=jn([e.action,e.text].filter(Boolean).join(" ")),f=d.flatMap(_=>{let N=Math.max(0,..._.subjects.map(H=>p.get(H.subjectId)??0)),T=Math.round(Ar(jn(_.claim),y)*35),B=N+T;return B>=50?[{decision:_,score:B}]:[]}).sort((_,N)=>N.score-_.score||_.decision.id.localeCompare(N.decision.id)),v=new Map;for(let _ of f.slice(0,t))v.set(_.decision.id,_.decision);for(let _ of o.relationships){if(!jt(_,"excepts")&&!jt(_,"contradicts"))continue;let N=i.find(B=>B.id===_.from.entityId),T=i.find(B=>B.id===_.to.entityId);!N||!T||!v.has(N.id)&&!v.has(T.id)||(v.size<t&&v.set(N.id,N),v.size<t&&v.set(T.id,T))}let x=[...v.values()],S=_=>_.from.entityType==="decision"&&_.to.entityType==="decision"&&v.has(_.from.entityId)&&v.has(_.to.entityId),A=(_,N=!1)=>{let T=new Set(_.map(M=>M.id)),B=h.filter(M=>M.target.entityType==="decision"&&T.has(M.target.entityId)),H=new Set(o.relationships.filter(M=>jt(M,"excepts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).flatMap(M=>[M.from.entityId,M.to.entityId])),W=o.relationships.filter(M=>jt(M,"contradicts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).map(M=>({id:M.id,decisionIds:[M.from.entityId,M.to.entityId],unresolvedQuestion:M.reason,expansionRefs:[{kind:"record",id:M.id}]})),te=new Set(W.flatMap(M=>M.decisionIds)),ne=R.filter(M=>M.sourceRefs.some(Y=>Y.kind==="record"&&T.has(Y.id))||o.relationships.some(Y=>Y.relationshipType==="supports"&&Y.from.entityType==="evidence"&&Y.from.entityId===M.id&&Y.to.entityType==="decision"&&T.has(Y.to.entityId))),ge=Math.max(0,f.length-_.length),X=o.relationships.some(M=>jt(M,"contradicts")&&S(M)&&(!T.has(M.from.entityId)||!T.has(M.to.entityId))),G=N||ge>0||X,U=[];g.length===0&&(e.subjectHints?.length??0)>0?U.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):_.length===0&&U.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),W.length&&U.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:W.flatMap(M=>M.expansionRefs)}),ne.some(M=>M.availability!=="available")&&U.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:ne.map(M=>({kind:"record",id:M.id}))}),G&&U.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let he={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:g.map(({score:M,...Y})=>Y),modelEntries:I.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,key:M.key,value:M.value,decisionIds:M.decisionIds})),evalSpecs:b.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,legacyId:M.legacyId,state:M.state,title:M.title,assertionCount:M.assertions.length,decisionIds:M.decisionIds,expansionRef:{kind:"record",id:M.id}})),decisions:_.map(M=>({id:M.id,kind:M.kind,claim:M.claim,subjectIds:M.subjects.map(Y=>Y.subjectId),authority:M.authority,effectiveState:te.has(M.id)?"conflicted":H.has(M.id)?"excepted":"active",freshness:B.filter(Y=>Y.target.entityId===M.id).map(Y=>Y.signalType),expansionRef:{kind:"record",id:M.id}})),conflicts:W,uncertainties:U,implementation:_.map(M=>wa(M.id,c)),verification:_.map(M=>Ia(M.id,l,B)),evidence:ne.map(M=>({evidenceId:M.id,summary:M.summary,availability:M.availability,sourceRefs:M.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:ge,omittedEvidenceCount:0,conflictsComplete:!X}};return he.budget.estimatedTokens=va(he),he},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>jt(T,"contradicts")&&(T.from.entityId===_.id||T.to.entityId===_.id)).flatMap(T=>[T.from.entityId,T.to.entityId]);x=x.filter(T=>!N.includes(T.id)),J=A(x,!0)}return J}var ba=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Et(o){return ba.test(o)}function xa(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 jo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){Et(n)||ce(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function lt(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ce(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(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 Sa={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"])},Pa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ra(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),lt(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=Sa[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ce(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let s=`${e.entity.entityType}:${e.toState}`;if(Pa.has(s)&&(wt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ce(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let i=e.transitionContext;(i?.kind!=="proposal_deferral"||i.resurfaceWhen.length===0)&&ce(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),i?.resurfaceWhen.includes("after_date")&&!i.revisitAfter&&ce(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),i?.revisitAfter&&lt(o,`${n}.transitionContext.revisitAfter`,i.revisitAfter)}}function ka(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),lt(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"&&(wt(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"&&jo(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"&&(lt(o,`${n}.appliedAt`,e.appliedAt),wt(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&&jo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&jo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ta(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),lt(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?wt(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 It(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),lt(e,"manifest.createdAt",o.manifest.createdAt),lt(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,y)=>{let f=n.get(p);f?ce(e,y,"duplicate_id",`ID is already used at ${f}.`):n.set(p,y)};o.records.forEach((p,y)=>{let f=`records[${y}]`;t(p.id,f),ka(e,p,f,o.manifest.projectId)}),o.events.forEach((p,y)=>{let f=`events[${y}]`;t(p.id,f),Ra(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let f=`relationships[${y}]`;t(p.id,f),Ta(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let f=`tombstones[${y}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),lt(e,`${f}.deletedAt`,p.deletedAt),wt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,y)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,y,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,y)=>i(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{i(p.from,`relationships[${y}].from`),i(p.to,`relationships[${y}].to`)});let d=new Set(o.artifacts.map(p=>p.id)),c=(p,y)=>{d.has(p)||ce(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,f)=>{!r.has(`${p}:${y}`)&&!s.has(`${p}:${y}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let f=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((v,x)=>l("subject",v,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((v,x)=>c(v,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((v,x)=>l("subject",v.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((v,x)=>c(v,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((v,x)=>i(v,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((v,x)=>l("thread",v,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((v,x)=>l("iteration",v,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((v,x)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((v,x)=>{v.subjectIds?.forEach((S,A)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${A}]`))}),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`));break;case"model_projection":wt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((v,x)=>l("model_entry",v,`${f}.entryIds[${x}]`)),p.coverage.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;default:break}});let h=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),I=new Map;o.events.forEach((p,y)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,v=I.get(f)??new Set;v.add(p.toState),I.set(f,v),v.size>1&&ce(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,y,f,v,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=b.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==y||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(f);(A<Date.parse(S.startsAt)||S.endsAt&&A>Date.parse(S.endsAt)||S.revokedAt&&A>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&v.length&&!v.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(y=>y.subjectId),`records:${p.id}.authority`);o.events.forEach((p,y)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),v=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,v,`events[${y}].authority`)}),o.relationships.forEach((p,y)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(v=>{let x=R.get(`${v.entityType}:${v.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${y}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let y=h.get(p.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==p.proposalId||y.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===p.id&&v.toState==="revoked"&&!!v.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return xa(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 ja(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function En(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Et(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of ja(e))Et(s)||n.push({code:"invalid_generated_id",message:`${s} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let s={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=Cr(o,t,e,s.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:i.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let s={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},i={...Qt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},d={...Qt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Cr(o,s,e,d.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,c],events:[i,d],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ea}from"crypto";import{readFile as Ma,readdir as Aa,realpath as _a}from"fs/promises";import{join as Xt,relative as Ca}from"path";var $a=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Mt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Fe(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function $r(...o){return o.find(e=>!!e?.trim())?.trim()}function ye(o,e,n,t){let s=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),i=Ea("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),d=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${d}${i.slice(4,7)}-${i.slice(7,19)}`}async function Eo(o,e){try{return JSON.parse(await Ma(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Oa(o){let e=Mt(o);if(!e)return 0;let n=0,t=r=>{let s=Mt(r);if(!s){n+=1;return}for(let i of Object.values(s))t(i)};for(let r of Object.values(e))t(r);return n}function Da(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 _a(o.projectRoot).catch(()=>o.projectRoot),t=Xt(n,".popmelt"),r=await Eo(Xt(t,"threads.json"),e),s=await Eo(Xt(t,"model.json"),e),i=Mt(r),d=Mt(i?.threads)??{},c=Object.entries(d).map(([M,Y])=>({key:M,value:Mt(Y)})).filter(M=>!!M.value),l=Xt(t,"decisions"),h=await Aa(l).catch(()=>[]),R=[];for(let M of h.filter(Y=>Y.endsWith(".json")).sort()){let Y=Mt(await Eo(Xt(l,M),e));Y&&R.push({file:M,value:Y})}let I=c.flatMap(({value:M})=>[M.createdAt,M.updatedAt]).filter(M=>typeof M=="number"&&Number.isFinite(M)),b=I.length?Math.min(...I):0,g=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ye(g,"project",g,b),y=ye(g,"participant","legacy-owner",b),f=ye(g,"participant","legacy-agent",b),v=ye(g,"subject","project",b),x=Fe(Math.max(b,...I)),S=[],A=[],J=new Map,_=new Map,N=new Map(R.map(M=>[M.value.id??M.file.replace(/^d-|\.json$/g,""),M.value])),T=new Map,B=(M,Y,ue,ie,De)=>{let Je=J.get(ue);if(Je)return Je;let Pe=ye(g,"artifact",M,ie);return A.push({id:Pe,kind:Y,mediaType:De,location:ue,availability:"available"}),J.set(ue,Pe),Pe};for(let{file:M,value:Y}of R){let ue=Y.id??M.replace(/^d-|\.json$/g,""),ie=Y.createdAt??b,De=[B(`${ue}:envelope`,"other",`.popmelt/decisions/${M}`,ie,"application/json")];Y.screenshotPath&&De.push(B(`${ue}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,ie,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Je,Pe]of(Y.pastedImagePaths??[]).entries())De.push(B(`${ue}:image:${Je}`,"image",Pe,ie));T.set(ue,De)}let H=(M,Y,ue)=>({id:M,schemaVersion:1,projectId:p,createdAt:x,participantId:Y,sourceRefs:ue}),ee=(M,Y)=>{S.push(Y);let ue=_.get(M)??[];ue.push(Y.id),_.set(M,ue)},W=[{...H(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...H(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...W),S.push({...H(v,y,[]),recordType:"subject",subjectType:"project",label:Ca(process.cwd(),n)||n,aliases:[],locators:[{id:ye(g,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:Fe(b),sourceRefs:[]}]});let te=new Map,ne=(M,Y)=>{let ue=te.get(M);if(ue)return ue;let ie=ye(g,"subject",M,Y),De={...H(ie,y,[{kind:"external",id:M}]),createdAt:Fe(Y),recordType:"subject",subjectType:"element",label:M,aliases:[],locators:[{id:ye(g,"locator",M,Y),kind:"dom_selector",value:M,status:"current",validFrom:Fe(Y),sourceRefs:[{kind:"external",id:M}]}]};return S.push(De),te.set(M,ie),ie};for(let{key:M,value:Y}of c){let ue=Y.id??M,ie=Y.createdAt??b,De=ye(g,"thread",ue,ie),Je={kind:"thread",id:ue},Pe=[],Ue=[],Ge=Array.isArray(Y.messages)?Y.messages:[],Ye,st,mt=0;Ge.forEach((we,it)=>{let Ae=we.timestamp??ie,Ze=ye(g,"artifact",`${ue}:message:${it}`,Ae);if(Pe.push(Ze),A.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${it}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${ue}/messages/${it}`,Ze),we.screenshotPath&&B(`${ue}:message:${it}:screenshot`,"screenshot",we.screenshotPath,Ae),we.role==="human"){Ye=we;let je=we.feedbackSummary??we.replyToQuestion;if(je?.trim()){let Ne=ye(g,"observation",`${ue}:${it}`,Ae),dt=Y.elementIdentifiers??[],Pt={...H(Ne,y,[Je,{kind:"message",id:Ze}]),createdAt:Fe(Ae),recordType:"observation",state:"open",statement:je,captureContext:{subjectIds:dt.map(ht=>ne(ht,ie)),artifactIds:[Ze]},resolvedByIds:[]};ee(ue,Pt),st=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let at=we.jobId??`${ue}:${it}`,ct=ye(g,"iteration",at,Ae),ft=N.get(at),ro=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",so={...H(ct,f,[Je,{kind:"message",id:Ze},...(T.get(at)??[]).map(je=>({kind:"artifact",id:je}))]),createdAt:Fe(Ae),recordType:"iteration",threadIds:[De],startedAt:Fe(Ye?.timestamp,Ae),completedAt:Fe(Ae),requestSummary:$r(Ye?.feedbackSummary,Ye?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:ro,execution:{provider:we.provider??ft?.provider,model:we.model??ft?.model,sessionId:we.sessionId??ft?.sessionId},artifactIds:[Ze,...T.get(at)??[]]};ee(ue,so),Ue.push({entityType:"iteration",entityId:ct});let zt=we.resolutions??ft?.resolutions??[];for(let[je,Ne]of zt.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let dt=Y.elementIdentifiers??[],Pt=(dt.length?dt:[n]).map(ln=>({subjectId:ln===n?v:ne(ln,ie),role:"governed"})),ht=ye(g,"proposal",`${at}:${Ne.annotationId??"resolution"}:${je}`,Ae),io={...H(ht,f,[Je,{kind:"iteration",id:ct}]),createdAt:Fe(Ae),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:Pt,subjectSemantics:Pt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:$r(Ye?.feedbackSummary,Ye?.replyToQuestion,Ne.summary),iterationId:ct,inferredById:f}};ee(ue,io),Ue.push({entityType:"proposal",entityId:ht}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${ht} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(zt.some(je=>je.status==="resolved")||ft?.gitDiff){let je=ye(g,"implementation",at,Ae),Ne={...H(je,f,[Je,{kind:"iteration",id:ct}]),createdAt:Fe(Ae),recordType:"implementation_attempt",state:"completed",iterationIds:[ct],coverageClaims:[],summary:zt.map(dt=>dt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};ee(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:je}),mt+=1}st&&(st=void 0)});let Lt=Ge.at(-1),Ft={...H(De,y,[Je]),createdAt:Fe(ie),recordType:"thread",state:Lt?.question?"open":"resolved",messageArtifactIds:Pe,outcome:Lt?.question?"question_unresolved":mt?"implementation_only":"no_outcome",resultRefs:Ue};S.push(Ft),_.set(ue,[De,..._.get(ue)??[]])}let ge=Oa(s);ge&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ge} model values were not promoted because their accepted decision provenance is unresolved.`});let X={manifest:{formatVersion:1,projectId:p,createdAt:Fe(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:A,tombstones:[]},G=It(X),he=(o.proofCaseIds??$a).map(M=>({legacyId:M,threadFound:c.some(({key:Y,value:ue})=>(ue.id??Y)===M),decisionEnvelopeFound:N.has(M),recordIds:_.get(M)??[]}));return{bundle:X,report:{projectRoot:n,source:{threads:c.length,messages:c.reduce((M,Y)=>M+(Y.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:ge,artifactsReferenced:A.length},imported:Da(S),unresolvedAcceptance:e.filter(M=>M.code==="acceptance_unresolved").length,deferredModelEntries:ge,proofCases:he,issues:e,schemaIssues:G.issues}}}import{createHash as Ja}from"crypto";import{mkdir as Or,open as Mo,readFile as Ao,readdir as Na,rename as Ba,unlink as _o}from"fs/promises";import{join as nt}from"path";var La={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function An(o){return Ja("sha256").update(JSON.stringify(o)).digest("hex")}function Dr(o){return An(o)}function Jr(o,e,n){for(let t of e.projectionUpdates){let r=o.records.find(s=>s.recordType===t.entityType&&s.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Fa(o,e,n){return Jr(structuredClone(o),e,n)}async function bt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Mo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
177
- `,"utf8"),await t.sync()}finally{await t.close()}try{await Ba(n,o)}catch(r){throw await _o(n).catch(()=>{}),r}}async function Mn(o){return JSON.parse(await Ao(o,"utf8"))}var _n=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=nt(e,".popmelt","memory"),this.journalDir=nt(this.memoryDir,"journal"),this.manifestPath=nt(this.memoryDir,"manifest.json"),this.checkpointPath=nt(this.memoryDir,"checkpoint.json"),this.lockPath=nt(this.memoryDir,"writer.lock")}async initialize(e){let n=It(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 Ao(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 Ao(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}let t=An(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},s={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await bt(this.checkpointPath,r),await bt(this.manifestPath,s)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await bt(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=An(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 bt(nt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await bt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Et(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,s={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},i={...s,hash:Dr(s)},d=Fa(t.bundle,e,n.committedAt),c=It(d);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await bt(nt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await bt(this.manifestPath,t.manifest),{bundle:d,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:i.hash}}}))}async commitReviewPlan(e,n){return this.commit({...La,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(nt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==An(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Na(this.journalDir),r=t.filter(I=>I.endsWith(".tmp")),i=t.filter(I=>/^\d{12}-[0-9a-f-]+\.json$/i.test(I)).sort().filter(I=>Number(I.slice(0,12))>n.sequence),d=structuredClone(n.bundle),c=n.sequence,l=n.journalHash??null,h=new Set;for(let I of i){let b=await Mn(nt(this.journalDir,I)),{hash:g,...p}=b;if(g!==Dr(p))throw new Error(`Journal hash mismatch: ${I}`);if(b.sequence!==c+1)throw new Error(`Journal sequence gap at ${I}`);if(b.previousHash!==l)throw new Error(`Journal chain mismatch at ${I}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${I}`);if(h.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);Jr(d,b.mutation,b.committedAt),c=b.sequence,l=b.hash,h.add(b.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=It(d);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:d,manifest:e,transactionIds:h,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:c,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Or(this.memoryDir,{recursive:!0});let n;try{n=await Mo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Mn(this.lockPath).catch(()=>({})),s=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(i){s=i.code!=="ESRCH"}if(s)throw new Error("Memory journal is locked by another writer.");await _o(this.lockPath),n=await Mo(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 za}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=za(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 Ua=()=>({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,s=`${e.threadId}:${e.jobId}`,i=new Date(e.createdAt).toISOString(),d=new Date(e.completedAt).toISOString(),c=Ua(),l=c.records,h=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));h||(h={id:ye(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(x=>x.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(h));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"element",label:x,aliases:[],locators:[{id:ye(r,"live-locator",x,e.createdAt),kind:"dom_selector",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}for(let x of[...new Set((e.filePaths??[]).filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.kind==="source_file"&&J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-file-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"file",label:x,aliases:[],locators:[{id:ye(r,"live-file-locator",x,e.createdAt),kind:"source_file",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}let I=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),b;if(I.length>0){b=ye(r,"live-observation",s,e.createdAt);let x={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:I.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds:R.map(S=>S.id),artifactIds:[]},resolvedByIds:[]};l.push(x)}let g=ye(r,"live-iteration",s,e.completedAt),p={id:g,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[h.id],startedAt:i,completedAt:d,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let y=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),v=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(I.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of I.entries()){let A=ye(r,"live-proposal",`${s}:${x}`,e.completedAt),J=v.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"iteration",id:g},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:S.claim.trim(),rationale:S.rationale?.trim()||void 0,proposedKind:S.proposedKind,subjects:J,subjectSemantics:J.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:S.sourceText?.trim()||e.requestSummary,iterationId:g,inferredById:t.id}};l.push(_),y.push(A)}if(f.length>0){let x=new Set(e.governingDecisionIds??[]),S=o.records.filter(J=>J.recordType==="decision"&&J.state==="active"&&x.has(J.id)),A={id:ye(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"iteration",id:g}],recordType:"implementation_attempt",state:"completed",iterationIds:[g],coverageClaims:S.map(J=>({decisionId:J.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(_=>_.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:c,iterationId:g,proposalIds:y,observationId:b}}import{createHash as qa}from"crypto";import{mkdir as Ha,open as Wa,readFile as Ga,rename as Va,unlink as Ka}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 qa("sha256").update(JSON.stringify(o)).digest("hex")}async function Qa(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Wa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
- `,"utf8"),await t.sync()}finally{await t.close()}try{await Va(n,o)}catch(r){throw await Ka(n).catch(()=>{}),r}}function Xa(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(c,l,h)=>{let R=c[l]??=[];R.includes(h)||R.push(h)};for(let c of o.records)if(c.recordType==="subject"){let l=c;for(let h of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Lr(h);R&&i(t,R,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)i(r,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)i(s,l.subjectId,c.id);let d={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...d,checksum:Fr(d)}}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 Ga(this.indexPath,"utf8")),{checksum:s,...i}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&s===Fr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Xa(e,n);return await Ha(this.indexDir,{recursive:!0}),await Qa(this.indexPath,t),t}};var $n=class{constructor(e){this.projectRoot=e;this.store=new _n(e),this.indexStore=new Cn(e),this.manifestPath=pt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await At(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await 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=pt(this.projectRoot,".popmelt","memory","migrations"),n=pt(e,"legacy-evals-v1.json");try{let s=JSON.parse(await At(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await At(pt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await At(pt(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(s.runs)?s.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await Co(e,{recursive:!0}),await $o(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=pt(this.projectRoot,".popmelt","memory","migrations"),n=pt(e,"imprint-evidence-v1.json");try{let s=JSON.parse(await At(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await At(pt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Co(e,{recursive:!0}),await $o(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=0;for(let s of t.explanations){let i=s.evidence.length?s.evidence:[{id:s.id,kind:"observation",stance:"supports",summary:s.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:s.createdAt}];for(let d of i){let c=d.kind==="confirmation"?"confirm":d.kind==="correction"||d.kind==="rejection"?"reason_wrong":d.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:d.id,kind:c?"strengthened":"added",title:s.statement.slice(0,120),detail:d.summary,changes:[{explanationId:s.id,action:c==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:d.threadId,jobId:d.jobId,action:c,occurredAt:d.createdAt}),r+=1}}return await Co(e,{recursive:!0}),await $o(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:ko(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:_r(t.bundle,r),reviewSelection:ko(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:En(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Yt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=En(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(I=>I.recordType==="proposal"&&I.id===e.proposalId),r=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),d={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},c=e.action==="accept"?{...d,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...d,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...d,action:"reject",eventId:le(s),reason:e.reason}:{...d,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(I=>I.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=En(n.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(I=>I.message).join(" ")};let h=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(h);let R=l.plan.resultRefs.find(I=>I.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:h.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Nr(n.bundle,e),r=ye(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let s=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(s),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:s.report.headSequence}}catch(s){if(s instanceof Error&&s.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw s}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n=await this.store.load(),t=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active"),r=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="ai"&&I.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(I=>I.recordType==="subject"&&I.subjectType==="project");if(!s||!i)return;let d=e.occurredAt??new Date().toISOString(),c=Date.parse(d),l=[],h=[];for(let I of e.summary.changes){let b={kind:"external",id:I.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(y=>y.recordType==="observation"&&y.sourceRefs.some(f=>f.kind==="external"&&f.id===I.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:I.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),h.push({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ye(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,c);try{let I=await this.store.commit({records:l,events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:d});await this.refreshIndex(I)}catch(I){if(!(I instanceof Error)||!I.message.includes("Transaction already exists"))throw I}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="model_projection"&&i.state==="applied"?i.coverage.filter(d=>d.status==="projected").map(d=>d.decisionId):[])),r=new Set(n.relationships.flatMap(i=>i.relationshipType==="contradicts"&&i.from.entityType==="decision"&&i.to.entityType==="decision"?[i.from.entityId,i.to.entityId]:[])),s=new Set(n.records.flatMap(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.target.entityType==="decision"?[i.target.entityId]:[]));return n.records.filter(i=>i.recordType==="decision"&&i.state==="active"&&!t.has(i.id)&&!r.has(i.id)&&!s.has(i.id)).sort((i,d)=>d.createdAt.localeCompare(i.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(s=>s.recordType==="model_entry").sort((s,i)=>s.createdAt.localeCompare(i.createdAt)))r.decisionIds.some(s=>n.has(s))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id]:[])),t=new Map;for(let d of e.records.filter(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))d.decisionIds.some(c=>n.has(c))&&t.set(d.key,d);let r=[...t.values()],s=e.records.filter(d=>d.recordType==="verification_attempt");return{decisions:e.records.filter(d=>d.recordType==="decision"&&d.state==="active").map(d=>{let c=s.filter(l=>l.targets.some(h=>h.entityType==="decision"&&h.entityId===d.id)).sort((l,h)=>h.createdAt.localeCompare(l.createdAt))[0];return{id:d.id,kind:d.kind,claim:d.claim,projected:r.some(l=>l.decisionIds.includes(d.id)),verification:c?c.state:"unverified"}}),entries:r.map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(d=>d.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),d=le(s),c=le(s),l=le(s),h=le(s),R=le(s),I=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"&&I.has(T.id)),g={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],y={...g,id:d,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:c,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:d},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...g,id:l,recordType:"decision",proposalId:d,acceptanceEventId:c,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...g,id:h,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${s}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:i,decisionIds:[l],entryIds:[h],coverage:[{decisionId:l,status:"projected"}]},A={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=b.map(T=>({...g,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=b.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[y,v,x,S],events:[f,...J],relationships:[A,..._],artifacts:[],tombstones:[],projectionUpdates:b.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:h}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),s=n.bundle.records.flatMap(g=>g.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===g.id||g.sourceRefs.some(y=>y.id===p))?[g.id]:[]),i=[...new Set(n.bundle.records.flatMap(g=>g.recordType==="decision"&&s.includes(g.id)?g.subjects.map(p=>p.subjectId):[]))],c={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(c))continue;let l=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!l)throw new Error("No active local owner participant is available.");let h=Date.now(),R=new Date(h).toISOString(),I={id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...c,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},b=r?[{id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:I.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:I.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[I],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(h),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(i=>i.objectType==="eval_spec").map(i=>i.objectId)),t=e.records.filter(i=>i.recordType==="eval_spec").reverse().filter((i,d,c)=>c.findIndex(l=>l.legacyId===i.legacyId)===d).filter(i=>!n.has(i.id)),r=e.records.filter(i=>i.recordType==="verification_attempt"),s=e.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.targetKind==="verification_result");return t.map(i=>{let d=r.filter(h=>h.evalSpecId===i.id).sort((h,R)=>R.createdAt.localeCompare(h.createdAt))[0],c=d&&s.some(h=>h.target.entityType==="verification_attempt"&&h.target.entityId===d.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":d?c?"stale":d.state==="passed"?"passing":d.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:d?.scopeFingerprint,verificationAttemptId:d?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(d=>({assertion:d,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(I=>I.recordType==="verification_attempt"&&I.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(I=>I.recordType==="participant"&&I.status==="active"&&I.kind==="ai")??t.bundle.records.find(I=>I.recordType==="participant"&&I.status==="active");if(!s)return;let i=n.completedAt,d=new Date(i).toISOString(),c={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[c.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},h=r.targets.map(I=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:c.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:I,reason:n.summary})),R=await this.store.commit({records:[c,l],events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),d={id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},c=await this.store.commit({records:[d],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(c)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id,...c.sourceRefs.map(l=>l.id)]:[])),r=e.filter(c=>(c.dependencies?.length??0)>0||c.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(c=>!r.includes(c)).map(c=>c.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(c=>c.recordType==="participant"&&c.kind==="human"&&c.status==="active");if(!i)return{valid:r,discardedIds:s};let d=s.flatMap(c=>{let l=this.latestEvalSpec(n.bundle,c);return l?[l]:[]}).filter(c=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===c.id));if(d.length>0){let c=Date.now(),l=new Date(c).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:d.map(h=>({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:h.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(c),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="model_projection"&&g.state==="applied"&&g.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(g=>g.recordType==="decision"&&e.decisionIds.includes(g.id)&&g.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let s=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),d=new Date(i).toISOString(),c=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(v=>e.decisionIds.includes(v)),y=p?.length?p:e.decisionIds,f=[...new Set(r.filter(v=>y.includes(v.id)).flatMap(v=>v.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:y.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:y,value:g.value}}),h=new Set(l.flatMap(g=>g.decisionIds)),R={id:c,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:e.decisionIds.map(g=>({kind:"record",id:g})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:d,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:h.has(g)?"projected":"unprojected"})},I=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...l,R],events:[],relationships:I,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});return await this.refreshIndex(b),{projectionId:c,entryIds:l.map(g=>g.id),headSequence:b.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Yt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=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 Ct(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 Oo(o){let e=Ct(o),n=Ct(e.authority),t=n.level,r=n.mode,s=_t(t,"authority.level",["owner","delegate","contributor"]),i=_t(r,"authority.mode",["local_trusted","hosted"]),d={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...d,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...d,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let c=Ct(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...d,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>_t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...d,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=Ct(c);return{subjectId:Se(l.subjectId,"subjectId"),role:_t(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Do(o){let e=Ct(o),n=(s,i)=>{if(s!==void 0){if(!Array.isArray(s))throw new Error(`${i} must be an array.`);return s.map(d=>Se(d,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0:Ct(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 Ur(o,e,n,t){let r=On(e);if(!(!r&&n.length===0))try{let s=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(s.actionPacket.decisions.length===0&&s.reviewSelection.packets.length===0)return;let i=new Map(s.actionPacket.implementation.map(c=>[c.decisionId,c.state])),d=new Map(s.actionPacket.verification.map(c=>[c.target.entityId,c.state]));return{source:s.source,...s.actionPacket.decisions.length>0?{acceptedTruth:{decisions:s.actionPacket.decisions.map(c=>({...c,implementation:i.get(c.id)??"unknown",verification:d.get(c.id)??"unverified"})),conflicts:s.actionPacket.conflicts,truncated:s.actionPacket.completeness.status==="truncated"}}:{},packets:s.reviewSelection.packets.map(c=>({packetId:c.packetId,proposalId:c.proposal.id,claim:c.proposal.claim,proposedKind:c.proposal.proposedKind,authority:c.authority,presentation:c.presentation,subjectLabels:c.trigger.subjectMatches.map(l=>l.label),evidenceCount:c.evidence.sourceCount,expansionRefs:c.expansionRefs})),truncated:s.reviewSelection.completeness.status==="truncated",estimatedTokens:s.actionPacket.budget.estimatedTokens+s.reviewSelection.completeness.estimatedTokens}}catch(s){t?.(s);return}}function qr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,r)=>["",`${r+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,r)=>["",`${r+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
180
- `)}function Hr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!r||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let s=new Set(["different_action","new_evidence","new_conflict","owner_request"]),i=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(d=>typeof d=="string"&&s.has(d)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:i}}catch{return null}}function Wr(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 Ya(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),d,c,l,h,R,I,b,g,p,y,f,v,x,S,A=[],J=[],_=0,N=[];for(;_<r.length;){let T=r.indexOf(s,_);if(T===-1)break;let B=T+s.length;if(r.slice(T,T+i.length).equals(i))break;let H=B;r[H]===13&&r[H+1]===10&&(H+=2);let ee=r.indexOf(`\r
176
+ `;return await Ar(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function $r(o=jo,e="copilot"){let n=await ga(e);if(ya(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{jr(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 ga(o){try{let e=await new Promise((n,t)=>{jr(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 ya(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 En=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 Jo,readFile as ut,writeFile as No}from"fs/promises";import{join as Xe}from"path";var va=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Eo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function An(o){return new Set(Eo(o).split(" ").filter(e=>e.length>2&&!va.has(e)))}function Or(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 Ia(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 wa(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Eo).filter(Boolean),i=An([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 Ia(s)){let l=Eo(d.value);for(let P of r){let x=l===P?95:l.includes(P)||P.includes(l)?75:0;x>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:x>=90?"exact":"strong",matchedBy:d.by,score:x})}let k=["/","#","[","]","="].some(P=>d.value.includes(P))?0:Math.round(Or(An(l),i)*55);k>=30&&k>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:k>=45?"strong":"weak",matchedBy:"query_text",score:k})}c&&n.set(s.id,c)}return n}function ba(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 xa(o){return Math.ceil(JSON.stringify(o).length/4)}function Ao(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let h=[...o.events].reverse().find(f=>f.entity.entityType==="proposal"&&f.entity.entityId===y.id&&f.toState==="deferred"&&f.transitionContext?.kind==="proposal_deferral")?.transitionContext;return h?h.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||h.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||h.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||h.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||h.resurfaceWhen.includes("after_date")&&!!(h.revisitAfter&&Date.parse(t)>=Date.parse(h.revisitAfter)):!1}),s=o.records.filter(y=>y.recordType==="implementation_attempt"),c=wa(n,e),d=[...c.values()].sort((y,h)=>h.score-y.score),l=An([e.action,e.text].filter(Boolean).join(" ")),w=i.flatMap(y=>{let h=y.subjects.map(O=>c.get(O.subjectId)).filter(O=>!!O),f=Math.max(0,...h.map(O=>O.score)),u=Math.round(Or(An(y.claim),l)*35),E=f+u;return E>=50?[{proposal:y,proposalMatches:h,score:E}]:[]}).sort((y,h)=>h.score-y.score||y.proposal.id.localeCompare(h.proposal.id)),k=Math.max(1,e.maxPackets??3),P=Math.max(200,e.maxEstimatedTokens??1200),x=[],m=0;for(let y of w){if(x.length>=k)break;let h=y.proposal.sourceRefs.slice(0,4),f={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(E=>E.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:E,...O})=>O)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(E=>E.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ba(y.proposal,s),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:h},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...h]},u={...f,estimatedTokens:xa(f)};if(m+u.estimatedTokens>P)break;x.push(u),m+=u.estimatedTokens}let p=Math.max(0,w.length-x.length);return{packets:x,subjectMatches:d.map(({score:y,...h})=>h),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:p,maxEstimatedTokens:P,estimatedTokens:m},uncertainty:c.size===0?"subject_unresolved":w.length===0?"no_relevant_pending_proposal":void 0}}var Sa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Mo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Mn(o){return new Set(Mo(o).split(" ").filter(e=>e.length>2&&!Sa.has(e)))}function Dr(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,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(Mo).filter(Boolean),r=Mn([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 w=Mo(l.value);for(let x of t){let m=w===x?95:w.includes(x)||x.includes(w)?75:0;m>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:m>=90?"exact":"strong",matchedBy:l.by,score:m})}let P=["/","#","[","]","="].some(x=>l.value.includes(x))?0:Math.round(Dr(Mn(w),r)*55);P>=30&&P>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:P>=45?"strong":"weak",matchedBy:"semantic",score:P})}c&&i.push(c)}return i.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Pa(o){return Math.ceil(JSON.stringify(o).length/4)}function Et(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ka(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 Ta(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 Jr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(C=>C.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(C=>C.recordType==="decision"&&C.state==="active"),c=i?s.filter(C=>i.has(C.id)):s,d=o.records.filter(C=>C.recordType==="implementation_attempt"),l=o.records.filter(C=>C.recordType==="verification_attempt"),w=o.records.filter(C=>C.recordType==="freshness_signal"&&C.state==="open"),k=o.records.filter(C=>C.recordType==="evidence"),P=o.records.filter(C=>C.recordType==="model_entry"),x=[...o.records].reverse().filter(C=>C.recordType==="eval_spec").filter((C,I,b)=>b.findIndex(M=>M.legacyId===C.legacyId)===I),m=Ra(r,e),p=new Map(m.map(C=>[C.subjectId,C.score])),y=Mn([e.action,e.text].filter(Boolean).join(" ")),h=c.flatMap(C=>{let I=Math.max(0,...C.subjects.map(L=>p.get(L.subjectId)??0)),b=Math.round(Dr(Mn(C.claim),y)*35),M=I+b;return M>=50?[{decision:C,score:M}]:[]}).sort((C,I)=>I.score-C.score||C.decision.id.localeCompare(I.decision.id)),f=new Map;for(let C of h.slice(0,t))f.set(C.decision.id,C.decision);for(let C of o.relationships){if(!Et(C,"excepts")&&!Et(C,"contradicts"))continue;let I=s.find(M=>M.id===C.from.entityId),b=s.find(M=>M.id===C.to.entityId);!I||!b||!f.has(I.id)&&!f.has(b.id)||(f.size<t&&f.set(I.id,I),f.size<t&&f.set(b.id,b))}let u=[...f.values()],E=C=>C.from.entityType==="decision"&&C.to.entityType==="decision"&&f.has(C.from.entityId)&&f.has(C.to.entityId),O=(C,I=!1)=>{let b=new Set(C.map($=>$.id)),M=w.filter($=>$.target.entityType==="decision"&&b.has($.target.entityId)),L=new Set(o.relationships.filter($=>Et($,"excepts")&&b.has($.from.entityId)&&b.has($.to.entityId)).flatMap($=>[$.from.entityId,$.to.entityId])),U=o.relationships.filter($=>Et($,"contradicts")&&b.has($.from.entityId)&&b.has($.to.entityId)).map($=>({id:$.id,decisionIds:[$.from.entityId,$.to.entityId],unresolvedQuestion:$.reason,expansionRefs:[{kind:"record",id:$.id}]})),ne=new Set(U.flatMap($=>$.decisionIds)),oe=k.filter($=>$.sourceRefs.some(Z=>Z.kind==="record"&&b.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===$.id&&Z.to.entityType==="decision"&&b.has(Z.to.entityId))),ye=Math.max(0,h.length-C.length),Y=o.relationships.some($=>Et($,"contradicts")&&E($)&&(!b.has($.from.entityId)||!b.has($.to.entityId))),V=I||ye>0||Y,q=[];m.length===0&&(e.subjectHints?.length??0)>0?q.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):C.length===0&&q.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),U.length&&q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:U.flatMap($=>$.expansionRefs)}),oe.some($=>$.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map($=>({kind:"record",id:$.id}))}),V&&q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let ge={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:m.map(({score:$,...Z})=>Z),modelEntries:P.filter($=>$.decisionIds.some(Z=>b.has(Z))).map($=>({id:$.id,key:$.key,value:$.value,decisionIds:$.decisionIds})),evalSpecs:x.filter($=>$.decisionIds.some(Z=>b.has(Z))).map($=>({id:$.id,legacyId:$.legacyId,state:$.state,title:$.title,assertionCount:$.assertions.length,decisionIds:$.decisionIds,expansionRef:{kind:"record",id:$.id}})),decisions:C.map($=>({id:$.id,kind:$.kind,claim:$.claim,subjectIds:$.subjects.map(Z=>Z.subjectId),authority:$.authority,effectiveState:ne.has($.id)?"conflicted":L.has($.id)?"excepted":"active",freshness:M.filter(Z=>Z.target.entityId===$.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:$.id}})),conflicts:U,uncertainties:q,implementation:C.map($=>ka($.id,d)),verification:C.map($=>Ta($.id,l,M)),evidence:oe.map($=>({evidenceId:$.id,summary:$.summary,availability:$.availability,sourceRefs:$.sourceRefs})),completeness:{status:V?"truncated":"complete",omittedDecisionCount:ye,omittedEvidenceCount:0,conflictsComplete:!Y}};return ge.budget.estimatedTokens=Pa(ge),ge},R=O(u);for(;R.budget.estimatedTokens>n&&u.length>0;){let C=u.pop(),I=o.relationships.filter(b=>Et(b,"contradicts")&&(b.from.entityId===C.id||b.to.entityId===C.id)).flatMap(b=>[b.from.entityId,b.to.entityId]);u=u.filter(b=>!I.includes(b.id)),R=O(u,!0)}return R}var ja=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function At(o){return ja.test(o)}function Ea(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ae(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function _o(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){At(n)||ae(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function We(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ae(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(o,e,n,t=!1){t&&n.level==="contributor"&&ae(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ae(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Aa={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"]),advisory_explanation:new Set(["null->emerging","null->testing","null->grounded","null->challenged","null->retired","emerging->testing","emerging->grounded","emerging->challenged","emerging->retired","testing->grounded","testing->challenged","testing->retired","grounded->challenged","grounded->retired","challenged->testing","challenged->retired"]),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"])},Ma=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function _a(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),We(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=Aa[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ae(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(Ma.has(i)&&(wt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ae(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)&&ae(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ae(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&We(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function Ca(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),We(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ae(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ae(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ae(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)&&ae(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(wt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ae(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&_o(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&ae(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),We(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ae(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&ae(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&ae(o,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),We(o,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),We(o,`${n}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ae(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(We(o,`${n}.appliedAt`,e.appliedAt),wt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ae(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())&&ae(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ae(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&_o(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&_o(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function $a(o,e,n){if(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),We(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ae(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let r=e.from.entityType==="decision"&&e.to.entityType==="decision",i=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!i&&ae(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?ae(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&wt(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ae(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ae(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))&&ae(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ae(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function bt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),We(e,"manifest.createdAt",o.manifest.createdAt),We(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,y)=>{let h=n.get(p);h?ae(e,y,"duplicate_id",`ID is already used at ${h}.`):n.set(p,y)};o.records.forEach((p,y)=>{let h=`records[${y}]`;t(p.id,h),Ca(e,p,h,o.manifest.projectId)}),o.events.forEach((p,y)=>{let h=`events[${y}]`;t(p.id,h),_a(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let h=`relationships[${y}]`;t(p.id,h),$a(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let h=`tombstones[${y}]`;t(p.id,h),Te(e,`${h}.id`,p.id),Te(e,`${h}.objectId`,p.objectId),Te(e,`${h}.deletedById`,p.deletedById),We(e,`${h}.deletedAt`,p.deletedAt),wt(e,`${h}.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,y)=>{let h=`${p.entityType}:${p.entityId}`;!r.has(h)&&!i.has(h)&&ae(e,y,"dangling_entity_reference",`No record or tombstone exists for ${h}.`)};o.events.forEach((p,y)=>s(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{s(p.from,`relationships[${y}].from`),s(p.to,`relationships[${y}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,y)=>{c.has(p)||ae(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,h)=>{!r.has(`${p}:${y}`)&&!i.has(`${p}:${y}`)&&ae(e,h,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let h=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${h}.granteeId`),l("participant",p.grantedById,`${h}.grantedById`),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`));break;case"observation":p.captureContext.subjectIds.forEach((f,u)=>l("subject",f,`${h}.captureContext.subjectIds[${u}]`)),p.captureContext.artifactIds.forEach((f,u)=>d(f,`${h}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":p.subjects.forEach((f,u)=>l("subject",f.subjectId,`${h}.subjects[${u}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((f,u)=>d(f,`${h}.messageArtifactIds[${u}]`)),p.resultRefs.forEach((f,u)=>s(f,`${h}.resultRefs[${u}]`));break;case"iteration":p.threadIds.forEach((f,u)=>l("thread",f,`${h}.threadIds[${u}]`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"evidence":p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"advisory_explanation":p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`)),p.supersededById&&l("advisory_explanation",p.supersededById,`${h}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((f,u)=>l("iteration",f,`${h}.iterationIds[${u}]`)),p.coverageClaims.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverageClaims[${u}].decisionId`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${h}.replacesSpecId`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),(p.dependencies??[]).forEach((f,u)=>{f.kind==="subject"&&f.subjectId&&l("subject",f.subjectId,`${h}.dependencies[${u}].subjectId`)}),(p.scenarios??[]).forEach((f,u)=>{f.subjectIds?.forEach((E,O)=>l("subject",E,`${h}.scenarios[${u}].subjectIds[${O}]`))}),p.targets.forEach((f,u)=>l(f.entityType,f.entityId,`${h}.targets[${u}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${h}.evalSpecId`),p.targets.forEach((f,u)=>l(f.entityType,f.entityId,`${h}.targets[${u}]`)),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`));break;case"model_entry":p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`));break;case"model_projection":wt(e,`${h}.authority`,p.authority,!0),l("participant",p.appliedById,`${h}.appliedById`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.entryIds.forEach((f,u)=>l("model_entry",f,`${h}.entryIds[${u}]`)),p.coverage.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverage[${u}].decisionId`));break;case"freshness_signal":s(p.target,`${h}.target`),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`));break;default:break}});let w=new Map(o.events.map(p=>[p.id,p])),k=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),P=new Map;o.events.forEach((p,y)=>{let h=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,f=P.get(h)??new Set;f.add(p.toState),P.set(h,f),f.size>1&&ae(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let x=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),m=(p,y,h,f,u)=>{if(p.level!=="delegate"||!p.grantId)return;let E=x.get(p.grantId);if(!E){ae(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(E.granteeId!==y||E.level!=="delegate")&&ae(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let O=Date.parse(h);(O<Date.parse(E.startsAt)||E.endsAt&&O>Date.parse(E.endsAt)||E.revokedAt&&O>=Date.parse(E.revokedAt))&&ae(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),E.subjectIds.length&&f.length&&!f.every(R=>E.subjectIds.includes(R))&&ae(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&m(p.authority,p.acceptedById,p.createdAt,p.subjects.map(y=>y.subjectId),`records:${p.id}.authority`);o.events.forEach((p,y)=>{let h=k.get(`${p.entity.entityType}:${p.entity.entityId}`),f=h&&"subjects"in h?h.subjects.map(u=>u.subjectId):[];m(p.authority,p.participantId,p.createdAt,f,`events[${y}].authority`)}),o.relationships.forEach((p,y)=>{if(!p.authority)return;let h=[p.from,p.to].flatMap(f=>{let u=k.get(`${f.entityType}:${f.entityId}`);return u&&"subjects"in u?u.subjects.map(E=>E.subjectId):[]});m(p.authority,p.participantId,p.createdAt,h,`relationships[${y}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let y=w.get(p.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==p.proposalId||y.toState!=="accepted")&&ae(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==p.acceptedById&&ae(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),k.has(`proposal:${p.proposalId}`)||ae(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(f=>f.relationshipType==="supersedes"&&f.to.entityType==="decision"&&f.to.entityId===p.id)||ae(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(f=>f.entity.entityType==="decision"&&f.entity.entityId===p.id&&f.toState==="revoked"&&!!f.reason?.trim())||ae(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(h=>h.recordType==="decision"&&h.proposalId===p.id)||ae(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ea(e)}function Xt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Nr(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 Oa(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 _n(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."}),At(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Oa(e))At(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={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Nr(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={...Xt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Xt(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Nr(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={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Da}from"crypto";import{readFile as Ja,readdir as Na,realpath as Ba}from"fs/promises";import{join as Yt,relative as La}from"path";var Fa=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Mt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Fe(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Br(...o){return o.find(e=>!!e?.trim())?.trim()}function le(o,e,n,t){let i=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=Da("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 Co(o,e){try{return JSON.parse(await Ja(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function za(o){let e=Mt(o);if(!e)return 0;let n=0,t=r=>{let i=Mt(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 Ua(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Zt(o){let e=[],n=await Ba(o.projectRoot).catch(()=>o.projectRoot),t=Yt(n,".popmelt"),r=await Co(Yt(t,"threads.json"),e),i=await Co(Yt(t,"model.json"),e),s=Mt(r),c=Mt(s?.threads)??{},d=Object.entries(c).map(([$,Z])=>({key:$,value:Mt(Z)})).filter($=>!!$.value),l=Yt(t,"decisions"),w=await Na(l).catch(()=>[]),k=[];for(let $ of w.filter(Z=>Z.endsWith(".json")).sort()){let Z=Mt(await Co(Yt(l,$),e));Z&&k.push({file:$,value:Z})}let P=d.flatMap(({value:$})=>[$.createdAt,$.updatedAt]).filter($=>typeof $=="number"&&Number.isFinite($)),x=P.length?Math.min(...P):0,m=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=le(m,"project",m,x),y=le(m,"participant","legacy-owner",x),h=le(m,"participant","legacy-agent",x),f=le(m,"subject","project",x),u=Fe(Math.max(x,...P)),E=[],O=[],R=new Map,C=new Map,I=new Map(k.map($=>[$.value.id??$.file.replace(/^d-|\.json$/g,""),$.value])),b=new Map,M=($,Z,ue,se,De)=>{let Je=R.get(ue);if(Je)return Je;let Re=le(m,"artifact",$,se);return O.push({id:Re,kind:Z,mediaType:De,location:ue,availability:"available"}),R.set(ue,Re),Re};for(let{file:$,value:Z}of k){let ue=Z.id??$.replace(/^d-|\.json$/g,""),se=Z.createdAt??x,De=[M(`${ue}:envelope`,"other",`.popmelt/decisions/${$}`,se,"application/json")];Z.screenshotPath&&De.push(M(`${ue}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,se,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Je,Re]of(Z.pastedImagePaths??[]).entries())De.push(M(`${ue}:image:${Je}`,"image",Re,se));b.set(ue,De)}let L=($,Z,ue)=>({id:$,schemaVersion:1,projectId:p,createdAt:u,participantId:Z,sourceRefs:ue}),G=($,Z)=>{E.push(Z);let ue=C.get($)??[];ue.push(Z.id),C.set($,ue)},U=[{...L(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...L(h,h,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];E.push(...U),E.push({...L(f,y,[]),recordType:"subject",subjectType:"project",label:La(process.cwd(),n)||n,aliases:[],locators:[{id:le(m,"locator",n,x),kind:"project_root",value:n,status:"current",validFrom:Fe(x),sourceRefs:[]}]});let ne=new Map,oe=($,Z)=>{let ue=ne.get($);if(ue)return ue;let se=le(m,"subject",$,Z),De={...L(se,y,[{kind:"external",id:$}]),createdAt:Fe(Z),recordType:"subject",subjectType:"element",label:$,aliases:[],locators:[{id:le(m,"locator",$,Z),kind:"dom_selector",value:$,status:"current",validFrom:Fe(Z),sourceRefs:[{kind:"external",id:$}]}]};return E.push(De),ne.set($,se),se};for(let{key:$,value:Z}of d){let ue=Z.id??$,se=Z.createdAt??x,De=le(m,"thread",ue,se),Je={kind:"thread",id:ue},Re=[],Ue=[],Ve=Array.isArray(Z.messages)?Z.messages:[],et,at,ft=0;Ve.forEach((we,ct)=>{let Me=we.timestamp??se,tt=le(m,"artifact",`${ue}:message:${ct}`,Me);if(Re.push(tt),O.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${ct}`,availability:"available"}),R.set(`.popmelt/threads.json#/threads/${ue}/messages/${ct}`,tt),we.screenshotPath&&M(`${ue}:message:${ct}:screenshot`,"screenshot",we.screenshotPath,Me),we.role==="human"){et=we;let Ee=we.feedbackSummary??we.replyToQuestion;if(Ee?.trim()){let Ne=le(m,"observation",`${ue}:${ct}`,Me),pt=Z.elementIdentifiers??[],Pt={...L(Ne,y,[Je,{kind:"message",id:tt}]),createdAt:Fe(Me),recordType:"observation",state:"open",statement:Ee,captureContext:{subjectIds:pt.map(gt=>oe(gt,se)),artifactIds:[tt]},resolvedByIds:[]};G(ue,Pt),at=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let dt=we.jobId??`${ue}:${ct}`,lt=le(m,"iteration",dt,Me),ht=I.get(dt),co=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",lo={...L(lt,h,[Je,{kind:"message",id:tt},...(b.get(dt)??[]).map(Ee=>({kind:"artifact",id:Ee}))]),createdAt:Fe(Me),recordType:"iteration",threadIds:[De],startedAt:Fe(et?.timestamp,Me),completedAt:Fe(Me),requestSummary:Br(et?.feedbackSummary,et?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:co,execution:{provider:we.provider??ht?.provider,model:we.model??ht?.model,sessionId:we.sessionId??ht?.sessionId},artifactIds:[tt,...b.get(dt)??[]]};G(ue,lo),Ue.push({entityType:"iteration",entityId:lt});let Ut=we.resolutions??ht?.resolutions??[];for(let[Ee,Ne]of Ut.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let pt=Z.elementIdentifiers??[],Pt=(pt.length?pt:[n]).map(mn=>({subjectId:mn===n?f:oe(mn,se),role:"governed"})),gt=le(m,"proposal",`${dt}:${Ne.annotationId??"resolution"}:${Ee}`,Me),po={...L(gt,h,[Je,{kind:"iteration",id:lt}]),createdAt:Fe(Me),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:Pt,subjectSemantics:Pt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Br(et?.feedbackSummary,et?.replyToQuestion,Ne.summary),iterationId:lt,inferredById:h}};G(ue,po),Ue.push({entityType:"proposal",entityId:gt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${gt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Ut.some(Ee=>Ee.status==="resolved")||ht?.gitDiff){let Ee=le(m,"implementation",dt,Me),Ne={...L(Ee,h,[Je,{kind:"iteration",id:lt}]),createdAt:Fe(Me),recordType:"implementation_attempt",state:"completed",iterationIds:[lt],coverageClaims:[],summary:Ut.map(pt=>pt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};G(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:Ee}),ft+=1}at&&(at=void 0)});let Ft=Ve.at(-1),zt={...L(De,y,[Je]),createdAt:Fe(se),recordType:"thread",state:Ft?.question?"open":"resolved",messageArtifactIds:Re,outcome:Ft?.question?"question_unresolved":ft?"implementation_only":"no_outcome",resultRefs:Ue};E.push(zt),C.set(ue,[De,...C.get(ue)??[]])}let ye=za(i);ye&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ye} model values were not promoted because their accepted decision provenance is unresolved.`});let Y={manifest:{formatVersion:1,projectId:p,createdAt:Fe(x),updatedAt:u,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:E,events:[],relationships:[],artifacts:O,tombstones:[]},V=bt(Y),ge=(o.proofCaseIds??Fa).map($=>({legacyId:$,threadFound:d.some(({key:Z,value:ue})=>(ue.id??Z)===$),decisionEnvelopeFound:I.has($),recordIds:C.get($)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce(($,Z)=>$+(Z.value.messages?.length??0),0),decisionEnvelopes:k.length,modelEntries:ye,artifactsReferenced:O.length},imported:Ua(E),unresolvedAcceptance:e.filter($=>$.code==="acceptance_unresolved").length,deferredModelEntries:ye,proofCases:ge,issues:e,schemaIssues:V.issues}}}import{createHash as qa}from"crypto";import{mkdir as Lr,open as $o,readFile as Oo,readdir as Ha,rename as Wa,unlink as Do}from"fs/promises";import{join as rt}from"path";var Ga={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function $n(o){return qa("sha256").update(JSON.stringify(o)).digest("hex")}function Fr(o){return $n(o)}function zr(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let r=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(r<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let i=o.records[r];if(i.projectId!==t.projectId||i.createdAt!==t.createdAt||i.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[r]=structuredClone(t)}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 Va(o,e,n){return zr(structuredClone(o),e,n)}async function xt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await $o(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
177
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Wa(n,o)}catch(r){throw await Do(n).catch(()=>{}),r}}async function Cn(o){return JSON.parse(await Oo(o,"utf8"))}var On=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=rt(e,".popmelt","memory"),this.journalDir=rt(this.memoryDir,"journal"),this.manifestPath=rt(this.memoryDir,"manifest.json"),this.checkpointPath=rt(this.memoryDir,"checkpoint.json"),this.lockPath=rt(this.memoryDir,"writer.lock")}async initialize(e){let n=bt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Lr(this.journalDir,{recursive:!0});try{throw await Oo(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 Oo(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 xt(this.checkpointPath,r),await xt(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 xt(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 xt(rt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await xt(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(!At(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:Fr(i)},c=Va(t.bundle,e,n.committedAt),d=bt(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 xt(rt(this.journalDir,l),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await xt(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({...Ga,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Cn(this.manifestPath),n=await Cn(rt(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 Ha(this.journalDir),r=t.filter(P=>P.endsWith(".tmp")),s=t.filter(P=>/^\d{12}-[0-9a-f-]+\.json$/i.test(P)).sort().filter(P=>Number(P.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,w=new Set;for(let P of s){let x=await Cn(rt(this.journalDir,P)),{hash:m,...p}=x;if(m!==Fr(p))throw new Error(`Journal hash mismatch: ${P}`);if(x.sequence!==d+1)throw new Error(`Journal sequence gap at ${P}`);if(x.previousHash!==l)throw new Error(`Journal chain mismatch at ${P}`);if(x.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${P}`);if(w.has(x.transactionId))throw new Error(`Duplicate transaction ID: ${x.transactionId}`);zr(c,x.mutation,x.committedAt),d=x.sequence,l=x.hash,w.add(x.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 k=bt(c);if(!k.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(k.issues)}`);return{bundle:c,manifest:e,transactionIds:w,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 Lr(this.memoryDir,{recursive:!0});let n;try{n=await $o(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Cn(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 Do(this.lockPath),n=await $o(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Do(this.lockPath).catch(()=>{})}}};import{randomBytes as Ka}from"crypto";function fe(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Ka(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 Qa=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Ur(o,e){let n=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),t=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.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=Qa(),l=d.records,w=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(E=>E.kind==="thread"&&E.id===e.threadId));w||(w={id:le(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(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(w));let k=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let E=o.records.find(O=>O.recordType==="subject"&&O.locators.some(R=>R.value===u&&R.status==="current"));E||(E={id:le(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(E)),k.push(E)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let E=o.records.find(O=>O.recordType==="subject"&&O.locators.some(R=>R.kind==="source_file"&&R.value===u&&R.status==="current"));E||(E={id:le(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(E)),k.push(E)}let P=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),x;if(P.length>0){x=le(r,"live-observation",i,e.createdAt);let u={id:x,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:P.map(E=>E.claim.trim()).join(" "),captureContext:{subjectIds:k.map(E=>E.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let m=le(r,"live-iteration",i,e.completedAt),p={id:m,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...x?[{kind:"record",id:x}]:[]],recordType:"iteration",threadIds:[w.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 y=[],h=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),f=k.length>0?k:o.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(P.length>0&&f.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,E]of P.entries()){let O=le(r,"live-proposal",`${i}:${u}`,e.completedAt),R=f.map(I=>({subjectId:I.id,role:"governed"})),C={id:O,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:m},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:E.claim.trim(),rationale:E.rationale?.trim()||void 0,proposedKind:E.proposedKind,subjects:R,subjectSemantics:R.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:E.sourceText?.trim()||e.requestSummary,iterationId:m,inferredById:t.id}};l.push(C),y.push(O)}if(h.length>0){let u=new Set(e.governingDecisionIds??[]),E=o.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&u.has(R.id)),O={id:le(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:m}],recordType:"implementation_attempt",state:"completed",iterationIds:[m],coverageClaims:E.map(R=>({decisionId:R.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${h.map(C=>C.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:m}]})),summary:h.map(R=>R.summary).join(" "),artifactIds:[]};l.push(O)}return{mutation:d,iterationId:m,proposalIds:y,observationId:x}}import{createHash as Xa}from"crypto";import{mkdir as Ya,open as Za,readFile as ec,rename as tc,unlink as nc}from"fs/promises";import{join as qr}from"path";function Hr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Wr(o){return Xa("sha256").update(JSON.stringify(o)).digest("hex")}async function oc(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Za(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await tc(n,o)}catch(r){throw await nc(n).catch(()=>{}),r}}function rc(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,l,w)=>{let k=d[l]??=[];k.includes(w)||k.push(w)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let w of[l.label,...l.aliases,...l.locators.filter(k=>k.status==="current").map(k=>k.value)]){let k=Hr(w);k&&s(t,k,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:Wr(c)}}function Gr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Hr(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 Dn=class{constructor(e){this.indexDir=qr(e,".popmelt","memory","indexes"),this.indexPath=qr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await ec(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===Wr(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=rc(e,n);return await Ya(this.indexDir,{recursive:!0}),await oc(this.indexPath,t),t}};var en="popmelt:imprint",Vr="popmelt:imprint-evidence",_t="popmelt:imprint-relation";function Jn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===en)?.id}function Bo(o){let e=new Set;return o.filter(n=>{let t=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(t)?!1:(e.add(t),!0)})}function Nn(o,e){if(!o)return[];let n=new Set(o.relations.flatMap(t=>t.type==="instantiates"&&t.fromId===e?[t.toId]:[]));return o.concrete.filter(t=>n.has(t.id)).map(t=>({id:t.id,modelPath:t.modelPath,value:structuredClone(t.value),createdAt:t.createdAt,updatedAt:t.updatedAt}))}var Bn=class{constructor(e){this.projectRoot=e;this.store=new On(e),this.indexStore=new Dn(e),this.manifestPath=Xe(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await ut(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 Zt({...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 Zt({...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=Xe(this.projectRoot,".popmelt","memory","migrations"),n=Xe(e,"legacy-evals-v1.json");try{let i=JSON.parse(await ut(n,"utf8"));return{migrated:!1,specs:i.specs??0,runs:i.runs??0}}catch{}let t=[],r=[];try{let i=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(i.cases)?i.cases:[]}catch{}try{let i=JSON.parse(await ut(Xe(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 Jo(e,{recursive:!0}),await No(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=Xe(this.projectRoot,".popmelt","memory","migrations"),n=Xe(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await ut(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Jo(e,{recursive:!0}),await No(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??i,d=r.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,w=new Set(r.bundle.records.map(u=>u.id)),k=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(E=>E.kind==="external"&&E.uri===_t?[E.id]:[]))),P=new Map,x=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let E=x.find(O=>Jn(O)===u.id);P.set(u.id,E?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let m=[],p=[],y=[],h=0;for(let u of t.explanations){let E=P.get(u.id),O=x.find(b=>b.id===E),R=[],C=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let b of C){let M=le(l,"imprint-evidence-record",b.id,Date.parse(b.createdAt));R.push(M),!w.has(M)&&(m.push({id:M,schemaVersion:1,projectId:l,createdAt:b.createdAt,participantId:c.id,sourceRefs:Bo([{kind:"external",id:b.id,uri:Vr},{kind:"external",id:u.id,uri:en},{kind:"thread",id:b.threadId},{kind:"message",id:b.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(b.kind)?"user_feedback":"judgment",summary:b.summary,availability:"available",artifactIds:[]}),y.push({id:le(l,"imprint-evidence-link",`${u.id}:${b.id}`,Date.parse(b.createdAt)),schemaVersion:1,projectId:l,createdAt:b.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:b.id,uri:Vr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),h+=1)}let I={id:E,schemaVersion:1,projectId:l,createdAt:O?.createdAt??u.createdAt,participantId:O?.participantId??c.id,sourceRefs:Bo([...O?.sourceRefs??[],{kind:"external",id:u.id,uri:en}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...O?.evidenceIds??[],...R])],concreteBindings:Nn(t,u.id),supersededById:u.supersededBy?P.get(u.supersededBy):void 0,updatedAt:u.updatedAt};O?p.push(I):m.push(I)}for(let u of t.relations){let E=P.get(u.fromId),O=P.get(u.toId);!E||!O||k.has(u.id)||y.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:u.id,uri:_t}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:O},reason:u.rationale||"The Imprint graph connected these explanations."})}let f=new Date().toISOString();if(m.length||p.length||y.length)try{let u=await this.store.commit({records:m,recordReplacements:p,events:[],relationships:y,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(l,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:f});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await Jo(e,{recursive:!0}),await No(n,JSON.stringify({version:2,migratedAt:f,explanations:t.explanations.length,evidence:h,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:h}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Ao(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Jr(t.bundle,r),reviewSelection:Ao(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:_n(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 Zt({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=_n(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(P=>P.recordType==="proposal"&&P.id===e.proposalId),r=n.bundle.records.find(P=>P.recordType==="participant"&&P.kind==="human"&&P.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:fe(i),decisionId:fe(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:fe(i),replacementProposalId:fe(i),acceptanceEventId:fe(i),decisionId:fe(i),relationshipId:fe(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:fe(i),reason:e.reason}:{...c,action:"defer",eventId:fe(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(P=>P.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=_n(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(P=>P.message).join(" ")};let w=await this.store.commitReviewPlan(l.plan,{transactionId:fe(i),committedAt:s});await this.refreshIndex(w);let k=l.plan.resultRefs.find(P=>P.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:k,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:w.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=Ur(n.bundle,e),r=le(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;try{n=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),r=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active"),i=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="ai"&&f.status==="active"),s=e.action?r:i??r,c=t.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),w=t.bundle.manifest.projectId,k=[],P=[],x=[],m=t.bundle.records.filter(f=>f.recordType==="advisory_explanation"),p=new Map(m.flatMap(f=>{let u=Jn(f);return u?[[u,f.id]]:[]}));for(let f of e.summary.changes)if(!p.has(f.explanationId)){let u=n?.explanations.find(E=>E.id===f.explanationId);p.set(f.explanationId,le(w,"imprint-explanation",f.explanationId,Date.parse(u?.createdAt??d)))}for(let f of e.summary.changes){let u={kind:"external",id:f.explanationId,uri:en},E=p.get(f.explanationId),O=m.find(b=>b.id===E),R=n?.explanations.find(b=>b.id===f.explanationId),C={id:le(w,"imprint-live-evidence",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[u,{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:[]};k.push(C);let I={id:E,schemaVersion:1,projectId:w,createdAt:O?.createdAt??R?.createdAt??d,participantId:O?.participantId??s.id,sourceRefs:Bo([...O?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:R?.kind??O?.kind??"pattern",state:R?.state??f.state,statement:R?.statement??f.statement,rationale:R?.rationale??O?.rationale??e.summary.detail,scope:structuredClone(R?.scope??O?.scope??{kind:"project",values:[]}),subjectIds:O?.subjectIds??[c.id],evidenceIds:[...new Set([...O?.evidenceIds??[],C.id])],concreteBindings:R?Nn(n,f.explanationId):O?.concreteBindings??[],supersededById:R?.supersededBy?p.get(R.supersededBy):O?.supersededById,updatedAt:R?.updatedAt??d};O?P.push(I):k.push(I),x.push({id:le(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:I.id},to:{entityType:"evidence",entityId:C.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let y=new Set(t.bundle.relationships.flatMap(f=>f.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===_t?[u.id]:[])));for(let f of n?.relations??[]){let u=p.get(f.fromId),E=p.get(f.toId);!u||!E||y.has(f.id)||x.push({id:le(w,"imprint-relation",f.id,Date.parse(f.createdAt)),schemaVersion:1,projectId:w,createdAt:f.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:f.id,uri:_t}],recordType:"relationship",relationshipType:f.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId:E},reason:f.rationale||"The Imprint graph connected these explanations."})}let h=le(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let f=await this.store.commit({records:k,recordReplacements:P,events:[],relationships:x,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:h,committedAt:d});await this.refreshIndex(f)}catch(f){if(!(f instanceof Error)||!f.message.includes("Transaction already exists"))throw f}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),t=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),i=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="ai"&&R.status==="active")??t;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(R=>R.recordType==="advisory_explanation"),l=new Map(d.flatMap(R=>{let C=Jn(R);return C?[[C,R]]:[]})),w=new Map([...[...l].map(([R,C])=>[R,C.id]),...e.explanations.filter(R=>!l.has(R.id)).map(R=>[R.id,le(c,"imprint-explanation",R.id,Date.parse(R.createdAt))])]),k=[],P=[],x=new Set(e.explanations.map(R=>R.id));for(let R of e.explanations){let C=l.get(R.id);if(!C){k.push({id:w.get(R.id),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:R.id,uri:en}],recordType:"advisory_explanation",kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Nn(e,R.id),supersededById:R.supersededBy?w.get(R.supersededBy):void 0,updatedAt:R.updatedAt});continue}let I={...structuredClone(C),kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),concreteBindings:Nn(e,R.id),supersededById:R.supersededBy?w.get(R.supersededBy):void 0,updatedAt:R.updatedAt},b=M=>JSON.stringify({kind:M.kind,state:M.state,statement:M.statement,rationale:M.rationale,scope:M.scope,concreteBindings:M.concreteBindings,supersededById:M.supersededById,updatedAt:M.updatedAt});b(C)!==b(I)&&P.push(I)}for(let[R,C]of l)x.has(R)||C.state==="retired"||P.push({...structuredClone(C),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let m=new Set(n.bundle.tombstones.flatMap(R=>R.objectType==="relationship"?[R.objectId]:[])),p=new Map(n.bundle.relationships.flatMap(R=>{if(m.has(R.id))return[];let C=R.sourceRefs.find(I=>I.kind==="external"&&I.uri===_t)?.id;return C?[[C,R]]:[]})),y=new Set(p.keys()),h=[];for(let R of e.relations){let C=w.get(R.fromId),I=w.get(R.toId);!C||!I||y.has(R.id)||h.push({id:le(c,"imprint-relation",R.id,Date.parse(R.createdAt)),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:R.id,uri:_t}],recordType:"relationship",relationshipType:R.type,from:{entityType:"advisory_explanation",entityId:C},to:{entityType:"advisory_explanation",entityId:I},reason:R.rationale||"The Imprint graph connected these explanations."})}let f=new Set(e.relations.map(R=>R.id)),u=t?[...p].filter(([R])=>!f.has(R)).map(([,R])=>({id:le(c,"imprint-relationship-tombstone",R.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:R.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:t.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!k.length&&!P.length&&!h.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let E=e.updatedAt,O=le(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(E));try{let R=await this.store.commit({records:k,recordReplacements:P,events:[],relationships:h,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:O,committedAt:E});return await this.refreshIndex(R),{status:"synced",relationships:h.length+u.length,explanations:k.length+P.length,headSequence:R.report.headSequence}}catch(R){if(!(R instanceof Error)||!R.message.includes("Transaction already exists"))throw R;return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence}}}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 getImprintView(e=[]){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let t=await this.store.load(),r=t.bundle.records.filter(p=>p.recordType==="advisory_explanation"),i=new Map(r.map(p=>[p.id,p])),s=new Map(r.flatMap(p=>{let y=Jn(p);return y?[[y,p.id]]:[]})),c=new Set(e.map(p=>s.get(p)??p)),d=new Map(t.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),l=new Map(t.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),w=new Set(t.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),k=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),P={testing:0,emerging:1,grounded:2,challenged:3,retired:4},x=r.map(p=>{let y=p.evidenceIds.flatMap(u=>{let E=l.get(u);if(!E)return[];let O=E.sourceRefs.find(b=>b.kind==="thread")?.id,R=E.sourceRefs.find(b=>b.kind==="message")?.id,C=E.kind==="judgment"||E.kind==="user_feedback"||E.kind==="project_state"?E.kind:"other",I=d.get(E.participantId)??"unknown";return[{id:E.id,kind:C,summary:E.summary,createdAt:E.createdAt,participantKind:I,threadId:O,jobId:R}]}).sort((u,E)=>E.createdAt.localeCompare(u.createdAt)),h=t.bundle.relationships.flatMap(u=>{if(w.has(u.id))return[];if(!k.has(u.relationshipType))return[];let E=u.from.entityType==="advisory_explanation"&&u.from.entityId===p.id&&u.to.entityType==="advisory_explanation",O=u.to.entityType==="advisory_explanation"&&u.to.entityId===p.id&&u.from.entityType==="advisory_explanation";if(!E&&!O)return[];let R=E?u.to.entityId:u.from.entityId,C=i.get(R);return C?[{id:u.id,type:u.relationshipType,direction:E?"outgoing":"incoming",explanationId:C.id,statement:C.statement,rationale:u.reason}]:[]}),f=[...new Set([...p.sourceRefs.flatMap(u=>u.kind==="thread"?[u.id]:[]),...y.flatMap(u=>u.threadId?[u.threadId]:[])])];return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:y.length,recentEvidence:y.slice(0,4),concrete:p.concreteBindings.map(u=>({...structuredClone(u)})),relations:h,sourceThreadIds:f,needsGrounding:p.state==="testing"&&c.has(p.id)}}).sort((p,y)=>Number(y.needsGrounding)-Number(p.needsGrounding)||P[p.state]-P[y.state]||y.updatedAt.localeCompare(p.updatedAt)),m={total:x.filter(p=>p.state!=="retired").length,emerging:x.filter(p=>p.state==="emerging").length,testing:x.filter(p=>p.state==="testing").length,grounded:x.filter(p=>p.state==="grounded").length,challenged:x.filter(p=>p.state==="challenged").length,retired:x.filter(p=>p.state==="retired").length,needsGrounding:x.filter(p=>p.needsGrounding).length};return{head:{sequence:t.report.headSequence,updatedAt:t.bundle.manifest.updatedAt},counts:m,explanations:x}}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(w=>w.entityType==="decision"&&w.entityId===c.id)).sort((l,w)=>w.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(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active"),r=n.bundle.records.find(b=>b.recordType==="subject"&&b.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=fe(i),d=fe(i),l=fe(i),w=fe(i),k=fe(i),P=new Set(n.bundle.records.flatMap(b=>b.recordType==="model_entry"&&b.key===e.key?b.decisionIds:[])),x=n.bundle.records.filter(b=>b.recordType==="decision"&&b.state==="active"&&P.has(b.id)),m={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"}],y={...m,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},h={...m,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."},f={...m,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},u={...m,id:w,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},E={...m,id:k,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:[w],coverage:[{decisionId:l,status:"projected"}]},O={...m,id:fe(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:w},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},R=x.map(b=>({...m,id:fe(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:b.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),C=x.map(b=>({...m,id:fe(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:f.id},to:{entityType:"decision",entityId:b.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),I=await this.store.commit({records:[y,f,u,E],events:[h,...R],relationships:[O,...C],artifacts:[],tombstones:[],projectionUpdates:x.map(b=>({entityType:"decision",entityId:b.id,fromState:"active",state:"superseded"}))},{transactionId:fe(i),committedAt:s});return await this.refreshIndex(I),{decisionId:l,entryId:w}}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(m=>m.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===m.id||m.sourceRefs.some(y=>y.id===p))?[m.id]:[]),s=[...new Set(n.bundle.records.flatMap(m=>m.recordType==="decision"&&i.includes(m.id)?m.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(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!l)throw new Error("No active local owner participant is available.");let w=Date.now(),k=new Date(w).toISOString(),P={id:fe(w),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:k,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...i.map(m=>({kind:"record",id:m}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:i.map(m=>({entityType:"decision",entityId:m})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},x=r?[{id:fe(w),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:k,participantId:l.id,sourceRefs:[{kind:"record",id:P.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:P.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[P],events:[],relationships:x,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(w),committedAt:k})}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(w=>w.evalSpecId===s.id).sort((w,k)=>k.createdAt.localeCompare(w.createdAt))[0],d=c&&i.some(w=>w.target.entityType==="verification_attempt"&&w.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(P=>P.recordType==="verification_attempt"&&P.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let i=t.bundle.records.find(P=>P.recordType==="participant"&&P.status==="active"&&P.kind==="ai")??t.bundle.records.find(P=>P.recordType==="participant"&&P.status==="active");if(!i)return;let s=n.completedAt,c=new Date(s).toISOString(),d={id:fe(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:fe(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}},w=r.targets.map(P=>({id:fe(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:P,reason:n.summary})),k=await this.store.commit({records:[d,l],events:[],relationships:w,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});await this.refreshIndex(k)}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:fe(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:fe(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(w=>({id:fe(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:w.id,objectType:"eval_spec",deletedAt:l,deletedById:s.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:fe(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(m=>m.recordType==="model_projection"&&m.state==="applied"&&m.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(m=>m.recordType==="decision"&&e.decisionIds.includes(m.id)&&m.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(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=fe(s),l=e.changes.map(m=>{let p=m.decisionIds?.filter(f=>e.decisionIds.includes(f)),y=p?.length?p:e.decisionIds,h=[...new Set(r.filter(f=>y.includes(f.id)).flatMap(f=>f.subjects.map(u=>u.subjectId)))];return{id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:y.map(f=>({kind:"record",id:f})),recordType:"model_entry",key:m.path.map(String).join("."),subjectIds:h,decisionIds:y,value:m.value}}),w=new Set(l.flatMap(m=>m.decisionIds)),k={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:e.decisionIds.map(m=>({kind:"record",id:m})),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(m=>m.id),coverage:e.decisionIds.map(m=>e.coverage?.find(p=>p.decisionId===m)??{decisionId:m,status:w.has(m)?"projected":"unprojected"})},P=l.flatMap(m=>m.decisionIds.map(p=>({id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:k.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:m.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),x=await this.store.commit({records:[...l,k],events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});return await this.refreshIndex(x),{projectionId:d,entryIds:l.map(m=>m.id),headSequence:x.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 Zt({...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=Gr(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function $t(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Ct(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Lo(o){let e=$t(o),n=$t(e.authority),t=n.level,r=n.mode,i=Ct(t,"authority.level",["owner","delegate","contributor"]),s=Ct(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:Ct(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=$t(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>Ct(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:Ct(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=$t(d);return{subjectId:Se(l.subjectId,"subjectId"),role:Ct(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 Fo(o){let e=$t(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:$t(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Ln(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
179
+ `)}async function Kr(o,e,n,t){let r=Ln(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 Qr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,r)=>["",`${r+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,r)=>["",`${r+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
180
+ `)}function Xr(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 Yr(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 Fn(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 ic(o),i=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,l,w,k,P,x,m,p,y,h,f,u,E,O=[],R=[],C=0,I=[];for(;C<r.length;){let b=r.indexOf(i,C);if(b===-1)break;let M=b+i.length;if(r.slice(b,b+s.length).equals(s))break;let L=M;r[L]===13&&r[L+1]===10&&(L+=2);let G=r.indexOf(`\r
181
181
  \r
182
- `,H);if(ee===-1)break;let W=r.slice(H,ee).toString("utf-8"),te=ee+4,ne=r.indexOf(s,te),ge=ne!==-1?ne-2:r.length;N.push({headers:W,body:r.slice(te,ge)}),_=ne!==-1?ne:r.length}for(let T of N){let B=T.headers.match(/name="([^"]+)"/);if(!B)continue;let H=B[1];if(H==="screenshot")d=T.body;else if(H==="feedback")c=T.body.toString("utf-8");else if(H==="color")l=T.body.toString("utf-8");else if(H==="provider")h=T.body.toString("utf-8");else if(H==="model")R=T.body.toString("utf-8");else if(H==="reasoningEffort")I=T.body.toString("utf-8");else if(H==="serviceTier")b=T.body.toString("utf-8");else if(H==="goal")g=T.body.toString("utf-8");else if(H==="pageUrl")p=T.body.toString("utf-8");else if(H==="viewport")y=T.body.toString("utf-8");else if(H==="planId")f=T.body.toString("utf-8");else if(H==="manifest")v=T.body.toString("utf-8");else if(H==="tasks")x=T.body.toString("utf-8");else if(H==="sourceId")S=T.body.toString("utf-8");else if(H.startsWith("screenshot-")){let ee=H.slice(11);try{let W=decodeURIComponent(ee);J.push({pathname:W,data:T.body})}catch{}}else if(H.startsWith("image-")){let ee=H.split("-"),W=parseInt(ee[ee.length-1],10),te=ee.slice(1,-1).join("-");te&&!isNaN(W)&&A.push({annotationId:te,index:W,data:T.body})}}if(!d)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:d,feedback:c,color:l,provider:h,model:R,reasoningEffort:I,serviceTier:b,goal:g,pageUrl:p,viewport:y,planId:f,manifest:v,tasks:x,sourceId:S,pastedImages:A,pageScreenshots:J}}function Ya(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 Za}from"crypto";var ec=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,tc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),nc=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 oc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Gr(o,e,n,t=Date.now()){let r=oc(o);if(!r)return null;let s=typeof r.transition=="string"&&tc.has(r.transition)?r.transition:null,i=Zt(r.focus);if(!s||!i)return null;let d=typeof r.evidencePosture=="string"&&nc.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Za(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Zt(r.seeking),workingHypothesis:Zt(r.workingHypothesis),evidencePosture:d,update:Zt(r.update),nextObservation:Zt(r.nextObservation)},contextPolicy:"exclude"}}function Jo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function rc(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(ec,(d,c)=>{try{let l=Gr(JSON.parse(c),e,s);if(!l)return"";let h=Jo(l);if(r.has(h))return"";r.add(h),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
182
+ `,L);if(G===-1)break;let U=r.slice(L,G).toString("utf-8"),ne=G+4,oe=r.indexOf(i,ne),ye=oe!==-1?oe-2:r.length;I.push({headers:U,body:r.slice(ne,ye)}),C=oe!==-1?oe:r.length}for(let b of I){let M=b.headers.match(/name="([^"]+)"/);if(!M)continue;let L=M[1];if(L==="screenshot")c=b.body;else if(L==="feedback")d=b.body.toString("utf-8");else if(L==="color")l=b.body.toString("utf-8");else if(L==="provider")w=b.body.toString("utf-8");else if(L==="model")k=b.body.toString("utf-8");else if(L==="reasoningEffort")P=b.body.toString("utf-8");else if(L==="serviceTier")x=b.body.toString("utf-8");else if(L==="goal")m=b.body.toString("utf-8");else if(L==="pageUrl")p=b.body.toString("utf-8");else if(L==="viewport")y=b.body.toString("utf-8");else if(L==="planId")h=b.body.toString("utf-8");else if(L==="manifest")f=b.body.toString("utf-8");else if(L==="tasks")u=b.body.toString("utf-8");else if(L==="sourceId")E=b.body.toString("utf-8");else if(L.startsWith("screenshot-")){let G=L.slice(11);try{let U=decodeURIComponent(G);R.push({pathname:U,data:b.body})}catch{}}else if(L.startsWith("image-")){let G=L.split("-"),U=parseInt(G[G.length-1],10),ne=G.slice(1,-1).join("-");ne&&!isNaN(U)&&O.push({annotationId:ne,index:U,data:b.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:w,model:k,reasoningEffort:P,serviceTier:x,goal:m,pageUrl:p,viewport:y,planId:h,manifest:f,tasks:u,sourceId:E,pastedImages:O,pageScreenshots:R}}function ic(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 sc}from"crypto";var ac=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,cc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),dc=new Set(["strengthened","weakened","mixed","unknown"]);function tn(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 lc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Zr(o,e,n,t=Date.now()){let r=lc(o);if(!r)return null;let i=typeof r.transition=="string"&&cc.has(r.transition)?r.transition:null,s=tn(r.focus);if(!i||!s)return null;let c=typeof r.evidencePosture=="string"&&dc.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:sc(),jobId:e,sequence:n,timestamp:t,transition:i,snapshot:{focus:s,seeking:tn(r.seeking),workingHypothesis:tn(r.workingHypothesis),evidencePosture:c,update:tn(r.update),nextObservation:tn(r.nextObservation)},contextPolicy:"exclude"}}function zo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function pc(o,e,n=0){let t=[],r=new Set,i=n;return{visibleText:o.replace(ac,(c,d)=>{try{let l=Zr(JSON.parse(d),e,i);if(!l)return"";let w=zo(l);if(r.has(w))return"";r.add(w),t.push(l),i++}catch{}return""}).replace(/\n{3,}/g,`
183
183
 
184
- `).trim(),orientations:t}}function sc(o){let e="<orientation>",n=Math.min(o.length,e.length-1);for(let t=n;t>0;t--)if(e.startsWith(o.slice(-t)))return t;return 0}var Jn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let d=sc(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}n+=this.buffer.slice(0,r);let s=this.buffer.indexOf("</orientation>",r+13);if(s<0){this.buffer=this.buffer.slice(r);break}let i=this.buffer.slice(r+13,s).trim();this.buffer=this.buffer.slice(s+14);try{let d=Gr(JSON.parse(i),this.jobId,this.sequence);if(!d)continue;let c=Jo(d);if(this.signatures.has(c))continue;this.signatures.add(c),t.push(d),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=rc(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=Jo(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Vr=`## Public orientation updates
184
+ `).trim(),orientations:t}}function uc(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 zn=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=uc(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=Zr(JSON.parse(s),this.jobId,this.sequence);if(!c)continue;let d=zo(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=pc(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let i=zo(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},ei=`## Public orientation updates
185
185
  During meaningful transitions in the work, emit a brief public coordination update using this exact form:
186
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
187
 
188
188
  Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
189
189
  Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
190
190
 
191
- These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function en(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(d=>{let c=[d.selector];return d.reactComponent&&c.push(`(${d.reactComponent})`),c.join(" ")}).join(", "),s=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${s} \u2192 Elements: ${r||"none"}`);let i=e?.[t.id];if(i&&i.length>0)for(let d of i)n.push(` Attached image: use the Read tool to view ${d}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let s of t.changes)n.push(`- ${t.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=JSON.stringify(t.original),i=JSON.stringify(t.modified),d=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${d}: ${s} \u2192 ${i}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",i=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${s} \u2192 ${t.targetParentSelector}${i}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
192
- ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let r of t.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let t=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[t.selector];t.reactComponent&&r.push(`(${t.reactComponent})`),t.context&&r.push(`in ${t.context}`),t.textContent&&r.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
193
- `)}function Kr(o,e,n){let t=[],s=new Set(e.annotations.map(i=>i.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!s&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let i=0;for(let d of n.threadHistory)if(d.role==="human")i++,d.replyToQuestion?(t.push(`### Round ${i} (human) \u2014 reply`),t.push(`"${d.replyToQuestion}"`)):(t.push(`### Round ${i} (human)`),d.feedbackSummary&&t.push(`Annotations: ${d.feedbackSummary}`),d.annotationIds&&d.annotationIds.length>0&&t.push(`Annotation IDs: ${d.annotationIds.join(", ")}`));else if(d.question)t.push(`### Round ${i} (assistant) \u2014 question`),t.push(`"${d.question}"`);else{if(t.push(`### Round ${i} (assistant)`),d.responseText&&t.push(`Response: ${d.responseText}`),d.resolutions&&d.resolutions.length>0)for(let c of d.resolutions){let l=c.finalScope??c.inferredScope,h=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${c.annotationId}: ${c.status}${h} \u2014 ${c.summary}`),c.filesModified&&c.filesModified.length>0&&t.push(` Files: ${c.filesModified.join(", ")}`)}d.toolsUsed&&d.toolsUsed.length>0&&t.push(`Tools used: ${d.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0)if(t.push(""),t.push("Rules:"),i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"scope"in i[0]){let h=new Map;for(let R of i)if(typeof R=="object"&&R!==null&&"text"in R){let I=R,b=I.scope||"general";h.has(b)||h.set(b,[]),h.get(b).push(I.text)}for(let[R,I]of h){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let b of I)t.push(`- ${b}`)}}else for(let h of i)typeof h=="string"&&t.push(`- ${h}`);let d=n.designModel.tokens;d&&typeof d=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```"));let c=n.designModel.components;c&&typeof c=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),s){let i=n?.screenshotPaths??{},d=new Map;for(let c of e.annotations){let l=c.pathname||new URL(e.url).pathname;d.has(l)||d.set(l,[]),d.get(l).push(c)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,l]of d){t.push(""),t.push(`## Page: ${c}`);let h=i[c];h&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${h}`):!h&&n?.provider!=="codex"&&(Object.keys(i).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:l,styleModifications:e.styleModifications},I=en(R,n?.imagePaths);I&&(t.push(""),t.push(I))}}else{let i=en(e,n?.imagePaths);i&&(t.push(""),t.push(i))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
194
- `)}function 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 s=e.find(i=>i.role==="human"&&i.feedbackContext);if(s?.feedbackContext&&(r.push(""),r.push(s.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let i=0;for(let d of e)d.role==="human"?(i++,d.replyToQuestion?(r.push(`### Round ${i} (human) \u2014 reply`),r.push(`"${d.replyToQuestion}"`)):(r.push(`### Round ${i} (human)`),d.feedbackSummary&&r.push(`Annotations: ${d.feedbackSummary}`))):d.question?(r.push(`### Round ${i} (assistant) \u2014 question`),r.push(`"${d.question}"`)):(r.push(`### Round ${i} (assistant)`),d.responseText&&r.push(`Response: ${d.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let i of t)r.push(`Attached image: use the Read tool to view the image at: ${i}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
195
- `)}function ic(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 ac(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&&!ic(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(ac):[]}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 cc}from"child_process";import{readdir as dc,readFile as lc,stat as pc}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:es()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:es()}],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"},uc=/^\s*-\s+"([^"]+)"/;function mc(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(uc);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:No(s),source:"cli"})}return Ln([on,...e])}function fc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,r)=>{let s=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,i=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return s-i}).flatMap(t=>{let r=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!r)return[];let s=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():No(r),i=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,d=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:s,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...i&&i.length>0?{supportedReasoningLevels:i}:{},...d&&d.length>0?{speedTiers:d}:{}}]})}function es(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function hc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ln(e.map(n=>({id:n,label:No(n),source:"cli"})))}function No(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let s=t[1]==="sonnet"?"Sonn":wc(t[1]),i=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${s}${i}${t[4]?" Fast":""}`}let r=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let s=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${s}`:r[3]==="codex"?`Codex ${s}`:r[3]==="spark"?`Spark ${s}`:`GPT ${s}`}return n}async function ts(o="copilot"){let e=await Nn(o,["help","config"]),n=mc(e);return n.length>1?n:[on]}async function ns(o="codex"){let e=await Nn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(tn(),".codex");return rs(Qe(t,"models_cache.json"))}),n=fc(e);return n.length>0?Ln([...n,...nn]):nn}async function os(o="claude"){let e=Qe(tn(),".claude"),n=[Qe(tn(),".claude","stats-cache.json"),Qe(tn(),".claude","settings.json"),Qe(tn(),".claude.json"),Qe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Nn(o,["--help"]).catch(()=>""),Nn(o,["--version"]).catch(()=>""),gc(e).catch(()=>[])]),i=vc([...n,...s]),d=await Promise.all(i.map(l=>rs(l).catch(()=>""))),c=hc([t,r,...d].join(`
197
- `));return Ln([...Bn,...c])}function Nn(o,e,n=5e3){return new Promise((t,r)=>{cc(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function rs(o){return lc(o,"utf-8")}async function gc(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await ss(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function ss(o,e,n){if(n<0)return;let t;try{t=await dc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Qe(o,r.name);if(r.isDirectory()){await ss(s,e,n-1);return}if(!(!r.isFile()||!yc(r.name)))try{let i=await pc(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function yc(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 vc(o){return[...new Set(o)]}function wc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Fn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let s=this.queue.length-1;s>=0;s--)if(this.queue[s]?.threadId===e.threadId){n=s;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let s of this.listeners)s(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},s=this.activeJobs.has(e);if(!t)return null;let i=n<0?t.events:t.events.filter(d=>d.seq>n);return{jobId:e,events:i,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:s}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let s=!1,i=()=>{s||(s=!0,r())};t.on("exit",i),t.on("error",i),setTimeout(()=>{if(!s){try{t.kill("SIGKILL")}catch{}setTimeout(i,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as We}from"crypto";import{createHash as Ic}from"crypto";import{mkdir as bc,open as xc,readFile as is,readdir as Sc,rename as Pc,unlink as Rc}from"fs/promises";import{dirname as kc,join as $t}from"path";function $e(o){return structuredClone(o)}function as(o){return Ic("sha256").update(JSON.stringify(o)).digest("hex")}async function rn(o,e){await bc(kc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await xc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
198
- `,"utf8"),await t.sync()}finally{await t.close()}try{await Pc(n,o)}catch(r){throw await Rc(n).catch(()=>{}),r}}function Tc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function jc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=$e(e):o.explanations.push($e(e))}function zn(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")jc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(s=>s.id===t.evidence.id)||(r.evidence.push($e(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,$e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(i=>i.id===t.relation.fromId),s=n.explanations.some(i=>i.id===t.relation.toId)||n.concrete.some(i=>i.id===t.relation.toId);if(!r||!s)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(i=>i.id===t.relation.id)||n.relations.push($e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Ec(o,e){let n=[],t=$e(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let s=t.explanations.find(i=>i.id===r.explanationId);s&&n.unshift({op:"add_explanation",explanation:$e(s)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let s=t.concrete.find(i=>i.id===r.concreteId);s&&n.unshift({op:"add_concrete",concrete:$e(s)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let s=r.op==="replace_explanation"?r.explanation.id:r.explanationId,i=t.explanations.find(d=>d.id===s);i&&n.unshift({op:"replace_explanation",explanation:$e(i)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let s=t.relations.find(i=>i.id===r.relationId);s&&n.unshift({op:"add_relation",relation:$e(s)})}t=zn(t,[r])}return n}function cs(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 Ot=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=$t(e,".popmelt","imprint"),this.manifestPath=$t(this.imprintDir,"manifest.json"),this.graphPath=$t(this.imprintDir,"graph.json"),this.journalDir=$t(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await is(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 Sc(this.journalDir).catch(d=>{if(d.code==="ENOENT")return[];throw d})).filter(d=>/^\d{12}-.+\.json$/.test(d)).sort(),r=Tc(this.projectId,e.createdAt),s=[],i=null;for(let d=0;d<t.length;d++){let c=JSON.parse(await is($t(this.journalDir,t[d]),"utf8")),{hash:l,...h}=c;if(c.sequence!==d+1||c.previousHash!==i||l!==as(h))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);r=zn(r,c.mutations),r.updatedAt=c.committedAt,r.head={sequence:c.sequence,hash:c.hash},s.push(c),i=c.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=Ec(t.graph,e.mutations),i={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:s,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},d={...i,hash:as(i)},c=zn(t.graph,d.mutations);c.updatedAt=e.committedAt,c.head={sequence:r,hash:d.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await rn($t(this.journalDir,l),d);let h={version:1,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await rn(this.graphPath,c),await rn(this.manifestPath,h),n={graph:c,transaction:d}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let d=new Set(i.mutations.flatMap(cs));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(h=>cs(h).some(R=>d.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await rn(this.graphPath,e.graph),await rn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Mc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ac=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function _c(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Un(o){return new Set(_c(o).split(" ").filter(e=>e.length>2&&!Ac.has(e)))}function qn(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 Bo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function ot(o,e,n){return{id:We(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function Ee(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function ds(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 Cc(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Hn(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let I=String(r.reason);if(!Mc.has(I))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:I},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let s=r.summary,i=s?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(i)))throw new Error("summary.kind is invalid");let d={kind:i,title:Ee(s?.title,120),detail:Ee(s?.detail,500)};if(!d.title||!d.detail)throw new Error("summary title and detail are required");let c=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(I=>typeof I=="string"&&!!I.trim()):[],l=[];for(let I of Array.isArray(r.mutations)?r.mutations:[]){if(!I||typeof I!="object")continue;let b=I;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let g=Ee(b.statement),p=Ee(b.rationale);if(!g||!p)continue;l.push({op:"add",clientId:Ee(b.clientId,100)||void 0,kind:b.kind,statement:g,rationale:p,scope:ds(b.scope)})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let g={op:"revise",explanationId:b.explanationId,statement:Ee(b.statement)||void 0,rationale:Ee(b.rationale)||void 0,scope:ds(b.scope),reopenGrounding:b.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let g=Ee(b.summary);g&&l.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:g})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type)))l.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:Ee(b.rationale)});else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let g=Ee(b.reason);g&&l.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:g})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let g=Ee(b.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:g,rationale:Ee(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&l.push({op:"retire",explanationId:b.explanationId,reason:Ee(b.reason)})}let h=r.grounding,R=h&&typeof h.explanationId=="string"&&Ee(h.question)?{explanationId:h.explanationId,question:Ee(h.question,300)}:void 0;return{draft:{decision:"mutate",summary:d,appliedExplanationIds:c,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Wn(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(s=>` - Concrete terminal: ${s.modelPath} = ${JSON.stringify(s.value)}`)].join(`
199
- `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]}},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
200
- `)}var Dt=class{constructor(e,n){this.noopCounts=new Map;this.store=new Ot(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Un(e.text??""),t=Un((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:s}=await this.store.load(),i=s.explanations.filter(c=>c.state!=="retired"&&c.state!=="challenged").map(c=>{let l=Un([c.statement,c.rationale].join(" ")),h=Un(c.scope.values.join(" ")),R=qn(l,n),I=qn(h,n),b=qn(h,t),g=qn(l,t),p=R+I*.2+b*.25+g*.1+(c.state==="grounded"?.08:0)+(r.has(c.id)?1:0),y=r.has(c.id)||(n.size?R>=.12||I>=.5:b>=.2||g>=.2);return{item:c,score:p,relevant:y}}).filter(c=>c.relevant&&c.score>=.18).sort((c,l)=>l.score-c.score||l.item.updatedAt.localeCompare(c.item.updatedAt)),d=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,d).map(({item:c})=>{let l=new Set(s.relations.filter(h=>h.fromId===c.id&&h.type==="instantiates").map(h=>h.toId));return{id:c.id,kind:c.kind,statement:c.statement,rationale:c.rationale,scope:c.scope,state:c.state,concrete:s.concrete.filter(h=>l.has(h.id)).map(h=>({id:h.id,modelPath:h.modelPath,value:h.value}))}}),truncated:i.length>d,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,d=new Map,c=[],l=new Set,h=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=We();S.clientId&&i.set(S.clientId,A);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,_={id:A,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:Bo(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(A,_),l.add(A),c.push({op:"add_explanation",explanation:_})}let R=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let A=R(S.explanationId),J=s.get(A);if(J?.state!=="grounded")continue;let _=We(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?Bo(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(_,N),d.set(A,_),l.add(_),c.push({op:"add_explanation",explanation:N}),c.push({op:"add_relation",relation:{id:We(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let I=S=>{let A=R(S);return d.get(A)??A};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=I(S.explanationId);if(!s.has(J))continue;let _=Cc(n.concreteModel,S.modelPath);if(!_.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(_.value));N||(N={id:We(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},c.push({op:"add_concrete",concrete:N})),c.push({op:"add_relation",relation:{id:We(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=I(S.fromId),_=I(S.toId);if(!s.has(J)||!s.has(_)||J===_)continue;c.push({op:"add_relation",relation:{id:We(),type:S.type,fromId:J,toId:_,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(_);continue}if(S.op==="supersede"){let J=I(S.explanationId),_=I(S.replacementId);if(!s.has(J)||!s.has(_)||J===_)continue;c.push({op:"add_evidence",explanationId:J,evidence:ot(n,"challenges",S.reason)}),c.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:_},updatedAt:t}),c.push({op:"add_relation",relation:{id:We(),type:"contradicts",fromId:_,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(_);continue}let A=I(S.explanationId);if(s.has(A))if(l.add(A),S.op==="revise"){if(d.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:Bo(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};c.push({op:"revise_explanation",explanationId:A,patch:J,updatedAt:t})}else S.op==="evidence"?(c.push({op:"add_evidence",explanationId:A,evidence:ot(n,S.stance,S.summary)}),S.stance==="challenges"&&c.push({op:"revise_explanation",explanationId:A,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(c.push({op:"add_evidence",explanationId:A,evidence:ot(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),c.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let A=I(S),J=s.get(A);!J||J.state==="grounded"||J.state==="retired"||h.has(A)&&!l.has(A)||(l.has(A)||(l.add(A),c.push({op:"add_evidence",explanationId:A,evidence:{...ot(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&c.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!c.length)return;let b=We(),g=await this.store.commit({transactionId:b,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:c}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),y=[...l].flatMap(S=>{let A=p.get(S);if(!A)return[];let J=!r.graph.explanations.some(N=>N.id===S),_=A.state==="challenged"||A.state==="retired";return[{explanationId:S,action:J?"added":_?"challenged":"revised",statement:A.statement,state:A.state}]}),f=e.grounding?I(e.grounding.explanationId):void 0,v=f?p.get(f):void 0,x=v?.state==="testing"&&!h.has(v.id)?{explanationId:v.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:b,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:y,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let h of l)await this.store.undo(h,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,We());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},d=[],c="";if(e.action==="confirm")d.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),c=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")d.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),c=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(h=>h.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");d.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),c=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")d.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),c=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");d.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),c=`Edited: ${l}`}if(!d.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:We(),committedAt:n,source:i,summary:c,mutations:d})}};function sn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Gn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Lo(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 ls(o){let e=Lo(Gn(o.origin));if(e)return e;let n=Lo(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 Lo(`${r}://${t}`)}function ps(o,e,n=5){let t=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(c=>c.status==="applied"||c.status==="failed").sort(t).slice(0,n),i=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),d=i.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:d,actionableProposals:i}}import{createHash as Vn}from"crypto";import{mkdir as an,readFile as xt,unlink as Dc,writeFile as Nt}from"fs/promises";import{dirname as Kn,extname as Jc,join as Oe}from"path";var $c={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function Oc(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 us(o,e){let n=e??Oc(o);return{kind:n,...$c[n]}}function Jt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ms(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 Nc={version:1,threads:{}},fs=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],cn={version:2,updatedAt:0,files:{}};function Bc(o){return JSON.stringify(o,null,2)}function Lc(o){return Object.fromEntries(fs.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Fc(o){let e={...o};for(let n of fs)delete e[n];return e}function Bt(o){let e=o;if(o.error){let n=us(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=Jt(e.result,!1),t=Jt(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=Oe(e,".popmelt");this.legacyFilePath=Oe(n,"threads.json"),this.threadsDir=Oe(n,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(n,"artifacts","thread-messages"),this.mediaDir=Oe(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await xt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let s=await this.readThread(Oe(this.threadsDir,r));s&&(n[t]=s)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await xt(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(Bt)}]))},this.index={...cn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Nc,threads:{}},this.index={...cn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Bt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=r.messages.findIndex(i=>i.role==="human"&&!!i.replyToQuestion&&i.queued);s>=0?r.messages.splice(s,0,Bt(n)):r.messages.push(Bt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=s.messages.filter(d=>d.jobId===n);if(i.length===0)return!1;for(let d of i)if(Object.assign(d,t),d.error){let c=Bt(d);Object.assign(d,c),delete d.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(d=>d.role==="assistant"&&d.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",d=r.messages.filter(y=>y.role==="assistant"),c=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let f=y.imprintSummary?.grounding;if(f?.question&&!y.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(y=>!!c(y)),h=r.messages.findLastIndex(y=>y.role==="human"),R=l>h?c(r.messages[l]):void 0,I=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,h)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),g=d.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=d.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:I,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 xt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...s})=>{let i={};if(r?.path)try{let d=await xt(Oe(Kn(this.legacyFilePath),r.path),"utf8");Vn("sha256").update(d).digest("hex")===r.sha256&&(i=JSON.parse(d))}catch{}return Bt({...s,...i})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Lc(e),t=Fc(e);if(Object.keys(n).length===0)return t;let r=Bc(n),s=Vn("sha256").update(r).digest("hex"),i=Oe("artifacts","thread-messages",`${s}.json`);await an(this.artifactsDir,{recursive:!0});try{await xt(Oe(Kn(this.legacyFilePath),i),"utf8")}catch{await Nt(Oe(Kn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Kn(t)===this.mediaDir)return t;try{let r=await xt(t),s=Vn("sha256").update(r).digest("hex"),i=Oe(this.mediaDir,`${s}${Jc(t)||".bin"}`);await an(this.mediaDir,{recursive:!0});try{await xt(i)}catch{await Nt(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await an(this.threadsDir,{recursive:!0});let n=this.index??{...cn,files:{}},t=n.files[e.id]??`${Vn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(i=>this.encodeMessage(i))),s={...e,version:2,messages:r};await Nt(Oe(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Nt(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 Nt(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 Dc(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await an(this.threadsDir,{recursive:!0}),await Nt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as zc,open as Uc,readFile as qc,rename as Hc,unlink as Wc}from"fs/promises";import{dirname as Gc,join as Vc}from"path";var hs={schemaVersion:1,theme:"auto",updatedAt:null};function gs(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Kc(o,e){await zc(Gc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Uc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
201
- `,"utf8"),await t.sync()}finally{await t.close()}await Hc(n,o)}catch(t){throw await Wc(n).catch(()=>{}),t}}var Xn=class{constructor(e){this.path=Vc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await qc(this.path,"utf8")),n=gs(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...hs}}}catch{return{exists:!1,preferences:{...hs}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Kc(this.path,n),n}};function ys(o){return gs(o)!==null}function Yn(o){return Xc(o).slice(0,12)}var Qc=[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 Xc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Yc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let I=7;I>=0;I--)e.push(n/Math.pow(2,I*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,d=1359893119,c=2600822924,l=528734635,h=1541459225,R=new Array(64);for(let I=0;I<e.length;I+=64){for(let A=0;A<16;A++){let J=I+A*4;R[A]=(e[J]<<24|e[J+1]<<16|e[J+2]<<8|e[J+3])>>>0}for(let A=16;A<64;A++){let J=Xe(R[A-15],7)^Xe(R[A-15],18)^R[A-15]>>>3,_=Xe(R[A-2],17)^Xe(R[A-2],19)^R[A-2]>>>10;R[A]=R[A-16]+J+R[A-7]+_>>>0}let b=t,g=r,p=s,y=i,f=d,v=c,x=l,S=h;for(let A=0;A<64;A++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),_=f&v^~f&x,N=S+J+_+Qc[A]+R[A]>>>0,T=Xe(b,2)^Xe(b,13)^Xe(b,22),B=b&g^b&p^g&p,H=T+B>>>0;S=x,x=v,v=f,f=y+N>>>0,y=p,p=g,g=b,b=N+H>>>0}t=t+b>>>0,r=r+g>>>0,s=s+p>>>0,i=i+y>>>0,d=d+f>>>0,c=c+v>>>0,l=l+x>>>0,h=h+S>>>0}return[t,r,s,i,d,c,l,h].map(I=>I.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Yc(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 vs={name:"@popmelt.com/core",version:"0.8.6",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var rt=vs.version;var dd=1111,ld=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],pd=1800*1e3,ud=3600*1e3,bs=45e3,md=5e3,fd=1e4;function xs(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
202
- `)}function eo(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function hd(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 Es(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 gd(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let s=n[n.length-1];s&&s.kind==="text"?s.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",s=t.file??void 0,i=t.content??void 0,d=s?s.split("/").pop()??s:void 0,c;switch(r){case"Read":c=d?`Reading ${d}`:"Reading file";break;case"Edit":c=d?`Editing ${d}`:"Editing file";break;case"Write":c=d?`Writing ${d}`:"Writing file";break;case"Bash":c=i?i.split(`
203
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=r?`Using ${r}`:"tool";break}let l=s??i??void 0,h=s?zo(s)?s:js(e,s):void 0,R=n[n.length-1];R&&R.kind==="tool_group"&&R.tool===r?R.items.push({label:c,detail:l,...h?{filePath:h}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:c,detail:l,...h?{filePath:h}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function yd(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let n=[];return o.success?n.push("Model suggestion ready."):n.push("Model projection failed."),o.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(n.push(""),n.push(`Error: ${o.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
204
- `)}function vd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Ss(o){let e=o.styleModifications.flatMap(i=>{let d=i.element?.reactComponent||i.element?.tagName||i.selector;return i.changes.map(c=>`${d}: ${c.property} ${c.original||"unset"} -> ${c.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(i=>`${i.tokenName}: ${i.originalPx}px -> ${i.newPx}px`),t=(o.textModifications??[]).map(i=>`${i.element?.reactComponent||i.element?.tagName||i.selector}: text ${i.original||"empty"} -> ${i.modified||"empty"}`),r=o.annotations.map(i=>{let d=i.instruction?.trim();if(d)return d;if(i.imageCount&&i.imageCount>0)return`${i.imageCount} image${i.imageCount===1?"":"s"}`;let c=i.elements?.[0]?.reactComponent||i.elements?.[0]?.selector||i.linkedSelector||i.type;return`${i.type==="annotation"?"Annotation":`${i.type} annotation`} on ${c}`}),s=[...e,...t,...n,...r].map(i=>vd(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function wd(o,e){let n=o.headers.origin;Es(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function E(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function ze(o){let e=[],n=0;for await(let r of o){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>16384)throw new Error("Request body too large");e.push(s)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Id(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function bd(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,r,s]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(r,16)};${parseInt(s,16)}m${e}\x1B[0m`}function to(o,e){try{o.res.write(`event: ${e.type}
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 nn(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 ti(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,w=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${w} \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 w=new Map;for(let k of s)if(typeof k=="object"&&k!==null&&"text"in k){let P=k,x=P.scope||"general";w.has(x)||w.set(x,[]),w.get(x).push(P.text)}for(let[k,P]of w){t.push(`**${k.charAt(0).toUpperCase()+k.slice(1)}**`);for(let x of P)t.push(`- ${x}`)}}else for(let w of s)typeof w=="string"&&t.push(`- ${w}`);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 w=s[d];w&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${w}`):!w&&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 k={...e,annotations:l,styleModifications:e.styleModifications},P=nn(k,n?.imagePaths);P&&(t.push(""),t.push(P))}}else{let s=nn(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 ni(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function oi(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 mc(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 fc(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&&!mc(e[n]))return!1;return!0}function ri(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(fc):[]}catch{return[]}}function ii(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 hc}from"child_process";import{readdir as gc,readFile as yc,stat as vc}from"fs/promises";import{homedir as on}from"os";import{join as Ye}from"path";var qn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:si()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:si()}],rn=[{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"}],sn={id:"",label:"Default",source:"cli"},Ic=/^\s*-\s+"([^"]+)"/;function wc(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(Ic);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Uo(i),source:"cli"})}return Hn([sn,...e])}function bc(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():Uo(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 si(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function xc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Hn(e.map(n=>({id:n,label:Uo(n),source:"cli"})))}function Uo(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":kc(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 ai(o="copilot"){let e=await Un(o,["help","config"]),n=wc(e);return n.length>1?n:[sn]}async function ci(o="codex"){let e=await Un(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Ye(on(),".codex");return li(Ye(t,"models_cache.json"))}),n=bc(e);return n.length>0?Hn([...n,...rn]):rn}async function di(o="claude"){let e=Ye(on(),".claude"),n=[Ye(on(),".claude","stats-cache.json"),Ye(on(),".claude","settings.json"),Ye(on(),".claude.json"),Ye(e,"cache","changelog.md")],[t,r,i]=await Promise.all([Un(o,["--help"]).catch(()=>""),Un(o,["--version"]).catch(()=>""),Sc(e).catch(()=>[])]),s=Pc([...n,...i]),c=await Promise.all(s.map(l=>li(l).catch(()=>""))),d=xc([t,r,...c].join(`
197
+ `));return Hn([...qn,...d])}function Un(o,e,n=5e3){return new Promise((t,r)=>{hc(o,e,{encoding:"utf-8",timeout:n},(i,s)=>{if(i){r(i);return}t(s)})})}async function li(o){return yc(o,"utf-8")}async function Sc(o){let e=[Ye(o,"projects"),Ye(o,"telemetry")],n=[];for(let t of e)await pi(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function pi(o,e,n){if(n<0)return;let t;try{t=await gc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let i=Ye(o,r.name);if(r.isDirectory()){await pi(i,e,n-1);return}if(!(!r.isFile()||!Rc(r.name)))try{let s=await vc(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function Rc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Hn(o){let e=new Set,n=[];for(let t of o)e.has(t.id)||(e.add(t.id),n.push(t));return n}function Pc(o){return[...new Set(o)]}function kc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Wn=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 Ge}from"crypto";import{createHash as Tc}from"crypto";import{mkdir as jc,open as Ec,readFile as ui,readdir as Ac,rename as Mc,unlink as _c}from"fs/promises";import{dirname as Cc,join as Ot}from"path";function $e(o){return structuredClone(o)}function mi(o){return Tc("sha256").update(JSON.stringify(o)).digest("hex")}async function an(o,e){await jc(Cc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ec(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
198
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Mc(n,o)}catch(r){throw await _c(n).catch(()=>{}),r}}function $c(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Oc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=$e(e):o.explanations.push($e(e))}function Gn(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")Oc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(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($e(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,$e(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($e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Dc(o,e){let n=[],t=$e(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=t.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:$e(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:$e(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:$e(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:$e(i)})}t=Gn(t,[r])}return n}function fi(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 Dt=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ot(e,".popmelt","imprint"),this.manifestPath=Ot(this.imprintDir,"manifest.json"),this.graphPath=Ot(this.imprintDir,"graph.json"),this.journalDir=Ot(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ui(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 Ac(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=$c(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await ui(Ot(this.journalDir,t[c]),"utf8")),{hash:l,...w}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==mi(w))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Gn(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(k=>k.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,i=Dc(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:$e(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:mi(s)},d=Gn(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 an(Ot(this.journalDir,l),c);let w={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await an(this.graphPath,d),await an(this.manifestPath,w),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(fi));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(w=>fi(w).some(k=>c.has(k)))))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 an(this.graphPath,e.graph),await an(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Jc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Nc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Bc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Vn(o){return new Set(Bc(o).split(" ").filter(e=>e.length>2&&!Nc.has(e)))}function Kn(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 qo(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 it(o,e,n){return{id:Ge(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function hi(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 gi(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 Qn(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 P=String(r.reason);if(!Jc.has(P))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:P},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(P=>typeof P=="string"&&!!P.trim()):[],l=[];for(let P of Array.isArray(r.mutations)?r.mutations:[]){if(!P||typeof P!="object")continue;let x=P;if(x.op==="add"&&["intention","principle","pattern"].includes(String(x.kind))){let m=je(x.statement),p=je(x.rationale);if(!m||!p)continue;l.push({op:"add",clientId:je(x.clientId,100)||void 0,kind:x.kind,statement:m,rationale:p,scope:hi(x.scope),rootReason:je(x.rootReason,300)||void 0})}else if(x.op==="revise"&&typeof x.explanationId=="string"){let m={op:"revise",explanationId:x.explanationId,statement:je(x.statement)||void 0,rationale:je(x.rationale)||void 0,scope:hi(x.scope),reopenGrounding:x.reopenGrounding===!0};(m.statement||m.rationale||m.scope||m.reopenGrounding)&&l.push(m)}else if(x.op==="evidence"&&typeof x.explanationId=="string"&&["supports","challenges","excepts"].includes(String(x.stance))){let m=je(x.summary);m&&l.push({op:"evidence",explanationId:x.explanationId,stance:x.stance,summary:m})}else if(x.op==="relation"&&typeof x.fromId=="string"&&typeof x.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(x.type))){let m=je(x.rationale);if(!m)continue;l.push({op:"relation",type:x.type,fromId:x.fromId,toId:x.toId,rationale:m})}else if(x.op==="supersede"&&typeof x.explanationId=="string"&&typeof x.replacementId=="string"){let m=je(x.reason);m&&l.push({op:"supersede",explanationId:x.explanationId,replacementId:x.replacementId,reason:m})}else if(x.op==="bind_concrete"&&typeof x.explanationId=="string"){let m=je(x.modelPath,300);m&&l.push({op:"bind_concrete",explanationId:x.explanationId,modelPath:m,rationale:je(x.rationale)})}else x.op==="retire"&&typeof x.explanationId=="string"&&l.push({op:"retire",explanationId:x.explanationId,reason:je(x.reason)})}let w=r.grounding,k=w&&typeof w.explanationId=="string"&&je(w.question)?{explanationId:w.explanationId,question:je(w.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:k},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Xn(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."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(t=>`- ${t.fromId} --${t.type}--> ${t.toId}: ${t.rationale}`)]:[],"","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.","Topology assessment is mandatory for every add mutation. Connect the new clientId with relation or supersede mutations whenever it overlaps, specializes, operationalizes, supports, contradicts, or excepts another surfaced or newly-added explanation. If it is genuinely a new root with no meaningful relative, include rootReason on the add mutation explaining why. Unmapped additions without rootReason are rejected.","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>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"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 Jt=class{constructor(e,n){this.noopCounts=new Map;this.store=new Dt(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=Vn(e.text??""),t=Vn((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(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let p=Vn([m.statement,m.rationale].join(" ")),y=Vn(m.scope.values.join(" ")),h=Kn(p,n),f=Kn(y,n),u=Kn(y,t),E=Kn(p,t),O=h+f*.2+u*.25+E*.1+(m.state==="grounded"?.08:0)+(r.has(m.id)?1:0),R=r.has(m.id)||(n.size?h>=.12||f>=.5:u>=.2||E>=.2);return{item:m,score:O,relevant:R}}).filter(m=>m.relevant&&m.score>=.18).sort((m,p)=>p.score-m.score||p.item.updatedAt.localeCompare(m.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:m})=>m),l=new Set(d.map(m=>m.id)),w=new Set(i.relations.flatMap(m=>l.has(m.fromId)?[m.toId]:l.has(m.toId)?[m.fromId]:[])),k=new Set(i.explanations.flatMap(m=>w.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),P=i.explanations.filter(m=>k.has(m.id)&&!l.has(m.id)).sort((m,p)=>p.updatedAt.localeCompare(m.updatedAt)).slice(0,4),x=[...d,...P];for(let m of P)l.add(m.id);return{explanations:x.map(m=>{let p=new Set(i.relations.filter(y=>y.fromId===m.id&&y.type==="instantiates").map(y=>y.toId));return{id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state,concrete:i.concrete.filter(y=>p.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||P.length<k.size,...r.size?{pendingGroundingExplanationIds:[...r]}:{},relations:i.relations.filter(m=>l.has(m.fromId)&&l.has(m.toId)&&m.type!=="instantiates").map(m=>({id:m.id,type:m.type,fromId:m.fromId,toId:m.toId,rationale:m.rationale}))}}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(I=>[I.id,I])),s=new Map,c=new Map,d=[],l=new Set,w=new Set(n.pendingGroundingExplanationIds??[]),k=new Set(e.mutations.flatMap(I=>I.op==="add"&&I.clientId?[I.clientId]:[])),P=I=>i.has(I)||k.has(I),x=new Set;for(let I of e.mutations)I.op==="relation"&&I.fromId!==I.toId&&P(I.fromId)&&P(I.toId)?(x.add(I.fromId),x.add(I.toId)):I.op==="supersede"&&I.explanationId!==I.replacementId&&P(I.explanationId)&&P(I.replacementId)?(x.add(I.explanationId),x.add(I.replacementId)):I.op==="bind_concrete"&&P(I.explanationId)&&gi(n.concreteModel,I.modelPath).found&&x.add(I.explanationId);let m=r.graph.explanations.length===0;for(let I of e.mutations){if(I.op!=="add")continue;let b=!!(I.clientId&&x.has(I.clientId)),M=!!I.rootReason?.trim()||m;if(!b&&!M)continue;m&&(m=!1);let L=Ge();I.clientId&&s.set(I.clientId,L);let G=I.clientId?e.appliedExplanationIds.includes(I.clientId):!1,U={id:L,kind:I.kind,statement:I.statement,rationale:I.rationale,scope:qo(I.scope),state:G?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[it(n,"supports",e.summary.detail)]};i.set(L,U),l.add(L),d.push({op:"add_explanation",explanation:U})}let p=I=>s.get(I)??I;for(let I of e.mutations){if(I.op!=="revise")continue;let b=p(I.explanationId),M=i.get(b);if(M?.state!=="grounded")continue;let L=Ge(),G={id:L,kind:M.kind,statement:I.statement??M.statement,rationale:I.rationale??M.rationale,scope:I.scope?qo(I.scope):M.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[it(n,"supports",e.summary.detail)]};i.set(L,G),c.set(b,L),l.add(L),d.push({op:"add_explanation",explanation:G}),d.push({op:"add_relation",relation:{id:Ge(),type:"refines",fromId:L,toId:b,rationale:I.rationale??e.summary.detail,createdAt:t}})}let y=I=>{let b=p(I);return c.get(b)??b};for(let I of e.mutations){if(I.op==="add")continue;if(I.op==="bind_concrete"){let M=y(I.explanationId);if(!i.has(M))continue;let L=gi(n.concreteModel,I.modelPath);if(!L.found)continue;let G=r.graph.concrete.find(U=>U.modelPath===I.modelPath&&JSON.stringify(U.value)===JSON.stringify(L.value));G||(G={id:Ge(),modelPath:I.modelPath,value:structuredClone(L.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:G})),d.push({op:"add_relation",relation:{id:Ge(),type:"instantiates",fromId:M,toId:G.id,rationale:I.rationale,createdAt:t}}),l.add(M);continue}if(I.op==="relation"){let M=y(I.fromId),L=y(I.toId);if(!i.has(M)||!i.has(L)||M===L)continue;d.push({op:"add_relation",relation:{id:Ge(),type:I.type,fromId:M,toId:L,rationale:I.rationale,createdAt:t}}),l.add(M),l.add(L);continue}if(I.op==="supersede"){let M=y(I.explanationId),L=y(I.replacementId);if(!i.has(M)||!i.has(L)||M===L)continue;d.push({op:"add_evidence",explanationId:M,evidence:it(n,"challenges",I.reason)}),d.push({op:"revise_explanation",explanationId:M,patch:{state:"challenged",supersededBy:L},updatedAt:t}),d.push({op:"add_relation",relation:{id:Ge(),type:"contradicts",fromId:L,toId:M,rationale:I.reason,createdAt:t}}),l.add(M),l.add(L);continue}let b=y(I.explanationId);if(i.has(b))if(l.add(b),I.op==="revise"){if(c.has(p(I.explanationId)))continue;let M={...I.statement?{statement:I.statement}:{},...I.rationale?{rationale:I.rationale}:{},...I.scope?{scope:qo(I.scope)}:{},...I.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:b,patch:M,updatedAt:t})}else I.op==="evidence"?(d.push({op:"add_evidence",explanationId:b,evidence:it(n,I.stance,I.summary)}),I.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:b,patch:{state:"challenged"},updatedAt:t})):I.op==="retire"&&(d.push({op:"add_evidence",explanationId:b,evidence:it(n,"challenges",I.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:b,patch:{state:"retired"},updatedAt:t}))}for(let I of e.appliedExplanationIds){let b=y(I),M=i.get(b);!M||M.state==="grounded"||M.state==="retired"||w.has(b)&&!l.has(b)||(l.has(b)||(l.add(b),d.push({op:"add_evidence",explanationId:b,evidence:{...it(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),M.state==="emerging"&&d.push({op:"revise_explanation",explanationId:b,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let h=Ge(),f=await this.store.commit({transactionId:h,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),u=new Map(f.graph.explanations.map(I=>[I.id,I])),E=[...l].flatMap(I=>{let b=u.get(I);if(!b)return[];let M=!r.graph.explanations.some(G=>G.id===I),L=b.state==="challenged"||b.state==="retired";return[{explanationId:I,action:M?"added":L?"challenged":"revised",statement:b.statement,state:b.state}]}),O=e.grounding?y(e.grounding.explanationId):void 0,R=O?u.get(O):void 0,C=R?.state==="testing"&&!w.has(R.id)?{explanationId:R.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:h,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:E,...C?{grounding:C}:{}}}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 w of l)await this.store.undo(w,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,Ge());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let 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:{...it(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:{...it(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(w=>w.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:{...it(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:Ge(),committedAt:n,source:s,summary:d,mutations:c})}};function cn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Yn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Ho(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 yi(o){let e=Ho(Yn(o.origin));if(e)return e;let n=Ho(Yn(o.referer));if(n)return n;let t=Yn(o["x-forwarded-host"]);if(!t)return null;let r=Yn(o["x-forwarded-proto"])==="https"?"https":"http";return Ho(`${r}://${t}`)}function vi(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 Zn}from"crypto";import{mkdir as dn,readFile as St,unlink as zc,writeFile as Bt}from"fs/promises";import{dirname as eo,extname as Uc,join as Oe}from"path";var Lc={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 Fc(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 Ii(o,e){let n=e??Fc(o);return{kind:n,...Lc[n]}}function Nt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function wi(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 qc={version:1,threads:{}},bi=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],ln={version:2,updatedAt:0,files:{}};function Hc(o){return JSON.stringify(o,null,2)}function Wc(o){return Object.fromEntries(bi.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Gc(o){let e={...o};for(let n of bi)delete e[n];return e}function Lt(o){let e=o;if(o.error){let n=Ii(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=Nt(e.result,!1),t=Nt(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 to=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Oe(e,".popmelt");this.legacyFilePath=Oe(n,"threads.json"),this.threadsDir=Oe(n,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(n,"artifacts","thread-messages"),this.mediaDir=Oe(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await St(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(Oe(this.threadsDir,r));i&&(n[t]=i)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await St(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(Lt)}]))},this.index={...ln,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...qc,threads:{}},this.index={...ln,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(Lt(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,Lt(n)):r.messages.push(Lt(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=Lt(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(y=>y.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(y=>y.role==="assistant"),d=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let h=y.imprintSummary?.grounding;if(h?.question&&!y.imprintSummary?.resolvedAction)return h.question},l=r.messages.findLastIndex(y=>!!d(y)),w=r.messages.findLastIndex(y=>y.role==="human"),k=l>w?d(r.messages[l]):void 0,P=r.messages.at(-1)?.role,x=Array.from(new Set(r.messages.slice(0,Math.max(0,w)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),m=c.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=c.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:m,hasError:p,lastMessageRole:P,pendingQuestion:k,acknowledgedJobIds:x,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 St(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 St(Oe(eo(this.legacyFilePath),r.path),"utf8");Zn("sha256").update(c).digest("hex")===r.sha256&&(s=JSON.parse(c))}catch{}return Lt({...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=Wc(e),t=Gc(e);if(Object.keys(n).length===0)return t;let r=Hc(n),i=Zn("sha256").update(r).digest("hex"),s=Oe("artifacts","thread-messages",`${i}.json`);await dn(this.artifactsDir,{recursive:!0});try{await St(Oe(eo(this.legacyFilePath),s),"utf8")}catch{await Bt(Oe(eo(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(eo(t)===this.mediaDir)return t;try{let r=await St(t),i=Zn("sha256").update(r).digest("hex"),s=Oe(this.mediaDir,`${i}${Uc(t)||".bin"}`);await dn(this.mediaDir,{recursive:!0});try{await St(s)}catch{await Bt(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 dn(this.threadsDir,{recursive:!0});let n=this.index??{...ln,files:{}},t=n.files[e.id]??`${Zn("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 Bt(Oe(this.threadsDir,t),JSON.stringify(i,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Bt(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 dn(this.threadsDir,{recursive:!0}),this.index=this.index??{...ln,files:{}},await Bt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...ln,files:{}},t=n.files[e];t&&await zc(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await dn(this.threadsDir,{recursive:!0}),await Bt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Vc,open as Kc,readFile as Qc,rename as Xc,unlink as Yc}from"fs/promises";import{dirname as Zc,join as ed}from"path";var xi={schemaVersion:1,theme:"auto",updatedAt:null};function Si(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function td(o,e){await Vc(Zc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Kc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
201
+ `,"utf8"),await t.sync()}finally{await t.close()}await Xc(n,o)}catch(t){throw await Yc(n).catch(()=>{}),t}}var no=class{constructor(e){this.path=ed(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Qc(this.path,"utf8")),n=Si(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...xi}}}catch{return{exists:!1,preferences:{...xi}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await td(this.path,n),n}};function Ri(o){return Si(o)!==null}function oo(o){return od(o).slice(0,12)}var nd=[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 od(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):rd(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let P=7;P>=0;P--)e.push(n/Math.pow(2,P*8)&255);let t=1779033703,r=3144134277,i=1013904242,s=2773480762,c=1359893119,d=2600822924,l=528734635,w=1541459225,k=new Array(64);for(let P=0;P<e.length;P+=64){for(let O=0;O<16;O++){let R=P+O*4;k[O]=(e[R]<<24|e[R+1]<<16|e[R+2]<<8|e[R+3])>>>0}for(let O=16;O<64;O++){let R=Ze(k[O-15],7)^Ze(k[O-15],18)^k[O-15]>>>3,C=Ze(k[O-2],17)^Ze(k[O-2],19)^k[O-2]>>>10;k[O]=k[O-16]+R+k[O-7]+C>>>0}let x=t,m=r,p=i,y=s,h=c,f=d,u=l,E=w;for(let O=0;O<64;O++){let R=Ze(h,6)^Ze(h,11)^Ze(h,25),C=h&f^~h&u,I=E+R+C+nd[O]+k[O]>>>0,b=Ze(x,2)^Ze(x,13)^Ze(x,22),M=x&m^x&p^m&p,L=b+M>>>0;E=u,u=f,f=h,h=y+I>>>0,y=p,p=m,m=x,x=I+L>>>0}t=t+x>>>0,r=r+m>>>0,i=i+p>>>0,s=s+y>>>0,c=c+h>>>0,d=d+f>>>0,l=l+u>>>0,w=w+E>>>0}return[t,r,i,s,c,d,l,w].map(P=>P.toString(16).padStart(8,"0")).join("")}function Ze(o,e){return o>>>e|o<<32-e}function rd(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 Pi={name:"@popmelt.com/core",version:"0.8.7",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 st=Pi.version;var hd=1111,gd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],yd=1800*1e3,vd=3600*1e3,ji=45e3,Id=5e3,wd=1e4;function Ei(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
202
+ `)}function un(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function bd(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 Di(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 xd(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(`
203
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let l=i??s??void 0,w=i?Go(i)?i:Oi(e,i):void 0,k=n[n.length-1];k&&k.kind==="tool_group"&&k.tool===r?k.items.push({label:d,detail:l,...w?{filePath:w}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...w?{filePath:w}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function Sd(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let n=[];return o.success?n.push("Model suggestion ready."):n.push("Model projection failed."),o.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(n.push(""),n.push(`Error: ${o.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
204
+ `)}function Rd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Ai(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=>Rd(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Pd(o,e){let n=o.headers.origin;Di(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 _(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function ze(o){let e=[],n=0;for await(let r of o){let 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 kd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function Td(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,r,i]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function io(o,e){try{o.res.write(`event: ${e.type}
205
205
  data: ${JSON.stringify(e)}
206
206
 
207
- `)}catch{}}function St(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function oo(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 xd(o,e){return new Promise((n,t)=>{let r=i=>{o.removeListener("listening",s),t(i)},s=()=>{o.removeListener("error",r),n()};o.once("error",r),o.once("listening",s),o.listen(e,"127.0.0.1")})}function Ps(o){try{let e=no("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=no("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=no("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Ts("sha256").update(`${e}
207
+ `)}catch{}}function Rt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function ao(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 jd(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 Mi(o){try{let e=so("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=so("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=so("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return $i("sha256").update(`${e}
208
208
  ${t}
209
- ${r}`).digest("hex").slice(0,16)}catch{return}}function Sd(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 Rs(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let s of[...t].sort((i,d)=>`${i.kind}:${i.value}`.localeCompare(`${d.kind}:${d.value}`)))if(s.kind==="model_path")r.push([s.kind,s.value,Sd(n,s.value)]);else if(s.kind==="source_file"){let i=js(o,s.value),c=i===o||i.startsWith(`${o}/`)?await Fo(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,c])}else r.push([s.kind,s.value]);return Ts("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ms(o={}){let e=new Date().toISOString(),n=o.port??dd,t=o.projectRoot??process.cwd(),r=await nd(t).catch(()=>t),s=Yn(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=o.tempDir??Me(id(),"popmelt-bridge"),c=o.maxTurns??40,l=o.maxBudgetUsd??1,h=[...o.allowedTools??ld],R=o.claudePath??"claude",I=o.copilotPath??"copilot",b=o.provider??"claude",g=o.timeoutMs,p=o.restartMode??"embedded",y=n,f={},v={claude:R,codex:"codex",copilot:I};for(let[a,u]of Object.entries(v))try{let k=u.includes("/")?u:no("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=ws(u,["--version"],{stdio:["ignore","ignore","ignore"]}),P=!1,w=$=>{P||(P=!0,k($))},j=setTimeout(()=>{m.kill("SIGTERM"),w(!0)},5e3);m.on("error",()=>{clearTimeout(j),w(!1)}),m.on("close",$=>{clearTimeout(j),w($===0)})})}await Promise.all([(async()=>{f.claude&&(f.claude.models=f.claude.available&&f.claude.path?await os(f.claude.path).catch(()=>Bn):Bn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await ns(f.codex.path).catch(()=>nn):nn)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await ts(f.copilot.path).catch(()=>[on]):[on])})()]);let[S,A,J]=await Promise.all([Io(r),bo(r),xo(r,f.copilot?.path??I)]),_=await br(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=A),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&h.push(`mcp__${S.name}__*`),await ed(d,{recursive:!0}),ks(d).catch(()=>{});let N=new Fn(1),T=new Sn,B=new kn(bs),H=null,ee=0,W=!1,te=()=>{ee+=1,W=!1,H&&clearTimeout(H),H=null},ne=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ge=()=>{if(p!=="detached"||B.size>0||W)return;W=!0;let a=++ee,u=Date.now()+fd,k=()=>{if(a!==ee)return;if(B.size>0){te();return}if(!(N.isRunning||N.depth>0||T.isRunning||T.depth>0)||Date.now()>=u){W=!1,H=setTimeout(ne,50),H.unref?.();return}H=setTimeout(k,250),H.unref?.()};k()},X=new Set,G=new Qn(r),U=new $n(r),he=new Dt(r,s),M=new Xn(r),Y=new gn(r),ue=new wn(r),ie=new xn(r,{claudePath:R,provider:b,timeoutMs:g,loadProjectableDecisions:a=>U.getProjectableDecisions(a),onEvent:a=>{for(let u of X)to(u,a)}});U.beginAutomaticInitialization({writerVersion:rt}).then(async a=>{a.state==="ready"?(await U.migrateLegacyEvals(),await U.migrateImprintSnapshot(),await ie.applyCanonicalEntries(await U.getCanonicalModelEntries()),b!=="copilot"&&(await ie.getUnprojectedPatternDecisions()).length>0&&await je({provider:b,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let De=20,Je=300*1e3,Pe=[];function Ue(){let a=Date.now()-Je;for(;Pe.length>0&&(Pe[0].completedAt<a||Pe.length>De);)Pe.shift()}let Ge=new Map;async function Ye(a){if(a.status!=="applied")return[];let u={version:1,updatedAt:Date.now(),cases:await U.getJournalEvalCases()},k=dr(a,u);if(k.length===0)return[];let m=await U.getEvalDependenciesForDecisions(a.decisionIds),P=a.threadId?await G.getThread(a.threadId):null,w=[...new Set((P?.messages??[]).flatMap(D=>(D.editEvents??[]).flatMap(F=>F.filePath?[F.filePath]:[])).map(D=>zo(D)?Is(r,D):D))].map(D=>({kind:"source_file",value:D})),j=k.map(D=>{let F=[...new Map([...D.dependencies??[],...m,...w].map(q=>[`${q.kind}:${q.value}:${"subjectId"in q?q.subjectId??"":""}`,q])).values()],L=F.filter(q=>q.kind==="route"),C=F.flatMap(q=>q.kind==="model_path"&&q.value.startsWith("components.")?[q.value.slice(11).split(".")[0]]:[]),O=[...new Set(F.flatMap(q=>"subjectId"in q&&q.subjectId?[q.subjectId]:[]))],K=L.length>0?L.map((q,se)=>({id:`route-${se+1}`,...q.value.includes("*")?{routePattern:q.value}:{route:q.value},components:C.map(ae=>({name:ae})),subjectIds:O})):[{id:C.length>0?`component-${C[0]}`:"current-page",components:C.map(q=>({name:q})),subjectIds:O}];return{...D,dependencies:F,scenarios:D.scenarios?.length?D.scenarios:K}}),$=new Set(u.cases.map(D=>D.id));return await U.syncEvalSpecs(j),await ie.attachGeneratedEvals(a.id,j.map(D=>({evalId:D.id,title:D.title,action:$.has(D.id)&&(a.evalProjections?.some(F=>F.evalId===D.id)||!a.generatedEvalIds?.includes(D.id))?"extended":"created"}))),j.map(D=>D.id)}async function st(a){let u=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",k=uo(a.claim)||"The product satisfies the declared model constraint.",m={id:`eval-decision-${a.decisionId}`,title:u.charAt(0).toUpperCase()+u.slice(1),status:"pending",category:a.modelPath.startsWith("components.")?"component":a.modelPath.startsWith("tokens.")?"visual":"workflow",prompt:"Verify this product expectation across the declared scenarios.",assertions:[k],rationale:`Protects the ${a.modelPath} constraint from implementation drift.`,sourceDecisionIds:[a.decisionId],sourceThreadIds:[],dependencies:[{kind:"model_path",value:a.modelPath}],scenarios:[{id:a.modelPath.startsWith("components.")?`component-${u.replace(/\s+/g,"-")}`:"current-page",components:a.modelPath.startsWith("components.")?[{name:a.modelPath.slice(11).split(".")[0]}]:void 0}]};return await U.syncEvalSpecs([m]),m.id}let mt=null,Lt;N.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&to(m,a)}),T.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&to(m,a)}),T.setProcessor(async a=>{let u=a.provider??b;try{let k=await ie.run({provider:u,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let m=await ie.loadRuns(),P=k.runId?m.runs.find(j=>j.id===k.runId):void 0;if(k.success&&k.proposalId){let j=await ie.findModelProposal(k.proposalId),$=await ie.loadModel(),D=j?gr(j,$):null;if(j&&D){let F=j.decisionIds.map(C=>({decisionId:C,status:"projected"}));await U.applyModelProjection({runId:j.runId??j.id,presentationJobId:j.presentationJobId,decisionIds:j.decisionIds,changes:D.map(C=>({path:C.path,value:C.value,decisionIds:C.decisionIds})),coverage:F});let L=await ie.applySelectedModelProposal(j.id,D.map(C=>({path:C.path,value:C.value})),D.map(C=>({group:C.path[0]==="rules"||C.path[0]==="components"||C.path[0]==="tokens"?C.path[0]:"model",label:C.label??C.id,detail:C.rationale,path:C.path,value:C.value})),"automatic");L&&await Ye(L)}}let w=yd(k,P);if(a.threadId&&(await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,model:a.model,provider:u})),k.success)a.status="done",a.result=w,T.broadcast({type:"done",jobId:a.id,success:!0,responseText:w,threadId:a.threadId},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue();else{if(a.status="error",a.error=k.error??"Projection failed",a.threadId){let j=`Model projection failed.
209
+ ${r}`).digest("hex").slice(0,16)}catch{return}}function Ed(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 _i(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,Ed(n,i.value)]);else if(i.kind==="source_file"){let s=Oi(o,i.value),d=s===o||s.startsWith(`${o}/`)?await Wo(s,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([i.kind,i.value,d])}else r.push([i.kind,i.value]);return $i("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ji(o={}){let e=new Date().toISOString(),n=o.port??hd,t=o.projectRoot??process.cwd(),r=await cd(t).catch(()=>t),i=oo(r),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ae(ud(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,w=[...o.allowedTools??gd],k=o.claudePath??"claude",P=o.copilotPath??"copilot",x=o.provider??"claude",m=o.timeoutMs,p=o.restartMode??"embedded",y=n,h={},f={claude:k,codex:"codex",copilot:P};for(let[a,g]of Object.entries(f))try{let j=g.includes("/")?g:so("which",[g],{encoding:"utf-8"}).trim();h[a]={available:!0,path:j}}catch{h[a]={available:!1,path:null}}function u(a,g){return new Promise(j=>{let v=ki(g,["--version"],{stdio:["ignore","ignore","ignore"]}),T=!1,S=J=>{T||(T=!0,j(J))},A=setTimeout(()=>{v.kill("SIGTERM"),S(!0)},5e3);v.on("error",()=>{clearTimeout(A),S(!1)}),v.on("close",J=>{clearTimeout(A),S(J===0)})})}await Promise.all([(async()=>{h.claude&&(h.claude.models=h.claude.available&&h.claude.path?await di(h.claude.path).catch(()=>qn):qn)})(),(async()=>{h.codex&&(h.codex.models=h.codex.available&&h.codex.path?await ci(h.codex.path).catch(()=>rn):rn)})(),(async()=>{h.copilot&&(h.copilot.models=h.copilot.available&&h.copilot.path?await ai(h.copilot.path).catch(()=>[sn]):[sn])})()]);let[E,O,R]=await Promise.all([Ro(r),Po(r),ko(r,h.copilot?.path??P)]),C=await kr(r);h.claude&&(h.claude.mcp=E),h.codex&&(h.codex.mcp=O),h.copilot&&(h.copilot.mcp=R),E.found&&E.name&&w.push(`mcp__${E.name}__*`),await sd(c,{recursive:!0}),Ci(c).catch(()=>{});let I=new Wn(1),b=new kn,M=new En(ji),L=null,G=0,U=!1,ne=()=>{G+=1,U=!1,L&&clearTimeout(L),L=null},oe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ye=()=>{if(p!=="detached"||M.size>0||U)return;U=!0;let a=++G,g=Date.now()+wd,j=()=>{if(a!==G)return;if(M.size>0){ne();return}if(!(I.isRunning||I.depth>0||b.isRunning||b.depth>0)||Date.now()>=g){U=!1,L=setTimeout(oe,50),L.unref?.();return}L=setTimeout(j,250),L.unref?.()};j()},Y=new Set,V=new to(r),q=new Bn(r),ge=new Jt(r,i),$=new no(r),Z=new In(r),ue=new xn(r),se=new Pn(r,{claudePath:k,provider:x,timeoutMs:m,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let g of Y)io(g,a)}});q.beginAutomaticInitialization({writerVersion:st}).then(async a=>{a.state==="ready"?(await q.migrateLegacyEvals(),await q.migrateImprintSnapshot(),await q.syncImprintGraph(),await se.applyCanonicalEntries(await q.getCanonicalModelEntries()),x!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await Ee({provider:x,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let De=20,Je=300*1e3,Re=[];function Ue(){let a=Date.now()-Je;for(;Re.length>0&&(Re[0].completedAt<a||Re.length>De);)Re.shift()}let Ve=new Map;async function et(a){if(a.status!=="applied")return[];let g={version:1,updatedAt:Date.now(),cases:await q.getJournalEvalCases()},j=fr(a,g);if(j.length===0)return[];let v=await q.getEvalDependenciesForDecisions(a.decisionIds),T=a.threadId?await V.getThread(a.threadId):null,S=[...new Set((T?.messages??[]).flatMap(B=>(B.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])).map(B=>Go(B)?Ti(r,B):B))].map(B=>({kind:"source_file",value:B})),A=j.map(B=>{let z=[...new Map([...B.dependencies??[],...v,...S].map(W=>[`${W.kind}:${W.value}:${"subjectId"in W?W.subjectId??"":""}`,W])).values()],F=z.filter(W=>W.kind==="route"),D=z.flatMap(W=>W.kind==="model_path"&&W.value.startsWith("components.")?[W.value.slice(11).split(".")[0]]:[]),N=[...new Set(z.flatMap(W=>"subjectId"in W&&W.subjectId?[W.subjectId]:[]))],Q=F.length>0?F.map((W,ie)=>({id:`route-${ie+1}`,...W.value.includes("*")?{routePattern:W.value}:{route:W.value},components:D.map(ce=>({name:ce})),subjectIds:N})):[{id:D.length>0?`component-${D[0]}`:"current-page",components:D.map(W=>({name:W})),subjectIds:N}];return{...B,dependencies:z,scenarios:B.scenarios?.length?B.scenarios:Q}}),J=new Set(g.cases.map(B=>B.id));return await q.syncEvalSpecs(A),await se.attachGeneratedEvals(a.id,A.map(B=>({evalId:B.id,title:B.title,action:J.has(B.id)&&(a.evalProjections?.some(z=>z.evalId===B.id)||!a.generatedEvalIds?.includes(B.id))?"extended":"created"}))),A.map(B=>B.id)}async function at(a){let g=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",j=go(a.claim)||"The product satisfies the declared model constraint.",v={id:`eval-decision-${a.decisionId}`,title:g.charAt(0).toUpperCase()+g.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:[j],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-${g.replace(/\s+/g,"-")}`:"current-page",components:a.modelPath.startsWith("components.")?[{name:a.modelPath.slice(11).split(".")[0]}]:void 0}]};return await q.syncEvalSpecs([v]),v.id}let ft=null,Ft;I.addListener((a,g,j)=>{for(let v of Y)(!j||!v.sourceId||v.sourceId===j)&&io(v,a)}),b.addListener((a,g,j)=>{for(let v of Y)(!j||!v.sourceId||v.sourceId===j)&&io(v,a)}),b.setProcessor(async a=>{let g=a.provider??x;try{let j=await se.run({provider:g,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let v=await se.loadRuns(),T=j.runId?v.runs.find(A=>A.id===j.runId):void 0;if(j.success&&j.proposalId){let A=await se.findModelProposal(j.proposalId),J=await se.loadModel(),B=A?br(A,J):null;if(A&&B){let z=A.decisionIds.map(D=>({decisionId:D,status:"projected"}));await q.applyModelProjection({runId:A.runId??A.id,presentationJobId:A.presentationJobId,decisionIds:A.decisionIds,changes:B.map(D=>({path:D.path,value:D.value,decisionIds:D.decisionIds})),coverage:z});let F=await se.applySelectedModelProposal(A.id,B.map(D=>({path:D.path,value:D.value})),B.map(D=>({group:D.path[0]==="rules"||D.path[0]==="components"||D.path[0]==="tokens"?D.path[0]:"model",label:D.label??D.id,detail:D.rationale,path:D.path,value:D.value})),"automatic");F&&await et(F)}}let S=Sd(j,T);if(a.threadId&&(await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:g})),j.success)a.status="done",a.result=S,b.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue();else{if(a.status="error",a.error=j.error??"Projection failed",a.threadId){let A=`Model projection failed.
210
210
 
211
- ${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}catch(k){if(a.status==="cancelled")return;if(a.status="error",a.error=k instanceof Error?k.message:String(k),a.threadId){let m=`Model projection failed.
211
+ ${a.error}`;await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:A,error:a.error,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:A,error:a.error,model:a.model,provider:g})}b.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:g,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}catch(j){if(a.status==="cancelled")return;if(a.status="error",a.error=j instanceof Error?j.message:String(j),a.threadId){let v=`Model projection failed.
212
212
 
213
- ${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}),N.setProcessor(async a=>{let u=a,k=u._replyPrompt,m=u._replyText,P=u._replyImagePaths,w=a.provider??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
+ ${a.error}`;await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:g})}b.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:g,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}),I.setProcessor(async a=>{let g=a,j=g._replyPrompt,v=g._replyText,T=g._replyImagePaths,S=a.provider??x,A=!!(a.surfacedProposalIds?.length&&j),J=!!g._evalRemediation,B=!A&&!["run_eval","synthesize_evals","synthesize","project_model"].includes(a.kind??"");a.threadId&&v!==void 0&&await V.updateMessage(a.threadId,a.id,{queued:!1});let z;if(a.threadId){let de=await V.getThread(a.threadId);if(de){for(let pe=de.messages.length-1;pe>=0;pe--)if(de.messages[pe].sessionId){z=de.messages[pe].sessionId;break}}}(A||J)&&(z=void 0);let F;if(z&&j){if(F=v??j,T&&T.length>0){F+=`
214
214
 
215
- The developer attached reference images with their reply:`;for(let de of P)L+=`
216
- Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?L+=`
215
+ The developer attached reference images with their reply:`;for(let de of T)F+=`
216
+ Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?F+=`
217
217
 
218
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:L+=`
218
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+=`
219
219
 
220
- After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(F)L=en(a.feedback,a.imagePaths)+`
220
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(z)F=nn(a.feedback,a.imagePaths)+`
221
221
 
222
222
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
223
223
 
224
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(w!=="codex"?`
224
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
225
225
 
226
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!k&&a.threadId?await G.getThreadHistory(a.threadId):void 0,pe=k?null:await ie.loadModel();L=k??Kr(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:w,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}L+=qr(a.memoryReview),D&&(L+=Wn(a.imprintContext)),L+=`
226
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!j&&a.threadId?await V.getThreadHistory(a.threadId):void 0,pe=j?null:await se.loadModel();F=j??ti(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:S,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}F+=Qr(a.memoryReview),B&&(F+=Xn(a.imprintContext)),F+=`
227
227
 
228
- ${Vr}`;let C=bd(a.color,`[\u22B9 ${y}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${C} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${F?` (resuming: ${F.slice(0,8)})`:""}`);let K=new Jn(a.id),q=(de,pe)=>{if(de.type==="delta"&&"text"in de){let _e=K.push(de.text);_e.visibleText&&(N.accumulateText(pe,"response",_e.visibleText),N.broadcast({...de,text:_e.visibleText},pe,a.sourceId));for(let Ce of _e.orientations)N.broadcast({type:"orientation",jobId:pe,orientation:Ce},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&N.accumulateText(pe,"thinking",de.text);N.broadcast(de,pe,a.sourceId)},{process:se,result:ae}=w==="codex"?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:q}):w==="copilot"?ir(a.id,{prompt:L,projectRoot:r,resumeSessionId:F,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??I,onEvent:q}):mn(a.id,{prompt:L,projectRoot:r,maxTurns:c,maxBudgetUsd:l,allowedTools:j?["Read"]:h,claudePath:R,resumeSessionId:F,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:g,onEvent:q});N.setActiveProcess(a.id,se);let oe=await ae,be=K.finalize(oe.text),ve=be.visibleText,V=D?Hn(ve):{visibleText:ve,draft:void 0,error:void 0},Ie=V.visibleText;for(let de of be.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=Ie,oe.success){console.log(`${C} Iteration complete`),oe.fileEdits&&oe.fileEdits.length>0&&console.log(`${C} Captured ${oe.fileEdits.length} file edit(s): ${oe.fileEdits.map(z=>`${z.tool} ${z.file_path}`).join(", ")}`),oe.editEvents&&oe.editEvents.length>0&&console.log(`${C} Captured ${oe.editEvents.length} edit event(s): ${oe.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Qr(ve),pe=Yr(ve);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let z=new Set(a.annotationIds);pe.every(Ve=>z.has(Ve.annotationId))||(pe=pe.map((Ve,Ke)=>({...Ve,annotationId:a.annotationIds[Ke%a.annotationIds.length]})))}let _e=oe.fileEdits&&oe.fileEdits.length>0?oe.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):oe.toolsUsed,Ce=N.getBufferedEvents(a.id),et=Ce?gd(Ce.events,r):void 0,Re,Z=Wr(ve),fe=Hr(ve);if(fe)if(!(a.memoryReview?.packets.some(re=>re.proposalId===fe.proposalId)||a.surfacedProposalIds?.includes(fe.proposalId)))Re={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Re=await U.commitConversationalReview(fe)}catch(re){Re={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:re instanceof Error?re.message:String(re)}}let ke=[...(oe.fileEdits??[]).map(z=>z.file_path),...(oe.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],xe,gt=a.imprintContext?.pendingGroundingExplanationIds??[];if(V.draft?.decision==="none"&&he.recordNoop(V.draft.reason),a.threadId&&V.draft?.decision==="mutate"&&!fe&&!Z)try{xe=await he.capture(V.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await ie.loadModel(),pendingGroundingExplanationIds:gt}),xe&&await U.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(z=>console.warn(`${C} Canonical Imprint evidence linkage failed:`,z))}catch(z){console.warn(`${C} Continuous imprint update failed; the thread result remains available:`,z instanceof Error?z.message:String(z))}else V.error&&console.warn(`${C} Ignored invalid imprint block: ${V.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let z=await G.getThread(a.threadId),re=new Set(xe.changes.map(Ke=>Ke.explanationId)),Ve=z?hd(z.messages,re):void 0;if(Ve?.imprintSummary){let Ke=Ve.imprintSummary;await G.updateAssistantMessage(a.threadId,Ve.jobId,{imprintSummary:{...Ke,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Ke.additionalObservationCount??0)+1,coalescedTransactionIds:[...Ke.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let Ut=ms({question:de,resolutions:pe,changedFiles:ke,decisionRequired:!!Z,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),Q=et?.flatMap(z=>z.kind==="orientation"?[z.orientation]:[])??[];if(a.threadId){let z=j?Z?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Ie;await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:z,resolutions:!j&&pe.length>0?pe:void 0,question:j?void 0:de??void 0,sessionId:oe.sessionId,toolsUsed:j?void 0:_e,editEvents:!j&&oe.editEvents&&oe.editEvents.length>0?oe.editEvents:void 0,segments:!j&&et&&et.length>0?et:void 0,turn:{phase:"complete",orientation:Q,result:Ut},result:Ut,memoryReviewCard:Z??void 0,memoryReceipt:Re,imprintSummary:xe,model:a.model,provider:w})}if(a.threadId&&!fe&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let z=a.feedback.annotations.flatMap(re=>re.linkedSelector?[re.pathname?`${re.pathname}:${re.linkedSelector}`:re.linkedSelector]:[]);try{await U.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:m??(On(a.feedback)||"[request unavailable]"),responseSummary:de??Ie,outcome:de?"question_asked":pe.some(re=>re.status==="resolved")?"completed":"no_change",execution:{provider:w,model:a.model,sessionId:oe.sessionId},subjectHints:z,filePaths:[...(oe.fileEdits??[]).map(re=>re.file_path),...(oe.editEvents??[]).flatMap(re=>re.filePath?[re.filePath]:[])].map(re=>zo(re)?Is(r,re):re),resolutions:pe.map(re=>({status:re.status,summary:re.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(re=>re.id)})}catch(re){console.warn(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,re instanceof Error?re.message:String(re))}}if(Re?.status==="committed"&&Re.decisionId&&w!=="copilot"&&await je({provider:w,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Re.decisionId}`}),a.kind==="run_eval"&&Ie&&a.evalId&&a.evalRunId){let z=await U.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(z&&re){let Ve=cr(ve,z.assertions),Ke=Date.now(),Vs={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:re,provider:w,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:Ps(r),rawResponse:ve,scopeFingerprint:a._evalScopeFingerprint,...Ve};await U.recordEvalVerification(z,Vs),console.log(`${C} Eval run: ${z.title} \u2192 ${Ve.status}`)}}de&&(console.log(`${C} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${X.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),N.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:de,annotationIds:a.annotationIds},a.id,a.sourceId));let me=Zr(ve);me.length>0&&(console.log(`${C} Novel pattern(s): ${me.map(z=>`${z.category}/${z.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),N.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:Ie,threadId:a.threadId,annotationIds:a.annotationIds,result:Ut},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${C} Error: ${oe.error}`),a.status="error",a.error=oe.error,a.threadId&&await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:oe.error||"Unknown error",model:a.model,provider:w}),N.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:oe.error||"Unknown error",provider:w,model:a.model,recoverable:oe.recoverableError,code:oe.errorCode},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:oe.error,threadId:a.threadId,annotationIds:a.annotationIds});Ue()});let Ft=sd(async(a,u)=>{if(wd(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let k=a.url||"/",m=k.split("?")[0],P=new URL(k,`http://127.0.0.1:${y}`),w=P.pathname,j=Id(a,P);if(j&&j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Zn(r)});return}if(a.headers.origin){if(!Es(a.headers.origin)){E(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Zn(r)});return}}try{if(a.method==="POST"&&w==="/send")await Ae(a,u);else if(a.method==="GET"&&w==="/events")at(a,u);else if(a.method==="GET"&&w==="/status")await ct(a,u,j);else if(a.method==="GET"&&w==="/ui-preferences")await ro(u);else if(a.method==="PATCH"&&w==="/ui-preferences")await so(a,u);else if(a.method==="PATCH"&&w==="/config")await ft(a,u);else if(a.method==="POST"&&w==="/leases"){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await ze(a),D=typeof $.leaseId=="string"?$.leaseId.trim():"",F=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){E(u,400,{error:"A valid leaseId is required."});return}te();let L=B.acquire(D,F);E(u,201,{ok:!0,lease:L,ttlMs:bs})}catch{E(u,400,{error:"Invalid lease request."})}}else if(w.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(w.slice(8))}catch{E(u,400,{error:"Invalid lease id."});return}if(!$){E(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat($);if(!D){E(u,404,{error:"Lease not found."});return}E(u,200,{ok:!0,lease:D})}else{let D=B.release($);E(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&ge()}}else if(a.method==="POST"&&w==="/shutdown"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0}),setTimeout(ne,100)}else if(a.method==="POST"&&w==="/restart"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of X)try{$.res.end()}catch{}Ft.close(()=>{ws(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&w==="/capabilities")E(u,200,{providers:f});else if(w.startsWith("/imprint/"))await it(a,u,w);else if(w.startsWith("/memory/"))await we(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await Ds(a,u);else if(a.method==="POST"&&w==="/reply")await Ze(a,u);else if(a.method==="POST"&&w==="/cancel")zt(a,u);else if(a.method==="POST"&&w==="/materialize")E(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&w==="/materialization-runs")E(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&w==="/projection-runs"){let $=await ie.loadRuns();E(u,200,$)}else if(a.method==="GET"&&w==="/projection/proposals"){let $=await ie.loadModelProposals();E(u,200,$)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply-selected")){let $=w.slice(22,-15);await dt($,a,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply")){let $=w.slice(22,-6);await Ne($,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/dismiss")){let $=w.slice(22,-8);await Pt($,a,u)}else if(w.startsWith("/model/proposals/"))E(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await Js(a,u);else if(a.method==="DELETE"&&w==="/model/component")await Ns(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Bs(a,u);else if(a.method==="DELETE"&&w==="/model/token")await Ls(a,u);else if(a.method==="POST"&&w==="/model/consolidate")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/model/synthesize")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/evals/synthesize")E(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&w==="/evals"){let $=await ie.loadModel(),D=await Promise.all((await U.getJournalEvalCases()).map(async C=>{let O=await Rs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),F=Ps(r),L=(await U.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===F);E(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:L,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&w.startsWith("/evals/")&&w.endsWith("/run")){let $=w.slice(7,-4);await io($,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await ln(w.slice(7),a,u);else if(a.method==="GET"&&w==="/model"){let $=await ie.loadModel();E(u,200,{model:$})}else if(a.method==="GET"&&w.startsWith("/jobs/")&&w.endsWith("/events")){let $=w.slice(6,w.length-7),D=parseInt(P.searchParams.get("afterSeq")??"-1",10),F=N.getBufferedEvents($,isNaN(D)?-1:D);F?E(u,200,F):E(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await qs(m.slice(7),u);else if(a.method==="GET"&&w==="/threads/recent"){let $=Math.min(Math.max(parseInt(P.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent($);E(u,200,D)}else if(a.method==="GET"&&w.startsWith("/decision/")){let $=w.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))E(u,400,{error:"Invalid decision id"});else{let D=await G.getThread($),F=[...D?.messages??[]].reverse().find(L=>L.annotationSnapshot);if(D&&F?.annotationSnapshot){let L=[...D.messages].reverse().find(C=>C.resolutions?.length);E(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 Y.loadDecision($);L?E(u,200,{decision:L,authority:"legacy_archive"}):E(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let $=w.slice(8);await Hs($,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let $=w.slice(8);await Ws($,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?Fs(a,u):a.method==="GET"&&w==="/canvas/manifest"?await zs(u):a.method==="GET"&&w==="/canvas/app.mjs"?await Us(u):E(u,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),E(u,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function we(a,u,k){try{if(a.method==="GET"&&k==="/memory/status"){E(u,200,await U.status());return}if(a.method==="GET"&&k==="/memory/diagnostics"){E(u,200,await U.diagnostics());return}if(a.method==="GET"&&k==="/memory/model-view"){E(u,200,await U.getModelView());return}if(a.method==="POST"&&k==="/memory/constraints"){let m=await ze(a),P=typeof m.reactComponent=="string"?m.reactComponent.trim():"",w=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",$=await U.getModelView(),D=P?$.entries.filter(C=>C.key===`components.${P}`||C.key.startsWith(`components.${P}.`)):[],F=(C,O)=>{if(!O)return!1;if(!C.includes("*"))return C===O;let K=C.split("*").map(q=>q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${K}$`).test(O)},L=(await U.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(q=>q.kind==="route"&&F(q.value,w)||q.kind==="subject"&&q.value===j),K=(C.scenarios??[]).some(q=>!!P&&(q.components??[]).some(se=>se.name===P||se.exportName===P)||!!w&&!!q.route&&q.route===w||!!w&&!!q.routePattern&&F(q.routePattern,w));return O||K}).map(C=>({id:C.id,title:C.title,verificationState:C.verificationState,assertions:C.assertions}));E(u,200,{modelEntries:D,evals:L});return}if(a.method==="POST"&&k==="/memory/conversation-action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!P||!w||!["accept","edit_and_accept","reject","defer"].includes(j)){E(u,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await G.getThread(P),D=$?.messages.find(ae=>ae.memoryReviewCard?.proposalId===w)?.memoryReviewCard;if(!$||!D){E(u,409,{error:"This decision review card is not available in the thread."});return}let F=await ie.findModelProposalsByThread(P),L=(await Promise.all(F.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(oe=>U.findPendingProposalForLegacyDecision(oe)))).some(oe=>oe?.proposalId===w)})))).find(ae=>ae.matches)?.proposal,C={proposalId:w,action:j,kind:D.kind,claim:j==="edit_and_accept"&&typeof m.claim=="string"?m.claim.trim():void 0,reason:j==="defer"?void 0:`The owner explicitly chose ${j.replaceAll("_"," ")} from the decision review card.`,taskContext:j==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:j==="defer"?["different_action","owner_request"]:void 0};if(C.action==="edit_and_accept"&&!C.claim){E(u,400,{error:"Edited decision wording is required."});return}let O=await U.commitConversationalReview(C),K=`memory-${ut().slice(0,8)}`,q=j==="accept"?"> Accepted decision":j==="edit_and_accept"?"> Edited and accepted decision":j==="reject"?"> Rejected decision":"> Deferred decision";await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:q}),await G.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:K,responseText:"",memoryReceipt:O,provider:St(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&L&&await ie.dismissModelProposal(L.id);let se=St(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&se!=="copilot"&&await je({provider:se,model:typeof m.model=="string"?m.model:void 0,agentSettings:yt(m),threadId:P,reason:`Project accepted decision ${O.decisionId}`}),E(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&k==="/memory/analyze"){let m=await ze(a),P=await U.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),w=Object.fromEntries([...new Set(P.issues.map(j=>j.code))].map(j=>[j,P.issues.filter($=>$.code===j).length]));E(u,200,{...P,issues:void 0,issueCounts:w});return}if(a.method==="POST"&&k==="/memory/review"){let m=await ze(a),P=await U.review(Do(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/context"){let m=await ze(a),P=await U.contextualize(Do(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/initialize"){let m=await ze(a),P=await U.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:rt});E(u,201,{status:P.status,report:{source:P.report.source,imported:P.report.imported,unresolvedAcceptance:P.report.unresolvedAcceptance,deferredModelEntries:P.report.deferredModelEntries,proofCases:P.report.proofCases,schemaIssues:P.report.schemaIssues}});return}if(a.method==="POST"&&k==="/memory/plan"){let m=await ze(a),P=await U.planReview(Oo(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,P.result.ok?200:422,P);return}if(a.method==="POST"&&k==="/memory/commit"){let m=await ze(a),P=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},w=await U.commitReview(Oo(m.command),{transactionId:typeof P.transactionId=="string"?P.transactionId:"",committedAt:typeof P.committedAt=="string"?P.committedAt:""});E(u,200,{status:await U.status(),journal:w.report});return}if(a.method==="POST"&&k==="/memory/recover"){let m=await ze(a),P=await U.recover(m.confirm===!0);E(u,200,{status:await U.status(),journal:P.report});return}E(u,404,{error:"Memory endpoint not found."})}catch(m){let P=m instanceof Error?m.message:String(m),w=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(P),j=/required|invalid|unsupported|expected|must be|confirmation/i.test(P);if(w||j){E(u,w?409:400,{error:P});return}throw m}}async function it(a,u,k){if(a.method==="GET"&&k==="/imprint/status"){let[m,P]=await Promise.all([he.store.load(),G.load()]),w=[...new Set(Object.values(P.threads).flatMap(j=>eo(j.messages)))];E(u,200,{state:"ready",head:m.graph.head,updatedAt:m.graph.updatedAt,explanationCount:m.graph.explanations.filter(j=>j.state!=="retired").length,concreteCount:m.graph.concrete.length,relationCount:m.graph.relations.length,pendingGroundingCount:w.length,recoveredTransactions:m.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&k==="/imprint/action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!P||!w||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(j)){E(u,400,{error:"A valid thread, imprint update, and action are required."});return}let D=await G.getThread(P),F=[...D?.messages??[]].reverse().find(se=>se.role==="assistant"&&se.imprintSummary?.transactionId===w),L=F?.imprintSummary;if(!D||!F||!L){E(u,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){E(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${ut().slice(0,8)}`;await he.applyGroundingAction({summary:L,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:P,jobId:C}),await U.recordImprintEvidence({summary:L,action:j,threadId:P,jobId:C}).catch(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));let O=Jt(F.result,!!F.question),K=F.turn?{...F.turn,result:Jt(F.turn.result,!!F.question)}:void 0;await G.updateAssistantMessage(P,F.jobId,{imprintSummary:{...L,resolvedAction:j},...O?{result:O}:{},...K?{turn:K}:{}});let q={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:C,replyToQuestion:q[j]}),E(u,200,{ok:!0,action:j});return}E(u,404,{error:"Imprint endpoint not found."})}async function Ae(a,u){let{screenshot:k,feedback:m,color:P,provider:w,model:j,reasoningEffort:$,serviceTier:D,sourceId:F,pastedImages:L,pageScreenshots:C}=await Dn(a),O;try{O=JSON.parse(m)}catch{E(u,400,{error:"Invalid feedback JSON"});return}let K=ut().slice(0,8),q={};if(C.length>0)for(let Z of C){let fe=encodeURIComponent(Z.pathname),ke=Me(d,`screenshot-${K}-${fe}.webp`);await dn(ke,Z.data),q[Z.pathname]=ke}let se=Me(d,`screenshot-${K}.webp`);await dn(se,k);let ae={};if(L.length>0)for(let Z of L){let fe=Me(d,`pasted-${K}-${Z.annotationId}-${Z.index}.webp`);await dn(fe,Z.data),ae[Z.annotationId]||(ae[Z.annotationId]=[]),ae[Z.annotationId].push(fe)}let oe=O.annotations.map(Z=>Z.linkedSelector?Z.pathname?`${Z.pathname}:${Z.linkedSelector}`:Z.linkedSelector:null).filter(Z=>!!Z),be;if(oe.length>0){let Z=await G.findContinuationThread(oe);Z?(be=Z.id,await G.addElementIdentifiers(be,oe)):be=(await G.createThread(K,oe)).id}else be=(await G.createThread(K,[])).id;let ve=O.annotations.map(Z=>Z.id),V=Object.keys(q).length>0,Ie=await Ur(U,O,oe,Z=>console.warn(`[\u22B9 ${y}:${K}] Contextual memory unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))),de=await he.contextualize({text:On(O),subjectHints:[...oe,...O.annotations.flatMap(Z=>[Z.pathname,Z.elements?.[0]?.reactComponent].filter(fe=>!!fe))],pendingGroundingExplanationIds:eo((await G.getThread(be))?.messages??[])}).catch(Z=>{console.warn(`[\u22B9 ${y}:${K}] Imprint context unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))}),pe={id:K,status:"queued",screenshotPath:se,feedback:O,createdAt:Date.now(),color:P,threadId:be,annotationIds:ve,provider:St(w),model:j||void 0,agentSettings:yt({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:F||void 0,...V?{screenshotPaths:q}:{},...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}},_e=new Set(O.annotations.map(Z=>Z.pathname).filter(Boolean)),Ce;if(_e.size>1){let Z=new Map;for(let fe of O.annotations){let ke=fe.pathname||"(unknown)";Z.has(ke)||Z.set(ke,[]),Z.get(ke).push(fe.instruction||Ss({...O,annotations:[fe]}))}Ce=[...Z.entries()].map(([fe,ke])=>`\`${fe}\`
228
+ ${ei}`;let D=Td(a.color,`[\u22B9 ${y}:${a.id}]`),N=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${D} Reviewing ${N} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${z?` (resuming: ${z.slice(0,8)})`:""}`);let Q=new zn(a.id),W=(de,pe)=>{if(de.type==="delta"&&"text"in de){let _e=Q.push(de.text);_e.visibleText&&(I.accumulateText(pe,"response",_e.visibleText),I.broadcast({...de,text:_e.visibleText},pe,a.sourceId));for(let Ce of _e.orientations)I.broadcast({type:"orientation",jobId:pe,orientation:Ce},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&I.accumulateText(pe,"thinking",de.text);I.broadcast(de,pe,a.sourceId)},{process:ie,result:ce}=S==="codex"?vn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:z,model:a.model,sandboxMode:A?"read-only":void 0,configOverrides:hn(a.agentSettings),onEvent:W}):S==="copilot"?pr(a.id,{prompt:F,projectRoot:r,resumeSessionId:z,model:a.model,timeoutMs:m,copilotPath:h.copilot?.path??P,onEvent:W}):gn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:A?["Read"]:w,claudePath:k,resumeSessionId:z,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:m,onEvent:W});I.setActiveProcess(a.id,ie);let te=await ce,be=Q.finalize(te.text),Ie=be.visibleText,ve=B?Qn(Ie):{visibleText:Ie,draft:void 0,error:void 0},K=ve.visibleText;for(let de of be.orientations)I.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=K,te.success){console.log(`${D} Iteration complete`),te.fileEdits&&te.fileEdits.length>0&&console.log(`${D} Captured ${te.fileEdits.length} file edit(s): ${te.fileEdits.map(H=>`${H.tool} ${H.file_path}`).join(", ")}`),te.editEvents&&te.editEvents.length>0&&console.log(`${D} Captured ${te.editEvents.length} edit event(s): ${te.editEvents.map(H=>`${H.operation} ${H.filePath}`).join(", ")}`),a.status="done";let de=ni(Ie),pe=ri(Ie);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let H=new Set(a.annotationIds);pe.every(Ke=>H.has(Ke.annotationId))||(pe=pe.map((Ke,Qe)=>({...Ke,annotationId:a.annotationIds[Qe%a.annotationIds.length]})))}let _e=te.fileEdits&&te.fileEdits.length>0?te.fileEdits.map(H=>`${H.tool} ${H.file_path.split("/").pop()}`):te.toolsUsed,Ce=I.getBufferedEvents(a.id),nt=Ce?xd(Ce.events,r):void 0,Pe,ee=Yr(Ie),he=Xr(Ie);if(he)if(!(a.memoryReview?.packets.some(re=>re.proposalId===he.proposalId)||a.surfacedProposalIds?.includes(he.proposalId)))Pe={status:"rejected",action:he.action,proposalId:he.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Pe=await q.commitConversationalReview(he)}catch(re){Pe={status:"rejected",action:he.action,proposalId:he.proposalId,message:re instanceof Error?re.message:String(re)}}let ke=[...(te.fileEdits??[]).map(H=>H.file_path),...(te.editEvents??[]).flatMap(H=>H.filePath?[H.filePath]:[])],xe,yt=a.imprintContext?.pendingGroundingExplanationIds??[];if(ve.draft?.decision==="none"&&ge.recordNoop(ve.draft.reason),a.threadId&&ve.draft?.decision==="mutate"&&!he&&!ee)try{xe=await ge.capture(ve.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:yt}),xe&&await q.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(H=>console.warn(`${D} Canonical Imprint evidence linkage failed:`,H))}catch(H){console.warn(`${D} Continuous imprint update failed; the thread result remains available:`,H instanceof Error?H.message:String(H))}else ve.error&&console.warn(`${D} Ignored invalid imprint block: ${ve.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let H=await V.getThread(a.threadId),re=new Set(xe.changes.map(Qe=>Qe.explanationId)),Ke=H?bd(H.messages,re):void 0;if(Ke?.imprintSummary){let Qe=Ke.imprintSummary;await V.updateAssistantMessage(a.threadId,Ke.jobId,{imprintSummary:{...Qe,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Qe.additionalObservationCount??0)+1,coalescedTransactionIds:[...Qe.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let qt=wi({question:de,resolutions:pe,changedFiles:ke,decisionRequired:!!ee,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),X=nt?.flatMap(H=>H.kind==="orientation"?[H.orientation]:[])??[];if(a.threadId){let H=A?ee?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":K;await V.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:H,resolutions:!A&&pe.length>0?pe:void 0,question:A?void 0:de??void 0,sessionId:te.sessionId,toolsUsed:A?void 0:_e,editEvents:!A&&te.editEvents&&te.editEvents.length>0?te.editEvents:void 0,segments:!A&&nt&&nt.length>0?nt:void 0,turn:{phase:"complete",orientation:X,result:qt},result:qt,memoryReviewCard:ee??void 0,memoryReceipt:Pe,imprintSummary:xe,model:a.model,provider:S})}if(a.threadId&&!he&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let H=a.feedback.annotations.flatMap(re=>re.linkedSelector?[re.pathname?`${re.pathname}:${re.linkedSelector}`:re.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(Ln(a.feedback)||"[request unavailable]"),responseSummary:de??K,outcome:de?"question_asked":pe.some(re=>re.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:te.sessionId},subjectHints:H,filePaths:[...(te.fileEdits??[]).map(re=>re.file_path),...(te.editEvents??[]).flatMap(re=>re.filePath?[re.filePath]:[])].map(re=>Go(re)?Ti(r,re):re),resolutions:pe.map(re=>({status:re.status,summary:re.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(re=>re.id)})}catch(re){console.warn(`${D} Canonical memory capture failed; iteration remains available in legacy history:`,re instanceof Error?re.message:String(re))}}if(Pe?.status==="committed"&&Pe.decisionId&&S!=="copilot"&&await Ee({provider:S,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"&&K&&a.evalId&&a.evalRunId){let H=await q.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(H&&re){let Ke=mr(Ie,H.assertions),Qe=Date.now(),ts={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Qe,durationMs:Qe-a.createdAt,scope:re,provider:S,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:Mi(r),rawResponse:Ie,scopeFingerprint:a._evalScopeFingerprint,...Ke};await q.recordEvalVerification(H,ts),console.log(`${D} Eval run: ${H.title} \u2192 ${Ke.status}`)}}de&&(console.log(`${D} \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"})`),I.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:de,annotationIds:a.annotationIds},a.id,a.sourceId));let me=ii(Ie);me.length>0&&(console.log(`${D} Novel pattern(s): ${me.map(H=>`${H.category}/${H.element}`).join(", ")}`),I.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),I.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:K,threadId:a.threadId,annotationIds:a.annotationIds,result:qt},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${D} Error: ${te.error}`),a.status="error",a.error=te.error,a.threadId&&await V.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:te.error||"Unknown error",model:a.model,provider:S}),I.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:te.error||"Unknown error",provider:S,model:a.model,recoverable:te.recoverableError,code:te.errorCode},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:te.error,threadId:a.threadId,annotationIds:a.annotationIds});Ue()});let zt=pd(async(a,g)=>{if(Pd(a,g),a.method==="OPTIONS"){g.writeHead(204),g.end();return}let j=a.url||"/",v=j.split("?")[0],T=new URL(j,`http://127.0.0.1:${y}`),S=T.pathname,A=kd(a,T);if(A&&A!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:A,projectName:ro(r)});return}if(a.headers.origin){if(!Di(a.headers.origin)){_(g,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(A!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:A,projectName:ro(r)});return}}try{if(a.method==="POST"&&S==="/send")await Me(a,g);else if(a.method==="GET"&&S==="/events")dt(a,g);else if(a.method==="GET"&&S==="/status")await lt(a,g,A);else if(a.method==="GET"&&S==="/ui-preferences")await co(g);else if(a.method==="PATCH"&&S==="/ui-preferences")await lo(a,g);else if(a.method==="PATCH"&&S==="/config")await ht(a,g);else if(a.method==="POST"&&S==="/leases"){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}try{let J=await ze(a),B=typeof J.leaseId=="string"?J.leaseId.trim():"",z=typeof J.ownerPid=="number"&&Number.isInteger(J.ownerPid)&&J.ownerPid>0?J.ownerPid:void 0;if(!B||B.length>128){_(g,400,{error:"A valid leaseId is required."});return}ne();let F=M.acquire(B,z);_(g,201,{ok:!0,lease:F,ttlMs:ji})}catch{_(g,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(S.slice(8))}catch{_(g,400,{error:"Invalid lease id."});return}if(!J){_(g,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let B=M.heartbeat(J);if(!B){_(g,404,{error:"Lease not found."});return}_(g,200,{ok:!0,lease:B})}else{let B=M.release(J);_(g,B.found?200:404,{ok:B.found}),B.becameEmpty&&ye()}}else if(a.method==="POST"&&S==="/shutdown"){if(p!=="detached"){_(g,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}_(g,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&S==="/restart"){if(p!=="detached"){_(g,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}_(g,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of Y)try{J.res.end()}catch{}zt.close(()=>{ki(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"&&S==="/capabilities")_(g,200,{providers:h});else if(S.startsWith("/imprint/"))await ct(a,g,S);else if(S.startsWith("/memory/"))await we(a,g,S);else if(a.method==="POST"&&S==="/mcp/install")await Ui(a,g);else if(a.method==="POST"&&S==="/reply")await tt(a,g);else if(a.method==="POST"&&S==="/cancel")Ut(a,g);else if(a.method==="POST"&&S==="/materialize")_(g,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(g,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let J=await se.loadRuns();_(g,200,J)}else if(a.method==="GET"&&S==="/projection/proposals"){let J=await se.loadModelProposals();_(g,200,J)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let J=S.slice(22,-15);await pt(J,a,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let J=S.slice(22,-6);await Ne(J,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let J=S.slice(22,-8);await Pt(J,a,g)}else if(S.startsWith("/model/proposals/"))_(g,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await qi(a,g);else if(a.method==="DELETE"&&S==="/model/component")await Hi(a,g);else if(a.method==="PATCH"&&S==="/model/token")await Wi(a,g);else if(a.method==="DELETE"&&S==="/model/token")await Gi(a,g);else if(a.method==="POST"&&S==="/model/consolidate")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/evals/synthesize")_(g,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&S==="/evals"){let J=await se.loadModel(),B=await Promise.all((await q.getJournalEvalCases()).map(async D=>{let N=await _i(r,D,J);return D.verificationState==="passing"&&(!D.verifiedScopeFingerprint||!N||D.verifiedScopeFingerprint!==N)?{...D,verificationState:"stale"}:D})),z=Mi(r),F=(await q.getJournalEvalRuns()).filter(D=>!D.codeFingerprint||D.codeFingerprint===z);_(g,200,{version:1,updatedAt:Date.now(),cases:B,runs:F,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&S.startsWith("/evals/")&&S.endsWith("/run")){let J=S.slice(7,-4);await po(J,a,g)}else if(a.method==="PATCH"&&S.startsWith("/evals/"))await mn(S.slice(7),a,g);else if(a.method==="GET"&&S==="/model"){let J=await se.loadModel();_(g,200,{model:J})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let J=S.slice(6,S.length-7),B=parseInt(T.searchParams.get("afterSeq")??"-1",10),z=I.getBufferedEvents(J,isNaN(B)?-1:B);z?_(g,200,z):_(g,404,{error:"Unknown job"})}else if(a.method==="GET"&&v.startsWith("/files/"))await Xi(v.slice(7),g);else if(a.method==="GET"&&S==="/threads/recent"){let J=Math.min(Math.max(parseInt(T.searchParams.get("limit")??"5",10)||5,1),20),B=await V.listRecent(J);_(g,200,B)}else if(a.method==="GET"&&S.startsWith("/decision/")){let J=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(J))_(g,400,{error:"Invalid decision id"});else{let B=await V.getThread(J),z=[...B?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(B&&z?.annotationSnapshot){let F=[...B.messages].reverse().find(D=>D.resolutions?.length);_(g,200,{decision:{id:B.id,createdAt:z.timestamp,url:z.annotationSnapshot.url,viewport:z.annotationSnapshot.viewport,color:z.annotationSnapshot.color,annotations:z.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await Z.loadDecision(J);F?_(g,200,{decision:F,authority:"legacy_archive"}):_(g,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let J=S.slice(8);await Yi(J,g)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let J=S.slice(8);await Zi(J,g)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?Vi(a,g):a.method==="GET"&&S==="/canvas/manifest"?await Ki(g):a.method==="GET"&&S==="/canvas/app.mjs"?await Qi(g):_(g,404,{error:"Not found"})}catch(J){console.error("[Bridge] Request error:",J),_(g,500,{error:J instanceof Error?J.message:"Internal error"})}});async function we(a,g,j){try{if(a.method==="GET"&&j==="/memory/status"){_(g,200,await q.status());return}if(a.method==="GET"&&j==="/memory/diagnostics"){_(g,200,await q.diagnostics());return}if(a.method==="GET"&&j==="/memory/model-view"){_(g,200,await q.getModelView());return}if(a.method==="GET"&&j==="/memory/imprint-view"){let v=await V.load(),T=[...new Set(Object.values(v.threads).flatMap(S=>un(S.messages)))];_(g,200,await q.getImprintView(T));return}if(a.method==="POST"&&j==="/memory/constraints"){let v=await ze(a),T=typeof v.reactComponent=="string"?v.reactComponent.trim():"",S=typeof v.pathname=="string"?v.pathname.trim():"",A=typeof v.selector=="string"?v.selector.trim():"",J=await q.getModelView(),B=T?J.entries.filter(D=>D.key===`components.${T}`||D.key.startsWith(`components.${T}.`)):[],z=(D,N)=>{if(!N)return!1;if(!D.includes("*"))return D===N;let Q=D.split("*").map(W=>W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`).test(N)},F=(await q.getJournalEvalCases()).filter(D=>{if(D.status==="rejected")return!1;let N=(D.dependencies??[]).some(W=>W.kind==="route"&&z(W.value,S)||W.kind==="subject"&&W.value===A),Q=(D.scenarios??[]).some(W=>!!T&&(W.components??[]).some(ie=>ie.name===T||ie.exportName===T)||!!S&&!!W.route&&W.route===S||!!S&&!!W.routePattern&&z(W.routePattern,S));return N||Q}).map(D=>({id:D.id,title:D.title,verificationState:D.verificationState,assertions:D.assertions}));_(g,200,{modelEntries:B,evals:F});return}if(a.method==="POST"&&j==="/memory/conversation-action"){let v=await ze(a),T=typeof v.threadId=="string"?v.threadId:"",S=typeof v.proposalId=="string"?v.proposalId:"",A=String(v.action);if(!T||!S||!["accept","edit_and_accept","reject","defer"].includes(A)){_(g,400,{error:"A valid thread, proposal, and review action are required."});return}let J=await V.getThread(T),B=J?.messages.find(ce=>ce.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!J||!B){_(g,409,{error:"This decision review card is not available in the thread."});return}let z=await se.findModelProposalsByThread(T),F=(await Promise.all(z.map(async ce=>({proposal:ce,matches:(await Promise.all(ce.decisionIds.map(te=>q.findPendingProposalForLegacyDecision(te)))).some(te=>te?.proposalId===S)})))).find(ce=>ce.matches)?.proposal,D={proposalId:S,action:A,kind:B.kind,claim:A==="edit_and_accept"&&typeof v.claim=="string"?v.claim.trim():void 0,reason:A==="defer"?void 0:`The owner explicitly chose ${A.replaceAll("_"," ")} from the decision review card.`,taskContext:A==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:A==="defer"?["different_action","owner_request"]:void 0};if(D.action==="edit_and_accept"&&!D.claim){_(g,400,{error:"Edited decision wording is required."});return}let N=await q.commitConversationalReview(D),Q=`memory-${mt().slice(0,8)}`,W=A==="accept"?"> Accepted decision":A==="edit_and_accept"?"> Edited and accepted decision":A==="reject"?"> Rejected decision":"> Deferred decision";await V.appendMessage(T,{role:"human",timestamp:Date.now(),jobId:Q,replyToQuestion:W}),await V.appendMessage(T,{role:"assistant",timestamp:Date.now(),jobId:Q,responseText:"",memoryReceipt:N,provider:Rt(typeof v.provider=="string"?v.provider:void 0),model:typeof v.model=="string"?v.model:void 0}),N.status==="committed"&&F&&await se.dismissModelProposal(F.id);let ie=Rt(typeof v.provider=="string"?v.provider:void 0);N.status==="committed"&&N.decisionId&&ie!=="copilot"&&await Ee({provider:ie,model:typeof v.model=="string"?v.model:void 0,agentSettings:vt(v),threadId:T,reason:`Project accepted decision ${N.decisionId}`}),_(g,N.status==="committed"?200:409,{receipt:N});return}if(a.method==="POST"&&j==="/memory/analyze"){let v=await ze(a),T=await q.analyzeLegacy({projectKey:typeof v.projectKey=="string"?v.projectKey:void 0}),S=Object.fromEntries([...new Set(T.issues.map(A=>A.code))].map(A=>[A,T.issues.filter(J=>J.code===A).length]));_(g,200,{...T,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&j==="/memory/review"){let v=await ze(a),T=await q.review(Fo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,T);return}if(a.method==="POST"&&j==="/memory/context"){let v=await ze(a),T=await q.contextualize(Fo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,T);return}if(a.method==="POST"&&j==="/memory/initialize"){let v=await ze(a),T=await q.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:st});_(g,201,{status:T.status,report:{source:T.report.source,imported:T.report.imported,unresolvedAcceptance:T.report.unresolvedAcceptance,deferredModelEntries:T.report.deferredModelEntries,proofCases:T.report.proofCases,schemaIssues:T.report.schemaIssues}});return}if(a.method==="POST"&&j==="/memory/plan"){let v=await ze(a),T=await q.planReview(Lo(v.command),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,T.result.ok?200:422,T);return}if(a.method==="POST"&&j==="/memory/commit"){let v=await ze(a),T=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},S=await q.commitReview(Lo(v.command),{transactionId:typeof T.transactionId=="string"?T.transactionId:"",committedAt:typeof T.committedAt=="string"?T.committedAt:""});_(g,200,{status:await q.status(),journal:S.report});return}if(a.method==="POST"&&j==="/memory/recover"){let v=await ze(a),T=await q.recover(v.confirm===!0);_(g,200,{status:await q.status(),journal:T.report});return}_(g,404,{error:"Memory endpoint not found."})}catch(v){let T=v instanceof Error?v.message:String(v),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(T),A=/required|invalid|unsupported|expected|must be|confirmation/i.test(T);if(S||A){_(g,S?409:400,{error:T});return}throw v}}async function ct(a,g,j){if(a.method==="GET"&&j==="/imprint/status"){let[v,T]=await Promise.all([ge.store.load(),V.load()]),S=[...new Set(Object.values(T.threads).flatMap(A=>un(A.messages)))].filter(A=>v.graph.explanations.some(J=>J.id===A&&J.state==="testing"));_(g,200,{state:"ready",head:v.graph.head,updatedAt:v.graph.updatedAt,explanationCount:v.graph.explanations.filter(A=>A.state!=="retired").length,concreteCount:v.graph.concrete.length,relationCount:v.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:v.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&j==="/imprint/action"){let v=await ze(a),T=typeof v.threadId=="string"?v.threadId:"",S=typeof v.transactionId=="string"?v.transactionId:"",A=String(v.action);if(!T||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(A)){_(g,400,{error:"A valid thread, imprint update, and action are required."});return}let B=await V.getThread(T),z=[...B?.messages??[]].reverse().find(ie=>ie.role==="assistant"&&ie.imprintSummary?.transactionId===S),F=z?.imprintSummary;if(!B||!z||!F){_(g,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){_(g,409,{error:"This imprint summary has already been resolved."});return}let D=`imprint-${mt().slice(0,8)}`;await ge.applyGroundingAction({summary:F,action:A,value:typeof v.value=="string"?v.value:void 0,threadId:T,jobId:D}),await q.recordImprintEvidence({summary:F,action:A,threadId:T,jobId:D}).catch(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let N=Nt(z.result,!!z.question),Q=z.turn?{...z.turn,result:Nt(z.turn.result,!!z.question)}:void 0;await V.updateAssistantMessage(T,z.jobId,{imprintSummary:{...F,resolvedAction:A},...N?{result:N}:{},...Q?{turn:Q}:{}});let W={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 V.appendMessage(T,{role:"human",timestamp:Date.now(),jobId:D,replyToQuestion:W[A]}),_(g,200,{ok:!0,action:A});return}_(g,404,{error:"Imprint endpoint not found."})}async function Me(a,g){let{screenshot:j,feedback:v,color:T,provider:S,model:A,reasoningEffort:J,serviceTier:B,sourceId:z,pastedImages:F,pageScreenshots:D}=await Fn(a),N;try{N=JSON.parse(v)}catch{_(g,400,{error:"Invalid feedback JSON"});return}let Q=mt().slice(0,8),W={};if(D.length>0)for(let ee of D){let he=encodeURIComponent(ee.pathname),ke=Ae(c,`screenshot-${Q}-${he}.webp`);await pn(ke,ee.data),W[ee.pathname]=ke}let ie=Ae(c,`screenshot-${Q}.webp`);await pn(ie,j);let ce={};if(F.length>0)for(let ee of F){let he=Ae(c,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await pn(he,ee.data),ce[ee.annotationId]||(ce[ee.annotationId]=[]),ce[ee.annotationId].push(he)}let te=N.annotations.map(ee=>ee.linkedSelector?ee.pathname?`${ee.pathname}:${ee.linkedSelector}`:ee.linkedSelector:null).filter(ee=>!!ee),be;if(te.length>0){let ee=await V.findContinuationThread(te);ee?(be=ee.id,await V.addElementIdentifiers(be,te)):be=(await V.createThread(Q,te)).id}else be=(await V.createThread(Q,[])).id;let Ie=N.annotations.map(ee=>ee.id),ve=Object.keys(W).length>0,K=await Kr(q,N,te,ee=>console.warn(`[\u22B9 ${y}:${Q}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),de=await ge.contextualize({text:Ln(N),subjectHints:[...te,...N.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(he=>!!he))],pendingGroundingExplanationIds:un((await V.getThread(be))?.messages??[])}).catch(ee=>{console.warn(`[\u22B9 ${y}:${Q}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),pe={id:Q,status:"queued",screenshotPath:ie,feedback:N,createdAt:Date.now(),color:T,threadId:be,annotationIds:Ie,provider:Rt(S),model:A||void 0,agentSettings:vt({reasoningEffort:J,serviceTier:B}),...Object.keys(ce).length>0?{imagePaths:ce}:{},sourceId:z||void 0,...ve?{screenshotPaths:W}:{},...K?{memoryReview:K}:{},...de?{imprintContext:de}:{}},_e=new Set(N.annotations.map(ee=>ee.pathname).filter(Boolean)),Ce;if(_e.size>1){let ee=new Map;for(let he of N.annotations){let ke=he.pathname||"(unknown)";ee.has(ke)||ee.set(ke,[]),ee.get(ke).push(he.instruction||Ai({...N,annotations:[he]}))}Ce=[...ee.entries()].map(([he,ke])=>`\`${he}\`
229
229
  ${ke.map(xe=>`- ${xe}`).join(`
230
230
  `)}`).join(`
231
- `)}else Ce=Ss(O);let et=en(O,Object.keys(ae).length>0?ae:void 0);await G.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:K,screenshotPath:se,...V?{screenshotPaths:q}:{},...Object.keys(ae).length>0?{imagePaths:ae}:{},annotationIds:ve,annotationSnapshot:{url:O.url,viewport:O.viewport,annotations:O.annotations,color:P||void 0},feedbackSummary:Ce,feedbackContext:et||void 0,...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}});let Re=N.enqueue(pe);E(u,200,{jobId:K,position:Re,threadId:be})}async function Ze(a,u){let k=a.headers["content-type"]||"",m,P,w,j,$,D,F,L,C,O=[];if(k.includes("multipart/form-data")){let Q=await Dn(a),me=Q.feedback?JSON.parse(Q.feedback):{};m=me.threadId,P=me.reply,w=me.color,j=me.provider,$=me.model,D=yt(me),F=me.sourceId||Q.sourceId,L=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0,C=me.evalRemediation?.action==="resolve"&&typeof me.evalRemediation.evalId=="string"?{evalId:me.evalRemediation.evalId,action:"resolve"}:void 0;for(let z of Q.pastedImages)O.push(z.data)}else{let Q=[];for await(let re of a)Q.push(typeof re=="string"?Buffer.from(re):re);let me=Buffer.concat(Q).toString("utf-8"),z;try{z=JSON.parse(me)}catch{E(u,400,{error:"Invalid JSON"});return}m=z.threadId,P=z.reply,w=z.color,j=z.provider,$=z.model,D=yt(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){E(u,400,{error:"Missing threadId or reply"});return}let K=await G.getThread(m);if(!K){E(u,404,{error:"Thread not found"});return}let q,se;if(C){let Q=await U.findJournalEvalCase(C.evalId),me=(await U.getJournalEvalRuns()).filter(z=>z.evalId===C.evalId&&z.threadId===m).sort((z,re)=>re.completedAt-z.completedAt)[0];if(!Q||!me){E(u,409,{error:"The failed eval run is not available in this thread."});return}if(me.status!=="fail"){E(u,409,{error:"Only a failed eval can start remediation."});return}se={evalCase:Q,run:me}}if(L){let Q=await ie.findModelProposalsByThread(m);if(q=(await Promise.all(Q.flatMap(z=>z.authorityStatus==="accepted"?[]:z.decisionIds.map(async re=>({modelProposalId:z.id,underlying:await U.findPendingProposalForLegacyDecision(re)}))))).filter(z=>!!z.underlying).find(z=>z.underlying.proposalId===L),!q){E(u,409,{error:"The requested memory decision is not pending in this thread."});return}}let ae="";{let Q=await G.getThreadHistory(m);for(let me=Q.length-1;me>=0;me--)if(Q[me].screenshotPath){ae=Q[me].screenshotPath;break}}let oe=await Os(m);if(!ae&&!oe){E(u,400,{error:"No screenshot available"});return}let be=N.hasActiveThread(m),ve=be?N.getQueuedThreadJob(m,Q=>Q._replyText!==void 0||Q._replyPrompt!==void 0):null,V=ve?.id??ut().slice(0,8),Ie=[],de=`${V}-${Date.now()}`;for(let Q=0;Q<O.length;Q++){let me=Me(d,`reply-${de}-${Q}.webp`);await dn(me,O[Q]),Ie.push(me)}await G.appendMessage(m,{role:"human",timestamp:Date.now(),jobId:V,replyToQuestion:P,screenshotPath:ae,...be?{queued:!0}:{},...Ie.length>0?{replyImagePaths:Ie}:{}});let pe=await G.getThreadHistory(m),_e=[...pe].reverse().find(Q=>Q.memoryReview)?.memoryReview,Ce=await he.contextualize({text:P,subjectHints:K.elementIdentifiers,pendingGroundingExplanationIds:eo(pe)}).catch(Q=>{console.warn(`[\u22B9 ${y}:${V}] Imprint context unavailable for reply; continuing without it:`,Q instanceof Error?Q.message:String(Q))}),et=new Set(pe.flatMap(Q=>Q.memoryReceipt?.status==="committed"?[Q.memoryReceipt.proposalId]:[])),Re=[...pe].reverse().find(Q=>Q.memoryReviewCard&&!et.has(Q.memoryReviewCard.proposalId))?.memoryReviewCard,Z=[];for(let Q of pe)if(Q.annotationIds)for(let me of Q.annotationIds)Z.includes(me)||Z.push(me);let fe=St(j),ke=q,xe=ke?[ke.underlying.proposalId]:Re?[Re.proposalId]:[],gt=Xr(ae,pe,fe,Ie.length>0?Ie:void 0);if(se?gt+=["","## Failed eval remediation","This is a new implementation goal based on a failed Popmelt eval. Fix the product gaps identified by the evaluator.","Do not weaken, rewrite, approve, retire, or otherwise modify the eval specification unless the developer explicitly asks.","Treat the accepted product decision as governing truth; the failed implementation is what should change.",`Eval: ${JSON.stringify(se.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:se.run.summary,assertionResults:se.run.assertionResults,scope:se.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
232
- `):ke?gt+=["","## Decision review card",`Privately review proposal ${ke.underlying.proposalId}: ${ke.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
233
- `):Re&&(gt+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Re)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
234
- `)),ve){let Q=ve,z=[...Q._replyTexts??(Q._replyText?[Q._replyText]:[]),P],re=[...Q._replyImagePaths??[],...Ie];Q._replyTexts=z,Q._replyText=xs(z),Q._replyImagePaths=re.length>0?re:void 0,Q._replyPrompt=gt,Q.annotationIds=Z.length>0?Z:Q.annotationIds,Q.agentSettings=D??Q.agentSettings,Q.memoryReview=_e??Q.memoryReview,Q.imprintContext=Ce??Q.imprintContext,Q.surfacedProposalIds=[...new Set([...Q.surfacedProposalIds??[],...xe])],E(u,200,{jobId:V,position:1,threadId:m,bundled:!0});return}let qe={id:V,status:"queued",screenshotPath:ae,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:w,threadId:m,annotationIds:Z.length>0?Z:void 0,provider:fe,model:$||void 0,agentSettings:D,sourceId:F||void 0,..._e?{memoryReview:_e}:{},...Ce?{imprintContext:Ce}:{},...xe.length?{surfacedProposalIds:xe}:{}};se?qe.kind="resolve_eval":oe&&(qe.kind=oe),qe._replyPrompt=gt,qe._evalRemediation=!!se,qe._replyTexts=[P],qe._replyText=xs([P]),Ie.length>0&&(qe._replyImagePaths=Ie);let Ut=be?N.enqueueNext(qe):N.enqueue(qe);E(u,200,{jobId:V,position:Ut,threadId:m})}function at(a,u){u.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),u.write(`event: connected
231
+ `)}else Ce=Ai(N);let nt=nn(N,Object.keys(ce).length>0?ce:void 0);await V.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:Q,screenshotPath:ie,...ve?{screenshotPaths:W}:{},...Object.keys(ce).length>0?{imagePaths:ce}:{},annotationIds:Ie,annotationSnapshot:{url:N.url,viewport:N.viewport,annotations:N.annotations,color:T||void 0},feedbackSummary:Ce,feedbackContext:nt||void 0,...K?{memoryReview:K}:{},...de?{imprintContext:de}:{}});let Pe=I.enqueue(pe);_(g,200,{jobId:Q,position:Pe,threadId:be})}async function tt(a,g){let j=a.headers["content-type"]||"",v,T,S,A,J,B,z,F,D,N=[];if(j.includes("multipart/form-data")){let X=await Fn(a),me=X.feedback?JSON.parse(X.feedback):{};v=me.threadId,T=me.reply,S=me.color,A=me.provider,J=me.model,B=vt(me),z=me.sourceId||X.sourceId,F=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0,D=me.evalRemediation?.action==="resolve"&&typeof me.evalRemediation.evalId=="string"?{evalId:me.evalRemediation.evalId,action:"resolve"}:void 0;for(let H of X.pastedImages)N.push(H.data)}else{let X=[];for await(let re of a)X.push(typeof re=="string"?Buffer.from(re):re);let me=Buffer.concat(X).toString("utf-8"),H;try{H=JSON.parse(me)}catch{_(g,400,{error:"Invalid JSON"});return}v=H.threadId,T=H.reply,S=H.color,A=H.provider,J=H.model,B=vt(H),z=H.sourceId,F=H.memoryReviewProposalId,D=H.evalRemediation?.action==="resolve"&&typeof H.evalRemediation.evalId=="string"?{evalId:H.evalRemediation.evalId,action:"resolve"}:void 0}if(!v||!T){_(g,400,{error:"Missing threadId or reply"});return}let Q=await V.getThread(v);if(!Q){_(g,404,{error:"Thread not found"});return}let W,ie;if(D){let X=await q.findJournalEvalCase(D.evalId),me=(await q.getJournalEvalRuns()).filter(H=>H.evalId===D.evalId&&H.threadId===v).sort((H,re)=>re.completedAt-H.completedAt)[0];if(!X||!me){_(g,409,{error:"The failed eval run is not available in this thread."});return}if(me.status!=="fail"){_(g,409,{error:"Only a failed eval can start remediation."});return}ie={evalCase:X,run:me}}if(F){let X=await se.findModelProposalsByThread(v);if(W=(await Promise.all(X.flatMap(H=>H.authorityStatus==="accepted"?[]:H.decisionIds.map(async re=>({modelProposalId:H.id,underlying:await q.findPendingProposalForLegacyDecision(re)}))))).filter(H=>!!H.underlying).find(H=>H.underlying.proposalId===F),!W){_(g,409,{error:"The requested memory decision is not pending in this thread."});return}}let ce="";{let X=await V.getThreadHistory(v);for(let me=X.length-1;me>=0;me--)if(X[me].screenshotPath){ce=X[me].screenshotPath;break}}let te=await zi(v);if(!ce&&!te){_(g,400,{error:"No screenshot available"});return}let be=I.hasActiveThread(v),Ie=be?I.getQueuedThreadJob(v,X=>X._replyText!==void 0||X._replyPrompt!==void 0):null,ve=Ie?.id??mt().slice(0,8),K=[],de=`${ve}-${Date.now()}`;for(let X=0;X<N.length;X++){let me=Ae(c,`reply-${de}-${X}.webp`);await pn(me,N[X]),K.push(me)}await V.appendMessage(v,{role:"human",timestamp:Date.now(),jobId:ve,replyToQuestion:T,screenshotPath:ce,...be?{queued:!0}:{},...K.length>0?{replyImagePaths:K}:{}});let pe=await V.getThreadHistory(v),_e=[...pe].reverse().find(X=>X.memoryReview)?.memoryReview,Ce=await ge.contextualize({text:T,subjectHints:Q.elementIdentifiers,pendingGroundingExplanationIds:un(pe)}).catch(X=>{console.warn(`[\u22B9 ${y}:${ve}] Imprint context unavailable for reply; continuing without it:`,X instanceof Error?X.message:String(X))}),nt=new Set(pe.flatMap(X=>X.memoryReceipt?.status==="committed"?[X.memoryReceipt.proposalId]:[])),Pe=[...pe].reverse().find(X=>X.memoryReviewCard&&!nt.has(X.memoryReviewCard.proposalId))?.memoryReviewCard,ee=[];for(let X of pe)if(X.annotationIds)for(let me of X.annotationIds)ee.includes(me)||ee.push(me);let he=Rt(A),ke=W,xe=ke?[ke.underlying.proposalId]:Pe?[Pe.proposalId]:[],yt=oi(ce,pe,he,K.length>0?K:void 0);if(ie?yt+=["","## Failed eval remediation","This is a new implementation goal based on a failed Popmelt eval. Fix the product gaps identified by the evaluator.","Do not weaken, rewrite, approve, retire, or otherwise modify the eval specification unless the developer explicitly asks.","Treat the accepted product decision as governing truth; the failed implementation is what should change.",`Eval: ${JSON.stringify(ie.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:ie.run.summary,assertionResults:ie.run.assertionResults,scope:ie.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
232
+ `):ke?yt+=["","## Decision review card",`Privately review proposal ${ke.underlying.proposalId}: ${ke.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
233
+ `):Pe&&(yt+=["","## 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(`
234
+ `)),Ie){let X=Ie,H=[...X._replyTexts??(X._replyText?[X._replyText]:[]),T],re=[...X._replyImagePaths??[],...K];X._replyTexts=H,X._replyText=Ei(H),X._replyImagePaths=re.length>0?re:void 0,X._replyPrompt=yt,X.annotationIds=ee.length>0?ee:X.annotationIds,X.agentSettings=B??X.agentSettings,X.memoryReview=_e??X.memoryReview,X.imprintContext=Ce??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...xe])],_(g,200,{jobId:ve,position:1,threadId:v,bundled:!0});return}let qe={id:ve,status:"queued",screenshotPath:ce,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:v,annotationIds:ee.length>0?ee:void 0,provider:he,model:J||void 0,agentSettings:B,sourceId:z||void 0,..._e?{memoryReview:_e}:{},...Ce?{imprintContext:Ce}:{},...xe.length?{surfacedProposalIds:xe}:{}};ie?qe.kind="resolve_eval":te&&(qe.kind=te),qe._replyPrompt=yt,qe._evalRemediation=!!ie,qe._replyTexts=[T],qe._replyText=Ei([T]),K.length>0&&(qe._replyImagePaths=K);let qt=be?I.enqueueNext(qe):I.enqueue(qe);_(g,200,{jobId:ve,position:qt,threadId:v})}function dt(a,g){g.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),g.write(`event: connected
235
235
  data: {"status":"connected"}
236
236
 
237
- `);let m=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,P={id:ut().slice(0,8),res:u,sourceId:m};X.add(P),a.on("close",()=>{X.delete(P)})}async function ct(a,u,k){i??=ls(a.headers),Ue();let m=[...N.allActive,...T.allActive.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds??[],color:"#000000",kind:"project_model",standalone:V.standalone}))],[P,w,j,$,D]=await Promise.allSettled([ie.loadRuns(),ie.loadModelProposals(),U.status(),he.store.load(),G.load()]),F=[],L=V=>V.reason instanceof Error?V.reason.message:String(V.reason);P.status==="rejected"&&F.push({subsystem:"projection",message:L(P)}),w.status==="rejected"&&F.push({subsystem:"projection",message:L(w)}),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=w.status==="fulfilled"?w.value.proposals:[],K=ps(C,O),q=K.actionableProposals.map(V=>({id:V.id,status:V.status,title:V.title,summary:V.summary,decisionIds:V.decisionIds,threadId:V.threadId,runId:V.runId,presentationJobId:V.presentationJobId,authorityStatus:V.authorityStatus,underlyingProposalId:V.underlyingProposalId,createdAt:V.createdAt,updatedAt:V.updatedAt,appliedAt:V.appliedAt,dismissedAt:V.dismissedAt,generatedEvalIds:V.generatedEvalIds,evalProjections:V.evalProjections,error:V.error})),se=j.status==="fulfilled"?j.value:{initialized:!1,state:"degraded",error:L(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(V=>eo(V.messages)))]:[],oe=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(V=>V.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:$.value.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:L($),pendingGroundingCount:ae.length,admission:he.diagnostics(),admissionWindowStartedAt:e},be=F.length>0?"degraded":se.state==="absent"||se.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();E(u,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:be,issues:F},version:rt,restartMode:p,projectId:s,projectName:Zn(r),projectRoot:r,requestProjectId:k,projectIdVerified:k===s,devOrigin:i,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds,color:V.color,kind:V.kind,standalone:"standalone"in V?V.standalone:void 0})),queueDepth:N.depth+T.depth,projectionQueueDepth:T.depth,leases:{active:B.isActivated,count:B.size,nextExpiryAt:B.nextExpiryAt,shutdownPending:W},projection:{state:P.status==="fulfilled"&&w.status==="fulfilled"?"ready":"degraded",activeJob:T.active?{id:T.active.id,status:T.active.status,threadId:T.active.threadId,annotationIds:T.active.annotationIds??[],provider:T.active.provider,model:T.active.model}:null,queueDepth:T.depth,recentRuns:K.recentRuns,recentAppliedRuns:K.recentAppliedRuns,actionableProposalCounts:K.actionableProposalCounts,actionableProposals:q},memory:se,imprint:oe,recentJobsRetentionMs:Je,recentJobs:Pe})}async function ft(a,u){let k=await new Promise(m=>{let P="";a.on("data",w=>{P+=w.toString()}),a.on("end",()=>m(P))});try{let m=JSON.parse(k);typeof m.devOrigin=="string"&&(i=m.devOrigin||null),E(u,200,{ok:!0,devOrigin:i})}catch{E(u,400,{error:"Invalid JSON"})}}async function ro(a){let u=await M.load();E(a,200,{ok:!0,...u})}async function so(a,u){let k=await ze(a);if(!ys(k.theme)){E(u,400,{error:"theme must be light, dark, or auto"});return}let m=await M.setTheme(k.theme);E(u,200,{ok:!0,exists:!0,preferences:m})}async function zt(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),P=m?N.allActive.filter(L=>L.id===m):N.allActive,w=m?T.allActive.filter(L=>L.id===m):T.allActive,j=[...P.map(L=>L.threadId),...w.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});E(u,200,{cancelled:F})}async function je(a){let u=ut().slice(0,8),k=a.threadId,m=!k;k||(k=(await G.createThread(u,[])).id,Ge.set(k,"project_model")),m&&await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:u,feedbackSummary:a.reason}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:u,responseText:m?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let P={id:u,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:k,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:m},w=T.enqueue(P);return{jobId:u,position:w,threadId:k}}async function Ne(a,u){let k=decodeURIComponent(a),m=await ie.findModelProposal(k);if(!m){E(u,404,{error:"Model proposal not found"});return}E(u,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:m})}async function dt(a,u,k){let m=decodeURIComponent(a),P=[];for await(let O of u)P.push(typeof O=="string"?Buffer.from(O):O);let w;try{w=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{E(k,400,{error:"Invalid JSON"});return}let j=(w.changes??[]).flatMap(O=>{if(!Array.isArray(O.path)||O.path.length===0)return[];let K=O.path.filter(se=>typeof se=="string"||typeof se=="number");if(K.length!==O.path.length)return[];let q=Array.isArray(O.decisionIds)?O.decisionIds.filter(se=>typeof se=="string"):void 0;return[{path:K,value:O.value,remove:O.remove===!0,decisionIds:q}]});if(j.length===0){E(k,400,{error:"No selected model changes"});return}let $=(w.changeSummaries??[]).flatMap(O=>{if(!O||typeof O!="object")return[];let K=Array.isArray(O.path)?O.path.filter(q=>typeof q=="string"||typeof q=="number"):void 0;return Array.isArray(O.path)&&K?.length!==O.path.length?[]:[{group:typeof O.group=="string"?O.group:void 0,label:typeof O.label=="string"?O.label:void 0,detail:typeof O.detail=="string"?O.detail:void 0,path:K,value:O.value,currentValue:O.currentValue}]}),D=await ie.findModelProposal(m);if(!D){E(k,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){E(k,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){E(k,409,{error:`Model proposal is already ${D.status}.`});return}let F=D.decisionIds.map(O=>{let K=D.changes?.filter(ae=>ae.decisionIds.includes(O)).length??0,q=j.filter(ae=>ae.decisionIds?.includes(O)).length,se=q===0?"unprojected":K>q?"partially_projected":"projected";return{decisionId:O,status:se}}),L=await U.applyModelProjection({runId:D.runId??D.id,presentationJobId:D.presentationJobId,decisionIds:D.decisionIds,changes:j.map(O=>({path:O.path,value:O.value,decisionIds:O.decisionIds})),coverage:F}),C=await ie.applySelectedModelProposal(m,j,$);if(!C){E(k,404,{error:"Model proposal not found"});return}if(await Ye(C),C.threadId){let O=St(w.provider),K=typeof w.model=="string"&&w.model?w.model:void 0;await G.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${C.id}`,responseText:"",provider:O,model:K})}E(k,200,{proposal:C,projection:L})}async function Pt(a,u,k){let m=decodeURIComponent(a),{provider:P,model:w}=await ht(u),j=await ie.dismissModelProposal(m);if(!j){E(k,404,{error:"Model proposal not found"});return}j.threadId&&await G.appendMessage(j.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${j.id}`,responseText:"",provider:P,model:w}),E(k,200,{proposal:j})}async function ht(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:St(typeof k.provider=="string"?k.provider:void 0),model:typeof k.model=="string"&&k.model?k.model:void 0,agentSettings:yt(k)}}catch{return{}}}async function io(a,u,k){let m=decodeURIComponent(a),P=await U.findJournalEvalCase(m);if(!P){E(k,404,{error:"Eval not found"});return}if(P.status!=="approved"){E(k,400,{error:"Only approved evals can be run"});return}let{screenshot:w,feedback:j,provider:$,model:D,reasoningEffort:F,serviceTier:L,sourceId:C}=await Dn(u),O=St($)??b;if(O==="copilot"){E(k,400,{error:"Eval runs are not available for Copilot yet."});return}let K={};try{K=j?JSON.parse(j):{}}catch{E(k,400,{error:"Invalid eval run context JSON"});return}let q=ut().slice(0,8),se=ut().slice(0,8),ae=Me(d,`eval-run-${q}.webp`);await dn(ae,w);let oe=await ue.persistEvalScreenshot(w),be=K.viewport,ve=be&&typeof be=="object"?be:{},V={type:"current_page",url:typeof K.url=="string"?K.url:"",viewport:{width:typeof ve.width=="number"?ve.width:0,height:typeof ve.height=="number"?ve.height:0}},Ie=await ie.loadModel(),de=await Rs(r,P,Ie),pe=O==="claude"?S.name:O==="codex"?A.name:null,_e=O==="codex"?_.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=pr({evalCase:P,scope:V,model:Ie,screenshotPath:ae,chromeDevtoolsAvailable:_e}),Re=(await G.createThread(se,[])).id;Ge.set(Re,"run_eval");let Z={timestamp:new Date().toISOString(),url:V.url,viewport:V.viewport,scrollPosition:{x:typeof K.scrollX=="number"?K.scrollX:0,y:typeof K.scrollY=="number"?K.scrollY:0},annotations:[],styleModifications:[]};await G.appendMessage(Re,{role:"human",timestamp:Date.now(),jobId:se,screenshotPath:ae,feedbackSummary:`Run eval \u2014 ${P.title}`,feedbackContext:[`Eval: ${P.title}`,"Scope: current page",`URL: ${V.url||"unknown"}`,"Assertions:",...P.assertions.map(xe=>`- ${xe}`)].join(`
238
- `)});let fe={id:se,status:"queued",screenshotPath:ae,feedback:Z,createdAt:Date.now(),color:"#111827",threadId:Re,kind:"run_eval",evalId:m,evalRunId:q,provider:O,model:D||void 0,agentSettings:yt({reasoningEffort:F,serviceTier:L}),sourceId:C||void 0};fe._replyPrompt=Ce,fe._evalRunScope=V,fe._evalScreenshotPath=oe,fe._evalScopeFingerprint=de;let ke=N.enqueue(fe);E(k,200,{jobId:se,runId:q,position:ke,threadId:Re,screenshotPath:oe})}async function ln(a,u,k){let m=decodeURIComponent(a),P={},w,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());w=L.status,j=L.title,$=L.assertions}catch{E(k,400,{error:"Invalid JSON"});return}if(w!==void 0&&w!=="pending"&&w!=="approved"&&w!=="rejected"){E(k,400,{error:"Invalid status"});return}if(w&&(P.status=w),j!==void 0){if(typeof j!="string"||j.trim().length===0){E(k,400,{error:"Invalid title"});return}P.title=j.trim()}if($!==void 0){if(!Array.isArray($)){E(k,400,{error:"Invalid assertions"});return}let F=$.filter(L=>typeof L=="string").map(L=>L.trim()).filter(Boolean);if(F.length===0){E(k,400,{error:"Invalid assertions"});return}P.assertions=F}if(!P.status&&!P.title&&!P.assertions){E(k,400,{error:"No eval changes provided"});return}let D=await U.updateJournalEvalCase(m,P);if(!D){E(k,404,{error:"Eval not found"});return}E(k,200,{eval:D})}async function Os(a){let u=Ge.get(a);if(u)return u;let P=(await G.getThread(a))?.messages.find(w=>w.role==="human")?.feedbackSummary??"";if(P.startsWith("Synthesize evals"))return Ge.set(a,"synthesize_evals"),"synthesize_evals";if(P.startsWith("Synthesize rules"))return Ge.set(a,"synthesize"),"synthesize";if(P.startsWith("Run eval"))return Ge.set(a,"run_eval"),"run_eval";if(P.startsWith("Materialize model")||P.startsWith("Project model"))return Ge.set(a,"project_model"),"project_model"}async function Ds(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??I));let[w,j,$]=await Promise.all([Io(r),bo(r),xo(r,f.copilot?.path??I)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),E(u,200,{results:P,capabilities:{providers:f}})}async function Js(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:{description:""},claim:`${m.name} is an explicitly governed component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await st({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});E(u,200,{added:!0,alreadyExists:!1,...P,evalId:w})}async function Ns(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:null,claim:`${m.name} is not governed as a component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await st({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});E(u,200,{removed:!0,...P,evalId:w})}async function Bs(a,u){let k=[];for await(let $ of a)k.push(typeof $=="string"?Buffer.from($):$);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){E(u,400,{error:"Missing or invalid path/value"});return}let P=m.value;try{let $=JSON.parse(m.value);$&&typeof $=="object"&&(P=$)}catch{}let w=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:P,claim:`${m.path} uses ${m.value} in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let j=await st({decisionId:w.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});E(u,200,{updated:!0,...w,evalId:j})}async function Ls(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){E(u,400,{error:"Missing or invalid path"});return}let P=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:null,claim:`${m.path} is intentionally absent from the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await st({decisionId:P.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});E(u,200,{removed:!0,...P,evalId:w})}function Fs(a,u){let k=i??"http://localhost:3000";if(!i){let P=a.headers.referer||a.headers.origin;if(P)try{let w=new URL(typeof P=="string"?P:P[0]||"");(w.hostname==="localhost"||w.hostname==="127.0.0.1")&&(k=w.origin)}catch{}}let m=Vo(y,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function zs(a){let u=Date.now();if(mt&&u<mt.expires){E(a,200,mt.data);return}try{let{scanForComponents:k}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),P=await k(r);mt={data:P,expires:u+5e3},m(P,r,Lt).then(w=>{Lt=w}).catch(w=>console.warn("[Bridge] Render generation failed:",w)),E(a,200,P)}catch(k){console.error("[Bridge] Scanner error:",k),E(a,500,{error:"Failed to scan components"})}}async function Us(a){let u=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let k=cd(import.meta.url);u.unshift(Me(ad(k),"canvas.mjs"))}catch{}for(let k of u)try{let m=await Fo(k,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(m);return}catch{}console.error("[Bridge] Canvas bundle not found in:",u),E(a,404,{error:"Canvas bundle not found"})}async function qs(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(u,400,{error:"Invalid filename"});return}try{let k=[Me(d,a),Me(r,".popmelt","artifacts","thread-media",a),Me(r,".popmelt","artifacts","eval-screenshots",a),Me(r,".popmelt","evals","screenshots",a),Me(r,".popmelt","screenshots",a)],m;for(let j of k)try{m=await Fo(j);break}catch{}if(!m)throw new Error("File not found");let P=a.split(".").pop()?.toLowerCase(),w=P==="png"?"image/png":P==="webp"?"image/webp":P==="jpg"||P==="jpeg"?"image/jpeg":"application/octet-stream";u.writeHead(200,{"Content-Type":w,"Cache-Control":"public, max-age=3600"}),u.end(m)}catch{E(u,404,{error:"File not found"})}}function pn(a){return`/files/${Zn(a)}`}async function Hs(a,u){let k=await G.getThread(a);if(!k){E(u,404,{error:"Thread not found"});return}let m=k.messages.some(C=>C.role==="assistant"&&C.responseText?.includes("<eval_run_result>")),P=k.messages.filter(C=>C.role==="assistant"&&C.responseText?.includes("Model suggestion ready")),[w,j]=await Promise.all([m?U.getJournalEvalRuns().then(C=>C.filter(O=>O.threadId===a).sort((O,K)=>K.completedAt-O.completedAt)[0]):Promise.resolve(void 0),P.length>0?ie.findModelProposalsByThread(a):Promise.resolve([])]),$=w?await U.findJournalEvalCase(w.evalId):null,D=await Promise.all(j.map(async(C,O)=>{if(C.authorityStatus==="accepted")return C;let K=(await Promise.all(C.decisionIds.map(q=>U.findPendingProposalForLegacyDecision(q)))).find(Boolean);return{...C,authorityStatus:"legacy_untrusted",presentationJobId:C.presentationJobId??P[O]?.jobId??P.at(-1)?.jobId,underlyingProposalId:K?.proposalId,underlyingClaim:K?.claim}})),F=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,L=k.messages.map(({screenshotPath:C,screenshotPaths:O,imagePaths:K,replyImagePaths:q,...se})=>({...se,...se.role==="assistant"&&w&&se.responseText?.includes("<eval_run_result>")?{evalRun:{...w,title:$?.title}}:{},...C?{screenshotUrl:pn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,oe])=>[ae,pn(oe)]))}:{},...K?{imageUrls:Object.fromEntries(Object.entries(K).map(([ae,oe])=>[ae,oe.map(pn)]))}:{},...q?{replyImageUrls:q.map(pn)}:{}}));E(u,200,{id:k.id,createdAt:k.createdAt,messages:L,modelProposal:F,modelProposals:D})}async function Ws(a,u){let k=decodeURIComponent(a);if(!await G.deleteThread(k)){E(u,404,{deleted:!1,error:"Thread not found"});return}E(u,200,{deleted:!0})}let Ho=9,Wo=!1;for(let a=n;a<n+Ho;a++)try{await xd(Ft,a),y=a,Wo=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await oo(a);if(sn(k,{projectId:s,version:rt,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Wo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Ho-1} in use`);for(let[a,u]of Object.entries(f))!u.available||!u.path||x(a,u.path).then(k=>{if(k)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),u.available=!1,u.path=null;for(let m of X)to(m,{type:"capabilities_changed",data:{}})}});let Gs=setInterval(()=>{ks(d).catch(()=>{})},pd),Go=setInterval(()=>{B.expireStale().becameEmpty&&ge()},md);return Go.unref?.(),{port:y,projectId:s,close:async()=>{clearInterval(Gs),clearInterval(Go),te(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of X)try{a.res.end()}catch{}return X.clear(),new Promise(a=>{Ft.close(()=>a())})}}}async function ks(o){try{let e=await td(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let s=await od(r);n-s.mtimeMs>ud&&await rd(r)}catch{}}}catch{}}import{randomUUID as Pd}from"crypto";var Rd=5e3,kd=250;function Uo(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function As(o,e=fetch){let n=`${process.pid}-${Pd()}`,t=`http://127.0.0.1:${o.port}`,r=!1,s=!1,i=async()=>(await e(`${t}/leases`,{method:"POST",headers:Uo(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await i())return null}catch(h){return console.warn("[popmelt] failed to register bridge lease:",h instanceof Error?h.message:String(h)),null}let d=async()=>{if(!(r||s)){s=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:Uo(o)})).status===404&&!r&&await i()}catch{}finally{s=!1}}},c=setInterval(()=>{d()},Rd);return c.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(c);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:Uo(o),keepalive:!0})}catch{}}}}}function _s(o,e=process){let n=!1,t=new Map,r=()=>{if(!n){n=!0;for(let[s,i]of t)e.removeListener(s,i);t.clear()}};for(let s of["SIGINT","SIGTERM"]){let i=()=>{let d=e.listenerCount(s),c=o.release();if(d>0)return;let l=new Promise(h=>{setTimeout(h,kd)});Promise.race([c,l]).finally(()=>{r(),e.kill(e.pid,s)})};t.set(s,i),e.prependOnceListener(s,i)}return r}var Dd=1111,Cs=3e4,Jd=8e3;async function Nd(o){return Cd(o).catch(()=>o)}async function $s(o,e){let t=(await _d(e,"utf8").catch(()=>"")).slice(-Jd).trim();return new Error(t?`${o}
237
+ `);let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,T={id:mt().slice(0,8),res:g,sourceId:v};Y.add(T),a.on("close",()=>{Y.delete(T)})}async function lt(a,g,j){s??=yi(a.headers),Ue();let v=[...I.allActive,...b.allActive.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds??[],color:"#000000",kind:"project_model",standalone:K.standalone}))],[T,S,A,J,B]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),q.status(),ge.store.load(),V.load()]),z=[],F=K=>K.reason instanceof Error?K.reason.message:String(K.reason);T.status==="rejected"&&z.push({subsystem:"projection",message:F(T)}),S.status==="rejected"&&z.push({subsystem:"projection",message:F(S)}),A.status==="rejected"?z.push({subsystem:"memory",message:F(A)}):A.value.state==="degraded"&&z.push({subsystem:"memory",message:A.value.error??"Product memory is degraded."}),J.status==="rejected"&&z.push({subsystem:"imprint",message:F(J)}),B.status==="rejected"&&z.push({subsystem:"threads",message:F(B)});let D=T.status==="fulfilled"?T.value.runs:[],N=S.status==="fulfilled"?S.value.proposals:[],Q=vi(D,N),W=Q.actionableProposals.map(K=>({id:K.id,status:K.status,title:K.title,summary:K.summary,decisionIds:K.decisionIds,threadId:K.threadId,runId:K.runId,presentationJobId:K.presentationJobId,authorityStatus:K.authorityStatus,underlyingProposalId:K.underlyingProposalId,createdAt:K.createdAt,updatedAt:K.updatedAt,appliedAt:K.appliedAt,dismissedAt:K.dismissedAt,generatedEvalIds:K.generatedEvalIds,evalProjections:K.evalProjections,error:K.error})),ie=A.status==="fulfilled"?A.value:{initialized:!1,state:"degraded",error:F(A)},ce=B.status==="fulfilled"?[...new Set(Object.values(B.value.threads).flatMap(K=>un(K.messages)))]:[],te=J.status==="fulfilled"?ce.filter(K=>J.value.graph.explanations.some(de=>de.id===K&&de.state==="testing")):[],be=J.status==="fulfilled"?{state:"ready",head:J.value.graph.head,updatedAt:J.value.graph.updatedAt,explanationCount:J.value.graph.explanations.filter(K=>K.state!=="retired").length,concreteCount:J.value.graph.concrete.length,relationCount:J.value.graph.relations.length,pendingGroundingCount:te.length,recoveredTransactions:J.value.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(J),pendingGroundingCount:te.length,admission:ge.diagnostics(),admissionWindowStartedAt:e},Ie=z.length>0?"degraded":ie.state==="absent"||ie.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();_(g,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:Ie,issues:z},version:st,restartMode:p,projectId:i,projectName:ro(r),projectRoot:r,requestProjectId:j,projectIdVerified:j===i,devOrigin:s,activeJob:v[0]?{id:v[0].id,status:v[0].status}:null,activeJobs:v.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:I.depth+b.depth,projectionQueueDepth:b.depth,leases:{active:M.isActivated,count:M.size,nextExpiryAt:M.nextExpiryAt,shutdownPending:U},projection:{state:T.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:b.active?{id:b.active.id,status:b.active.status,threadId:b.active.threadId,annotationIds:b.active.annotationIds??[],provider:b.active.provider,model:b.active.model}:null,queueDepth:b.depth,recentRuns:Q.recentRuns,recentAppliedRuns:Q.recentAppliedRuns,actionableProposalCounts:Q.actionableProposalCounts,actionableProposals:W},memory:ie,imprint:be,recentJobsRetentionMs:Je,recentJobs:Re})}async function ht(a,g){let j=await new Promise(v=>{let T="";a.on("data",S=>{T+=S.toString()}),a.on("end",()=>v(T))});try{let v=JSON.parse(j);typeof v.devOrigin=="string"&&(s=v.devOrigin||null),_(g,200,{ok:!0,devOrigin:s})}catch{_(g,400,{error:"Invalid JSON"})}}async function co(a){let g=await $.load();_(a,200,{ok:!0,...g})}async function lo(a,g){let j=await ze(a);if(!Ri(j.theme)){_(g,400,{error:"theme must be light, dark, or auto"});return}let v=await $.setTheme(j.theme);_(g,200,{ok:!0,exists:!0,preferences:v})}async function Ut(a,g){let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),T=v?I.allActive.filter(F=>F.id===v):I.allActive,S=v?b.allActive.filter(F=>F.id===v):b.allActive,A=[...T.map(F=>F.threadId),...S.map(F=>F.threadId)].filter(Boolean),J=v?I.cancelJob(v):I.cancelActive(),B=v?b.cancelJob(v):b.cancelActive(),z=!!(J||B);for(let F of A)await V.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:v||B?.id||"",cancelled:!0});_(g,200,{cancelled:z})}async function Ee(a){let g=mt().slice(0,8),j=a.threadId,v=!j;j||(j=(await V.createThread(g,[])).id,Ve.set(j,"project_model")),v&&await V.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:a.reason}),await V.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:g,responseText:v?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let T={id:g,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:j,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:v},S=b.enqueue(T);return{jobId:g,position:S,threadId:j}}async function Ne(a,g){let j=decodeURIComponent(a),v=await se.findModelProposal(j);if(!v){_(g,404,{error:"Model proposal not found"});return}_(g,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:v})}async function pt(a,g,j){let v=decodeURIComponent(a),T=[];for await(let N of g)T.push(typeof N=="string"?Buffer.from(N):N);let S;try{S=JSON.parse(Buffer.concat(T).toString("utf-8"))}catch{_(j,400,{error:"Invalid JSON"});return}let A=(S.changes??[]).flatMap(N=>{if(!Array.isArray(N.path)||N.path.length===0)return[];let Q=N.path.filter(ie=>typeof ie=="string"||typeof ie=="number");if(Q.length!==N.path.length)return[];let W=Array.isArray(N.decisionIds)?N.decisionIds.filter(ie=>typeof ie=="string"):void 0;return[{path:Q,value:N.value,remove:N.remove===!0,decisionIds:W}]});if(A.length===0){_(j,400,{error:"No selected model changes"});return}let J=(S.changeSummaries??[]).flatMap(N=>{if(!N||typeof N!="object")return[];let Q=Array.isArray(N.path)?N.path.filter(W=>typeof W=="string"||typeof W=="number"):void 0;return Array.isArray(N.path)&&Q?.length!==N.path.length?[]:[{group:typeof N.group=="string"?N.group:void 0,label:typeof N.label=="string"?N.label:void 0,detail:typeof N.detail=="string"?N.detail:void 0,path:Q,value:N.value,currentValue:N.currentValue}]}),B=await se.findModelProposal(v);if(!B){_(j,404,{error:"Model proposal not found"});return}if(B.authorityStatus!=="accepted"){_(j,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(B.status!=="pending"){_(j,409,{error:`Model proposal is already ${B.status}.`});return}let z=B.decisionIds.map(N=>{let Q=B.changes?.filter(ce=>ce.decisionIds.includes(N)).length??0,W=A.filter(ce=>ce.decisionIds?.includes(N)).length,ie=W===0?"unprojected":Q>W?"partially_projected":"projected";return{decisionId:N,status:ie}}),F=await q.applyModelProjection({runId:B.runId??B.id,presentationJobId:B.presentationJobId,decisionIds:B.decisionIds,changes:A.map(N=>({path:N.path,value:N.value,decisionIds:N.decisionIds})),coverage:z}),D=await se.applySelectedModelProposal(v,A,J);if(!D){_(j,404,{error:"Model proposal not found"});return}if(await et(D),D.threadId){let N=Rt(S.provider),Q=typeof S.model=="string"&&S.model?S.model:void 0;await V.appendMessage(D.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${D.id}`,responseText:"",provider:N,model:Q})}_(j,200,{proposal:D,projection:F})}async function Pt(a,g,j){let v=decodeURIComponent(a),{provider:T,model:S}=await gt(g),A=await se.dismissModelProposal(v);if(!A){_(j,404,{error:"Model proposal not found"});return}A.threadId&&await V.appendMessage(A.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${A.id}`,responseText:"",provider:T,model:S}),_(j,200,{proposal:A})}async function gt(a){try{let g=[];for await(let v of a)g.push(typeof v=="string"?Buffer.from(v):v);if(g.length===0)return{};let j=JSON.parse(Buffer.concat(g).toString());return{provider:Rt(typeof j.provider=="string"?j.provider:void 0),model:typeof j.model=="string"&&j.model?j.model:void 0,agentSettings:vt(j)}}catch{return{}}}async function po(a,g,j){let v=decodeURIComponent(a),T=await q.findJournalEvalCase(v);if(!T){_(j,404,{error:"Eval not found"});return}if(T.status!=="approved"){_(j,400,{error:"Only approved evals can be run"});return}let{screenshot:S,feedback:A,provider:J,model:B,reasoningEffort:z,serviceTier:F,sourceId:D}=await Fn(g),N=Rt(J)??x;if(N==="copilot"){_(j,400,{error:"Eval runs are not available for Copilot yet."});return}let Q={};try{Q=A?JSON.parse(A):{}}catch{_(j,400,{error:"Invalid eval run context JSON"});return}let W=mt().slice(0,8),ie=mt().slice(0,8),ce=Ae(c,`eval-run-${W}.webp`);await pn(ce,S);let te=await ue.persistEvalScreenshot(S),be=Q.viewport,Ie=be&&typeof be=="object"?be:{},ve={type:"current_page",url:typeof Q.url=="string"?Q.url:"",viewport:{width:typeof Ie.width=="number"?Ie.width:0,height:typeof Ie.height=="number"?Ie.height:0}},K=await se.loadModel(),de=await _i(r,T,K),pe=N==="claude"?E.name:N==="codex"?O.name:null,_e=N==="codex"?C.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=gr({evalCase:T,scope:ve,model:K,screenshotPath:ce,chromeDevtoolsAvailable:_e}),Pe=(await V.createThread(ie,[])).id;Ve.set(Pe,"run_eval");let ee={timestamp:new Date().toISOString(),url:ve.url,viewport:ve.viewport,scrollPosition:{x:typeof Q.scrollX=="number"?Q.scrollX:0,y:typeof Q.scrollY=="number"?Q.scrollY:0},annotations:[],styleModifications:[]};await V.appendMessage(Pe,{role:"human",timestamp:Date.now(),jobId:ie,screenshotPath:ce,feedbackSummary:`Run eval \u2014 ${T.title}`,feedbackContext:[`Eval: ${T.title}`,"Scope: current page",`URL: ${ve.url||"unknown"}`,"Assertions:",...T.assertions.map(xe=>`- ${xe}`)].join(`
238
+ `)});let he={id:ie,status:"queued",screenshotPath:ce,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:Pe,kind:"run_eval",evalId:v,evalRunId:W,provider:N,model:B||void 0,agentSettings:vt({reasoningEffort:z,serviceTier:F}),sourceId:D||void 0};he._replyPrompt=Ce,he._evalRunScope=ve,he._evalScreenshotPath=te,he._evalScopeFingerprint=de;let ke=I.enqueue(he);_(j,200,{jobId:ie,runId:W,position:ke,threadId:Pe,screenshotPath:te})}async function mn(a,g,j){let v=decodeURIComponent(a),T={},S,A,J;try{let z=[];for await(let D of g)z.push(typeof D=="string"?Buffer.from(D):D);let F=JSON.parse(Buffer.concat(z).toString());S=F.status,A=F.title,J=F.assertions}catch{_(j,400,{error:"Invalid JSON"});return}if(S!==void 0&&S!=="pending"&&S!=="approved"&&S!=="rejected"){_(j,400,{error:"Invalid status"});return}if(S&&(T.status=S),A!==void 0){if(typeof A!="string"||A.trim().length===0){_(j,400,{error:"Invalid title"});return}T.title=A.trim()}if(J!==void 0){if(!Array.isArray(J)){_(j,400,{error:"Invalid assertions"});return}let z=J.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(z.length===0){_(j,400,{error:"Invalid assertions"});return}T.assertions=z}if(!T.status&&!T.title&&!T.assertions){_(j,400,{error:"No eval changes provided"});return}let B=await q.updateJournalEvalCase(v,T);if(!B){_(j,404,{error:"Eval not found"});return}_(j,200,{eval:B})}async function zi(a){let g=Ve.get(a);if(g)return g;let T=(await V.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(T.startsWith("Synthesize evals"))return Ve.set(a,"synthesize_evals"),"synthesize_evals";if(T.startsWith("Synthesize rules"))return Ve.set(a,"synthesize"),"synthesize";if(T.startsWith("Run eval"))return Ve.set(a,"run_eval"),"run_eval";if(T.startsWith("Materialize model")||T.startsWith("Project model"))return Ve.set(a,"project_model"),"project_model"}async function Ui(a,g){let j=[];for await(let B of a)j.push(typeof B=="string"?Buffer.from(B):B);let v;if(j.length>0)try{v=JSON.parse(Buffer.concat(j).toString("utf-8")).serverUrl}catch{}let T=[];h.claude?.available&&h.claude.mcp&&!h.claude.mcp.found&&T.push(await _r(v)),h.codex?.available&&h.codex.mcp&&!h.codex.mcp.found&&T.push(await Cr(v)),h.copilot?.available&&h.copilot.mcp&&!h.copilot.mcp.found&&T.push(await $r(v,h.copilot.path??P));let[S,A,J]=await Promise.all([Ro(r),Po(r),ko(r,h.copilot?.path??P)]);h.claude&&(h.claude.mcp=S),h.codex&&(h.codex.mcp=A),h.copilot&&(h.copilot.mcp=J),_(g,200,{results:T,capabilities:{providers:h}})}async function qi(a,g){let j=[];for await(let A of a)j.push(typeof A=="string"?Buffer.from(A):A);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let T=await q.recordDirectModelMutation({key:`components.${v.name}`,value:{description:""},claim:`${v.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await at({decisionId:T.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is an explicitly governed component in the product model.`});_(g,200,{added:!0,alreadyExists:!1,...T,evalId:S})}async function Hi(a,g){let j=[];for await(let A of a)j.push(typeof A=="string"?Buffer.from(A):A);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let T=await q.recordDirectModelMutation({key:`components.${v.name}`,value:null,claim:`${v.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await at({decisionId:T.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is not governed as a component in the product model.`});_(g,200,{removed:!0,...T,evalId:S})}async function Wi(a,g){let j=[];for await(let J of a)j.push(typeof J=="string"?Buffer.from(J):J);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"||typeof v.value!="string"){_(g,400,{error:"Missing or invalid path/value"});return}let T=v.value;try{let J=JSON.parse(v.value);J&&typeof J=="object"&&(T=J)}catch{}let S=await q.recordDirectModelMutation({key:`tokens.${v.path}`,value:T,claim:`${v.path} uses ${v.value} in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let A=await at({decisionId:S.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} uses ${v.value} in the product model.`});_(g,200,{updated:!0,...S,evalId:A})}async function Gi(a,g){let j=[];for await(let A of a)j.push(typeof A=="string"?Buffer.from(A):A);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"){_(g,400,{error:"Missing or invalid path"});return}let T=await q.recordDirectModelMutation({key:`tokens.${v.path}`,value:null,claim:`${v.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await at({decisionId:T.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} is intentionally absent from the product model.`});_(g,200,{removed:!0,...T,evalId:S})}function Vi(a,g){let j=s??"http://localhost:3000";if(!s){let T=a.headers.referer||a.headers.origin;if(T)try{let S=new URL(typeof T=="string"?T:T[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(j=S.origin)}catch{}}let v=Zo(y,j);g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(v)}async function Ki(a){let g=Date.now();if(ft&&g<ft.expires){_(a,200,ft.data);return}try{let{scanForComponents:j}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:v}=await import("./render-generator-HWFLZYC3.mjs"),T=await j(r);ft={data:T,expires:g+5e3},v(T,r,Ft).then(S=>{Ft=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,T)}catch(j){console.error("[Bridge] Scanner error:",j),_(a,500,{error:"Failed to scan components"})}}async function Qi(a){let g=[Ae(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ae(r,"packages","popmelt","dist","canvas.mjs")];try{let j=fd(import.meta.url);g.unshift(Ae(md(j),"canvas.mjs"))}catch{}for(let j of g)try{let v=await Wo(j,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(v);return}catch{}console.error("[Bridge] Canvas bundle not found in:",g),_(a,404,{error:"Canvas bundle not found"})}async function Xi(a,g){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(g,400,{error:"Invalid filename"});return}try{let j=[Ae(c,a),Ae(r,".popmelt","artifacts","thread-media",a),Ae(r,".popmelt","artifacts","eval-screenshots",a),Ae(r,".popmelt","evals","screenshots",a),Ae(r,".popmelt","screenshots",a)],v;for(let A of j)try{v=await Wo(A);break}catch{}if(!v)throw new Error("File not found");let T=a.split(".").pop()?.toLowerCase(),S=T==="png"?"image/png":T==="webp"?"image/webp":T==="jpg"||T==="jpeg"?"image/jpeg":"application/octet-stream";g.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),g.end(v)}catch{_(g,404,{error:"File not found"})}}function fn(a){return`/files/${ro(a)}`}async function Yi(a,g){let j=await V.getThread(a);if(!j){_(g,404,{error:"Thread not found"});return}let v=j.messages.some(D=>D.role==="assistant"&&D.responseText?.includes("<eval_run_result>")),T=j.messages.filter(D=>D.role==="assistant"&&D.responseText?.includes("Model suggestion ready")),[S,A]=await Promise.all([v?q.getJournalEvalRuns().then(D=>D.filter(N=>N.threadId===a).sort((N,Q)=>Q.completedAt-N.completedAt)[0]):Promise.resolve(void 0),T.length>0?se.findModelProposalsByThread(a):Promise.resolve([])]),J=S?await q.findJournalEvalCase(S.evalId):null,B=await Promise.all(A.map(async(D,N)=>{if(D.authorityStatus==="accepted")return D;let Q=(await Promise.all(D.decisionIds.map(W=>q.findPendingProposalForLegacyDecision(W)))).find(Boolean);return{...D,authorityStatus:"legacy_untrusted",presentationJobId:D.presentationJobId??T[N]?.jobId??T.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),z=[...B].sort((D,N)=>N.updatedAt-D.updatedAt)[0]??null,F=j.messages.map(({screenshotPath:D,screenshotPaths:N,imagePaths:Q,replyImagePaths:W,...ie})=>({...ie,...ie.role==="assistant"&&S&&ie.responseText?.includes("<eval_run_result>")?{evalRun:{...S,title:J?.title}}:{},...D?{screenshotUrl:fn(D)}:{},...N?{screenshotUrls:Object.fromEntries(Object.entries(N).map(([ce,te])=>[ce,fn(te)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ce,te])=>[ce,te.map(fn)]))}:{},...W?{replyImageUrls:W.map(fn)}:{}}));_(g,200,{id:j.id,createdAt:j.createdAt,messages:F,modelProposal:z,modelProposals:B})}async function Zi(a,g){let j=decodeURIComponent(a);if(!await V.deleteThread(j)){_(g,404,{deleted:!1,error:"Thread not found"});return}_(g,200,{deleted:!0})}let Qo=9,Xo=!1;for(let a=n;a<n+Qo;a++)try{await jd(zt,a),y=a,Xo=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(g){if(g.code==="EADDRINUSE"){let j=await ao(a);if(cn(j,{projectId:i,version:st,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw g}if(!Xo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Qo-1} in use`);for(let[a,g]of Object.entries(h))!g.available||!g.path||u(a,g.path).then(j=>{if(j)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),g.available=!1,g.path=null;for(let v of Y)io(v,{type:"capabilities_changed",data:{}})}});let es=setInterval(()=>{Ci(c).catch(()=>{})},yd),Yo=setInterval(()=>{M.expireStale().becameEmpty&&ye()},Id);return Yo.unref?.(),{port:y,projectId:i,close:async()=>{clearInterval(es),clearInterval(Yo),ne(),M.clear(),await I.destroyAsync(),b.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{zt.close(()=>a())})}}}async function Ci(o){try{let e=await ad(o),n=Date.now();for(let t of e){let r=Ae(o,t);try{let i=await dd(r);n-i.mtimeMs>vd&&await ld(r)}catch{}}}catch{}}import{randomUUID as Ad}from"crypto";var Md=5e3,_d=250;function Vo(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function Ni(o,e=fetch){let n=`${process.pid}-${Ad()}`,t=`http://127.0.0.1:${o.port}`,r=!1,i=!1,s=async()=>(await e(`${t}/leases`,{method:"POST",headers:Vo(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(w){return console.warn("[popmelt] failed to register bridge lease:",w instanceof Error?w.message:String(w)),null}let c=async()=>{if(!(r||i)){i=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:Vo(o)})).status===404&&!r&&await s()}catch{}finally{i=!1}}},d=setInterval(()=>{c()},Md);return d.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(d);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:Vo(o),keepalive:!0})}catch{}}}}}function Bi(o,e=process){let n=!1,t=new Map,r=()=>{if(!n){n=!0;for(let[i,s]of t)e.removeListener(i,s);t.clear()}};for(let i of["SIGINT","SIGTERM"]){let s=()=>{let c=e.listenerCount(i),d=o.release();if(c>0)return;let l=new Promise(w=>{setTimeout(w,_d)});Promise.race([d,l]).finally(()=>{r(),e.kill(e.pid,i)})};t.set(i,s),e.prependOnceListener(i,s)}return r}var zd=1111,Li=3e4,Ud=8e3;async function qd(o){return Bd(o).catch(()=>o)}async function Fi(o,e){let t=(await Nd(e,"utf8").catch(()=>"")).slice(-Ud).trim();return new Error(t?`${o}
239
239
  Bridge log (${e}):
240
- ${t}`:o)}async function Nu(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 Bd(o);if(o.manageLease===!1)return n;let t=await As({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let r=_s(t);return{...n,close:async()=>{r(),await t.release()}}}let e=await Ms(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Bd(o){let e=o.port??Dd,n=await Nd(o.projectRoot??process.cwd()),t=Yn(n);for(let R=e;R<e+10;R++){let I=await oo(R);if(I&&I.projectId===t){if(I.version&&I.version!==rt){if(I.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${R}/shutdown`,{method:"POST"})}catch{}await new Promise(g=>setTimeout(g,500));break}continue}if(!sn(I,{projectId:t,version:rt,restartMode:"detached"}))continue;let b=o.devOrigin;if(b&&I.devOrigin!==b)try{await fetch(`http://127.0.0.1:${R}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:b})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(R),process.env.POPMELT_PROJECT_ID=t,{port:R,projectId:t,close:async()=>{}}}}let r=qo($d(Od(import.meta.url)),"bridge-entry.mjs"),s=qo(n,".popmelt"),i=qo(s,"bridge.log");await Ad(s,{recursive:!0}),await Md(i,`
240
+ ${t}`:o)}async function qu(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 Hd(o);if(o.manageLease===!1)return n;let t=await Ni({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let r=Bi(t);return{...n,close:async()=>{r(),await t.release()}}}let e=await Ji(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Hd(o){let e=o.port??zd,n=await qd(o.projectRoot??process.cwd()),t=oo(n);for(let k=e;k<e+10;k++){let P=await ao(k);if(P&&P.projectId===t){if(P.version&&P.version!==st){if(P.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${k}/shutdown`,{method:"POST"})}catch{}await new Promise(m=>setTimeout(m,500));break}continue}if(!cn(P,{projectId:t,version:st,restartMode:"detached"}))continue;let x=o.devOrigin;if(x&&P.devOrigin!==x)try{await fetch(`http://127.0.0.1:${k}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:x})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(k),process.env.POPMELT_PROJECT_ID=t,{port:k,projectId:t,close:async()=>{}}}}let r=Ko(Ld(Fd(import.meta.url)),"bridge-entry.mjs"),i=Ko(n,".popmelt"),s=Ko(i,"bridge.log");await Jd(i,{recursive:!0}),await Dd(s,`
241
241
  [${new Date().toISOString()}] Starting detached bridge
242
- `);let d=Ed(i,"a"),c;try{c=Td(process.execPath,[r],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{jd(d)}let l=null;c.once("error",R=>{l=`spawn error: ${R.message}`}),c.once("exit",(R,I)=>{l=`child exited before becoming healthy (${I?`signal ${I}`:`code ${R??"unknown"}`})`}),c.unref();let h=Date.now()+Cs;for(;Date.now()<h;){if(await new Promise(R=>setTimeout(R,100)),l)throw await $s(`[Bridge] Detached bridge ${l}`,i);for(let R=e;R<e+10;R++){let I=await oo(R);if(sn(I,{projectId:t,version:rt,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(R),process.env.POPMELT_PROJECT_ID=t,{port:R,projectId:t,close:async()=>{}}}}throw c.kill("SIGTERM"),await $s(`[Bridge] Detached bridge failed to start within ${Cs/1e3}s (port ${e})`,i)}export{Dt as ImprintService,Ot as ImprintStore,Wn as formatImprintPrompt,Hn as parseImprintDraft,Nu as startPopmelt};
242
+ `);let c=Od(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{$d(c)}let l=null;d.once("error",k=>{l=`spawn error: ${k.message}`}),d.once("exit",(k,P)=>{l=`child exited before becoming healthy (${P?`signal ${P}`:`code ${k??"unknown"}`})`}),d.unref();let w=Date.now()+Li;for(;Date.now()<w;){if(await new Promise(k=>setTimeout(k,100)),l)throw await Fi(`[Bridge] Detached bridge ${l}`,s);for(let k=e;k<e+10;k++){let P=await ao(k);if(cn(P,{projectId:t,version:st,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(k),process.env.POPMELT_PROJECT_ID=t,{port:k,projectId:t,close:async()=>{}}}}throw d.kill("SIGTERM"),await Fi(`[Bridge] Detached bridge failed to start within ${Li/1e3}s (port ${e})`,s)}export{Jt as ImprintService,Dt as ImprintStore,Xn as formatImprintPrompt,Qn as parseImprintDraft,qu as startPopmelt};