@popmelt.com/core 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{mkdir as Sd,unlink as Pd,writeFile as kd}from"fs/promises";import{join as js}from"path";import{execFileSync as Xn,spawn as gs}from"child_process";import{createHash as Ps,randomUUID as pt}from"crypto";import{mkdir as Yc,readFile as No,readdir as Zc,realpath as ed,stat as td,unlink as nd,writeFile as an}from"fs/promises";import{createServer as od}from"http";import{tmpdir as rd}from"os";import{basename as Vn,dirname as sd,isAbsolute as Bo,join as Me,relative as ys,resolve as ks}from"path";import{fileURLToPath as id}from"url";function Uo(o,e){return`<!DOCTYPE html>
1
+ import{mkdir as Jc,unlink as Nc,writeFile as Bc}from"fs/promises";import{join as li}from"path";import{execFileSync as lc,spawn as ti}from"child_process";import{randomUUID as Mt}from"crypto";import{mkdir as pc,readFile as ni,readdir as uc,realpath as mc,stat as fc,unlink as hc,writeFile as Ln}from"fs/promises";import{createServer as gc}from"http";import{tmpdir as yc}from"os";import{basename as Fn,dirname as vc,isAbsolute as ai,join as Ee,relative as Ic,resolve as wc}from"path";import{fileURLToPath as bc}from"url";function _o(o,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -25,75 +25,19 @@ import{mkdir as Sd,unlink as Pd,writeFile as kd}from"fs/promises";import{join as
25
25
  });
26
26
  </script>
27
27
  </body>
28
- </html>`}var Gs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Vs=new Set(["default","flex","fast","priority"]);function gt(o){let e=typeof o.reasoningEffort=="string"&&Gs.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Vs.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function ln(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as Ks}from"child_process";import{createInterface as Qs}from"readline";var Xs=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),qo=1e5;function Ys(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Xs.has(n))return;let t;if(o.name==="Write"&&typeof o.input?.content=="string"?t=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(t=o.input.new_string),!!t)return t.length>qo?t.slice(0,qo)+`
29
- \u2026[truncated]`:t}function pn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:v,timeoutMs:R=3e5,onEvent:b}=e,I=[];d?I.push("--resume",d,"-p",n):I.push("-p",n),I.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(s)),l&&I.push("--model",l),v&&I.push("--effort",v);for(let h of i)I.push("--allowedTools",h);let g=Ks(c,I,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(h=>{let f,y=[],x=[],S=[],A=!1,J="",_,N,T=!1,B=setTimeout(()=>{T=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},R),W=Qs({input:g.stdout}),ee=new Set;W.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&&y.length===0){let X=typeof ne.result=="string"?ne.result:"";X&&(y.push(X),b?.({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&&(y.push(X.text),b?.({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=Ys(X);if(b?.({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&&b?.({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&&b?.({type:"tool_use",jobId:o,tool:"Read",file:ne.tool_use_result.file.filePath},o)}catch{}});let H=[];g.stderr?.on("data",te=>{H.push(te.toString())}),g.on("close",te=>{if(clearTimeout(B),W.close(),y.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=H.join("").trim(),X=y.join("").trim(),G=y.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=Zs(J,_);h({sessionId:f,text:y.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,h({sessionId:f,text:y.join(""),success:!1,error:J,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})})});return{process:g,result:p}}function Zs(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 ei,spawnSync as Qo}from"child_process";import{readFileSync as ti,statSync as ni}from"fs";import{basename as oi,extname as ri,isAbsolute as si,relative as Xo,resolve as ii}from"path";import{createInterface as ai}from"readline";function Wo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Ho=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"]),to=2e5,ci=1e5,Yo=2e5;function Zo(o){let e=oi(o).toLowerCase(),n=ri(o).toLowerCase();return Ho.has(n)||Ho.has(e)}function Lt(o,e){let n=si(e)?e:ii(o,e),t=Xo(o,n);return t===""||t.startsWith("..")?null:n}function un(o,e){if(!Zo(e))return;let n=Lt(o,e);if(n)try{let t=ni(n);return t.isFile()?t.size>to?{exists:!0,truncated:!0}:{exists:!0,content:ti(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function di(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function li(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 Go(o){return di(o,["patch","diff","unifiedDiff","unified_diff"])}function no(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Vo(o,e){let n=Qo("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Yo+65536});return n.status!==0?null:n.stdout??""}function pi(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 Ko(o){let e=Vo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Vo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=no(n,Yo);return{status:e,changedFiles:pi(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function ui(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function mi(o,e){if(!Zo(e))return;let n=Lt(o,e);if(!n)return;let t=Xo(o,n);if(t===""||t.startsWith(".."))return;let r=Qo("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:to+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=no(s,to);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function fi(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):mi(o,t),s=un(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function mn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,v=[];if(s){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let I of l)v.push("-c",I);i&&v.push("-m",i),v.push(s),v.push(n),r&&v.push("--image",r)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let I of l)v.push("-c",I);i&&v.push("-m",i),v.push(n),r&&v.push("--image",r)}let R=ei("codex",v,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),b=new Promise(I=>{let g,p=[],h=[],f=[],y=new Map,x=new Map,S=!1,A="",J=ai({input:R.stdout}),_=new Set;J.on("line",T=>{if(T.trim())try{let B=JSON.parse(T),W=B.type??"unknown";if(_.add(W),W==="thread.started"&&B.thread_id&&!g&&(g=B.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),c?.({type:"delta",jobId:o,text:B.delta.text},o)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&B.delta?.text&&c?.({type:"thinking",jobId:o,text:B.delta.text},o),(W==="item.started"||W==="item/started")&&B.item){let ee=B.item.type;if(ee==="command_execution"){let H=B.item.command,te=H?Wo(H):void 0,ne=Ko(t),ge=new Map;for(let G of ne?.changedFiles??[])ge.set(G,un(t,G));typeof B.item.id=="string"&&x.set(B.item.id,{...H?{rawCommand:H}:{},...te?{command:te}:{},...ne?{beforeWorktree:ne}:{},beforeSnapshots:ge});let X=te?`Bash: ${te.split(`
31
- `)[0].slice(0,80)}`:"Bash";h.push(X),c?.({type:"tool_use",jobId:o,tool:"Bash",...te?{content:te}:{}},o)}else if(ee==="file_change"){let H=B.item.filename||B.item.path;H&&!y.has(H)&&y.set(H,un(t,H)),h.push(H?`Edit ${H.split("/").pop()}`:"Edit");let te=H?Lt(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...te?{file:te}:{}},o)}else if(ee==="file_read"){let H=B.item.filename||B.item.path;h.push(H?`Read ${H.split("/").pop()}`:"Read");let te=H?Lt(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...te?{file:te}:{}},o)}else if(ee==="web_search")h.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(ee==="mcp_tool_call"){let H=B.item.tool_name||B.item.name||"MCP";h.push(H),c?.({type:"tool_use",jobId:o,tool:H},o)}}if((W==="item.completed"||W==="item/completed")&&B.item){if(B.item.type==="agent_message"){let ee=B.item.text;typeof ee=="string"&&ee&&(p.push(ee),c?.({type:"delta",jobId:o,text:ee},o))}else if(B.item.type==="reasoning"){let ee=B.item.text;typeof ee=="string"&&ee&&c?.({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 H=ee.path||ee.filename,te=ee.kind==="add"?"Write":"Edit";if(H){h.push(`${te} ${H.split("/").pop()}`);let ne=Lt(t,H)??H;c?.({type:"tool_use",jobId:o,tool:te,file:ne},o);let ge=ee,X=typeof ge.kind=="string"?ge.kind:void 0,G=li(X),U=y.get(H),he=un(t,H);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:H,...U?{before:U}:{},...he?{after:he}:{},...Go(ge)?{patch:Go(ge)}:{},...X?{rawKind:X}:{}}),y.set(H,he)}}else if(B.item.type==="command_execution"){let ee=typeof B.item.id=="string"?B.item.id:void 0,H=ee?x.get(ee):void 0,te=typeof B.item.command=="string"?B.item.command:H?.rawCommand,ne=te?Wo(te):H?.command,ge=Ko(t);if(ui(H?.beforeWorktree,ge)){let X=[...new Set([...H?.beforeWorktree?.changedFiles??[],...ge?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?no(B.item.aggregated_output,ci):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}:{},...H?.beforeWorktree?{beforeWorktree:H.beforeWorktree}:{},...ge?{afterWorktree:ge}:{},...X.length>0?{touchedFiles:fi(t,X,H?.beforeSnapshots??new Map)}:{}})}ee&&x.delete(ee)}}W==="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}`),I({sessionId:g,text:p.join(""),success:!S,error:S?A:void 0,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})}),R.on("error",T=>{S=!0,A=T.message,I({sessionId:g,text:p.join(""),success:!1,error:A,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})})});return{process:R,result:b}}import{spawn as hi}from"child_process";import{createInterface as gi}from"readline";function er(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 tr(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:s,timeoutMs:i=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),s&&l.push("--model",s),l.push("-p",n);let v=hi(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(b=>{let I,g=[],p=[],h=!1,f="",y=!1,x=setTimeout(()=>{y=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},i),S=gi({input:v.stdout}),A=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Ut(T);A.add(B),J.length<5&&vi(B)&&J.push(N.slice(0,800));let W=zt(T,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!I&&(I=W);let ee=yi(T,g.length===0);ee&&(g.push(ee),c?.({type:"delta",jobId:o,text:ee},o));let H=wi(T);H&&c?.({type:"thinking",jobId:o,text:H},o);let te=Ii(T);te&&(p.push(te.label),c?.({type:"tool_use",jobId:o,tool:te.tool,...te.file?{file:te.file}:{},...te.content?{content:te.content}:{}},o));let ne=bi(T);ne&&(h=!0,f=ne)}catch{}});let _=[];v.stderr?.on("data",N=>{_.push(N.toString())}),v.on("close",N=>{clearTimeout(x),S.close(),g.length===0&&A.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),J.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${J.join(`
32
- `)}`)),y?(h=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(h=!0,f=_.join("").trim()||f||`Copilot process exited with code ${N}`);let T=h?er(f,s):null;b({sessionId:I,text:g.join(""),success:!h,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),v.on("error",N=>{clearTimeout(x);let T=er(N.message,s);b({sessionId:I,text:g.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:v,result:R}}function Ut(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 yi(o,e=!1){let n=Ut(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Fe(o.delta)??Fe(o.content)??Fe(o.message);if(n==="assistant.message"&&e)return Fe(o.message)??Fe(o.content)??Fe(o);if(n==="result"&&e)return Fe(o.result)??Fe(o.output)??Fe(o.message)??Fe(o);let s=o.content;if(s?.type==="text"&&typeof s.text=="string")return s.text;if(typeof o.text=="string"&&oo(o))return o.text;if(typeof o.message=="string"&&oo(o))return o.message;if(typeof o.delta=="string"&&oo(o))return o.delta}function Fe(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Fe).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Fe(e[n]);if(t)return t}}function vi(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function wi(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 Ii(o){let e=zt(o,["tool","toolName","tool_name","name"]),n=zt(o,["command","cmd"]),t=zt(o,["file","path","filename","filePath"]),r=Ut(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 bi(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"&&Ut(o).toLowerCase().includes("error"))return o.message}function zt(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(i=>t.toLowerCase().includes(i)))continue;let s=zt(r,e);if(s)return s}}function oo(o){let e=Ut(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as xi,readFile as Si}from"fs/promises";import{join as ro}from"path";var fn=class{constructor(e){let n=ro(e,".popmelt");this.decisionsDir=ro(n,"decisions")}async listDecisionIds(){try{return(await xi(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 Si(ro(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 or(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=Ai(t.assertionResults,e),s=_i(r);return{status:s,summary:tt(t.summary)||ar(s),assertionResults:r,tooling:Ci(t.tooling)}}catch{}return{status:"needs_review",summary:$i(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 rr(o,e){let n=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length?[y.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(y=>y.path),s=[...new Set(r.map(y=>y.map(String).join(".")).filter(Boolean))].map(y=>({kind:"model_path",value:y}));if(s.length===0||o.decisionIds.length===0)return[];let i=new Set(o.decisionIds),c=new Set(s.map(y=>y.value)),d=e.cases.find(y=>y.status!=="rejected"&&(y.sourceDecisionIds.some(x=>i.has(x))||(y.dependencies??[]).some(x=>x.kind==="model_path"&&c.has(x.value)))),l=(o.selectedChanges??[]).find(y=>y.label?.trim())?.label?.trim()??t.find(y=>y.label?.trim())?.label?.trim()??o.title,v=d?.id.startsWith("eval-model-")??!1,R=(o.selectedChanges??[]).flatMap(y=>Array.isArray(y.path)&&y.path.length>0?[{path:y.path,value:y.value,label:y.label,detail:y.detail}]:[]),I=(R.length>0?R:t.map(y=>({path:y.path,value:y.value,label:y.label,detail:y.rationale}))).flatMap(y=>Pi(y,o.decisionIds)),g=gn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!v?d.assertions:[],...I,...I.length===0&&g?[g]:[]])],h=s[0].value,f=h.startsWith("components.")?"component":h.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!v?d.title:l,status:"pending",category:d?.category??f,prompt:d&&!v?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!v?d.rationale:Ti(h),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...s].map(y=>[`${y.kind}:${y.value}`,y])).values()]}]}function Pi(o,e){let n=String(o.path[0]??"");if(n==="rules")return ki(o.value,e);if(n==="components"){let i=sr(String(o.path[1]??o.label??"component")),c=hn(o.value),d=c?Wt(c.usage):[];if(d.length>0){let v=ji(d),R=d.length===1?"uses":"use";return[`The ${v} ${R} the same shared implementation for the ${i} pattern.`]}if(c?.shared===!0)return[`The product uses a shared implementation for the ${i} pattern.`];let l=c?tt(c.constraint):"";if(l){let v=Ri(l,i);if(v)return[v]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),c=hn(o.value),d=c&&"value"in c?c.value:o.value,l=Ei(d);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=hn(o.value),r=t?tt(t.text)||tt(t.constraint):typeof o.value=="string"?o.value:"",s=gn(r||o.detail||"");return s?[s]:[]}function ki(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let c=hn(i),d=c?tt(c.text):"";return d?[{text:d,sources:c?Wt(c.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(i=>gn(i.text)).filter(i=>!!i)}function Ri(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?Pt(`Wherever ${qt(n[1])}, the shared ${e} implementation is used instead of ${qt(n[2])}`):gn(o)}function so(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Pt(`${nr(n[1])} is ${qt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Pt(nr(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Pt(`The product uses ${qt(r[1])}`);let s=e.match(/^Do not (.+?)\.?$/i);return s?Pt(`The product does not ${qt(s[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Pt(e)}var gn=so;function Ti(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${sr(e[1]??"component")} contract across its declared product surfaces.`:e[0]==="tokens"?`Protects the ${e.slice(1).join(".")} token from implementation drift.`:e[0]==="rules"?"Protects an enforceable product rule across its declared scope.":"Protects an enforceable product expectation across its declared scope."}function hn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function sr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function ji(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 Ei(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function Pt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function nr(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function qt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function ir(o){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
34
-
35
- ## Eval
36
- \`\`\`json
37
- ${JSON.stringify(o.evalCase,null,2)}
38
- \`\`\`
39
-
40
- ## Scope
41
- \`\`\`json
42
- ${JSON.stringify(o.scope,null,2)}
43
- \`\`\`
44
-
45
- ## Current Design Model
46
- \`\`\`json
47
- ${JSON.stringify(o.model??null,null,2)}
48
- \`\`\`
49
-
50
- ## Evidence
51
- - Current page screenshot: ${o.screenshotPath}
52
- - Chrome DevTools MCP is ${o.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
53
-
54
- ## Instructions
55
- 1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
56
- 2. Compare the runtime URL, component evidence, and visible state with the eval's declared scenarios. If the runtime does not satisfy an applicable declared scenario, mark affected assertions "needs_review" and name the scope mismatch instead of guessing.
57
- 3. Use the screenshot as baseline evidence.
58
- 4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
59
- 5. Judge each assertion independently as "pass", "fail", or "needs_review".
60
- 6. Keep failures actionable and grounded in observed evidence.
61
- 7. Do not propose visual markers yet.
62
- 8. End with exactly one machine-readable <eval_run_result> block.
63
- 9. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
64
- 10. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
65
-
66
- The block must be valid JSON with this shape:
67
-
68
- \`\`\`json
69
- {
70
- "status": "pass",
71
- "summary": "Short run summary.",
72
- "assertionResults": [
73
- {
74
- "assertion": "Original assertion text",
75
- "status": "pass",
76
- "summary": "What was observed.",
77
- "evidence": ["Screenshot shows ...", "DOM selector ..."]
78
- }
79
- ],
80
- "tooling": {
81
- "chromeDevtools": "available",
82
- "evidenceTypes": ["screenshot", "dom", "computed_styles"]
83
- }
84
- }
85
-
86
- \`\`\`
87
-
88
- Allowed statuses: pass, fail, needs_review.
89
- Allowed chromeDevtools values: available, unavailable, unknown.`}function tt(o){return typeof o=="string"?o.trim():""}function Wt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Mi(o){let e=tt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ai(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:Mi(s.status)??"needs_review",summary:tt(s.summary)||ar("needs_review"),evidence:Wt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function _i(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Ci(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:Wt(e.evidenceTypes).length>0?Wt(e.evidenceTypes):["screenshot"]}}function ar(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 $i(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Oi}from"crypto";import{mkdir as Di,writeFile as Ji}from"fs/promises";import{join as io}from"path";var yn=class{constructor(e){this.root=io(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=io(this.root,"eval-screenshots"),t=Oi("sha256").update(e).digest("hex"),r=io(n,`${t}.webp`);return await Di(n,{recursive:!0}),await Ji(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as cr}from"crypto";import{mkdir as ao,readFile as co,writeFile as vn}from"fs/promises";import{dirname as lo,join as kt}from"path";var We="[ProjectionWorker]",Ni={version:1,runs:[]},Bi={version:1,updatedAt:0,proposals:[]},Fi=12;function Li(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 dr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function zi(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ui(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let g of s){if(!g||typeof g!="object")continue;let p=g.sources;if(Array.isArray(p))for(let h of p)typeof h=="string"&&t.has(h)&&r.add(h)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,h=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(h)!==JSON.stringify(g)}).length,v=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(v[g])).length,I=Object.keys(c).filter(g=>JSON.stringify(c[g])!==JSON.stringify(R[g])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:I,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function qi(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Wi(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function wn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Wi(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=qi(n)}function lr(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 Hi(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 Gi(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 pr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Hi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Gi(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var In=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=kt(e,".popmelt");this.runsPath=kt(t,"projection-runs.json"),this.legacyRunsPath=kt(t,"materialization-runs.json"),this.proposalsPath=kt(t,"projection-queue.json"),this.legacyProposalsPath=kt(t,"model-proposals.json"),this.modelPath=kt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await co(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Li(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?lr(n,r):wn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Fi),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let s=r.map(g=>g.id);console.log(`${We} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),c=Xi(r,i),d=zi(r,t.totalCandidateDecisionCount,c);n=cr().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:s,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let v=!0,R,b,I;try{let g=`projection-${Date.now()}`,{provider:p,result:h}=this.spawnModelAgent(g,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await h;if(!f.success)v=!1,R=f.error,console.error(`${We} ${p} spawn error:`,R);else{let y=Qi(f.text,s);if(y){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of y)wn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=dr(x.rules));let S=Ui(x,s,i);if(y){let J=[...new Set(y.flatMap(_=>_.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(_=>!J.includes(_))}b=S;let A=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:b,changes:y});I=A.id,console.log(`${We} Created model proposal ${A.id} for ${s.length} decision(s)`)}else v=!1,R="No valid bounded <model-changes> block found in response",console.error(`${We} ${R}`)}}catch(g){v=!1,R=g instanceof Error?g.message:String(g),console.error(`${We} Error:`,R)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:b,proposalId:I}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:v,error:R}),{processedIds:s,success:v,error:R,runId:n,proposalId:I}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=dr(e.rules)),await vn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await ao(lo(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2)),n):{...Ni,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??{...Bi,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let s=structuredClone(t);for(let i of r.changes??[])wn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?lr(i,d.path):wn(i,d.path,d.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let c=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(c.evalId),s.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:cr().slice(0,8),status:"pending",title:Vi(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"}.`:Ki(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 ao(lo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await vn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await ao(lo(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await co(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await co(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return s==="codex"?{provider:"codex",...mn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:ln(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...pn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:s==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:i})})}};function Vi(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 Ki(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Qi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,c)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let d=i;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(R=>typeof R=="string"||typeof R=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let v=Array.isArray(d.decisionIds)?d.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Xi(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(`
95
-
96
- `),t=o.map(s=>s.id);return`You are extracting a local design model from accumulated design decisions.
28
+ </html>`}var xi=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Si=new Set(["default","flex","fast","priority"]);function ht(o){let e=typeof o.reasoningEffort=="string"&&xi.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Si.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function rn(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 ki}from"child_process";import{createInterface as Ri}from"readline";var Pi=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"]),Co=1e5;function Ti(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Pi.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>Co?t.slice(0,Co)+`
29
+ \u2026[truncated]`:t}function sn(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:u,reasoningEffort:x,timeoutMs:T=3e5,onEvent:P}=e,b=[];d?b.push("--resume",d,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),u&&b.push("--model",u),x&&b.push("--effort",x);for(let y of s)b.push("--allowedTools",y);let f=ki(c,b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),l=new Promise(y=>{let m,I=[],p=[],k=[],A=!1,g="",E,$,h=!1,M=setTimeout(()=>{h=!0,f.kill("SIGTERM"),setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},5e3)},T),O=Ri({input:f.stdout}),N=new Set;O.on("line",K=>{if(K.trim())try{let Z=JSON.parse(K);Z.session_id&&!m&&(m=Z.session_id);let re=Z.type??(Z.event?.type?`event.${Z.event.type}`:"unknown");if(N.add(re),Z.type==="result"&&Z.result&&I.length===0){let D=typeof Z.result=="string"?Z.result:"";D&&(I.push(D),P?.({type:"delta",jobId:o,text:D},o))}if(Z.type==="assistant"&&Array.isArray(Z.message?.content)){typeof Z.error=="string"&&(E=Z.error);for(let D of Z.message.content){if(D.type==="text"&&D.text&&(I.push(D.text),P?.({type:"delta",jobId:o,text:D.text},o)),D.type==="tool_use"&&D.name){let V=D.input?.file_path||D.input?.path||void 0,he=Ti(D);if(P?.({type:"tool_use",jobId:o,tool:D.name,...V?{file:V}:{},...he?{content:he}:{}},o),D.name==="Edit"&&D.input?.file_path){let L={tool:"Edit",file_path:D.input.file_path,old_string:D.input.old_string,new_string:D.input.new_string,replace_all:D.input.replace_all};p.push(L),k.push({sequence:k.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:L.file_path,oldString:typeof L.old_string=="string"?L.old_string:void 0,newString:typeof L.new_string=="string"?L.new_string:void 0,replaceAll:typeof L.replace_all=="boolean"?L.replace_all:void 0})}else D.name==="Write"&&D.input?.file_path&&(p.push({tool:"Write",file_path:D.input.file_path,content:D.input.content}),k.push({sequence:k.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:D.input.file_path,content:typeof D.input.content=="string"?D.input.content:void 0}))}D.type==="thinking"&&D.thinking&&P?.({type:"thinking",jobId:o,text:D.thinking},o)}}Z.type==="result"&&Z.is_error===!0&&(A=!0,typeof Z.error=="string"&&(E=Z.error),typeof Z.result=="string"&&($=Z.result)),Z.type==="user"&&Z.tool_use_result?.file?.filePath&&P?.({type:"tool_use",jobId:o,tool:"Read",file:Z.tool_use_result.file.filePath},o)}catch{}});let z=[];f.stderr?.on("data",K=>{z.push(K.toString())}),f.on("close",K=>{if(clearTimeout(M),O.close(),I.length===0&&N.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...N].join(", ")}`),h)A=!0,g=`Timed out after ${Math.round(T/6e4)} minutes`;else if(K!==0&&K!==null){A=!0;let re=z.join("").trim(),D=I.join("").trim(),V=I.length===0&&N.size>0?` (no text captured, event types: ${[...N].join(", ")})`:"";g=re||$||D||`Claude process exited with code ${K}${V}`}A&&!g&&$&&(g=$);let Z=ji(g,E);y({sessionId:m,text:I.join(""),success:!A,error:A?Z.message:void 0,errorCode:A?Z.code:void 0,recoverableError:A?Z.recoverable:void 0,fileEdits:p.length>0?p:void 0,editEvents:k.length>0?k:void 0})}),f.on("error",K=>{clearTimeout(M),A=!0,g=K.message,y({sessionId:m,text:I.join(""),success:!1,error:g,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:p.length>0?p:void 0,editEvents:k.length>0?k:void 0})})});return{process:f,result:l}}function ji(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 Mi,spawnSync as Bo}from"child_process";import{readFileSync as Ai,statSync as Ei}from"fs";import{basename as _i,extname as Ci,isAbsolute as $i,relative as Lo,resolve as Oi}from"path";import{createInterface as Di}from"readline";function $o(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Oo=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"]),Vn=2e5,Ji=1e5,Fo=2e5;function qo(o){let e=_i(o).toLowerCase(),n=Ci(o).toLowerCase();return Oo.has(n)||Oo.has(e)}function $t(o,e){let n=$i(e)?e:Oi(o,e),t=Lo(o,n);return t===""||t.startsWith("..")?null:n}function an(o,e){if(!qo(e))return;let n=$t(o,e);if(n)try{let t=Ei(n);return t.isFile()?t.size>Vn?{exists:!0,truncated:!0}:{exists:!0,content:Ai(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Ni(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function Bi(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 Do(o){return Ni(o,["patch","diff","unifiedDiff","unified_diff"])}function Kn(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Jo(o,e){let n=Bo("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Fo+65536});return n.status!==0?null:n.stdout??""}function Li(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 No(o){let e=Jo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Jo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=Kn(n,Fo);return{status:e,changedFiles:Li(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 qi(o,e){if(!qo(e))return;let n=$t(o,e);if(!n)return;let t=Lo(o,n);if(t===""||t.startsWith(".."))return;let r=Bo("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Vn+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=Kn(i,Vn);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Ui(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):qi(o,t),i=an(o,t);return{filePath:t,...r?{before:r}:{},...i?{after:i}:{}}})}function cn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:i,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:u=[]}=e,x=[];if(i){x.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let b of u)x.push("-c",b);s&&x.push("-m",s),x.push(i),x.push(n),r&&x.push("--image",r)}else{x.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let b of u)x.push("-c",b);s&&x.push("-m",s),x.push(n),r&&x.push("--image",r)}let T=Mi("codex",x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),P=new Promise(b=>{let f,l=[],y=[],m=[],I=new Map,p=new Map,k=!1,A="",g=Di({input:T.stdout}),E=new Set;g.on("line",h=>{if(h.trim())try{let M=JSON.parse(h),O=M.type??"unknown";if(E.add(O),O==="thread.started"&&M.thread_id&&!f&&(f=M.thread_id),(O==="item.agentMessage.delta"||O==="item/agentMessage/delta")&&M.delta?.text&&(l.push(M.delta.text),c?.({type:"delta",jobId:o,text:M.delta.text},o)),(O==="item.reasoning.delta"||O==="item/reasoning/delta")&&M.delta?.text&&c?.({type:"thinking",jobId:o,text:M.delta.text},o),(O==="item.started"||O==="item/started")&&M.item){let N=M.item.type;if(N==="command_execution"){let z=M.item.command,K=z?$o(z):void 0,Z=No(t),re=new Map;for(let V of Z?.changedFiles??[])re.set(V,an(t,V));typeof M.item.id=="string"&&p.set(M.item.id,{...z?{rawCommand:z}:{},...K?{command:K}:{},...Z?{beforeWorktree:Z}:{},beforeSnapshots:re});let D=K?`Bash: ${K.split(`
31
+ `)[0].slice(0,80)}`:"Bash";y.push(D),c?.({type:"tool_use",jobId:o,tool:"Bash",...K?{content:K}:{}},o)}else if(N==="file_change"){let z=M.item.filename||M.item.path;z&&!I.has(z)&&I.set(z,an(t,z)),y.push(z?`Edit ${z.split("/").pop()}`:"Edit");let K=z?$t(t,z)??z:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...K?{file:K}:{}},o)}else if(N==="file_read"){let z=M.item.filename||M.item.path;y.push(z?`Read ${z.split("/").pop()}`:"Read");let K=z?$t(t,z)??z:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...K?{file:K}:{}},o)}else if(N==="web_search")y.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(N==="mcp_tool_call"){let z=M.item.tool_name||M.item.name||"MCP";y.push(z),c?.({type:"tool_use",jobId:o,tool:z},o)}}if((O==="item.completed"||O==="item/completed")&&M.item){if(M.item.type==="agent_message"){let N=M.item.text;typeof N=="string"&&N&&(l.push(N),c?.({type:"delta",jobId:o,text:N},o))}else if(M.item.type==="reasoning"){let N=M.item.text;typeof N=="string"&&N&&c?.({type:"thinking",jobId:o,text:N},o)}else if(M.item.type==="file_change"&&Array.isArray(M.item.changes))for(let N of M.item.changes){let z=N.path||N.filename,K=N.kind==="add"?"Write":"Edit";if(z){y.push(`${K} ${z.split("/").pop()}`);let Z=$t(t,z)??z;c?.({type:"tool_use",jobId:o,tool:K,file:Z},o);let re=N,D=typeof re.kind=="string"?re.kind:void 0,V=Bi(D),he=I.get(z),L=an(t,z);m.push({sequence:m.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:V,filePath:z,...he?{before:he}:{},...L?{after:L}:{},...Do(re)?{patch:Do(re)}:{},...D?{rawKind:D}:{}}),I.set(z,L)}}else if(M.item.type==="command_execution"){let N=typeof M.item.id=="string"?M.item.id:void 0,z=N?p.get(N):void 0,K=typeof M.item.command=="string"?M.item.command:z?.rawCommand,Z=K?$o(K):z?.command,re=No(t);if(Fi(z?.beforeWorktree,re)){let D=[...new Set([...z?.beforeWorktree?.changedFiles??[],...re?.changedFiles??[]])],V=typeof M.item.aggregated_output=="string"?Kn(M.item.aggregated_output,Ji):void 0,he=typeof M.item.exit_code=="number"?M.item.exit_code:M.item.exit_code===null?null:void 0,L=typeof M.item.status=="string"?M.item.status:void 0;m.push({sequence:m.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...K?{rawCommand:K}:{},...Z?{command:Z}:{},...he!==void 0?{exitCode:he}:{},...L?{status:L}:{},...V?{output:V.text}:{},...V?.truncated?{outputTruncated:!0}:{},...z?.beforeWorktree?{beforeWorktree:z.beforeWorktree}:{},...re?{afterWorktree:re}:{},...D.length>0?{touchedFiles:Ui(t,D,z?.beforeSnapshots??new Map)}:{}})}N&&p.delete(N)}}O==="turn.failed"&&(k=!0,A=M.error?.message||M.message||"Turn failed")}catch{}});let $=[];T.stderr?.on("data",h=>{$.push(h.toString())}),T.on("close",h=>{g.close(),l.length===0&&E.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...E].join(", ")}`),h!==0&&h!==null&&(k=!0,A=$.join("")||`Codex process exited with code ${h}`),b({sessionId:f,text:l.join(""),success:!k,error:k?A:void 0,editEvents:m.length>0?m:void 0,toolsUsed:y.length>0?y:void 0})}),T.on("error",h=>{k=!0,A=h.message,b({sessionId:f,text:l.join(""),success:!1,error:A,editEvents:m.length>0?m:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:T,result:P}}import{spawn as zi}from"child_process";import{createInterface as Gi}from"readline";function Uo(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 zo(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,u=["--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&&u.push(`--resume=${r}`),i&&u.push("--model",i),u.push("-p",n);let x=zi(d,u,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),T=new Promise(P=>{let b,f=[],l=[],y=!1,m="",I=!1,p=setTimeout(()=>{I=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},s),k=Gi({input:x.stdout}),A=new Set,g=[];k.on("line",$=>{if($.trim())try{let h=JSON.parse($),M=Dt(h);A.add(M),g.length<5&&Wi(M)&&g.push($.slice(0,800));let O=Ot(h,["sessionId","session_id","id"],["session","conversation","thread"]);O&&!b&&(b=O);let N=Hi(h,f.length===0);N&&(f.push(N),c?.({type:"delta",jobId:o,text:N},o));let z=Vi(h);z&&c?.({type:"thinking",jobId:o,text:z},o);let K=Ki(h);K&&(l.push(K.label),c?.({type:"tool_use",jobId:o,tool:K.tool,...K.file?{file:K.file}:{},...K.content?{content:K.content}:{}},o));let Z=Qi(h);Z&&(y=!0,m=Z)}catch{}});let E=[];x.stderr?.on("data",$=>{E.push($.toString())}),x.on("close",$=>{clearTimeout(p),k.close(),f.length===0&&A.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),g.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${g.join(`
32
+ `)}`)),I?(y=!0,m=`Timed out after ${Math.round(s/6e4)} minutes`):$!==0&&$!==null&&(y=!0,m=E.join("").trim()||m||`Copilot process exited with code ${$}`);let h=y?Uo(m,i):null;P({sessionId:b,text:f.join(""),success:!y,error:h?.message,errorCode:h?.code,recoverableError:h?.recoverable,provider:"copilot",toolsUsed:l.length>0?l:void 0})}),x.on("error",$=>{clearTimeout(p);let h=Uo($.message,i);P({sessionId:b,text:f.join(""),success:!1,error:h.message,errorCode:h.code,recoverableError:h.recoverable,provider:"copilot",toolsUsed:l.length>0?l:void 0})})});return{process:x,result:T}}function Dt(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 Hi(o,e=!1){let n=Dt(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 Je(o.delta)??Je(o.content)??Je(o.message);if(n==="assistant.message"&&e)return Je(o.message)??Je(o.content)??Je(o);if(n==="result"&&e)return Je(o.result)??Je(o.output)??Je(o.message)??Je(o);let i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof o.text=="string"&&Qn(o))return o.text;if(typeof o.message=="string"&&Qn(o))return o.message;if(typeof o.delta=="string"&&Qn(o))return o.delta}function Je(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Je).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=Je(e[n]);if(t)return t}}function Wi(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function Vi(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 Ki(o){let e=Ot(o,["tool","toolName","tool_name","name"]),n=Ot(o,["command","cmd"]),t=Ot(o,["file","path","filename","filePath"]),r=Dt(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 Qi(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"&&Dt(o).toLowerCase().includes("error"))return o.message}function Ot(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=Ot(r,e);if(i)return i}}function Qn(o){let e=Dt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as Xi,readFile as Yi}from"fs/promises";import{join as Xn}from"path";var dn=class{constructor(e){let n=Xn(e,".popmelt");this.decisionsDir=Xn(n,"decisions")}async listDecisionIds(){try{return(await Xi(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 Yi(Xn(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)}};import{randomUUID as Go}from"crypto";import{mkdir as Yn,readFile as Zn,writeFile as ln}from"fs/promises";import{dirname as eo,join as gt}from"path";var qe="[ProjectionWorker]",Zi={version:1,runs:[]},es={version:1,updatedAt:0,proposals:[]},ts=12;function ns(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 Ho(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(`${qe} 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(`${qe} Rule count ${e.length} exceeds cap of 30`),e}function os(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function rs(o,e,n){let t=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let f of i){if(!f||typeof f!="object")continue;let l=f.sources;if(Array.isArray(l))for(let y of l)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:[],u=i.filter(f=>{if(!f||typeof f!="object")return!1;let l=f.id,y=typeof l=="string"?d.find(m=>m&&typeof m=="object"&&m.id===l):void 0;return JSON.stringify(y)!==JSON.stringify(f)}).length,x=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},T=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},P=Object.keys(s).filter(f=>JSON.stringify(s[f])!==JSON.stringify(x[f])).length,b=Object.keys(c).filter(f=>JSON.stringify(c[f])!==JSON.stringify(T[f])).length;return{ruleCount:u,tokenSectionCount:P,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(f=>!r.has(f))}}function is(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function ss(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 pn(o,e,n){let t=o;for(let i=0;i<e.length-1;i++)t=ss(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=is(n)}function Wo(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 as(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 cs(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 Vo(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=as(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?cs(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var un=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=gt(e,".popmelt");this.runsPath=gt(t,"projection-runs.json"),this.legacyRunsPath=gt(t,"materialization-runs.json"),this.proposalsPath=gt(t,"projection-queue.json"),this.legacyProposalsPath=gt(t,"model-proposals.json"),this.modelPath=gt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Zn(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=ns(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?Wo(n,r):pn(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(ts),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(f=>f.id);console.log(`${qe} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=us(r,s),d=os(r,t.totalCandidateDecisionCount,c);n=Go().slice(0,8);let u={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(u);let x=!0,T,P,b;try{let f=`projection-${Date.now()}`,{provider:l,result:y}=this.spawnModelAgent(f,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});u={...u,provider:l},await this.persistRun(u);let m=await y;if(!m.success)x=!1,T=m.error,console.error(`${qe} ${l} spawn error:`,T);else{let I=ps(m.text,i);if(I){let p=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of I)pn(p,g.path,g.value);Array.isArray(p.rules)&&(p.rules=Ho(p.rules));let k=rs(p,i,s);if(I){let g=[...new Set(I.flatMap(E=>E.decisionIds))];k.coveredDecisionIds=g,k.uncoveredDecisionIds=i.filter(E=>!g.includes(E))}P=k;let A=await this.createModelProposal({decisionIds:i,proposedModel:p,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:l,model:e.model??this.options.model,outputStats:P,changes:I});b=A.id,console.log(`${qe} Created model proposal ${A.id} for ${i.length} decision(s)`)}else x=!1,T="No valid bounded <model-changes> block found in response",console.error(`${qe} ${T}`)}}catch(f){x=!1,T=f instanceof Error?f.message:String(f),console.error(`${qe} Error:`,T)}return await this.persistRun({...u,status:x?"proposed":"failed",completedAt:Date.now(),error:T,outputStats:P,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:x,error:T}),{processedIds:i,success:x,error:T,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ho(e.rules)),await ln(this.modelPath,JSON.stringify(e,null,2)),console.log(`${qe} 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 Yn(eo(this.runsPath),{recursive:!0}),await ln(this.runsPath,JSON.stringify(n,null,2)),n):{...Zi,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??{...es,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??[])pn(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?Wo(s,d.path):pn(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 createModelProposal(e){let n={id:Go().slice(0,8),status:"pending",title:ds(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"}.`:ls(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 Yn(eo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await ln(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${qe} 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 Yn(eo(this.runsPath),{recursive:!0}),await ln(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${qe} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await Zn(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await Zn(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",...cn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:rn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${qe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...sn(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 ds(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 ls(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 ps(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(T=>typeof T=="string"||typeof T=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let u=d.path[0];if(u!=="tokens"&&u!=="components"&&u!=="rules")return[];if(u==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let x=Array.isArray(d.decisionIds)?d.decisionIds.filter(T=>typeof T=="string"&&r.has(T)):[];return x.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:x,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===t.length?i:null}catch{return null}}function us(o,e){let n=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
34
+ Kind: ${i.kind}
35
+ Claim: ${i.claim}
36
+ ${i.rationale?`Rationale: ${i.rationale}`:""}
37
+ Subjects: ${i.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
38
+ Authority: ${i.authority.level}/${i.authority.mode}`).join(`
39
+
40
+ `),t=o.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
97
41
 
98
42
  ## Instructions
99
43
  1. Review the current model (if any) and the new decisions below.
@@ -165,75 +109,71 @@ Example:
165
109
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
166
110
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
167
111
  - 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 bn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as Yi}from"child_process";import{readFile as uo}from"fs/promises";import{homedir as Sn}from"os";import{join as Be}from"path";var mo=/popmelt/i,Zi=/chrome|devtools/i;function yt(){return{found:!1,name:null,scope:null,disabled:!1}}function Rt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Ht(o){for(let e of Object.keys(o))if(mo.test(e))return e;return null}async function xn(o){try{let e=await uo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function fo(o){let e=Sn(),n=await xn(Be(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Ht(r.mcpServers);if(s)return Rt(s,"user")}if(r.projects&&typeof r.projects=="object"){let i=r.projects[o];if(i&&typeof i=="object"){let c=i;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Ht(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(v=>mo.test(v));return Rt(d,"project",l)}}}}}let t=await xn(Be(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Ht(r.mcpServers);if(i){let c=await ur(o,i);return Rt(i,"mcp.json",c)}}let s=Ht(r);if(s&&s!=="mcpServers"){let i=await ur(o,s);return Rt(s,"mcp.json",i)}}return yt()}async function ur(o,e){let n=Be(o,".claude","settings.local.json"),t=await xn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(s=>s===e)}return!1}var ea=/^\[mcp_servers\.([^\]]+)\]/;function ta(o){return o.replace(/^"(.+)"$/,"$1")}function na(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function fr(o){let e=o.split(`
169
- `),n=[],t=null;for(let r of e){let s=r.match(ea);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(`
112
+ Include property and bindings when the decision context has class-level evidence.`}var mn=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 ms}from"child_process";import{readFile as Xo}from"fs/promises";import{homedir as no}from"os";import{join as We}from"path";var oo=/popmelt/i;function dt(){return{found:!1,name:null,scope:null,disabled:!1}}function yt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Jt(o){for(let e of Object.keys(o))if(oo.test(e))return e;return null}async function fn(o){try{let e=await Xo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function ro(o){let e=no(),n=await fn(We(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Jt(r.mcpServers);if(i)return yt(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=Jt(c.mcpServers);if(d){let u=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(x=>oo.test(x));return yt(d,"project",u)}}}}}let t=await fn(We(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Jt(r.mcpServers);if(s){let c=await Ko(o,s);return yt(s,"mcp.json",c)}}let i=Jt(r);if(i&&i!=="mcpServers"){let s=await Ko(o,i);return yt(i,"mcp.json",s)}}return dt()}async function Ko(o,e){let n=We(o,".claude","settings.local.json"),t=await fn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var fs=/^\[mcp_servers\.([^\]]+)\]/;function hs(o){let e=o.split(`
113
+ `),n=[],t=null;for(let r of e){let i=r.match(fs);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
114
+ `)}),t={name:i[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
171
115
  `)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
172
- `)}),n}function hr(o){return/enabled\s*=\s*false/i.test(o)}async function ho(o){let e=process.env.CODEX_HOME||Be(Sn(),".codex"),n=await mr(Be(e,"config.toml"),"user");if(n.found)return n;let t=await mr(Be(o,".codex","config.toml"),"project");return t.found?t:yt()}async function oa(o,e){let n=process.env.CODEX_HOME||Be(Sn(),".codex"),t=new Set;for(let r of[Be(n,"config.toml"),Be(o,".codex","config.toml")])try{let s=await uo(r,"utf-8");for(let i of fr(s)){if(na(i.name)||hr(i.body))continue;let c=ta(i.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function gr(o){return oa(o,Zi)}async function go(o,e="copilot"){let n=await ra(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Be(Sn(),".copilot"),r=await po(Be(t,"mcp-config.json"),"user");if(r.found)return r;let s=await po(Be(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await po(Be(o,".github","mcp.json"),"mcp.json");return i.found?i:yt()}async function ra(o){try{let e=await new Promise((n,t)=>{Yi(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return yr(JSON.parse(e),"user")}catch{return yt()}}async function po(o,e){let n=await xn(o);return yr(n,e)}function yr(o,e){if(!o||typeof o!="object")return yt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Ht(t);return r?Rt(r,e):yt()}async function mr(o,e){try{let n=await uo(o,"utf-8"),t=fr(n);for(let r of t)if(mo.test(r.name)){let s=hr(r.body);return Rt(r.name,e,s)}}catch{}return yt()}import{execFile as vr}from"child_process";import{mkdir as sa,readFile as wr,writeFile as Ir}from"fs/promises";import{homedir as br}from"os";import{dirname as ia,join as yo}from"path";var vo="https://mcp.popmelt.com/mcp";async function xr(o=vo){let e=yo(br(),".claude.json"),n;try{let r=await wr(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 Ir(e,JSON.stringify(n,null,2)+`
173
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Sr(o=vo){let e=process.env.CODEX_HOME||yo(br(),".codex"),n=yo(e,"config.toml"),t;try{t=await wr(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await sa(ia(n),{recursive:!0});let r=`
116
+ `)}),n}function gs(o){return/enabled\s*=\s*false/i.test(o)}async function io(o){let e=process.env.CODEX_HOME||We(no(),".codex"),n=await Qo(We(e,"config.toml"),"user");if(n.found)return n;let t=await Qo(We(o,".codex","config.toml"),"project");return t.found?t:dt()}async function so(o,e="copilot"){let n=await ys(e);if(n.found)return n;let t=process.env.COPILOT_HOME||We(no(),".copilot"),r=await to(We(t,"mcp-config.json"),"user");if(r.found)return r;let i=await to(We(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await to(We(o,".github","mcp.json"),"mcp.json");return s.found?s:dt()}async function ys(o){try{let e=await new Promise((n,t)=>{ms(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return Yo(JSON.parse(e),"user")}catch{return dt()}}async function to(o,e){let n=await fn(o);return Yo(n,e)}function Yo(o,e){if(!o||typeof o!="object")return dt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Jt(t);return r?yt(r,e):dt()}async function Qo(o,e){try{let n=await Xo(o,"utf-8"),t=hs(n);for(let r of t)if(oo.test(r.name)){let i=gs(r.body);return yt(r.name,e,i)}}catch{}return dt()}import{execFile as Zo}from"child_process";import{mkdir as vs,readFile as er,writeFile as tr}from"fs/promises";import{homedir as nr}from"os";import{dirname as Is,join as ao}from"path";var co="https://mcp.popmelt.com/mcp";async function or(o=co){let e=ao(nr(),".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 tr(e,JSON.stringify(n,null,2)+`
117
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function rr(o=co){let e=process.env.CODEX_HOME||ao(nr(),".codex"),n=ao(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 vs(Is(n),{recursive:!0});let r=`
174
118
  [mcp_servers.popmelt]
175
119
  url = "${o}"
176
- `;return await Ir(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Pr(o=vo,e="copilot"){let n=await aa(e);if(ca(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{vr(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 aa(o){try{let e=await new Promise((n,t)=>{vr(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 ca(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 Pn=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 To,readFile as Mt,writeFile as jo}from"fs/promises";import{join as lt}from"path";var da=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function wo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function kn(o){return new Set(wo(o).split(" ").filter(e=>e.length>2&&!da.has(e)))}function kr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function la(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 pa(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(wo).filter(Boolean),s=kn([e.action,e.text].filter(Boolean).join(" "));for(let i of o){if(t.has(i.id)){n.set(i.id,{subjectId:i.id,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of la(i)){let l=wo(d.value);for(let b of r){let I=l===b?95:l.includes(b)||b.includes(l)?75:0;I>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:I>=90?"exact":"strong",matchedBy:d.by,score:I})}let R=["/","#","[","]","="].some(b=>d.value.includes(b))?0:Math.round(kr(kn(l),s)*55);R>=30&&R>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}c&&n.set(i.id,c)}return n}function ua(o,e){let n=new Set(o.sourceRefs.filter(i=>i.kind==="iteration").map(i=>i.id)),t=new Set(o.sourceRefs.filter(i=>i.kind==="thread").map(i=>i.id)),r=e.filter(i=>i.iterationIds.some(c=>n.has(c))||i.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let s=new Set(r.map(i=>i.state));return{state:s.size>1?"mixed":s.has("completed")?"completed":"attempted",attemptIds:r.map(i=>i.id)}}function ma(o){return Math.ceil(JSON.stringify(o).length/4)}function Io(o,e){let n=o.records.filter(h=>h.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(h=>{if(h.recordType!=="proposal"||r&&!r.has(h.id))return!1;if(h.state==="pending")return!0;if(h.state!=="deferred")return!1;let f=[...o.events].reverse().find(y=>y.entity.entityType==="proposal"&&y.entity.entityId===h.id&&y.toState==="deferred"&&y.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(h=>h.recordType==="implementation_attempt"),c=pa(n,e),d=[...c.values()].sort((h,f)=>f.score-h.score),l=kn([e.action,e.text].filter(Boolean).join(" ")),v=s.flatMap(h=>{let f=h.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),y=Math.max(0,...f.map(A=>A.score)),x=Math.round(kr(kn(h.claim),l)*35),S=y+x;return S>=50?[{proposal:h,proposalMatches:f,score:S}]:[]}).sort((h,f)=>f.score-h.score||h.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),I=[],g=0;for(let h of v){if(I.length>=R)break;let f=h.proposal.sourceRefs.slice(0,4),y={contractVersion:1,packetId:`review:${h.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:h.proposalMatches.length?`Historical proposal intersects ${h.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:h.proposalMatches.map(({score:S,...A})=>A)},proposal:{id:h.proposal.id,claim:h.proposal.claim,state:h.proposal.state,proposedKind:h.proposal.proposedKind,subjectIds:h.proposal.subjects.map(S=>S.subjectId),origin:h.proposal.origin.mode},authority:"unaccepted",presentation:h.score>=100&&["constraint","rule"].includes(h.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ua(h.proposal,i),evidence:{sourceCount:h.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:h.proposal.id},...f]},x={...y,estimatedTokens:ma(y)};if(g+x.estimatedTokens>b)break;I.push(x),g+=x.estimatedTokens}let p=Math.max(0,v.length-I.length);return{packets:I,subjectMatches:d.map(({score:h,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:p,maxEstimatedTokens:b,estimatedTokens:g},uncertainty:c.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var fa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function bo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Rn(o){return new Set(bo(o).split(" ").filter(e=>e.length>2&&!fa.has(e)))}function Rr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ha(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(bo).filter(Boolean),r=Rn([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=bo(l.value);for(let I of t){let g=v===I?95:v.includes(I)||I.includes(v)?75:0;g>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let b=["/","#","[","]","="].some(I=>l.value.includes(I))?0:Math.round(Rr(Rn(v),r)*55);b>=30&&b>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}c&&s.push(c)}return s.sort((i,c)=>c.score-i.score||i.subjectId.localeCompare(c.subjectId))}function ga(o){return Math.ceil(JSON.stringify(o).length/4)}function Tt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ya(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 va(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),s=t[0],i=r?"stale":s?s.state==="passed"?"passing":s.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(s.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:i,attemptIds:t.map(c=>c.id)}}function Tr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(_=>_.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(_=>_.recordType==="decision"&&_.state==="active"),c=s?i.filter(_=>s.has(_.id)):i,d=o.records.filter(_=>_.recordType==="implementation_attempt"),l=o.records.filter(_=>_.recordType==="verification_attempt"),v=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),R=o.records.filter(_=>_.recordType==="evidence"),b=o.records.filter(_=>_.recordType==="model_entry"),I=[...o.records].reverse().filter(_=>_.recordType==="eval_spec").filter((_,N,T)=>T.findIndex(B=>B.legacyId===_.legacyId)===N),g=ha(r,e),p=new Map(g.map(_=>[_.subjectId,_.score])),h=Rn([e.action,e.text].filter(Boolean).join(" ")),f=c.flatMap(_=>{let N=Math.max(0,..._.subjects.map(W=>p.get(W.subjectId)??0)),T=Math.round(Rr(Rn(_.claim),h)*35),B=N+T;return B>=50?[{decision:_,score:B}]:[]}).sort((_,N)=>N.score-_.score||_.decision.id.localeCompare(N.decision.id)),y=new Map;for(let _ of f.slice(0,t))y.set(_.decision.id,_.decision);for(let _ of o.relationships){if(!Tt(_,"excepts")&&!Tt(_,"contradicts"))continue;let N=i.find(B=>B.id===_.from.entityId),T=i.find(B=>B.id===_.to.entityId);!N||!T||!y.has(N.id)&&!y.has(T.id)||(y.size<t&&y.set(N.id,N),y.size<t&&y.set(T.id,T))}let x=[...y.values()],S=_=>_.from.entityType==="decision"&&_.to.entityType==="decision"&&y.has(_.from.entityId)&&y.has(_.to.entityId),A=(_,N=!1)=>{let T=new Set(_.map(M=>M.id)),B=v.filter(M=>M.target.entityType==="decision"&&T.has(M.target.entityId)),W=new Set(o.relationships.filter(M=>Tt(M,"excepts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).flatMap(M=>[M.from.entityId,M.to.entityId])),H=o.relationships.filter(M=>Tt(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(H.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=>Tt(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:[]}),H.length&&U.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.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:b.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,key:M.key,value:M.value,decisionIds:M.decisionIds})),evalSpecs:I.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":W.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:H,uncertainties:U,implementation:_.map(M=>ya(M.id,d)),verification:_.map(M=>va(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=ga(he),he},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>Tt(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 wa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function jt(o){return wa.test(o)}function Ia(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 xo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){jt(n)||ce(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function dt(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ce(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function vt(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 ba={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"])},xa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Sa(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),dt(o,`${n}.createdAt`,e.createdAt),vt(o,`${n}.authority`,e.authority);let t=ba[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(xa.has(s)&&(vt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ce(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let i=e.transitionContext;(i?.kind!=="proposal_deferral"||i.resurfaceWhen.length===0)&&ce(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),i?.resurfaceWhen.includes("after_date")&&!i.revisitAfter&&ce(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),i?.revisitAfter&&dt(o,`${n}.transitionContext.revisitAfter`,i.revisitAfter)}}function Pa(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),dt(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ce(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ce(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ce(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ce(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(vt(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"&&xo(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ce(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(dt(o,`${n}.appliedAt`,e.appliedAt),vt(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&&xo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&xo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ka(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),dt(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ce(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)&&((e.from.entityType!=="decision"||e.to.entityType!=="decision")&&ce(o,n,"invalid_normative_relationship","Normative relationships connect decisions to decisions."),e.authority?vt(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 wt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),dt(e,"manifest.createdAt",o.manifest.createdAt),dt(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,h)=>{let f=n.get(p);f?ce(e,h,"duplicate_id",`ID is already used at ${f}.`):n.set(p,h)};o.records.forEach((p,h)=>{let f=`records[${h}]`;t(p.id,f),Pa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,h)=>{let f=`events[${h}]`;t(p.id,f),Sa(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,h)=>{let f=`relationships[${h}]`;t(p.id,f),ka(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,h)=>{t(p.id,`artifacts[${h}]`),Te(e,`artifacts[${h}].id`,p.id)}),o.tombstones.forEach((p,h)=>{let f=`tombstones[${h}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),dt(e,`${f}.deletedAt`,p.deletedAt),vt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,h)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,h,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,h)=>i(p.entity,`events[${h}].entity`)),o.relationships.forEach((p,h)=>{i(p.from,`relationships[${h}].from`),i(p.to,`relationships[${h}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,h)=>{c.has(p)||ce(e,h,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,h,f)=>{!r.has(`${p}:${h}`)&&!s.has(`${p}:${h}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,h)=>{let f=`records[${h}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((y,x)=>l("subject",y,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((y,x)=>d(y,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((y,x)=>l("subject",y.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((y,x)=>d(y,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((y,x)=>i(y,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((y,x)=>l("thread",y,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((y,x)=>l("iteration",y,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((y,x)=>{y.kind==="subject"&&y.subjectId&&l("subject",y.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((y,x)=>{y.subjectIds?.forEach((S,A)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${A}]`))}),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`));break;case"model_projection":vt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((y,x)=>l("model_entry",y,`${f}.entryIds[${x}]`)),p.coverage.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;default:break}});let v=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),b=new Map;o.events.forEach((p,h)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,y=b.get(f)??new Set;y.add(p.toState),b.set(f,y),y.size>1&&ce(e,`events[${h}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let I=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,h,f,y,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=I.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==h||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(f);(A<Date.parse(S.startsAt)||S.endsAt&&A>Date.parse(S.endsAt)||S.revokedAt&&A>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&y.length&&!y.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(h=>h.subjectId),`records:${p.id}.authority`);o.events.forEach((p,h)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),y=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,y,`events[${h}].authority`)}),o.relationships.forEach((p,h)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(y=>{let x=R.get(`${y.entityType}:${y.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${h}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let h=v.get(p.acceptanceEventId);(!h||h.entity.entityType!=="proposal"||h.entity.entityId!==p.proposalId||h.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),h&&h.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(y=>y.relationshipType==="supersedes"&&y.to.entityType==="decision"&&y.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(y=>y.entity.entityType==="decision"&&y.entity.entityId===p.id&&y.toState==="revoked"&&!!y.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ia(e)}function Gt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function jr(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 Ra(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function Tn(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),jt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of Ra(e))jt(s)||n.push({code:"invalid_generated_id",message:`${s} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=jr(o,t,e,s.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:i.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let s={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},i={...Gt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Gt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=jr(o,s,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,d],events:[i,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ta}from"crypto";import{readFile as ja,readdir as Ea,realpath as Ma}from"fs/promises";import{join as Vt,relative as Aa}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 Et(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Le(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Er(...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=Ta("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${c}${i.slice(4,7)}-${i.slice(7,19)}`}async function So(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 Ca(o){let e=Et(o);if(!e)return 0;let n=0,t=r=>{let s=Et(r);if(!s){n+=1;return}for(let i of Object.values(s))t(i)};for(let r of Object.values(e))t(r);return n}function $a(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Kt(o){let e=[],n=await Ma(o.projectRoot).catch(()=>o.projectRoot),t=Vt(n,".popmelt"),r=await So(Vt(t,"threads.json"),e),s=await So(Vt(t,"model.json"),e),i=Et(r),c=Et(i?.threads)??{},d=Object.entries(c).map(([M,Y])=>({key:M,value:Et(Y)})).filter(M=>!!M.value),l=Vt(t,"decisions"),v=await Ea(l).catch(()=>[]),R=[];for(let M of v.filter(Y=>Y.endsWith(".json")).sort()){let Y=Et(await So(Vt(l,M),e));Y&&R.push({file:M,value:Y})}let b=d.flatMap(({value:M})=>[M.createdAt,M.updatedAt]).filter(M=>typeof M=="number"&&Number.isFinite(M)),I=b.length?Math.min(...b):0,g=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ye(g,"project",g,I),h=ye(g,"participant","legacy-owner",I),f=ye(g,"participant","legacy-agent",I),y=ye(g,"subject","project",I),x=Le(Math.max(I,...b)),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??I,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 W=(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)},H=[{...W(h,h,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...W(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...H),S.push({...W(y,h,[]),recordType:"subject",subjectType:"project",label:Aa(process.cwd(),n)||n,aliases:[],locators:[{id:ye(g,"locator",n,I),kind:"project_root",value:n,status:"current",validFrom:Le(I),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={...W(ie,h,[{kind:"external",id:M}]),createdAt:Le(Y),recordType:"subject",subjectType:"element",label:M,aliases:[],locators:[{id:ye(g,"locator",M,Y),kind:"dom_selector",value:M,status:"current",validFrom:Le(Y),sourceRefs:[{kind:"external",id:M}]}]};return S.push(De),te.set(M,ie),ie};for(let{key:M,value:Y}of d){let ue=Y.id??M,ie=Y.createdAt??I,De=ye(g,"thread",ue,ie),Je={kind:"thread",id:ue},Pe=[],Ue=[],Ge=Array.isArray(Y.messages)?Y.messages:[],Ye,rt,ut=0;Ge.forEach((we,st)=>{let Ae=we.timestamp??ie,Ze=ye(g,"artifact",`${ue}:message:${st}`,Ae);if(Pe.push(Ze),A.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${st}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${ue}/messages/${st}`,Ze),we.screenshotPath&&B(`${ue}:message:${st}: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}:${st}`,Ae),ct=Y.elementIdentifiers??[],St={...W(Ne,h,[Je,{kind:"message",id:Ze}]),createdAt:Le(Ae),recordType:"observation",state:"open",statement:je,captureContext:{subjectIds:ct.map(ft=>ne(ft,ie)),artifactIds:[Ze]},resolvedByIds:[]};ee(ue,St),rt=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let it=we.jobId??`${ue}:${st}`,at=ye(g,"iteration",it,Ae),mt=N.get(it),Yn=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",Zn={...W(at,f,[Je,{kind:"message",id:Ze},...(T.get(it)??[]).map(je=>({kind:"artifact",id:je}))]),createdAt:Le(Ae),recordType:"iteration",threadIds:[De],startedAt:Le(Ye?.timestamp,Ae),completedAt:Le(Ae),requestSummary:Er(Ye?.feedbackSummary,Ye?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:Yn,execution:{provider:we.provider??mt?.provider,model:we.model??mt?.model,sessionId:we.sessionId??mt?.sessionId},artifactIds:[Ze,...T.get(it)??[]]};ee(ue,Zn),Ue.push({entityType:"iteration",entityId:at});let Bt=we.resolutions??mt?.resolutions??[];for(let[je,Ne]of Bt.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let ct=Y.elementIdentifiers??[],St=(ct.length?ct:[n]).map(cn=>({subjectId:cn===n?y:ne(cn,ie),role:"governed"})),ft=ye(g,"proposal",`${it}:${Ne.annotationId??"resolution"}:${je}`,Ae),eo={...W(ft,f,[Je,{kind:"iteration",id:at}]),createdAt:Le(Ae),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:St,subjectSemantics:St.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Er(Ye?.feedbackSummary,Ye?.replyToQuestion,Ne.summary),iterationId:at,inferredById:f}};ee(ue,eo),Ue.push({entityType:"proposal",entityId:ft}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${ft} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Bt.some(je=>je.status==="resolved")||mt?.gitDiff){let je=ye(g,"implementation",it,Ae),Ne={...W(je,f,[Je,{kind:"iteration",id:at}]),createdAt:Le(Ae),recordType:"implementation_attempt",state:"completed",iterationIds:[at],coverageClaims:[],summary:Bt.map(ct=>ct.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};ee(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:je}),ut+=1}rt&&(rt=void 0)});let Jt=Ge.at(-1),Nt={...W(De,h,[Je]),createdAt:Le(ie),recordType:"thread",state:Jt?.question?"open":"resolved",messageArtifactIds:Pe,outcome:Jt?.question?"question_unresolved":ut?"implementation_only":"no_outcome",resultRefs:Ue};S.push(Nt),_.set(ue,[De,..._.get(ue)??[]])}let ge=Ca(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:Le(I),updatedAt:x,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:S,events:[],relationships:[],artifacts:A,tombstones:[]},G=wt(X),he=(o.proofCaseIds??_a).map(M=>({legacyId:M,threadFound:d.some(({key:Y,value:ue})=>(ue.id??Y)===M),decisionEnvelopeFound:N.has(M),recordIds:_.get(M)??[]}));return{bundle:X,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((M,Y)=>M+(Y.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:ge,artifactsReferenced:A.length},imported:$a(S),unresolvedAcceptance:e.filter(M=>M.code==="acceptance_unresolved").length,deferredModelEntries:ge,proofCases:he,issues:e,schemaIssues:G.issues}}}import{createHash as Oa}from"crypto";import{mkdir as Mr,open as Po,readFile as ko,readdir as Da,rename as Ja,unlink as Ro}from"fs/promises";import{join as nt}from"path";var Na={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function En(o){return Oa("sha256").update(JSON.stringify(o)).digest("hex")}function Ar(o){return En(o)}function _r(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 Ba(o,e,n){return _r(structuredClone(o),e,n)}async function It(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Po(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
177
- `,"utf8"),await t.sync()}finally{await t.close()}try{await Ja(n,o)}catch(r){throw await Ro(n).catch(()=>{}),r}}async function jn(o){return JSON.parse(await ko(o,"utf8"))}var Mn=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=wt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Mr(this.journalDir,{recursive:!0});try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}let t=En(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},s={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await It(this.checkpointPath,r),await It(this.manifestPath,s)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await It(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=En(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await It(nt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await It(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!jt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,s={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},i={...s,hash:Ar(s)},c=Ba(t.bundle,e,n.committedAt),d=wt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await It(nt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await It(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:i.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Na,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await jn(this.manifestPath),n=await jn(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!==En(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Da(this.journalDir),r=t.filter(b=>b.endsWith(".tmp")),i=t.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,v=new Set;for(let b of i){let I=await jn(nt(this.journalDir,b)),{hash:g,...p}=I;if(g!==Ar(p))throw new Error(`Journal hash mismatch: ${b}`);if(I.sequence!==d+1)throw new Error(`Journal sequence gap at ${b}`);if(I.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(I.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(v.has(I.transactionId))throw new Error(`Duplicate transaction ID: ${I.transactionId}`);_r(c,I.mutation,I.committedAt),d=I.sequence,l=I.hash,v.add(I.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=wt(c);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:c,manifest:e,transactionIds:v,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Mr(this.memoryDir,{recursive:!0});let n;try{n=await Po(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await jn(this.lockPath).catch(()=>({})),s=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(i){s=i.code!=="ESRCH"}if(s)throw new Error("Memory journal is locked by another writer.");await Ro(this.lockPath),n=await Po(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Ro(this.lockPath).catch(()=>{})}}};import{randomBytes as Fa}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Fa(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 La=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Cr(o,e){let n=o.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active"),t=o.records.find(x=>x.recordType==="participant"&&x.kind==="ai"&&x.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,s=`${e.threadId}:${e.jobId}`,i=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=La(),l=d.records,v=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));v||(v={id: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(v));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 b=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),I;if(b.length>0){I=ye(r,"live-observation",s,e.createdAt);let x={id:I,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds: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},...I?[{kind:"record",id:I}]:[]],recordType:"iteration",threadIds:[v.id],startedAt:i,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let h=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),y=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(b.length>0&&y.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of b.entries()){let A=ye(r,"live-proposal",`${s}:${x}`,e.completedAt),J=y.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:S.claim.trim(),rationale:S.rationale?.trim()||void 0,proposedKind:S.proposedKind,subjects:J,subjectSemantics:J.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:S.sourceText?.trim()||e.requestSummary,iterationId:g,inferredById:t.id}};l.push(_),h.push(A)}if(f.length>0){let x=new Set(e.governingDecisionIds??[]),S=o.records.filter(J=>J.recordType==="decision"&&J.state==="active"&&x.has(J.id)),A={id:ye(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g}],recordType:"implementation_attempt",state:"completed",iterationIds:[g],coverageClaims:S.map(J=>({decisionId:J.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(_=>_.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:d,iterationId:g,proposalIds:h,observationId:I}}import{createHash as za}from"crypto";import{mkdir as Ua,open as qa,readFile as Wa,rename as Ha,unlink as Ga}from"fs/promises";import{join as $r}from"path";function Or(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dr(o){return za("sha256").update(JSON.stringify(o)).digest("hex")}async function Va(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await qa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
- `,"utf8"),await t.sync()}finally{await t.close()}try{await Ha(n,o)}catch(r){throw await Ga(n).catch(()=>{}),r}}function Ka(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(d,l,v)=>{let R=d[l]??=[];R.includes(v)||R.push(v)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Or(v);R&&i(t,R,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)i(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)i(s,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...c,checksum:Dr(c)}}function Jr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Or(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var An=class{constructor(e){this.indexDir=$r(e,".popmelt","memory","indexes"),this.indexPath=$r(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Wa(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===Dr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ka(e,n);return await Ua(this.indexDir,{recursive:!0}),await Va(this.indexPath,t),t}};var _n=class{constructor(e){this.projectRoot=e;this.store=new Mn(e),this.indexStore=new An(e),this.manifestPath=lt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Mt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Kt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Kt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"legacy-evals-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(s.runs)?s.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:r.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:r.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"imprint-evidence-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=0;for(let s of t.explanations){let i=s.evidence.length?s.evidence:[{id:s.id,kind:"observation",stance:"supports",summary:s.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:s.createdAt}];for(let c of i){let d=c.kind==="confirmation"?"confirm":c.kind==="correction"||c.kind==="rejection"?"reason_wrong":c.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:c.id,kind:d?"strengthened":"added",title:s.statement.slice(0,120),detail:c.summary,changes:[{explanationId:s.id,action:d==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:c.threadId,jobId:c.jobId,action:d,occurredAt:c.createdAt}),r+=1}}return await To(e,{recursive:!0}),await jo(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:Io(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Tr(t.bundle,r),reviewSelection:Io(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Tn(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Kt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=Tn(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},d=e.action==="accept"?{...c,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:le(s),reason:e.reason}:{...c,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=Tn(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(v);let R=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:v.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Cr(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(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active"),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="ai"&&b.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(b=>b.recordType==="subject"&&b.subjectType==="project");if(!s||!i)return;let c=e.occurredAt??new Date().toISOString(),d=Date.parse(c),l=[],v=[];for(let b of e.summary.changes){let I={kind:"external",id:b.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(h=>h.recordType==="observation"&&h.sourceRefs.some(f=>f.kind==="external"&&f.id===b.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:b.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),v.push({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ye(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,d);try{let b=await this.store.commit({records:l,events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:c});await this.refreshIndex(b)}catch(b){if(!(b instanceof Error)||!b.message.includes("Transaction already exists"))throw b}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="model_projection"&&i.state==="applied"?i.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(i=>i.relationshipType==="contradicts"&&i.from.entityType==="decision"&&i.to.entityType==="decision"?[i.from.entityId,i.to.entityId]:[])),s=new Set(n.records.flatMap(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.target.entityType==="decision"?[i.target.entityId]:[]));return n.records.filter(i=>i.recordType==="decision"&&i.state==="active"&&!t.has(i.id)&&!r.has(i.id)&&!s.has(i.id)).sort((i,c)=>c.createdAt.localeCompare(i.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(s=>s.recordType==="model_entry").sort((s,i)=>s.createdAt.localeCompare(i.createdAt)))r.decisionIds.some(s=>n.has(s))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let r=[...t.values()],s=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=s.filter(l=>l.targets.some(v=>v.entityType==="decision"&&v.entityId===c.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(c=>c.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),c=le(s),d=le(s),l=le(s),v=le(s),R=le(s),b=new Set(n.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),I=n.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&b.has(T.id)),g={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],h={...g,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},y={...g,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...g,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id: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:[v],coverage:[{decisionId:l,status:"projected"}]},A={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=I.map(T=>({...g,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=I.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:y.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[h,y,x,S],events:[f,...J],relationships:[A,..._],artifacts:[],tombstones:[],projectionUpdates:I.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:v}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),s=n.bundle.records.flatMap(g=>g.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===g.id||g.sourceRefs.some(h=>h.id===p))?[g.id]:[]),i=[...new Set(n.bundle.records.flatMap(g=>g.recordType==="decision"&&s.includes(g.id)?g.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!l)throw new Error("No active local owner participant is available.");let v=Date.now(),R=new Date(v).toISOString(),b={id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},I=r?[{id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:b.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:b.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[b],events:[],relationships:I,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(v),committedAt: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,c,d)=>d.findIndex(l=>l.legacyId===i.legacyId)===c).filter(i=>!n.has(i.id)),r=e.records.filter(i=>i.recordType==="verification_attempt"),s=e.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.targetKind==="verification_result");return t.map(i=>{let c=r.filter(v=>v.evalSpecId===i.id).sort((v,R)=>R.createdAt.localeCompare(v.createdAt))[0],d=c&&s.some(v=>v.target.entityType==="verification_attempt"&&v.target.entityId===c.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(b=>b.recordType==="verification_attempt"&&b.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active"&&b.kind==="ai")??t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active");if(!s)return;let i=n.completedAt,c=new Date(i).toISOString(),d={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},v=r.targets.map(b=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:b,reason:n.summary})),R=await this.store.commit({records:[d,l],events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),c={id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),r=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(d=>!r.includes(d)).map(d=>d.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!i)return{valid:r,discardedIds:s};let c=s.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(v=>({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:v.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="model_projection"&&g.state==="applied"&&g.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(g=>g.recordType==="decision"&&e.decisionIds.includes(g.id)&&g.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let s=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),c=new Date(i).toISOString(),d=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(y=>e.decisionIds.includes(y)),h=p?.length?p:e.decisionIds,f=[...new Set(r.filter(y=>h.includes(y.id)).flatMap(y=>y.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:h.map(y=>({kind:"record",id:y})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:h,value:g.value}}),v=new Set(l.flatMap(g=>g.decisionIds)),R={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:e.decisionIds.map(g=>({kind:"record",id:g})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:v.has(g)?"projected":"unprojected"})},b=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id: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."}))),I=await this.store.commit({records:[...l,R],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});return await this.refreshIndex(I),{projectionId:d,entryIds:l.map(g=>g.id),headSequence:I.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Kt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Jr(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 At(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Eo(o){let e=_t(o),n=_t(e.authority),t=n.level,r=n.mode,s=At(t,"authority.level",["owner","delegate","contributor"]),i=At(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:At(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=>At(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:At(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=_t(d);return{subjectId:Se(l.subjectId,"subjectId"),role:At(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Mo(o){let e=_t(o),n=(s,i)=>{if(s!==void 0){if(!Array.isArray(s))throw new Error(`${i} must be an array.`);return s.map(c=>Se(c,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0:_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 Cn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
179
- `)}async function Nr(o,e,n,t){let r=Cn(e);if(!(!r&&n.length===0))try{let s=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(s.actionPacket.decisions.length===0&&s.reviewSelection.packets.length===0)return;let i=new Map(s.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(s.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:s.source,...s.actionPacket.decisions.length>0?{acceptedTruth:{decisions:s.actionPacket.decisions.map(d=>({...d,implementation:i.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:s.actionPacket.conflicts,truncated:s.actionPacket.completeness.status==="truncated"}}:{},packets:s.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:s.reviewSelection.completeness.status==="truncated",estimatedTokens:s.actionPacket.budget.estimatedTokens+s.reviewSelection.completeness.estimatedTokens}}catch(s){t?.(s);return}}function Br(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 Fr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!r||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let s=new Set(["different_action","new_evidence","new_conflict","owner_request"]),i=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&s.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:i}}catch{return null}}function Lr(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!t||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:t,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function $n(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],r=await Qa(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),c,d,l,v,R,b,I,g,p,h,f,y,x,S,A=[],J=[],_=0,N=[];for(;_<r.length;){let T=r.indexOf(s,_);if(T===-1)break;let B=T+s.length;if(r.slice(T,T+i.length).equals(i))break;let W=B;r[W]===13&&r[W+1]===10&&(W+=2);let ee=r.indexOf(`\r
120
+ `;return await tr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function ir(o=co,e="copilot"){let n=await ws(e);if(bs(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{Zo(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 ws(o){try{let e=await new Promise((n,t)=>{Zo(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 bs(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 hn=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 Ir,readFile as Ft,writeFile as wr}from"fs/promises";import{join as bt}from"path";var xs=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function lo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function gn(o){return new Set(lo(o).split(" ").filter(e=>e.length>2&&!xs.has(e)))}function sr(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 Ss(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 ks(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(lo).filter(Boolean),i=gn([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 Ss(s)){let u=lo(d.value);for(let P of r){let b=u===P?95:u.includes(P)||P.includes(u)?75:0;b>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:d.by,score:b})}let T=["/","#","[","]","="].some(P=>d.value.includes(P))?0:Math.round(sr(gn(u),i)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}c&&n.set(s.id,c)}return n}function Rs(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 Ps(o){return Math.ceil(JSON.stringify(o).length/4)}function po(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 m=[...o.events].reverse().find(I=>I.entity.entityType==="proposal"&&I.entity.entityId===y.id&&I.toState==="deferred"&&I.transitionContext?.kind==="proposal_deferral")?.transitionContext;return m?m.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||m.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||m.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||m.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||m.resurfaceWhen.includes("after_date")&&!!(m.revisitAfter&&Date.parse(t)>=Date.parse(m.revisitAfter)):!1}),s=o.records.filter(y=>y.recordType==="implementation_attempt"),c=ks(n,e),d=[...c.values()].sort((y,m)=>m.score-y.score),u=gn([e.action,e.text].filter(Boolean).join(" ")),x=i.flatMap(y=>{let m=y.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),I=Math.max(0,...m.map(A=>A.score)),p=Math.round(sr(gn(y.claim),u)*35),k=I+p;return k>=50?[{proposal:y,proposalMatches:m,score:k}]:[]}).sort((y,m)=>m.score-y.score||y.proposal.id.localeCompare(m.proposal.id)),T=Math.max(1,e.maxPackets??3),P=Math.max(200,e.maxEstimatedTokens??1200),b=[],f=0;for(let y of x){if(b.length>=T)break;let m=y.proposal.sourceRefs.slice(0,4),I={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(k=>k.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:k,...A})=>A)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(k=>k.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Rs(y.proposal,s),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:m},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...m]},p={...I,estimatedTokens:Ps(I)};if(f+p.estimatedTokens>P)break;b.push(p),f+=p.estimatedTokens}let l=Math.max(0,x.length-b.length);return{packets:b,subjectMatches:d.map(({score:y,...m})=>m),completeness:{status:l>0?"truncated":"complete",consideredProposalCount:x.length,omittedPacketCount:l,maxEstimatedTokens:P,estimatedTokens:f},uncertainty:c.size===0?"subject_unresolved":x.length===0?"no_relevant_pending_proposal":void 0}}var Ts=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function uo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function yn(o){return new Set(uo(o).split(" ").filter(e=>e.length>2&&!Ts.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 js(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(uo).filter(Boolean),r=yn([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(u=>({value:u,by:"alias"})),...s.locators.map(u=>({value:u.value,by:"locator"}))];for(let u of d){let x=uo(u.value);for(let b of t){let f=x===b?95:x.includes(b)||b.includes(x)?75:0;f>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:f>=90?"exact":"strong",matchedBy:u.by,score:f})}let P=["/","#","[","]","="].some(b=>u.value.includes(b))?0:Math.round(ar(yn(x),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 Ms(o){return Math.ceil(JSON.stringify(o).length/4)}function vt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function As(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 Es(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 cr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(g=>g.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"),c=i?s.filter(g=>i.has(g.id)):s,d=o.records.filter(g=>g.recordType==="implementation_attempt"),u=o.records.filter(g=>g.recordType==="verification_attempt"),x=o.records.filter(g=>g.recordType==="freshness_signal"&&g.state==="open"),T=o.records.filter(g=>g.recordType==="evidence"),P=o.records.filter(g=>g.recordType==="model_entry"),b=js(r,e),f=new Map(b.map(g=>[g.subjectId,g.score])),l=yn([e.action,e.text].filter(Boolean).join(" ")),y=c.flatMap(g=>{let E=Math.max(0,...g.subjects.map(M=>f.get(M.subjectId)??0)),$=Math.round(ar(yn(g.claim),l)*35),h=E+$;return h>=50?[{decision:g,score:h}]:[]}).sort((g,E)=>E.score-g.score||g.decision.id.localeCompare(E.decision.id)),m=new Map;for(let g of y.slice(0,t))m.set(g.decision.id,g.decision);for(let g of o.relationships){if(!vt(g,"excepts")&&!vt(g,"contradicts"))continue;let E=s.find(h=>h.id===g.from.entityId),$=s.find(h=>h.id===g.to.entityId);!E||!$||!m.has(E.id)&&!m.has($.id)||(m.size<t&&m.set(E.id,E),m.size<t&&m.set($.id,$))}let I=[...m.values()],p=g=>g.from.entityType==="decision"&&g.to.entityType==="decision"&&m.has(g.from.entityId)&&m.has(g.to.entityId),k=(g,E=!1)=>{let $=new Set(g.map(L=>L.id)),h=x.filter(L=>L.target.entityType==="decision"&&$.has(L.target.entityId)),M=new Set(o.relationships.filter(L=>vt(L,"excepts")&&$.has(L.from.entityId)&&$.has(L.to.entityId)).flatMap(L=>[L.from.entityId,L.to.entityId])),N=o.relationships.filter(L=>vt(L,"contradicts")&&$.has(L.from.entityId)&&$.has(L.to.entityId)).map(L=>({id:L.id,decisionIds:[L.from.entityId,L.to.entityId],unresolvedQuestion:L.reason,expansionRefs:[{kind:"record",id:L.id}]})),z=new Set(N.flatMap(L=>L.decisionIds)),K=T.filter(L=>L.sourceRefs.some(G=>G.kind==="record"&&$.has(G.id))||o.relationships.some(G=>G.relationshipType==="supports"&&G.from.entityType==="evidence"&&G.from.entityId===L.id&&G.to.entityType==="decision"&&$.has(G.to.entityId))),Z=Math.max(0,y.length-g.length),re=o.relationships.some(L=>vt(L,"contradicts")&&p(L)&&(!$.has(L.from.entityId)||!$.has(L.to.entityId))),D=E||Z>0||re,V=[];b.length===0&&(e.subjectHints?.length??0)>0?V.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):g.length===0&&V.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),N.length&&V.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:N.flatMap(L=>L.expansionRefs)}),K.some(L=>L.availability!=="available")&&V.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:K.map(L=>({kind:"record",id:L.id}))}),D&&V.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:b.map(({score:L,...G})=>G),modelEntries:P.filter(L=>L.decisionIds.some(G=>$.has(G))).map(L=>({id:L.id,key:L.key,value:L.value,decisionIds:L.decisionIds})),decisions:g.map(L=>({id:L.id,kind:L.kind,claim:L.claim,subjectIds:L.subjects.map(G=>G.subjectId),authority:L.authority,effectiveState:z.has(L.id)?"conflicted":M.has(L.id)?"excepted":"active",freshness:h.filter(G=>G.target.entityId===L.id).map(G=>G.signalType),expansionRef:{kind:"record",id:L.id}})),conflicts:N,uncertainties:V,implementation:g.map(L=>As(L.id,d)),verification:g.map(L=>Es(L.id,u,h)),evidence:K.map(L=>({evidenceId:L.id,summary:L.summary,availability:L.availability,sourceRefs:L.sourceRefs})),completeness:{status:D?"truncated":"complete",omittedDecisionCount:Z,omittedEvidenceCount:0,conflictsComplete:!re}};return he.budget.estimatedTokens=Ms(he),he},A=k(I);for(;A.budget.estimatedTokens>n&&I.length>0;){let g=I.pop(),E=o.relationships.filter($=>vt($,"contradicts")&&($.from.entityId===g.id||$.to.entityId===g.id)).flatMap($=>[$.from.entityId,$.to.entityId]);I=I.filter($=>!E.includes($.id)),A=k(I,!0)}return A}var _s=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function It(o){return _s.test(o)}function Cs(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ee(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function mo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function ke(o,e,n){It(n)||ee(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Ue(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ee(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function lt(o,e,n,t=!1){t&&n.level==="contributor"&&ee(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ee(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var $s={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"])},Os=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ds(o,e,n){ke(o,`${n}.id`,e.id),ke(o,`${n}.projectId`,e.projectId),ke(o,`${n}.participantId`,e.participantId),ke(o,`${n}.entity.entityId`,e.entity.entityId),Ue(o,`${n}.createdAt`,e.createdAt),lt(o,`${n}.authority`,e.authority);let t=$s[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ee(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(Os.has(i)&&(lt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ee(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)&&ee(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ee(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Ue(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function Js(o,e,n,t){ke(o,`${n}.id`,e.id),ke(o,`${n}.projectId`,e.projectId),ke(o,`${n}.participantId`,e.participantId),Ue(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ee(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ee(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ee(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)&&ee(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(lt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ee(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&mo(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())&&ee(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Ue(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ee(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&ee(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&ee(o,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Ue(o,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),Ue(o,`${n}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ee(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Ue(o,`${n}.appliedAt`,e.appliedAt),lt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ee(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())&&ee(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ee(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&mo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&mo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ns(o,e,n){if(ke(o,`${n}.id`,e.id),ke(o,`${n}.projectId`,e.projectId),ke(o,`${n}.participantId`,e.participantId),ke(o,`${n}.from.entityId`,e.from.entityId),ke(o,`${n}.to.entityId`,e.to.entityId),Ue(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ee(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&&ee(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?ee(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&lt(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ee(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ee(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))&&ee(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ee(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function pt(o){let e=[];ke(e,"manifest.projectId",o.manifest.projectId),Ue(e,"manifest.createdAt",o.manifest.createdAt),Ue(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(l,y)=>{let m=n.get(l);m?ee(e,y,"duplicate_id",`ID is already used at ${m}.`):n.set(l,y)};o.records.forEach((l,y)=>{let m=`records[${y}]`;t(l.id,m),Js(e,l,m,o.manifest.projectId)}),o.events.forEach((l,y)=>{let m=`events[${y}]`;t(l.id,m),Ds(e,l,m),l.projectId!==o.manifest.projectId&&ee(e,`${m}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((l,y)=>{let m=`relationships[${y}]`;t(l.id,m),Ns(e,l,m),l.projectId!==o.manifest.projectId&&ee(e,`${m}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((l,y)=>{t(l.id,`artifacts[${y}]`),ke(e,`artifacts[${y}].id`,l.id)}),o.tombstones.forEach((l,y)=>{let m=`tombstones[${y}]`;t(l.id,m),ke(e,`${m}.id`,l.id),ke(e,`${m}.objectId`,l.objectId),ke(e,`${m}.deletedById`,l.deletedById),Ue(e,`${m}.deletedAt`,l.deletedAt),lt(e,`${m}.authority`,l.authority,!0)});let r=new Set(o.records.map(l=>`${l.recordType}:${l.id}`)),i=new Set(o.tombstones.map(l=>`${l.objectType}:${l.objectId}`)),s=(l,y)=>{let m=`${l.entityType}:${l.entityId}`;!r.has(m)&&!i.has(m)&&ee(e,y,"dangling_entity_reference",`No record or tombstone exists for ${m}.`)};o.events.forEach((l,y)=>s(l.entity,`events[${y}].entity`)),o.relationships.forEach((l,y)=>{s(l.from,`relationships[${y}].from`),s(l.to,`relationships[${y}].to`)});let c=new Set(o.artifacts.map(l=>l.id)),d=(l,y)=>{c.has(l)||ee(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},u=(l,y,m)=>{!r.has(`${l}:${y}`)&&!i.has(`${l}:${y}`)&&ee(e,m,"dangling_entity_reference",`No ${l} record or tombstone exists.`)};o.records.forEach((l,y)=>{let m=`records[${y}]`;switch(l.recordType){case"authority_grant":u("participant",l.granteeId,`${m}.granteeId`),u("participant",l.grantedById,`${m}.grantedById`),l.subjectIds.forEach((I,p)=>u("subject",I,`${m}.subjectIds[${p}]`));break;case"observation":l.captureContext.subjectIds.forEach((I,p)=>u("subject",I,`${m}.captureContext.subjectIds[${p}]`)),l.captureContext.artifactIds.forEach((I,p)=>d(I,`${m}.captureContext.artifactIds[${p}]`));break;case"proposal":case"decision":l.subjects.forEach((I,p)=>u("subject",I.subjectId,`${m}.subjects[${p}].subjectId`));break;case"thread":l.messageArtifactIds.forEach((I,p)=>d(I,`${m}.messageArtifactIds[${p}]`)),l.resultRefs.forEach((I,p)=>s(I,`${m}.resultRefs[${p}]`));break;case"iteration":l.threadIds.forEach((I,p)=>u("thread",I,`${m}.threadIds[${p}]`)),l.artifactIds.forEach((I,p)=>d(I,`${m}.artifactIds[${p}]`));break;case"evidence":l.artifactIds.forEach((I,p)=>d(I,`${m}.artifactIds[${p}]`));break;case"advisory_explanation":l.subjectIds.forEach((I,p)=>u("subject",I,`${m}.subjectIds[${p}]`)),l.evidenceIds.forEach((I,p)=>u("evidence",I,`${m}.evidenceIds[${p}]`)),l.supersededById&&u("advisory_explanation",l.supersededById,`${m}.supersededById`);break;case"implementation_attempt":l.iterationIds.forEach((I,p)=>u("iteration",I,`${m}.iterationIds[${p}]`)),l.coverageClaims.forEach((I,p)=>u("decision",I.decisionId,`${m}.coverageClaims[${p}].decisionId`)),l.artifactIds.forEach((I,p)=>d(I,`${m}.artifactIds[${p}]`));break;case"eval_spec":l.replacesSpecId&&u("eval_spec",l.replacesSpecId,`${m}.replacesSpecId`),l.decisionIds.forEach((I,p)=>u("decision",I,`${m}.decisionIds[${p}]`)),l.subjectIds.forEach((I,p)=>u("subject",I,`${m}.subjectIds[${p}]`)),(l.dependencies??[]).forEach((I,p)=>{I.kind==="subject"&&I.subjectId&&u("subject",I.subjectId,`${m}.dependencies[${p}].subjectId`)}),(l.scenarios??[]).forEach((I,p)=>{I.subjectIds?.forEach((k,A)=>u("subject",k,`${m}.scenarios[${p}].subjectIds[${A}]`))}),l.targets.forEach((I,p)=>u(I.entityType,I.entityId,`${m}.targets[${p}]`));break;case"verification_attempt":l.evalSpecId&&u("eval_spec",l.evalSpecId,`${m}.evalSpecId`),l.targets.forEach((I,p)=>u(I.entityType,I.entityId,`${m}.targets[${p}]`)),l.evidenceIds.forEach((I,p)=>u("evidence",I,`${m}.evidenceIds[${p}]`));break;case"model_entry":l.subjectIds.forEach((I,p)=>u("subject",I,`${m}.subjectIds[${p}]`)),l.decisionIds.forEach((I,p)=>u("decision",I,`${m}.decisionIds[${p}]`));break;case"model_projection":lt(e,`${m}.authority`,l.authority,!0),u("participant",l.appliedById,`${m}.appliedById`),l.decisionIds.forEach((I,p)=>u("decision",I,`${m}.decisionIds[${p}]`)),l.entryIds.forEach((I,p)=>u("model_entry",I,`${m}.entryIds[${p}]`)),l.coverage.forEach((I,p)=>u("decision",I.decisionId,`${m}.coverage[${p}].decisionId`));break;case"freshness_signal":s(l.target,`${m}.target`),l.evidenceIds.forEach((I,p)=>u("evidence",I,`${m}.evidenceIds[${p}]`));break;default:break}});let x=new Map(o.events.map(l=>[l.id,l])),T=new Map(o.records.map(l=>[`${l.recordType}:${l.id}`,l])),P=new Map;o.events.forEach((l,y)=>{let m=`${l.entity.entityType}:${l.entity.entityId}:${l.fromState??"null"}`,I=P.get(m)??new Set;I.add(l.toState),P.set(m,I),I.size>1&&ee(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(l=>l.recordType==="authority_grant"?[[l.id,l]]:[])),f=(l,y,m,I,p)=>{if(l.level!=="delegate"||!l.grantId)return;let k=b.get(l.grantId);if(!k){ee(e,p,"invalid_authority_grant","Delegated authority references a missing grant.");return}(k.granteeId!==y||k.level!=="delegate")&&ee(e,p,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(m);(A<Date.parse(k.startsAt)||k.endsAt&&A>Date.parse(k.endsAt)||k.revokedAt&&A>=Date.parse(k.revokedAt))&&ee(e,p,"inactive_authority_grant","The delegated authority grant was not active at this time."),k.subjectIds.length&&I.length&&!I.every(g=>k.subjectIds.includes(g))&&ee(e,p,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let l of o.records)l.recordType==="decision"&&f(l.authority,l.acceptedById,l.createdAt,l.subjects.map(y=>y.subjectId),`records:${l.id}.authority`);o.events.forEach((l,y)=>{let m=T.get(`${l.entity.entityType}:${l.entity.entityId}`),I=m&&"subjects"in m?m.subjects.map(p=>p.subjectId):[];f(l.authority,l.participantId,l.createdAt,I,`events[${y}].authority`)}),o.relationships.forEach((l,y)=>{if(!l.authority)return;let m=[l.from,l.to].flatMap(I=>{let p=T.get(`${I.entityType}:${I.entityId}`);return p&&"subjects"in p?p.subjects.map(k=>k.subjectId):[]});f(l.authority,l.participantId,l.createdAt,m,`relationships[${y}].authority`)});for(let l of o.records){if(l.recordType!=="decision")continue;let y=x.get(l.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==l.proposalId||y.toState!=="accepted")&&ee(e,`records:${l.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==l.acceptedById&&ee(e,`records:${l.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),T.has(`proposal:${l.proposalId}`)||ee(e,`records:${l.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),l.state==="superseded"&&(o.relationships.some(I=>I.relationshipType==="supersedes"&&I.to.entityType==="decision"&&I.to.entityId===l.id)||ee(e,`records:${l.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),l.state==="revoked"&&(o.events.some(I=>I.entity.entityType==="decision"&&I.entity.entityId===l.id&&I.toState==="revoked"&&!!I.reason?.trim())||ee(e,`records:${l.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let l of o.records){if(l.recordType!=="proposal"||l.state!=="accepted")continue;o.records.some(m=>m.recordType==="decision"&&m.proposalId===l.id)||ee(e,`records:${l.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Cs(e)}function Nt(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 dr(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 Bs(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 vn(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."}),It(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Bs(e))It(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={...Nt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=dr(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={...Nt(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={...Nt(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=dr(o,i,e,c.id,e.decisionId),u={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:[u]},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={...Nt(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={...Nt(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 Ls}from"crypto";import{readFile as Fs,readdir as qs,realpath as Us}from"fs/promises";import{join as Bt,relative as zs}from"path";var Gs=["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 wt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Ne(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function lr(...o){return o.find(e=>!!e?.trim())?.trim()}function oe(o,e,n,t){let i=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=Ls("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 fo(o,e){try{return JSON.parse(await Fs(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Hs(o){let e=wt(o);if(!e)return 0;let n=0,t=r=>{let i=wt(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 Ws(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Lt(o){let e=[],n=await Us(o.projectRoot).catch(()=>o.projectRoot),t=Bt(n,".popmelt"),r=await fo(Bt(t,"threads.json"),e),i=await fo(Bt(t,"model.json"),e),s=wt(r),c=wt(s?.threads)??{},d=Object.entries(c).map(([G,W])=>({key:G,value:wt(W)})).filter(G=>!!G.value),u=Bt(t,"decisions"),x=await qs(u).catch(()=>[]),T=[];for(let G of x.filter(W=>W.endsWith(".json")).sort()){let W=wt(await fo(Bt(u,G),e));W&&T.push({file:G,value:W})}let P=d.flatMap(({value:G})=>[G.createdAt,G.updatedAt]).filter(G=>typeof G=="number"&&Number.isFinite(G)),b=P.length?Math.min(...P):0,f=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 l=oe(f,"project",f,b),y=oe(f,"participant","legacy-owner",b),m=oe(f,"participant","legacy-agent",b),I=oe(f,"subject","project",b),p=Ne(Math.max(b,...P)),k=[],A=[],g=new Map,E=new Map,$=new Map(T.map(G=>[G.value.id??G.file.replace(/^d-|\.json$/g,""),G.value])),h=new Map,M=(G,W,se,Se,ye)=>{let Re=g.get(se);if(Re)return Re;let _e=oe(f,"artifact",G,Se);return A.push({id:_e,kind:W,mediaType:ye,location:se,availability:"available"}),g.set(se,_e),_e};for(let{file:G,value:W}of T){let se=W.id??G.replace(/^d-|\.json$/g,""),Se=W.createdAt??b,ye=[M(`${se}:envelope`,"other",`.popmelt/decisions/${G}`,Se,"application/json")];W.screenshotPath&&ye.push(M(`${se}:screenshot`,"screenshot",`.popmelt/${W.screenshotPath.replace(/^\.popmelt\//,"")}`,Se,W.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Re,_e]of(W.pastedImagePaths??[]).entries())ye.push(M(`${se}:image:${Re}`,"image",_e,Se));h.set(se,ye)}let O=(G,W,se)=>({id:G,schemaVersion:1,projectId:l,createdAt:p,participantId:W,sourceRefs:se}),N=(G,W)=>{k.push(W);let se=E.get(G)??[];se.push(W.id),E.set(G,se)},z=[{...O(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...O(m,m,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];k.push(...z),k.push({...O(I,y,[]),recordType:"subject",subjectType:"project",label:zs(process.cwd(),n)||n,aliases:[],locators:[{id:oe(f,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:Ne(b),sourceRefs:[]}]});let K=new Map,Z=(G,W)=>{let se=K.get(G);if(se)return se;let Se=oe(f,"subject",G,W),ye={...O(Se,y,[{kind:"external",id:G}]),createdAt:Ne(W),recordType:"subject",subjectType:"element",label:G,aliases:[],locators:[{id:oe(f,"locator",G,W),kind:"dom_selector",value:G,status:"current",validFrom:Ne(W),sourceRefs:[{kind:"external",id:G}]}]};return k.push(ye),K.set(G,Se),Se};for(let{key:G,value:W}of d){let se=W.id??G,Se=W.createdAt??b,ye=oe(f,"thread",se,Se),Re={kind:"thread",id:se},_e=[],Ge=[],Et=Array.isArray(W.messages)?W.messages:[],He,_t,en=0;Et.forEach((ve,tt)=>{let je=ve.timestamp??Se,Qe=oe(f,"artifact",`${se}:message:${tt}`,je);if(_e.push(Qe),A.push({id:Qe,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${se}/messages/${tt}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${se}/messages/${tt}`,Qe),ve.screenshotPath&&M(`${se}:message:${tt}:screenshot`,"screenshot",ve.screenshotPath,je),ve.role==="human"){He=ve;let Ce=ve.feedbackSummary??ve.replyToQuestion;if(Ce?.trim()){let $e=oe(f,"observation",`${se}:${tt}`,je),rt=W.elementIdentifiers??[],ft={...O($e,y,[Re,{kind:"message",id:Qe}]),createdAt:Ne(je),recordType:"observation",state:"open",statement:Ce,captureContext:{subjectIds:rt.map(st=>Z(st,Se)),artifactIds:[Qe]},resolvedByIds:[]};N(se,ft),_t=$e,Ge.push({entityType:"observation",entityId:$e})}return}if(ve.role!=="assistant")return;let nt=ve.jobId??`${se}:${tt}`,ot=oe(f,"iteration",nt,je),Xe=$.get(nt),zn=ve.cancelled?"cancelled":ve.error?"failed":ve.question?"question_asked":(ve.resolutions?.length??0)>0?"completed":"no_change",Gn={...O(ot,m,[Re,{kind:"message",id:Qe},...(h.get(nt)??[]).map(Ce=>({kind:"artifact",id:Ce}))]),createdAt:Ne(je),recordType:"iteration",threadIds:[ye],startedAt:Ne(He?.timestamp,je),completedAt:Ne(je),requestSummary:lr(He?.feedbackSummary,He?.replyToQuestion)??"[legacy request unavailable]",responseSummary:ve.question??ve.error??ve.responseText?.slice(0,1e3),outcome:zn,execution:{provider:ve.provider??Xe?.provider,model:ve.model??Xe?.model,sessionId:ve.sessionId??Xe?.sessionId},artifactIds:[Qe,...h.get(nt)??[]]};N(se,Gn),Ge.push({entityType:"iteration",entityId:ot});let Ct=ve.resolutions??Xe?.resolutions??[];for(let[Ce,$e]of Ct.entries()){if($e.status!=="resolved"||!$e.summary?.trim())continue;let rt=W.elementIdentifiers??[],ft=(rt.length?rt:[n]).map(nn=>({subjectId:nn===n?I:Z(nn,Se),role:"governed"})),st=oe(f,"proposal",`${nt}:${$e.annotationId??"resolution"}:${Ce}`,je),Hn={...O(st,m,[Re,{kind:"iteration",id:ot}]),createdAt:Ne(je),recordType:"proposal",state:"pending",claim:$e.summary,subjects:ft,subjectSemantics:ft.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:lr(He?.feedbackSummary,He?.replyToQuestion,$e.summary),iterationId:ot,inferredById:m}};N(se,Hn),Ge.push({entityType:"proposal",entityId:st}),e.push({severity:"warning",code:"acceptance_unresolved",source:se,message:`Proposal ${st} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Ct.some(Ce=>Ce.status==="resolved")||Xe?.gitDiff){let Ce=oe(f,"implementation",nt,je),$e={...O(Ce,m,[Re,{kind:"iteration",id:ot}]),createdAt:Ne(je),recordType:"implementation_attempt",state:"completed",iterationIds:[ot],coverageClaims:[],summary:Ct.map(rt=>rt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};N(se,$e),Ge.push({entityType:"implementation_attempt",entityId:Ce}),en+=1}_t&&(_t=void 0)});let tn=Et.at(-1),Un={...O(ye,y,[Re]),createdAt:Ne(Se),recordType:"thread",state:tn?.question?"open":"resolved",messageArtifactIds:_e,outcome:tn?.question?"question_unresolved":en?"implementation_only":"no_outcome",resultRefs:Ge};k.push(Un),E.set(se,[ye,...E.get(se)??[]])}let re=Hs(i);re&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${re} model values were not promoted because their accepted decision provenance is unresolved.`});let D={manifest:{formatVersion:1,projectId:l,createdAt:Ne(b),updatedAt:p,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:k,events:[],relationships:[],artifacts:A,tombstones:[]},V=pt(D),L=(o.proofCaseIds??Gs).map(G=>({legacyId:G,threadFound:d.some(({key:W,value:se})=>(se.id??W)===G),decisionEnvelopeFound:$.has(G),recordIds:E.get(G)??[]}));return{bundle:D,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((G,W)=>G+(W.value.messages?.length??0),0),decisionEnvelopes:T.length,modelEntries:re,artifactsReferenced:A.length},imported:Ws(k),unresolvedAcceptance:e.filter(G=>G.code==="acceptance_unresolved").length,deferredModelEntries:re,proofCases:L,issues:e,schemaIssues:V.issues}}}import{createHash as Vs}from"crypto";import{mkdir as pr,open as ho,readFile as go,readdir as Ks,rename as Qs,unlink as yo}from"fs/promises";import{join as Ze}from"path";var Xs={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function wn(o){return Vs("sha256").update(JSON.stringify(o)).digest("hex")}function ur(o){return wn(o)}function mr(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 Ys(o,e,n){return mr(structuredClone(o),e,n)}async function ut(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await ho(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
121
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Qs(n,o)}catch(r){throw await yo(n).catch(()=>{}),r}}async function In(o){return JSON.parse(await go(o,"utf8"))}var bn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=Ze(e,".popmelt","memory"),this.journalDir=Ze(this.memoryDir,"journal"),this.manifestPath=Ze(this.memoryDir,"manifest.json"),this.checkpointPath=Ze(this.memoryDir,"checkpoint.json"),this.lockPath=Ze(this.memoryDir,"writer.lock")}async initialize(e){let n=pt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await pr(this.journalDir,{recursive:!0});try{throw await go(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 go(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=wn(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 ut(this.checkpointPath,r),await ut(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 ut(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=wn(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 ut(Ze(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await ut(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(!It(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:ur(i)},c=Ys(t.bundle,e,n.committedAt),d=pt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let u=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await ut(Ze(this.journalDir,u),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await ut(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({...Xs,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await In(this.manifestPath),n=await In(Ze(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!==wn(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Ks(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,u=n.journalHash??null,x=new Set;for(let P of s){let b=await In(Ze(this.journalDir,P)),{hash:f,...l}=b;if(f!==ur(l))throw new Error(`Journal hash mismatch: ${P}`);if(b.sequence!==d+1)throw new Error(`Journal sequence gap at ${P}`);if(b.previousHash!==u)throw new Error(`Journal chain mismatch at ${P}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${P}`);if(x.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);mr(c,b.mutation,b.committedAt),d=b.sequence,u=b.hash,x.add(b.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==u)throw new Error("Journal manifest head hash mismatch.");let T=pt(c);if(!T.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(T.issues)}`);return{bundle:c,manifest:e,transactionIds:x,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:u}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await pr(this.memoryDir,{recursive:!0});let n;try{n=await ho(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await In(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 yo(this.lockPath),n=await ho(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await yo(this.lockPath).catch(()=>{})}}};import{randomBytes as Zs}from"crypto";function ge(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Zs(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 ea=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function fr(o,e){let n=o.records.find(p=>p.recordType==="participant"&&p.kind==="human"&&p.status==="active"),t=o.records.find(p=>p.recordType==="participant"&&p.kind==="ai"&&p.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=ea(),u=d.records,x=o.records.find(p=>p.recordType==="thread"&&p.sourceRefs.some(k=>k.kind==="thread"&&k.id===e.threadId));x||(x={id:oe(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(p=>p.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},u.push(x));let T=[];for(let p of[...new Set(e.subjectHints.filter(Boolean))]){let k=o.records.find(A=>A.recordType==="subject"&&A.locators.some(g=>g.value===p&&g.status==="current"));k||(k={id:oe(r,"live-subject",p,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:p}],recordType:"subject",subjectType:"element",label:p,aliases:[],locators:[{id:oe(r,"live-locator",p,e.createdAt),kind:"dom_selector",value:p,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:p}]}]},u.push(k)),T.push(k)}for(let p of[...new Set((e.filePaths??[]).filter(Boolean))]){let k=o.records.find(A=>A.recordType==="subject"&&A.locators.some(g=>g.kind==="source_file"&&g.value===p&&g.status==="current"));k||(k={id:oe(r,"live-file-subject",p,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:p}],recordType:"subject",subjectType:"file",label:p,aliases:[],locators:[{id:oe(r,"live-file-locator",p,e.createdAt),kind:"source_file",value:p,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:p}]}]},u.push(k)),T.push(k)}let P=(e.semanticCandidates??[]).filter(p=>p.claim.trim()),b;if(P.length>0){b=oe(r,"live-observation",i,e.createdAt);let p={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:P.map(k=>k.claim.trim()).join(" "),captureContext:{subjectIds:T.map(k=>k.id),artifactIds:[]},resolvedByIds:[]};u.push(p)}let f=oe(r,"live-iteration",i,e.completedAt),l={id:f,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[x.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};u.push(l);let y=[],m=e.resolutions.filter(p=>p.status==="resolved"&&p.summary.trim()),I=T.length>0?T:o.records.filter(p=>p.recordType==="subject"&&p.subjectType==="project").slice(0,1);if(P.length>0&&I.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[p,k]of P.entries()){let A=oe(r,"live-proposal",`${i}:${p}`,e.completedAt),g=I.map($=>({subjectId:$.id,role:"governed"})),E={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:f},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:k.claim.trim(),rationale:k.rationale?.trim()||void 0,proposedKind:k.proposedKind,subjects:g,subjectSemantics:g.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:k.sourceText?.trim()||e.requestSummary,iterationId:f,inferredById:t.id}};u.push(E),y.push(A)}if(m.length>0){let p=new Set(e.governingDecisionIds??[]),k=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"&&p.has(g.id)),A={id:oe(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:f}],recordType:"implementation_attempt",state:"completed",iterationIds:[f],coverageClaims:k.map(g=>({decisionId:g.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${m.map(E=>E.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:f}]})),summary:m.map(g=>g.summary).join(" "),artifactIds:[]};u.push(A)}return{mutation:d,iterationId:f,proposalIds:y,observationId:b}}import{createHash as ta}from"crypto";import{mkdir as na,open as oa,readFile as ra,rename as ia,unlink as sa}from"fs/promises";import{join as hr}from"path";function gr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function yr(o){return ta("sha256").update(JSON.stringify(o)).digest("hex")}async function aa(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await oa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
122
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await ia(n,o)}catch(r){throw await sa(n).catch(()=>{}),r}}function ca(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,u,x)=>{let T=d[u]??=[];T.includes(x)||T.push(x)};for(let d of o.records)if(d.recordType==="subject"){let u=d;for(let x of[u.label,...u.aliases,...u.locators.filter(T=>T.status==="current").map(T=>T.value)]){let T=gr(x);T&&s(t,T,u.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let u of d.subjects)s(r,u.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let u of d.subjects)s(i,u.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...c,checksum:yr(c)}}function vr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[gr(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 xn=class{constructor(e){this.indexDir=hr(e,".popmelt","memory","indexes"),this.indexPath=hr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await ra(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===yr(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=ca(e,n);return await na(this.indexDir,{recursive:!0}),await aa(this.indexPath,t),t}};var qt="popmelt:imprint",br="popmelt:imprint-evidence",xt="popmelt:imprint-relation";function Sn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===qt)?.id}function vo(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 kn(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 Rn=class{constructor(e){this.projectRoot=e;this.store=new bn(e),this.indexStore=new xn(e),this.manifestPath=bt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Ft(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 Lt({...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 Lt({...e,projectRoot:this.projectRoot})).report}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=bt(this.projectRoot,".popmelt","memory","migrations"),n=bt(e,"imprint-advisories-v2.json");try{let p=JSON.parse(await Ft(n,"utf8"));return{migrated:!1,explanations:p.explanations??0,evidence:p.evidence??0}}catch{}let t;try{t=JSON.parse(await Ft(bt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Ir(e,{recursive:!0}),await wr(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(p=>p.recordType==="participant"&&p.kind==="human"&&p.status==="active"),c=r.bundle.records.find(p=>p.recordType==="participant"&&p.kind==="ai"&&p.status==="active")??i,d=r.bundle.records.find(p=>p.recordType==="subject"&&p.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let u=r.bundle.manifest.projectId,x=new Set(r.bundle.records.map(p=>p.id)),T=new Set(r.bundle.relationships.flatMap(p=>p.sourceRefs.flatMap(k=>k.kind==="external"&&k.uri===xt?[k.id]:[]))),P=new Map,b=r.bundle.records.filter(p=>p.recordType==="advisory_explanation");for(let p of t.explanations){let k=b.find(A=>Sn(A)===p.id);P.set(p.id,k?.id??oe(u,"imprint-explanation",p.id,Date.parse(p.createdAt)))}let f=[],l=[],y=[],m=0;for(let p of t.explanations){let k=P.get(p.id),A=b.find(h=>h.id===k),g=[],E=p.evidence.length?p.evidence:[{id:`fallback:${p.id}`,kind:"observation",stance:"supports",summary:p.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:p.createdAt}];for(let h of E){let M=oe(u,"imprint-evidence-record",h.id,Date.parse(h.createdAt));g.push(M),!x.has(M)&&(f.push({id:M,schemaVersion:1,projectId:u,createdAt:h.createdAt,participantId:c.id,sourceRefs:vo([{kind:"external",id:h.id,uri:br},{kind:"external",id:p.id,uri:qt},{kind:"thread",id:h.threadId},{kind:"message",id:h.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(h.kind)?"user_feedback":"judgment",summary:h.summary,availability:"available",artifactIds:[]}),y.push({id:oe(u,"imprint-evidence-link",`${p.id}:${h.id}`,Date.parse(h.createdAt)),schemaVersion:1,projectId:u,createdAt:h.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:h.id,uri:br}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:k},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),m+=1)}let $={id:k,schemaVersion:1,projectId:u,createdAt:A?.createdAt??p.createdAt,participantId:A?.participantId??c.id,sourceRefs:vo([...A?.sourceRefs??[],{kind:"external",id:p.id,uri:qt}]),recordType:"advisory_explanation",kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),subjectIds:[d.id],evidenceIds:[...new Set([...A?.evidenceIds??[],...g])],concreteBindings:kn(t,p.id),supersededById:p.supersededBy?P.get(p.supersededBy):void 0,updatedAt:p.updatedAt};A?l.push($):f.push($)}for(let p of t.relations){let k=P.get(p.fromId),A=P.get(p.toId);!k||!A||T.has(p.id)||y.push({id:oe(u,"imprint-relation",p.id,Date.parse(p.createdAt)),schemaVersion:1,projectId:u,createdAt:p.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:p.id,uri:xt}],recordType:"relationship",relationshipType:p.type,from:{entityType:"advisory_explanation",entityId:k},to:{entityType:"advisory_explanation",entityId:A},reason:p.rationale||"The Imprint graph connected these explanations."})}let I=new Date().toISOString();if(f.length||l.length||y.length)try{let p=await this.store.commit({records:f,recordReplacements:l,events:[],relationships:y,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:oe(u,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:I});await this.refreshIndex(p)}catch(p){if(!(p instanceof Error)||!p.message.includes("Transaction already exists"))throw p}return await Ir(e,{recursive:!0}),await wr(n,JSON.stringify({version:2,migratedAt:I,explanations:t.explanations.length,evidence:m,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:m}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:po(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:cr(t.bundle,r),reviewSelection:po(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:vn(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 Lt({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=vn(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:ge(i),decisionId:ge(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:ge(i),replacementProposalId:ge(i),acceptanceEventId:ge(i),decisionId:ge(i),relationshipId:ge(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:ge(i),reason:e.reason}:{...c,action:"defer",eventId:ge(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"]}},u=vn(n.bundle,d);if(!u.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:u.errors.map(P=>P.message).join(" ")};let x=await this.store.commitReviewPlan(u.plan,{transactionId:ge(i),committedAt:s});await this.refreshIndex(x);let T=u.plan.resultRefs.find(P=>P.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:T,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:x.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=fr(n.bundle,e),r=oe(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 Ft(bt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),r=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active"),i=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="ai"&&I.status==="active"),s=e.action?r:i??r,c=t.bundle.records.find(I=>I.recordType==="subject"&&I.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),u=Date.parse(d),x=t.bundle.manifest.projectId,T=[],P=[],b=[],f=t.bundle.records.filter(I=>I.recordType==="advisory_explanation"),l=new Map(f.flatMap(I=>{let p=Sn(I);return p?[[p,I.id]]:[]}));for(let I of e.summary.changes)if(!l.has(I.explanationId)){let p=n?.explanations.find(k=>k.id===I.explanationId);l.set(I.explanationId,oe(x,"imprint-explanation",I.explanationId,Date.parse(p?.createdAt??d)))}for(let I of e.summary.changes){let p={kind:"external",id:I.explanationId,uri:qt},k=l.get(I.explanationId),A=f.find(h=>h.id===k),g=n?.explanations.find(h=>h.id===I.explanationId),E={id:oe(x,"imprint-live-evidence",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[p,{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:[]};T.push(E);let $={id:k,schemaVersion:1,projectId:x,createdAt:A?.createdAt??g?.createdAt??d,participantId:A?.participantId??s.id,sourceRefs:vo([...A?.sourceRefs??[],p,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??A?.kind??"pattern",state:g?.state??I.state,statement:g?.statement??I.statement,rationale:g?.rationale??A?.rationale??e.summary.detail,scope:structuredClone(g?.scope??A?.scope??{kind:"project",values:[]}),subjectIds:A?.subjectIds??[c.id],evidenceIds:[...new Set([...A?.evidenceIds??[],E.id])],concreteBindings:g?kn(n,I.explanationId):A?.concreteBindings??[],supersededById:g?.supersededBy?l.get(g.supersededBy):A?.supersededById,updatedAt:g?.updatedAt??d};A?P.push($):T.push($),b.push({id:oe(x,"imprint-live-evidence-link",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[p],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:$.id},to:{entityType:"evidence",entityId:E.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(I=>I.sourceRefs.flatMap(p=>p.kind==="external"&&p.uri===xt?[p.id]:[])));for(let I of n?.relations??[]){let p=l.get(I.fromId),k=l.get(I.toId);!p||!k||y.has(I.id)||b.push({id:oe(x,"imprint-relation",I.id,Date.parse(I.createdAt)),schemaVersion:1,projectId:x,createdAt:I.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:I.id,uri:xt}],recordType:"relationship",relationshipType:I.type,from:{entityType:"advisory_explanation",entityId:p},to:{entityType:"advisory_explanation",entityId:k},reason:I.rationale||"The Imprint graph connected these explanations."})}let m=oe(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,u);try{let I=await this.store.commit({records:T,recordReplacements:P,events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:m,committedAt:d});await this.refreshIndex(I)}catch(I){if(!(I instanceof Error)||!I.message.includes("Transaction already exists"))throw I}}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 Ft(bt(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(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active"),i=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??t;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(g=>g.recordType==="subject"&&g.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(g=>g.recordType==="advisory_explanation"),u=new Map(d.flatMap(g=>{let E=Sn(g);return E?[[E,g]]:[]})),x=new Map([...[...u].map(([g,E])=>[g,E.id]),...e.explanations.filter(g=>!u.has(g.id)).map(g=>[g.id,oe(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),T=[],P=[],b=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let E=u.get(g.id);if(!E){T.push({id:x.get(g.id),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:g.id,uri:qt}],recordType:"advisory_explanation",kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:kn(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let $={...structuredClone(E),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:kn(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt},h=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});h(E)!==h($)&&P.push($)}for(let[g,E]of u)b.has(g)||E.state==="retired"||P.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let f=new Set(n.bundle.tombstones.flatMap(g=>g.objectType==="relationship"?[g.objectId]:[])),l=new Map(n.bundle.relationships.flatMap(g=>{if(f.has(g.id))return[];let E=g.sourceRefs.find($=>$.kind==="external"&&$.uri===xt)?.id;return E?[[E,g]]:[]})),y=new Set(l.keys()),m=[];for(let g of e.relations){let E=x.get(g.fromId),$=x.get(g.toId);!E||!$||y.has(g.id)||m.push({id:oe(c,"imprint-relation",g.id,Date.parse(g.createdAt)),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:g.id,uri:xt}],recordType:"relationship",relationshipType:g.type,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:$},reason:g.rationale||"The Imprint graph connected these explanations."})}let I=new Set(e.relations.map(g=>g.id)),p=t?[...l].filter(([g])=>!I.has(g)).map(([,g])=>({id:oe(c,"imprint-relationship-tombstone",g.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:g.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:t.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!T.length&&!P.length&&!m.length&&!p.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let k=e.updatedAt,A=oe(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(k));try{let g=await this.store.commit({records:T,recordReplacements:P,events:[],relationships:m,artifacts:[],tombstones:p,projectionUpdates:[]},{transactionId:A,committedAt:k});return await this.refreshIndex(g),{status:"synced",relationships:m.length+p.length,explanations:T.length+P.length,headSequence:g.report.headSequence}}catch(g){if(!(g instanceof Error)||!g.message.includes("Transaction already exists"))throw g;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(l=>l.recordType==="advisory_explanation"),i=new Map(r.map(l=>[l.id,l])),s=new Map(r.flatMap(l=>{let y=Sn(l);return y?[[y,l.id]]:[]})),c=new Set(e.map(l=>s.get(l)??l)),d=new Map(t.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),u=new Map(t.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),x=new Set(t.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),T=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),P={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=r.map(l=>{let y=l.evidenceIds.flatMap(p=>{let k=u.get(p);if(!k)return[];let A=k.sourceRefs.find(h=>h.kind==="thread")?.id,g=k.sourceRefs.find(h=>h.kind==="message")?.id,E=k.kind==="judgment"||k.kind==="user_feedback"||k.kind==="project_state"?k.kind:"other",$=d.get(k.participantId)??"unknown";return[{id:k.id,kind:E,summary:k.summary,createdAt:k.createdAt,participantKind:$,threadId:A,jobId:g}]}).sort((p,k)=>k.createdAt.localeCompare(p.createdAt)),m=t.bundle.relationships.flatMap(p=>{if(x.has(p.id))return[];if(!T.has(p.relationshipType))return[];let k=p.from.entityType==="advisory_explanation"&&p.from.entityId===l.id&&p.to.entityType==="advisory_explanation",A=p.to.entityType==="advisory_explanation"&&p.to.entityId===l.id&&p.from.entityType==="advisory_explanation";if(!k&&!A)return[];let g=k?p.to.entityId:p.from.entityId,E=i.get(g);return E?[{id:p.id,type:p.relationshipType,direction:k?"outgoing":"incoming",explanationId:E.id,statement:E.statement,rationale:p.reason}]:[]}),I=[...new Set([...l.sourceRefs.flatMap(p=>p.kind==="thread"?[p.id]:[]),...y.flatMap(p=>p.threadId?[p.threadId]:[])])];return{id:l.id,kind:l.kind,state:l.state,statement:l.statement,rationale:l.rationale,scope:structuredClone(l.scope),createdAt:l.createdAt,updatedAt:l.updatedAt,evidenceCount:y.length,recentEvidence:y.slice(0,4),concrete:l.concreteBindings.map(p=>({...structuredClone(p)})),relations:m,sourceThreadIds:I,needsGrounding:l.state==="testing"&&c.has(l.id)}}).sort((l,y)=>Number(y.needsGrounding)-Number(l.needsGrounding)||P[l.state]-P[y.state]||y.updatedAt.localeCompare(l.updatedAt)),f={total:b.filter(l=>l.state!=="retired").length,emerging:b.filter(l=>l.state==="emerging").length,testing:b.filter(l=>l.state==="testing").length,grounded:b.filter(l=>l.state==="grounded").length,challenged:b.filter(l=>l.state==="challenged").length,retired:b.filter(l=>l.state==="retired").length,needsGrounding:b.filter(l=>l.needsGrounding).length};return{head:{sequence:t.report.headSequence,updatedAt:t.bundle.manifest.updatedAt},counts:f,explanations:b}}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,u)=>d.createdAt.localeCompare(u.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(u=>u.targets.some(x=>x.entityType==="decision"&&x.entityId===c.id)).sort((u,x)=>x.createdAt.localeCompare(u.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(u=>u.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 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(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),r=n.bundle.records.find(h=>h.recordType==="subject"&&h.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=ge(i),d=ge(i),u=ge(i),x=ge(i),T=ge(i),P=new Set(n.bundle.records.flatMap(h=>h.recordType==="model_entry"&&h.key===e.key?h.decisionIds:[])),b=n.bundle.records.filter(h=>h.recordType==="decision"&&h.state==="active"&&P.has(h.id)),f={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},l=[{subjectId:r.id,role:"governed"}],y={...f,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:l,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},m={...f,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."},I={...f,id:u,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:l,noChange:!1,effectiveAt:s},p={...f,id:x,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[u],value:e.value},k={...f,id:T,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[u],entryIds:[x],coverage:[{decisionId:u,status:"projected"}]},A={...f,id:ge(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x},to:{entityType:"decision",entityId:u},reason:"The model change is projected from the owner-confirmed decision."},g=b.map(h=>({...f,id:ge(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:h.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),E=b.map(h=>({...f,id:ge(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:I.id},to:{entityType:"decision",entityId:h.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),$=await this.store.commit({records:[y,I,p,k],events:[m,...g],relationships:[A,...E],artifacts:[],tombstones:[],projectionUpdates:b.map(h=>({entityType:"decision",entityId:h.id,fromState:"active",state:"superseded"}))},{transactionId:ge(i),committedAt:s});return await this.refreshIndex($),{decisionId:u,entryId:x}}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(f=>f.recordType==="model_projection"&&f.state==="applied"&&f.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(f=>f.recordType==="decision"&&e.decisionIds.includes(f.id)&&f.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(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=ge(s),u=e.changes.map(f=>{let l=f.decisionIds?.filter(I=>e.decisionIds.includes(I)),y=l?.length?l:e.decisionIds,m=[...new Set(r.filter(I=>y.includes(I.id)).flatMap(I=>I.subjects.map(p=>p.subjectId)))];return{id:ge(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:y.map(I=>({kind:"record",id:I})),recordType:"model_entry",key:f.path.map(String).join("."),subjectIds:m,decisionIds:y,value:f.value}}),x=new Set(u.flatMap(f=>f.decisionIds)),T={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:e.decisionIds.map(f=>({kind:"record",id:f})),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:u.map(f=>f.id),coverage:e.decisionIds.map(f=>e.coverage?.find(l=>l.decisionId===f)??{decisionId:f,status:x.has(f)?"projected":"unprojected"})},P=u.flatMap(f=>f.decisionIds.map(l=>({id:ge(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:T.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:f.id},to:{entityType:"decision",entityId:l},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...u,T],events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ge(s),committedAt:c});return await this.refreshIndex(b),{projectionId:d,entryIds:u.map(f=>f.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 Lt({...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=vr(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 kt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function be(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function St(o,e,n){let t=be(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Io(o){let e=kt(o),n=kt(e.authority),t=n.level,r=n.mode,i=St(t,"authority.level",["owner","delegate","contributor"]),s=St(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:be(e.proposalId,"proposalId"),participantId:be(e.participantId,"participantId"),occurredAt:be(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:be(e.eventId,"eventId"),decisionId:be(e.decisionId,"decisionId"),kind:St(e.kind,"kind",["principle","preference","rule","constraint"]),reason:be(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:be(e.eventId,"eventId"),reason:be(e.reason,"reason")};case"defer":{let d=kt(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:be(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(u=>be(u,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(u=>St(u,"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:be(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:be(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:be(e.acceptanceEventId,"acceptanceEventId"),decisionId:be(e.decisionId,"decisionId"),relationshipId:be(e.relationshipId,"relationshipId"),claim:be(e.claim,"claim"),kind:St(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let u=kt(d);return{subjectId:be(u.subjectId,"subjectId"),role:St(u.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:be(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function wo(o){let e=kt(o),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(c=>be(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:kt(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 Pn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
123
+ `)}async function xr(o,e,n,t){let r=Pn(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(u=>u.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 Sr(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(`
124
+ `)}function kr(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 Rr(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 bo(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 da(o),i=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,u,x,T,P,b,f,l,y,m,I,p,k,A=[],g=[],E=0,$=[];for(;E<r.length;){let h=r.indexOf(i,E);if(h===-1)break;let M=h+i.length;if(r.slice(h,h+s.length).equals(s))break;let O=M;r[O]===13&&r[O+1]===10&&(O+=2);let N=r.indexOf(`\r
181
125
  \r
182
- `,W);if(ee===-1)break;let H=r.slice(W,ee).toString("utf-8"),te=ee+4,ne=r.indexOf(s,te),ge=ne!==-1?ne-2:r.length;N.push({headers:H,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 W=B[1];if(W==="screenshot")c=T.body;else if(W==="feedback")d=T.body.toString("utf-8");else if(W==="color")l=T.body.toString("utf-8");else if(W==="provider")v=T.body.toString("utf-8");else if(W==="model")R=T.body.toString("utf-8");else if(W==="reasoningEffort")b=T.body.toString("utf-8");else if(W==="serviceTier")I=T.body.toString("utf-8");else if(W==="goal")g=T.body.toString("utf-8");else if(W==="pageUrl")p=T.body.toString("utf-8");else if(W==="viewport")h=T.body.toString("utf-8");else if(W==="planId")f=T.body.toString("utf-8");else if(W==="manifest")y=T.body.toString("utf-8");else if(W==="tasks")x=T.body.toString("utf-8");else if(W==="sourceId")S=T.body.toString("utf-8");else if(W.startsWith("screenshot-")){let ee=W.slice(11);try{let H=decodeURIComponent(ee);J.push({pathname:H,data:T.body})}catch{}}else if(W.startsWith("image-")){let ee=W.split("-"),H=parseInt(ee[ee.length-1],10),te=ee.slice(1,-1).join("-");te&&!isNaN(H)&&A.push({annotationId:te,index:H,data:T.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:v,model:R,reasoningEffort:b,serviceTier:I,goal:g,pageUrl:p,viewport:h,planId:f,manifest:y,tasks:x,sourceId:S,pastedImages:A,pageScreenshots:J}}function Qa(o){return new Promise((e,n)=>{let t=[];o.on("data",r=>t.push(r)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as Xa}from"crypto";var Ya=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,Za=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),ec=new Set(["strengthened","weakened","mixed","unknown"]);function Qt(o,e=180){if(typeof o!="string")return;let n=o.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function tc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function zr(o,e,n,t=Date.now()){let r=tc(o);if(!r)return null;let s=typeof r.transition=="string"&&Za.has(r.transition)?r.transition:null,i=Qt(r.focus);if(!s||!i)return null;let c=typeof r.evidencePosture=="string"&&ec.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Xa(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Qt(r.seeking),workingHypothesis:Qt(r.workingHypothesis),evidencePosture:c,update:Qt(r.update),nextObservation:Qt(r.nextObservation)},contextPolicy:"exclude"}}function Ao(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function nc(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(Ya,(c,d)=>{try{let l=zr(JSON.parse(d),e,s);if(!l)return"";let v=Ao(l);if(r.has(v))return"";r.add(v),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
126
+ `,O);if(N===-1)break;let z=r.slice(O,N).toString("utf-8"),K=N+4,Z=r.indexOf(i,K),re=Z!==-1?Z-2:r.length;$.push({headers:z,body:r.slice(K,re)}),E=Z!==-1?Z:r.length}for(let h of $){let M=h.headers.match(/name="([^"]+)"/);if(!M)continue;let O=M[1];if(O==="screenshot")c=h.body;else if(O==="feedback")d=h.body.toString("utf-8");else if(O==="color")u=h.body.toString("utf-8");else if(O==="provider")x=h.body.toString("utf-8");else if(O==="model")T=h.body.toString("utf-8");else if(O==="reasoningEffort")P=h.body.toString("utf-8");else if(O==="serviceTier")b=h.body.toString("utf-8");else if(O==="goal")f=h.body.toString("utf-8");else if(O==="pageUrl")l=h.body.toString("utf-8");else if(O==="viewport")y=h.body.toString("utf-8");else if(O==="planId")m=h.body.toString("utf-8");else if(O==="manifest")I=h.body.toString("utf-8");else if(O==="tasks")p=h.body.toString("utf-8");else if(O==="sourceId")k=h.body.toString("utf-8");else if(O.startsWith("screenshot-")){let N=O.slice(11);try{let z=decodeURIComponent(N);g.push({pathname:z,data:h.body})}catch{}}else if(O.startsWith("image-")){let N=O.split("-"),z=parseInt(N[N.length-1],10),K=N.slice(1,-1).join("-");K&&!isNaN(z)&&A.push({annotationId:K,index:z,data:h.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:u,provider:x,model:T,reasoningEffort:P,serviceTier:b,goal:f,pageUrl:l,viewport:y,planId:m,manifest:I,tasks:p,sourceId:k,pastedImages:A,pageScreenshots:g}}function da(o){return new Promise((e,n)=>{let t=[];o.on("data",r=>t.push(r)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as la}from"crypto";var pa=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,ua=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),ma=new Set(["strengthened","weakened","mixed","unknown"]);function Ut(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 fa(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Pr(o,e,n,t=Date.now()){let r=fa(o);if(!r)return null;let i=typeof r.transition=="string"&&ua.has(r.transition)?r.transition:null,s=Ut(r.focus);if(!i||!s)return null;let c=typeof r.evidencePosture=="string"&&ma.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:la(),jobId:e,sequence:n,timestamp:t,transition:i,snapshot:{focus:s,seeking:Ut(r.seeking),workingHypothesis:Ut(r.workingHypothesis),evidencePosture:c,update:Ut(r.update),nextObservation:Ut(r.nextObservation)},contextPolicy:"exclude"}}function xo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function ha(o,e,n=0){let t=[],r=new Set,i=n;return{visibleText:o.replace(pa,(c,d)=>{try{let u=Pr(JSON.parse(d),e,i);if(!u)return"";let x=xo(u);if(r.has(x))return"";r.add(x),t.push(u),i++}catch{}return""}).replace(/\n{3,}/g,`
183
127
 
184
- `).trim(),orientations:t}}function oc(o){let e="<orientation>",n=Math.min(o.length,e.length-1);for(let t=n;t>0;t--)if(e.startsWith(o.slice(-t)))return t;return 0}var On=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let c=oc(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,r);let s=this.buffer.indexOf("</orientation>",r+13);if(s<0){this.buffer=this.buffer.slice(r);break}let i=this.buffer.slice(r+13,s).trim();this.buffer=this.buffer.slice(s+14);try{let c=zr(JSON.parse(i),this.jobId,this.sequence);if(!c)continue;let d=Ao(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=nc(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=Ao(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Ur=`## Public orientation updates
128
+ `).trim(),orientations:t}}function ga(o){let e="<orientation>",n=Math.min(o.length,e.length-1);for(let t=n;t>0;t--)if(e.startsWith(o.slice(-t)))return t;return 0}var Tn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let c=ga(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,r);let 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=Pr(JSON.parse(s),this.jobId,this.sequence);if(!c)continue;let d=xo(c);if(this.signatures.has(d))continue;this.signatures.add(d),t.push(c),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=ha(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let i=xo(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Tr=`## Public orientation updates
185
129
  During meaningful transitions in the work, emit a brief public coordination update using this exact form:
186
130
  <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
131
 
188
132
  Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
189
133
  Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
190
134
 
191
- These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function Xt(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),s=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${s} \u2192 Elements: ${r||"none"}`);let i=e?.[t.id];if(i&&i.length>0)for(let c of i)n.push(` Attached image: use the Read tool to view ${c}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let s of t.changes)n.push(`- ${t.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=JSON.stringify(t.original),i=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${c}: ${s} \u2192 ${i}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",i=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${s} \u2192 ${t.targetParentSelector}${i}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
192
- ### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let r of t.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let t=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[t.selector];t.reactComponent&&r.push(`(${t.reactComponent})`),t.context&&r.push(`in ${t.context}`),t.textContent&&r.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
193
- `)}function qr(o,e,n){let t=[],s=new Set(e.annotations.map(i=>i.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!s&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let i=0;for(let c of n.threadHistory)if(c.role==="human")i++,c.replyToQuestion?(t.push(`### Round ${i} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${i} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${i} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${i} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,v=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${v} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0)if(t.push(""),t.push("Rules:"),i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"scope"in i[0]){let v=new Map;for(let R of i)if(typeof R=="object"&&R!==null&&"text"in R){let b=R,I=b.scope||"general";v.has(I)||v.set(I,[]),v.get(I).push(b.text)}for(let[R,b]of v){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let I of b)t.push(`- ${I}`)}}else for(let v of i)typeof v=="string"&&t.push(`- ${v}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),s){let i=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;c.has(l)||c.set(l,[]),c.get(l).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of c){t.push(""),t.push(`## Page: ${d}`);let v=i[d];v&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&n?.provider!=="codex"&&(Object.keys(i).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:l,styleModifications:e.styleModifications},b=Xt(R,n?.imagePaths);b&&(t.push(""),t.push(b))}}else{let i=Xt(e,n?.imagePaths);i&&(t.push(""),t.push(i))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
194
- `)}function Wr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Hr(o,e,n,t){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let s=e.find(i=>i.role==="human"&&i.feedbackContext);if(s?.feedbackContext&&(r.push(""),r.push(s.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let i=0;for(let c of e)c.role==="human"?(i++,c.replyToQuestion?(r.push(`### Round ${i} (human) \u2014 reply`),r.push(`"${c.replyToQuestion}"`)):(r.push(`### Round ${i} (human)`),c.feedbackSummary&&r.push(`Annotations: ${c.feedbackSummary}`))):c.question?(r.push(`### Round ${i} (assistant) \u2014 question`),r.push(`"${c.question}"`)):(r.push(`### Round ${i} (assistant)`),c.responseText&&r.push(`Response: ${c.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let i of t)r.push(`Attached image: use the Read tool to view the image at: ${i}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
195
- `)}function rc(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 sc(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&&!rc(e[n]))return!1;return!0}function Gr(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(sc):[]}catch{return[]}}function Vr(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 ic}from"child_process";import{readdir as ac,readFile as cc,stat as dc}from"fs/promises";import{homedir as Yt}from"os";import{join as Qe}from"path";var Jn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Kr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Kr()}],Zt=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],en={id:"",label:"Default",source:"cli"},lc=/^\s*-\s+"([^"]+)"/;function pc(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(lc);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:_o(s),source:"cli"})}return Nn([en,...e])}function uc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,r)=>{let s=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,i=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return s-i}).flatMap(t=>{let r=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!r)return[];let s=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():_o(r),i=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:s,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...i&&i.length>0?{supportedReasoningLevels:i}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function Kr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function mc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Nn(e.map(n=>({id:n,label:_o(n),source:"cli"})))}function _o(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let s=t[1]==="sonnet"?"Sonn":yc(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 Qr(o="copilot"){let e=await Dn(o,["help","config"]),n=pc(e);return n.length>1?n:[en]}async function Xr(o="codex"){let e=await Dn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(Yt(),".codex");return Zr(Qe(t,"models_cache.json"))}),n=uc(e);return n.length>0?Nn([...n,...Zt]):Zt}async function Yr(o="claude"){let e=Qe(Yt(),".claude"),n=[Qe(Yt(),".claude","stats-cache.json"),Qe(Yt(),".claude","settings.json"),Qe(Yt(),".claude.json"),Qe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Dn(o,["--help"]).catch(()=>""),Dn(o,["--version"]).catch(()=>""),fc(e).catch(()=>[])]),i=gc([...n,...s]),c=await Promise.all(i.map(l=>Zr(l).catch(()=>""))),d=mc([t,r,...c].join(`
197
- `));return Nn([...Jn,...d])}function Dn(o,e,n=5e3){return new Promise((t,r)=>{ic(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function Zr(o){return cc(o,"utf-8")}async function fc(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await es(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function es(o,e,n){if(n<0)return;let t;try{t=await ac(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Qe(o,r.name);if(r.isDirectory()){await es(s,e,n-1);return}if(!(!r.isFile()||!hc(r.name)))try{let i=await dc(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function hc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Nn(o){let e=new Set,n=[];for(let t of o)e.has(t.id)||(e.add(t.id),n.push(t));return n}function gc(o){return[...new Set(o)]}function yc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Bn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let s=this.queue.length-1;s>=0;s--)if(this.queue[s]?.threadId===e.threadId){n=s;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let s of this.listeners)s(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},s=this.activeJobs.has(e);if(!t)return null;let i=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:i,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:s}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let s=!1,i=()=>{s||(s=!0,r())};t.on("exit",i),t.on("error",i),setTimeout(()=>{if(!s){try{t.kill("SIGKILL")}catch{}setTimeout(i,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as He}from"crypto";import{createHash as vc}from"crypto";import{mkdir as wc,open as Ic,readFile as ts,readdir as bc,rename as xc,unlink as Sc}from"fs/promises";import{dirname as Pc,join as Ct}from"path";function $e(o){return structuredClone(o)}function ns(o){return vc("sha256").update(JSON.stringify(o)).digest("hex")}async function tn(o,e){await wc(Pc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ic(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
198
- `,"utf8"),await t.sync()}finally{await t.close()}try{await xc(n,o)}catch(r){throw await Sc(n).catch(()=>{}),r}}function kc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Rc(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 Co(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")Rc(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 Tc(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(c=>c.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=Co(t,[r])}return n}function os(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Fn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ct(e,".popmelt","imprint"),this.manifestPath=Ct(this.imprintDir,"manifest.json"),this.graphPath=Ct(this.imprintDir,"graph.json"),this.journalDir=Ct(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ts(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 bc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=kc(this.projectId,e.createdAt),s=[],i=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await ts(Ct(this.journalDir,t[c]),"utf8")),{hash:l,...v}=d;if(d.sequence!==c+1||d.previousHash!==i||l!==ns(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Co(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},s.push(d),i=d.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=Tc(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}:{}},c={...i,hash:ns(i)},d=Co(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await tn(Ct(this.journalDir,l),c);let v={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await tn(this.graphPath,d),await tn(this.manifestPath,v),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(i.mutations.flatMap(os));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(v=>os(v).some(R=>c.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await tn(this.graphPath,e.graph),await tn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var jc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ec=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Mc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ln(o){return new Set(Mc(o).split(" ").filter(e=>e.length>2&&!Ec.has(e)))}function zn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function $o(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:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function Ee(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function rs(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 Ac(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 Oo(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let b=String(r.reason);if(!jc.has(b))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:b},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let s=r.summary,i=s?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(i)))throw new Error("summary.kind is invalid");let c={kind:i,title:Ee(s?.title,120),detail:Ee(s?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(b=>typeof b=="string"&&!!b.trim()):[],l=[];for(let b of Array.isArray(r.mutations)?r.mutations:[]){if(!b||typeof b!="object")continue;let I=b;if(I.op==="add"&&["intention","principle","pattern"].includes(String(I.kind))){let g=Ee(I.statement),p=Ee(I.rationale);if(!g||!p)continue;l.push({op:"add",clientId:Ee(I.clientId,100)||void 0,kind:I.kind,statement:g,rationale:p,scope:rs(I.scope)})}else if(I.op==="revise"&&typeof I.explanationId=="string"){let g={op:"revise",explanationId:I.explanationId,statement:Ee(I.statement)||void 0,rationale:Ee(I.rationale)||void 0,scope:rs(I.scope),reopenGrounding:I.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(I.op==="evidence"&&typeof I.explanationId=="string"&&["supports","challenges","excepts"].includes(String(I.stance))){let g=Ee(I.summary);g&&l.push({op:"evidence",explanationId:I.explanationId,stance:I.stance,summary:g})}else if(I.op==="relation"&&typeof I.fromId=="string"&&typeof I.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(I.type)))l.push({op:"relation",type:I.type,fromId:I.fromId,toId:I.toId,rationale:Ee(I.rationale)});else if(I.op==="supersede"&&typeof I.explanationId=="string"&&typeof I.replacementId=="string"){let g=Ee(I.reason);g&&l.push({op:"supersede",explanationId:I.explanationId,replacementId:I.replacementId,reason:g})}else if(I.op==="bind_concrete"&&typeof I.explanationId=="string"){let g=Ee(I.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:I.explanationId,modelPath:g,rationale:Ee(I.rationale)})}else I.op==="retire"&&typeof I.explanationId=="string"&&l.push({op:"retire",explanationId:I.explanationId,reason:Ee(I.reason)})}let v=r.grounding,R=v&&typeof v.explanationId=="string"&&Ee(v.question)?{explanationId:v.explanationId,question:Ee(v.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Do(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(s=>` - Concrete terminal: ${s.modelPath} = ${JSON.stringify(s.value)}`)].join(`
199
- `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]}},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
200
- `)}var nn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Fn(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Ln(e.text??""),t=Ln((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:s}=await this.store.load(),i=s.explanations.filter(d=>d.state!=="retired"&&d.state!=="challenged").map(d=>{let l=Ln([d.statement,d.rationale].join(" ")),v=Ln(d.scope.values.join(" ")),R=zn(l,n),b=zn(v,n),I=zn(v,t),g=zn(l,t),p=R+b*.2+I*.25+g*.1+(d.state==="grounded"?.08:0)+(r.has(d.id)?1:0),h=r.has(d.id)||(n.size?R>=.12||b>=.5:I>=.2||g>=.2);return{item:d,score:p,relevant:h}}).filter(d=>d.relevant&&d.score>=.18).sort((d,l)=>l.score-d.score||l.item.updatedAt.localeCompare(d.item.updatedAt)),c=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,c).map(({item:d})=>{let l=new Set(s.relations.filter(v=>v.fromId===d.id&&v.type==="instantiates").map(v=>v.toId));return{id:d.id,kind:d.kind,statement:d.statement,rationale:d.rationale,scope:d.scope,state:d.state,concrete:s.concrete.filter(v=>l.has(v.id)).map(v=>({id:v.id,modelPath:v.modelPath,value:v.value}))}}),truncated:i.length>c,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,c=new Map,d=[],l=new Set,v=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=He();S.clientId&&i.set(S.clientId,A);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,_={id:A,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:$o(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(A,_),l.add(A),d.push({op:"add_explanation",explanation:_})}let 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 _=He(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?$o(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(_,N),c.set(A,_),l.add(_),d.push({op:"add_explanation",explanation:N}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let b=S=>{let A=R(S);return c.get(A)??A};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=b(S.explanationId);if(!s.has(J))continue;let _=Ac(n.concreteModel,S.modelPath);if(!_.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(_.value));N||(N={id:He(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:N})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=b(S.fromId),_=b(S.toId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_relation",relation:{id:He(),type:S.type,fromId:J,toId:_,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(_);continue}if(S.op==="supersede"){let J=b(S.explanationId),_=b(S.replacementId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_evidence",explanationId:J,evidence:ot(n,"challenges",S.reason)}),d.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:_},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"contradicts",fromId:_,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(_);continue}let A=b(S.explanationId);if(s.has(A))if(l.add(A),S.op==="revise"){if(c.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:$o(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:A,patch:J,updatedAt:t})}else S.op==="evidence"?(d.push({op:"add_evidence",explanationId:A,evidence:ot(n,S.stance,S.summary)}),S.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(d.push({op:"add_evidence",explanationId:A,evidence:ot(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let A=b(S),J=s.get(A);!J||J.state==="grounded"||J.state==="retired"||v.has(A)&&!l.has(A)||(l.has(A)||(l.add(A),d.push({op:"add_evidence",explanationId:A,evidence:{...ot(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=He(),g=await this.store.commit({transactionId:I,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),h=[...l].flatMap(S=>{let A=p.get(S);if(!A)return[];let J=!r.graph.explanations.some(N=>N.id===S),_=A.state==="challenged"||A.state==="retired";return[{explanationId:S,action:J?"added":_?"challenged":"revised",statement:A.statement,state:A.state}]}),f=e.grounding?b(e.grounding.explanationId):void 0,y=f?p.get(f):void 0,x=y?.state==="testing"&&!v.has(y.id)?{explanationId:y.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:I,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:h,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let v of l)await this.store.undo(v,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(v=>v.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:i,summary:d,mutations:c})}};function ss(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Un(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Jo(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 is(o){let e=Jo(Un(o.origin));if(e)return e;let n=Jo(Un(o.referer));if(n)return n;let t=Un(o["x-forwarded-host"]);if(!t)return null;let r=Un(o["x-forwarded-proto"])==="https"?"https":"http";return Jo(`${r}://${t}`)}function as(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),i=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=i.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:c,actionableProposals:i}}import{createHash as qn}from"crypto";import{mkdir as on,readFile as bt,unlink as $c,writeFile as Ot}from"fs/promises";import{dirname as Wn,extname as Oc,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 Cc(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 cs(o,e){let n=e??Cc(o);return{kind:n,..._c[n]}}function $t(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ds(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 Dc={version:1,threads:{}},ls=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],rn={version:2,updatedAt:0,files:{}};function Jc(o){return JSON.stringify(o,null,2)}function Nc(o){return Object.fromEntries(ls.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Bc(o){let e={...o};for(let n of ls)delete e[n];return e}function Dt(o){let e=o;if(o.error){let n=cs(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=$t(e.result,!1),t=$t(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Hn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=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 bt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let s=await this.readThread(Oe(this.threadsDir,r));s&&(n[t]=s)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await bt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Dt)}]))},this.index={...rn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Dc,threads:{}},this.index={...rn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Dt(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,Dt(n)):r.messages.push(Dt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=s.messages.filter(c=>c.jobId===n);if(i.length===0)return!1;for(let c of i)if(Object.assign(c,t),c.error){let d=Dt(c);Object.assign(c,d),delete c.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(h=>h.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(h=>h.role==="assistant"),d=h=>{if(h.role!=="assistant")return;if(h.question)return h.question;let f=h.imprintSummary?.grounding;if(f?.question&&!h.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(h=>!!d(h)),v=r.messages.findLastIndex(h=>h.role==="human"),R=l>v?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,I=Array.from(new Set(r.messages.slice(0,Math.max(0,v)).filter(h=>h.role==="assistant"&&!!h.jobId).map(h=>h.jobId))),g=c.some(h=>!!h.responseText||!!h.question||!!h.result||!!h.memoryReviewCard||!!h.memoryReceipt),p=c.some(h=>!!h.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:b,pendingQuestion:R,acknowledgedJobIds:I,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await bt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...s})=>{let i={};if(r?.path)try{let c=await bt(Oe(Wn(this.legacyFilePath),r.path),"utf8");qn("sha256").update(c).digest("hex")===r.sha256&&(i=JSON.parse(c))}catch{}return Dt({...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=Nc(e),t=Bc(e);if(Object.keys(n).length===0)return t;let r=Jc(n),s=qn("sha256").update(r).digest("hex"),i=Oe("artifacts","thread-messages",`${s}.json`);await on(this.artifactsDir,{recursive:!0});try{await bt(Oe(Wn(this.legacyFilePath),i),"utf8")}catch{await Ot(Oe(Wn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Wn(t)===this.mediaDir)return t;try{let r=await bt(t),s=qn("sha256").update(r).digest("hex"),i=Oe(this.mediaDir,`${s}${Oc(t)||".bin"}`);await on(this.mediaDir,{recursive:!0});try{await bt(i)}catch{await Ot(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await on(this.threadsDir,{recursive:!0});let n=this.index??{...rn,files:{}},t=n.files[e.id]??`${qn("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 Ot(Oe(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Ot(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await on(this.threadsDir,{recursive:!0}),this.index=this.index??{...rn,files:{}},await Ot(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...rn,files:{}},t=n.files[e];t&&await $c(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await on(this.threadsDir,{recursive:!0}),await Ot(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Fc,open as Lc,readFile as zc,rename as Uc,unlink as qc}from"fs/promises";import{dirname as Wc,join as Hc}from"path";var ps={schemaVersion:1,theme:"auto",updatedAt:null};function us(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Gc(o,e){await Fc(Wc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Lc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
201
- `,"utf8"),await t.sync()}finally{await t.close()}await Uc(n,o)}catch(t){throw await qc(n).catch(()=>{}),t}}var Gn=class{constructor(e){this.path=Hc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await zc(this.path,"utf8")),n=us(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...ps}}}catch{return{exists:!1,preferences:{...ps}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Gc(this.path,n),n}};function ms(o){return us(o)!==null}function fs(o){return Kc(o).slice(0,12)}var Vc=[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 Kc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Qc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(n/Math.pow(2,b*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,c=1359893119,d=2600822924,l=528734635,v=1541459225,R=new Array(64);for(let b=0;b<e.length;b+=64){for(let A=0;A<16;A++){let J=b+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 I=t,g=r,p=s,h=i,f=c,y=d,x=l,S=v;for(let A=0;A<64;A++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),_=f&y^~f&x,N=S+J+_+Vc[A]+R[A]>>>0,T=Xe(I,2)^Xe(I,13)^Xe(I,22),B=I&g^I&p^g&p,W=T+B>>>0;S=x,x=y,y=f,f=h+N>>>0,h=p,p=g,g=I,I=N+W>>>0}t=t+I>>>0,r=r+g>>>0,s=s+p>>>0,i=i+h>>>0,c=c+f>>>0,d=d+y>>>0,l=l+x>>>0,v=v+S>>>0}return[t,r,s,i,c,d,l,v].map(b=>b.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Qc(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 hs={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 sn=hs.version;var ad=1111,cd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],dd=1800*1e3,ld=3600*1e3,vs=45e3,pd=5e3,ud=1e4;function ws(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 Kn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function md(o,e){if(e.size===1)return[...o].reverse().find(n=>{let t=n.imprintSummary;return n.role==="assistant"&&!!t?.grounding&&!t?.resolvedAction&&e.has(t.grounding.explanationId)})}function Rs(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function fd(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let s=n[n.length-1];s&&s.kind==="text"?s.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",s=t.file??void 0,i=t.content??void 0,c=s?s.split("/").pop()??s:void 0,d;switch(r){case"Read":d=c?`Reading ${c}`:"Reading file";break;case"Edit":d=c?`Editing ${c}`:"Editing file";break;case"Write":d=c?`Writing ${c}`:"Writing file";break;case"Bash":d=i?i.split(`
203
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let l=s??i??void 0,v=s?Bo(s)?s:ks(e,s):void 0,R=n[n.length-1];R&&R.kind==="tool_group"&&R.tool===r?R.items.push({label:d,detail:l,...v?{filePath:v}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...v?{filePath:v}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function hd(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 gd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Is(o){let e=o.styleModifications.flatMap(i=>{let c=i.element?.reactComponent||i.element?.tagName||i.selector;return i.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(i=>`${i.tokenName}: ${i.originalPx}px -> ${i.newPx}px`),t=(o.textModifications??[]).map(i=>`${i.element?.reactComponent||i.element?.tagName||i.selector}: text ${i.original||"empty"} -> ${i.modified||"empty"}`),r=o.annotations.map(i=>{let c=i.instruction?.trim();if(c)return c;if(i.imageCount&&i.imageCount>0)return`${i.imageCount} image${i.imageCount===1?"":"s"}`;let d=i.elements?.[0]?.reactComponent||i.elements?.[0]?.selector||i.linkedSelector||i.type;return`${i.type==="annotation"?"Annotation":`${i.type} annotation`} on ${d}`}),s=[...e,...t,...n,...r].map(i=>gd(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function yd(o,e){let n=o.headers.origin;Rs(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function 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 vd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function wd(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 Qn(o,e){try{o.res.write(`event: ${e.type}
135
+ 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 zt(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(`
136
+ ### ${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(`
137
+ `)}function jr(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 u=d.finalScope??d.inferredScope,x=u?` [${u.breadth} ${u.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${x} \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 x=new Map;for(let T of s)if(typeof T=="object"&&T!==null&&"text"in T){let P=T,b=P.scope||"general";x.has(b)||x.set(b,[]),x.get(b).push(P.text)}for(let[T,P]of x){t.push(`**${T.charAt(0).toUpperCase()+T.slice(1)}**`);for(let b of P)t.push(`- ${b}`)}}else for(let x of s)typeof x=="string"&&t.push(`- ${x}`);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 u=d.pathname||new URL(e.url).pathname;c.has(u)||c.set(u,[]),c.get(u).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,u]of c){t.push(""),t.push(`## Page: ${d}`);let x=s[d];x&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${x}`):!x&&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 T={...e,annotations:u,styleModifications:e.styleModifications},P=zt(T,n?.imagePaths);P&&(t.push(""),t.push(P))}}else{let s=zt(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(`
138
+ `)}function Mr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ar(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(`
139
+ `)}function ya(o){if(typeof o!="object"||o===null)return!1;let e=o;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function va(o){if(typeof o!="object"||o===null||typeof o.annotationId!="string"||o.status!=="resolved"&&o.status!=="needs_review"||typeof o.summary!="string")return!1;let e=o;for(let n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!ya(e[n]))return!1;return!0}function Er(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(va):[]}catch{return[]}}function _r(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 Ia}from"child_process";import{readdir as wa,readFile as ba,stat as xa}from"fs/promises";import{homedir as Gt}from"os";import{join as Ve}from"path";var Mn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Cr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Cr()}],Ht=[{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"}],Wt={id:"",label:"Default",source:"cli"},Sa=/^\s*-\s+"([^"]+)"/;function ka(o){let e=[],n=!1;for(let t of o.split(`
140
+ `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(Sa);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:So(i),source:"cli"})}return An([Wt,...e])}function Ra(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():So(r),s=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let u=d;return typeof u.effort!="string"?[]:[{effort:u.effort,...typeof u.description=="string"?{description:u.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let u=d;return typeof u.id!="string"?[]:[{id:u.id,label:typeof u.name=="string"?u.name:u.id,...typeof u.description=="string"?{description:u.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 Cr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function Pa(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return An(e.map(n=>({id:n,label:So(n),source:"cli"})))}function So(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":Aa(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 $r(o="copilot"){let e=await jn(o,["help","config"]),n=ka(e);return n.length>1?n:[Wt]}async function Or(o="codex"){let e=await jn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Ve(Gt(),".codex");return Jr(Ve(t,"models_cache.json"))}),n=Ra(e);return n.length>0?An([...n,...Ht]):Ht}async function Dr(o="claude"){let e=Ve(Gt(),".claude"),n=[Ve(Gt(),".claude","stats-cache.json"),Ve(Gt(),".claude","settings.json"),Ve(Gt(),".claude.json"),Ve(e,"cache","changelog.md")],[t,r,i]=await Promise.all([jn(o,["--help"]).catch(()=>""),jn(o,["--version"]).catch(()=>""),Ta(e).catch(()=>[])]),s=Ma([...n,...i]),c=await Promise.all(s.map(u=>Jr(u).catch(()=>""))),d=Pa([t,r,...c].join(`
141
+ `));return An([...Mn,...d])}function jn(o,e,n=5e3){return new Promise((t,r)=>{Ia(o,e,{encoding:"utf-8",timeout:n},(i,s)=>{if(i){r(i);return}t(s)})})}async function Jr(o){return ba(o,"utf-8")}async function Ta(o){let e=[Ve(o,"projects"),Ve(o,"telemetry")],n=[];for(let t of e)await Nr(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Nr(o,e,n){if(n<0)return;let t;try{t=await wa(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let i=Ve(o,r.name);if(r.isDirectory()){await Nr(i,e,n-1);return}if(!(!r.isFile()||!ja(r.name)))try{let s=await xa(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function ja(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function An(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 Ma(o){return[...new Set(o)]}function Aa(o){return o.charAt(0).toUpperCase()+o.slice(1)}var En=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==="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 ze}from"crypto";import{createHash as Ea}from"crypto";import{mkdir as _a,open as Ca,readFile as Br,readdir as $a,rename as Oa,unlink as Da}from"fs/promises";import{dirname as Ja,join as Rt}from"path";function Me(o){return structuredClone(o)}function Lr(o){return Ea("sha256").update(JSON.stringify(o)).digest("hex")}async function Vt(o,e){await _a(Ja(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ca(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
142
+ `,"utf8"),await t.sync()}finally{await t.close()}try{await Oa(n,o)}catch(r){throw await Da(n).catch(()=>{}),r}}function Na(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Ba(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Me(e):o.explanations.push(Me(e))}function ko(o,e){let n=Me(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(Me(t.explanation))}else if(t.op==="replace_explanation")Ba(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(Me(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(Me(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,Me(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(Me(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function La(o,e){let n=[],t=Me(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:Me(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:Me(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:Me(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:Me(i)})}t=ko(t,[r])}return n}function Fr(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 _n=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Rt(e,".popmelt","imprint"),this.manifestPath=Rt(this.imprintDir,"manifest.json"),this.graphPath=Rt(this.imprintDir,"graph.json"),this.journalDir=Rt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Br(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 $a(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=Na(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await Br(Rt(this.journalDir,t[c]),"utf8")),{hash:u,...x}=d;if(d.sequence!==c+1||d.previousHash!==s||u!==Lr(x))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=ko(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(T=>T.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,i=La(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:Me(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:Lr(s)},d=ko(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let u=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await Vt(Rt(this.journalDir,u),c);let x={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Vt(this.graphPath,d),await Vt(this.manifestPath,x),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let i=await this.load(),s=i.transactions.find(u=>u.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(u=>u.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(Fr));if(i.transactions.filter(u=>u.sequence>s.sequence).some(u=>u.mutations.some(x=>Fr(x).some(T=>c.has(T)))))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 Vt(this.graphPath,e.graph),await Vt(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Fa=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),qa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Ua(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Cn(o){return new Set(Ua(o).split(" ").filter(e=>e.length>2&&!qa.has(e)))}function $n(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 Ro(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 et(o,e,n){return{id:ze(),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 Te(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function qr(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 Ur(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 Po(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(!Fa.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:Te(i?.title,120),detail:Te(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()):[],u=[];for(let P of Array.isArray(r.mutations)?r.mutations:[]){if(!P||typeof P!="object")continue;let b=P;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let f=Te(b.statement),l=Te(b.rationale);if(!f||!l)continue;u.push({op:"add",clientId:Te(b.clientId,100)||void 0,kind:b.kind,statement:f,rationale:l,scope:qr(b.scope),rootReason:Te(b.rootReason,300)||void 0})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let f={op:"revise",explanationId:b.explanationId,statement:Te(b.statement)||void 0,rationale:Te(b.rationale)||void 0,scope:qr(b.scope),reopenGrounding:b.reopenGrounding===!0};(f.statement||f.rationale||f.scope||f.reopenGrounding)&&u.push(f)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let f=Te(b.summary);f&&u.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:f})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type))){let f=Te(b.rationale);if(!f)continue;u.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:f})}else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let f=Te(b.reason);f&&u.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:f})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let f=Te(b.modelPath,300);f&&u.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:f,rationale:Te(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&u.push({op:"retire",explanationId:b.explanationId,reason:Te(b.reason)})}let x=r.grounding,T=x&&typeof x.explanationId=="string"&&Te(x.question)?{explanationId:x.explanationId,question:Te(x.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:u,grounding:T},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function To(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(`
143
+ `)),...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.","Keep correction identity explicit. If feedback refines an emerging or testing explanation without rejecting its underlying claim, revise it and set reopenGrounding true; do not also add challenging evidence to that same explanation. If feedback rejects the claim as written, preserve that rejected wording, add a distinct replacement, and supersede the old explanation. Never revise an explanation and mark that same identity challenged in one update.","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(`
144
+ `)}var Kt=class{constructor(e,n){this.noopCounts=new Map;this.store=new _n(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=Cn(e.text??""),t=Cn((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(f=>f.state!=="retired"&&f.state!=="challenged").map(f=>{let l=Cn([f.statement,f.rationale].join(" ")),y=Cn(f.scope.values.join(" ")),m=$n(l,n),I=$n(y,n),p=$n(y,t),k=$n(l,t),A=m+I*.2+p*.25+k*.1+(f.state==="grounded"?.08:0)+(r.has(f.id)?1:0),g=r.has(f.id)||(n.size?m>=.12||I>=.5:p>=.2||k>=.2);return{item:f,score:A,relevant:g}}).filter(f=>f.relevant&&f.score>=.18).sort((f,l)=>l.score-f.score||l.item.updatedAt.localeCompare(f.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:f})=>f),u=new Set(d.map(f=>f.id)),x=new Set(i.relations.flatMap(f=>u.has(f.fromId)?[f.toId]:u.has(f.toId)?[f.fromId]:[])),T=new Set(i.explanations.flatMap(f=>x.has(f.id)&&f.state!=="retired"&&f.state!=="challenged"?[f.id]:[])),P=i.explanations.filter(f=>T.has(f.id)&&!u.has(f.id)).sort((f,l)=>l.updatedAt.localeCompare(f.updatedAt)).slice(0,4),b=[...d,...P];for(let f of P)u.add(f.id);return{explanations:b.map(f=>{let l=new Set(i.relations.filter(y=>y.fromId===f.id&&y.type==="instantiates").map(y=>y.toId));return{id:f.id,kind:f.kind,statement:f.statement,rationale:f.rationale,scope:f.scope,state:f.state,concrete:i.concrete.filter(y=>l.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||P.length<T.size,...r.size?{pendingGroundingExplanationIds:[...r]}:{},relations:i.relations.filter(f=>u.has(f.fromId)&&u.has(f.toId)&&f.type!=="instantiates").map(f=>({id:f.id,type:f.type,fromId:f.fromId,toId:f.toId,rationale:f.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(h=>[h.id,h])),s=new Map,c=new Map,d=[],u=new Set,x=new Set(n.pendingGroundingExplanationIds??[]),T=new Set(e.mutations.flatMap(h=>h.op==="revise"&&e.mutations.some(M=>M.op==="evidence"&&M.stance==="challenges"&&M.explanationId===h.explanationId)?[h.explanationId]:[])),P=new Set(e.mutations.flatMap(h=>h.op==="add"&&h.clientId?[h.clientId]:[])),b=h=>i.has(h)||P.has(h),f=new Set;for(let h of e.mutations)h.op==="relation"&&h.fromId!==h.toId&&b(h.fromId)&&b(h.toId)?(f.add(h.fromId),f.add(h.toId)):h.op==="supersede"&&h.explanationId!==h.replacementId&&b(h.explanationId)&&b(h.replacementId)?(f.add(h.explanationId),f.add(h.replacementId)):h.op==="bind_concrete"&&b(h.explanationId)&&Ur(n.concreteModel,h.modelPath).found&&f.add(h.explanationId);let l=r.graph.explanations.length===0;for(let h of e.mutations){if(h.op!=="add")continue;let M=!!(h.clientId&&f.has(h.clientId)),O=!!h.rootReason?.trim()||l;if(!M&&!O)continue;l&&(l=!1);let N=ze();h.clientId&&s.set(h.clientId,N);let z=h.clientId?e.appliedExplanationIds.includes(h.clientId):!1,K={id:N,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:Ro(h.scope),state:z?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[et(n,"supports",e.summary.detail)]};i.set(N,K),u.add(N),d.push({op:"add_explanation",explanation:K})}let y=h=>s.get(h)??h;for(let h of e.mutations){if(h.op!=="revise")continue;let M=y(h.explanationId),O=i.get(M);if(O?.state!=="grounded")continue;let N=ze(),z={id:N,kind:O.kind,statement:h.statement??O.statement,rationale:h.rationale??O.rationale,scope:h.scope?Ro(h.scope):O.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[et(n,"supports",e.summary.detail)]};i.set(N,z),c.set(M,N),u.add(N),d.push({op:"add_explanation",explanation:z}),d.push({op:"add_relation",relation:{id:ze(),type:"refines",fromId:N,toId:M,rationale:h.rationale??e.summary.detail,createdAt:t}})}let m=h=>{let M=y(h);return c.get(M)??M};for(let h of e.mutations){if(h.op==="add")continue;if(h.op==="bind_concrete"){let O=m(h.explanationId);if(!i.has(O))continue;let N=Ur(n.concreteModel,h.modelPath);if(!N.found)continue;let z=r.graph.concrete.find(K=>K.modelPath===h.modelPath&&JSON.stringify(K.value)===JSON.stringify(N.value));z||(z={id:ze(),modelPath:h.modelPath,value:structuredClone(N.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:z})),d.push({op:"add_relation",relation:{id:ze(),type:"instantiates",fromId:O,toId:z.id,rationale:h.rationale,createdAt:t}}),u.add(O);continue}if(h.op==="relation"){let O=m(h.fromId),N=m(h.toId);if(!i.has(O)||!i.has(N)||O===N)continue;d.push({op:"add_relation",relation:{id:ze(),type:h.type,fromId:O,toId:N,rationale:h.rationale,createdAt:t}}),u.add(O),u.add(N);continue}if(h.op==="supersede"){let O=m(h.explanationId),N=m(h.replacementId);if(!i.has(O)||!i.has(N)||O===N)continue;d.push({op:"add_evidence",explanationId:O,evidence:et(n,"challenges",h.reason)}),d.push({op:"revise_explanation",explanationId:O,patch:{state:"challenged",supersededBy:N},updatedAt:t}),d.push({op:"add_relation",relation:{id:ze(),type:"supersedes",fromId:N,toId:O,rationale:h.reason,createdAt:t}}),u.add(O),u.add(N);continue}let M=m(h.explanationId);if(i.has(M))if(u.add(M),h.op==="revise"){if(c.has(y(h.explanationId)))continue;let O=i.get(M);if(!O||O.state!=="emerging"&&O.state!=="testing")continue;let N={...h.statement?{statement:h.statement}:{},...h.rationale?{rationale:h.rationale}:{},...h.scope?{scope:Ro(h.scope)}:{},...h.reopenGrounding||T.has(h.explanationId)?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:M,patch:N,updatedAt:t})}else if(h.op==="evidence"){if(h.stance==="challenges"&&T.has(h.explanationId))continue;d.push({op:"add_evidence",explanationId:M,evidence:et(n,h.stance,h.summary)}),h.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:M,patch:{state:"challenged"},updatedAt:t})}else h.op==="retire"&&(d.push({op:"add_evidence",explanationId:M,evidence:et(n,"challenges",h.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:M,patch:{state:"retired"},updatedAt:t}))}for(let h of e.appliedExplanationIds){let M=m(h),O=i.get(M);!O||O.state==="grounded"||O.state==="retired"||x.has(M)&&!u.has(M)||(u.has(M)||(u.add(M),d.push({op:"add_evidence",explanationId:M,evidence:{...et(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),O.state==="emerging"&&d.push({op:"revise_explanation",explanationId:M,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=ze(),p=await this.store.commit({transactionId:I,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),k=new Map(p.graph.explanations.map(h=>[h.id,h])),A=[...u].flatMap(h=>{let M=k.get(h);if(!M)return[];let O=!r.graph.explanations.some(z=>z.id===h),N=M.state==="challenged"||M.state==="retired";return[{explanationId:h,action:O?"added":N?"challenged":"revised",statement:M.statement,state:M.state}]}),g=e.grounding?m(e.grounding.explanationId):void 0,E=g?k.get(g):void 0,$=E?.state==="testing"&&!x.has(E.id)?{explanationId:E.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:I,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:A,...$?{grounding:$}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let u=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let x of u)await this.store.undo(x,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,ze());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(u=>u.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:{...et(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:{...et(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 u=(e.value??"").split(",").map(x=>x.trim()).filter(Boolean);if(!u.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:i.scope.kind,values:u},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${i.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...et(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 u=e.value?.trim();if(!u)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:u,state:"testing"},updatedAt:n}),d=`Edited: ${u}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:ze(),committedAt:n,source:s,summary:d,mutations:c})}};function zr(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function On(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function jo(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 Gr(o){let e=jo(On(o.origin));if(e)return e;let n=jo(On(o.referer));if(n)return n;let t=On(o["x-forwarded-host"]);if(!t)return null;let r=On(o["x-forwarded-proto"])==="https"?"https":"http";return jo(`${r}://${t}`)}function Hr(o,e,n=5){let t=(d,u)=>(u.completedAt??u.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,u)=>u.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,u)=>(d[u.status]=(d[u.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Dn}from"crypto";import{mkdir as Qt,readFile as mt,unlink as Ha,writeFile as Tt}from"fs/promises";import{dirname as Jn,extname as Wa,join as Ae}from"path";var za={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 Ga(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 Wr(o,e){let n=e??Ga(o);return{kind:n,...za[n]}}function Pt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function Vr(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 Va={version:1,threads:{}},Kr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],Xt={version:2,updatedAt:0,files:{}};function Ka(o){return JSON.stringify(o,null,2)}function Qa(o){return Object.fromEntries(Kr.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Xa(o){let e={...o};for(let n of Kr)delete e[n];return e}function jt(o){let e=o;if(o.error){let n=Wr(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=Pt(e.result,!1),t=Pt(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 Nn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Ae(e,".popmelt");this.legacyFilePath=Ae(n,"threads.json"),this.threadsDir=Ae(n,"threads"),this.indexPath=Ae(this.threadsDir,"index.json"),this.artifactsDir=Ae(n,"artifacts","thread-messages"),this.mediaDir=Ae(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await mt(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(Ae(this.threadsDir,r));i&&(n[t]=i)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await mt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(jt)}]))},this.index={...Xt,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Va,threads:{}},this.index={...Xt,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(jt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,jt(n)):r.messages.push(jt(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=jt(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 m=y.imprintSummary?.grounding;if(m?.question&&!y.imprintSummary?.resolvedAction)return m.question},u=r.messages.findLastIndex(y=>!!d(y)),x=r.messages.findLastIndex(y=>y.role==="human"),T=u>x?d(r.messages[u]):void 0,P=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,x)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),f=c.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),l=c.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:f,hasError:l,lastMessageRole:P,pendingQuestion:T,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 mt(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 mt(Ae(Jn(this.legacyFilePath),r.path),"utf8");Dn("sha256").update(c).digest("hex")===r.sha256&&(s=JSON.parse(c))}catch{}return jt({...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=Qa(e),t=Xa(e);if(Object.keys(n).length===0)return t;let r=Ka(n),i=Dn("sha256").update(r).digest("hex"),s=Ae("artifacts","thread-messages",`${i}.json`);await Qt(this.artifactsDir,{recursive:!0});try{await mt(Ae(Jn(this.legacyFilePath),s),"utf8")}catch{await Tt(Ae(Jn(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(Jn(t)===this.mediaDir)return t;try{let r=await mt(t),i=Dn("sha256").update(r).digest("hex"),s=Ae(this.mediaDir,`${i}${Wa(t)||".bin"}`);await Qt(this.mediaDir,{recursive:!0});try{await mt(s)}catch{await Tt(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 Qt(this.threadsDir,{recursive:!0});let n=this.index??{...Xt,files:{}},t=n.files[e.id]??`${Dn("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 Tt(Ae(this.threadsDir,t),JSON.stringify(i,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Tt(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 Qt(this.threadsDir,{recursive:!0}),this.index=this.index??{...Xt,files:{}},await Tt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...Xt,files:{}},t=n.files[e];t&&await Ha(Ae(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await Qt(this.threadsDir,{recursive:!0}),await Tt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Ya,open as Za,readFile as ec,rename as tc,unlink as nc}from"fs/promises";import{dirname as oc,join as rc}from"path";var Qr={schemaVersion:1,theme:"auto",updatedAt:null};function Xr(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function ic(o,e){await Ya(oc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Za(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
145
+ `,"utf8"),await t.sync()}finally{await t.close()}await tc(n,o)}catch(t){throw await nc(n).catch(()=>{}),t}}var Bn=class{constructor(e){this.path=rc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await ec(this.path,"utf8")),n=Xr(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Qr}}}catch{return{exists:!1,preferences:{...Qr}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await ic(this.path,n),n}};function Yr(o){return Xr(o)!==null}function Zr(o){return ac(o).slice(0,12)}var sc=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function ac(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):cc(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,u=528734635,x=1541459225,T=new Array(64);for(let P=0;P<e.length;P+=64){for(let A=0;A<16;A++){let g=P+A*4;T[A]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])>>>0}for(let A=16;A<64;A++){let g=Ke(T[A-15],7)^Ke(T[A-15],18)^T[A-15]>>>3,E=Ke(T[A-2],17)^Ke(T[A-2],19)^T[A-2]>>>10;T[A]=T[A-16]+g+T[A-7]+E>>>0}let b=t,f=r,l=i,y=s,m=c,I=d,p=u,k=x;for(let A=0;A<64;A++){let g=Ke(m,6)^Ke(m,11)^Ke(m,25),E=m&I^~m&p,$=k+g+E+sc[A]+T[A]>>>0,h=Ke(b,2)^Ke(b,13)^Ke(b,22),M=b&f^b&l^f&l,O=h+M>>>0;k=p,p=I,I=m,m=y+$>>>0,y=l,l=f,f=b,b=$+O>>>0}t=t+b>>>0,r=r+f>>>0,i=i+l>>>0,s=s+y>>>0,c=c+m>>>0,d=d+I>>>0,u=u+p>>>0,x=x+k>>>0}return[t,r,i,s,c,d,u,x].map(P=>P.toString(16).padStart(8,"0")).join("")}function Ke(o,e){return o>>>e|o<<32-e}function cc(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 ei={name:"@popmelt.com/core",version:"0.8.8",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 Yt=ei.version;var xc=1111,Sc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],kc=1800*1e3,Rc=3600*1e3,oi=45e3,Pc=5e3,Tc=1e4;function ri(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(`
146
+ `)}function Zt(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function jc(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 ci(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 Mc(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(`
147
+ `)[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 u=i??s??void 0,x=i?ai(i)?i:wc(e,i):void 0,T=n[n.length-1];T&&T.kind==="tool_group"&&T.tool===r?T.items.push({label:d,detail:u,...x?{filePath:x}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:u,...x?{filePath:x}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function Ac(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(`
148
+ `)}function Ec(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function ii(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),t=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),i=[...e,...t,...n,...r].map(s=>Ec(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function _c(o,e){let n=o.headers.origin;ci(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 C(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function Be(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 Cc(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function $c(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 qn(o,e){try{o.res.write(`event: ${e.type}
205
149
  data: ${JSON.stringify(e)}
206
150
 
207
- `)}catch{}}function xt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function Id(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 bd(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 bs(o){try{let e=Xn("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=Xn("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=Xn("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Ps("sha256").update(`${e}
208
- ${t}
209
- ${r}`).digest("hex").slice(0,16)}catch{return}}function xd(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 xs(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let s of[...t].sort((i,c)=>`${i.kind}:${i.value}`.localeCompare(`${c.kind}:${c.value}`)))if(s.kind==="model_path")r.push([s.kind,s.value,xd(n,s.value)]);else if(s.kind==="source_file"){let i=ks(o,s.value),d=i===o||i.startsWith(`${o}/`)?await No(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,d])}else r.push([s.kind,s.value]);return Ps("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ts(o={}){let e=new Date().toISOString(),n=o.port??ad,t=o.projectRoot??process.cwd(),r=await ed(t).catch(()=>t),s=fs(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Me(rd(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,v=[...o.allowedTools??cd],R=o.claudePath??"claude",b=o.copilotPath??"copilot",I=o.provider??"claude",g=o.timeoutMs,p=o.restartMode??"embedded",h=n,f={},y={claude:R,codex:"codex",copilot:b};for(let[a,u]of Object.entries(y))try{let k=u.includes("/")?u:Xn("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=gs(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 Yr(f.claude.path).catch(()=>Jn):Jn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await Xr(f.codex.path).catch(()=>Zt):Zt)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await Qr(f.copilot.path).catch(()=>[en]):[en])})()]);let[S,A,J]=await Promise.all([fo(r),ho(r),go(r,f.copilot?.path??b)]),_=await gr(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=A),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&v.push(`mcp__${S.name}__*`),await Yc(c,{recursive:!0}),Ss(c).catch(()=>{});let N=new Bn(1),T=new bn,B=new Pn(vs),W=null,ee=0,H=!1,te=()=>{ee+=1,H=!1,W&&clearTimeout(W),W=null},ne=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ge=()=>{if(p!=="detached"||B.size>0||H)return;H=!0;let a=++ee,u=Date.now()+ud,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){H=!1,W=setTimeout(ne,50),W.unref?.();return}W=setTimeout(k,250),W.unref?.()};k()},X=new Set,G=new Hn(r),U=new _n(r),he=new nn(r,s),M=new Gn(r),Y=new fn(r),ue=new yn(r),ie=new In(r,{claudePath:R,provider:I,timeoutMs:g,loadProjectableDecisions:a=>U.getProjectableDecisions(a),onEvent:a=>{for(let u of X)Qn(u,a)}});U.beginAutomaticInitialization({writerVersion:sn}).then(async a=>{a.state==="ready"?(await U.migrateLegacyEvals(),await U.migrateImprintSnapshot(),await ie.applyCanonicalEntries(await U.getCanonicalModelEntries()),I!=="copilot"&&(await ie.getUnprojectedPatternDecisions()).length>0&&await je({provider:I,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${h}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let 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=rr(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(L=>L.filePath?[L.filePath]:[])).map(D=>Bo(D)?ys(r,D):D))].map(D=>({kind:"source_file",value:D})),j=k.map(D=>{let L=[...new Map([...D.dependencies??[],...m,...w].map(q=>[`${q.kind}:${q.value}:${"subjectId"in q?q.subjectId??"":""}`,q])).values()],F=L.filter(q=>q.kind==="route"),C=L.flatMap(q=>q.kind==="model_path"&&q.value.startsWith("components.")?[q.value.slice(11).split(".")[0]]:[]),O=[...new Set(L.flatMap(q=>"subjectId"in q&&q.subjectId?[q.subjectId]:[]))],K=F.length>0?F.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:L,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(L=>L.evalId===D.id)||!a.generatedEvalIds?.includes(D.id))?"extended":"created"}))),j.map(D=>D.id)}async function rt(a){let u=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",k=so(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 ut=null,Jt;N.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&Qn(m,a)}),T.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&Qn(m,a)}),T.setProcessor(async a=>{let u=a.provider??I;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?pr(j,$):null;if(j&&D){let L=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:L});let F=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");F&&await Ye(F)}}let w=hd(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.
151
+ `)}catch{}}function At(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function Oc(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 Dc(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")})}async function di(o={}){let e=new Date().toISOString(),n=o.port??xc,t=o.projectRoot??process.cwd(),r=await mc(t).catch(()=>t),i=Zr(r),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ee(yc(),"popmelt-bridge"),d=o.maxTurns??40,u=o.maxBudgetUsd??1,x=[...o.allowedTools??Sc],T=o.claudePath??"claude",P=o.copilotPath??"copilot",b=o.provider??"claude",f=o.timeoutMs,l=o.restartMode??"embedded",y=n,m={},I={claude:T,codex:"codex",copilot:P};for(let[a,v]of Object.entries(I))try{let R=v.includes("/")?v:lc("which",[v],{encoding:"utf-8"}).trim();m[a]={available:!0,path:R}}catch{m[a]={available:!1,path:null}}function p(a,v){return new Promise(R=>{let w=ti(v,["--version"],{stdio:["ignore","ignore","ignore"]}),j=!1,S=J=>{j||(j=!0,R(J))},_=setTimeout(()=>{w.kill("SIGTERM"),S(!0)},5e3);w.on("error",()=>{clearTimeout(_),S(!1)}),w.on("close",J=>{clearTimeout(_),S(J===0)})})}await Promise.all([(async()=>{m.claude&&(m.claude.models=m.claude.available&&m.claude.path?await Dr(m.claude.path).catch(()=>Mn):Mn)})(),(async()=>{m.codex&&(m.codex.models=m.codex.available&&m.codex.path?await Or(m.codex.path).catch(()=>Ht):Ht)})(),(async()=>{m.copilot&&(m.copilot.models=m.copilot.available&&m.copilot.path?await $r(m.copilot.path).catch(()=>[Wt]):[Wt])})()]);let[k,A,g]=await Promise.all([ro(r),io(r),so(r,m.copilot?.path??P)]);m.claude&&(m.claude.mcp=k),m.codex&&(m.codex.mcp=A),m.copilot&&(m.copilot.mcp=g),k.found&&k.name&&x.push(`mcp__${k.name}__*`),await pc(c,{recursive:!0}),si(c).catch(()=>{});let E=new En(1),$=new mn,h=new hn(oi),M=null,O=0,N=!1,z=()=>{O+=1,N=!1,M&&clearTimeout(M),M=null},K=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},Z=()=>{if(l!=="detached"||h.size>0||N)return;N=!0;let a=++O,v=Date.now()+Tc,R=()=>{if(a!==O)return;if(h.size>0){z();return}if(!(E.isRunning||E.depth>0||$.isRunning||$.depth>0)||Date.now()>=v){N=!1,M=setTimeout(K,50),M.unref?.();return}M=setTimeout(R,250),M.unref?.()};R()},re=new Set,D=new Nn(r),V=new Rn(r),he=new Kt(r,i),L=new Bn(r),G=new dn(r),W=new un(r,{claudePath:T,provider:b,timeoutMs:f,loadProjectableDecisions:a=>V.getProjectableDecisions(a),onEvent:a=>{for(let v of re)qn(v,a)}});V.beginAutomaticInitialization({writerVersion:Yt}).then(async a=>{a.state==="ready"?(await V.migrateImprintSnapshot(),await V.syncImprintGraph(),await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),b!=="copilot"&&(await W.getUnprojectedPatternDecisions()).length>0&&await Xe({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 se=20,Se=300*1e3,ye=[];function Re(){let a=Date.now()-Se;for(;ye.length>0&&(ye[0].completedAt<a||ye.length>se);)ye.shift()}let _e=new Map,Ge=null,Et;E.addListener((a,v,R)=>{for(let w of re)(!R||!w.sourceId||w.sourceId===R)&&qn(w,a)}),$.addListener((a,v,R)=>{for(let w of re)(!R||!w.sourceId||w.sourceId===R)&&qn(w,a)}),$.setProcessor(async a=>{let v=a.provider??b;try{let R=await W.run({provider:v,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let w=await W.loadRuns(),j=R.runId?w.runs.find(_=>_.id===R.runId):void 0;if(R.success&&R.proposalId){let _=await W.findModelProposal(R.proposalId),J=await W.loadModel(),B=_?Vo(_,J):null;if(_&&B){let H=_.decisionIds.map(F=>({decisionId:F,status:"projected"}));await V.applyModelProjection({runId:_.runId??_.id,presentationJobId:_.presentationJobId,decisionIds:_.decisionIds,changes:B.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:H}),await W.applySelectedModelProposal(_.id,B.map(F=>({path:F.path,value:F.value})),B.map(F=>({group:F.path[0]==="rules"||F.path[0]==="components"||F.path[0]==="tokens"?F.path[0]:"model",label:F.label??F.id,detail:F.rationale,path:F.path,value:F.value})),"automatic")}}let S=Ac(R,j);if(a.threadId&&(await D.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:v})||await D.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:v})),R.success)a.status="done",a.result=S,$.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),ye.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Re();else{if(a.status="error",a.error=R.error??"Projection failed",a.threadId){let _=`Model projection failed.
210
152
 
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.
153
+ ${a.error}`;await D.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:_,error:a.error,model:a.model,provider:v})||await D.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:_,error:a.error,model:a.model,provider:v})}$.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),ye.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Re()}}catch(R){if(a.status==="cancelled")return;if(a.status="error",a.error=R instanceof Error?R.message:String(R),a.threadId){let w=`Model projection failed.
212
154
 
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??I,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 L;if(a.threadId){let de=await G.getThread(a.threadId);if(de){for(let pe=de.messages.length-1;pe>=0;pe--)if(de.messages[pe].sessionId){L=de.messages[pe].sessionId;break}}}(j||$)&&(L=void 0);let F;if(L&&k){if(F=m??k,P&&P.length>0){F+=`
155
+ ${a.error}`;await D.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,error:a.error,model:a.model,provider:v})||await D.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,error:a.error,model:a.model,provider:v})}$.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),ye.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Re()}}),E.setProcessor(async a=>{let v=a,R=v._replyPrompt,w=v._replyText,j=v._replyImagePaths,S=a.provider??b,_=!!(a.surfacedProposalIds?.length&&R),J=!_&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&w!==void 0&&await D.updateMessage(a.threadId,a.id,{queued:!1});let B;if(a.threadId){let q=await D.getThread(a.threadId);if(q){for(let ie=q.messages.length-1;ie>=0;ie--)if(q.messages[ie].sessionId){B=q.messages[ie].sessionId;break}}}_&&(B=void 0);let H;if(B&&R){if(H=w??R,j&&j.length>0){H+=`
214
156
 
215
- The developer attached reference images with their reply:`;for(let de of P)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+=`
157
+ The developer attached reference images with their reply:`;for(let q of j)H+=`
158
+ Attached image: use the Read tool to view the image at: ${q}`}a.kind==="synthesize"?H+=`
217
159
 
218
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+=`
160
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:H+=`
219
161
 
220
- After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(L)F=Xt(a.feedback,a.imagePaths)+`
162
+ 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(B)H=zt(a.feedback,a.imagePaths)+`
221
163
 
222
164
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
223
165
 
224
- After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(w!=="codex"?`
166
+ After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
225
167
 
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();F=k??qr(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:w,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}F+=Br(a.memoryReview),D&&(F+=Do(a.imprintContext)),F+=`
168
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let q=!R&&a.threadId?await D.getThreadHistory(a.threadId):void 0,ie=R?null:await W.loadModel();H=R??jr(a.screenshotPath,a.feedback,{threadHistory:q&&q.length>0?q:void 0,provider:S,imagePaths:a.imagePaths,designModel:ie??void 0,screenshotPaths:a.screenshotPaths})}H+=Sr(a.memoryReview),J&&(H+=To(a.imprintContext)),H+=`
227
169
 
228
- ${Ur}`;let C=wd(a.color,`[\u22B9 ${h}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${C} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${L?` (resuming: ${L.slice(0,8)})`:""}`);let K=new On(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"?mn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:L,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:ln(a.agentSettings),onEvent:q}):w==="copilot"?tr(a.id,{prompt:F,projectRoot:r,resumeSessionId:L,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??b,onEvent:q}):pn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:j?["Read"]:v,claudePath:R,resumeSessionId:L,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?Oo(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=Wr(ve),pe=Gr(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?fd(Ce.events,r):void 0,ke,Z=Lr(ve),fe=Fr(ve);if(fe)if(!(a.memoryReview?.packets.some(re=>re.proposalId===fe.proposalId)||a.surfacedProposalIds?.includes(fe.proposalId)))ke={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{ke=await U.commitConversationalReview(fe)}catch(re){ke={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:re instanceof Error?re.message:String(re)}}let Re=[...(oe.fileEdits??[]).map(z=>z.file_path),...(oe.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],xe,ht=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:ht}),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?md(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 Ft=ds({question:de,resolutions:pe,changedFiles:Re,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:Ft},result:Ft,memoryReviewCard:Z??void 0,memoryReceipt:ke,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??(Cn(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=>Bo(re)?ys(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(ke?.status==="committed"&&ke.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 ${ke.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=or(ve,z.assertions),Ke=Date.now(),Hs={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:bs(r),rawResponse:ve,scopeFingerprint:a._evalScopeFingerprint,...Ve};await U.recordEvalVerification(z,Hs),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=Vr(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:Ft},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 Nt=od(async(a,u)=>{if(yd(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:${h}`),w=P.pathname,j=vd(a,P);if(j&&j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Vn(r)});return}if(a.headers.origin){if(!Rs(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:Vn(r)});return}}try{if(a.method==="POST"&&w==="/send")await Ae(a,u);else if(a.method==="GET"&&w==="/events")it(a,u);else if(a.method==="GET"&&w==="/status")await at(a,u,j);else if(a.method==="GET"&&w==="/ui-preferences")await Yn(u);else if(a.method==="PATCH"&&w==="/ui-preferences")await Zn(a,u);else if(a.method==="PATCH"&&w==="/config")await mt(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():"",L=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){E(u,400,{error:"A valid leaseId is required."});return}te();let F=B.acquire(D,L);E(u,201,{ok:!0,lease:F,ttlMs:vs})}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{}Nt.close(()=>{gs(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 st(a,u,w);else if(w.startsWith("/memory/"))await we(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await $s(a,u);else if(a.method==="POST"&&w==="/reply")await Ze(a,u);else if(a.method==="POST"&&w==="/cancel")Bt(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 ct($,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 St($,a,u)}else if(w.startsWith("/model/proposals/"))E(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await Os(a,u);else if(a.method==="DELETE"&&w==="/model/component")await Ds(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Js(a,u);else if(a.method==="DELETE"&&w==="/model/token")await Ns(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 xs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),L=bs(r),F=(await U.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===L);E(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:F,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&w.startsWith("/evals/")&&w.endsWith("/run")){let $=w.slice(7,-4);await eo($,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await cn(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),L=N.getBufferedEvents($,isNaN(D)?-1:D);L?E(u,200,L):E(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await zs(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($),L=[...D?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(D&&L?.annotationSnapshot){let F=[...D.messages].reverse().find(C=>C.resolutions?.length);E(u,200,{decision:{id:D.id,createdAt:L.timestamp,url:L.annotationSnapshot.url,viewport:L.annotationSnapshot.viewport,color:L.annotationSnapshot.color,annotations:L.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await Y.loadDecision($);F?E(u,200,{decision:F,authority:"legacy_archive"}):E(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let $=w.slice(8);await Us($,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let $=w.slice(8);await qs($,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?Bs(a,u):a.method==="GET"&&w==="/canvas/manifest"?await Fs(u):a.method==="GET"&&w==="/canvas/app.mjs"?await Ls(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}.`)):[],L=(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)},F=(await U.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(q=>q.kind==="route"&&L(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&&L(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:F});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 L=await ie.findModelProposalsByThread(P),F=(await Promise.all(L.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-${pt().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:xt(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&F&&await ie.dismissModelProposal(F.id);let se=xt(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:gt(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(Mo(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(Mo(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:sn});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(Eo(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(Eo(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 st(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=>Kn(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),L=[...D?.messages??[]].reverse().find(se=>se.role==="assistant"&&se.imprintSummary?.transactionId===w),F=L?.imprintSummary;if(!D||!L||!F){E(u,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){E(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${pt().slice(0,8)}`;await he.applyGroundingAction({summary:F,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:P,jobId:C}),await U.recordImprintEvidence({summary:F,action:j,threadId:P,jobId:C}).catch(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));let O=$t(L.result,!!L.question),K=L.turn?{...L.turn,result:$t(L.turn.result,!!L.question)}:void 0;await G.updateAssistantMessage(P,L.jobId,{imprintSummary:{...F,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:L,pastedImages:F,pageScreenshots:C}=await $n(a),O;try{O=JSON.parse(m)}catch{E(u,400,{error:"Invalid feedback JSON"});return}let K=pt().slice(0,8),q={};if(C.length>0)for(let Z of C){let fe=encodeURIComponent(Z.pathname),Re=Me(c,`screenshot-${K}-${fe}.webp`);await an(Re,Z.data),q[Z.pathname]=Re}let se=Me(c,`screenshot-${K}.webp`);await an(se,k);let ae={};if(F.length>0)for(let Z of F){let fe=Me(c,`pasted-${K}-${Z.annotationId}-${Z.index}.webp`);await an(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 Nr(U,O,oe,Z=>console.warn(`[\u22B9 ${h}:${K}] Contextual memory unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))),de=await he.contextualize({text:Cn(O),subjectHints:[...oe,...O.annotations.flatMap(Z=>[Z.pathname,Z.elements?.[0]?.reactComponent].filter(fe=>!!fe))],pendingGroundingExplanationIds:Kn((await G.getThread(be))?.messages??[])}).catch(Z=>{console.warn(`[\u22B9 ${h}:${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:xt(w),model:j||void 0,agentSettings:gt({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:L||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 Re=fe.pathname||"(unknown)";Z.has(Re)||Z.set(Re,[]),Z.get(Re).push(fe.instruction||Is({...O,annotations:[fe]}))}Ce=[...Z.entries()].map(([fe,Re])=>`\`${fe}\`
229
- ${Re.map(xe=>`- ${xe}`).join(`
170
+ ${Tr}`;let F=$c(a.color,`[\u22B9 ${y}:${a.id}]`),ce=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${F} Reviewing ${ce} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${B?` (resuming: ${B.slice(0,8)})`:""}`);let U=new Tn(a.id),ne=(q,ie)=>{if(q.type==="delta"&&"text"in q){let De=U.push(q.text);De.visibleText&&(E.accumulateText(ie,"response",De.visibleText),E.broadcast({...q,text:De.visibleText},ie,a.sourceId));for(let it of De.orientations)E.broadcast({type:"orientation",jobId:ie,orientation:it},ie,a.sourceId);return}else q.type==="thinking"&&"text"in q&&E.accumulateText(ie,"thinking",q.text);E.broadcast(q,ie,a.sourceId)},{process:de,result:le}=S==="codex"?cn(a.id,{prompt:H,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:B,model:a.model,sandboxMode:_?"read-only":void 0,configOverrides:rn(a.agentSettings),onEvent:ne}):S==="copilot"?zo(a.id,{prompt:H,projectRoot:r,resumeSessionId:B,model:a.model,timeoutMs:f,copilotPath:m.copilot?.path??P,onEvent:ne}):sn(a.id,{prompt:H,projectRoot:r,maxTurns:d,maxBudgetUsd:u,allowedTools:_?["Read"]:x,claudePath:T,resumeSessionId:B,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:ne});E.setActiveProcess(a.id,de);let Y=await le,we=U.finalize(Y.text),fe=we.visibleText,Ie=J?Po(fe):{visibleText:fe,draft:void 0,error:void 0},Le=Ie.visibleText;for(let q of we.orientations)E.broadcast({type:"orientation",jobId:a.id,orientation:q},a.id,a.sourceId);if(a.result=Le,Y.success){console.log(`${F} Iteration complete`),Y.fileEdits&&Y.fileEdits.length>0&&console.log(`${F} Captured ${Y.fileEdits.length} file edit(s): ${Y.fileEdits.map(te=>`${te.tool} ${te.file_path}`).join(", ")}`),Y.editEvents&&Y.editEvents.length>0&&console.log(`${F} Captured ${Y.editEvents.length} edit event(s): ${Y.editEvents.map(te=>`${te.operation} ${te.filePath}`).join(", ")}`),a.status="done";let q=Mr(fe),ie=Er(fe);if(ie.length>0&&a.annotationIds&&a.annotationIds.length>0){let te=new Set(a.annotationIds);ie.every(at=>te.has(at.annotationId))||(ie=ie.map((at,ct)=>({...at,annotationId:a.annotationIds[ct%a.annotationIds.length]})))}let De=Y.fileEdits&&Y.fileEdits.length>0?Y.fileEdits.map(te=>`${te.tool} ${te.file_path.split("/").pop()}`):Y.toolsUsed,it=E.getBufferedEvents(a.id),Oe=it?Mc(it.events,r):void 0,Pe,Ye=Rr(fe),Q=kr(fe);if(Q)if(!(a.memoryReview?.packets.some(ae=>ae.proposalId===Q.proposalId)||a.surfacedProposalIds?.includes(Q.proposalId)))Pe={status:"rejected",action:Q.action,proposalId:Q.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Pe=await V.commitConversationalReview(Q)}catch(ae){Pe={status:"rejected",action:Q.action,proposalId:Q.proposalId,message:ae instanceof Error?ae.message:String(ae)}}let xe=[...(Y.fileEdits??[]).map(te=>te.file_path),...(Y.editEvents??[]).flatMap(te=>te.filePath?[te.filePath]:[])],pe,Fe=a.imprintContext?.pendingGroundingExplanationIds??[];if(Ie.draft?.decision==="none"&&he.recordNoop(Ie.draft.reason),a.threadId&&Ie.draft?.decision==="mutate"&&!Q&&!Ye)try{pe=await he.capture(Ie.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await W.loadModel(),pendingGroundingExplanationIds:Fe}),pe&&await V.recordImprintEvidence({summary:pe,threadId:a.threadId,jobId:a.id}).catch(te=>console.warn(`${F} Canonical Imprint evidence linkage failed:`,te))}catch(te){console.warn(`${F} Continuous imprint update failed; the thread result remains available:`,te instanceof Error?te.message:String(te))}else Ie.error&&console.warn(`${F} Ignored invalid imprint block: ${Ie.error}`);let Wn=pe?.transactionId;if(a.threadId&&pe&&!pe.grounding){let te=await D.getThread(a.threadId),ae=new Set(pe.changes.map(ct=>ct.explanationId)),at=te?jc(te.messages,ae):void 0;if(at?.imprintSummary){let ct=at.imprintSummary;await D.updateAssistantMessage(a.threadId,at.jobId,{imprintSummary:{...ct,detail:pe.detail,changes:pe.changes,additionalObservationCount:(ct.additionalObservationCount??0)+1,coalescedTransactionIds:[...ct.coalescedTransactionIds??[],pe.transactionId]}}),pe=void 0}}let X=Vr({question:q,resolutions:ie,changedFiles:xe,decisionRequired:!!Ye,imprintTransactionId:Wn,groundingRequired:!!pe?.grounding}),ue=Oe?.flatMap(te=>te.kind==="orientation"?[te.orientation]:[])??[];if(a.threadId){let te=_?Ye?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Le;await D.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:te,resolutions:!_&&ie.length>0?ie:void 0,question:_?void 0:q??void 0,sessionId:Y.sessionId,toolsUsed:_?void 0:De,editEvents:!_&&Y.editEvents&&Y.editEvents.length>0?Y.editEvents:void 0,segments:!_&&Oe&&Oe.length>0?Oe:void 0,turn:{phase:"complete",orientation:ue,result:X},result:X,memoryReviewCard:Ye??void 0,memoryReceipt:Pe,imprintSummary:pe,model:a.model,provider:S})}if(a.threadId&&!Q&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let te=a.feedback.annotations.flatMap(ae=>ae.linkedSelector?[ae.pathname?`${ae.pathname}:${ae.linkedSelector}`:ae.linkedSelector]:[]);try{await V.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:w??(Pn(a.feedback)||"[request unavailable]"),responseSummary:q??Le,outcome:q?"question_asked":ie.some(ae=>ae.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:Y.sessionId},subjectHints:te,filePaths:[...(Y.fileEdits??[]).map(ae=>ae.file_path),...(Y.editEvents??[]).flatMap(ae=>ae.filePath?[ae.filePath]:[])].map(ae=>ai(ae)?Ic(r,ae):ae),resolutions:ie.map(ae=>({status:ae.status,summary:ae.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ae=>ae.id)})}catch(ae){console.warn(`${F} Canonical memory capture failed; iteration remains available in legacy history:`,ae instanceof Error?ae.message:String(ae))}}Pe?.status==="committed"&&Pe.decisionId&&S!=="copilot"&&await Xe({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Pe.decisionId}`}),q&&(console.log(`${F} \u{1F4AC} Question detected: "${q.slice(0,120)}" \u2192 broadcasting to ${re.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),E.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:q,annotationIds:a.annotationIds},a.id,a.sourceId));let me=_r(fe);me.length>0&&(console.log(`${F} Novel pattern(s): ${me.map(te=>`${te.category}/${te.element}`).join(", ")}`),E.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),E.broadcast({type:"done",jobId:a.id,success:!0,resolutions:ie.length>0?ie:void 0,responseText:Le,threadId:a.threadId,annotationIds:a.annotationIds,result:X},a.id,a.sourceId),ye.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${F} Error: ${Y.error}`),a.status="error",a.error=Y.error,a.threadId&&await D.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:Y.error||"Unknown error",model:a.model,provider:S}),E.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:Y.error||"Unknown error",provider:S,model:a.model,recoverable:Y.recoverableError,code:Y.errorCode},a.id,a.sourceId),ye.push({id:a.id,status:"error",completedAt:Date.now(),error:Y.error,threadId:a.threadId,annotationIds:a.annotationIds});Re()});let He=gc(async(a,v)=>{if(_c(a,v),a.method==="OPTIONS"){v.writeHead(204),v.end();return}let R=a.url||"/",w=R.split("?")[0],j=new URL(R,`http://127.0.0.1:${y}`),S=j.pathname,_=Cc(a,j);if(_&&_!==i){C(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:_,projectName:Fn(r)});return}if(a.headers.origin){if(!ci(a.headers.origin)){C(v,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(_!==i){C(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:_,projectName:Fn(r)});return}}try{if(a.method==="POST"&&S==="/send")await tn(a,v);else if(a.method==="GET"&&S==="/events")ve(a,v);else if(a.method==="GET"&&S==="/status")await tt(a,v,_);else if(a.method==="GET"&&S==="/ui-preferences")await Qe(v);else if(a.method==="PATCH"&&S==="/ui-preferences")await nt(a,v);else if(a.method==="PATCH"&&S==="/config")await je(a,v);else if(a.method==="POST"&&S==="/leases"){if(l!=="detached"){C(v,409,{error:"Bridge leases are only available for detached bridges."});return}try{let J=await Be(a),B=typeof J.leaseId=="string"?J.leaseId.trim():"",H=typeof J.ownerPid=="number"&&Number.isInteger(J.ownerPid)&&J.ownerPid>0?J.ownerPid:void 0;if(!B||B.length>128){C(v,400,{error:"A valid leaseId is required."});return}z();let F=h.acquire(B,H);C(v,201,{ok:!0,lease:F,ttlMs:oi})}catch{C(v,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){C(v,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(S.slice(8))}catch{C(v,400,{error:"Invalid lease id."});return}if(!J){C(v,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let B=h.heartbeat(J);if(!B){C(v,404,{error:"Lease not found."});return}C(v,200,{ok:!0,lease:B})}else{let B=h.release(J);C(v,B.found?200:404,{ok:B.found}),B.becameEmpty&&Z()}}else if(a.method==="POST"&&S==="/shutdown"){if(l!=="detached"){C(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}C(v,200,{ok:!0}),setTimeout(K,100)}else if(a.method==="POST"&&S==="/restart"){if(l!=="detached"){C(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}C(v,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of re)try{J.res.end()}catch{}He.close(()=>{ti(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")C(v,200,{providers:m});else if(S.startsWith("/imprint/"))await en(a,v,S);else if(S.startsWith("/memory/"))await _t(a,v,S);else if(a.method==="POST"&&S==="/mcp/install")await rt(a,v);else if(a.method==="POST"&&S==="/reply")await Un(a,v);else if(a.method==="POST"&&S==="/cancel")ot(a,v);else if(a.method==="POST"&&S==="/materialize")C(v,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")C(v,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let J=await W.loadRuns();C(v,200,J)}else if(a.method==="GET"&&S==="/projection/proposals"){let J=await W.loadModelProposals();C(v,200,J)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let J=S.slice(22,-15);await Gn(J,a,v)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let J=S.slice(22,-6);await zn(J,v)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let J=S.slice(22,-8);await Ct(J,a,v)}else if(S.startsWith("/model/proposals/"))C(v,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await ft(a,v);else if(a.method==="DELETE"&&S==="/model/component")await st(a,v);else if(a.method==="PATCH"&&S==="/model/token")await Hn(a,v);else if(a.method==="DELETE"&&S==="/model/token")await nn(a,v);else if(a.method==="POST"&&S==="/model/consolidate")C(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")C(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&S==="/model"){let J=await W.loadModel();C(v,200,{model:J})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let J=S.slice(6,S.length-7),B=parseInt(j.searchParams.get("afterSeq")??"-1",10),H=E.getBufferedEvents(J,isNaN(B)?-1:B);H?C(v,200,H):C(v,404,{error:"Unknown job"})}else if(a.method==="GET"&&w.startsWith("/files/"))await vi(w.slice(7),v);else if(a.method==="GET"&&S==="/threads/recent"){let J=Math.min(Math.max(parseInt(j.searchParams.get("limit")??"5",10)||5,1),20),B=await D.listRecent(J);C(v,200,B)}else if(a.method==="GET"&&S.startsWith("/decision/")){let J=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(J))C(v,400,{error:"Invalid decision id"});else{let B=await D.getThread(J),H=[...B?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(B&&H?.annotationSnapshot){let F=[...B.messages].reverse().find(ce=>ce.resolutions?.length);C(v,200,{decision:{id:B.id,createdAt:H.timestamp,url:H.annotationSnapshot.url,viewport:H.annotationSnapshot.viewport,color:H.annotationSnapshot.color,annotations:H.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await G.loadDecision(J);F?C(v,200,{decision:F,authority:"legacy_archive"}):C(v,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let J=S.slice(8);await Ii(J,v)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let J=S.slice(8);await wi(J,v)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?hi(a,v):a.method==="GET"&&S==="/canvas/manifest"?await gi(v):a.method==="GET"&&S==="/canvas/app.mjs"?await yi(v):C(v,404,{error:"Not found"})}catch(J){console.error("[Bridge] Request error:",J),C(v,500,{error:J instanceof Error?J.message:"Internal error"})}});async function _t(a,v,R){try{if(a.method==="GET"&&R==="/memory/status"){C(v,200,await V.status());return}if(a.method==="GET"&&R==="/memory/diagnostics"){C(v,200,await V.diagnostics());return}if(a.method==="GET"&&R==="/memory/model-view"){C(v,200,await V.getModelView());return}if(a.method==="GET"&&R==="/memory/imprint-view"){let w=await D.load(),j=[...new Set(Object.values(w.threads).flatMap(S=>Zt(S.messages)))];C(v,200,await V.getImprintView(j));return}if(a.method==="POST"&&R==="/memory/constraints"){let w=await Be(a),j=typeof w.reactComponent=="string"?w.reactComponent.trim():"",S=await V.getModelView(),_=j?S.entries.filter(J=>J.key===`components.${j}`||J.key.startsWith(`components.${j}.`)):[];C(v,200,{modelEntries:_});return}if(a.method==="POST"&&R==="/memory/conversation-action"){let w=await Be(a),j=typeof w.threadId=="string"?w.threadId:"",S=typeof w.proposalId=="string"?w.proposalId:"",_=String(w.action);if(!j||!S||!["accept","edit_and_accept","reject","defer"].includes(_)){C(v,400,{error:"A valid thread, proposal, and review action are required."});return}let J=await D.getThread(j),B=J?.messages.find(Y=>Y.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!J||!B){C(v,409,{error:"This decision review card is not available in the thread."});return}let H=await W.findModelProposalsByThread(j),F=(await Promise.all(H.map(async Y=>({proposal:Y,matches:(await Promise.all(Y.decisionIds.map(we=>V.findPendingProposalForLegacyDecision(we)))).some(we=>we?.proposalId===S)})))).find(Y=>Y.matches)?.proposal,ce={proposalId:S,action:_,kind:B.kind,claim:_==="edit_and_accept"&&typeof w.claim=="string"?w.claim.trim():void 0,reason:_==="defer"?void 0:`The owner explicitly chose ${_.replaceAll("_"," ")} from the decision review card.`,taskContext:_==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:_==="defer"?["different_action","owner_request"]:void 0};if(ce.action==="edit_and_accept"&&!ce.claim){C(v,400,{error:"Edited decision wording is required."});return}let U=await V.commitConversationalReview(ce),ne=`memory-${Mt().slice(0,8)}`,de=_==="accept"?"> Accepted decision":_==="edit_and_accept"?"> Edited and accepted decision":_==="reject"?"> Rejected decision":"> Deferred decision";await D.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:ne,replyToQuestion:de}),await D.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:ne,responseText:"",memoryReceipt:U,provider:At(typeof w.provider=="string"?w.provider:void 0),model:typeof w.model=="string"?w.model:void 0}),U.status==="committed"&&F&&await W.dismissModelProposal(F.id);let le=At(typeof w.provider=="string"?w.provider:void 0);U.status==="committed"&&U.decisionId&&le!=="copilot"&&await Xe({provider:le,model:typeof w.model=="string"?w.model:void 0,agentSettings:ht(w),threadId:j,reason:`Project accepted decision ${U.decisionId}`}),C(v,U.status==="committed"?200:409,{receipt:U});return}if(a.method==="POST"&&R==="/memory/analyze"){let w=await Be(a),j=await V.analyzeLegacy({projectKey:typeof w.projectKey=="string"?w.projectKey:void 0}),S=Object.fromEntries([...new Set(j.issues.map(_=>_.code))].map(_=>[_,j.issues.filter(J=>J.code===_).length]));C(v,200,{...j,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&R==="/memory/review"){let w=await Be(a),j=await V.review(wo(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});C(v,200,j);return}if(a.method==="POST"&&R==="/memory/context"){let w=await Be(a),j=await V.contextualize(wo(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});C(v,200,j);return}if(a.method==="POST"&&R==="/memory/initialize"){let w=await Be(a),j=await V.initializeFromLegacy({confirmed:w.confirm===!0,projectKey:typeof w.projectKey=="string"?w.projectKey:void 0,writerVersion:Yt});C(v,201,{status:j.status,report:{source:j.report.source,imported:j.report.imported,unresolvedAcceptance:j.report.unresolvedAcceptance,deferredModelEntries:j.report.deferredModelEntries,proofCases:j.report.proofCases,schemaIssues:j.report.schemaIssues}});return}if(a.method==="POST"&&R==="/memory/plan"){let w=await Be(a),j=await V.planReview(Io(w.command),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});C(v,j.result.ok?200:422,j);return}if(a.method==="POST"&&R==="/memory/commit"){let w=await Be(a),j=w.transaction&&typeof w.transaction=="object"&&!Array.isArray(w.transaction)?w.transaction:{},S=await V.commitReview(Io(w.command),{transactionId:typeof j.transactionId=="string"?j.transactionId:"",committedAt:typeof j.committedAt=="string"?j.committedAt:""});C(v,200,{status:await V.status(),journal:S.report});return}if(a.method==="POST"&&R==="/memory/recover"){let w=await Be(a),j=await V.recover(w.confirm===!0);C(v,200,{status:await V.status(),journal:j.report});return}C(v,404,{error:"Memory endpoint not found."})}catch(w){let j=w instanceof Error?w.message:String(w),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(j),_=/required|invalid|unsupported|expected|must be|confirmation/i.test(j);if(S||_){C(v,S?409:400,{error:j});return}throw w}}async function en(a,v,R){if(a.method==="GET"&&R==="/imprint/status"){let[w,j]=await Promise.all([he.store.load(),D.load()]),S=[...new Set(Object.values(j.threads).flatMap(_=>Zt(_.messages)))].filter(_=>w.graph.explanations.some(J=>J.id===_&&J.state==="testing"));C(v,200,{state:"ready",head:w.graph.head,updatedAt:w.graph.updatedAt,explanationCount:w.graph.explanations.filter(_=>_.state!=="retired").length,concreteCount:w.graph.concrete.length,relationCount:w.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:w.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&R==="/imprint/action"){let w=await Be(a),j=typeof w.threadId=="string"?w.threadId:"",S=typeof w.transactionId=="string"?w.transactionId:"",_=String(w.action);if(!j||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(_)){C(v,400,{error:"A valid thread, imprint update, and action are required."});return}let B=await D.getThread(j),H=[...B?.messages??[]].reverse().find(le=>le.role==="assistant"&&le.imprintSummary?.transactionId===S),F=H?.imprintSummary;if(!B||!H||!F){C(v,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){C(v,409,{error:"This imprint summary has already been resolved."});return}let ce=`imprint-${Mt().slice(0,8)}`;await he.applyGroundingAction({summary:F,action:_,value:typeof w.value=="string"?w.value:void 0,threadId:j,jobId:ce}),await V.recordImprintEvidence({summary:F,action:_,threadId:j,jobId:ce}).catch(le=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",le));let U=Pt(H.result,!!H.question),ne=H.turn?{...H.turn,result:Pt(H.turn.result,!!H.question)}:void 0;await D.updateAssistantMessage(j,H.jobId,{imprintSummary:{...F,resolvedAction:_},...U?{result:U}:{},...ne?{turn:ne}:{}});let de={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 D.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:ce,replyToQuestion:de[_]}),C(v,200,{ok:!0,action:_});return}C(v,404,{error:"Imprint endpoint not found."})}async function tn(a,v){let{screenshot:R,feedback:w,color:j,provider:S,model:_,reasoningEffort:J,serviceTier:B,sourceId:H,pastedImages:F,pageScreenshots:ce}=await bo(a),U;try{U=JSON.parse(w)}catch{C(v,400,{error:"Invalid feedback JSON"});return}let ne=Mt().slice(0,8),de={};if(ce.length>0)for(let Q of ce){let xe=encodeURIComponent(Q.pathname),pe=Ee(c,`screenshot-${ne}-${xe}.webp`);await Ln(pe,Q.data),de[Q.pathname]=pe}let le=Ee(c,`screenshot-${ne}.webp`);await Ln(le,R);let Y={};if(F.length>0)for(let Q of F){let xe=Ee(c,`pasted-${ne}-${Q.annotationId}-${Q.index}.webp`);await Ln(xe,Q.data),Y[Q.annotationId]||(Y[Q.annotationId]=[]),Y[Q.annotationId].push(xe)}let we=U.annotations.map(Q=>Q.linkedSelector?Q.pathname?`${Q.pathname}:${Q.linkedSelector}`:Q.linkedSelector:null).filter(Q=>!!Q),fe;if(we.length>0){let Q=await D.findContinuationThread(we);Q?(fe=Q.id,await D.addElementIdentifiers(fe,we)):fe=(await D.createThread(ne,we)).id}else fe=(await D.createThread(ne,[])).id;let Ie=U.annotations.map(Q=>Q.id),Le=Object.keys(de).length>0,q=await xr(V,U,we,Q=>console.warn(`[\u22B9 ${y}:${ne}] Contextual memory unavailable; continuing without it:`,Q instanceof Error?Q.message:String(Q))),ie=await he.contextualize({text:Pn(U),subjectHints:[...we,...U.annotations.flatMap(Q=>[Q.pathname,Q.elements?.[0]?.reactComponent].filter(xe=>!!xe))],pendingGroundingExplanationIds:Zt((await D.getThread(fe))?.messages??[])}).catch(Q=>{console.warn(`[\u22B9 ${y}:${ne}] Imprint context unavailable; continuing without it:`,Q instanceof Error?Q.message:String(Q))}),De={id:ne,status:"queued",screenshotPath:le,feedback:U,createdAt:Date.now(),color:j,threadId:fe,annotationIds:Ie,provider:At(S),model:_||void 0,agentSettings:ht({reasoningEffort:J,serviceTier:B}),...Object.keys(Y).length>0?{imagePaths:Y}:{},sourceId:H||void 0,...Le?{screenshotPaths:de}:{},...q?{memoryReview:q}:{},...ie?{imprintContext:ie}:{}},it=new Set(U.annotations.map(Q=>Q.pathname).filter(Boolean)),Oe;if(it.size>1){let Q=new Map;for(let xe of U.annotations){let pe=xe.pathname||"(unknown)";Q.has(pe)||Q.set(pe,[]),Q.get(pe).push(xe.instruction||ii({...U,annotations:[xe]}))}Oe=[...Q.entries()].map(([xe,pe])=>`\`${xe}\`
171
+ ${pe.map(Fe=>`- ${Fe}`).join(`
230
172
  `)}`).join(`
231
- `)}else Ce=Is(O);let et=Xt(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 ke=N.enqueue(pe);E(u,200,{jobId:K,position:ke,threadId:be})}async function Ze(a,u){let k=a.headers["content-type"]||"",m,P,w,j,$,D,L,F,C,O=[];if(k.includes("multipart/form-data")){let Q=await $n(a),me=Q.feedback?JSON.parse(Q.feedback):{};m=me.threadId,P=me.reply,w=me.color,j=me.provider,$=me.model,D=gt(me),L=me.sourceId||Q.sourceId,F=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=gt(z),L=z.sourceId,F=z.memoryReviewProposalId,C=z.evalRemediation?.action==="resolve"&&typeof z.evalRemediation.evalId=="string"?{evalId:z.evalRemediation.evalId,action:"resolve"}:void 0}if(!m||!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(F){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===F),!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 Cs(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??pt().slice(0,8),Ie=[],de=`${V}-${Date.now()}`;for(let Q=0;Q<O.length;Q++){let me=Me(c,`reply-${de}-${Q}.webp`);await an(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:Kn(pe)}).catch(Q=>{console.warn(`[\u22B9 ${h}:${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]:[])),ke=[...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=xt(j),Re=q,xe=Re?[Re.underlying.proposalId]:ke?[ke.proposalId]:[],ht=Hr(ae,pe,fe,Ie.length>0?Ie:void 0);if(se?ht+=["","## 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
- `):Re?ht+=["","## Decision review card",`Privately review proposal ${Re.underlying.proposalId}: ${Re.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
233
- `):ke&&(ht+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(ke)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
234
- `)),ve){let Q=ve,z=[...Q._replyTexts??(Q._replyText?[Q._replyText]:[]),P],re=[...Q._replyImagePaths??[],...Ie];Q._replyTexts=z,Q._replyText=ws(z),Q._replyImagePaths=re.length>0?re:void 0,Q._replyPrompt=ht,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:L||void 0,..._e?{memoryReview:_e}:{},...Ce?{imprintContext:Ce}:{},...xe.length?{surfacedProposalIds:xe}:{}};se?qe.kind="resolve_eval":oe&&(qe.kind=oe),qe._replyPrompt=ht,qe._evalRemediation=!!se,qe._replyTexts=[P],qe._replyText=ws([P]),Ie.length>0&&(qe._replyImagePaths=Ie);let Ft=be?N.enqueueNext(qe):N.enqueue(qe);E(u,200,{jobId:V,position:Ft,threadId:m})}function it(a,u){u.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),u.write(`event: connected
173
+ `)}else Oe=ii(U);let Pe=zt(U,Object.keys(Y).length>0?Y:void 0);await D.appendMessage(fe,{role:"human",timestamp:Date.now(),jobId:ne,screenshotPath:le,...Le?{screenshotPaths:de}:{},...Object.keys(Y).length>0?{imagePaths:Y}:{},annotationIds:Ie,annotationSnapshot:{url:U.url,viewport:U.viewport,annotations:U.annotations,color:j||void 0},feedbackSummary:Oe,feedbackContext:Pe||void 0,...q?{memoryReview:q}:{},...ie?{imprintContext:ie}:{}});let Ye=E.enqueue(De);C(v,200,{jobId:ne,position:Ye,threadId:fe})}async function Un(a,v){let R=a.headers["content-type"]||"",w,j,S,_,J,B,H,F,ce=[];if(R.includes("multipart/form-data")){let X=await bo(a),ue=X.feedback?JSON.parse(X.feedback):{};w=ue.threadId,j=ue.reply,S=ue.color,_=ue.provider,J=ue.model,B=ht(ue),H=ue.sourceId||X.sourceId,F=typeof ue.memoryReviewProposalId=="string"?ue.memoryReviewProposalId:void 0;for(let me of X.pastedImages)ce.push(me.data)}else{let X=[];for await(let te of a)X.push(typeof te=="string"?Buffer.from(te):te);let ue=Buffer.concat(X).toString("utf-8"),me;try{me=JSON.parse(ue)}catch{C(v,400,{error:"Invalid JSON"});return}w=me.threadId,j=me.reply,S=me.color,_=me.provider,J=me.model,B=ht(me),H=me.sourceId,F=me.memoryReviewProposalId}if(!w||!j){C(v,400,{error:"Missing threadId or reply"});return}let U=await D.getThread(w);if(!U){C(v,404,{error:"Thread not found"});return}let ne;if(F){let X=await W.findModelProposalsByThread(w);if(ne=(await Promise.all(X.flatMap(me=>me.authorityStatus==="accepted"?[]:me.decisionIds.map(async te=>({modelProposalId:me.id,underlying:await V.findPendingProposalForLegacyDecision(te)}))))).filter(me=>!!me.underlying).find(me=>me.underlying.proposalId===F),!ne){C(v,409,{error:"The requested memory decision is not pending in this thread."});return}}let de="";{let X=await D.getThreadHistory(w);for(let ue=X.length-1;ue>=0;ue--)if(X[ue].screenshotPath){de=X[ue].screenshotPath;break}}let le=await $e(w);if(!de&&!le){C(v,400,{error:"No screenshot available"});return}let Y=E.hasActiveThread(w),we=Y?E.getQueuedThreadJob(w,X=>X._replyText!==void 0||X._replyPrompt!==void 0):null,fe=we?.id??Mt().slice(0,8),Ie=[],Le=`${fe}-${Date.now()}`;for(let X=0;X<ce.length;X++){let ue=Ee(c,`reply-${Le}-${X}.webp`);await Ln(ue,ce[X]),Ie.push(ue)}await D.appendMessage(w,{role:"human",timestamp:Date.now(),jobId:fe,replyToQuestion:j,screenshotPath:de,...Y?{queued:!0}:{},...Ie.length>0?{replyImagePaths:Ie}:{}});let q=await D.getThreadHistory(w),ie=[...q].reverse().find(X=>X.memoryReview)?.memoryReview,De=await he.contextualize({text:j,subjectHints:U.elementIdentifiers,pendingGroundingExplanationIds:Zt(q)}).catch(X=>{console.warn(`[\u22B9 ${y}:${fe}] Imprint context unavailable for reply; continuing without it:`,X instanceof Error?X.message:String(X))}),it=new Set(q.flatMap(X=>X.memoryReceipt?.status==="committed"?[X.memoryReceipt.proposalId]:[])),Oe=[...q].reverse().find(X=>X.memoryReviewCard&&!it.has(X.memoryReviewCard.proposalId))?.memoryReviewCard,Pe=[];for(let X of q)if(X.annotationIds)for(let ue of X.annotationIds)Pe.includes(ue)||Pe.push(ue);let Ye=At(_),Q=ne,xe=Q?[Q.underlying.proposalId]:Oe?[Oe.proposalId]:[],pe=Ar(de,q,Ye,Ie.length>0?Ie:void 0);if(Q?pe+=["","## Decision review card",`Privately review proposal ${Q.underlying.proposalId}: ${Q.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(`
174
+ `):Oe&&(pe+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Oe)}`,"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(`
175
+ `)),we){let X=we,me=[...X._replyTexts??(X._replyText?[X._replyText]:[]),j],te=[...X._replyImagePaths??[],...Ie];X._replyTexts=me,X._replyText=ri(me),X._replyImagePaths=te.length>0?te:void 0,X._replyPrompt=pe,X.annotationIds=Pe.length>0?Pe:X.annotationIds,X.agentSettings=B??X.agentSettings,X.memoryReview=ie??X.memoryReview,X.imprintContext=De??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...xe])],C(v,200,{jobId:fe,position:1,threadId:w,bundled:!0});return}let Fe={id:fe,status:"queued",screenshotPath:de,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:w,annotationIds:Pe.length>0?Pe:void 0,provider:Ye,model:J||void 0,agentSettings:B,sourceId:H||void 0,...ie?{memoryReview:ie}:{},...De?{imprintContext:De}:{},...xe.length?{surfacedProposalIds:xe}:{}};le&&(Fe.kind=le),Fe._replyPrompt=pe,Fe._replyTexts=[j],Fe._replyText=ri([j]),Ie.length>0&&(Fe._replyImagePaths=Ie);let Wn=Y?E.enqueueNext(Fe):E.enqueue(Fe);C(v,200,{jobId:fe,position:Wn,threadId:w})}function ve(a,v){v.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),v.write(`event: connected
235
176
  data: {"status":"connected"}
236
177
 
237
- `);let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,P={id:pt().slice(0,8),res:u,sourceId:m};X.add(P),a.on("close",()=>{X.delete(P)})}async function at(a,u,k){i??=is(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()]),L=[],F=V=>V.reason instanceof Error?V.reason.message:String(V.reason);P.status==="rejected"&&L.push({subsystem:"projection",message:F(P)}),w.status==="rejected"&&L.push({subsystem:"projection",message:F(w)}),j.status==="rejected"?L.push({subsystem:"memory",message:F(j)}):j.value.state==="degraded"&&L.push({subsystem:"memory",message:j.value.error??"Product memory is degraded."}),$.status==="rejected"&&L.push({subsystem:"imprint",message:F($)}),D.status==="rejected"&&L.push({subsystem:"threads",message:F(D)});let C=P.status==="fulfilled"?P.value.runs:[],O=w.status==="fulfilled"?w.value.proposals:[],K=as(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:F(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(V=>Kn(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:F($),pendingGroundingCount:ae.length,admission:he.diagnostics(),admissionWindowStartedAt:e},be=L.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:L},version:sn,restartMode:p,projectId:s,projectName:Vn(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:H},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 mt(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 Yn(a){let u=await M.load();E(a,200,{ok:!0,...u})}async function Zn(a,u){let k=await ze(a);if(!ms(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 Bt(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("jobId"),P=m?N.allActive.filter(F=>F.id===m):N.allActive,w=m?T.allActive.filter(F=>F.id===m):T.allActive,j=[...P.map(F=>F.threadId),...w.map(F=>F.threadId)].filter(Boolean),$=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),L=!!($||D);for(let F of j)await G.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});E(u,200,{cancelled:L})}async function je(a){let u=pt().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 ct(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 L=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}}),F=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:L}),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=xt(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:F})}async function St(a,u,k){let m=decodeURIComponent(a),{provider:P,model:w}=await ft(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 ft(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:xt(typeof k.provider=="string"?k.provider:void 0),model:typeof k.model=="string"&&k.model?k.model:void 0,agentSettings:gt(k)}}catch{return{}}}async function eo(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:L,serviceTier:F,sourceId:C}=await $n(u),O=xt($)??I;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=pt().slice(0,8),se=pt().slice(0,8),ae=Me(c,`eval-run-${q}.webp`);await an(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 xs(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=ir({evalCase:P,scope:V,model:Ie,screenshotPath:ae,chromeDevtoolsAvailable:_e}),ke=(await G.createThread(se,[])).id;Ge.set(ke,"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(ke,{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:ke,kind:"run_eval",evalId:m,evalRunId:q,provider:O,model:D||void 0,agentSettings:gt({reasoningEffort:L,serviceTier:F}),sourceId:C||void 0};fe._replyPrompt=Ce,fe._evalRunScope=V,fe._evalScreenshotPath=oe,fe._evalScopeFingerprint=de;let Re=N.enqueue(fe);E(k,200,{jobId:se,runId:q,position:Re,threadId:ke,screenshotPath:oe})}async function cn(a,u,k){let m=decodeURIComponent(a),P={},w,j,$;try{let L=[];for await(let C of u)L.push(typeof C=="string"?Buffer.from(C):C);let F=JSON.parse(Buffer.concat(L).toString());w=F.status,j=F.title,$=F.assertions}catch{E(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 L=$.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(L.length===0){E(k,400,{error:"Invalid assertions"});return}P.assertions=L}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 Cs(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 $s(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 xr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&P.push(await Sr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&P.push(await Pr(m,f.copilot.path??b));let[w,j,$]=await Promise.all([fo(r),ho(r),go(r,f.copilot?.path??b)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),E(u,200,{results:P,capabilities:{providers:f}})}async function Os(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 rt({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 Ds(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 rt({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 Js(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 rt({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 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.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 rt({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 Bs(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=Uo(h,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Fs(a){let u=Date.now();if(ut&&u<ut.expires){E(a,200,ut.data);return}try{let{scanForComponents:k}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),P=await k(r);ut={data:P,expires:u+5e3},m(P,r,Jt).then(w=>{Jt=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 Ls(a){let u=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let k=id(import.meta.url);u.unshift(Me(sd(k),"canvas.mjs"))}catch{}for(let k of u)try{let m=await No(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 zs(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(u,400,{error:"Invalid filename"});return}try{let k=[Me(c,a),Me(r,".popmelt","artifacts","thread-media",a),Me(r,".popmelt","artifacts","eval-screenshots",a),Me(r,".popmelt","evals","screenshots",a),Me(r,".popmelt","screenshots",a)],m;for(let j of k)try{m=await No(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 dn(a){return`/files/${Vn(a)}`}async function Us(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}})),L=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,F=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:dn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,oe])=>[ae,dn(oe)]))}:{},...K?{imageUrls:Object.fromEntries(Object.entries(K).map(([ae,oe])=>[ae,oe.map(dn)]))}:{},...q?{replyImageUrls:q.map(dn)}:{}}));E(u,200,{id:k.id,createdAt:k.createdAt,messages:F,modelProposal:L,modelProposals:D})}async function qs(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 Fo=9,Lo=!1;for(let a=n;a<n+Fo;a++)try{await bd(Nt,a),h=a,Lo=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await Id(a);if(ss(k,{projectId:s,version:sn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Lo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Fo-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)Qn(m,{type:"capabilities_changed",data:{}})}});let Ws=setInterval(()=>{Ss(c).catch(()=>{})},dd),zo=setInterval(()=>{B.expireStale().becameEmpty&&ge()},pd);return zo.unref?.(),{port:h,projectId:s,close:async()=>{clearInterval(Ws),clearInterval(zo),te(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of X)try{a.res.end()}catch{}return X.clear(),new Promise(a=>{Nt.close(()=>a())})}}}async function Ss(o){try{let e=await Zc(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let s=await td(r);n-s.mtimeMs>ld&&await nd(r)}catch{}}}catch{}}var Rd=parseInt(process.env.POPMELT_PORT||"1111",10),Es=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Td=process.env.POPMELT_DEV_ORIGIN||void 0,jd=process.env.POPMELT_COPILOT_PATH||void 0,Ms=js(Es,".popmelt"),As=js(Ms,"bridge.lock");async function Ed(o){await Sd(Ms,{recursive:!0}),await kd(As,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
239
- `)}async function _s(){try{await Pd(As)}catch{}}async function Md(){let o=await Ts({port:Rd,projectRoot:Es,devOrigin:Td,copilotPath:jd,restartMode:"detached"});await Ed(o.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await o.close(),await _s(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}Md().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),_s().finally(()=>process.exit(1))});
178
+ `);let w=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,j={id:Mt().slice(0,8),res:v,sourceId:w};re.add(j),a.on("close",()=>{re.delete(j)})}async function tt(a,v,R){s??=Gr(a.headers),Re();let w=[...E.allActive,...$.allActive.map(q=>({id:q.id,status:q.status,threadId:q.threadId,annotationIds:q.annotationIds??[],color:"#000000",kind:"project_model",standalone:q.standalone}))],[j,S,_,J,B]=await Promise.allSettled([W.loadRuns(),W.loadModelProposals(),V.status(),he.store.load(),D.load()]),H=[],F=q=>q.reason instanceof Error?q.reason.message:String(q.reason);j.status==="rejected"&&H.push({subsystem:"projection",message:F(j)}),S.status==="rejected"&&H.push({subsystem:"projection",message:F(S)}),_.status==="rejected"?H.push({subsystem:"memory",message:F(_)}):_.value.state==="degraded"&&H.push({subsystem:"memory",message:_.value.error??"Product memory is degraded."}),J.status==="rejected"&&H.push({subsystem:"imprint",message:F(J)}),B.status==="rejected"&&H.push({subsystem:"threads",message:F(B)});let ce=j.status==="fulfilled"?j.value.runs:[],U=S.status==="fulfilled"?S.value.proposals:[],ne=Hr(ce,U),de=ne.actionableProposals.map(q=>({id:q.id,status:q.status,title:q.title,summary:q.summary,decisionIds:q.decisionIds,threadId:q.threadId,runId:q.runId,presentationJobId:q.presentationJobId,authorityStatus:q.authorityStatus,underlyingProposalId:q.underlyingProposalId,createdAt:q.createdAt,updatedAt:q.updatedAt,appliedAt:q.appliedAt,dismissedAt:q.dismissedAt,error:q.error})),le=_.status==="fulfilled"?_.value:{initialized:!1,state:"degraded",error:F(_)},Y=B.status==="fulfilled"?[...new Set(Object.values(B.value.threads).flatMap(q=>Zt(q.messages)))]:[],we=J.status==="fulfilled"?Y.filter(q=>J.value.graph.explanations.some(ie=>ie.id===q&&ie.state==="testing")):[],fe=J.status==="fulfilled"?{state:"ready",head:J.value.graph.head,updatedAt:J.value.graph.updatedAt,explanationCount:J.value.graph.explanations.filter(q=>q.state!=="retired").length,concreteCount:J.value.graph.concrete.length,relationCount:J.value.graph.relations.length,pendingGroundingCount:we.length,recoveredTransactions:J.value.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(J),pendingGroundingCount:we.length,admission:he.diagnostics(),admissionWindowStartedAt:e},Ie=H.length>0?"degraded":le.state==="absent"||le.state==="initializing"?"initializing":"healthy",Le=new Date().toISOString();C(v,200,{ok:!0,schemaVersion:3,generatedAt:Le,serverStartedAt:e,health:{state:Ie,issues:H},version:Yt,restartMode:l,projectId:i,projectName:Fn(r),projectRoot:r,requestProjectId:R,projectIdVerified:R===i,devOrigin:s,activeJob:w[0]?{id:w[0].id,status:w[0].status}:null,activeJobs:w.map(q=>({id:q.id,status:q.status,threadId:q.threadId,annotationIds:q.annotationIds,color:q.color,kind:q.kind,standalone:"standalone"in q?q.standalone:void 0})),queueDepth:E.depth+$.depth,projectionQueueDepth:$.depth,leases:{active:h.isActivated,count:h.size,nextExpiryAt:h.nextExpiryAt,shutdownPending:N},projection:{state:j.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:$.active?{id:$.active.id,status:$.active.status,threadId:$.active.threadId,annotationIds:$.active.annotationIds??[],provider:$.active.provider,model:$.active.model}:null,queueDepth:$.depth,recentRuns:ne.recentRuns,recentAppliedRuns:ne.recentAppliedRuns,actionableProposalCounts:ne.actionableProposalCounts,actionableProposals:de},memory:le,imprint:fe,recentJobsRetentionMs:Se,recentJobs:ye})}async function je(a,v){let R=await new Promise(w=>{let j="";a.on("data",S=>{j+=S.toString()}),a.on("end",()=>w(j))});try{let w=JSON.parse(R);typeof w.devOrigin=="string"&&(s=w.devOrigin||null),C(v,200,{ok:!0,devOrigin:s})}catch{C(v,400,{error:"Invalid JSON"})}}async function Qe(a){let v=await L.load();C(a,200,{ok:!0,...v})}async function nt(a,v){let R=await Be(a);if(!Yr(R.theme)){C(v,400,{error:"theme must be light, dark, or auto"});return}let w=await L.setTheme(R.theme);C(v,200,{ok:!0,exists:!0,preferences:w})}async function ot(a,v){let w=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),j=w?E.allActive.filter(F=>F.id===w):E.allActive,S=w?$.allActive.filter(F=>F.id===w):$.allActive,_=[...j.map(F=>F.threadId),...S.map(F=>F.threadId)].filter(Boolean),J=w?E.cancelJob(w):E.cancelActive(),B=w?$.cancelJob(w):$.cancelActive(),H=!!(J||B);for(let F of _)await D.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:w||B?.id||"",cancelled:!0});C(v,200,{cancelled:H})}async function Xe(a){let v=Mt().slice(0,8),R=a.threadId,w=!R;R||(R=(await D.createThread(v,[])).id,_e.set(R,"project_model")),w&&await D.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:a.reason}),await D.appendMessage(R,{role:"assistant",timestamp:Date.now(),jobId:v,responseText:w?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let j={id:v,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:R,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:w},S=$.enqueue(j);return{jobId:v,position:S,threadId:R}}async function zn(a,v){let R=decodeURIComponent(a),w=await W.findModelProposal(R);if(!w){C(v,404,{error:"Model proposal not found"});return}C(v,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:w})}async function Gn(a,v,R){let w=decodeURIComponent(a),j=[];for await(let U of v)j.push(typeof U=="string"?Buffer.from(U):U);let S;try{S=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{C(R,400,{error:"Invalid JSON"});return}let _=(S.changes??[]).flatMap(U=>{if(!Array.isArray(U.path)||U.path.length===0)return[];let ne=U.path.filter(le=>typeof le=="string"||typeof le=="number");if(ne.length!==U.path.length)return[];let de=Array.isArray(U.decisionIds)?U.decisionIds.filter(le=>typeof le=="string"):void 0;return[{path:ne,value:U.value,remove:U.remove===!0,decisionIds:de}]});if(_.length===0){C(R,400,{error:"No selected model changes"});return}let J=(S.changeSummaries??[]).flatMap(U=>{if(!U||typeof U!="object")return[];let ne=Array.isArray(U.path)?U.path.filter(de=>typeof de=="string"||typeof de=="number"):void 0;return Array.isArray(U.path)&&ne?.length!==U.path.length?[]:[{group:typeof U.group=="string"?U.group:void 0,label:typeof U.label=="string"?U.label:void 0,detail:typeof U.detail=="string"?U.detail:void 0,path:ne,value:U.value,currentValue:U.currentValue}]}),B=await W.findModelProposal(w);if(!B){C(R,404,{error:"Model proposal not found"});return}if(B.authorityStatus!=="accepted"){C(R,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(B.status!=="pending"){C(R,409,{error:`Model proposal is already ${B.status}.`});return}let H=B.decisionIds.map(U=>{let ne=B.changes?.filter(Y=>Y.decisionIds.includes(U)).length??0,de=_.filter(Y=>Y.decisionIds?.includes(U)).length,le=de===0?"unprojected":ne>de?"partially_projected":"projected";return{decisionId:U,status:le}}),F=await V.applyModelProjection({runId:B.runId??B.id,presentationJobId:B.presentationJobId,decisionIds:B.decisionIds,changes:_.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:H}),ce=await W.applySelectedModelProposal(w,_,J);if(!ce){C(R,404,{error:"Model proposal not found"});return}if(ce.threadId){let U=At(S.provider),ne=typeof S.model=="string"&&S.model?S.model:void 0;await D.appendMessage(ce.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ce.id}`,responseText:"",provider:U,model:ne})}C(R,200,{proposal:ce,projection:F})}async function Ct(a,v,R){let w=decodeURIComponent(a),{provider:j,model:S}=await Ce(v),_=await W.dismissModelProposal(w);if(!_){C(R,404,{error:"Model proposal not found"});return}_.threadId&&await D.appendMessage(_.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${_.id}`,responseText:"",provider:j,model:S}),C(R,200,{proposal:_})}async function Ce(a){try{let v=[];for await(let w of a)v.push(typeof w=="string"?Buffer.from(w):w);if(v.length===0)return{};let R=JSON.parse(Buffer.concat(v).toString());return{provider:At(typeof R.provider=="string"?R.provider:void 0),model:typeof R.model=="string"&&R.model?R.model:void 0,agentSettings:ht(R)}}catch{return{}}}async function $e(a){let v=_e.get(a);if(v)return v;let j=(await D.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(j.startsWith("Synthesize rules"))return _e.set(a,"synthesize"),"synthesize";if(j.startsWith("Materialize model")||j.startsWith("Project model"))return _e.set(a,"project_model"),"project_model"}async function rt(a,v){let R=[];for await(let B of a)R.push(typeof B=="string"?Buffer.from(B):B);let w;if(R.length>0)try{w=JSON.parse(Buffer.concat(R).toString("utf-8")).serverUrl}catch{}let j=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&j.push(await or(w)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&j.push(await rr(w)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&j.push(await ir(w,m.copilot.path??P));let[S,_,J]=await Promise.all([ro(r),io(r),so(r,m.copilot?.path??P)]);m.claude&&(m.claude.mcp=S),m.codex&&(m.codex.mcp=_),m.copilot&&(m.copilot.mcp=J),C(v,200,{results:j,capabilities:{providers:m}})}async function ft(a,v){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){C(v,400,{error:"Missing or invalid name"});return}let j=await V.recordDirectModelMutation({key:`components.${w.name}`,value:{description:""},claim:`${w.name} is an explicitly governed component in the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),C(v,200,{added:!0,alreadyExists:!1,...j})}async function st(a,v){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){C(v,400,{error:"Missing or invalid name"});return}let j=await V.recordDirectModelMutation({key:`components.${w.name}`,value:null,claim:`${w.name} is not governed as a component in the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),C(v,200,{removed:!0,...j})}async function Hn(a,v){let R=[];for await(let _ of a)R.push(typeof _=="string"?Buffer.from(_):_);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"||typeof w.value!="string"){C(v,400,{error:"Missing or invalid path/value"});return}let j=w.value;try{let _=JSON.parse(w.value);_&&typeof _=="object"&&(j=_)}catch{}let S=await V.recordDirectModelMutation({key:`tokens.${w.path}`,value:j,claim:`${w.path} uses ${w.value} in the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),C(v,200,{updated:!0,...S})}async function nn(a,v){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"){C(v,400,{error:"Missing or invalid path"});return}let j=await V.recordDirectModelMutation({key:`tokens.${w.path}`,value:null,claim:`${w.path} is intentionally absent from the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),C(v,200,{removed:!0,...j})}function hi(a,v){let R=s??"http://localhost:3000";if(!s){let j=a.headers.referer||a.headers.origin;if(j)try{let S=new URL(typeof j=="string"?j:j[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(R=S.origin)}catch{}}let w=_o(y,R);v.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),v.end(w)}async function gi(a){let v=Date.now();if(Ge&&v<Ge.expires){C(a,200,Ge.data);return}try{let{scanForComponents:R}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:w}=await import("./render-generator-HWFLZYC3.mjs"),j=await R(r);Ge={data:j,expires:v+5e3},w(j,r,Et).then(S=>{Et=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),C(a,200,j)}catch(R){console.error("[Bridge] Scanner error:",R),C(a,500,{error:"Failed to scan components"})}}async function yi(a){let v=[Ee(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ee(r,"packages","popmelt","dist","canvas.mjs")];try{let R=bc(import.meta.url);v.unshift(Ee(vc(R),"canvas.mjs"))}catch{}for(let R of v)try{let w=await ni(R,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(w);return}catch{}console.error("[Bridge] Canvas bundle not found in:",v),C(a,404,{error:"Canvas bundle not found"})}async function vi(a,v){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){C(v,400,{error:"Invalid filename"});return}try{let R=[Ee(c,a),Ee(r,".popmelt","artifacts","thread-media",a),Ee(r,".popmelt","artifacts","eval-screenshots",a),Ee(r,".popmelt","evals","screenshots",a),Ee(r,".popmelt","screenshots",a)],w;for(let _ of R)try{w=await ni(_);break}catch{}if(!w)throw new Error("File not found");let j=a.split(".").pop()?.toLowerCase(),S=j==="png"?"image/png":j==="webp"?"image/webp":j==="jpg"||j==="jpeg"?"image/jpeg":"application/octet-stream";v.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),v.end(w)}catch{C(v,404,{error:"File not found"})}}function on(a){return`/files/${Fn(a)}`}async function Ii(a,v){let R=await D.getThread(a);if(!R){C(v,404,{error:"Thread not found"});return}let w=R.messages.filter(B=>B.role==="assistant"&&B.responseText?.includes("Model suggestion ready")),j=await(w.length>0?W.findModelProposalsByThread(a):Promise.resolve([])),S=await Promise.all(j.map(async(B,H)=>{if(B.authorityStatus==="accepted")return B;let F=(await Promise.all(B.decisionIds.map(ce=>V.findPendingProposalForLegacyDecision(ce)))).find(Boolean);return{...B,authorityStatus:"legacy_untrusted",presentationJobId:B.presentationJobId??w[H]?.jobId??w.at(-1)?.jobId,underlyingProposalId:F?.proposalId,underlyingClaim:F?.claim}})),_=[...S].sort((B,H)=>H.updatedAt-B.updatedAt)[0]??null,J=R.messages.map(({screenshotPath:B,screenshotPaths:H,imagePaths:F,replyImagePaths:ce,...U})=>({...U,...B?{screenshotUrl:on(B)}:{},...H?{screenshotUrls:Object.fromEntries(Object.entries(H).map(([ne,de])=>[ne,on(de)]))}:{},...F?{imageUrls:Object.fromEntries(Object.entries(F).map(([ne,de])=>[ne,de.map(on)]))}:{},...ce?{replyImageUrls:ce.map(on)}:{}}));C(v,200,{id:R.id,createdAt:R.createdAt,messages:J,modelProposal:_,modelProposals:S})}async function wi(a,v){let R=decodeURIComponent(a);if(!await D.deleteThread(R)){C(v,404,{deleted:!1,error:"Thread not found"});return}C(v,200,{deleted:!0})}let Mo=9,Ao=!1;for(let a=n;a<n+Mo;a++)try{await Dc(He,a),y=a,Ao=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(v){if(v.code==="EADDRINUSE"){let R=await Oc(a);if(zr(R,{projectId:i,version:Yt,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw v}if(!Ao)throw new Error(`[Bridge] All ports ${n}\u2013${n+Mo-1} in use`);for(let[a,v]of Object.entries(m))!v.available||!v.path||p(a,v.path).then(R=>{if(R)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),v.available=!1,v.path=null;for(let w of re)qn(w,{type:"capabilities_changed",data:{}})}});let bi=setInterval(()=>{si(c).catch(()=>{})},kc),Eo=setInterval(()=>{h.expireStale().becameEmpty&&Z()},Pc);return Eo.unref?.(),{port:y,projectId:i,close:async()=>{clearInterval(bi),clearInterval(Eo),z(),h.clear(),await E.destroyAsync(),$.destroy();for(let a of re)try{a.res.end()}catch{}return re.clear(),new Promise(a=>{He.close(()=>a())})}}}async function si(o){try{let e=await uc(o),n=Date.now();for(let t of e){let r=Ee(o,t);try{let i=await fc(r);n-i.mtimeMs>Rc&&await hc(r)}catch{}}}catch{}}var Lc=parseInt(process.env.POPMELT_PORT||"1111",10),pi=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Fc=process.env.POPMELT_DEV_ORIGIN||void 0,qc=process.env.POPMELT_COPILOT_PATH||void 0,ui=li(pi,".popmelt"),mi=li(ui,"bridge.lock");async function Uc(o){await Jc(ui,{recursive:!0}),await Bc(mi,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
179
+ `)}async function fi(){try{await Nc(mi)}catch{}}async function zc(){let o=await di({port:Lc,projectRoot:pi,devOrigin:Fc,copilotPath:qc,restartMode:"detached"});await Uc(o.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await o.close(),await fi(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}zc().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),fi().finally(()=>process.exit(1))});