@popmelt.com/core 0.8.17 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{spawn as il}from"child_process";import{closeSync as rl,openSync as sl}from"fs";import{appendFile as al,mkdir as cl,readFile as dl,realpath as ll}from"fs/promises";import{dirname as pl,join as ci}from"path";import{fileURLToPath as ul}from"url";import{execFileSync as kd,spawn as Wr}from"child_process";import{randomUUID as rt}from"crypto";import{mkdir as jd,readFile as Hr,readdir as Ad,realpath as Md,stat as Ed,unlink as _d,writeFile as lo}from"fs/promises";import{createServer as Cd}from"http";import{tmpdir as $d}from"os";import{basename as po,dirname as Od,isAbsolute as Zr,join as De,relative as Dd,resolve as Nd}from"path";import{fileURLToPath as Bd}from"url";function ui(o,e){return`<!DOCTYPE html>
1
+ import{spawn as Ml}from"child_process";import{closeSync as El,openSync as _l}from"fs";import{appendFile as Cl,mkdir as $l,readFile as Ol,realpath as Dl}from"fs/promises";import{dirname as Nl,join as vo}from"path";import{fileURLToPath as Bl}from"url";import{execFileSync as Zd,spawn as ps}from"child_process";import{randomUUID as ct}from"crypto";import{mkdir as el,readFile as us,readdir as tl,realpath as nl,stat as il,unlink as ol,writeFile as vi}from"fs/promises";import{createServer as rl}from"http";import{tmpdir as sl}from"os";import{basename as Ii,dirname as al,isAbsolute as vs,join as Ne,relative as cl,resolve as dl}from"path";import{fileURLToPath as ll}from"url";function To(i,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -28,21 +28,21 @@ import{spawn as il}from"child_process";import{closeSync as rl,openSync as sl}fro
28
28
  });
29
29
  </script>
30
30
  </body>
31
- </html>`}var ys=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),vs=new Set(["default","flex","fast","priority"]);function At(o){let e=typeof o.reasoningEffort=="string"&&ys.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 In(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 Is}from"child_process";import{createInterface as ws}from"readline";function Qt(o,e){let n=e.trim();if(!n)return"";let t=o.length>0?`
32
-
33
- ${n}`:n;return o.push(t),t}var bs=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"]),mi=1e5;function xs(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!bs.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>mi?t.slice(0,mi)+`
34
- \u2026[truncated]`:t}function wn(o,e){let{prompt:n,projectRoot:t,maxTurns:i=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:u,reasoningEffort:I,timeoutMs:x=3e5,onEvent:T}=e,k=[];d?k.push("--resume",d,"-p",n):k.push("-p",n),k.push("--output-format","stream-json","--verbose","--max-turns",String(i),"--max-budget-usd",String(r)),u&&k.push("--model",u),I&&k.push("--effort",I);for(let l of s)k.push("--allowedTools",l);let S=Is(c,k,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(l=>{let f,m=[],h=[],j=[],b=!1,g="",J,E,R=!1,N=setTimeout(()=>{R=!0,S.kill("SIGTERM"),setTimeout(()=>{try{S.kill("SIGKILL")}catch{}},5e3)},x),V=ws({input:S.stdout}),K=new Set;V.on("line",Q=>{if(Q.trim())try{let w=JSON.parse(Q);w.session_id&&!f&&(f=w.session_id);let H=w.type??(w.event?.type?`event.${w.event.type}`:"unknown");if(K.add(H),w.type==="result"&&w.result&&m.length===0){let L=typeof w.result=="string"?w.result:"";if(L){let O=Qt(m,L);O&&T?.({type:"delta",jobId:o,text:O},o)}}if(w.type==="assistant"&&Array.isArray(w.message?.content)){typeof w.error=="string"&&(J=w.error);for(let L of w.message.content){if(L.type==="text"&&L.text){let O=Qt(m,L.text);O&&T?.({type:"delta",jobId:o,text:O},o)}if(L.type==="tool_use"&&L.name){let O=L.input?.file_path||L.input?.path||void 0,he=xs(L);if(T?.({type:"tool_use",jobId:o,tool:L.name,...O?{file:O}:{},...he?{content:he}:{}},o),L.name==="Edit"&&L.input?.file_path){let B={tool:"Edit",file_path:L.input.file_path,old_string:L.input.old_string,new_string:L.input.new_string,replace_all:L.input.replace_all};h.push(B),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:B.file_path,oldString:typeof B.old_string=="string"?B.old_string:void 0,newString:typeof B.new_string=="string"?B.new_string:void 0,replaceAll:typeof B.replace_all=="boolean"?B.replace_all:void 0})}else L.name==="Write"&&L.input?.file_path&&(h.push({tool:"Write",file_path:L.input.file_path,content:L.input.content}),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:L.input.file_path,content:typeof L.input.content=="string"?L.input.content:void 0}))}L.type==="thinking"&&L.thinking&&T?.({type:"thinking",jobId:o,text:L.thinking},o)}}w.type==="result"&&w.is_error===!0&&(b=!0,typeof w.error=="string"&&(J=w.error),typeof w.result=="string"&&(E=w.result)),w.type==="user"&&w.tool_use_result?.file?.filePath&&T?.({type:"tool_use",jobId:o,tool:"Read",file:w.tool_use_result.file.filePath},o)}catch{}});let W=[];S.stderr?.on("data",Q=>{W.push(Q.toString())}),S.on("close",Q=>{if(clearTimeout(N),V.close(),m.length===0&&K.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...K].join(", ")}`),R)b=!0,g=`Timed out after ${Math.round(x/6e4)} minutes`;else if(Q!==0&&Q!==null){b=!0;let H=W.join("").trim(),L=m.join("").trim(),O=m.length===0&&K.size>0?` (no text captured, event types: ${[...K].join(", ")})`:"";g=H||E||L||`Claude process exited with code ${Q}${O}`}b&&!g&&E&&(g=E);let w=Ss(g,J);l({sessionId:f,text:m.join(""),success:!b,error:b?w.message:void 0,errorCode:b?w.code:void 0,recoverableError:b?w.recoverable:void 0,fileEdits:h.length>0?h:void 0,editEvents:j.length>0?j:void 0})}),S.on("error",Q=>{clearTimeout(N),b=!0,g=Q.message,l({sessionId:f,text:m.join(""),success:!1,error:g,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:h.length>0?h:void 0,editEvents:j.length>0?j:void 0})})});return{process:S,result:p}}function Ss(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 Ts,spawnSync as Ii}from"child_process";import{readFileSync as Ps,statSync as Rs}from"fs";import{basename as ks,extname as js,isAbsolute as As,relative as wi,resolve as Ms}from"path";import{createInterface as Es}from"readline";function fi(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var hi=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"]),bo=2e5,_s=1e5,bi=2e5;function xi(o){let e=ks(o).toLowerCase(),n=js(o).toLowerCase();return hi.has(n)||hi.has(e)}function Xt(o,e){let n=As(e)?e:Ms(o,e),t=wi(o,n);return t===""||t.startsWith("..")?null:n}function bn(o,e){if(!xi(e))return;let n=Xt(o,e);if(n)try{let t=Rs(n);return t.isFile()?t.size>bo?{exists:!0,truncated:!0}:{exists:!0,content:Ps(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Cs(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function $s(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 gi(o){return Cs(o,["patch","diff","unifiedDiff","unified_diff"])}function xo(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function yi(o,e){let n=Ii("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:bi+65536});return n.status!==0?null:n.stdout??""}function Os(o){let e=new Set;for(let n of o.split(`
35
- `)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let i=t.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function vi(o){let e=yi(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=yi(o,["diff","--no-ext-diff","HEAD","--"])??"",t=xo(n,bi);return{status:e,changedFiles:Os(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Ds(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function Ns(o,e){if(!xi(e))return;let n=Xt(o,e);if(!n)return;let t=wi(o,n);if(t===""||t.startsWith(".."))return;let i=Ii("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:bo+65536});if(i.status!==0)return{exists:!1};let r=i.stdout??"",s=xo(r,bo);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Bs(o,e,n){return e.map(t=>{let i=n.has(t)?n.get(t):Ns(o,t),r=bn(o,t);return{filePath:t,...i?{before:i}:{},...r?{after:r}:{}}})}function xn(o,e){let{prompt:n,projectRoot:t,screenshotPath:i,resumeSessionId:r,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:u=[]}=e,I=[];if(r){I.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let k of u)I.push("-c",k);s&&I.push("-m",s),I.push(r),I.push(n),i&&I.push("--image",i)}else{I.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let k of u)I.push("-c",k);s&&I.push("-m",s),I.push(n),i&&I.push("--image",i)}let x=Ts("codex",I,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),T=new Promise(k=>{let S,p=[],l=[],f=[],m=new Map,h=new Map,j=!1,b="",g=Es({input:x.stdout}),J=new Set;g.on("line",R=>{if(R.trim())try{let N=JSON.parse(R),V=N.type??"unknown";if(J.add(V),V==="thread.started"&&N.thread_id&&!S&&(S=N.thread_id),(V==="item.agentMessage.delta"||V==="item/agentMessage/delta")&&N.delta?.text&&(p.push(N.delta.text),c?.({type:"delta",jobId:o,text:N.delta.text},o)),(V==="item.reasoning.delta"||V==="item/reasoning/delta")&&N.delta?.text&&c?.({type:"thinking",jobId:o,text:N.delta.text},o),(V==="item.started"||V==="item/started")&&N.item){let K=N.item.type;if(K==="command_execution"){let W=N.item.command,Q=W?fi(W):void 0,w=vi(t),H=new Map;for(let O of w?.changedFiles??[])H.set(O,bn(t,O));typeof N.item.id=="string"&&h.set(N.item.id,{...W?{rawCommand:W}:{},...Q?{command:Q}:{},...w?{beforeWorktree:w}:{},beforeSnapshots:H});let L=Q?`Bash: ${Q.split(`
36
- `)[0].slice(0,80)}`:"Bash";l.push(L),c?.({type:"tool_use",jobId:o,tool:"Bash",...Q?{content:Q}:{}},o)}else if(K==="file_change"){let W=N.item.filename||N.item.path;W&&!m.has(W)&&m.set(W,bn(t,W)),l.push(W?`Edit ${W.split("/").pop()}`:"Edit");let Q=W?Xt(t,W)??W:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...Q?{file:Q}:{}},o)}else if(K==="file_read"){let W=N.item.filename||N.item.path;l.push(W?`Read ${W.split("/").pop()}`:"Read");let Q=W?Xt(t,W)??W:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...Q?{file:Q}:{}},o)}else if(K==="web_search")l.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(K==="mcp_tool_call"){let W=N.item.tool_name||N.item.name||"MCP";l.push(W),c?.({type:"tool_use",jobId:o,tool:W},o)}}if((V==="item.completed"||V==="item/completed")&&N.item){if(N.item.type==="agent_message"){let K=N.item.text;if(typeof K=="string"&&K){let W=Qt(p,K);W&&c?.({type:"delta",jobId:o,text:W},o)}}else if(N.item.type==="reasoning"){let K=N.item.text;typeof K=="string"&&K&&c?.({type:"thinking",jobId:o,text:K},o)}else if(N.item.type==="file_change"&&Array.isArray(N.item.changes))for(let K of N.item.changes){let W=K.path||K.filename,Q=K.kind==="add"?"Write":"Edit";if(W){l.push(`${Q} ${W.split("/").pop()}`);let w=Xt(t,W)??W;c?.({type:"tool_use",jobId:o,tool:Q,file:w},o);let H=K,L=typeof H.kind=="string"?H.kind:void 0,O=$s(L),he=m.get(W),B=bn(t,W);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:O,filePath:W,...he?{before:he}:{},...B?{after:B}:{},...gi(H)?{patch:gi(H)}:{},...L?{rawKind:L}:{}}),m.set(W,B)}}else if(N.item.type==="command_execution"){let K=typeof N.item.id=="string"?N.item.id:void 0,W=K?h.get(K):void 0,Q=typeof N.item.command=="string"?N.item.command:W?.rawCommand,w=Q?fi(Q):W?.command,H=vi(t);if(Ds(W?.beforeWorktree,H)){let L=[...new Set([...W?.beforeWorktree?.changedFiles??[],...H?.changedFiles??[]])],O=typeof N.item.aggregated_output=="string"?xo(N.item.aggregated_output,_s):void 0,he=typeof N.item.exit_code=="number"?N.item.exit_code:N.item.exit_code===null?null:void 0,B=typeof N.item.status=="string"?N.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...Q?{rawCommand:Q}:{},...w?{command:w}:{},...he!==void 0?{exitCode:he}:{},...B?{status:B}:{},...O?{output:O.text}:{},...O?.truncated?{outputTruncated:!0}:{},...W?.beforeWorktree?{beforeWorktree:W.beforeWorktree}:{},...H?{afterWorktree:H}:{},...L.length>0?{touchedFiles:Bs(t,L,W?.beforeSnapshots??new Map)}:{}})}K&&h.delete(K)}}V==="turn.failed"&&(j=!0,b=N.error?.message||N.message||"Turn failed")}catch{}});let E=[];x.stderr?.on("data",R=>{E.push(R.toString())}),x.on("close",R=>{g.close(),p.length===0&&J.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...J].join(", ")}`),R!==0&&R!==null&&(j=!0,b=E.join("")||`Codex process exited with code ${R}`),k({sessionId:S,text:p.join(""),success:!j,error:j?b:void 0,editEvents:f.length>0?f:void 0,toolsUsed:l.length>0?l:void 0})}),x.on("error",R=>{j=!0,b=R.message,k({sessionId:S,text:p.join(""),success:!1,error:b,editEvents:f.length>0?f:void 0,toolsUsed:l.length>0?l:void 0})})});return{process:x,result:T}}import{spawn as Js}from"child_process";import{createInterface as Ls}from"readline";function Si(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 Ti(o,e){let{prompt:n,projectRoot:t,resumeSessionId:i,model:r,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"];i&&u.push(`--resume=${i}`),r&&u.push("--model",r),u.push("-p",n);let I=Js(d,u,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),x=new Promise(T=>{let k,S=[],p=[],l=!1,f="",m=!1,h=setTimeout(()=>{m=!0,I.kill("SIGTERM"),setTimeout(()=>{try{I.kill("SIGKILL")}catch{}},5e3)},s),j=Ls({input:I.stdout}),b=new Set,g=[];j.on("line",E=>{if(E.trim())try{let R=JSON.parse(E),N=Zt(R);b.add(N),g.length<5&&Fs(N)&&g.push(E.slice(0,800));let V=Yt(R,["sessionId","session_id","id"],["session","conversation","thread"]);V&&!k&&(k=V);let K=qs(R,S.length===0);K&&(S.push(K),c?.({type:"delta",jobId:o,text:K},o));let W=Us(R);W&&c?.({type:"thinking",jobId:o,text:W},o);let Q=zs(R);Q&&(p.push(Q.label),c?.({type:"tool_use",jobId:o,tool:Q.tool,...Q.file?{file:Q.file}:{},...Q.content?{content:Q.content}:{}},o));let w=Gs(R);w&&(l=!0,f=w)}catch{}});let J=[];I.stderr?.on("data",E=>{J.push(E.toString())}),I.on("close",E=>{clearTimeout(h),j.close(),S.length===0&&b.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...b].join(", ")}`),g.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${g.join(`
37
- `)}`)),m?(l=!0,f=`Timed out after ${Math.round(s/6e4)} minutes`):E!==0&&E!==null&&(l=!0,f=J.join("").trim()||f||`Copilot process exited with code ${E}`);let R=l?Si(f,r):null;T({sessionId:k,text:S.join(""),success:!l,error:R?.message,errorCode:R?.code,recoverableError:R?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),I.on("error",E=>{clearTimeout(h);let R=Si(E.message,r);T({sessionId:k,text:S.join(""),success:!1,error:R.message,errorCode:R.code,recoverableError:R.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:I,result:x}}function Zt(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 qs(o,e=!1){let n=Zt(o).toLowerCase(),t=o.update,i=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&i?.type==="text"&&typeof i.text=="string")return i.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return ze(o.delta)??ze(o.content)??ze(o.message);if(n==="assistant.message"&&e)return ze(o.message)??ze(o.content)??ze(o);if(n==="result"&&e)return ze(o.result)??ze(o.output)??ze(o.message)??ze(o);let r=o.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof o.text=="string"&&So(o))return o.text;if(typeof o.message=="string"&&So(o))return o.message;if(typeof o.delta=="string"&&So(o))return o.delta}function ze(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(ze).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=ze(e[n]);if(t)return t}}function Fs(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function Us(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 zs(o){let e=Yt(o,["tool","toolName","tool_name","name"]),n=Yt(o,["command","cmd"]),t=Yt(o,["file","path","filename","filePath"]),i=Zt(o);if(n||i.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
38
- `)[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&&(i.includes("file")||i.includes("write")||i.includes("edit"))){let r=i.includes("write")?"Write":i.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${t.split("/").pop()}`,file:t}}}function Gs(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"&&Zt(o).toLowerCase().includes("error"))return o.message}function Yt(o,e,n=[]){for(let t of e){let i=o[t];if(typeof i=="string")return i}for(let[t,i]of Object.entries(o)){if(!i||typeof i!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let r=Yt(i,e);if(r)return r}}function So(o){let e=Zt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as Ws,readFile as Hs}from"fs/promises";import{join as To}from"path";var Sn=class{constructor(e){let n=To(e,".popmelt");this.decisionsDir=To(n,"decisions")}async listDecisionIds(){try{return(await Ws(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 Hs(To(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{createHash as Vs,randomUUID as Ks}from"crypto";import{mkdir as Po,readFile as Pi,readdir as Ri,rename as Tn,stat as ki,unlink as Pn,writeFile as Rn}from"fs/promises";import{extname as Qs,join as Ve}from"path";var Xs=10080*60*1e3,Ys=600*1e3,Zs=3600*1e3;function ea(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function ta(o,e){return[...o.trim()].map(t=>t==="/"||t==="\\"||t.charCodeAt(0)<32?"-":t).join("").slice(0,120)||e}var kn=class{constructor(e){this.draftsDir=Ve(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ve(e,".popmelt","artifacts","thread-media")}async stage(e){let n=Ks(),t=ea(e.mimeType),i=`${n}${t}`,r=Date.now(),s={id:n,annotationId:e.annotationId,name:ta(e.name,`pasted-context${t}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:i};await Po(this.draftsDir,{recursive:!0});let c=Ve(this.draftsDir,i),d=Ve(this.draftsDir,`${n}.json`),u=`${c}.part`,I=`${d}.part`;return await Rn(u,e.data),await Tn(u,c),await Rn(I,JSON.stringify(s,null,2)),await Tn(I,d),s}async claim(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(delete t.releasedAt,t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async release(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(t.releasedAt=Date.now(),t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async promote(e){let n={};for(let t of e){let i=await this.readManifest(t.id);if(!i)throw new Error(`Draft attachment ${t.id} is unavailable or expired.`);if(i.annotationId!==t.annotationId)throw new Error(`Draft attachment ${t.id} does not belong to annotation ${t.annotationId}.`);let r=Ve(this.draftsDir,i.contentFile),s=await Pi(r),c=Vs("sha256").update(s).digest("hex"),d=Ve(this.mediaDir,`${c}${Qs(i.contentFile)||".bin"}`);await Po(this.mediaDir,{recursive:!0});try{await ki(d)}catch{let u=`${d}.part`;await Rn(u,s),await Tn(u,d)}(n[t.annotationId]??=[]).push({id:i.id,name:i.name,mimeType:i.mimeType,size:i.size,kind:i.kind,path:d}),i.releasedAt=Date.now(),i.lastSeenAt=Date.now(),await this.writeManifest(i)}return n}async sweep(e=Date.now()){let n;try{n=await Ri(this.draftsDir)}catch{return}await Promise.all(n.map(async t=>{let i=Ve(this.draftsDir,t);if(t.endsWith(".part")){let c=await ki(i).catch(()=>null);c&&e-c.mtimeMs>Zs&&await Pn(i).catch(()=>{});return}if(!t.endsWith(".json"))return;let r=await this.readManifest(t.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>Ys:e-r.lastSeenAt>Xs)||await Promise.all([Pn(i).catch(()=>{}),Pn(Ve(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Ri(this.draftsDir)}catch{return}await Promise.all(e.filter(n=>n.endsWith(".part")).map(n=>Pn(Ve(this.draftsDir,n)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Pi(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await Po(this.draftsDir,{recursive:!0});let n=Ve(this.draftsDir,`${e.id}.json`),t=`${n}.part`;await Rn(t,JSON.stringify(e,null,2)),await Tn(t,n)}};import{randomUUID as ji}from"crypto";import{mkdir as Ro,readFile as ko,writeFile as jn}from"fs/promises";import{dirname as jo,join as Mt}from"path";var Ke="[ProjectionWorker]",na={version:1,runs:[]},oa={version:1,updatedAt:0,proposals:[]},ia=12;function ra(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 Ai(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(`${Ke} 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(i=>typeof i=="string"):[]})}return e.length>30&&console.warn(`${Ke} Rule count ${e.length} exceeds cap of 30`),e}function sa(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function aa(o,e,n){let t=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let S of r){if(!S||typeof S!="object")continue;let p=S.sources;if(Array.isArray(p))for(let l of p)typeof l=="string"&&t.has(l)&&i.add(l)}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=r.filter(S=>{if(!S||typeof S!="object")return!1;let p=S.id,l=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(l)!==JSON.stringify(S)}).length,I=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},x=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},T=Object.keys(s).filter(S=>JSON.stringify(s[S])!==JSON.stringify(I[S])).length,k=Object.keys(c).filter(S=>JSON.stringify(c[S])!==JSON.stringify(x[S])).length;return{ruleCount:u,tokenSectionCount:T,componentCount:k,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(S=>!i.has(S))}}function ca(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function da(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let i=typeof n=="number"?[]:{};return o[String(e)]=i,i}function An(o,e,n){let t=o;for(let r=0;r<e.length-1;r++)t=da(t,e[r],e[r+1]);let i=e[e.length-1];t[String(i)]=ca(n)}function Mi(o,e){let n=o;for(let i=0;i<e.length-1;i++){let r=n[String(e[i])];if(!r||typeof r!="object")return;n=r}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function la(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 pa(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 Ei(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=la(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?pa(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Mn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Mt(e,".popmelt");this.runsPath=Mt(t,"projection-runs.json"),this.legacyRunsPath=Mt(t,"materialization-runs.json"),this.proposalsPath=Mt(t,"projection-queue.json"),this.legacyProposalsPath=Mt(t,"model-proposals.json"),this.modelPath=Mt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ko(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=ra(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let i=t.key.split(".");t.value===null?Mi(n,i):An(n,i,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(ia),n=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!n.has(i.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(),i=t.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(S=>S.id);console.log(`${Ke} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=ha(i,s),d=sa(i,t.totalCandidateDecisionCount,c);n=ji().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:r,startedAt:Date.now(),promptStats:d};await this.persistRun(u);let I=!0,x,T,k;try{let S=`projection-${Date.now()}`,{provider:p,result:l}=this.spawnModelAgent(S,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});u={...u,provider:p},await this.persistRun(u);let f=await l;if(!f.success)I=!1,x=f.error,console.error(`${Ke} ${p} spawn error:`,x);else{let m=fa(f.text,r);if(m){let h=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of m)An(h,g.path,g.value);Array.isArray(h.rules)&&(h.rules=Ai(h.rules));let j=aa(h,r,s);if(m){let g=[...new Set(m.flatMap(J=>J.decisionIds))];j.coveredDecisionIds=g,j.uncoveredDecisionIds=r.filter(J=>!g.includes(J))}T=j;let b=await this.createModelProposal({decisionIds:r,proposedModel:h,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:T,changes:m});k=b.id,console.log(`${Ke} Created model proposal ${b.id} for ${r.length} decision(s)`)}else I=!1,x="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${x}`)}}catch(S){I=!1,x=S instanceof Error?S.message:String(S),console.error(`${Ke} Error:`,x)}return await this.persistRun({...u,status:I?"proposed":"failed",completedAt:Date.now(),error:x,outputStats:T,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:I,error:x}),{processedIds:r,success:I,error:x,runId:n,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ai(e.rules)),await jn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ke} 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 Ro(jo(this.runsPath),{recursive:!0}),await jn(this.runsPath,JSON.stringify(n,null,2)),n):{...na,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let i=await this.readProposalStore(this.legacyProposalsPath);i&&(e={version:1,updatedAt:Date.now(),proposals:i.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...oa,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(t);for(let s of i.changes??[])An(r,s.path,s.value);return{...i,proposedModel:r}})}}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,i)=>i.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>t.createdAt-i.createdAt||t.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,n,t,i="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?Mi(s,d.path):An(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:i,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:ji().slice(0,8),status:"pending",title:ua(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"}.`:ma(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(i=>i.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),i=null;return t.proposals=t.proposals.map(r=>r.id!==e?r:(i={...r,...n,updatedAt:Date.now()},i)),i?(t.updatedAt=Date.now(),await this.persistModelProposals(t),i):null}async persistModelProposals(e){try{await Ro(jo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...i})=>i)};await jn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ke} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(i=>i.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await Ro(jo(this.runsPath),{recursive:!0}),await jn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ke} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await ko(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await ko(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,i){let r=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...xn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:In(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Ke} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...wn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function ua(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.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 ma(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,i=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function fa(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 i=new Set(e),r=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(x=>typeof x=="string"||typeof x=="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 I=Array.isArray(d.decisionIds)?d.decisionIds.filter(x=>typeof x=="string"&&i.has(x)):[];return I.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:I,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===t.length?r:null}catch{return null}}function ha(o,e){let n=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
31
+ </html>`}var Ns=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Bs=new Set(["default","flex","fast","priority"]);function _t(i){let e=typeof i.reasoningEffort=="string"&&Ns.has(i.reasoningEffort)?i.reasoningEffort:void 0,t=typeof i.serviceTier=="string"&&Bs.has(i.serviceTier)?i.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function kn(i){let e=[];return i?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(i.reasoningEffort)}`),i?.serviceTier&&e.push(`service_tier=${JSON.stringify(i.serviceTier)}`),e}import{spawn as Js}from"child_process";import{createInterface as Ls}from"readline";function nn(i,e){let t=e.trim();if(!t)return"";let n=i.length>0?`
32
+
33
+ ${t}`:t;return i.push(n),n}var qs=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"]),Po=1e5;function Fs(i){let e=i.input?.file_path||i.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!qs.has(t))return;let n;if(i.name==="Write"&&typeof i.input?.content=="string"?n=i.input.content:i.name==="Edit"&&typeof i.input?.new_string=="string"&&(n=i.input.new_string),!!n)return n.length>Po?n.slice(0,Po)+`
34
+ \u2026[truncated]`:n}function Rn(i,e){let{prompt:t,projectRoot:n,maxTurns:o=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:w,timeoutMs:b=3e5,onEvent:P}=e,R=[];d?R.push("--resume",d,"-p",t):R.push("-p",t),R.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(r)),l&&R.push("--model",l),w&&R.push("--effort",w);for(let p of s)R.push("--allowedTools",p);let S=Js(c,R,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),f=new Promise(p=>{let y,m=[],h=[],M=[],g=!1,u="",E,j,T=!1,O=setTimeout(()=>{T=!0,S.kill("SIGTERM"),setTimeout(()=>{try{S.kill("SIGKILL")}catch{}},5e3)},b),H=Ls({input:S.stdout}),K=new Set;H.on("line",Q=>{if(Q.trim())try{let x=JSON.parse(Q);x.session_id&&!y&&(y=x.session_id);let V=x.type??(x.event?.type?`event.${x.event.type}`:"unknown");if(K.add(V),x.type==="result"&&x.result&&m.length===0){let L=typeof x.result=="string"?x.result:"";if(L){let N=nn(m,L);N&&P?.({type:"delta",jobId:i,text:N},i)}}if(x.type==="assistant"&&Array.isArray(x.message?.content)){typeof x.error=="string"&&(E=x.error);for(let L of x.message.content){if(L.type==="text"&&L.text){let N=nn(m,L.text);N&&P?.({type:"delta",jobId:i,text:N},i)}if(L.type==="tool_use"&&L.name){let N=L.input?.file_path||L.input?.path||void 0,ge=Fs(L);if(P?.({type:"tool_use",jobId:i,tool:L.name,...N?{file:N}:{},...ge?{content:ge}:{}},i),L.name==="Edit"&&L.input?.file_path){let J={tool:"Edit",file_path:L.input.file_path,old_string:L.input.old_string,new_string:L.input.new_string,replace_all:L.input.replace_all};h.push(J),M.push({sequence:M.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:J.file_path,oldString:typeof J.old_string=="string"?J.old_string:void 0,newString:typeof J.new_string=="string"?J.new_string:void 0,replaceAll:typeof J.replace_all=="boolean"?J.replace_all:void 0})}else L.name==="Write"&&L.input?.file_path&&(h.push({tool:"Write",file_path:L.input.file_path,content:L.input.content}),M.push({sequence:M.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:L.input.file_path,content:typeof L.input.content=="string"?L.input.content:void 0}))}L.type==="thinking"&&L.thinking&&P?.({type:"thinking",jobId:i,text:L.thinking},i)}}x.type==="result"&&x.is_error===!0&&(g=!0,typeof x.error=="string"&&(E=x.error),typeof x.result=="string"&&(j=x.result)),x.type==="user"&&x.tool_use_result?.file?.filePath&&P?.({type:"tool_use",jobId:i,tool:"Read",file:x.tool_use_result.file.filePath},i)}catch{}});let G=[];S.stderr?.on("data",Q=>{G.push(Q.toString())}),S.on("close",Q=>{if(clearTimeout(O),H.close(),m.length===0&&K.size>0&&console.warn(`[Claude:${i}] No text captured. Event types seen: ${[...K].join(", ")}`),T)g=!0,u=`Timed out after ${Math.round(b/6e4)} minutes`;else if(Q!==0&&Q!==null){g=!0;let V=G.join("").trim(),L=m.join("").trim(),N=m.length===0&&K.size>0?` (no text captured, event types: ${[...K].join(", ")})`:"";u=V||j||L||`Claude process exited with code ${Q}${N}`}g&&!u&&j&&(u=j);let x=Us(u,E);p({sessionId:y,text:m.join(""),success:!g,error:g?x.message:void 0,errorCode:g?x.code:void 0,recoverableError:g?x.recoverable:void 0,fileEdits:h.length>0?h:void 0,editEvents:M.length>0?M:void 0})}),S.on("error",Q=>{clearTimeout(O),g=!0,u=Q.message,p({sessionId:y,text:m.join(""),success:!1,error:u,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:h.length>0?h:void 0,editEvents:M.length>0?M:void 0})})});return{process:S,result:f}}function Us(i,e){let t=i.trim()||"Claude CLI failed",n=`${e??""} ${t}`.toLowerCase();return n.includes("authentication_failed")||n.includes("not logged in")||n.includes("please run /login")||n.includes("api key")?{message:t,code:"claude_auth_required",recoverable:!0}:n.includes("model")&&(n.includes("not found")||n.includes("unknown")||n.includes("unavailable"))?{message:t,code:"claude_model_unavailable",recoverable:!0}:{message:t,code:e||"claude_error",recoverable:!1}}import{spawn as Ws,spawnSync as Co}from"child_process";import{readFileSync as Hs,statSync as Gs}from"fs";import{basename as Vs,extname as Ks,isAbsolute as Qs,relative as $o,resolve as Xs}from"path";import{createInterface as Ys}from"readline";function An(i){return i&&typeof i=="object"&&!Array.isArray(i)?i:void 0}function jn(i,e){for(let t of i)if(t)for(let n of e){let o=t[n];if(typeof o=="string"&&o.trim())return o.trim()}}function ko(i){let e=An(i);if(e)return e;if(typeof i=="string")try{return An(JSON.parse(i))}catch{return}}function Ai(i){return i.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function zs(i,e,t,n){return i!=="node_repl"||e!=="js"?!1:n&&/(?:setupBrowserRuntime|browser-client|\b(?:browser|tab|iab|chrome)\s*\.)/.test(n)?!0:!!(t&&/\b(?:browser|page|tab|rendered|geometry|FAQ)\b/i.test(t))}function Ro(i){let e=An(i)??{},t=An(e.invocation),n=ko(e.arguments)??ko(t?.arguments),o=jn([e,t],["server","server_name"]),r=jn([e,t],["tool","tool_name","name"]),s=jn([n,e,t],["title","display_name","description"]),c=jn([n],["code","script"]),d=zs(o,r,s,c)?"Browser":o?Ai(o):r?Ai(r):"MCP",l=r&&Ai(r),w=s??l,b=w&&w!==d?`${d}: ${w}`:d;return{tool:d,...w?{content:w}:{},telemetryLabel:b}}function jo(i){let e=i.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i}var Ao=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"]),Mi=2e5,Zs=1e5,Oo=2e5;function Do(i){let e=Vs(i).toLowerCase(),t=Ks(i).toLowerCase();return Ao.has(t)||Ao.has(e)}function on(i,e){let t=Qs(e)?e:Xs(i,e),n=$o(i,t);return n===""||n.startsWith("..")?null:t}function Mn(i,e){if(!Do(e))return;let t=on(i,e);if(t)try{let n=Gs(t);return n.isFile()?n.size>Mi?{exists:!0,truncated:!0}:{exists:!0,content:Hs(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function ea(i,e){for(let t of e){let n=i[t];if(typeof n=="string")return n}}function ta(i){let e=i?.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 Mo(i){return ea(i,["patch","diff","unifiedDiff","unified_diff"])}function Ei(i,e){return i.length<=e?{text:i}:{text:i.slice(0,e),truncated:!0}}function Eo(i,e){let t=Co("git",e,{cwd:i,encoding:"utf8",timeout:5e3,maxBuffer:Oo+65536});return t.status!==0?null:t.stdout??""}function na(i){let e=new Set;for(let t of i.split(`
35
+ `)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let o=n.split(" -> ");for(let r of o)r&&e.add(r)}return[...e]}function _o(i){let e=Eo(i,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=Eo(i,["diff","--no-ext-diff","HEAD","--"])??"",n=Ei(t,Oo);return{status:e,changedFiles:na(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function ia(i,e){return!i||!e?!1:i.status!==e.status||(i.diff??"")!==(e.diff??"")}function oa(i,e){if(!Do(e))return;let t=on(i,e);if(!t)return;let n=$o(i,t);if(n===""||n.startsWith(".."))return;let o=Co("git",["show",`HEAD:${n}`],{cwd:i,encoding:"utf8",timeout:5e3,maxBuffer:Mi+65536});if(o.status!==0)return{exists:!1};let r=o.stdout??"",s=Ei(r,Mi);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function ra(i,e,t){return e.map(n=>{let o=t.has(n)?t.get(n):oa(i,n),r=Mn(i,n);return{filePath:n,...o?{before:o}:{},...r?{after:r}:{}}})}function En(i,e){let{prompt:t,projectRoot:n,screenshotPath:o,resumeSessionId:r,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,w=[];if(r){w.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let R of l)w.push("-c",R);s&&w.push("-m",s),w.push(r),w.push(t),o&&w.push("--image",o)}else{w.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let R of l)w.push("-c",R);s&&w.push("-m",s),w.push(t),o&&w.push("--image",o)}let b=Ws("codex",w,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),P=new Promise(R=>{let S,f=[],p=[],y=[],m=new Map,h=new Map,M=!1,g="",u=Ys({input:b.stdout}),E=new Set;u.on("line",T=>{if(T.trim())try{let O=JSON.parse(T),H=O.type??"unknown";if(E.add(H),H==="thread.started"&&O.thread_id&&!S&&(S=O.thread_id),(H==="item.agentMessage.delta"||H==="item/agentMessage/delta")&&O.delta?.text&&(f.push(O.delta.text),c?.({type:"delta",jobId:i,text:O.delta.text},i)),(H==="item.reasoning.delta"||H==="item/reasoning/delta")&&O.delta?.text&&c?.({type:"thinking",jobId:i,text:O.delta.text},i),(H==="item.started"||H==="item/started")&&O.item){let K=O.item.type;if(K==="command_execution"){let G=O.item.command,Q=G?jo(G):void 0,x=_o(n),V=new Map;for(let N of x?.changedFiles??[])V.set(N,Mn(n,N));typeof O.item.id=="string"&&h.set(O.item.id,{...G?{rawCommand:G}:{},...Q?{command:Q}:{},...x?{beforeWorktree:x}:{},beforeSnapshots:V});let L=Q?`Bash: ${Q.split(`
36
+ `)[0].slice(0,80)}`:"Bash";p.push(L),c?.({type:"tool_use",jobId:i,tool:"Bash",...Q?{content:Q}:{}},i)}else if(K==="file_change"){let G=O.item.filename||O.item.path;G&&!m.has(G)&&m.set(G,Mn(n,G)),p.push(G?`Edit ${G.split("/").pop()}`:"Edit");let Q=G?on(n,G)??G:void 0;c?.({type:"tool_use",jobId:i,tool:"Edit",...Q?{file:Q}:{}},i)}else if(K==="file_read"){let G=O.item.filename||O.item.path;p.push(G?`Read ${G.split("/").pop()}`:"Read");let Q=G?on(n,G)??G:void 0;c?.({type:"tool_use",jobId:i,tool:"Read",...Q?{file:Q}:{}},i)}else if(K==="web_search")p.push("WebSearch"),c?.({type:"tool_use",jobId:i,tool:"WebSearch"},i);else if(K==="mcp_tool_call"){let G=Ro(O.item);p.push(G.telemetryLabel),c?.({type:"tool_use",jobId:i,tool:G.tool,...G.content?{content:G.content}:{}},i)}}if((H==="item.completed"||H==="item/completed")&&O.item){if(O.item.type==="agent_message"){let K=O.item.text;if(typeof K=="string"&&K){let G=nn(f,K);G&&c?.({type:"delta",jobId:i,text:G},i)}}else if(O.item.type==="reasoning"){let K=O.item.text;typeof K=="string"&&K&&c?.({type:"thinking",jobId:i,text:K},i)}else if(O.item.type==="file_change"&&Array.isArray(O.item.changes))for(let K of O.item.changes){let G=K.path||K.filename,Q=K.kind==="add"?"Write":"Edit";if(G){p.push(`${Q} ${G.split("/").pop()}`);let x=on(n,G)??G;c?.({type:"tool_use",jobId:i,tool:Q,file:x},i);let V=K,L=typeof V.kind=="string"?V.kind:void 0,N=ta(L),ge=m.get(G),J=Mn(n,G);y.push({sequence:y.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:N,filePath:G,...ge?{before:ge}:{},...J?{after:J}:{},...Mo(V)?{patch:Mo(V)}:{},...L?{rawKind:L}:{}}),m.set(G,J)}}else if(O.item.type==="command_execution"){let K=typeof O.item.id=="string"?O.item.id:void 0,G=K?h.get(K):void 0,Q=typeof O.item.command=="string"?O.item.command:G?.rawCommand,x=Q?jo(Q):G?.command,V=_o(n);if(ia(G?.beforeWorktree,V)){let L=[...new Set([...G?.beforeWorktree?.changedFiles??[],...V?.changedFiles??[]])],N=typeof O.item.aggregated_output=="string"?Ei(O.item.aggregated_output,Zs):void 0,ge=typeof O.item.exit_code=="number"?O.item.exit_code:O.item.exit_code===null?null:void 0,J=typeof O.item.status=="string"?O.item.status:void 0;y.push({sequence:y.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...Q?{rawCommand:Q}:{},...x?{command:x}:{},...ge!==void 0?{exitCode:ge}:{},...J?{status:J}:{},...N?{output:N.text}:{},...N?.truncated?{outputTruncated:!0}:{},...G?.beforeWorktree?{beforeWorktree:G.beforeWorktree}:{},...V?{afterWorktree:V}:{},...L.length>0?{touchedFiles:ra(n,L,G?.beforeSnapshots??new Map)}:{}})}K&&h.delete(K)}}H==="turn.failed"&&(M=!0,g=O.error?.message||O.message||"Turn failed")}catch{}});let j=[];b.stderr?.on("data",T=>{j.push(T.toString())}),b.on("close",T=>{u.close(),f.length===0&&E.size>0&&console.warn(`[Codex:${i}] No text captured. Event types seen: ${[...E].join(", ")}`),T!==0&&T!==null&&(M=!0,g=j.join("")||`Codex process exited with code ${T}`),R({sessionId:S,text:f.join(""),success:!M,error:M?g:void 0,editEvents:y.length>0?y:void 0,toolsUsed:p.length>0?p:void 0})}),b.on("error",T=>{M=!0,g=T.message,R({sessionId:S,text:f.join(""),success:!1,error:g,editEvents:y.length>0?y:void 0,toolsUsed:p.length>0?p:void 0})})});return{process:b,result:P}}import{spawn as sa}from"child_process";import{createInterface as aa}from"readline";function No(i,e){let t=i.trim()||"Copilot CLI failed",n=t.toLowerCase();return n.includes("no authentication information")||n.includes("not authenticated")||n.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`."}:n.includes("model")&&(n.includes("not available")||n.includes("not found")||n.includes("disabled")||n.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:t}:n.includes("mcp")&&(n.includes("blocked")||n.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."}:n.includes("permission")||n.includes("denied")||n.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:t}:{code:"copilot_error",recoverable:!1,message:t}}function Bo(i,e){let{prompt:t,projectRoot:n,resumeSessionId:o,model:r,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];o&&l.push(`--resume=${o}`),r&&l.push("--model",r),l.push("-p",t);let w=sa(d,l,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),b=new Promise(P=>{let R,S=[],f=[],p=!1,y="",m=!1,h=setTimeout(()=>{m=!0,w.kill("SIGTERM"),setTimeout(()=>{try{w.kill("SIGKILL")}catch{}},5e3)},s),M=aa({input:w.stdout}),g=new Set,u=[];M.on("line",j=>{if(j.trim())try{let T=JSON.parse(j),O=sn(T);g.add(O),u.length<5&&da(O)&&u.push(j.slice(0,800));let H=rn(T,["sessionId","session_id","id"],["session","conversation","thread"]);H&&!R&&(R=H);let K=ca(T,S.length===0);K&&(S.push(K),c?.({type:"delta",jobId:i,text:K},i));let G=la(T);G&&c?.({type:"thinking",jobId:i,text:G},i);let Q=pa(T);Q&&(f.push(Q.label),c?.({type:"tool_use",jobId:i,tool:Q.tool,...Q.file?{file:Q.file}:{},...Q.content?{content:Q.content}:{}},i));let x=ua(T);x&&(p=!0,y=x)}catch{}});let E=[];w.stderr?.on("data",j=>{E.push(j.toString())}),w.on("close",j=>{clearTimeout(h),M.close(),S.length===0&&g.size>0&&(console.warn(`[Copilot:${i}] No text captured. Event types seen: ${[...g].join(", ")}`),u.length>0&&console.warn(`[Copilot:${i}] Sample text-bearing candidates: ${u.join(`
37
+ `)}`)),m?(p=!0,y=`Timed out after ${Math.round(s/6e4)} minutes`):j!==0&&j!==null&&(p=!0,y=E.join("").trim()||y||`Copilot process exited with code ${j}`);let T=p?No(y,r):null;P({sessionId:R,text:S.join(""),success:!p,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})}),w.on("error",j=>{clearTimeout(h);let T=No(j.message,r);P({sessionId:R,text:S.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})})});return{process:w,result:b}}function sn(i){if(typeof i.type=="string")return i.type;let e=i.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof i.event=="string"?i.event:"unknown"}function ca(i,e=!1){let t=sn(i).toLowerCase(),n=i.update,o=n?.content;if(n?.sessionUpdate==="agent_message_chunk"&&o?.type==="text"&&typeof o.text=="string")return o.text;if(t==="assistant.message_delta"||t.includes("agent_message.delta"))return Fe(i.delta)??Fe(i.content)??Fe(i.message);if(t==="assistant.message"&&e)return Fe(i.message)??Fe(i.content)??Fe(i);if(t==="result"&&e)return Fe(i.result)??Fe(i.output)??Fe(i.message)??Fe(i);let r=i.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof i.text=="string"&&_i(i))return i.text;if(typeof i.message=="string"&&_i(i))return i.message;if(typeof i.delta=="string"&&_i(i))return i.delta}function Fe(i){if(typeof i=="string")return i;if(!i)return;if(Array.isArray(i)){let t=i.map(Fe).filter(n=>!!n);return t.length>0?t.join(""):void 0}if(typeof i!="object")return;let e=i;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let t of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let n=Fe(e[t]);if(n)return n}}function da(i){let e=i.toLowerCase();return e.includes("assistant.message")||e==="result"}function la(i){if(typeof i.thinking=="string")return i.thinking;if(typeof i.reasoning=="string")return i.reasoning;let e=i.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function pa(i){let e=rn(i,["tool","toolName","tool_name","name"]),t=rn(i,["command","cmd"]),n=rn(i,["file","path","filename","filePath"]),o=sn(i);if(t||o.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
38
+ `)[0].slice(0,80)}`:"Bash",...t?{content:t}:{}};if(e)return{tool:e,label:n?`${e} ${n.split("/").pop()}`:e,...n?{file:n}:{}};if(n&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let r=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${n.split("/").pop()}`,file:n}}}function ua(i){if(typeof i.error=="string")return i.error;if(i.error&&typeof i.error=="object"){let e=i.error;if(typeof e.message=="string")return e.message}if(typeof i.message=="string"&&sn(i).toLowerCase().includes("error"))return i.message}function rn(i,e,t=[]){for(let n of e){let o=i[n];if(typeof o=="string")return o}for(let[n,o]of Object.entries(i)){if(!o||typeof o!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let r=rn(o,e);if(r)return r}}function _i(i){let e=sn(i).toLowerCase();return(typeof i.role=="string"?i.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as ma,readFile as fa}from"fs/promises";import{join as Ci}from"path";var _n=class{constructor(e){let t=Ci(e,".popmelt");this.decisionsDir=Ci(t,"decisions")}async listDecisionIds(){try{return(await ma(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let t=await fa(Ci(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}};import{createHash as ha,randomUUID as ga}from"crypto";import{mkdir as $i,readFile as Jo,readdir as Lo,rename as Cn,stat as qo,unlink as $n,writeFile as On}from"fs/promises";import{extname as ya,join as Ke}from"path";var va=10080*60*1e3,Ia=600*1e3,wa=3600*1e3;function ba(i){return i==="image/svg+xml"?".svg":i==="text/plain"?".txt":".bin"}function xa(i,e){return[...i.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var Dn=class{constructor(e){this.draftsDir=Ke(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ke(e,".popmelt","artifacts","thread-media")}async stage(e){let t=ga(),n=ba(e.mimeType),o=`${t}${n}`,r=Date.now(),s={id:t,annotationId:e.annotationId,name:xa(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:o};await $i(this.draftsDir,{recursive:!0});let c=Ke(this.draftsDir,o),d=Ke(this.draftsDir,`${t}.json`),l=`${c}.part`,w=`${d}.part`;return await On(l,e.data),await Cn(l,c),await On(w,JSON.stringify(s,null,2)),await Cn(w,d),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let o=await this.readManifest(n.id);if(!o)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(o.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let r=Ke(this.draftsDir,o.contentFile),s=await Jo(r),c=ha("sha256").update(s).digest("hex"),d=Ke(this.mediaDir,`${c}${ya(o.contentFile)||".bin"}`);await $i(this.mediaDir,{recursive:!0});try{await qo(d)}catch{let l=`${d}.part`;await On(l,s),await Cn(l,d)}(t[n.annotationId]??=[]).push({id:o.id,name:o.name,mimeType:o.mimeType,size:o.size,kind:o.kind,path:d}),o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o)}return t}async sweep(e=Date.now()){let t;try{t=await Lo(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let o=Ke(this.draftsDir,n);if(n.endsWith(".part")){let c=await qo(o).catch(()=>null);c&&e-c.mtimeMs>wa&&await $n(o).catch(()=>{});return}if(!n.endsWith(".json"))return;let r=await this.readManifest(n.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>Ia:e-r.lastSeenAt>va)||await Promise.all([$n(o).catch(()=>{}),$n(Ke(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Lo(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>$n(Ke(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Jo(Ke(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await $i(this.draftsDir,{recursive:!0});let t=Ke(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await On(n,JSON.stringify(e,null,2)),await Cn(n,t)}};import{randomUUID as Fo}from"crypto";import{mkdir as Oi,readFile as Di,writeFile as Nn}from"fs/promises";import{dirname as Ni,join as Ct}from"path";var Qe="[ProjectionWorker]",Sa={version:1,runs:[]},Ta={version:1,updatedAt:0,proposals:[]},Pa=12;function ka(i){return Array.isArray(i)?i.map((e,t)=>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 Uo(i){let e=[];for(let t of i){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Qe} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${Qe} Rule count ${e.length} exceeds cap of 30`),e}function Ra(i,e,t){return{decisionCount:i.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function ja(i,e,t){let n=new Set(e),o=new Set,r=Array.isArray(i.rules)?i.rules:[];for(let S of r){if(!S||typeof S!="object")continue;let f=S.sources;if(Array.isArray(f))for(let p of f)typeof p=="string"&&n.has(p)&&o.add(p)}let s=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?i.tokens:{},c=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?i.components:{},d=Array.isArray(t?.rules)?t.rules:[],l=r.filter(S=>{if(!S||typeof S!="object")return!1;let f=S.id,p=typeof f=="string"?d.find(y=>y&&typeof y=="object"&&y.id===f):void 0;return JSON.stringify(p)!==JSON.stringify(S)}).length,w=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},b=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},P=Object.keys(s).filter(S=>JSON.stringify(s[S])!==JSON.stringify(w[S])).length,R=Object.keys(c).filter(S=>JSON.stringify(c[S])!==JSON.stringify(b[S])).length;return{ruleCount:l,tokenSectionCount:P,componentCount:R,coveredDecisionIds:[...o],uncoveredDecisionIds:e.filter(S=>!o.has(S))}}function Aa(i){if(i!==void 0)return JSON.parse(JSON.stringify(i))}function Ma(i,e,t){let n=i[e];if(n&&typeof n=="object")return n;let o=typeof t=="number"?[]:{};return i[String(e)]=o,o}function Bn(i,e,t){let n=i;for(let r=0;r<e.length-1;r++)n=Ma(n,e[r],e[r+1]);let o=e[e.length-1];n[String(o)]=Aa(t)}function zo(i,e){let t=i;for(let o=0;o<e.length-1;o++){let r=t[String(e[o])];if(!r||typeof r!="object")return;t=r}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function Ea(i,e){if(!i)return{exists:!1};let t=i;for(let n of e){if(!t||typeof t!="object"||!(String(n)in t))return{exists:!1};t=t[String(n)]}return{exists:!0,value:t}}function _a(i,e){return Array.isArray(e)?i===void 0?e.length>0:!Array.isArray(i)||e.length<=i.length?!1:i.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function Wo(i,e){if(i.authorityStatus!=="accepted"||!i.changes?.length)return null;for(let t of i.changes){let n=Ea(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?_a(n.exists?n.value:void 0,t.value):!n.exists))return null}return i.changes}var Jn=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Ct(e,".popmelt");this.runsPath=Ct(n,"projection-runs.json"),this.legacyRunsPath=Ct(n,"materialization-runs.json"),this.proposalsPath=Ct(n,"projection-queue.json"),this.legacyProposalsPath=Ct(n,"model-proposals.json"),this.modelPath=Ct(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Di(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=ka(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let o=n.key.split(".");n.value===null?zo(t,o):Bn(t,o,n.value)}await this.writeModel(t)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Pa),t=new Set((await this.loadModelProposals()).proposals.flatMap(o=>o.status==="pending"&&o.authorityStatus==="accepted"?o.decisionIds:[]));return{decisions:e.filter(o=>!t.has(o.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let t;try{let n=await this.selectUnprojectedPatternDecisions(),o=n.decisions;if(o.length===0)return{processedIds:[],success:!0};let r=o.map(S=>S.id);console.log(`${Qe} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=Da(o,s),d=Ra(o,n.totalCandidateDecisionCount,c);t=Fo().slice(0,8);let l={id:t,status:"running",provider:e.provider??this.options.provider??"codex",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let w=!0,b,P,R;try{let S=`projection-${Date.now()}`,{provider:f,result:p}=this.spawnModelAgent(S,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:f},await this.persistRun(l);let y=await p;if(!y.success)w=!1,b=y.error,console.error(`${Qe} ${f} spawn error:`,b);else{let m=Oa(y.text,r);if(m){let h=structuredClone(s??{tokens:{},components:{},rules:[]});for(let u of m)Bn(h,u.path,u.value);Array.isArray(h.rules)&&(h.rules=Uo(h.rules));let M=ja(h,r,s);if(m){let u=[...new Set(m.flatMap(E=>E.decisionIds))];M.coveredDecisionIds=u,M.uncoveredDecisionIds=r.filter(E=>!u.includes(E))}P=M;let g=await this.createModelProposal({decisionIds:r,proposedModel:h,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:P,changes:m});R=g.id,console.log(`${Qe} Created model proposal ${g.id} for ${r.length} decision(s)`)}else w=!1,b="No valid bounded <model-changes> block found in response",console.error(`${Qe} ${b}`)}}catch(S){w=!1,b=S instanceof Error?S.message:String(S),console.error(`${Qe} Error:`,b)}return await this.persistRun({...l,status:w?"proposed":"failed",completedAt:Date.now(),error:b,outputStats:P,proposalId:R}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:w,error:b}),{processedIds:r,success:w,error:b,runId:t,proposalId:R}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Uo(e.rules)),await Nn(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 t=await this.readRunStore(this.legacyRunsPath);return t?(await Oi(Ni(this.runsPath),{recursive:!0}),await Nn(this.runsPath,JSON.stringify(t,null,2)),t):{...Sa,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let o=await this.readProposalStore(this.legacyProposalsPath);o&&(e={version:1,updatedAt:Date.now(),proposals:o.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let t=e??{...Ta,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(o=>{if(o.proposedModel)return o;let r=structuredClone(n);for(let s of o.changes??[])Bn(r,s.path,s.value);return{...o,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>o.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>n.createdAt-o.createdAt||n.updatedAt-o.updatedAt)}async applySelectedModelProposal(e,t,n,o="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of t)!Array.isArray(d.path)||d.path.length===0||(d.remove?zo(s,d.path):Bn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:o,error:void 0,selectedChanges:n})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:Fo().slice(0,8),status:"pending",title:Ca(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"}.`:$a(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()},n=await this.loadModelProposals();return n.proposals=[t,...n.proposals.filter(o=>o.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),o=null;return n.proposals=n.proposals.map(r=>r.id!==e?r:(o={...r,...t,updatedAt:Date.now()},o)),o?(n.updatedAt=Date.now(),await this.persistModelProposals(n),o):null}async persistModelProposals(e){try{await Oi(Ni(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...o})=>o)};await Nn(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Qe} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(o=>o.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await Oi(Ni(this.runsPath),{recursive:!0}),await Nn(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Qe} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await Di(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await Di(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,o){let r=n.provider??this.options.provider??"codex",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...En(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:kn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Qe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...Rn(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function Ca(i){let t=(Array.isArray(i.rules)?i.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let n=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function $a(i,e){let t=Array.isArray(i.rules)?i.rules.length:0,n=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?Object.keys(i.tokens).length:0,o=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Oa(i,e){let t=i.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);if(!Array.isArray(n)||n.length===0||n.length>40)return null;let o=new Set(e),r=n.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(b=>typeof b=="string"||typeof b=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let w=Array.isArray(d.decisionIds)?d.decisionIds.filter(b=>typeof b=="string"&&o.has(b)):[];return w.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:w,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===n.length?r:null}catch{return null}}function Da(i,e){let t=i.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
39
39
  Kind: ${r.kind}
40
40
  Claim: ${r.claim}
41
41
  ${r.rationale?`Rationale: ${r.rationale}`:""}
42
42
  Subjects: ${r.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
43
43
  Authority: ${r.authority.level}/${r.authority.mode}`).join(`
44
44
 
45
- `),t=o.map(r=>r.id);return`You are extracting a local design model from accumulated design decisions.
45
+ `),n=i.map(r=>r.id);return`You are extracting a local design model from accumulated design decisions.
46
46
 
47
47
  ## Instructions
48
48
  1. Review the current model (if any) and the new decisions below.
@@ -59,7 +59,7 @@ ${JSON.stringify(e,null,2)}
59
59
  Use this only to understand the existing state and avoid proposing unchanged values.`:"No model exists yet. Propose only the entries directly supported by the accepted decisions below."}
60
60
 
61
61
  ## Accepted Decisions to Project
62
- ${n}
62
+ ${t}
63
63
 
64
64
  ## Output Format
65
65
  Each change is a JSON object with:
@@ -67,7 +67,7 @@ Each change is a JSON object with:
67
67
  - \`path\`: JSON path in the derived model; the first segment must be \`tokens\`, \`components\`, or \`rules\`
68
68
  - \`label\`: short human-readable label
69
69
  - \`value\`: complete JSON value to set at that path
70
- - \`decisionIds\`: one or more IDs from ${JSON.stringify(t)} that directly support the change
70
+ - \`decisionIds\`: one or more IDs from ${JSON.stringify(n)} that directly support the change
71
71
  - \`rationale\`: concise explanation of the projection from decision to model entry
72
72
 
73
73
  For tokens and components, choose the narrowest durable path. For rules, emit a single change at path \`["rules"]\` whose value is the complete next rules array. Preserve unchanged rule IDs and order, and keep the array at 30 rules maximum.
@@ -82,7 +82,7 @@ Fields:
82
82
  - \`id\`: 8-character hex string. Preserve IDs for unchanged rules. Generate new IDs for new or merged rules.
83
83
  - \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
84
84
  - \`text\`: A clear, enforceable design rule
85
- - \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(t)}
85
+ - \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(n)}
86
86
 
87
87
  ### Rule guidelines
88
88
  - **Hard cap: 30 rules maximum.** Merge rules covering the same concern into one.
@@ -97,7 +97,7 @@ Example:
97
97
  "path": ["tokens", "colors", "primary"],
98
98
  "label": "Primary color",
99
99
  "value": "#3b82f6",
100
- "decisionIds": [${JSON.stringify(t[0]??"")}],
100
+ "decisionIds": [${JSON.stringify(n[0]??"")}],
101
101
  "rationale": "The accepted decision establishes this as the shared primary action color."
102
102
  }
103
103
  ]
@@ -114,15 +114,15 @@ Example:
114
114
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
115
115
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
116
116
  - bindings: Tailwind class names (without responsive prefixes) that use this token
117
- Include property and bindings when the decision context has class-level evidence.`}var En=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 i of this.listeners)i(e,n,t)}cancelJob(e){let n=this.queue.findIndex(i=>i.id===e);if(n>=0){let[i]=this.queue.splice(n,1);return i?(i.status="cancelled",i.error="Cancelled by user",this.broadcast({type:"error",jobId:i.id,threadId:i.threadId,message:i.error,cancelled:!0,provider:i.provider,model:i.model},i.id,i.sourceId),i):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 ga}from"child_process";import{readFile as $i}from"fs/promises";import{homedir as Mo}from"os";import{join as Xe}from"path";var Eo=/popmelt/i;function It(){return{found:!1,name:null,scope:null,disabled:!1}}function Et(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function en(o){for(let e of Object.keys(o))if(Eo.test(e))return e;return null}async function _n(o){try{let e=await $i(o,"utf-8");return JSON.parse(e)}catch{return null}}async function _o(o){let e=Mo(),n=await _n(Xe(e,".claude.json"));if(n&&typeof n=="object"){let i=n;if(i.mcpServers&&typeof i.mcpServers=="object"){let r=en(i.mcpServers);if(r)return Et(r,"user")}if(i.projects&&typeof i.projects=="object"){let s=i.projects[o];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=en(c.mcpServers);if(d){let u=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(I=>Eo.test(I));return Et(d,"project",u)}}}}}let t=await _n(Xe(o,".mcp.json"));if(t&&typeof t=="object"){let i=t;if(i.mcpServers&&typeof i.mcpServers=="object"){let s=en(i.mcpServers);if(s){let c=await _i(o,s);return Et(s,"mcp.json",c)}}let r=en(i);if(r&&r!=="mcpServers"){let s=await _i(o,r);return Et(r,"mcp.json",s)}}return It()}async function _i(o,e){let n=Xe(o,".claude","settings.local.json"),t=await _n(n);if(t&&typeof t=="object"){let i=t;if(Array.isArray(i.disabledMcpjsonServers))return i.disabledMcpjsonServers.some(r=>r===e)}return!1}var ya=/^\[mcp_servers\.([^\]]+)\]/;function va(o){let e=o.split(`
118
- `),n=[],t=null;for(let i of e){let r=i.match(ya);r?(t&&n.push({name:t.name,body:t.bodyLines.join(`
119
- `)}),t={name:r[1],bodyLines:[]}):i.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
120
- `)}),t=null):t&&t.bodyLines.push(i)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
121
- `)}),n}function Ia(o){return/enabled\s*=\s*false/i.test(o)}async function Co(o){let e=process.env.CODEX_HOME||Xe(Mo(),".codex"),n=await Ci(Xe(e,"config.toml"),"user");if(n.found)return n;let t=await Ci(Xe(o,".codex","config.toml"),"project");return t.found?t:It()}async function $o(o,e="copilot"){let n=await wa(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Xe(Mo(),".copilot"),i=await Ao(Xe(t,"mcp-config.json"),"user");if(i.found)return i;let r=await Ao(Xe(o,".mcp.json"),"mcp.json");if(r.found)return r;let s=await Ao(Xe(o,".github","mcp.json"),"mcp.json");return s.found?s:It()}async function wa(o){try{let e=await new Promise((n,t)=>{ga(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return Oi(JSON.parse(e),"user")}catch{return It()}}async function Ao(o,e){let n=await _n(o);return Oi(n,e)}function Oi(o,e){if(!o||typeof o!="object")return It();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,i=en(t);return i?Et(i,e):It()}async function Ci(o,e){try{let n=await $i(o,"utf-8"),t=va(n);for(let i of t)if(Eo.test(i.name)){let r=Ia(i.body);return Et(i.name,e,r)}}catch{}return It()}import{execFile as Di}from"child_process";import{mkdir as ba,readFile as Ni,writeFile as Bi}from"fs/promises";import{homedir as Ji}from"os";import{dirname as xa,join as Oo}from"path";var Do="https://mcp.popmelt.com/mcp";async function Li(o=Do){let e=Oo(Ji(),".claude.json"),n;try{let i=await Ni(e,"utf-8");n=JSON.parse(i)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let i of Object.keys(t))if(/popmelt/i.test(i))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await Bi(e,JSON.stringify(n,null,2)+`
122
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function qi(o=Do){let e=process.env.CODEX_HOME||Oo(Ji(),".codex"),n=Oo(e,"config.toml"),t;try{t=await Ni(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await ba(xa(n),{recursive:!0});let i=`
117
+ Include property and bindings when the decision context has class-level evidence.`}var Ln=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,t,n){for(let o of this.listeners)o(e,t,n)}cancelJob(e){let t=this.queue.findIndex(o=>o.id===e);if(t>=0){let[o]=this.queue.splice(t,1);return o?(o.status="cancelled",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),o):null}let n=this.activeJob;return!n||n.id!==e?null:(n.status="cancelled",n.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:n.error,cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},n.id),this.processNext(),n)}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(t=>{e.status!=="cancelled"&&(e.status="error",e.error=t instanceof Error?t.message:String(t),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 Na}from"child_process";import{readFile as Vo}from"fs/promises";import{homedir as Ji}from"os";import{join as Ze}from"path";var Li=/popmelt/i;function xt(){return{found:!1,name:null,scope:null,disabled:!1}}function $t(i,e,t=!1){return{found:!0,name:i,scope:e,disabled:t}}function an(i){for(let e of Object.keys(i))if(Li.test(e))return e;return null}async function qn(i){try{let e=await Vo(i,"utf-8");return JSON.parse(e)}catch{return null}}async function qi(i){let e=Ji(),t=await qn(Ze(e,".claude.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let r=an(o.mcpServers);if(r)return $t(r,"user")}if(o.projects&&typeof o.projects=="object"){let s=o.projects[i];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=an(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(w=>Li.test(w));return $t(d,"project",l)}}}}}let n=await qn(Ze(i,".mcp.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let s=an(o.mcpServers);if(s){let c=await Ho(i,s);return $t(s,"mcp.json",c)}}let r=an(o);if(r&&r!=="mcpServers"){let s=await Ho(i,r);return $t(r,"mcp.json",s)}}return xt()}async function Ho(i,e){let t=Ze(i,".claude","settings.local.json"),n=await qn(t);if(n&&typeof n=="object"){let o=n;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(r=>r===e)}return!1}var Ba=/^\[mcp_servers\.([^\]]+)\]/;function Ja(i){let e=i.split(`
118
+ `),t=[],n=null;for(let o of e){let r=o.match(Ba);r?(n&&t.push({name:n.name,body:n.bodyLines.join(`
119
+ `)}),n={name:r[1],bodyLines:[]}):o.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
120
+ `)}),n=null):n&&n.bodyLines.push(o)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
121
+ `)}),t}function La(i){return/enabled\s*=\s*false/i.test(i)}async function Fi(i){let e=process.env.CODEX_HOME||Ze(Ji(),".codex"),t=await Go(Ze(e,"config.toml"),"user");if(t.found)return t;let n=await Go(Ze(i,".codex","config.toml"),"project");return n.found?n:xt()}async function Ui(i,e="copilot"){let t=await qa(e);if(t.found)return t;let n=process.env.COPILOT_HOME||Ze(Ji(),".copilot"),o=await Bi(Ze(n,"mcp-config.json"),"user");if(o.found)return o;let r=await Bi(Ze(i,".mcp.json"),"mcp.json");if(r.found)return r;let s=await Bi(Ze(i,".github","mcp.json"),"mcp.json");return s.found?s:xt()}async function qa(i){try{let e=await new Promise((t,n)=>{Na(i,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,r)=>{if(o){n(o);return}t(r)})});return Ko(JSON.parse(e),"user")}catch{return xt()}}async function Bi(i,e){let t=await qn(i);return Ko(t,e)}function Ko(i,e){if(!i||typeof i!="object")return xt();let t=i,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,o=an(n);return o?$t(o,e):xt()}async function Go(i,e){try{let t=await Vo(i,"utf-8"),n=Ja(t);for(let o of n)if(Li.test(o.name)){let r=La(o.body);return $t(o.name,e,r)}}catch{}return xt()}import{execFile as Qo}from"child_process";import{mkdir as Fa,readFile as Xo,writeFile as Yo}from"fs/promises";import{homedir as Zo}from"os";import{dirname as Ua,join as zi}from"path";var Wi="https://mcp.popmelt.com/mcp";async function er(i=Wi){let e=zi(Zo(),".claude.json"),t;try{let o=await Xo(e,"utf-8");t=JSON.parse(o)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let o of Object.keys(n))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:i},await Yo(e,JSON.stringify(t,null,2)+`
122
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function tr(i=Wi){let e=process.env.CODEX_HOME||zi(Zo(),".codex"),t=zi(e,"config.toml"),n;try{n=await Xo(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Fa(Ua(t),{recursive:!0});let o=`
123
123
  [mcp_servers.popmelt]
124
- url = "${o}"
125
- `;return await Bi(n,t+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Fi(o=Do,e="copilot"){let n=await Sa(e);if(Ta(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,i)=>{Di(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);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 Sa(o){try{let e=await new Promise((n,t)=>{Di(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return JSON.parse(e)}catch{return null}}function Ta(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var Cn=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 i=this.leases.get(e),r={id:e,ownerPid:n,createdAt:i?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}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,i]of this.leases)i.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()}};var Pa=String.raw`
124
+ url = "${i}"
125
+ `;return await Yo(t,n+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function nr(i=Wi,e="copilot"){let t=await za(e);if(Wa(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,o)=>{Qo(e,["mcp","add","--transport","http","--json","popmelt",i],{encoding:"utf-8",timeout:1e4},r=>{if(r){o(r);return}n()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(n){return{installed:!1,provider:"copilot",scope:null,reason:n instanceof Error?n.message:"install_failed"}}}async function za(i){try{let e=await new Promise((t,n)=>{Qo(i,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,r)=>{if(o){n(o);return}t(r)})});return JSON.parse(e)}catch{return null}}function Wa(i){if(!i||typeof i!="object")return!1;let e=i,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(n=>/popmelt/i.test(n))}var Fn=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 t of this.leases.values())(e===null||t.expiresAt<e)&&(e=t.expiresAt);return e}acquire(e,t,n=Date.now()){let o=this.leases.get(e),r={id:e,ownerPid:t,createdAt:o?.createdAt??n,expiresAt:n+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,t=Date.now()){let n=this.leases.get(e);return n?(n.expiresAt=t+this.ttlMs,n):null}release(e){let t=this.leases.delete(e);return{found:t,becameEmpty:t&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let t=[];for(let[n,o]of this.leases)o.expiresAt>e||(this.leases.delete(n),t.push(n));return{expiredIds:t,becameEmpty:t.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};var Ha=String.raw`
126
126
  (() => {
127
127
  const hidden = [];
128
128
  const visit = (root) => {
@@ -143,7 +143,7 @@ url = "${o}"
143
143
  visit(document);
144
144
  window.__popmeltNativeCaptureHidden = hidden;
145
145
  })()
146
- `,Ra=String.raw`
146
+ `,Ga=String.raw`
147
147
  (() => {
148
148
  for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
149
149
  if (value) element.style.setProperty('visibility', value, priority);
@@ -151,71 +151,83 @@ url = "${o}"
151
151
  }
152
152
  delete window.__popmeltNativeCaptureHidden;
153
153
  })()
154
- `;function $n(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function ka(o,e){let n=$n(e);if(!n)return null;let t=new URL(n),i=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&$n(s.url)),r=i.find(s=>$n(s.url)===n);return r||(i.find(s=>{let c=new URL($n(s.url));return c.origin===t.origin&&c.pathname===t.pathname})??null)}function ja(o){let e={x:Number(o.x),y:Number(o.y),width:Number(o.width),height:Number(o.height)};if(!Object.values(e).every(Number.isFinite)||e.x<0||e.y<0||e.width<=0||e.height<=0||e.width>1e5||e.height>1e5)throw new Error("Invalid native screenshot clip");return e}async function Aa(o){let e=new AbortController,n=setTimeout(()=>e.abort(),1e3);try{let t=new URL("/json/list",o).href,i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`CDP discovery returned ${i.status}`);let r=await i.json();return Array.isArray(r)?r:[]}finally{clearTimeout(n)}}async function Ma(o){let{WebSocket:e}=await import("ws");return new Promise((n,t)=>{let i=new e(o,{handshakeTimeout:1e3}),r=()=>{i.off("error",s),n(i)},s=c=>{i.off("open",r),t(c)};i.once("open",r),i.once("error",s)})}function Ea(o){let e=1,n=new Map;return o.on("message",t=>{let i;try{i=JSON.parse(String(t))}catch{return}if(!i.id)return;let r=n.get(i.id);r&&(n.delete(i.id),clearTimeout(r.timeout),i.error?r.reject(new Error(i.error.message||`CDP error ${i.error.code??""}`.trim())):r.resolve(i.result??{}))}),o.on("close",()=>{for(let[t,i]of n)clearTimeout(i.timeout),i.reject(new Error("CDP connection closed")),n.delete(t)}),(t,i={})=>new Promise((r,s)=>{let c=e++,d=setTimeout(()=>{n.delete(c),s(new Error(`CDP ${t} timed out`))},4e3);n.set(c,{resolve:r,reject:s,timeout:d}),o.send(JSON.stringify({id:c,method:t,params:i}),u=>{u&&(clearTimeout(d),n.delete(c),s(u))})})}async function Ui(o,e){let n=ja(e.clip),t=await Aa(o),i=ka(t,e.pageUrl);if(!i?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await Ma(i.webSocketDebuggerUrl),s=Ea(r),c=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Pa,returnByValue:!0}),c=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...n,scale:Math.max(.25,Math.min(4,e.scale??1))}}),u=typeof d.data=="string"?d.data:"";if(!u)throw new Error("CDP returned an empty screenshot");return Buffer.from(u,"base64")}finally{c&&await s("Runtime.evaluate",{expression:Ra,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as sr,readFile as rn,writeFile as ar}from"fs/promises";import{join as Dt}from"path";var _a=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function No(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function On(o){return new Set(No(o).split(" ").filter(e=>e.length>2&&!_a.has(e)))}function zi(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Ca(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function $a(o,e){let n=new Map,t=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(No).filter(Boolean),r=On([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 Ca(s)){let u=No(d.value);for(let T of i){let k=u===T?95:u.includes(T)||T.includes(u)?75:0;k>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:k>=90?"exact":"strong",matchedBy:d.by,score:k})}let x=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(zi(On(u),r)*55);x>=30&&x>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:x>=45?"strong":"weak",matchedBy:"query_text",score:x})}c&&n.set(s.id,c)}return n}function Oa(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)),i=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!i.length)return{state:"none_found",attemptIds:[]};let r=new Set(i.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:i.map(s=>s.id)}}function Da(o){return Math.ceil(JSON.stringify(o).length/4)}function Bo(o,e){let n=o.records.filter(l=>l.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),i=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=o.records.filter(l=>{if(l.recordType!=="proposal"||i&&!i.has(l.id))return!1;if(l.state==="pending")return!0;if(l.state!=="deferred")return!1;let f=[...o.events].reverse().find(m=>m.entity.entityType==="proposal"&&m.entity.entityId===l.id&&m.toState==="deferred"&&m.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),s=o.records.filter(l=>l.recordType==="implementation_attempt"),c=$a(n,e),d=[...c.values()].sort((l,f)=>f.score-l.score),u=On([e.action,e.text].filter(Boolean).join(" ")),I=r.flatMap(l=>{let f=l.subjects.map(b=>c.get(b.subjectId)).filter(b=>!!b),m=Math.max(0,...f.map(b=>b.score)),h=Math.round(zi(On(l.claim),u)*35),j=m+h;return j>=50?[{proposal:l,proposalMatches:f,score:j}]:[]}).sort((l,f)=>f.score-l.score||l.proposal.id.localeCompare(f.proposal.id)),x=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),k=[],S=0;for(let l of I){if(k.length>=x)break;let f=l.proposal.sourceRefs.slice(0,4),m={contractVersion:1,packetId:`review:${l.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:l.proposalMatches.length?`Historical proposal intersects ${l.proposalMatches.map(j=>j.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:l.proposalMatches.map(({score:j,...b})=>b)},proposal:{id:l.proposal.id,claim:l.proposal.claim,state:l.proposal.state,proposedKind:l.proposal.proposedKind,subjectIds:l.proposal.subjects.map(j=>j.subjectId),origin:l.proposal.origin.mode},authority:"unaccepted",presentation:l.score>=100&&["constraint","rule"].includes(l.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Oa(l.proposal,s),evidence:{sourceCount:l.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:l.proposal.id},...f]},h={...m,estimatedTokens:Da(m)};if(S+h.estimatedTokens>T)break;k.push(h),S+=h.estimatedTokens}let p=Math.max(0,I.length-k.length);return{packets:k,subjectMatches:d.map(({score:l,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:I.length,omittedPacketCount:p,maxEstimatedTokens:T,estimatedTokens:S},uncertainty:c.size===0?"subject_unresolved":I.length===0?"no_relevant_pending_proposal":void 0}}var Na=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Jo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dn(o){return new Set(Jo(o).split(" ").filter(e=>e.length>2&&!Na.has(e)))}function Gi(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 Ba(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(Jo).filter(Boolean),i=Dn([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(n.has(s.id)){r.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 I=Jo(u.value);for(let k of t){let S=I===k?95:I.includes(k)||k.includes(I)?75:0;S>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:S>=90?"exact":"strong",matchedBy:u.by,score:S})}let T=["/","#","[","]","="].some(k=>u.value.includes(k))?0:Math.round(Gi(Dn(I),i)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"semantic",score:T})}c&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Ja(o){return Math.ceil(JSON.stringify(o).length/4)}function _t(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function La(o,e){let n=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(r=>r.state==="completed"),i=t.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":t.length?"partial":"unknown",attemptIds:n.map(r=>r.id)}}function qa(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)),i=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),r=t[0],s=i?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function Wi(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),i=o.records.filter(g=>g.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"),c=r?s.filter(g=>r.has(g.id)):s,d=o.records.filter(g=>g.recordType==="implementation_attempt"),u=o.records.filter(g=>g.recordType==="verification_attempt"),I=o.records.filter(g=>g.recordType==="freshness_signal"&&g.state==="open"),x=o.records.filter(g=>g.recordType==="evidence"),T=o.records.filter(g=>g.recordType==="model_entry"),k=Ba(i,e),S=new Map(k.map(g=>[g.subjectId,g.score])),p=Dn([e.action,e.text].filter(Boolean).join(" ")),l=c.flatMap(g=>{let J=Math.max(0,...g.subjects.map(N=>S.get(N.subjectId)??0)),E=Math.round(Gi(Dn(g.claim),p)*35),R=J+E;return R>=50?[{decision:g,score:R}]:[]}).sort((g,J)=>J.score-g.score||g.decision.id.localeCompare(J.decision.id)),f=new Map;for(let g of l.slice(0,t))f.set(g.decision.id,g.decision);for(let g of o.relationships){if(!_t(g,"excepts")&&!_t(g,"contradicts"))continue;let J=s.find(R=>R.id===g.from.entityId),E=s.find(R=>R.id===g.to.entityId);!J||!E||!f.has(J.id)&&!f.has(E.id)||(f.size<t&&f.set(J.id,J),f.size<t&&f.set(E.id,E))}let m=[...f.values()],h=g=>g.from.entityType==="decision"&&g.to.entityType==="decision"&&f.has(g.from.entityId)&&f.has(g.to.entityId),j=(g,J=!1)=>{let E=new Set(g.map(B=>B.id)),R=I.filter(B=>B.target.entityType==="decision"&&E.has(B.target.entityId)),N=new Set(o.relationships.filter(B=>_t(B,"excepts")&&E.has(B.from.entityId)&&E.has(B.to.entityId)).flatMap(B=>[B.from.entityId,B.to.entityId])),K=o.relationships.filter(B=>_t(B,"contradicts")&&E.has(B.from.entityId)&&E.has(B.to.entityId)).map(B=>({id:B.id,decisionIds:[B.from.entityId,B.to.entityId],unresolvedQuestion:B.reason,expansionRefs:[{kind:"record",id:B.id}]})),W=new Set(K.flatMap(B=>B.decisionIds)),Q=x.filter(B=>B.sourceRefs.some(D=>D.kind==="record"&&E.has(D.id))||o.relationships.some(D=>D.relationshipType==="supports"&&D.from.entityType==="evidence"&&D.from.entityId===B.id&&D.to.entityType==="decision"&&E.has(D.to.entityId))),w=Math.max(0,l.length-g.length),H=o.relationships.some(B=>_t(B,"contradicts")&&h(B)&&(!E.has(B.from.entityId)||!E.has(B.to.entityId))),L=J||w>0||H,O=[];k.length===0&&(e.subjectHints?.length??0)>0?O.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):g.length===0&&O.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),K.length&&O.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:K.flatMap(B=>B.expansionRefs)}),Q.some(B=>B.availability!=="available")&&O.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Q.map(B=>({kind:"record",id:B.id}))}),L&&O.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:k.map(({score:B,...D})=>D),modelEntries:T.filter(B=>B.decisionIds.some(D=>E.has(D))).map(B=>({id:B.id,key:B.key,value:B.value,decisionIds:B.decisionIds})),decisions:g.map(B=>({id:B.id,kind:B.kind,claim:B.claim,subjectIds:B.subjects.map(D=>D.subjectId),authority:B.authority,effectiveState:W.has(B.id)?"conflicted":N.has(B.id)?"excepted":"active",freshness:R.filter(D=>D.target.entityId===B.id).map(D=>D.signalType),expansionRef:{kind:"record",id:B.id}})),conflicts:K,uncertainties:O,implementation:g.map(B=>La(B.id,d)),verification:g.map(B=>qa(B.id,u,R)),evidence:Q.map(B=>({evidenceId:B.id,summary:B.summary,availability:B.availability,sourceRefs:B.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:w,omittedEvidenceCount:0,conflictsComplete:!H}};return he.budget.estimatedTokens=Ja(he),he},b=j(m);for(;b.budget.estimatedTokens>n&&m.length>0;){let g=m.pop(),J=o.relationships.filter(E=>_t(E,"contradicts")&&(E.from.entityId===g.id||E.to.entityId===g.id)).flatMap(E=>[E.from.entityId,E.to.entityId]);m=m.filter(E=>!J.includes(E.id)),b=j(m,!0)}return b}var Fa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Ct(o){return Fa.test(o)}function Ua(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function te(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function Lo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Re(o,e,n){Ct(n)||te(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&te(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(o,e,n,t=!1){t&&n.level==="contributor"&&te(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&te(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var za={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->emerging","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"])},Ga=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Wa(o,e,n){Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Re(o,`${n}.entity.entityId`,e.entity.entityId),Qe(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=za[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(i)&&te(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(Ga.has(r)&&(wt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||te(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)&&te(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&te(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Qe(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function Ha(o,e,n,t){Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Qe(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&te(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&te(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&te(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)&&te(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(wt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||te(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Lo(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())&&te(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Qe(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&te(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&te(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&te(o,`${n}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Qe(o,`${n}.concreteBindings[${r}].createdAt`,i.createdAt),Qe(o,`${n}.concreteBindings[${r}].updatedAt`,i.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&te(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Qe(o,`${n}.appliedAt`,e.appliedAt),wt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&te(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())&&te(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(i=>!i.trim()))&&te(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Lo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Lo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Va(o,e,n){if(Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Re(o,`${n}.from.entityId`,e.from.entityId),Re(o,`${n}.to.entityId`,e.to.entityId),Qe(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||te(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let i=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!i&&!r&&te(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?te(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&wt(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&te(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&te(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))&&te(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&te(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function bt(o){let e=[];Re(e,"manifest.projectId",o.manifest.projectId),Qe(e,"manifest.createdAt",o.manifest.createdAt),Qe(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,l)=>{let f=n.get(p);f?te(e,l,"duplicate_id",`ID is already used at ${f}.`):n.set(p,l)};o.records.forEach((p,l)=>{let f=`records[${l}]`;t(p.id,f),Ha(e,p,f,o.manifest.projectId)}),o.events.forEach((p,l)=>{let f=`events[${l}]`;t(p.id,f),Wa(e,p,f),p.projectId!==o.manifest.projectId&&te(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,l)=>{let f=`relationships[${l}]`;t(p.id,f),Va(e,p,f),p.projectId!==o.manifest.projectId&&te(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,l)=>{t(p.id,`artifacts[${l}]`),Re(e,`artifacts[${l}].id`,p.id)}),o.tombstones.forEach((p,l)=>{let f=`tombstones[${l}]`;t(p.id,f),Re(e,`${f}.id`,p.id),Re(e,`${f}.objectId`,p.objectId),Re(e,`${f}.deletedById`,p.deletedById),Qe(e,`${f}.deletedAt`,p.deletedAt),wt(e,`${f}.authority`,p.authority,!0)});let i=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),r=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,l)=>{let f=`${p.entityType}:${p.entityId}`;!i.has(f)&&!r.has(f)&&te(e,l,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,l)=>s(p.entity,`events[${l}].entity`)),o.relationships.forEach((p,l)=>{s(p.from,`relationships[${l}].from`),s(p.to,`relationships[${l}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,l)=>{c.has(p)||te(e,l,"dangling_artifact_reference","No artifact manifest entry exists.")},u=(p,l,f)=>{!i.has(`${p}:${l}`)&&!r.has(`${p}:${l}`)&&te(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,l)=>{let f=`records[${l}]`;switch(p.recordType){case"authority_grant":u("participant",p.granteeId,`${f}.granteeId`),u("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`));break;case"observation":p.captureContext.subjectIds.forEach((m,h)=>u("subject",m,`${f}.captureContext.subjectIds[${h}]`)),p.captureContext.artifactIds.forEach((m,h)=>d(m,`${f}.captureContext.artifactIds[${h}]`));break;case"proposal":case"decision":p.subjects.forEach((m,h)=>u("subject",m.subjectId,`${f}.subjects[${h}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((m,h)=>d(m,`${f}.messageArtifactIds[${h}]`)),p.resultRefs.forEach((m,h)=>s(m,`${f}.resultRefs[${h}]`));break;case"iteration":p.threadIds.forEach((m,h)=>u("thread",m,`${f}.threadIds[${h}]`)),p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"evidence":p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"advisory_explanation":p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`)),p.supersededById&&u("advisory_explanation",p.supersededById,`${f}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((m,h)=>u("iteration",m,`${f}.iterationIds[${h}]`)),p.coverageClaims.forEach((m,h)=>u("decision",m.decisionId,`${f}.coverageClaims[${h}].decisionId`)),p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"eval_spec":p.replacesSpecId&&u("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`)),p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),(p.dependencies??[]).forEach((m,h)=>{m.kind==="subject"&&m.subjectId&&u("subject",m.subjectId,`${f}.dependencies[${h}].subjectId`)}),(p.scenarios??[]).forEach((m,h)=>{m.subjectIds?.forEach((j,b)=>u("subject",j,`${f}.scenarios[${h}].subjectIds[${b}]`))}),p.targets.forEach((m,h)=>u(m.entityType,m.entityId,`${f}.targets[${h}]`));break;case"verification_attempt":p.evalSpecId&&u("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((m,h)=>u(m.entityType,m.entityId,`${f}.targets[${h}]`)),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`));break;case"model_entry":p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`));break;case"model_projection":wt(e,`${f}.authority`,p.authority,!0),u("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`)),p.entryIds.forEach((m,h)=>u("model_entry",m,`${f}.entryIds[${h}]`)),p.coverage.forEach((m,h)=>u("decision",m.decisionId,`${f}.coverage[${h}].decisionId`));break;case"freshness_signal":s(p.target,`${f}.target`),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`));break;default:break}});let I=new Map(o.events.map(p=>[p.id,p])),x=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),T=new Map;o.events.forEach((p,l)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,m=T.get(f)??new Set;m.add(p.toState),T.set(f,m),m.size>1&&te(e,`events[${l}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let k=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),S=(p,l,f,m,h)=>{if(p.level!=="delegate"||!p.grantId)return;let j=k.get(p.grantId);if(!j){te(e,h,"invalid_authority_grant","Delegated authority references a missing grant.");return}(j.granteeId!==l||j.level!=="delegate")&&te(e,h,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let b=Date.parse(f);(b<Date.parse(j.startsAt)||j.endsAt&&b>Date.parse(j.endsAt)||j.revokedAt&&b>=Date.parse(j.revokedAt))&&te(e,h,"inactive_authority_grant","The delegated authority grant was not active at this time."),j.subjectIds.length&&m.length&&!m.every(g=>j.subjectIds.includes(g))&&te(e,h,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&S(p.authority,p.acceptedById,p.createdAt,p.subjects.map(l=>l.subjectId),`records:${p.id}.authority`);o.events.forEach((p,l)=>{let f=x.get(`${p.entity.entityType}:${p.entity.entityId}`),m=f&&"subjects"in f?f.subjects.map(h=>h.subjectId):[];S(p.authority,p.participantId,p.createdAt,m,`events[${l}].authority`)}),o.relationships.forEach((p,l)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(m=>{let h=x.get(`${m.entityType}:${m.entityId}`);return h&&"subjects"in h?h.subjects.map(j=>j.subjectId):[]});S(p.authority,p.participantId,p.createdAt,f,`relationships[${l}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let l=I.get(p.acceptanceEventId);(!l||l.entity.entityType!=="proposal"||l.entity.entityId!==p.proposalId||l.toState!=="accepted")&&te(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),l&&l.participantId!==p.acceptedById&&te(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),x.has(`proposal:${p.proposalId}`)||te(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(m=>m.relationshipType==="supersedes"&&m.to.entityType==="decision"&&m.to.entityId===p.id)||te(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(m=>m.entity.entityType==="decision"&&m.entity.entityId===p.id&&m.toState==="revoked"&&!!m.reason?.trim())||te(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)||te(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ua(e)}function tn(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 Hi(o,e,n,t,i){return{id:i,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 Ka(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 Nn(o,e){let n=[],t=o.records.find(r=>r.recordType==="proposal"&&r.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."}),Ct(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of Ka(e))Ct(r)||n.push({code:"invalid_generated_id",message:`${r} 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 r={...tn(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Hi(o,t,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[r],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 r={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={...tn(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={...tn(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Hi(o,r,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:r.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:[r,d],events:[s,c],relationships:[u]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.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 r={...tn(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:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let i={...tn(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:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}var Vi={project:0,route:1,component:2,selector:2,file:3},Ki={intention:0,principle:1,pattern:2};function $t(o,e){let n=Vi[o.scope.kind]-Vi[e.scope.kind];return n!==0?n:Ki[o.kind]-Ki[e.kind]}function Qi(o){return o==="expresses"||o==="excepts"}function Qa(o,e){if(e.type==="expresses"||e.type==="excepts")return structuredClone(e);if(e.type==="operationalizes")return{...structuredClone(e),type:"expresses"};if(e.type==="instantiates")return{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId};if(e.type==="refines"){let n=o.explanations.find(r=>r.id===e.fromId),t=o.explanations.find(r=>r.id===e.toId);if(!n||!t)return;let i=$t(n,t);return i===0?void 0:i>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function xt(o){let e=structuredClone(o),n=new Set;return e.relations=o.relations.flatMap(t=>{let i=Qa(o,t);if(!i)return[];let r=`${i.type}:${i.fromId}:${i.toId}`;return n.has(r)?[]:(n.add(r),[i])}),e}import{createHash as Xa}from"crypto";import{readFile as Ya,readdir as Za,realpath as ec}from"fs/promises";import{join as nn,relative as tc}from"path";var nc=["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 Ot(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Ge(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Xi(...o){return o.find(e=>!!e?.trim())?.trim()}function ie(o,e,n,t){let r=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=Xa("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function qo(o,e){try{return JSON.parse(await Ya(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function oc(o){let e=Ot(o);if(!e)return 0;let n=0,t=i=>{let r=Ot(i);if(!r){n+=1;return}for(let s of Object.values(r))t(s)};for(let i of Object.values(e))t(i);return n}function ic(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function on(o){let e=[],n=await ec(o.projectRoot).catch(()=>o.projectRoot),t=nn(n,".popmelt"),i=await qo(nn(t,"threads.json"),e),r=await qo(nn(t,"model.json"),e),s=Ot(i),c=Ot(s?.threads)??{},d=Object.entries(c).map(([D,Y])=>({key:D,value:Ot(Y)})).filter(D=>!!D.value),u=nn(t,"decisions"),I=await Za(u).catch(()=>[]),x=[];for(let D of I.filter(Y=>Y.endsWith(".json")).sort()){let Y=Ot(await qo(nn(u,D),e));Y&&x.push({file:D,value:Y})}let T=d.flatMap(({value:D})=>[D.createdAt,D.updatedAt]).filter(D=>typeof D=="number"&&Number.isFinite(D)),k=T.length?Math.min(...T):0,S=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=ie(S,"project",S,k),l=ie(S,"participant","legacy-owner",k),f=ie(S,"participant","legacy-agent",k),m=ie(S,"subject","project",k),h=Ge(Math.max(k,...T)),j=[],b=[],g=new Map,J=new Map,E=new Map(x.map(D=>[D.value.id??D.file.replace(/^d-|\.json$/g,""),D.value])),R=new Map,N=(D,Y,ce,Pe,se)=>{let Ue=g.get(ce);if(Ue)return Ue;let We=ie(S,"artifact",D,Pe);return b.push({id:We,kind:Y,mediaType:se,location:ce,availability:"available"}),g.set(ce,We),We};for(let{file:D,value:Y}of x){let ce=Y.id??D.replace(/^d-|\.json$/g,""),Pe=Y.createdAt??k,se=[N(`${ce}:envelope`,"other",`.popmelt/decisions/${D}`,Pe,"application/json")];Y.screenshotPath&&se.push(N(`${ce}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,Pe,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ue,We]of(Y.pastedImagePaths??[]).entries())se.push(N(`${ce}:image:${Ue}`,"image",We,Pe));R.set(ce,se)}let V=(D,Y,ce)=>({id:D,schemaVersion:1,projectId:p,createdAt:h,participantId:Y,sourceRefs:ce}),K=(D,Y)=>{j.push(Y);let ce=J.get(D)??[];ce.push(Y.id),J.set(D,ce)},W=[{...V(l,l,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...V(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];j.push(...W),j.push({...V(m,l,[]),recordType:"subject",subjectType:"project",label:tc(process.cwd(),n)||n,aliases:[],locators:[{id:ie(S,"locator",n,k),kind:"project_root",value:n,status:"current",validFrom:Ge(k),sourceRefs:[]}]});let Q=new Map,w=(D,Y)=>{let ce=Q.get(D);if(ce)return ce;let Pe=ie(S,"subject",D,Y),se={...V(Pe,l,[{kind:"external",id:D}]),createdAt:Ge(Y),recordType:"subject",subjectType:"element",label:D,aliases:[],locators:[{id:ie(S,"locator",D,Y),kind:"dom_selector",value:D,status:"current",validFrom:Ge(Y),sourceRefs:[{kind:"external",id:D}]}]};return j.push(se),Q.set(D,Pe),Pe};for(let{key:D,value:Y}of d){let ce=Y.id??D,Pe=Y.createdAt??k,se=ie(S,"thread",ce,Pe),Ue={kind:"thread",id:ce},We=[],ke=[],st=Array.isArray(Y.messages)?Y.messages:[],He,at,Vt=0;st.forEach((be,ct)=>{let Ee=be.timestamp??Pe,et=ie(S,"artifact",`${ce}:message:${ct}`,Ee);if(We.push(et),b.push({id:et,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ce}/messages/${ct}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${ce}/messages/${ct}`,et),be.screenshotPath&&N(`${ce}:message:${ct}:screenshot`,"screenshot",be.screenshotPath,Ee),be.role==="human"){He=be;let Ne=be.feedbackSummary??be.replyToQuestion;if(Ne?.trim()){let Be=ie(S,"observation",`${ce}:${ct}`,Ee),pt=Y.elementIdentifiers??[],kt={...V(Be,l,[Ue,{kind:"message",id:et}]),createdAt:Ge(Ee),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:pt.map(gt=>w(gt,Pe)),artifactIds:[et]},resolvedByIds:[]};K(ce,kt),at=Be,ke.push({entityType:"observation",entityId:Be})}return}if(be.role!=="assistant")return;let dt=be.jobId??`${ce}:${ct}`,lt=ie(S,"iteration",dt,Ee),ft=E.get(dt),ho=be.cancelled?"cancelled":be.error?"failed":be.question?"question_asked":(be.resolutions?.length??0)>0?"completed":"no_change",go={...V(lt,f,[Ue,{kind:"message",id:et},...(R.get(dt)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:Ge(Ee),recordType:"iteration",threadIds:[se],startedAt:Ge(He?.timestamp,Ee),completedAt:Ge(Ee),requestSummary:Xi(He?.feedbackSummary,He?.replyToQuestion)??"[legacy request unavailable]",responseSummary:be.question??be.error??be.responseText?.slice(0,1e3),outcome:ho,execution:{provider:be.provider??ft?.provider,model:be.model??ft?.model,sessionId:be.sessionId??ft?.sessionId},artifactIds:[et,...R.get(dt)??[]]};K(ce,go),ke.push({entityType:"iteration",entityId:lt});let ht=be.resolutions??ft?.resolutions??[];for(let[Ne,Be]of ht.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let pt=Y.elementIdentifiers??[],kt=(pt.length?pt:[n]).map(vn=>({subjectId:vn===n?m:w(vn,Pe),role:"governed"})),gt=ie(S,"proposal",`${dt}:${Be.annotationId??"resolution"}:${Ne}`,Ee),yo={...V(gt,f,[Ue,{kind:"iteration",id:lt}]),createdAt:Ge(Ee),recordType:"proposal",state:"pending",claim:Be.summary,subjects:kt,subjectSemantics:kt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Xi(He?.feedbackSummary,He?.replyToQuestion,Be.summary),iterationId:lt,inferredById:f}};K(ce,yo),ke.push({entityType:"proposal",entityId:gt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ce,message:`Proposal ${gt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(ht.some(Ne=>Ne.status==="resolved")||ft?.gitDiff){let Ne=ie(S,"implementation",dt,Ee),Be={...V(Ne,f,[Ue,{kind:"iteration",id:lt}]),createdAt:Ge(Ee),recordType:"implementation_attempt",state:"completed",iterationIds:[lt],coverageClaims:[],summary:ht.map(pt=>pt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};K(ce,Be),ke.push({entityType:"implementation_attempt",entityId:Ne}),Vt+=1}at&&(at=void 0)});let Rt=st.at(-1),fo={...V(se,l,[Ue]),createdAt:Ge(Pe),recordType:"thread",state:Rt?.question?"open":"resolved",messageArtifactIds:We,outcome:Rt?.question?"question_unresolved":Vt?"implementation_only":"no_outcome",resultRefs:ke};j.push(fo),J.set(ce,[se,...J.get(ce)??[]])}let H=oc(r);H&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${H} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:p,createdAt:Ge(k),updatedAt:h,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:j,events:[],relationships:[],artifacts:b,tombstones:[]},O=bt(L),B=(o.proofCaseIds??nc).map(D=>({legacyId:D,threadFound:d.some(({key:Y,value:ce})=>(ce.id??Y)===D),decisionEnvelopeFound:E.has(D),recordIds:J.get(D)??[]}));return{bundle:L,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((D,Y)=>D+(Y.value.messages?.length??0),0),decisionEnvelopes:x.length,modelEntries:H,artifactsReferenced:b.length},imported:ic(j),unresolvedAcceptance:e.filter(D=>D.code==="acceptance_unresolved").length,deferredModelEntries:H,proofCases:B,issues:e,schemaIssues:O.issues}}}import{createHash as rc}from"crypto";import{mkdir as Yi,open as Fo,readFile as Uo,readdir as sc,rename as ac,unlink as zo}from"fs/promises";import{join as tt}from"path";var cc={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Jn(o){return rc("sha256").update(JSON.stringify(o)).digest("hex")}function Zi(o){return Jn(o)}function er(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 i=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(i<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let r=o.records[i];if(r.projectId!==t.projectId||r.createdAt!==t.createdAt||r.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[i]=structuredClone(t)}for(let t of e.projectionUpdates){let i=o.records.find(r=>r.recordType===t.entityType&&r.id===t.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(i.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${i.state}`);i.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 dc(o,e,n){return er(structuredClone(o),e,n)}async function St(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Fo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
155
- `,"utf8"),await t.sync()}finally{await t.close()}try{await ac(n,o)}catch(i){throw await zo(n).catch(()=>{}),i}}async function Bn(o){return JSON.parse(await Uo(o,"utf8"))}var Ln=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=tt(e,".popmelt","memory"),this.journalDir=tt(this.memoryDir,"journal"),this.manifestPath=tt(this.memoryDir,"manifest.json"),this.checkpointPath=tt(this.memoryDir,"checkpoint.json"),this.lockPath=tt(this.memoryDir,"writer.lock")}async initialize(e){let n=bt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Yi(this.journalDir,{recursive:!0});try{throw await Uo(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 Uo(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=Jn(e),i={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await St(this.checkpointPath,i),await St(this.manifestPath,r)})}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 St(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=Jn(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await St(tt(this.memoryDir,t),i),e.manifest.checkpoint={file:t,sequence:i.sequence,hash:n},await St(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.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(!Ct(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 i=t.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...r,hash:Zi(r)},c=dc(t.bundle,e,n.committedAt),d=bt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let u=`${String(i).padStart(12,"0")}-${n.transactionId}.json`;return await St(tt(this.journalDir,u),s),t.manifest.head={sequence:i,hash:s.hash},t.manifest.updatedAt=n.committedAt,await St(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...cc,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Bn(this.manifestPath),n=await Bn(tt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==Jn(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await sc(this.journalDir),i=t.filter(T=>T.endsWith(".tmp")),s=t.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,u=n.journalHash??null,I=new Set;for(let T of s){let k=await Bn(tt(this.journalDir,T)),{hash:S,...p}=k;if(S!==Zi(p))throw new Error(`Journal hash mismatch: ${T}`);if(k.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(k.previousHash!==u)throw new Error(`Journal chain mismatch at ${T}`);if(k.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(I.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);er(c,k.mutation,k.committedAt),d=k.sequence,u=k.hash,I.add(k.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 x=bt(c);if(!x.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(x.issues)}`);return{bundle:c,manifest:e,transactionIds:I,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:d,headHash:u}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Yi(this.memoryDir,{recursive:!0});let n;try{n=await Fo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let i=await Bn(this.lockPath).catch(()=>({})),r=!0;if(typeof i.pid=="number")try{process.kill(i.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await zo(this.lockPath),n=await Fo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await zo(this.lockPath).catch(()=>{})}}};import{randomBytes as lc}from"crypto";function Ie(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=lc(10).toString("hex"),i=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${i}${t.slice(4,7)}-${t.slice(7,19)}`}var pc=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function tr(o,e){let n=o.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),t=o.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let i=o.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=pc(),u=d.records,I=o.records.find(h=>h.recordType==="thread"&&h.sourceRefs.some(j=>j.kind==="thread"&&j.id===e.threadId));I||(I={id:ie(i,"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(h=>h.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},u.push(I));let x=[];for(let h of[...new Set(e.subjectHints.filter(Boolean))]){let j=o.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.value===h&&g.status==="current"));j||(j={id:ie(i,"live-subject",h,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"element",label:h,aliases:[],locators:[{id:ie(i,"live-locator",h,e.createdAt),kind:"dom_selector",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},u.push(j)),x.push(j)}for(let h of[...new Set((e.filePaths??[]).filter(Boolean))]){let j=o.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.kind==="source_file"&&g.value===h&&g.status==="current"));j||(j={id:ie(i,"live-file-subject",h,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"file",label:h,aliases:[],locators:[{id:ie(i,"live-file-locator",h,e.createdAt),kind:"source_file",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},u.push(j)),x.push(j)}let T=(e.semanticCandidates??[]).filter(h=>h.claim.trim()),k;if(T.length>0){k=ie(i,"live-observation",r,e.createdAt);let h={id:k,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(j=>j.claim.trim()).join(" "),captureContext:{subjectIds:x.map(j=>j.id),artifactIds:[]},resolvedByIds:[]};u.push(h)}let S=ie(i,"live-iteration",r,e.completedAt),p={id:S,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:imprint-evidence"})),...k?[{kind:"record",id:k}]:[]],recordType:"iteration",threadIds:[I.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};u.push(p);let l=[],f=e.resolutions.filter(h=>h.status==="resolved"&&h.summary.trim()),m=x.length>0?x:o.records.filter(h=>h.recordType==="subject"&&h.subjectType==="project").slice(0,1);if(T.length>0&&m.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[h,j]of T.entries()){let b=ie(i,"live-proposal",`${r}:${h}`,e.completedAt),g=m.map(E=>({subjectId:E.id,role:"governed"})),J={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:S},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:j.claim.trim(),rationale:j.rationale?.trim()||void 0,proposedKind:j.proposedKind,subjects:g,subjectSemantics:g.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:j.sourceText?.trim()||e.requestSummary,iterationId:S,inferredById:t.id}};u.push(J),l.push(b)}if(f.length>0){let h=new Set(e.governingDecisionIds??[]),j=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"&&h.has(g.id)),b={id:ie(i,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:S}],recordType:"implementation_attempt",state:"completed",iterationIds:[S],coverageClaims:j.map(g=>({decisionId:g.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(J=>J.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:S}]})),summary:f.map(g=>g.summary).join(" "),artifactIds:[]};u.push(b)}return{mutation:d,iterationId:S,proposalIds:l,observationId:k}}import{createHash as uc}from"crypto";import{mkdir as mc,open as fc,readFile as hc,rename as gc,unlink as yc}from"fs/promises";import{join as nr}from"path";function or(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ir(o){return uc("sha256").update(JSON.stringify(o)).digest("hex")}async function vc(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await fc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
156
- `,"utf8"),await t.sync()}finally{await t.close()}try{await gc(n,o)}catch(i){throw await yc(n).catch(()=>{}),i}}function Ic(o,e,n=new Date().toISOString()){let t={},i={},r={},s=(d,u,I)=>{let x=d[u]??=[];x.includes(I)||x.push(I)};for(let d of o.records)if(d.recordType==="subject"){let u=d;for(let I of[u.label,...u.aliases,...u.locators.filter(x=>x.status==="current").map(x=>x.value)]){let x=or(I);x&&s(t,x,u.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let u of d.subjects)s(i,u.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let u of d.subjects)s(r,u.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...c,checksum:ir(c)}}function rr(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 qn=class{constructor(e){this.indexDir=nr(e,".popmelt","memory","indexes"),this.indexPath=nr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let i=JSON.parse(await hc(this.indexPath,"utf8")),{checksum:r,...s}=i;if(i.version===1&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===n.sequence&&i.journalHead.hash===n.hash&&r===ir(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let t=Ic(e,n);return await mc(this.indexDir,{recursive:!0}),await vc(this.indexPath,t),t}};var sn="popmelt:imprint",cr="popmelt:imprint-evidence",Nt="popmelt:imprint-relation";function Fn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===sn)?.id}function Go(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 Un(o,e){if(!o)return[];let n=new Set(o.relations.flatMap(t=>t.type==="expresses"&&t.toId===e?[t.fromId]:[]));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}))}function Wo(o){if(o==="expresses")return"operationalizes";if(o==="excepts")return"excepts"}var zn=class{constructor(e){this.projectRoot=e;this.store=new Ln(e),this.indexStore=new qn(e),this.manifestPath=Dt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await rn(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 i=await this.store.load();return i.report.recoveredTransactions>0&&(i=await this.store.recover()),await this.refreshIndex(i),await this.status()}let t=await on({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(i=>i.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(i){if(!(i instanceof Error)||!i.message.includes("already initialized"))throw i}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 on({...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=Dt(this.projectRoot,".popmelt","memory","migrations"),n=Dt(e,"imprint-advisories-v2.json");try{let h=JSON.parse(await rn(n,"utf8"));return{migrated:!1,explanations:h.explanations??0,evidence:h.evidence??0}}catch{}let t;try{t=xt(JSON.parse(await rn(Dt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!t?.explanations)return await sr(e,{recursive:!0}),await ar(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let i=await this.store.load(),r=i.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),c=i.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active")??r,d=i.bundle.records.find(h=>h.recordType==="subject"&&h.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let u=i.bundle.manifest.projectId,I=new Set(i.bundle.records.map(h=>h.id)),x=new Set(i.bundle.relationships.flatMap(h=>h.sourceRefs.flatMap(j=>j.kind==="external"&&j.uri===Nt?[j.id]:[]))),T=new Map,k=i.bundle.records.filter(h=>h.recordType==="advisory_explanation");for(let h of t.explanations){let j=k.find(b=>Fn(b)===h.id);T.set(h.id,j?.id??ie(u,"imprint-explanation",h.id,Date.parse(h.createdAt)))}let S=[],p=[],l=[],f=0;for(let h of t.explanations){let j=T.get(h.id),b=k.find(R=>R.id===j),g=[],J=h.evidence.length?h.evidence:[{id:`fallback:${h.id}`,kind:"observation",stance:"supports",summary:h.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:h.createdAt}];for(let R of J){let N=ie(u,"imprint-evidence-record",R.id,Date.parse(R.createdAt));g.push(N),!I.has(N)&&(S.push({id:N,schemaVersion:1,projectId:u,createdAt:R.createdAt,participantId:c.id,sourceRefs:Go([{kind:"external",id:R.id,uri:cr},{kind:"external",id:h.id,uri:sn},{kind:"thread",id:R.threadId},{kind:"message",id:R.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(R.kind)?"user_feedback":"judgment",summary:R.summary,availability:"available",artifactIds:[]}),l.push({id:ie(u,"imprint-evidence-link",`${h.id}:${R.id}`,Date.parse(R.createdAt)),schemaVersion:1,projectId:u,createdAt:R.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:R.id,uri:cr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"evidence",entityId:N},reason:"This advisory explanation was derived from collaboration evidence."}),f+=1)}let E={id:j,schemaVersion:1,projectId:u,createdAt:b?.createdAt??h.createdAt,participantId:b?.participantId??c.id,sourceRefs:Go([...b?.sourceRefs??[],{kind:"external",id:h.id,uri:sn}]),recordType:"advisory_explanation",kind:h.kind,state:h.state,statement:h.statement,rationale:h.rationale,scope:structuredClone(h.scope),subjectIds:[d.id],evidenceIds:[...new Set([...b?.evidenceIds??[],...g])],concreteBindings:Un(t,h.id),supersededById:h.supersededBy?T.get(h.supersededBy):void 0,updatedAt:h.updatedAt};b?p.push(E):S.push(E)}for(let h of t.relations){let j=Wo(h.type);if(!j)continue;let b=T.get(h.fromId),g=T.get(h.toId);!b||!g||x.has(h.id)||l.push({id:ie(u,"imprint-relation",h.id,Date.parse(h.createdAt)),schemaVersion:1,projectId:u,createdAt:h.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:h.id,uri:Nt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:b},to:{entityType:"advisory_explanation",entityId:g},reason:h.rationale||"The Imprint graph connected these explanations."})}let m=new Date().toISOString();if(S.length||p.length||l.length)try{let h=await this.store.commit({records:S,recordReplacements:p,events:[],relationships:l,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ie(u,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:m});await this.refreshIndex(h)}catch(h){if(!(h instanceof Error)||!h.message.includes("Transaction already exists"))throw h}return await sr(e,{recursive:!0}),await ar(n,JSON.stringify({version:2,migratedAt:m,explanations:t.explanations.length,evidence:f,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:f}}async review(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Bo(t.bundle,i)}}async contextualize(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Wi(t.bundle,i),reviewSelection:Bo(t.bundle,i)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Nn(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 on({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(),i=Nn(t.bundle,e);if(!i.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(i.errors)}`);let r=await this.store.commitReviewPlan(i.plan,n);return await this.refreshIndex(r),r}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(T=>T.recordType==="proposal"&&T.id===e.proposalId),i=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!t||t.state!=="pending"||!i)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 r=Date.now(),s=new Date(r).toISOString(),c={proposalId:t.id,participantId:i.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:Ie(r),decisionId:Ie(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:Ie(r),replacementProposalId:Ie(r),acceptanceEventId:Ie(r),decisionId:Ie(r),relationshipId:Ie(r),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:Ie(r),reason:e.reason}:{...c,action:"defer",eventId:Ie(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},u=Nn(n.bundle,d);if(!u.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:u.errors.map(T=>T.message).join(" ")};let I=await this.store.commitReviewPlan(u.plan,{transactionId:Ie(r),committedAt:s});await this.refreshIndex(I);let x=u.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:x,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:I.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=tr(n.bundle,e),i=ie(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(t.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=xt(JSON.parse(await rn(Dt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let t=await this.store.load(),i=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),r=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active"),s=e.action?i:r??i,c=t.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),u=Date.parse(d),I=t.bundle.manifest.projectId,x=[],T=[],k=[],S=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),p=new Map(S.flatMap(m=>{let h=Fn(m);return h?[[h,m.id]]:[]}));for(let m of e.summary.changes)if(!p.has(m.explanationId)){let h=n?.explanations.find(j=>j.id===m.explanationId);p.set(m.explanationId,ie(I,"imprint-explanation",m.explanationId,Date.parse(h?.createdAt??d)))}for(let m of e.summary.changes){let h={kind:"external",id:m.explanationId,uri:sn},j=p.get(m.explanationId),b=S.find(R=>R.id===j),g=n?.explanations.find(R=>R.id===m.explanationId),J={id:ie(I,"imprint-live-evidence",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:I,createdAt:d,participantId:s.id,sourceRefs:[h,{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:[]};x.push(J);let E={id:j,schemaVersion:1,projectId:I,createdAt:b?.createdAt??g?.createdAt??d,participantId:b?.participantId??s.id,sourceRefs:Go([...b?.sourceRefs??[],h,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??b?.kind??"pattern",state:g?.state??m.state,statement:g?.statement??m.statement,rationale:g?.rationale??b?.rationale??e.summary.detail,scope:structuredClone(g?.scope??b?.scope??{kind:"project",values:[]}),subjectIds:b?.subjectIds??[c.id],evidenceIds:[...new Set([...b?.evidenceIds??[],J.id])],concreteBindings:g?Un(n,m.explanationId):b?.concreteBindings??[],supersededById:g?.supersededBy?p.get(g.supersededBy):b?.supersededById,updatedAt:g?.updatedAt??d};b?T.push(E):x.push(E),k.push({id:ie(I,"imprint-live-evidence-link",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:I,createdAt:d,participantId:s.id,sourceRefs:[h],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:E.id},to:{entityType:"evidence",entityId:J.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let l=new Set(t.bundle.relationships.flatMap(m=>m.sourceRefs.flatMap(h=>h.kind==="external"&&h.uri===Nt?[h.id]:[])));for(let m of n?.relations??[]){let h=Wo(m.type);if(!h)continue;let j=p.get(m.fromId),b=p.get(m.toId);!j||!b||l.has(m.id)||k.push({id:ie(I,"imprint-relation",m.id,Date.parse(m.createdAt)),schemaVersion:1,projectId:I,createdAt:m.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:m.id,uri:Nt}],recordType:"relationship",relationshipType:h,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:b},reason:m.rationale||"The Imprint graph connected these explanations."})}let f=ie(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,u);try{let m=await this.store.commit({records:x,recordReplacements:T,events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:f,committedAt:d});await this.refreshIndex(m)}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=xt(JSON.parse(await rn(Dt(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"),r=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??t;if(!r)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 J=Fn(g);return J?[[J,g]]:[]})),I=new Map([...[...u].map(([g,J])=>[g,J.id]),...e.explanations.filter(g=>!u.has(g.id)).map(g=>[g.id,ie(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),x=[],T=[],k=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let J=u.get(g.id);if(!J){x.push({id:I.get(g.id),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:sn}],recordType:"advisory_explanation",kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Un(e,g.id),supersededById:g.supersededBy?I.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let E={...structuredClone(J),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:Un(e,g.id),supersededById:g.supersededBy?I.get(g.supersededBy):void 0,updatedAt:g.updatedAt},R=N=>JSON.stringify({kind:N.kind,state:N.state,statement:N.statement,rationale:N.rationale,scope:N.scope,concreteBindings:N.concreteBindings,supersededById:N.supersededById,updatedAt:N.updatedAt});R(J)!==R(E)&&T.push(E)}for(let[g,J]of u)k.has(g)||J.state==="retired"||T.push({...structuredClone(J),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let S=new Set(n.bundle.tombstones.flatMap(g=>g.objectType==="relationship"?[g.objectId]:[])),p=new Map(n.bundle.relationships.flatMap(g=>{if(S.has(g.id))return[];let J=g.sourceRefs.find(E=>E.kind==="external"&&E.uri===Nt)?.id;return J?[[J,g]]:[]})),l=[],f=new Set;for(let g of e.relations){let J=Wo(g.type);if(!J)continue;let E=I.get(g.fromId),R=I.get(g.toId);if(!E||!R)continue;let N=p.get(g.id);N&&N.relationshipType===J&&N.from.entityType==="advisory_explanation"&&N.from.entityId===E&&N.to.entityType==="advisory_explanation"&&N.to.entityId===R||(N&&f.add(g.id),l.push({id:ie(c,"imprint-relation",`${g.id}:${J}:${E}:${R}`,Date.parse(g.createdAt)),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:Nt}],recordType:"relationship",relationshipType:J,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:R},reason:g.rationale||"The Imprint graph connected these explanations."}))}let m=new Set(e.relations.map(g=>g.id)),h=t?[...p].filter(([g])=>!m.has(g)||f.has(g)).map(([,g])=>({id:ie(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(!x.length&&!T.length&&!l.length&&!h.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let j=e.updatedAt,b=ie(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(j));try{let g=await this.store.commit({records:x,recordReplacements:T,events:[],relationships:l,artifacts:[],tombstones:h,projectionUpdates:[]},{transactionId:b,committedAt:j});return await this.refreshIndex(g),{status:"synced",relationships:l.length+h.length,explanations:x.length+T.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 i of n.bundle.records)t[i.recordType]=(t[i.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:n.bundle.records.filter(i=>i.recordType==="evidence"&&i.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):[])),i=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=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)&&!i.has(s.id)&&!r.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(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),t=new Map;for(let i of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))i.decisionIds.some(r=>n.has(r))&&t.set(i.key,i);return[...t.values()]}async getImprintView(e=[],n){let t=()=>({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 t();let i=await this.store.load(),r=i.bundle.records.filter(l=>l.recordType==="advisory_explanation"),s=new Map(r.map(l=>[l.id,l])),c=new Map(r.flatMap(l=>{let f=Fn(l);return f?[[f,l.id]]:[]})),d=new Set(e.map(l=>c.get(l)??l)),u=new Map(i.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),I=new Map(i.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),x=new Set(i.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),T=new Set(["operationalizes","excepts"]),k={testing:0,emerging:1,grounded:2,challenged:3,retired:4},S=r.map(l=>{let f=l.evidenceIds.flatMap(b=>{let g=I.get(b);if(!g)return[];let J=g.sourceRefs.find(V=>V.kind==="thread")?.id,E=g.sourceRefs.find(V=>V.kind==="message")?.id,R=g.kind==="judgment"||g.kind==="user_feedback"||g.kind==="project_state"?g.kind:"other",N=u.get(g.participantId)??"unknown";return[{id:g.id,kind:R,summary:g.summary,createdAt:g.createdAt,participantKind:N,threadId:J,jobId:E}]}).sort((b,g)=>g.createdAt.localeCompare(b.createdAt)),m=i.bundle.relationships.flatMap(b=>{if(x.has(b.id))return[];if(!T.has(b.relationshipType))return[];let g=b.from.entityType==="advisory_explanation"&&b.from.entityId===l.id&&b.to.entityType==="advisory_explanation",J=b.to.entityType==="advisory_explanation"&&b.to.entityId===l.id&&b.from.entityType==="advisory_explanation";if(!g&&!J)return[];let E=g?b.to.entityId:b.from.entityId,R=s.get(E);return R?[{id:b.id,type:b.relationshipType==="operationalizes"?"expresses":"excepts",direction:g?"outgoing":"incoming",explanationId:R.id,statement:R.statement,rationale:b.reason}]:[]}),h=[...(l.supersededById?[l.supersededById]:[]).flatMap(b=>{let g=s.get(b);return g?[{id:`supersedes:${l.id}:${g.id}`,type:"supersedes",direction:"incoming",explanationId:g.id,statement:g.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(b=>b.supersededById===l.id?[{id:`supersedes:${b.id}:${l.id}`,type:"supersedes",direction:"outgoing",explanationId:b.id,statement:b.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],j=[...new Set([...l.sourceRefs.flatMap(b=>b.kind==="thread"?[b.id]:[]),...f.flatMap(b=>b.threadId?[b.threadId]:[])])].filter(b=>!n||n.has(b));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:f.length,recentEvidence:f.slice(0,4),concrete:l.concreteBindings.map(b=>({...structuredClone(b)})),relations:[...m,...h],sourceThreadIds:j,needsGrounding:l.state==="testing"&&d.has(l.id)}}).sort((l,f)=>Number(f.needsGrounding)-Number(l.needsGrounding)||k[l.state]-k[f.state]||f.updatedAt.localeCompare(l.updatedAt)),p={total:S.filter(l=>l.state!=="retired").length,emerging:S.filter(l=>l.state==="emerging").length,testing:S.filter(l=>l.state==="testing").length,grounded:S.filter(l=>l.state==="grounded").length,challenged:S.filter(l=>l.state==="challenged").length,retired:S.filter(l=>l.state==="retired").length,needsGrounding:S.filter(l=>l.needsGrounding).length};return{head:{sequence:i.report.headSequence,updatedAt:i.bundle.manifest.updatedAt},counts:p,explanations:S}}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 i=[...t.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(u=>u.targets.some(I=>I.entityType==="decision"&&I.entityId===c.id)).sort((u,I)=>I.createdAt.localeCompare(u.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:i.some(u=>u.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:i.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(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),i=n.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!t||!i)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=Ie(r),d=Ie(r),u=Ie(r),I=Ie(r),x=Ie(r),T=new Set(n.bundle.records.flatMap(R=>R.recordType==="model_entry"&&R.key===e.key?R.decisionIds:[])),k=n.bundle.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&T.has(R.id)),S={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:i.id,role:"governed"}],l={...S,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...S,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."},m={...S,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:p,noChange:!1,effectiveAt:s},h={...S,id:I,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[u],value:e.value},j={...S,id:x,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[u],entryIds:[I],coverage:[{decisionId:u,status:"projected"}]},b={...S,id:Ie(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:I},to:{entityType:"decision",entityId:u},reason:"The model change is projected from the owner-confirmed decision."},g=k.map(R=>({...S,id:Ie(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:R.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),J=k.map(R=>({...S,id:Ie(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:m.id},to:{entityType:"decision",entityId:R.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),E=await this.store.commit({records:[l,m,h,j],events:[f,...g],relationships:[b,...J],artifacts:[],tombstones:[],projectionUpdates:k.map(R=>({entityType:"decision",entityId:R.id,fromState:"active",state:"superseded"}))},{transactionId:Ie(r),committedAt:s});return await this.refreshIndex(E),{decisionId:u,entryId:I}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.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(S=>S.recordType==="model_projection"&&S.state==="applied"&&S.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let i=n.bundle.records.filter(S=>S.recordType==="decision"&&e.decisionIds.includes(S.id)&&S.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=n.bundle.records.find(S=>S.recordType==="participant"&&S.kind==="human"&&S.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=Ie(s),u=e.changes.map(S=>{let p=S.decisionIds?.filter(m=>e.decisionIds.includes(m)),l=p?.length?p:e.decisionIds,f=[...new Set(i.filter(m=>l.includes(m.id)).flatMap(m=>m.subjects.map(h=>h.subjectId)))];return{id:Ie(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:l.map(m=>({kind:"record",id:m})),recordType:"model_entry",key:S.path.map(String).join("."),subjectIds:f,decisionIds:l,value:S.value}}),I=new Set(u.flatMap(S=>S.decisionIds)),x={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(S=>({kind:"record",id:S})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:u.map(S=>S.id),coverage:e.decisionIds.map(S=>e.coverage?.find(p=>p.decisionId===S)??{decisionId:S,status:I.has(S)?"projected":"unprojected"})},T=u.flatMap(S=>S.decisionIds.map(p=>({id:Ie(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:x.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:S.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),k=await this.store.commit({records:[...u,x],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:Ie(s),committedAt:c});return await this.refreshIndex(k),{projectionId:d,entryIds:u.map(S=>S.id),headSequence:k.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 on({...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}),i=rr(t,n.subjectHints??[]);return i?{...n,subjectIds:[...new Set([...n.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.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 Jt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Te(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Bt(o,e,n){let t=Te(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Ho(o){let e=Jt(o),n=Jt(e.authority),t=n.level,i=n.mode,r=Bt(t,"authority.level",["owner","delegate","contributor"]),s=Bt(i,"authority.mode",["local_trusted","hosted"]),c={proposalId:Te(e.proposalId,"proposalId"),participantId:Te(e.participantId,"participantId"),occurredAt:Te(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Te(e.eventId,"eventId"),decisionId:Te(e.decisionId,"decisionId"),kind:Bt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Te(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Te(e.eventId,"eventId"),reason:Te(e.reason,"reason")};case"defer":{let d=Jt(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:Te(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=>Te(u,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(u=>Bt(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:Te(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Te(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Te(e.acceptanceEventId,"acceptanceEventId"),decisionId:Te(e.decisionId,"decisionId"),relationshipId:Te(e.relationshipId,"relationshipId"),claim:Te(e.claim,"claim"),kind:Bt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let u=Jt(d);return{subjectId:Te(u.subjectId,"subjectId"),role:Bt(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:Te(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Vo(o){let e=Jt(o),n=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>Te(c,s))}},t=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},i=e.resurface===void 0?void 0:Jt(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:i?{differentAction:i.differentAction===!0,newEvidence:i.newEvidence===!0,newConflict:i.newConflict===!0,ownerRequested:i.ownerRequested===!0}:void 0}}function Lt(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
157
- `)}async function dr(o,e,n,t){let i=Lt(e);if(!(!i&&n.length===0))try{let r=await o.contextualize({action:i||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(r.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.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:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){t?.(r);return}}function lr(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,i)=>["",`${i+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,i)=>["",`${i+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(`
158
- `)}function pr(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,i=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!i||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&r.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:i,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 ur(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 Ko(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],i=await wc(o),r=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,u,I,x,T,k,S,p,l,f,m,h,j,b=[],g=[],J=0,E=[];for(;J<i.length;){let R=i.indexOf(r,J);if(R===-1)break;let N=R+r.length;if(i.slice(R,R+s.length).equals(s))break;let V=N;i[V]===13&&i[V+1]===10&&(V+=2);let K=i.indexOf(`\r
154
+ `;function Un(i){try{let e=new URL(i);return e.hash="",e.href}catch{return null}}function Va(i,e){let t=Un(e);if(!t)return null;let n=new URL(t),o=i.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&Un(s.url)),r=o.find(s=>Un(s.url)===t);return r||(o.find(s=>{let c=new URL(Un(s.url));return c.origin===n.origin&&c.pathname===n.pathname})??null)}function Ka(i){let e={x:Number(i.x),y:Number(i.y),width:Number(i.width),height:Number(i.height)};if(!Object.values(e).every(Number.isFinite)||e.x<0||e.y<0||e.width<=0||e.height<=0||e.width>1e5||e.height>1e5)throw new Error("Invalid native screenshot clip");return e}async function Qa(i){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",i).href,o=await fetch(n,{signal:e.signal});if(!o.ok)throw new Error(`CDP discovery returned ${o.status}`);let r=await o.json();return Array.isArray(r)?r:[]}finally{clearTimeout(t)}}async function Xa(i){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let o=new e(i,{handshakeTimeout:1e3}),r=()=>{o.off("error",s),t(o)},s=c=>{o.off("open",r),n(c)};o.once("open",r),o.once("error",s)})}function Ya(i){let e=1,t=new Map;return i.on("message",n=>{let o;try{o=JSON.parse(String(n))}catch{return}if(!o.id)return;let r=t.get(o.id);r&&(t.delete(o.id),clearTimeout(r.timeout),o.error?r.reject(new Error(o.error.message||`CDP error ${o.error.code??""}`.trim())):r.resolve(o.result??{}))}),i.on("close",()=>{for(let[n,o]of t)clearTimeout(o.timeout),o.reject(new Error("CDP connection closed")),t.delete(n)}),(n,o={})=>new Promise((r,s)=>{let c=e++,d=setTimeout(()=>{t.delete(c),s(new Error(`CDP ${n} timed out`))},4e3);t.set(c,{resolve:r,reject:s,timeout:d}),i.send(JSON.stringify({id:c,method:n,params:o}),l=>{l&&(clearTimeout(d),t.delete(c),s(l))})})}async function ir(i,e){let t=Ka(e.clip),n=await Qa(i),o=Va(n,e.pageUrl);if(!o?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await Xa(o.webSocketDebuggerUrl),s=Ya(r),c=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Ha,returnByValue:!0}),c=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),l=typeof d.data=="string"?d.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{c&&await s("Runtime.evaluate",{expression:Ga,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as wr,readFile as pn,writeFile as br}from"fs/promises";import{join as Jt}from"path";var Za=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Hi(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function zn(i){return new Set(Hi(i).split(" ").filter(e=>e.length>2&&!Za.has(e)))}function or(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function ec(i){return[{value:i.label,by:"label"},...i.aliases.map(e=>({value:e,by:"alias"})),...i.locators.map(e=>({value:e.value,by:"locator"}))]}function tc(i,e){let t=new Map,n=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(Hi).filter(Boolean),r=zn([e.action,e.text].filter(Boolean).join(" "));for(let s of i){if(n.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of ec(s)){let l=Hi(d.value);for(let P of o){let R=l===P?95:l.includes(P)||P.includes(l)?75:0;R>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:R>=90?"exact":"strong",matchedBy:d.by,score:R})}let b=["/","#","[","]","="].some(P=>d.value.includes(P))?0:Math.round(or(zn(l),r)*55);b>=30&&b>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:b>=45?"strong":"weak",matchedBy:"query_text",score:b})}c&&t.set(s.id,c)}return t}function nc(i,e){let t=new Set(i.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(i.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),o=e.filter(s=>s.iterationIds.some(c=>t.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&n.has(c.id)));if(!o.length)return{state:"none_found",attemptIds:[]};let r=new Set(o.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:o.map(s=>s.id)}}function ic(i){return Math.ceil(JSON.stringify(i).length/4)}function Gi(i,e){let t=i.records.filter(p=>p.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),o=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=i.records.filter(p=>{if(p.recordType!=="proposal"||o&&!o.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let y=[...i.events].reverse().find(m=>m.entity.entityType==="proposal"&&m.entity.entityId===p.id&&m.toState==="deferred"&&m.transitionContext?.kind==="proposal_deferral")?.transitionContext;return y?y.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||y.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||y.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||y.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||y.resurfaceWhen.includes("after_date")&&!!(y.revisitAfter&&Date.parse(n)>=Date.parse(y.revisitAfter)):!1}),s=i.records.filter(p=>p.recordType==="implementation_attempt"),c=tc(t,e),d=[...c.values()].sort((p,y)=>y.score-p.score),l=zn([e.action,e.text].filter(Boolean).join(" ")),w=r.flatMap(p=>{let y=p.subjects.map(g=>c.get(g.subjectId)).filter(g=>!!g),m=Math.max(0,...y.map(g=>g.score)),h=Math.round(or(zn(p.claim),l)*35),M=m+h;return M>=50?[{proposal:p,proposalMatches:y,score:M}]:[]}).sort((p,y)=>y.score-p.score||p.proposal.id.localeCompare(y.proposal.id)),b=Math.max(1,e.maxPackets??3),P=Math.max(200,e.maxEstimatedTokens??1200),R=[],S=0;for(let p of w){if(R.length>=b)break;let y=p.proposal.sourceRefs.slice(0,4),m={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:i.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:p.proposalMatches.length?`Historical proposal intersects ${p.proposalMatches.map(M=>M.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:p.proposalMatches.map(({score:M,...g})=>g)},proposal:{id:p.proposal.id,claim:p.proposal.claim,state:p.proposal.state,proposedKind:p.proposal.proposedKind,subjectIds:p.proposal.subjects.map(M=>M.subjectId),origin:p.proposal.origin.mode},authority:"unaccepted",presentation:p.score>=100&&["constraint","rule"].includes(p.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:nc(p.proposal,s),evidence:{sourceCount:p.proposal.sourceRefs.length,sourceRefs:y},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:p.proposal.id},...y]},h={...m,estimatedTokens:ic(m)};if(S+h.estimatedTokens>P)break;R.push(h),S+=h.estimatedTokens}let f=Math.max(0,w.length-R.length);return{packets:R,subjectMatches:d.map(({score:p,...y})=>y),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:f,maxEstimatedTokens:P,estimatedTokens:S},uncertainty:c.size===0?"subject_unresolved":w.length===0?"no_relevant_pending_proposal":void 0}}var oc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Vi(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Wn(i){return new Set(Vi(i).split(" ").filter(e=>e.length>2&&!oc.has(e)))}function rr(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function rc(i,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Vi).filter(Boolean),o=Wn([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of i){if(t.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let w=Vi(l.value);for(let R of n){let S=w===R?95:w.includes(R)||R.includes(w)?75:0;S>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:S>=90?"exact":"strong",matchedBy:l.by,score:S})}let P=["/","#","[","]","="].some(R=>l.value.includes(R))?0:Math.round(rr(Wn(w),o)*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&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function sc(i){return Math.ceil(JSON.stringify(i).length/4)}function Ot(i,e){return i.relationshipType===e&&i.from.entityType==="decision"&&i.to.entityType==="decision"}function ac(i,e){let t=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===i));if(!t.length)return{decisionId:i,state:"unimplemented",attemptIds:[]};let n=t.filter(r=>r.state==="completed"),o=n.some(r=>r.coverageClaims.some(s=>s.decisionId===i&&s.coverage==="full"));return{decisionId:i,state:o?"implemented":n.length?"partial":"unknown",attemptIds:t.map(r=>r.id)}}function cc(i,e,t){let n=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===i)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),o=t.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===i),r=n[0],s=o?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:i},state:s,attemptIds:n.map(c=>c.id)}}function sr(i,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),o=i.records.filter(u=>u.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=i.records.filter(u=>u.recordType==="decision"&&u.state==="active"),c=r?s.filter(u=>r.has(u.id)):s,d=i.records.filter(u=>u.recordType==="implementation_attempt"),l=i.records.filter(u=>u.recordType==="verification_attempt"),w=i.records.filter(u=>u.recordType==="freshness_signal"&&u.state==="open"),b=i.records.filter(u=>u.recordType==="evidence"),P=i.records.filter(u=>u.recordType==="model_entry"),R=rc(o,e),S=new Map(R.map(u=>[u.subjectId,u.score])),f=Wn([e.action,e.text].filter(Boolean).join(" ")),p=c.flatMap(u=>{let E=Math.max(0,...u.subjects.map(O=>S.get(O.subjectId)??0)),j=Math.round(rr(Wn(u.claim),f)*35),T=E+j;return T>=50?[{decision:u,score:T}]:[]}).sort((u,E)=>E.score-u.score||u.decision.id.localeCompare(E.decision.id)),y=new Map;for(let u of p.slice(0,n))y.set(u.decision.id,u.decision);for(let u of i.relationships){if(!Ot(u,"excepts")&&!Ot(u,"contradicts"))continue;let E=s.find(T=>T.id===u.from.entityId),j=s.find(T=>T.id===u.to.entityId);!E||!j||!y.has(E.id)&&!y.has(j.id)||(y.size<n&&y.set(E.id,E),y.size<n&&y.set(j.id,j))}let m=[...y.values()],h=u=>u.from.entityType==="decision"&&u.to.entityType==="decision"&&y.has(u.from.entityId)&&y.has(u.to.entityId),M=(u,E=!1)=>{let j=new Set(u.map(J=>J.id)),T=w.filter(J=>J.target.entityType==="decision"&&j.has(J.target.entityId)),O=new Set(i.relationships.filter(J=>Ot(J,"excepts")&&j.has(J.from.entityId)&&j.has(J.to.entityId)).flatMap(J=>[J.from.entityId,J.to.entityId])),K=i.relationships.filter(J=>Ot(J,"contradicts")&&j.has(J.from.entityId)&&j.has(J.to.entityId)).map(J=>({id:J.id,decisionIds:[J.from.entityId,J.to.entityId],unresolvedQuestion:J.reason,expansionRefs:[{kind:"record",id:J.id}]})),G=new Set(K.flatMap(J=>J.decisionIds)),Q=b.filter(J=>J.sourceRefs.some(B=>B.kind==="record"&&j.has(B.id))||i.relationships.some(B=>B.relationshipType==="supports"&&B.from.entityType==="evidence"&&B.from.entityId===J.id&&B.to.entityType==="decision"&&j.has(B.to.entityId))),x=Math.max(0,p.length-u.length),V=i.relationships.some(J=>Ot(J,"contradicts")&&h(J)&&(!j.has(J.from.entityId)||!j.has(J.to.entityId))),L=E||x>0||V,N=[];R.length===0&&(e.subjectHints?.length??0)>0?N.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):u.length===0&&N.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),K.length&&N.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:K.flatMap(J=>J.expansionRefs)}),Q.some(J=>J.availability!=="available")&&N.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Q.map(J=>({kind:"record",id:J.id}))}),L&&N.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:i.manifest.projectId}]});let ge={contractVersion:1,projectId:i.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:R.map(({score:J,...B})=>B),modelEntries:P.filter(J=>J.decisionIds.some(B=>j.has(B))).map(J=>({id:J.id,key:J.key,value:J.value,decisionIds:J.decisionIds})),decisions:u.map(J=>({id:J.id,kind:J.kind,claim:J.claim,subjectIds:J.subjects.map(B=>B.subjectId),authority:J.authority,effectiveState:G.has(J.id)?"conflicted":O.has(J.id)?"excepted":"active",freshness:T.filter(B=>B.target.entityId===J.id).map(B=>B.signalType),expansionRef:{kind:"record",id:J.id}})),conflicts:K,uncertainties:N,implementation:u.map(J=>ac(J.id,d)),verification:u.map(J=>cc(J.id,l,T)),evidence:Q.map(J=>({evidenceId:J.id,summary:J.summary,availability:J.availability,sourceRefs:J.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:x,omittedEvidenceCount:0,conflictsComplete:!V}};return ge.budget.estimatedTokens=sc(ge),ge},g=M(m);for(;g.budget.estimatedTokens>t&&m.length>0;){let u=m.pop(),E=i.relationships.filter(j=>Ot(j,"contradicts")&&(j.from.entityId===u.id||j.to.entityId===u.id)).flatMap(j=>[j.from.entityId,j.to.entityId]);m=m.filter(j=>!E.includes(j.id)),g=M(m,!0)}return g}var dc=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Dt(i){return dc.test(i)}function lc(i){return{valid:!i.some(e=>e.severity==="error"),issues:i}}function ne(i,e,t,n){i.push({path:e,code:t,message:n,severity:"error"})}function Ki(i,e,t,n){i.push({path:e,code:t,message:n,severity:"warning"})}function Ae(i,e,t){Dt(t)||ne(i,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Xe(i,e,t){(!t||Number.isNaN(Date.parse(t)))&&ne(i,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function St(i,e,t,n=!1){n&&t.level==="contributor"&&ne(i,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&ne(i,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var pc={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->emerging","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"])},uc=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function mc(i,e,t){Ae(i,`${t}.id`,e.id),Ae(i,`${t}.projectId`,e.projectId),Ae(i,`${t}.participantId`,e.participantId),Ae(i,`${t}.entity.entityId`,e.entity.entityId),Xe(i,`${t}.createdAt`,e.createdAt),St(i,`${t}.authority`,e.authority);let n=pc[e.entity.entityType],o=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(o)&&ne(i,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${o}.`);let r=`${e.entity.entityType}:${e.toState}`;if(uc.has(r)&&(St(i,`${t}.authority`,e.authority,!0),e.reason?.trim()||ne(i,`${t}.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)&&ne(i,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ne(i,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Xe(i,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function fc(i,e,t,n){Ae(i,`${t}.id`,e.id),Ae(i,`${t}.projectId`,e.projectId),Ae(i,`${t}.participantId`,e.participantId),Xe(i,`${t}.createdAt`,e.createdAt),e.projectId!==n&&ne(i,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ne(i,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ne(i,`${t}.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)&&ne(i,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(St(i,`${t}.authority`,e.authority,!0),e.claim.trim()||ne(i,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Ki(i,`${t}.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())&&ne(i,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Xe(i,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ne(i,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(o=>!o.trim())&&ne(i,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((o,r)=>{(!o.id.trim()||!o.modelPath.trim())&&ne(i,`${t}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Xe(i,`${t}.concreteBindings[${r}].createdAt`,o.createdAt),Xe(i,`${t}.concreteBindings[${r}].updatedAt`,o.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ne(i,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Xe(i,`${t}.appliedAt`,e.appliedAt),St(i,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&ne(i,`${t}.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())&&ne(i,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(o=>!o.trim()))&&ne(i,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Ki(i,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Ki(i,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function hc(i,e,t){if(Ae(i,`${t}.id`,e.id),Ae(i,`${t}.projectId`,e.projectId),Ae(i,`${t}.participantId`,e.participantId),Ae(i,`${t}.from.entityId`,e.from.entityId),Ae(i,`${t}.to.entityId`,e.to.entityId),Xe(i,`${t}.createdAt`,e.createdAt),e.reason.trim()||ne(i,`${t}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let o=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!o&&!r&&ne(i,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),o&&!e.authority?ne(i,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):o&&e.authority&&St(i,`${t}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ne(i,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ne(i,t,"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))&&ne(i,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ne(i,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function Tt(i){let e=[];Ae(e,"manifest.projectId",i.manifest.projectId),Xe(e,"manifest.createdAt",i.manifest.createdAt),Xe(e,"manifest.updatedAt",i.manifest.updatedAt);let t=new Map,n=(f,p)=>{let y=t.get(f);y?ne(e,p,"duplicate_id",`ID is already used at ${y}.`):t.set(f,p)};i.records.forEach((f,p)=>{let y=`records[${p}]`;n(f.id,y),fc(e,f,y,i.manifest.projectId)}),i.events.forEach((f,p)=>{let y=`events[${p}]`;n(f.id,y),mc(e,f,y),f.projectId!==i.manifest.projectId&&ne(e,`${y}.projectId`,"project_mismatch","Event belongs to another project.")}),i.relationships.forEach((f,p)=>{let y=`relationships[${p}]`;n(f.id,y),hc(e,f,y),f.projectId!==i.manifest.projectId&&ne(e,`${y}.projectId`,"project_mismatch","Relationship belongs to another project.")}),i.artifacts.forEach((f,p)=>{n(f.id,`artifacts[${p}]`),Ae(e,`artifacts[${p}].id`,f.id)}),i.tombstones.forEach((f,p)=>{let y=`tombstones[${p}]`;n(f.id,y),Ae(e,`${y}.id`,f.id),Ae(e,`${y}.objectId`,f.objectId),Ae(e,`${y}.deletedById`,f.deletedById),Xe(e,`${y}.deletedAt`,f.deletedAt),St(e,`${y}.authority`,f.authority,!0)});let o=new Set(i.records.map(f=>`${f.recordType}:${f.id}`)),r=new Set(i.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,p)=>{let y=`${f.entityType}:${f.entityId}`;!o.has(y)&&!r.has(y)&&ne(e,p,"dangling_entity_reference",`No record or tombstone exists for ${y}.`)};i.events.forEach((f,p)=>s(f.entity,`events[${p}].entity`)),i.relationships.forEach((f,p)=>{s(f.from,`relationships[${p}].from`),s(f.to,`relationships[${p}].to`)});let c=new Set(i.artifacts.map(f=>f.id)),d=(f,p)=>{c.has(f)||ne(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(f,p,y)=>{!o.has(`${f}:${p}`)&&!r.has(`${f}:${p}`)&&ne(e,y,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};i.records.forEach((f,p)=>{let y=`records[${p}]`;switch(f.recordType){case"authority_grant":l("participant",f.granteeId,`${y}.granteeId`),l("participant",f.grantedById,`${y}.grantedById`),f.subjectIds.forEach((m,h)=>l("subject",m,`${y}.subjectIds[${h}]`));break;case"observation":f.captureContext.subjectIds.forEach((m,h)=>l("subject",m,`${y}.captureContext.subjectIds[${h}]`)),f.captureContext.artifactIds.forEach((m,h)=>d(m,`${y}.captureContext.artifactIds[${h}]`));break;case"proposal":case"decision":f.subjects.forEach((m,h)=>l("subject",m.subjectId,`${y}.subjects[${h}].subjectId`));break;case"thread":f.messageArtifactIds.forEach((m,h)=>d(m,`${y}.messageArtifactIds[${h}]`)),f.resultRefs.forEach((m,h)=>s(m,`${y}.resultRefs[${h}]`));break;case"iteration":f.threadIds.forEach((m,h)=>l("thread",m,`${y}.threadIds[${h}]`)),f.artifactIds.forEach((m,h)=>d(m,`${y}.artifactIds[${h}]`));break;case"evidence":f.artifactIds.forEach((m,h)=>d(m,`${y}.artifactIds[${h}]`));break;case"advisory_explanation":f.subjectIds.forEach((m,h)=>l("subject",m,`${y}.subjectIds[${h}]`)),f.evidenceIds.forEach((m,h)=>l("evidence",m,`${y}.evidenceIds[${h}]`)),f.supersededById&&l("advisory_explanation",f.supersededById,`${y}.supersededById`);break;case"implementation_attempt":f.iterationIds.forEach((m,h)=>l("iteration",m,`${y}.iterationIds[${h}]`)),f.coverageClaims.forEach((m,h)=>l("decision",m.decisionId,`${y}.coverageClaims[${h}].decisionId`)),f.artifactIds.forEach((m,h)=>d(m,`${y}.artifactIds[${h}]`));break;case"eval_spec":f.replacesSpecId&&l("eval_spec",f.replacesSpecId,`${y}.replacesSpecId`),f.decisionIds.forEach((m,h)=>l("decision",m,`${y}.decisionIds[${h}]`)),f.subjectIds.forEach((m,h)=>l("subject",m,`${y}.subjectIds[${h}]`)),(f.dependencies??[]).forEach((m,h)=>{m.kind==="subject"&&m.subjectId&&l("subject",m.subjectId,`${y}.dependencies[${h}].subjectId`)}),(f.scenarios??[]).forEach((m,h)=>{m.subjectIds?.forEach((M,g)=>l("subject",M,`${y}.scenarios[${h}].subjectIds[${g}]`))}),f.targets.forEach((m,h)=>l(m.entityType,m.entityId,`${y}.targets[${h}]`));break;case"verification_attempt":f.evalSpecId&&l("eval_spec",f.evalSpecId,`${y}.evalSpecId`),f.targets.forEach((m,h)=>l(m.entityType,m.entityId,`${y}.targets[${h}]`)),f.evidenceIds.forEach((m,h)=>l("evidence",m,`${y}.evidenceIds[${h}]`));break;case"model_entry":f.subjectIds.forEach((m,h)=>l("subject",m,`${y}.subjectIds[${h}]`)),f.decisionIds.forEach((m,h)=>l("decision",m,`${y}.decisionIds[${h}]`));break;case"model_projection":St(e,`${y}.authority`,f.authority,!0),l("participant",f.appliedById,`${y}.appliedById`),f.decisionIds.forEach((m,h)=>l("decision",m,`${y}.decisionIds[${h}]`)),f.entryIds.forEach((m,h)=>l("model_entry",m,`${y}.entryIds[${h}]`)),f.coverage.forEach((m,h)=>l("decision",m.decisionId,`${y}.coverage[${h}].decisionId`));break;case"freshness_signal":s(f.target,`${y}.target`),f.evidenceIds.forEach((m,h)=>l("evidence",m,`${y}.evidenceIds[${h}]`));break;default:break}});let w=new Map(i.events.map(f=>[f.id,f])),b=new Map(i.records.map(f=>[`${f.recordType}:${f.id}`,f])),P=new Map;i.events.forEach((f,p)=>{let y=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,m=P.get(y)??new Set;m.add(f.toState),P.set(y,m),m.size>1&&ne(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let R=new Map(i.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),S=(f,p,y,m,h)=>{if(f.level!=="delegate"||!f.grantId)return;let M=R.get(f.grantId);if(!M){ne(e,h,"invalid_authority_grant","Delegated authority references a missing grant.");return}(M.granteeId!==p||M.level!=="delegate")&&ne(e,h,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let g=Date.parse(y);(g<Date.parse(M.startsAt)||M.endsAt&&g>Date.parse(M.endsAt)||M.revokedAt&&g>=Date.parse(M.revokedAt))&&ne(e,h,"inactive_authority_grant","The delegated authority grant was not active at this time."),M.subjectIds.length&&m.length&&!m.every(u=>M.subjectIds.includes(u))&&ne(e,h,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let f of i.records)f.recordType==="decision"&&S(f.authority,f.acceptedById,f.createdAt,f.subjects.map(p=>p.subjectId),`records:${f.id}.authority`);i.events.forEach((f,p)=>{let y=b.get(`${f.entity.entityType}:${f.entity.entityId}`),m=y&&"subjects"in y?y.subjects.map(h=>h.subjectId):[];S(f.authority,f.participantId,f.createdAt,m,`events[${p}].authority`)}),i.relationships.forEach((f,p)=>{if(!f.authority)return;let y=[f.from,f.to].flatMap(m=>{let h=b.get(`${m.entityType}:${m.entityId}`);return h&&"subjects"in h?h.subjects.map(M=>M.subjectId):[]});S(f.authority,f.participantId,f.createdAt,y,`relationships[${p}].authority`)});for(let f of i.records){if(f.recordType!=="decision")continue;let p=w.get(f.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==f.proposalId||p.toState!=="accepted")&&ne(e,`records:${f.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==f.acceptedById&&ne(e,`records:${f.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),b.has(`proposal:${f.proposalId}`)||ne(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(i.relationships.some(m=>m.relationshipType==="supersedes"&&m.to.entityType==="decision"&&m.to.entityId===f.id)||ne(e,`records:${f.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),f.state==="revoked"&&(i.events.some(m=>m.entity.entityType==="decision"&&m.entity.entityId===f.id&&m.toState==="revoked"&&!!m.reason?.trim())||ne(e,`records:${f.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let f of i.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;i.records.some(y=>y.recordType==="decision"&&y.proposalId===f.id)||ne(e,`records:${f.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return lc(e)}function cn(i,e,t,n){return{id:n,schemaVersion:1,projectId:i.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function ar(i,e,t,n,o){return{id:o,schemaVersion:1,projectId:i.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:n,acceptedById:t.participantId,authority:t.authority,state:"active",kind:t.kind,claim:e.claim,rationale:t.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function gc(i){switch(i.action){case"accept":return[i.eventId,i.decisionId];case"edit_and_accept":return[i.withdrawalEventId,i.replacementProposalId,i.acceptanceEventId,i.decisionId,i.relationshipId];case"reject":case"defer":return[i.eventId]}}function Hn(i,e){let t=[],n=i.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Dt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of gc(e))Dt(r)||t.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!n)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...cn(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=ar(i,n,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.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 r={id:e.replacementProposalId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.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={...cn(i,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...cn(i,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=ar(i,r,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[r,d],events:[s,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.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 r={...cn(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let o={...cn(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.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:n.id,append:{records:[],events:[o],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}var cr={project:0,route:1,component:2,selector:2,file:3},dr={intention:0,principle:1,pattern:2};function Nt(i,e){let t=cr[i.scope.kind]-cr[e.scope.kind];return t!==0?t:dr[i.kind]-dr[e.kind]}function lr(i){return i==="expresses"||i==="excepts"}function yc(i,e){if(e.type==="expresses"||e.type==="excepts")return structuredClone(e);if(e.type==="operationalizes")return{...structuredClone(e),type:"expresses"};if(e.type==="instantiates")return{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId};if(e.type==="refines"){let t=i.explanations.find(r=>r.id===e.fromId),n=i.explanations.find(r=>r.id===e.toId);if(!t||!n)return;let o=Nt(t,n);return o===0?void 0:o>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function Pt(i){let e=structuredClone(i),t=new Set;return e.relations=i.relations.flatMap(n=>{let o=yc(i,n);if(!o)return[];let r=`${o.type}:${o.fromId}:${o.toId}`;return t.has(r)?[]:(t.add(r),[o])}),e}import{createHash as vc}from"crypto";import{readFile as Ic,readdir as wc,realpath as bc}from"fs/promises";import{join as dn,relative as xc}from"path";var Sc=["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 Bt(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:null}function Ue(i,e=0){return new Date(Number.isFinite(i)?i:e).toISOString()}function pr(...i){return i.find(e=>!!e?.trim())?.trim()}function ae(i,e,t,n){let r=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=vc("sha256").update(`${i}\0${e}\0${t}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function Qi(i,e){try{return JSON.parse(await Ic(i,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:i,message:t instanceof Error?t.message:String(t)}),null}}function Tc(i){let e=Bt(i);if(!e)return 0;let t=0,n=o=>{let r=Bt(o);if(!r){t+=1;return}for(let s of Object.values(r))n(s)};for(let o of Object.values(e))n(o);return t}function Pc(i){let e={};for(let t of i)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function ln(i){let e=[],t=await bc(i.projectRoot).catch(()=>i.projectRoot),n=dn(t,".popmelt"),o=await Qi(dn(n,"threads.json"),e),r=await Qi(dn(n,"model.json"),e),s=Bt(o),c=Bt(s?.threads)??{},d=Object.entries(c).map(([B,X])=>({key:B,value:Bt(X)})).filter(B=>!!B.value),l=dn(n,"decisions"),w=await wc(l).catch(()=>[]),b=[];for(let B of w.filter(X=>X.endsWith(".json")).sort()){let X=Bt(await Qi(dn(l,B),e));X&&b.push({file:B,value:X})}let P=d.flatMap(({value:B})=>[B.createdAt,B.updatedAt]).filter(B=>typeof B=="number"&&Number.isFinite(B)),R=P.length?Math.min(...P):0,S=i.projectKey??t;i.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 f=ae(S,"project",S,R),p=ae(S,"participant","legacy-owner",R),y=ae(S,"participant","legacy-agent",R),m=ae(S,"subject","project",R),h=Ue(Math.max(R,...P)),M=[],g=[],u=new Map,E=new Map,j=new Map(b.map(B=>[B.value.id??B.file.replace(/^d-|\.json$/g,""),B.value])),T=new Map,O=(B,X,pe,ke,ce)=>{let Le=u.get(pe);if(Le)return Le;let ze=ae(S,"artifact",B,ke);return g.push({id:ze,kind:X,mediaType:ce,location:pe,availability:"available"}),u.set(pe,ze),ze};for(let{file:B,value:X}of b){let pe=X.id??B.replace(/^d-|\.json$/g,""),ke=X.createdAt??R,ce=[O(`${pe}:envelope`,"other",`.popmelt/decisions/${B}`,ke,"application/json")];X.screenshotPath&&ce.push(O(`${pe}:screenshot`,"screenshot",`.popmelt/${X.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,X.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Le,ze]of(X.pastedImagePaths??[]).entries())ce.push(O(`${pe}:image:${Le}`,"image",ze,ke));T.set(pe,ce)}let H=(B,X,pe)=>({id:B,schemaVersion:1,projectId:f,createdAt:h,participantId:X,sourceRefs:pe}),K=(B,X)=>{M.push(X);let pe=E.get(B)??[];pe.push(X.id),E.set(B,pe)},G=[{...H(p,p,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...H(y,y,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];M.push(...G),M.push({...H(m,p,[]),recordType:"subject",subjectType:"project",label:xc(process.cwd(),t)||t,aliases:[],locators:[{id:ae(S,"locator",t,R),kind:"project_root",value:t,status:"current",validFrom:Ue(R),sourceRefs:[]}]});let Q=new Map,x=(B,X)=>{let pe=Q.get(B);if(pe)return pe;let ke=ae(S,"subject",B,X),ce={...H(ke,p,[{kind:"external",id:B}]),createdAt:Ue(X),recordType:"subject",subjectType:"element",label:B,aliases:[],locators:[{id:ae(S,"locator",B,X),kind:"dom_selector",value:B,status:"current",validFrom:Ue(X),sourceRefs:[{kind:"external",id:B}]}]};return M.push(ce),Q.set(B,ke),ke};for(let{key:B,value:X}of d){let pe=X.id??B,ke=X.createdAt??R,ce=ae(S,"thread",pe,ke),Le={kind:"thread",id:pe},ze=[],Me=[],dt=Array.isArray(X.messages)?X.messages:[],We,lt,en=0;dt.forEach((xe,pt)=>{let _e=xe.timestamp??ke,nt=ae(S,"artifact",`${pe}:message:${pt}`,_e);if(ze.push(nt),g.push({id:nt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${pe}/messages/${pt}`,availability:"available"}),u.set(`.popmelt/threads.json#/threads/${pe}/messages/${pt}`,nt),xe.screenshotPath&&O(`${pe}:message:${pt}:screenshot`,"screenshot",xe.screenshotPath,_e),xe.role==="human"){We=xe;let Be=xe.feedbackSummary??xe.replyToQuestion;if(Be?.trim()){let Je=ae(S,"observation",`${pe}:${pt}`,_e),ft=X.elementIdentifiers??[],Mt={...H(Je,p,[Le,{kind:"message",id:nt}]),createdAt:Ue(_e),recordType:"observation",state:"open",statement:Be,captureContext:{subjectIds:ft.map(wt=>x(wt,ke)),artifactIds:[nt]},resolvedByIds:[]};K(pe,Mt),lt=Je,Me.push({entityType:"observation",entityId:Je})}return}if(xe.role!=="assistant")return;let ut=xe.jobId??`${pe}:${pt}`,mt=ae(S,"iteration",ut,_e),vt=j.get(ut),Si=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",Ti={...H(mt,y,[Le,{kind:"message",id:nt},...(T.get(ut)??[]).map(Be=>({kind:"artifact",id:Be}))]),createdAt:Ue(_e),recordType:"iteration",threadIds:[ce],startedAt:Ue(We?.timestamp,_e),completedAt:Ue(_e),requestSummary:pr(We?.feedbackSummary,We?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:Si,execution:{provider:xe.provider??vt?.provider,model:xe.model??vt?.model,sessionId:xe.sessionId??vt?.sessionId},artifactIds:[nt,...T.get(ut)??[]]};K(pe,Ti),Me.push({entityType:"iteration",entityId:mt});let It=xe.resolutions??vt?.resolutions??[];for(let[Be,Je]of It.entries()){if(Je.status!=="resolved"||!Je.summary?.trim())continue;let ft=X.elementIdentifiers??[],Mt=(ft.length?ft:[t]).map(Tn=>({subjectId:Tn===t?m:x(Tn,ke),role:"governed"})),wt=ae(S,"proposal",`${ut}:${Je.annotationId??"resolution"}:${Be}`,_e),Pi={...H(wt,y,[Le,{kind:"iteration",id:mt}]),createdAt:Ue(_e),recordType:"proposal",state:"pending",claim:Je.summary,subjects:Mt,subjectSemantics:Mt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:pr(We?.feedbackSummary,We?.replyToQuestion,Je.summary),iterationId:mt,inferredById:y}};K(pe,Pi),Me.push({entityType:"proposal",entityId:wt}),e.push({severity:"warning",code:"acceptance_unresolved",source:pe,message:`Proposal ${wt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(It.some(Be=>Be.status==="resolved")||vt?.gitDiff){let Be=ae(S,"implementation",ut,_e),Je={...H(Be,y,[Le,{kind:"iteration",id:mt}]),createdAt:Ue(_e),recordType:"implementation_attempt",state:"completed",iterationIds:[mt],coverageClaims:[],summary:It.map(ft=>ft.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};K(pe,Je),Me.push({entityType:"implementation_attempt",entityId:Be}),en+=1}lt&&(lt=void 0)});let At=dt.at(-1),xi={...H(ce,p,[Le]),createdAt:Ue(ke),recordType:"thread",state:At?.question?"open":"resolved",messageArtifactIds:ze,outcome:At?.question?"question_unresolved":en?"implementation_only":"no_outcome",resultRefs:Me};M.push(xi),E.set(pe,[ce,...E.get(pe)??[]])}let V=Tc(r);V&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${V} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:f,createdAt:Ue(R),updatedAt:h,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:i.writerVersion??"0.8.4-dev"}},records:M,events:[],relationships:[],artifacts:g,tombstones:[]},N=Tt(L),J=(i.proofCaseIds??Sc).map(B=>({legacyId:B,threadFound:d.some(({key:X,value:pe})=>(pe.id??X)===B),decisionEnvelopeFound:j.has(B),recordIds:E.get(B)??[]}));return{bundle:L,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((B,X)=>B+(X.value.messages?.length??0),0),decisionEnvelopes:b.length,modelEntries:V,artifactsReferenced:g.length},imported:Pc(M),unresolvedAcceptance:e.filter(B=>B.code==="acceptance_unresolved").length,deferredModelEntries:V,proofCases:J,issues:e,schemaIssues:N.issues}}}import{createHash as kc}from"crypto";import{mkdir as ur,open as Xi,readFile as Yi,readdir as Rc,rename as jc,unlink as Zi}from"fs/promises";import{join as it}from"path";var Ac={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Vn(i){return kc("sha256").update(JSON.stringify(i)).digest("hex")}function mr(i){return Vn(i)}function fr(i,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!i.manifest.features.includes("advisory_explanations")&&i.manifest.features.push("advisory_explanations");for(let n of e.recordReplacements??[]){if(n.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${n.recordType}.`);let o=i.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(o<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let r=i.records[o];if(r.projectId!==n.projectId||r.createdAt!==n.createdAt||r.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);i.records[o]=structuredClone(n)}for(let n of e.projectionUpdates){let o=i.records.find(r=>r.recordType===n.entityType&&r.id===n.entityId);if(!o||o.recordType!=="proposal"&&o.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(o.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${o.state}`);o.state=n.state}return i.records.push(...e.records),i.events.push(...e.events),i.relationships.push(...e.relationships),i.artifacts.push(...e.artifacts),i.tombstones.push(...e.tombstones),i.manifest.updatedAt=t,i}function Mc(i,e,t){return fr(structuredClone(i),e,t)}async function kt(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await Xi(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
155
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await jc(t,i)}catch(o){throw await Zi(t).catch(()=>{}),o}}async function Gn(i){return JSON.parse(await Yi(i,"utf8"))}var Kn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=it(e,".popmelt","memory"),this.journalDir=it(this.memoryDir,"journal"),this.manifestPath=it(this.memoryDir,"manifest.json"),this.checkpointPath=it(this.memoryDir,"checkpoint.json"),this.lockPath=it(this.memoryDir,"writer.lock")}async initialize(e){let t=Tt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await ur(this.journalDir,{recursive:!0});try{throw await Yi(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(n){if(n instanceof Error&&n.message==="Memory journal is already initialized."||n.code!=="ENOENT")throw n}await this.withWriterLock(async()=>{try{throw await Yi(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 n=Vn(e),o={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await kt(this.checkpointPath,o),await kt(this.manifestPath,r)})}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 kt(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 t=Vn(e.bundle),n=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,o={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await kt(it(this.memoryDir,n),o),e.manifest.checkpoint={file:n,sequence:o.sequence,hash:t},await kt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:o.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Dt(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let o=n.report.headSequence+1,r={storageVersion:1,sequence:o,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...r,hash:mr(r)},c=Mc(n.bundle,e,t.committedAt),d=Tt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(o).padStart(12,"0")}-${t.transactionId}.json`;return await kt(it(this.journalDir,l),s),n.manifest.head={sequence:o,hash:s.hash},n.manifest.updatedAt=t.committedAt,await kt(this.manifestPath,n.manifest),{bundle:c,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:o,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...Ac,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await Gn(this.manifestPath),t=await Gn(it(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||t.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==t.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(t.hash!==Vn(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await Rc(this.journalDir),o=n.filter(P=>P.endsWith(".tmp")),s=n.filter(P=>/^\d{12}-[0-9a-f-]+\.json$/i.test(P)).sort().filter(P=>Number(P.slice(0,12))>t.sequence),c=structuredClone(t.bundle),d=t.sequence,l=t.journalHash??null,w=new Set;for(let P of s){let R=await Gn(it(this.journalDir,P)),{hash:S,...f}=R;if(S!==mr(f))throw new Error(`Journal hash mismatch: ${P}`);if(R.sequence!==d+1)throw new Error(`Journal sequence gap at ${P}`);if(R.previousHash!==l)throw new Error(`Journal chain mismatch at ${P}`);if(R.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${P}`);if(w.has(R.transactionId))throw new Error(`Duplicate transaction ID: ${R.transactionId}`);fr(c,R.mutation,R.committedAt),d=R.sequence,l=R.hash,w.add(R.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 b=Tt(c);if(!b.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(b.issues)}`);return{bundle:c,manifest:e,transactionIds:w,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:o.length,headSequence:d,headHash:l}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await ur(this.memoryDir,{recursive:!0});let t;try{t=await Xi(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let o=await Gn(this.lockPath).catch(()=>({})),r=!0;if(typeof o.pid=="number")try{process.kill(o.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await Zi(this.lockPath),t=await Xi(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Zi(this.lockPath).catch(()=>{})}}};import{randomBytes as Ec}from"crypto";function be(i=Date.now()){let t=Math.max(0,Math.min(Math.floor(i),0xffffffffffff)).toString(16).padStart(12,"0"),n=Ec(10).toString("hex"),o=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${o}${n.slice(4,7)}-${n.slice(7,19)}`}var _c=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function hr(i,e){let t=i.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),n=i.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let o=i.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=_c(),l=d.records,w=i.records.find(h=>h.recordType==="thread"&&h.sourceRefs.some(M=>M.kind==="thread"&&M.id===e.threadId));w||(w={id:ae(o,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.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(h=>h.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(w));let b=[];for(let h of[...new Set(e.subjectHints.filter(Boolean))]){let M=i.records.find(g=>g.recordType==="subject"&&g.locators.some(u=>u.value===h&&u.status==="current"));M||(M={id:ae(o,"live-subject",h,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"element",label:h,aliases:[],locators:[{id:ae(o,"live-locator",h,e.createdAt),kind:"dom_selector",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},l.push(M)),b.push(M)}for(let h of[...new Set((e.filePaths??[]).filter(Boolean))]){let M=i.records.find(g=>g.recordType==="subject"&&g.locators.some(u=>u.kind==="source_file"&&u.value===h&&u.status==="current"));M||(M={id:ae(o,"live-file-subject",h,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"file",label:h,aliases:[],locators:[{id:ae(o,"live-file-locator",h,e.createdAt),kind:"source_file",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},l.push(M)),b.push(M)}let P=(e.semanticCandidates??[]).filter(h=>h.claim.trim()),R;if(P.length>0){R=ae(o,"live-observation",r,e.createdAt);let h={id:R,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:P.map(M=>M.claim.trim()).join(" "),captureContext:{subjectIds:b.map(M=>M.id),artifactIds:[]},resolvedByIds:[]};l.push(h)}let S=ae(o,"live-iteration",r,e.completedAt),f={id:S,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:imprint-evidence"})),...R?[{kind:"record",id:R}]:[]],recordType:"iteration",threadIds:[w.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};l.push(f);let p=[],y=e.resolutions.filter(h=>h.status==="resolved"&&h.summary.trim()),m=b.length>0?b:i.records.filter(h=>h.recordType==="subject"&&h.subjectType==="project").slice(0,1);if(P.length>0&&m.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[h,M]of P.entries()){let g=ae(o,"live-proposal",`${r}:${h}`,e.completedAt),u=m.map(j=>({subjectId:j.id,role:"governed"})),E={id:g,schemaVersion:1,projectId:i.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:S},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:M.claim.trim(),rationale:M.rationale?.trim()||void 0,proposedKind:M.proposedKind,subjects:u,subjectSemantics:u.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:M.sourceText?.trim()||e.requestSummary,iterationId:S,inferredById:n.id}};l.push(E),p.push(g)}if(y.length>0){let h=new Set(e.governingDecisionIds??[]),M=i.records.filter(u=>u.recordType==="decision"&&u.state==="active"&&h.has(u.id)),g={id:ae(o,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:S}],recordType:"implementation_attempt",state:"completed",iterationIds:[S],coverageClaims:M.map(u=>({decisionId:u.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${y.map(E=>E.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:S}]})),summary:y.map(u=>u.summary).join(" "),artifactIds:[]};l.push(g)}return{mutation:d,iterationId:S,proposalIds:p,observationId:R}}import{createHash as Cc}from"crypto";import{mkdir as $c,open as Oc,readFile as Dc,rename as Nc,unlink as Bc}from"fs/promises";import{join as gr}from"path";function yr(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function vr(i){return Cc("sha256").update(JSON.stringify(i)).digest("hex")}async function Jc(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await Oc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
156
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await Nc(t,i)}catch(o){throw await Bc(t).catch(()=>{}),o}}function Lc(i,e,t=new Date().toISOString()){let n={},o={},r={},s=(d,l,w)=>{let b=d[l]??=[];b.includes(w)||b.push(w)};for(let d of i.records)if(d.recordType==="subject"){let l=d;for(let w of[l.label,...l.aliases,...l.locators.filter(b=>b.status==="current").map(b=>b.value)]){let b=yr(w);b&&s(n,b,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(o,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(r,l.subjectId,d.id);let c={version:1,projectId:i.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:o,proposalIdsBySubject:r};return{...c,checksum:vr(c)}}function Ir(i,e){let t=[...new Set(e.flatMap(n=>i.subjectIdsByValue[yr(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>i.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>i.proposalIdsBySubject[n]??[]))]}}var Qn=class{constructor(e){this.indexDir=gr(e,".popmelt","memory","indexes"),this.indexPath=gr(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let o=JSON.parse(await Dc(this.indexPath,"utf8")),{checksum:r,...s}=o;if(o.version===1&&o.projectId===e.manifest.projectId&&o.journalHead.sequence===t.sequence&&o.journalHead.hash===t.hash&&r===vr(s))return o}catch(o){if(o.code!=="ENOENT"&&!(o instanceof SyntaxError))throw o}let n=Lc(e,t);return await $c(this.indexDir,{recursive:!0}),await Jc(this.indexPath,n),n}};var un="popmelt:imprint",xr="popmelt:imprint-evidence",Lt="popmelt:imprint-relation";function Xn(i){return i.sourceRefs.find(e=>e.kind==="external"&&e.uri===un)?.id}function eo(i){let e=new Set;return i.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function Yn(i,e){if(!i)return[];let t=new Set(i.relations.flatMap(n=>n.type==="expresses"&&n.toId===e?[n.fromId]:[]));return i.concrete.filter(n=>t.has(n.id)).map(n=>({id:n.id,modelPath:n.modelPath,value:structuredClone(n.value),createdAt:n.createdAt,updatedAt:n.updatedAt}))}function to(i){if(i==="expresses")return"operationalizes";if(i==="excepts")return"excepts"}var Zn=class{constructor(e){this.projectRoot=e;this.store=new Kn(e),this.indexStore=new Qn(e),this.manifestPath=Jt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await pn(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 o=await this.store.load();return o.report.recoveredTransactions>0&&(o=await this.store.recover()),await this.refreshIndex(o),await this.status()}let n=await ln({...e,projectRoot:this.projectRoot});if(n.report.schemaIssues.some(o=>o.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(n.bundle)}catch(o){if(!(o instanceof Error)||!o.message.includes("already initialized"))throw o}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await ln({...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=Jt(this.projectRoot,".popmelt","memory","migrations"),t=Jt(e,"imprint-advisories-v2.json");try{let h=JSON.parse(await pn(t,"utf8"));return{migrated:!1,explanations:h.explanations??0,evidence:h.evidence??0}}catch{}let n;try{n=Pt(JSON.parse(await pn(Jt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await wr(e,{recursive:!0}),await br(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let o=await this.store.load(),r=o.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),c=o.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active")??r,d=o.bundle.records.find(h=>h.recordType==="subject"&&h.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let l=o.bundle.manifest.projectId,w=new Set(o.bundle.records.map(h=>h.id)),b=new Set(o.bundle.relationships.flatMap(h=>h.sourceRefs.flatMap(M=>M.kind==="external"&&M.uri===Lt?[M.id]:[]))),P=new Map,R=o.bundle.records.filter(h=>h.recordType==="advisory_explanation");for(let h of n.explanations){let M=R.find(g=>Xn(g)===h.id);P.set(h.id,M?.id??ae(l,"imprint-explanation",h.id,Date.parse(h.createdAt)))}let S=[],f=[],p=[],y=0;for(let h of n.explanations){let M=P.get(h.id),g=R.find(T=>T.id===M),u=[],E=h.evidence.length?h.evidence:[{id:`fallback:${h.id}`,kind:"observation",stance:"supports",summary:h.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:h.createdAt}];for(let T of E){let O=ae(l,"imprint-evidence-record",T.id,Date.parse(T.createdAt));u.push(O),!w.has(O)&&(S.push({id:O,schemaVersion:1,projectId:l,createdAt:T.createdAt,participantId:c.id,sourceRefs:eo([{kind:"external",id:T.id,uri:xr},{kind:"external",id:h.id,uri:un},{kind:"thread",id:T.threadId},{kind:"message",id:T.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(T.kind)?"user_feedback":"judgment",summary:T.summary,availability:"available",artifactIds:[]}),p.push({id:ae(l,"imprint-evidence-link",`${h.id}:${T.id}`,Date.parse(T.createdAt)),schemaVersion:1,projectId:l,createdAt:T.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:T.id,uri:xr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"evidence",entityId:O},reason:"This advisory explanation was derived from collaboration evidence."}),y+=1)}let j={id:M,schemaVersion:1,projectId:l,createdAt:g?.createdAt??h.createdAt,participantId:g?.participantId??c.id,sourceRefs:eo([...g?.sourceRefs??[],{kind:"external",id:h.id,uri:un}]),recordType:"advisory_explanation",kind:h.kind,state:h.state,statement:h.statement,rationale:h.rationale,scope:structuredClone(h.scope),subjectIds:[d.id],evidenceIds:[...new Set([...g?.evidenceIds??[],...u])],concreteBindings:Yn(n,h.id),supersededById:h.supersededBy?P.get(h.supersededBy):void 0,updatedAt:h.updatedAt};g?f.push(j):S.push(j)}for(let h of n.relations){let M=to(h.type);if(!M)continue;let g=P.get(h.fromId),u=P.get(h.toId);!g||!u||b.has(h.id)||p.push({id:ae(l,"imprint-relation",h.id,Date.parse(h.createdAt)),schemaVersion:1,projectId:l,createdAt:h.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:h.id,uri:Lt}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:g},to:{entityType:"advisory_explanation",entityId:u},reason:h.rationale||"The Imprint graph connected these explanations."})}let m=new Date().toISOString();if(S.length||f.length||p.length)try{let h=await this.store.commit({records:S,recordReplacements:f,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ae(l,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:m});await this.refreshIndex(h)}catch(h){if(!(h instanceof Error)||!h.message.includes("Transaction already exists"))throw h}return await wr(e,{recursive:!0}),await br(t,JSON.stringify({version:2,migratedAt:m,explanations:n.explanations.length,evidence:y,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:y}}async review(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,selection:Gi(n.bundle,o)}}async contextualize(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:sr(n.bundle,o),reviewSelection:Gi(n.bundle,o)}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:Hn(n.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 t=await ln({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.load(),o=Hn(n.bundle,e);if(!o.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(o.errors)}`);let r=await this.store.commitReviewPlan(o.plan,t);return await this.refreshIndex(r),r}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 t=await this.store.load(),n=t.bundle.records.find(P=>P.recordType==="proposal"&&P.id===e.proposalId),o=t.bundle.records.find(P=>P.recordType==="participant"&&P.kind==="human"&&P.status==="active");if(!n||n.state!=="pending"||!o)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),c={proposalId:n.id,participantId:o.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:be(r),decisionId:be(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:be(r),replacementProposalId:be(r),acceptanceEventId:be(r),decisionId:be(r),relationshipId:be(r),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:be(r),reason:e.reason}:{...c,action:"defer",eventId:be(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(P=>P.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=Hn(t.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(P=>P.message).join(" ")};let w=await this.store.commitReviewPlan(l.plan,{transactionId:be(r),committedAt:s});await this.refreshIndex(w);let b=l.plan.resultRefs.find(P=>P.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:b,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:w.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),n=hr(t.bundle,e),o=ae(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(n.mutation,{transactionId:o,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=Pt(JSON.parse(await pn(Jt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),o=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),r=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active"),s=e.action?o:r??o,c=n.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),w=n.bundle.manifest.projectId,b=[],P=[],R=[],S=n.bundle.records.filter(m=>m.recordType==="advisory_explanation"),f=new Map(S.flatMap(m=>{let h=Xn(m);return h?[[h,m.id]]:[]}));for(let m of e.summary.changes)if(!f.has(m.explanationId)){let h=t?.explanations.find(M=>M.id===m.explanationId);f.set(m.explanationId,ae(w,"imprint-explanation",m.explanationId,Date.parse(h?.createdAt??d)))}for(let m of e.summary.changes){let h={kind:"external",id:m.explanationId,uri:un},M=f.get(m.explanationId),g=S.find(T=>T.id===M),u=t?.explanations.find(T=>T.id===m.explanationId),E={id:ae(w,"imprint-live-evidence",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[h,{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:[]};b.push(E);let j={id:M,schemaVersion:1,projectId:w,createdAt:g?.createdAt??u?.createdAt??d,participantId:g?.participantId??s.id,sourceRefs:eo([...g?.sourceRefs??[],h,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:u?.kind??g?.kind??"pattern",state:u?.state??m.state,statement:u?.statement??m.statement,rationale:u?.rationale??g?.rationale??e.summary.detail,scope:structuredClone(u?.scope??g?.scope??{kind:"project",values:[]}),subjectIds:g?.subjectIds??[c.id],evidenceIds:[...new Set([...g?.evidenceIds??[],E.id])],concreteBindings:u?Yn(t,m.explanationId):g?.concreteBindings??[],supersededById:u?.supersededBy?f.get(u.supersededBy):g?.supersededById,updatedAt:u?.updatedAt??d};g?P.push(j):b.push(j),R.push({id:ae(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[h],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:j.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 p=new Set(n.bundle.relationships.flatMap(m=>m.sourceRefs.flatMap(h=>h.kind==="external"&&h.uri===Lt?[h.id]:[])));for(let m of t?.relations??[]){let h=to(m.type);if(!h)continue;let M=f.get(m.fromId),g=f.get(m.toId);!M||!g||p.has(m.id)||R.push({id:ae(w,"imprint-relation",m.id,Date.parse(m.createdAt)),schemaVersion:1,projectId:w,createdAt:m.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:m.id,uri:Lt}],recordType:"relationship",relationshipType:h,from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"advisory_explanation",entityId:g},reason:m.rationale||"The Imprint graph connected these explanations."})}let y=ae(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let m=await this.store.commit({records:b,recordReplacements:P,events:[],relationships:R,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:y,committedAt:d});await this.refreshIndex(m)}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=Pt(JSON.parse(await pn(Jt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),r=t.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??n;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=t.bundle.manifest.projectId,d=t.bundle.records.filter(u=>u.recordType==="advisory_explanation"),l=new Map(d.flatMap(u=>{let E=Xn(u);return E?[[E,u]]:[]})),w=new Map([...[...l].map(([u,E])=>[u,E.id]),...e.explanations.filter(u=>!l.has(u.id)).map(u=>[u.id,ae(c,"imprint-explanation",u.id,Date.parse(u.createdAt))])]),b=[],P=[],R=new Set(e.explanations.map(u=>u.id));for(let u of e.explanations){let E=l.get(u.id);if(!E){b.push({id:w.get(u.id),schemaVersion:1,projectId:c,createdAt:u.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:u.id,uri:un}],recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Yn(e,u.id),supersededById:u.supersededBy?w.get(u.supersededBy):void 0,updatedAt:u.updatedAt});continue}let j={...structuredClone(E),kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),concreteBindings:Yn(e,u.id),supersededById:u.supersededBy?w.get(u.supersededBy):void 0,updatedAt:u.updatedAt},T=O=>JSON.stringify({kind:O.kind,state:O.state,statement:O.statement,rationale:O.rationale,scope:O.scope,concreteBindings:O.concreteBindings,supersededById:O.supersededById,updatedAt:O.updatedAt});T(E)!==T(j)&&P.push(j)}for(let[u,E]of l)R.has(u)||E.state==="retired"||P.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let S=new Set(t.bundle.tombstones.flatMap(u=>u.objectType==="relationship"?[u.objectId]:[])),f=new Map(t.bundle.relationships.flatMap(u=>{if(S.has(u.id))return[];let E=u.sourceRefs.find(j=>j.kind==="external"&&j.uri===Lt)?.id;return E?[[E,u]]:[]})),p=[],y=new Set;for(let u of e.relations){let E=to(u.type);if(!E)continue;let j=w.get(u.fromId),T=w.get(u.toId);if(!j||!T)continue;let O=f.get(u.id);O&&O.relationshipType===E&&O.from.entityType==="advisory_explanation"&&O.from.entityId===j&&O.to.entityType==="advisory_explanation"&&O.to.entityId===T||(O&&y.add(u.id),p.push({id:ae(c,"imprint-relation",`${u.id}:${E}:${j}:${T}`,Date.parse(u.createdAt)),schemaVersion:1,projectId:c,createdAt:u.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:u.id,uri:Lt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:T},reason:u.rationale||"The Imprint graph connected these explanations."}))}let m=new Set(e.relations.map(u=>u.id)),h=n?[...f].filter(([u])=>!m.has(u)||y.has(u)).map(([,u])=>({id:ae(c,"imprint-relationship-tombstone",u.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:u.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!b.length&&!P.length&&!p.length&&!h.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let M=e.updatedAt,g=ae(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(M));try{let u=await this.store.commit({records:b,recordReplacements:P,events:[],relationships:p,artifacts:[],tombstones:h,projectionUpdates:[]},{transactionId:g,committedAt:M});return await this.refreshIndex(u),{status:"synced",relationships:p.length+h.length,explanations:b.length+P.length,headSequence:u.report.headSequence}}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u;return{status:"no_change",relationships:0,explanations:0,headSequence:t.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 t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let n={};for(let o of t.bundle.records)n[o.recordType]=(n[o.recordType]??0)+1;return{status:e,journal:t.report,records:n,openFreshnessSignals:t.bundle.records.filter(o=>o.recordType==="freshness_signal"&&o.state==="open").length,unavailableEvidence:t.bundle.records.filter(o=>o.recordType==="evidence"&&o.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),o=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!n.has(s.id)&&!o.has(s.id)&&!r.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(),t=new Set(e.records.flatMap(o=>o.recordType==="decision"&&o.state==="active"?[o.id]:[])),n=new Map;for(let o of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))o.decisionIds.some(r=>t.has(r))&&n.set(o.key,o);return[...n.values()]}async getImprintView(e=[],t){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 o=await this.store.load(),r=o.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(r.map(p=>[p.id,p])),c=new Map(r.flatMap(p=>{let y=Xn(p);return y?[[y,p.id]]:[]})),d=new Set(e.map(p=>c.get(p)??p)),l=new Map(o.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),w=new Map(o.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),b=new Set(o.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),P=new Set(["operationalizes","excepts"]),R={testing:0,emerging:1,grounded:2,challenged:3,retired:4},S=r.map(p=>{let y=p.evidenceIds.flatMap(g=>{let u=w.get(g);if(!u)return[];let E=u.sourceRefs.find(H=>H.kind==="thread")?.id,j=u.sourceRefs.find(H=>H.kind==="message")?.id,T=u.kind==="judgment"||u.kind==="user_feedback"||u.kind==="project_state"?u.kind:"other",O=l.get(u.participantId)??"unknown";return[{id:u.id,kind:T,summary:u.summary,createdAt:u.createdAt,participantKind:O,threadId:E,jobId:j}]}).sort((g,u)=>u.createdAt.localeCompare(g.createdAt)),m=o.bundle.relationships.flatMap(g=>{if(b.has(g.id))return[];if(!P.has(g.relationshipType))return[];let u=g.from.entityType==="advisory_explanation"&&g.from.entityId===p.id&&g.to.entityType==="advisory_explanation",E=g.to.entityType==="advisory_explanation"&&g.to.entityId===p.id&&g.from.entityType==="advisory_explanation";if(!u&&!E)return[];let j=u?g.to.entityId:g.from.entityId,T=s.get(j);return T?[{id:g.id,type:g.relationshipType==="operationalizes"?"expresses":"excepts",direction:u?"outgoing":"incoming",explanationId:T.id,statement:T.statement,rationale:g.reason}]:[]}),h=[...(p.supersededById?[p.supersededById]:[]).flatMap(g=>{let u=s.get(g);return u?[{id:`supersedes:${p.id}:${u.id}`,type:"supersedes",direction:"incoming",explanationId:u.id,statement:u.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(g=>g.supersededById===p.id?[{id:`supersedes:${g.id}:${p.id}`,type:"supersedes",direction:"outgoing",explanationId:g.id,statement:g.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],M=[...new Set([...p.sourceRefs.flatMap(g=>g.kind==="thread"?[g.id]:[]),...y.flatMap(g=>g.threadId?[g.threadId]:[])])].filter(g=>!t||t.has(g));return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:y.length,recentEvidence:y.slice(0,4),concrete:p.concreteBindings.map(g=>({...structuredClone(g)})),relations:[...m,...h],sourceThreadIds:M,needsGrounding:p.state==="testing"&&d.has(p.id)}}).sort((p,y)=>Number(y.needsGrounding)-Number(p.needsGrounding)||R[p.state]-R[y.state]||y.updatedAt.localeCompare(p.updatedAt)),f={total:S.filter(p=>p.state!=="retired").length,emerging:S.filter(p=>p.state==="emerging").length,testing:S.filter(p=>p.state==="testing").length,grounded:S.filter(p=>p.state==="grounded").length,challenged:S.filter(p=>p.state==="challenged").length,retired:S.filter(p=>p.state==="retired").length,needsGrounding:S.filter(p=>p.needsGrounding).length};return{head:{sequence:o.report.headSequence,updatedAt:o.bundle.manifest.updatedAt},counts:f,explanations:S}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),n=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=>t.has(d))&&n.set(c.key,c);let o=[...n.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(l=>l.targets.some(w=>w.entityType==="decision"&&w.entityId===c.id)).sort((l,w)=>w.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:o.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:o.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 t=await this.store.load(),n=t.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),o=t.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!n||!o)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=be(r),d=be(r),l=be(r),w=be(r),b=be(r),P=new Set(t.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),R=t.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&P.has(T.id)),S={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:o.id,role:"governed"}],p={...S,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},y={...S,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."},m={...S,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},h={...S,id:w,recordType:"model_entry",key:e.key,subjectIds:[o.id],decisionIds:[l],value:e.value},M={...S,id:b,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[w],coverage:[{decisionId:l,status:"projected"}]},g={...S,id:be(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:w},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},u=R.map(T=>({...S,id:be(r),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}.`})),E=R.map(T=>({...S,id:be(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:m.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),j=await this.store.commit({records:[p,m,h,M],events:[y,...u],relationships:[g,...E],artifacts:[],tombstones:[],projectionUpdates:R.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:be(r),committedAt:s});return await this.refreshIndex(j),{decisionId:l,entryId:w}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(o=>o.recordType==="proposal"&&o.state==="pending"&&o.sourceRefs.some(r=>r.id===e));return n?{proposalId:n.id,claim:n.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 t=await this.store.load(),n=t.bundle.records.find(S=>S.recordType==="model_projection"&&S.state==="applied"&&S.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let o=t.bundle.records.filter(S=>S.recordType==="decision"&&e.decisionIds.includes(S.id)&&S.state==="active");if(o.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=t.bundle.records.find(S=>S.recordType==="participant"&&S.kind==="human"&&S.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=be(s),l=e.changes.map(S=>{let f=S.decisionIds?.filter(m=>e.decisionIds.includes(m)),p=f?.length?f:e.decisionIds,y=[...new Set(o.filter(m=>p.includes(m.id)).flatMap(m=>m.subjects.map(h=>h.subjectId)))];return{id:be(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:p.map(m=>({kind:"record",id:m})),recordType:"model_entry",key:S.path.map(String).join("."),subjectIds:y,decisionIds:p,value:S.value}}),w=new Set(l.flatMap(S=>S.decisionIds)),b={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(S=>({kind:"record",id:S})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(S=>S.id),coverage:e.decisionIds.map(S=>e.coverage?.find(f=>f.decisionId===S)??{decisionId:S,status:w.has(S)?"projected":"unprojected"})},P=l.flatMap(S=>S.decisionIds.map(f=>({id:be(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:b.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:S.id},to:{entityType:"decision",entityId:f},reason:"The owner applied this model entry as a projection of accepted product truth."}))),R=await this.store.commit({records:[...l,b],events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:be(s),committedAt:c});return await this.refreshIndex(R),{projectionId:d,entryIds:l.map(S=>S.id),headSequence:R.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let t=await this.store.load();return{source:"journal",bundle:t.bundle,journal:t.report}}return{source:"legacy_preview",bundle:(await ln({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),o=Ir(n,t.subjectHints??[]);return o?{...t,subjectIds:[...new Set([...t.subjectIds??[],...o.subjectIds])],candidateDecisionIds:o.decisionIds,candidateProposalIds:o.proposalIds}:t}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 Ft(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Expected a JSON object.");return i}function Te(i,e){if(typeof i!="string"||!i.trim())throw new Error(`${e} must be a non-empty string.`);return i}function qt(i,e,t){let n=Te(i,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function no(i){let e=Ft(i),t=Ft(e.authority),n=t.level,o=t.mode,r=qt(n,"authority.level",["owner","delegate","contributor"]),s=qt(o,"authority.mode",["local_trusted","hosted"]),c={proposalId:Te(e.proposalId,"proposalId"),participantId:Te(e.participantId,"participantId"),occurredAt:Te(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Te(e.eventId,"eventId"),decisionId:Te(e.decisionId,"decisionId"),kind:qt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Te(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Te(e.eventId,"eventId"),reason:Te(e.reason,"reason")};case"defer":{let d=Ft(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:Te(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=>Te(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>qt(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:Te(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Te(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Te(e.acceptanceEventId,"acceptanceEventId"),decisionId:Te(e.decisionId,"decisionId"),relationshipId:Te(e.relationshipId,"relationshipId"),claim:Te(e.claim,"claim"),kind:qt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=Ft(d);return{subjectId:Te(l.subjectId,"subjectId"),role:qt(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:Te(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function io(i){let e=Ft(i),t=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>Te(c,s))}},n=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},o=e.resurface===void 0?void 0:Ft(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:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:o?{differentAction:o.differentAction===!0,newEvidence:o.newEvidence===!0,newConflict:o.newConflict===!0,ownerRequested:o.ownerRequested===!0}:void 0}}function Ut(i){return i.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
157
+ `)}async function Sr(i,e,t,n){let o=Ut(e);if(!(!o&&t.length===0))try{let r=await i.contextualize({action:o||void 0,subjectHints:t,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(r.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.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:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){n?.(r);return}}function Tr(i){if(!i?.packets.length&&!i?.acceptedTruth?.decisions.length)return"";let e=i.packets.some(n=>n.presentation==="surface_before_action");return["","## Contextual product memory","",...i.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.",...i.acceptedTruth.decisions.flatMap((n,o)=>["",`${o+1}. [${n.kind}; ${n.effectiveState}] ${n.claim}`,` - Implementation: ${n.implementation}`,` - Verification: ${n.verification}`,...n.freshness.length?[` - Freshness warnings: ${n.freshness.join(", ")}`]:[],` - Decision: ${n.id}`]),...i.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...i.acceptedTruth.conflicts.map(n=>`- ${n.unresolvedQuestion}`)]:[],...i.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...i.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...i.packets.flatMap((n,o)=>["",`${o+1}. ${n.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${n.proposedKind??"unspecified"}`,` - Presentation: ${n.presentation}`,` - Packet: ${n.packetId}`,` - Evidence references available: ${n.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(`
158
+ `)}function Pr(i){let e=i.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]);if(typeof t.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(t.action)))return null;let n=t.action,o=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!o||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(c=>typeof c=="string"&&r.has(c)):void 0;return{proposalId:t.proposalId,action:n,kind:o,claim:typeof t.claim=="string"?t.claim:void 0,reason:typeof t.reason=="string"?t.reason:void 0,taskContext:typeof t.taskContext=="string"?t.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function kr(i){let e=i.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]),n=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:null;return!n||typeof t.proposalId!="string"||!t.proposalId||typeof t.title!="string"||!t.title.trim()||typeof t.claim!="string"||!t.claim.trim()||typeof t.rationale!="string"||!t.rationale.trim()?null:{proposalId:t.proposalId,kind:n,title:t.title.trim(),claim:t.claim.trim(),rationale:t.rationale.trim(),scope:typeof t.scope=="string"&&t.scope.trim()?t.scope.trim():void 0}}catch{return null}}async function oo(i){let t=(i.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],o=await qc(i),r=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),c,d,l,w,b,P,R,S,f,p,y,m,h,M,g=[],u=[],E=0,j=[];for(;E<o.length;){let T=o.indexOf(r,E);if(T===-1)break;let O=T+r.length;if(o.slice(T,T+s.length).equals(s))break;let H=O;o[H]===13&&o[H+1]===10&&(H+=2);let K=o.indexOf(`\r
159
159
  \r
160
- `,V);if(K===-1)break;let W=i.slice(V,K).toString("utf-8"),Q=K+4,w=i.indexOf(r,Q),H=w!==-1?w-2:i.length;E.push({headers:W,body:i.slice(Q,H)}),J=w!==-1?w:i.length}for(let R of E){let N=R.headers.match(/name="([^"]+)"/);if(!N)continue;let V=N[1];if(V==="screenshot")c=R.body;else if(V==="feedback")d=R.body.toString("utf-8");else if(V==="color")u=R.body.toString("utf-8");else if(V==="provider")I=R.body.toString("utf-8");else if(V==="model")x=R.body.toString("utf-8");else if(V==="reasoningEffort")T=R.body.toString("utf-8");else if(V==="serviceTier")k=R.body.toString("utf-8");else if(V==="goal")S=R.body.toString("utf-8");else if(V==="pageUrl")p=R.body.toString("utf-8");else if(V==="viewport")l=R.body.toString("utf-8");else if(V==="planId")f=R.body.toString("utf-8");else if(V==="manifest")m=R.body.toString("utf-8");else if(V==="tasks")h=R.body.toString("utf-8");else if(V==="sourceId")j=R.body.toString("utf-8");else if(V.startsWith("screenshot-")){let K=V.slice(11);try{let W=decodeURIComponent(K);g.push({pathname:W,data:R.body})}catch{}}else if(V.startsWith("image-")){let K=V.split("-"),W=parseInt(K[K.length-1],10),Q=K.slice(1,-1).join("-");Q&&!isNaN(W)&&b.push({annotationId:Q,index:W,data:R.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:u,provider:I,model:x,reasoningEffort:T,serviceTier:k,goal:S,pageUrl:p,viewport:l,planId:f,manifest:m,tasks:h,sourceId:j,pastedImages:b,pageScreenshots:g}}function wc(o){return new Promise((e,n)=>{let t=[];o.on("data",i=>t.push(i)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as bc}from"crypto";var an="<orientation>",nt="</orientation>";function Qo(o,e){let n=e;for(;n<o.length&&/\s/.test(o[n]);)n++;if(n>=o.length)return{status:"incomplete",start:n};if(o[n]!=="{")return{status:"invalid",start:n};let t=0,i=!1,r=!1;for(let s=n;s<o.length;s++){let c=o[s];if(i){r?r=!1:c==="\\"?r=!0:c==='"'&&(i=!1);continue}if(c==='"')i=!0;else if(c==="{")t++;else if(c==="}"){if(t--,t===0)return{status:"complete",start:n,end:s+1};if(t<0)return{status:"invalid",start:n}}}return{status:"incomplete",start:n}}function mr(o,e){if(!e)return;let n=o[o.length-1];n?.kind==="text"?n.text+=e:o.push({kind:"text",text:e})}function fr(o){let e=[],n=0;for(;n<o.length;){let t=o.indexOf(an,n);if(t<0){mr(e,o.slice(n));break}mr(e,o.slice(n,t));let i=t+an.length,r=Qo(o,i);if(r.status!=="complete"){let c=o.indexOf(nt,i);if(c>=0){n=c+nt.length;continue}n=i;continue}e.push({kind:"orientation",json:o.slice(r.start,r.end)}),n=r.end;let s=n;for(;s<o.length&&/\s/.test(o[s]);)s++;o.startsWith(nt,s)&&(n=s+nt.length)}return e}var xc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Sc=new Set(["strengthened","weakened","mixed","unknown"]);function cn(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 hr(o,e,n,t=Date.now()){let i=Tc(o);if(!i)return null;let r=typeof i.transition=="string"&&xc.has(i.transition)?i.transition:null,s=cn(i.focus);if(!r||!s)return null;let c=typeof i.evidencePosture=="string"&&Sc.has(i.evidencePosture)?i.evidencePosture:void 0;return{id:bc(),jobId:e,sequence:n,timestamp:t,transition:r,snapshot:{focus:s,seeking:cn(i.seeking),workingHypothesis:cn(i.workingHypothesis),evidencePosture:c,update:cn(i.update),nextObservation:cn(i.nextObservation)},contextPolicy:"exclude"}}function Xo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Yo(o,e,n=0){let t=[],i=[],r=new Set,s=n;for(let d of fr(o)){if(d.kind==="text"){d.text&&i.push(d);continue}try{let u=hr(JSON.parse(d.json),e,s);if(!u)continue;let I=Xo(u);if(r.has(I))continue;r.add(I),t.push(u),i.push({kind:"orientation",orientation:u}),s++}catch{}}return{visibleText:i.map(d=>d.kind==="text"?d.text:`
160
+ `,H);if(K===-1)break;let G=o.slice(H,K).toString("utf-8"),Q=K+4,x=o.indexOf(r,Q),V=x!==-1?x-2:o.length;j.push({headers:G,body:o.slice(Q,V)}),E=x!==-1?x:o.length}for(let T of j){let O=T.headers.match(/name="([^"]+)"/);if(!O)continue;let H=O[1];if(H==="screenshot")c=T.body;else if(H==="feedback")d=T.body.toString("utf-8");else if(H==="color")l=T.body.toString("utf-8");else if(H==="provider")w=T.body.toString("utf-8");else if(H==="model")b=T.body.toString("utf-8");else if(H==="reasoningEffort")P=T.body.toString("utf-8");else if(H==="serviceTier")R=T.body.toString("utf-8");else if(H==="goal")S=T.body.toString("utf-8");else if(H==="pageUrl")f=T.body.toString("utf-8");else if(H==="viewport")p=T.body.toString("utf-8");else if(H==="planId")y=T.body.toString("utf-8");else if(H==="manifest")m=T.body.toString("utf-8");else if(H==="tasks")h=T.body.toString("utf-8");else if(H==="sourceId")M=T.body.toString("utf-8");else if(H.startsWith("screenshot-")){let K=H.slice(11);try{let G=decodeURIComponent(K);u.push({pathname:G,data:T.body})}catch{}}else if(H.startsWith("image-")){let K=H.split("-"),G=parseInt(K[K.length-1],10),Q=K.slice(1,-1).join("-");Q&&!isNaN(G)&&g.push({annotationId:Q,index:G,data:T.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:w,model:b,reasoningEffort:P,serviceTier:R,goal:S,pageUrl:f,viewport:p,planId:y,manifest:m,tasks:h,sourceId:M,pastedImages:g,pageScreenshots:u}}function qc(i){return new Promise((e,t)=>{let n=[];i.on("data",o=>n.push(o)),i.on("end",()=>e(Buffer.concat(n))),i.on("error",t)})}import{randomUUID as Fc}from"crypto";var mn="<orientation>",ot="</orientation>";function zt(i,e){let t=e;for(;t<i.length&&/\s/.test(i[t]);)t++;if(t>=i.length)return{status:"incomplete",start:t};if(i[t]!=="{")return{status:"invalid",start:t};let n=0,o=!1,r=!1;for(let s=t;s<i.length;s++){let c=i[s];if(o){r?r=!1:c==="\\"?r=!0:c==='"'&&(o=!1);continue}if(c==='"')o=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0)return{status:"complete",start:t,end:s+1};if(n<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function Rr(i,e){if(!e)return;let t=i[i.length-1];t?.kind==="text"?t.text+=e:i.push({kind:"text",text:e})}function jr(i){let e=[],t=0;for(;t<i.length;){let n=i.indexOf(mn,t);if(n<0){Rr(e,i.slice(t));break}Rr(e,i.slice(t,n));let o=n+mn.length,r=zt(i,o);if(r.status!=="complete"){let c=i.indexOf(ot,o);if(c>=0){t=c+ot.length;continue}t=o;continue}e.push({kind:"orientation",json:i.slice(r.start,r.end)}),t=r.end;let s=t;for(;s<i.length&&/\s/.test(i[s]);)s++;i.startsWith(ot,s)&&(t=s+ot.length)}return e}var Uc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),zc=new Set(["strengthened","weakened","mixed","unknown"]);function fn(i,e=180){if(typeof i!="string")return;let t=i.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Wc(i){return!i||typeof i!="object"||Array.isArray(i)?null:i}function Ar(i,e,t,n=Date.now()){let o=Wc(i);if(!o)return null;let r=typeof o.transition=="string"&&Uc.has(o.transition)?o.transition:null,s=fn(o.focus);if(!r||!s)return null;let c=typeof o.evidencePosture=="string"&&zc.has(o.evidencePosture)?o.evidencePosture:void 0;return{id:Fc(),jobId:e,sequence:t,timestamp:n,transition:r,snapshot:{focus:s,seeking:fn(o.seeking),workingHypothesis:fn(o.workingHypothesis),evidencePosture:c,update:fn(o.update),nextObservation:fn(o.nextObservation)},contextPolicy:"exclude"}}function ro(i){return JSON.stringify({transition:i.transition,snapshot:i.snapshot})}function so(i,e,t=0){let n=[],o=[],r=new Set,s=t;for(let d of jr(i)){if(d.kind==="text"){d.text&&o.push(d);continue}try{let l=Ar(JSON.parse(d.json),e,s);if(!l)continue;let w=ro(l);if(r.has(w))continue;r.add(w),n.push(l),o.push({kind:"orientation",orientation:l}),s++}catch{}}return{visibleText:o.map(d=>d.kind==="text"?d.text:`
161
161
 
162
162
  `).join("").replace(/\n{3,}/g,`
163
163
 
164
- `).trim(),orientations:t,segments:i}}function Pc(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 Gn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let u=this.buffer.slice(d);if(nt.startsWith(u)&&u.length<nt.length||(u.startsWith(nt)&&(this.buffer=this.buffer.slice(d+nt.length)),this.optionalClosePending=!1,!this.buffer))break}let i=this.buffer.indexOf(an);if(i<0){let d=Pc(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}n+=this.buffer.slice(0,i);let r=i+an.length,s=Qo(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(i);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let c=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=hr(JSON.parse(c),this.jobId,this.sequence);if(!d)continue;let u=Xo(d);if(this.signatures.has(u))continue;this.signatures.add(u),t.push(d),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=Yo(e,this.jobId,this.sequence),t=n.orientations.filter(i=>{let r=Xo(i);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:n.visibleText,orientations:t}}},gr=`## Public orientation updates
164
+ `).trim(),orientations:n,segments:o}}function Hc(i){let e="<orientation>",t=Math.min(i.length,e.length-1);for(let n=t;n>0;n--)if(e.startsWith(i.slice(-n)))return n;return 0}var ei=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(ot.startsWith(l)&&l.length<ot.length||(l.startsWith(ot)&&(this.buffer=this.buffer.slice(d+ot.length)),this.optionalClosePending=!1,!this.buffer))break}let o=this.buffer.indexOf(mn);if(o<0){let d=Hc(this.buffer);t+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}t+=this.buffer.slice(0,o);let r=o+mn.length,s=zt(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(o);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let c=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=Ar(JSON.parse(c),this.jobId,this.sequence);if(!d)continue;let l=ro(d);if(this.signatures.has(l))continue;this.signatures.add(l),n.push(d),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=so(e,this.jobId,this.sequence),n=t.orientations.filter(o=>{let r=ro(o);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},Mr=`## Public orientation updates
165
165
  During meaningful transitions in the work, emit a brief public coordination update using this exact form:
166
166
  <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>
167
167
 
168
168
  Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
169
169
  Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
170
170
 
171
- 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 dn(o,e,n){let t=[];if(o.annotations.length>0){t.push("## Annotations");for(let i of o.annotations){let r=i.elements.map(u=>{let I=[u.selector];return u.reactComponent&&I.push(`(${u.reactComponent})`),I.join(" ")}).join(", "),s=i.instruction||"No text";t.push(`- id=${i.id} [${i.type}] ${s} \u2192 Elements: ${r||"none"}`);let c=e?.[i.id];if(c&&c.length>0)for(let u of c)t.push(` Attached image: use the Read tool to view ${u}`);let d=n?.[i.id];if(d?.length)for(let u of d)t.push(` Attached context (${u.name}, ${u.mimeType}): use the Read tool to inspect ${u.path}`)}}if(o.styleModifications.length>0){t.push(""),t.push("## Style Changes (make permanent in source)"),t.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 i of o.styleModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"";for(let s of i.changes)t.push(`- ${i.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){t.push(""),t.push("## Text Changes (make permanent in source)"),t.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 i of o.textModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=JSON.stringify(i.original),c=JSON.stringify(i.modified),d=i.textNodePath.length>0?` textNodePath=${i.textNodePath.join(".")}`:"";t.push(`- ${i.selector} ${r}${d}: ${s} \u2192 ${c}`)}}if(o.domModifications?.length){t.push(""),t.push("## DOM Structure Changes (make permanent in source)"),t.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 i of o.domModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=i.sourceElement?.reactComponent?` from ${i.sourceSelector} (${i.sourceElement.reactComponent})`:i.sourceSelector?` from ${i.sourceSelector}`:"",c=i.referenceSelector?` ${i.placement} ${i.referenceSelector}`:` at index ${i.targetIndex}`;t.push(`- ${i.operation}: ${i.selector} ${r}${s} \u2192 ${i.targetParentSelector}${c}`)}}if(o.spacingTokenChanges?.length){t.push(""),t.push("## Spacing Token Changes"),t.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let i of o.spacingTokenChanges){t.push(`
172
- ### ${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`);for(let r of i.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?t.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):t.push(`- ${r.selector}${s}: ${r.property} ${i.originalPx}px \u2192 ${i.newPx}px`),t.push(` class="${r.className}"`)}}}if(o.inspectedElement){let i=o.inspectedElement;t.push(""),t.push("## Inspected Element"),t.push("The developer has this element selected in the inspector:");let r=[i.selector];i.reactComponent&&r.push(`(${i.reactComponent})`),i.context&&r.push(`in ${i.context}`),i.textContent&&r.push(`"${i.textContent.slice(0,80)}"`),t.push(`- ${r.join(" ")}`)}return t.join(`
173
- `)}function yr(o,e,n){let t=[],r=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(""),!r&&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,I=u?` [${u.breadth} ${u.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${I} \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 I=new Map;for(let x of s)if(typeof x=="object"&&x!==null&&"text"in x){let T=x,k=T.scope||"general";I.has(k)||I.set(k,[]),I.get(k).push(T.text)}for(let[x,T]of I){t.push(`**${x.charAt(0).toUpperCase()+x.slice(1)}**`);for(let k of T)t.push(`- ${k}`)}}else for(let I of s)typeof I=="string"&&t.push(`- ${I}`);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("### Applied Model-Gap Details"),t.push("Only when you actually modify the project and implement 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), describe that applied gap:"),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 actually implemented (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),t.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}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.")),r){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 I=s[d];I&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${I}`):!I&&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 x={...e,annotations:u,styleModifications:e.styleModifications},T=dn(x,n?.imagePaths,n?.attachmentFiles);T&&(t.push(""),t.push(T))}}else{let s=dn(e,n?.imagePaths,n?.attachmentFiles);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 one resolution envelope listing what you did for each annotation:"),t.push("<resolution>"),t.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),t.push("</resolution>"),t.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),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(`
174
- `)}function vr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ir(o,e,n,t){let i=[];i.push("You are continuing work on a UI based on the developer's reply to your question."),i.push(""),n!=="codex"&&i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(i.push(""),i.push(r.feedbackContext)),e.length>0){i.push(""),i.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(i.push(`### Round ${s} (human) \u2014 reply`),i.push(`"${c.replyToQuestion}"`)):(i.push(`### Round ${s} (human)`),c.feedbackSummary&&i.push(`Annotations: ${c.feedbackSummary}`))):c.question?(i.push(`### Round ${s} (assistant) \u2014 question`),i.push(`"${c.question}"`)):(i.push(`### Round ${s} (assistant)`),c.responseText&&i.push(`Response: ${c.responseText}`))}if(i.push(""),i.push("The developer answered your question. Continue working based on their reply."),i.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),i.push(""),i.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){i.push(""),i.push("## Attached Images"),i.push("The developer attached reference images with their reply:");for(let s of t)i.push(`Attached image: use the Read tool to view the image at: ${s}`)}return i.push(""),i.push("## Resolution"),i.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),i.push("<resolution>"),i.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),i.push("</resolution>"),i.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),i.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),i.push(""),i.push("### Scope classification"),i.push("Each resolution MUST include scope fields:"),i.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),i.push("- `inferredScope`: What scope the change actually has, based on what you modified."),i.push("Scope has two dimensions:"),i.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),i.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),i.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),i.push("If you cannot confidently determine scope, set it to null."),i.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.'),i.push(""),i.push("## Questions"),i.push("If you still need clarification, output:"),i.push("<question>Your question here</question>"),i.push("You may output BOTH a <resolution> and a <question> in the same response."),i.join(`
175
- `)}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 kc(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 wr(o){let n=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!n)return[];try{let t=JSON.parse(n);return(Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.annotations)?t.annotations:[]).filter(kc)}catch{return[]}}function jc(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 i=t;return(i.category==="token"||i.category==="component"||i.category==="element")&&typeof i.element=="string"&&typeof i.decision=="string"&&typeof i.reason=="string"}):[]}catch{return[]}}function br(o,e){return e>0?jc(o):[]}import{execFile as Ac}from"child_process";import{readdir as Mc,readFile as Ec,stat as _c}from"fs/promises";import{homedir as ln}from"os";import{join as Ye}from"path";var Hn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:xr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:xr()}],pn=[{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"}],un={id:"",label:"Default",source:"cli"},Cc=/^\s*-\s+"([^"]+)"/;function $c(o){let e=[],n=!1;for(let t of o.split(`
176
- `)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let i=t.match(Cc);if(!i?.[1])continue;let r=i[1];e.push({id:r,label:Zo(r),source:"cli"})}return Vn([un,...e])}function Oc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,i)=>{let r=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,s=typeof i.priority=="number"?i.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(t=>{let i=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!i)return[];let r=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Zo(i),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:i,label:r,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 xr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function Dc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Vn(e.map(n=>({id:n,label:Zo(n),source:"cli"})))}function Zo(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 r=t[1]==="sonnet"?"Sonn":Lc(t[1]),s=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${r}${s}${t[4]?" Fast":""}`}let i=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(i){let r=i[2]?`${i[1]}.${i[2]}`:i[1];return i[3]==="mini"?`Mini ${r}`:i[3]==="codex"?`Codex ${r}`:i[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return n}async function Sr(o="copilot"){let e=await Wn(o,["help","config"]),n=$c(e);return n.length>1?n:[un]}async function Tr(o="codex"){let e=await Wn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Ye(ln(),".codex");return Rr(Ye(t,"models_cache.json"))}),n=Oc(e);return n.length>0?Vn([...n,...pn]):pn}async function Pr(o="claude"){let e=Ye(ln(),".claude"),n=[Ye(ln(),".claude","stats-cache.json"),Ye(ln(),".claude","settings.json"),Ye(ln(),".claude.json"),Ye(e,"cache","changelog.md")],[t,i,r]=await Promise.all([Wn(o,["--help"]).catch(()=>""),Wn(o,["--version"]).catch(()=>""),Nc(e).catch(()=>[])]),s=Jc([...n,...r]),c=await Promise.all(s.map(u=>Rr(u).catch(()=>""))),d=Dc([t,i,...c].join(`
177
- `));return Vn([...Hn,...d])}function Wn(o,e,n=5e3){return new Promise((t,i)=>{Ac(o,e,{encoding:"utf-8",timeout:n},(r,s)=>{if(r){i(r);return}t(s)})})}async function Rr(o){return Ec(o,"utf-8")}async function Nc(o){let e=[Ye(o,"projects"),Ye(o,"telemetry")],n=[];for(let t of e)await kr(t,n,4);return n.sort((t,i)=>i.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function kr(o,e,n){if(n<0)return;let t;try{t=await Mc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async i=>{let r=Ye(o,i.name);if(i.isDirectory()){await kr(r,e,n-1);return}if(!(!i.isFile()||!Bc(i.name)))try{let s=await _c(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function Bc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Vn(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 Jc(o){return[...new Set(o)]}function Lc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Kn=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 r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){n=r;break}}let t=n>=0?n+1:0,i=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),i}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 i=this.bufferEvent(n,e);for(let r of this.listeners)r(i,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let i={...n,seq:t.nextSeq++};return t.events.push(i),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),i}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),i=this.accumulators.get(e)??{response:"",thinking:""},r=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:{...i},jobActive:r}}accumulateText(e,n,t){let i=this.accumulators.get(e);i||(i={response:"",thinking:""},this.accumulators.set(e,i)),i[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(i=>{let r=!1,s=()=>{r||(r=!0,i())};t.on("exit",s),t.on("error",s),setTimeout(()=>{if(!r){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 ot}from"crypto";import{createHash as qc}from"crypto";import{mkdir as Fc,open as Uc,readFile as jr,readdir as zc,rename as Gc,unlink as Wc}from"fs/promises";import{dirname as Hc,join as qt}from"path";function Ce(o){return structuredClone(o)}function Ar(o){return qc("sha256").update(JSON.stringify(o)).digest("hex")}async function Tt(o,e){await Fc(Hc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Uc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
178
- `,"utf8"),await t.sync()}finally{await t.close()}try{await Gc(n,o)}catch(i){throw await Wc(n).catch(()=>{}),i}}function Vc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Kc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Ce(e):o.explanations.push(Ce(e))}function Qn(o,e){let n=Ce(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(i=>i.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push(Ce(t.explanation))}else if(t.op==="replace_explanation")Kc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(i=>i.id!==t.explanationId),n.relations=n.relations.filter(i=>i.fromId!==t.explanationId&&i.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(i=>i.id===t.concrete.id)||n.concrete.push(Ce(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(i=>i.id!==t.concreteId),n.relations=n.relations.filter(i=>i.fromId!==t.concreteId&&i.toId!==t.concreteId);else if(t.op==="add_evidence"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);i.evidence.some(r=>r.id===t.evidence.id)||(i.evidence.push(Ce(t.evidence)),i.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(i,Ce(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let i=t.relation,r=n.explanations.find(u=>u.id===i.fromId),s=n.explanations.find(u=>u.id===i.toId),c=n.concrete.some(u=>u.id===i.fromId),d=n.concrete.some(u=>u.id===i.toId);if(Qi(i.type)){if(!(i.type==="expresses"?!!((r||c)&&s):!!(r&&s)))throw new Error(`Imprint ${i.type} relation has invalid endpoints: ${i.id}`);if(n.relations.some(I=>I.type===i.type&&I.fromId===i.fromId&&I.toId===i.toId))throw new Error(`Duplicate imprint relation: ${i.type}:${i.fromId}:${i.toId}`);if(i.type==="expresses"&&r&&s){if($t(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${i.id}`);let I=new Map;for(let k of n.relations)k.type==="expresses"&&I.set(k.fromId,[...I.get(k.fromId)??[],k.toId]);let x=[i.toId],T=new Set;for(;x.length;){let k=x.pop();if(k===i.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${i.id}`);T.has(k)||(T.add(k),x.push(...I.get(k)??[]))}}}else if(!r||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${i.id}`);n.relations.some(u=>u.id===i.id)||n.relations.push(Ce(i))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(i=>i.id!==t.relationId));return n}function Qc(o,e){let n=[],t=Ce(o);for(let i of e){if(i.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=t.explanations.find(s=>s.id===i.explanationId);r&&n.unshift({op:"add_explanation",explanation:Ce(r)})}else if(i.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=t.concrete.find(s=>s.id===i.concreteId);r&&n.unshift({op:"add_concrete",concrete:Ce(r)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let r=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=t.explanations.find(c=>c.id===r);s&&n.unshift({op:"replace_explanation",explanation:Ce(s)})}else if(i.op==="add_relation")n.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=t.relations.find(s=>s.id===i.relationId);r&&n.unshift({op:"add_relation",relation:Ce(r)})}t=Qn(t,[i])}return n}function Mr(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 Ft=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=qt(e,".popmelt","imprint"),this.manifestPath=qt(this.imprintDir,"manifest.json"),this.graphPath=qt(this.imprintDir,"graph.json"),this.journalDir=qt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await jr(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 loadRaw(){let e=await this.readManifest(),t=(await zc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),i=Vc(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await jr(qt(this.journalDir,t[c]),"utf8")),{hash:u,...I}=d;if(d.sequence!==c+1||d.previousHash!==s||u!==Ar(I))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);i=Qn(i,d.mutations),i.updatedAt=d.committedAt,i.head={sequence:d.sequence,hash:d.hash},r.push(d),s=d.hash}return{graph:i,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:xt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let n=await this.loadRaw(),t=xt(n.graph),i=new Map(t.relations.map(s=>[s.id,s])),r=[];for(let s of n.graph.relations){let c=i.get(s.id);c&&c.type===s.type&&c.fromId===s.fromId&&c.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),c&&r.push({op:"add_relation",relation:c}))}if(r.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${n.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await Tt(this.graphPath,t),await Tt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(x=>x.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=t.graph.head.sequence+1,r=Qc(t.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:Ce(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:Ar(s)},d=Qn(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:i,hash:c.hash};let u=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await Tt(qt(this.journalDir,u),c);let I={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Tt(this.graphPath,d),await Tt(this.manifestPath,I),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,i){let r=await this.load(),s=r.transactions.find(u=>u.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(u=>u.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(Mr));if(r.transactions.filter(u=>u.sequence>s.sequence).some(u=>u.mutations.some(I=>Mr(I).some(x=>c.has(x)))))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:i,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Tt(this.graphPath,e.graph),await Tt(this.manifestPath,{version:1,topologyVersion:2,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Xc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Yc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]),Zc=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function ti(o){return!!(o&&Zc.test(o))}function ed(o){return o.scope.kind==="project"||ti(`${o.statement} ${o.rationale}`)}function td(o){let e=o?.scope.values.filter(n=>n!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function nd(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Xn(o){return new Set(nd(o).split(" ").filter(e=>e.length>2&&!Yc.has(e)))}function Yn(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 ei(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 mt(o,e,n){return{id:ot(),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 ye(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Er(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 _r(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 i=Number(t);if(!Number.isInteger(i)||i<0||i>=n.length)return{found:!1};n=n[i]}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 Zn(o,e={}){let n=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],t=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),i=n.at(-1)?.[1],r,s=[];if(i)r=i;else{let d=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:t,error:"imprint assessment is missing"};try{let u=JSON.parse(d);if(!u||typeof u!="object"||Array.isArray(u)||!Object.prototype.hasOwnProperty.call(u,"imprint"))return{visibleText:t,error:"imprint assessment is missing"};let I=u;r=I.imprint,s=Array.isArray(I.annotations)?I.annotations:[]}catch{return{visibleText:t,error:"resolution envelope is invalid"}}}try{let c=typeof r=="string"?JSON.parse(r):r;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("imprint assessment is invalid");if(c.decision==="none"){let p=String(c.reason);if(!Xc.has(p))throw new Error("imprint no-op reason is invalid");if(p==="task_specific_detail"&&s.some(f=>{if(!f||typeof f!="object"||Array.isArray(f))return!1;let m=f;return(m.finalScope??m.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let l=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[];if(l.length){let f=l,m=new Set(e.context?.explanations.map(b=>b.id)??[]),h=new Set(e.context?.pendingGroundingExplanationIds??[]),j=f.filter(b=>{let g=e.context?.explanations.find(J=>J.id===b);return m.has(b)&&g&&(g.state==="emerging"||g.state==="testing")&&!h.has(b)});if(j.length){let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0],J=ye(b?.question,300);return{draft:{decision:"apply",summary:{title:ye(c.summary?.title,120)||"Applied shared understanding",detail:ye(c.summary?.detail,500)||ye(e.requestText||t,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:j,grounding:{explanationId:g,question:J||"Does applying this understanding here match your intent?"}},visibleText:t}}}if(p==="duplicate"){let f=ye(c.duplicateOfExplanationId,100),m=c.scopeComparison;if(!f)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(m!=="equivalent"&&m!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let h=e.context?.explanations.find(j=>j.id===f);if(!h)throw new Error("duplicate assessment must cite a surfaced explanation");if(ti(e.requestText)&&!ed(h))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:p,duplicateOfExplanationId:f,scopeComparison:m},visibleText:t}}return{draft:{decision:"none",reason:p},visibleText:t}}if(c.decision==="recognize"){let p=ye(c.explanationId,100);if(!p)throw new Error("recognition requires explanationId");let l=e.context?.explanations.find(h=>h.id===p);if(!l)throw new Error("recognition must cite a surfaced explanation");if(l.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let f=c.summary,m={title:ye(f?.title,120),detail:ye(f?.detail,500)};if(!m.title||!m.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:p,summary:m},visibleText:t}}if(c.decision==="apply"){let p=c.summary,l={title:ye(p?.title,120),detail:ye(p?.detail,500)};if(!l.title||!l.detail)throw new Error("application summary title and detail are required");let f=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(J=>typeof J=="string"&&!!J.trim()):[];if(!f.length)throw new Error("application requires appliedExplanationIds");let m=new Map(e.context?.explanations.map(J=>[J.id,J])??[]),h=new Set(e.context?.pendingGroundingExplanationIds??[]),j=f.filter(J=>{let E=m.get(J);return E&&(E.state==="emerging"||E.state==="testing")&&!h.has(J)});if(!j.length){if(f.every(E=>m.get(E)?.state==="grounded"||h.has(E)))return{draft:{decision:"none",reason:"application_only"},visibleText:t};throw new Error("application must cite a surfaced ungrounded explanation")}let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0];return{draft:{decision:"apply",summary:l,appliedExplanationIds:j,grounding:{explanationId:g,question:ye(b?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:t}}if(c.decision!==void 0&&c.decision!=="mutate")throw new Error("imprint decision is invalid");let d=c.summary,u=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(u)))throw new Error("summary.kind is invalid");let I={kind:u,title:ye(d?.title,120),detail:ye(d?.detail,500)};if(!I.title||!I.detail)throw new Error("summary title and detail are required");let x=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(p=>typeof p=="string"&&!!p.trim()):[],T=[];for(let p of Array.isArray(c.mutations)?c.mutations:[]){if(!p||typeof p!="object")continue;let l=p;if(l.op==="add"&&["intention","principle","pattern"].includes(String(l.kind))){let f=ye(l.statement),m=ye(l.rationale);if(!f||!m)continue;T.push({op:"add",clientId:ye(l.clientId,100)||void 0,kind:l.kind,statement:f,rationale:m,scope:Er(l.scope),rootReason:ye(l.rootReason,300)||void 0})}else if(l.op==="revise"&&typeof l.explanationId=="string"){let f={op:"revise",explanationId:l.explanationId,statement:ye(l.statement)||void 0,rationale:ye(l.rationale)||void 0,scope:Er(l.scope),reopenGrounding:l.reopenGrounding===!0};(f.statement||f.rationale||f.scope||f.reopenGrounding)&&T.push(f)}else if(l.op==="evidence"&&typeof l.explanationId=="string"&&["supports","challenges","excepts"].includes(String(l.stance))){let f=ye(l.summary);f&&T.push({op:"evidence",explanationId:l.explanationId,stance:l.stance,summary:f})}else if(l.op==="relation"&&typeof l.fromId=="string"&&typeof l.toId=="string"&&["expresses","excepts"].includes(String(l.type))){let f=ye(l.rationale);if(!f)continue;T.push({op:"relation",type:l.type,fromId:l.fromId,toId:l.toId,rationale:f})}else if(l.op==="supersede"&&typeof l.explanationId=="string"&&typeof l.replacementId=="string"){let f=ye(l.reason);f&&T.push({op:"supersede",explanationId:l.explanationId,replacementId:l.replacementId,reason:f})}else if(l.op==="bind_concrete"&&typeof l.explanationId=="string"){let f=ye(l.modelPath,300);f&&T.push({op:"bind_concrete",explanationId:l.explanationId,modelPath:f,rationale:ye(l.rationale)})}else l.op==="retire"&&typeof l.explanationId=="string"&&T.push({op:"retire",explanationId:l.explanationId,reason:ye(l.reason)})}let k=c.grounding,S=k&&typeof k.explanationId=="string"&&ye(k.question)?{explanationId:k.explanationId,question:ye(k.question,300)}:void 0;return{draft:{decision:"mutate",summary:I,appliedExplanationIds:x,mutations:T,grounding:S},visibleText:t}}catch(c){return{visibleText:t,error:c instanceof Error?c.message:String(c)}}}function eo(o,e={}){let n=o?.explanations??[],t=new Set(o?.pendingGroundingExplanationIds??[]),i=new Set(o?.correctionExplanationIds??[]),r=ti(e.requestText);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.",...n.length?["","Relevant explanations from the project imprint:",...n.map((s,c)=>[`${c+1}. [${s.state}; ${s.kind}] ${s.statement}`,` - Why: ${s.rationale}`,` - Scope: ${s.scope.kind} ${s.scope.values.join(", ")}`,` - Explanation: ${s.id}`,...t.has(s.id)?[" - Grounding: already pending; do not ask again"]:[],...i.has(s.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...s.concrete.map(d=>` - Concrete terminal: ${d.modelPath} = ${JSON.stringify(d.value)}`)].join(`
179
- `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(s=>`- ${s.fromId} --${s.type}--> ${s.toId}: ${s.rationale}`)]:[],"","Work normally and preserve developer agency. A testing explanation may guide action as a hypothesis without asking permission first. An emerging explanation is observation-only: use it to recognize recurrence, not to choose behavior. If the developer independently repeats an emerging observation in a meaningfully different occurrence, that new application may promote it into testing and request grounding. Silence is not confirmation.","Assess learning proactively as part of completing every thread. Do not wait for the developer to ask whether there was a learning. Before choosing none, look one abstraction level above the exact edit and ask: would the reasoning behind this outcome change how a future agent handles a meaningfully different occurrence?","The developer's original annotation, ordinary instruction, scope language, and later corrections are already human-supplied evidence. They can support learning when they establish a reusable dependency, boundary, or rationale; a separate post-completion learning prompt is not required. Mere acceptance of completed work is still insufficient.","The default outcome is no imprint mutation. Completing work or making a successful design choice does not by itself constitute learning.","Application evidence is distinct from changing shared understanding. When an emerging or testing explanation materially influenced a completed action, report decision apply even when no explanation wording changed.","Applying grounded understanding does not mutate the graph. Usually report none. Use decision recognize only when visibly acknowledging the grounded explanation closes a correction loop or otherwise makes consequential reuse legible to the developer. Recognition must cite one exact surfaced grounded explanation ID; never infer or invent an ID.","Application and recognition are whole-statement operations. Cite an existing explanation only when the completed behavior is compatible with every material clause, its scope, and its exceptions. Sharing one useful clause is not a match. If the durable behavior is narrower, add one atomic explanation linked to the broader explanation when the admission tests pass; otherwise report none.","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.","Relationship-first admission: before calling any completed change task-specific, compare its requested behavior and effective scope with every surfaced explanation that could plausibly govern the same subject or treatment. The developer does not need to name an Imprint concept or relation. Infer the relationship from the ordinary instruction, the annotated context, the implementation, and the surfaced explanations.","A narrower completed behavior that departs from an applicable broader explanation establishes an applicability boundary even when the developer did not say exception. Add one narrow testing explanation and link it to the broader rule with excepts. If the behaviors concern distinct concepts rather than the same rule, assess the reusable behavior as a sibling explanation instead. Do not manufacture an exception merely because implementations differ.","Scope and Imprint assessment must agree. If any resolved annotation has an effective inferred or final breadth of pattern, do not classify the Imprint decision as task_specific_detail. Either capture the reusable conceptual change, report application of existing understanding, cite a valid duplicate, or use another accurate no-op reason. The bridge rejects pattern-scoped task_specific_detail assessments.","","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 anywhere in the thread, including the original instruction, not merely acceptance of completed work or the model's own implementation choice.","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. Distinguish mechanics from the reusable reasoning they may reveal: a CSS property alone is not learning, but a human-directed causal rule such as keeping optical adjustment out of layout geometry may be. This heuristic never overrides relationship-first admission: a small local change that narrows or contradicts an applicable surfaced explanation may establish an exception or correction. A task-specific edit otherwise becomes learning only if the human establishes a reusable dependency, applicability boundary, 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.","Duplicate means the same reusable claim is already represented at an equivalent or broader conceptual scope. Shared code, a centralized component, or implementation reuse does not establish conceptual duplication. A narrower component-, route-, selector-, or file-scoped explanation is not a duplicate of newly broadened applicability.","Words such as all, every, across, throughout, globally, and project-wide are explicit applicability signals. When the human broadens a grounded explanation, preserve the grounded narrower explanation and add a broader testing explanation. Link the narrower explanation to the broader one with expresses. Do not substitute another no-op reason for that scope change.",...r?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"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.","When an explanation is marked Correction in the supplied context, the developer selected No but the graph has not yet been changed. Interpret the current reply before mutating anything. Decide whether it corrects only the implementation result, the explanation scope, or the reasoning. Do not challenge the whole explanation for a narrow correction, and do not recognize a different explanation merely because one clause overlaps.","Topology assessment is mandatory for every add mutation. Imprint topology has exactly two relation types: expresses and excepts. expresses always points from the more specific, concrete, or lower-level explanation to the more abstract explanation it expresses. excepts points from the narrower exception to the rule whose applicability it limits. Support and challenge belong in evidence; correction belongs in supersede; neither is a topology relation. If an addition is genuinely a new root with no meaningful relative, include rootReason 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 with expresses or excepts. Multiple specific explanations may express the same parent, and one explanation may express multiple parents; never create an expresses cycle.","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 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. The bridge supplies a fallback question when the application is otherwise valid.","","At the end, emit exactly one machine-readable <resolution> envelope after the normal response. Its `annotations` array reports annotation outcomes, and its required `imprint` field completes the learning assessment. The envelope is hidden from the developer. Do not emit a separate <imprint> block.","For no learning, include:",'"imprint":{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}',"A no-op reason cannot suppress application evidence. When the completed action semantically matches the top retrieved ungrounded explanation, the bridge records that application regardless of the no-op label. Report decision apply directly so the summary and grounding question are intentional.","When and only when reason is duplicate, also include `duplicateOfExplanationId` naming one surfaced explanation and `scopeComparison` set to `equivalent` or `existing_broader`. The bridge rejects uncited duplicates and duplicates whose cited explanation cannot cover explicit broadening language.","For application evidence without a conceptual change, include:",'"imprint":{"decision":"apply","summary":{"title":"<short expandable-summary title>","detail":"<how the explanation influenced this completed action>"},"appliedExplanationIds":["<surfaced emerging or testing explanation id>"],"grounding":{"explanationId":"<one applied id>","question":"<brief post-application confirmation question>"}}',"For a consequential, non-mutating reuse of grounded understanding that should be visible, include:",'"imprint":{"decision":"recognize","explanationId":"<one exact surfaced grounded explanation id>","summary":{"title":"<short name for the recognized understanding>","detail":"<how it guided this outcome>"}}',"Or, only after every admission test passes for a conceptual change:",'"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":"expresses|excepts","fromId":"<specific id or clientId>","toId":"<abstract rule 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 expresses the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}','The final shape is `<resolution>{"annotations":[...],"imprint":{...}}</resolution>`. The `imprint` field is required even when the decision is none; omission leaves the completed run explicitly unassessed.',"Include only mutation objects actually needed. A new explanation established through completed implementation must include its clientId in appliedExplanationIds; the bridge also derives this application from a completed change as a safeguard. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Never claim that a new explanation is grounded."].join(`
180
- `)}var Ut=class{constructor(e,n){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Ft(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let n=Xn(e.text??""),t=Xn((e.subjectHints??[]).join(" ")),i=new Set(e.pendingGroundingExplanationIds??[]),r=new Set(e.correctionExplanationIds??[]);if(!n.size&&!t.size&&!i.size&&!r.size)return;let{graph:s}=await this.store.load(),c=s.explanations.filter(p=>p.state!=="retired"&&(p.state!=="challenged"||r.has(p.id))).map(p=>{let l=Xn([p.statement,p.rationale].join(" ")),f=Xn(p.scope.values.join(" ")),m=Yn(l,n),h=Yn(f,n),j=Yn(f,t),b=Yn(l,t),g=m+h*.2+j*.25+b*.1+(p.state==="grounded"?.08:0)+(i.has(p.id)?1:0)+(r.has(p.id)?1:0),J=i.has(p.id)||r.has(p.id)||(n.size?m>=.12||h>=.5:j>=.2||b>=.2);return{item:p,score:g,relevant:J}}).filter(p=>p.relevant&&p.score>=.18).sort((p,l)=>l.score-p.score||l.item.updatedAt.localeCompare(p.item.updatedAt)),d=Math.max(1,e.maxExplanations??6);if(!c.length)return;let u=c.slice(0,d).map(({item:p})=>p),I=new Set(u.map(p=>p.id)),x=new Set(s.relations.flatMap(p=>I.has(p.fromId)?[p.toId]:I.has(p.toId)?[p.fromId]:[])),T=new Set(s.explanations.flatMap(p=>x.has(p.id)&&p.state!=="retired"&&p.state!=="challenged"?[p.id]:[])),k=s.explanations.filter(p=>T.has(p.id)&&!I.has(p.id)).sort((p,l)=>l.updatedAt.localeCompare(p.updatedAt)).slice(0,4),S=[...u,...k];for(let p of k)I.add(p.id);return{explanations:S.map(p=>{let l=new Set(s.relations.filter(f=>f.toId===p.id&&f.type==="expresses").map(f=>f.fromId));return{id:p.id,kind:p.kind,statement:p.statement,rationale:p.rationale,scope:p.scope,state:p.state,concrete:s.concrete.filter(f=>l.has(f.id)).map(f=>({id:f.id,modelPath:f.modelPath,value:f.value}))}}),truncated:c.length>u.length||k.length<T.size,...i.size?{pendingGroundingExplanationIds:[...i]}:{},...r.size?{correctionExplanationIds:[...r]}:{},relations:s.relations.filter(p=>I.has(p.fromId)&&I.has(p.toId)).map(p=>({id:p.id,type:p.type,fromId:p.fromId,toId:p.toId,rationale:p.rationale}))}}async capture(e,n){let t=e.decision==="mutate"?e.mutations:[],i=n.applicationOccurred?t.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...i])];if(t.length===0&&r.length===0)return;let s=n.occurredAt??new Date().toISOString(),c=await this.store.load(),d=new Map(c.graph.explanations.map(w=>[w.id,w])),u=new Map,I=new Map,x=[],T=new Set,k=new Set(n.pendingGroundingExplanationIds??[]),S=new Set(t.flatMap(w=>w.op==="revise"&&t.some(H=>H.op==="evidence"&&H.stance==="challenges"&&H.explanationId===w.explanationId)?[w.explanationId]:[])),p=new Set(t.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[])),l=w=>d.has(w)||p.has(w),f=new Set;for(let w of t)w.op==="relation"&&w.fromId!==w.toId&&l(w.fromId)&&l(w.toId)?(f.add(w.fromId),f.add(w.toId)):w.op==="supersede"&&w.explanationId!==w.replacementId&&l(w.explanationId)&&l(w.replacementId)?(f.add(w.explanationId),f.add(w.replacementId)):w.op==="bind_concrete"&&l(w.explanationId)&&_r(n.concreteModel,w.modelPath).found&&f.add(w.explanationId);let m=c.graph.explanations.length===0;for(let w of t){if(w.op!=="add")continue;let H=!!(w.clientId&&f.has(w.clientId)),L=!!w.rootReason?.trim()||m;if(!H&&!L)continue;m&&(m=!1);let O=ot();w.clientId&&u.set(w.clientId,O);let he=w.clientId?r.includes(w.clientId):!1,B={id:O,kind:w.kind,statement:w.statement,rationale:w.rationale,scope:ei(w.scope),state:he?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[mt(n,"supports",e.summary.detail)]};d.set(O,B),T.add(O),x.push({op:"add_explanation",explanation:B})}let h=w=>u.get(w)??w;for(let w of t){if(w.op!=="revise")continue;let H=h(w.explanationId),L=d.get(H);if(L?.state!=="grounded")continue;let O=ot(),he={id:O,kind:L.kind,statement:w.statement??L.statement,rationale:w.rationale??L.rationale,scope:w.scope?ei(w.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[mt(n,"supports",e.summary.detail)]};d.set(O,he),I.set(H,O),T.add(O),x.push({op:"add_explanation",explanation:he});let B=$t(L,he);B!==0&&x.push({op:"add_relation",relation:{id:ot(),type:"expresses",fromId:B>0?H:O,toId:B>0?O:H,rationale:w.rationale??e.summary.detail,createdAt:s}})}let j=w=>{let H=h(w);return I.get(H)??H};for(let w of t){if(w.op==="add")continue;if(w.op==="bind_concrete"){let L=j(w.explanationId);if(!d.has(L))continue;let O=_r(n.concreteModel,w.modelPath);if(!O.found)continue;let he=c.graph.concrete.find(B=>B.modelPath===w.modelPath&&JSON.stringify(B.value)===JSON.stringify(O.value));he||(he={id:ot(),modelPath:w.modelPath,value:structuredClone(O.value),createdAt:s,updatedAt:s},x.push({op:"add_concrete",concrete:he})),x.push({op:"add_relation",relation:{id:ot(),type:"expresses",fromId:he.id,toId:L,rationale:w.rationale,createdAt:s}}),T.add(L);continue}if(w.op==="relation"){let L=j(w.fromId),O=j(w.toId);if(!d.has(L)||!d.has(O)||L===O)continue;w.type==="expresses"&&$t(d.get(L),d.get(O))<0&&([L,O]=[O,L]),x.push({op:"add_relation",relation:{id:ot(),type:w.type,fromId:L,toId:O,rationale:w.rationale,createdAt:s}}),T.add(L),T.add(O);continue}if(w.op==="supersede"){let L=j(w.explanationId),O=j(w.replacementId);if(!d.has(L)||!d.has(O)||L===O)continue;x.push({op:"add_evidence",explanationId:L,evidence:mt(n,"challenges",w.reason)}),x.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:O},updatedAt:s}),T.add(L),T.add(O);continue}let H=j(w.explanationId);if(d.has(H))if(T.add(H),w.op==="revise"){if(I.has(h(w.explanationId)))continue;let L=d.get(H);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let O={...w.statement?{statement:w.statement}:{},...w.rationale?{rationale:w.rationale}:{},...w.scope?{scope:ei(w.scope)}:{},...w.reopenGrounding||S.has(w.explanationId)?{state:"testing"}:{}};x.push({op:"revise_explanation",explanationId:H,patch:O,updatedAt:s})}else if(w.op==="evidence"){if(w.stance==="challenges"&&S.has(w.explanationId))continue;x.push({op:"add_evidence",explanationId:H,evidence:mt(n,w.stance,w.summary)}),w.stance==="challenges"&&x.push({op:"revise_explanation",explanationId:H,patch:{state:"challenged"},updatedAt:s})}else w.op==="retire"&&(x.push({op:"add_evidence",explanationId:H,evidence:mt(n,"challenges",w.reason||"Retired after contradictory collaboration evidence.")}),x.push({op:"revise_explanation",explanationId:H,patch:{state:"retired"},updatedAt:s}))}for(let w of r){let H=j(w),L=d.get(H);!L||L.state==="grounded"||L.state==="retired"||k.has(H)&&!T.has(H)||(T.has(H)||(T.add(H),x.push({op:"add_evidence",explanationId:H,evidence:{...mt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&x.push({op:"revise_explanation",explanationId:H,patch:{state:"testing"},updatedAt:s}))}let b=new Set(c.graph.relations.map(w=>`${w.type}:${w.fromId}:${w.toId}`)),g=x.filter(w=>{if(w.op!=="add_relation")return!0;let H=`${w.relation.type}:${w.relation.fromId}:${w.relation.toId}`;return b.has(H)?!1:(b.add(H),!0)});if(!g.length)return;let J=ot(),E=await this.store.commit({transactionId:J,committedAt:s,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:g}),R=new Map(E.graph.explanations.map(w=>[w.id,w])),N=[...T].flatMap(w=>{let H=R.get(w);if(!H)return[];let L=!c.graph.explanations.some(he=>he.id===w),O=H.state==="challenged"||H.state==="retired";return[{explanationId:w,action:L?"added":O?"challenged":"revised",statement:H.statement,state:H.state}]}),V=r.map(j).find(w=>R.get(w)?.state==="testing"&&!k.has(w)),K=e.grounding?j(e.grounding.explanationId):V,W=K?R.get(K):void 0,Q=W?.state==="testing"&&!k.has(W.id)?{explanationId:W.id,question:e.grounding?.question||td(W),state:"testing"}:void 0;return{transactionId:J,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:N,...Q?{grounding:Q}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString(),t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(u=>u.id===t);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="yes"?(c.push({op:"add_evidence",explanationId:t,evidence:{...mt(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: ${r.statement}`):e.action==="this_time"&&(c.push({op:"add_evidence",explanationId:t,evidence:{...mt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"emerging"},updatedAt:n}),d=`Observed this time: ${r.statement}`),!c.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:ot(),committedAt:n,source:s,summary:d,mutations:c}),"applied"}};function mn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function to(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function ni(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 Cr(o){let e=ni(to(o.origin));if(e)return e;let n=ni(to(o.referer));if(n)return n;let t=to(o["x-forwarded-host"]);if(!t)return null;let i=to(o["x-forwarded-proto"])==="https"?"https":"http";return ni(`${i}://${t}`)}function $r(o,e,n=5){let t=(d,u)=>(u.completedAt??u.startedAt)-(d.completedAt??d.startedAt),i=[...o].sort(t).slice(0,n),r=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:i,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as io}from"crypto";import{mkdir as hn,readFile as Pt,unlink as cd,writeFile as Gt}from"fs/promises";import{dirname as ro,extname as dd,join as $e}from"path";var od={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 id(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 Or(o,e){let n=e??id(o);return{kind:n,...od[n]}}function zt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function oi(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(i=>i.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}import{createHash as rd,randomUUID as sd}from"crypto";var Dr=o=>`${o}-${sd()}`;function ii(o,...e){return`${o}-${rd("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function ri(o){return{schemaVersion:1,submissionIds:[Dr("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function fn(o,e=[],n){return{...o,outcomeId:o.outcomeId??Dr("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...n?{imprintAssessment:n}:{}}}function ad(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function no(o,e){return e?[`${o||"/"}:${e}`]:[]}function Nr(o){let e=ad(o.url);return[...new Set([...o.annotations.flatMap(n=>no(n.pathname??e,n.linkedSelector)),...o.styleModifications.flatMap(n=>no(e,n.durableSelector??n.selector)),...(o.textModifications??[]).flatMap(n=>no(n.pathname??e,n.durableSelector??n.selector)),...(o.domModifications??[]).flatMap(n=>no(n.pathname??e,n.durableSelector??n.selector))])]}function Br(o,e){return[...new Set([`screenshot:${e}`,...o.annotations.map(n=>`annotation:${n.id}`),...o.annotations.flatMap(n=>(n.attachments??[]).map(t=>`attachment:${t.id}`))])]}function oo(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let n=ii("submission",o,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[n],jobId:e.jobId,threadId:o,artifactIds:[...(e.annotationIds??[]).map(t=>`annotation:${t}`),...e.screenshotPath?[ii("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:ii("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function si(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let n of o.messages)e=oo(o.id,n)||e;return e}function Jr(o){let e=o.messages.at(-1),n=[...o.messages].reverse().find(i=>i.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:o.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:o.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let t=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:n?.jobId,threadId:o.id,status:t?"waiting_input":"resolved",label:t?"Question":"Replied",outcomeId:n?.lifecycle?.outcomeId,imprintEvidenceIds:n?.lifecycle?.imprintEvidenceIds??[]}}var ld={version:1,threads:{}},Lr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],gn={version:2,updatedAt:0,files:{}};function pd(o){return JSON.stringify(o,null,2)}function ud(o){return Object.fromEntries(Lr.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function md(o){let e={...o};for(let n of Lr)delete e[n];return e}function Wt(o){let e=o;if(o.error){let n=Or(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=zt(e.result,!1),t=zt(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 so=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=$e(e,".popmelt");this.legacyFilePath=$e(n,"threads.json"),this.threadsDir=$e(n,"threads"),this.indexPath=$e(this.threadsDir,"index.json"),this.artifactsDir=$e(n,"artifacts","thread-messages"),this.mediaDir=$e(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Pt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[i,r]of Object.entries(e.files)){let s=await this.readThread($e(this.threadsDir,r));s&&(n[i]=s)}this.cache={version:1,threads:n};let t=!1;for(let i of Object.values(n))t=si(i)||t;return t&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Pt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Wt)}]))},this.index={...gn,files:{},migratedFromLegacyAt:Date.now()};for(let n of Object.values(this.cache.threads))si(n);return await this.persistAll(),this.cache}}catch{}return this.cache={...ld,threads:{}},this.index={...gn,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 i of Object.values(n.threads))if(i.elementIdentifiers.some(s=>t.has(s)))return i;return null}async createThread(e,n){let t=await this.load(),i={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,n){let i=(await this.load()).threads[e];i&&(oo(e,n),i.messages.push(Wt(n)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,n){let i=(await this.load()).threads[e];if(!i)return;oo(e,n);let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,Wt(n)):i.messages.push(Wt(n)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.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=Wt(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of n)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}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((i,r)=>r.updatedAt-i.updatedAt),t.slice(0,e).map(i=>{let s=i.messages.find(l=>l.role==="human")?.feedbackSummary||"[thread]",c=i.messages.filter(l=>l.role==="assistant"),d=l=>{if(l.role!=="assistant")return;if(l.question)return l.question;let f=l.imprintSummary?.grounding;if(f?.question&&!l.imprintSummary?.resolvedAction)return f.question},u=i.messages.findLastIndex(l=>!!d(l)),I=i.messages.findLastIndex(l=>l.role==="human"),x=u>I?d(i.messages[u]):void 0,T=i.messages.at(-1)?.role,k=Array.from(new Set(i.messages.slice(0,Math.max(0,I)).filter(l=>l.role==="assistant"&&!!l.jobId).map(l=>l.jobId))),S=c.some(l=>!!l.responseText||!!l.question||!!l.result||!!l.memoryReviewCard||!!l.memoryReceipt),p=c.some(l=>!!l.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:S,hasError:p,lastMessageRole:T,pendingQuestion:x,acknowledgedJobIds:k,elementIdentifiers:i.elementIdentifiers,lifecycle:Jr(i)}})}async recoverInterruptedTurns(){let e=await this.load(),n=0;for(let t of Object.values(e.threads)){let i=t.messages.at(-1);if(!i||i.role!=="human"||/^(imprint|memory)-/.test(i.jobId))continue;let r=fn(i.lifecycle);i.queued&&await this.updateMessage(t.id,i.jobId,{queued:!1}),await this.appendMessage(t.id,{role:"assistant",timestamp:Date.now(),jobId:i.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),n+=1}return n}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 Pt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let c=await Pt($e(ro(this.legacyFilePath),i.path),"utf8");io("sha256").update(c).digest("hex")===i.sha256&&(s=JSON.parse(c))}catch{}return Wt({...r,...s})}));return{id:n.id,lifecycleVersion:n.lifecycleVersion,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=ud(e),t=md(e);if(Object.keys(n).length===0)return t;let i=pd(n),r=io("sha256").update(i).digest("hex"),s=$e("artifacts","thread-messages",`${r}.json`);await hn(this.artifactsDir,{recursive:!0});try{await Pt($e(ro(this.legacyFilePath),s),"utf8")}catch{await Gt($e(ro(this.legacyFilePath),s),i)}return{...t,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let n=async t=>{if(ro(t)===this.mediaDir)return t;try{let i=await Pt(t),r=io("sha256").update(i).digest("hex"),s=$e(this.mediaDir,`${r}${dd(t)||".bin"}`);await hn(this.mediaDir,{recursive:!0});try{await Pt(s)}catch{await Gt(s,i)}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,i])=>[t,await n(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,i])=>[t,await Promise.all(i.map(n))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([t,i])=>[t,await Promise.all(i.map(async r=>({...r,path:await n(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await hn(this.threadsDir,{recursive:!0});let n=this.index??{...gn,files:{}},t=n.files[e.id]??`${io("sha256").update(e.id).digest("hex").slice(0,32)}.json`,i=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:i};await Gt($e(this.threadsDir,t),JSON.stringify(r,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Gt(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 hn(this.threadsDir,{recursive:!0}),this.index=this.index??{...gn,files:{}},await Gt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...gn,files:{}},t=n.files[e];t&&await cd($e(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await hn(this.threadsDir,{recursive:!0}),await Gt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as fd,open as hd,readFile as gd,rename as yd,unlink as vd}from"fs/promises";import{dirname as Id,join as wd}from"path";var qr={schemaVersion:1,theme:"auto",updatedAt:null};function Fr(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function bd(o,e){await fd(Id(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await hd(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
181
- `,"utf8"),await t.sync()}finally{await t.close()}await yd(n,o)}catch(t){throw await vd(n).catch(()=>{}),t}}var ao=class{constructor(e){this.path=wd(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await gd(this.path,"utf8")),n=Fr(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 bd(this.path,n),n}};function Ur(o){return Fr(o)!==null}function co(o){return Sd(o).slice(0,12)}var xd=[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 Sd(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Td(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let T=7;T>=0;T--)e.push(n/Math.pow(2,T*8)&255);let t=1779033703,i=3144134277,r=1013904242,s=2773480762,c=1359893119,d=2600822924,u=528734635,I=1541459225,x=new Array(64);for(let T=0;T<e.length;T+=64){for(let b=0;b<16;b++){let g=T+b*4;x[b]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])>>>0}for(let b=16;b<64;b++){let g=Ze(x[b-15],7)^Ze(x[b-15],18)^x[b-15]>>>3,J=Ze(x[b-2],17)^Ze(x[b-2],19)^x[b-2]>>>10;x[b]=x[b-16]+g+x[b-7]+J>>>0}let k=t,S=i,p=r,l=s,f=c,m=d,h=u,j=I;for(let b=0;b<64;b++){let g=Ze(f,6)^Ze(f,11)^Ze(f,25),J=f&m^~f&h,E=j+g+J+xd[b]+x[b]>>>0,R=Ze(k,2)^Ze(k,13)^Ze(k,22),N=k&S^k&p^S&p,V=R+N>>>0;j=h,h=m,m=f,f=l+E>>>0,l=p,p=S,S=k,k=E+V>>>0}t=t+k>>>0,i=i+S>>>0,r=r+p>>>0,s=s+l>>>0,c=c+f>>>0,d=d+m>>>0,u=u+h>>>0,I=I+j>>>0}return[t,i,r,s,c,d,u,I].map(T=>T.toString(16).padStart(8,"0")).join("")}function Ze(o,e){return o>>>e|o<<32-e}function Td(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}function Pd(o){let e=o.instruction?.trim();return e?o.attachments?.some(t=>t.name?.trim()===e)?null:e:null}function zr(o){let e=o.annotations.flatMap(i=>{let r=Pd(i);return r?[{instruction:r,pathname:i.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(i=>i.pathname).filter(Boolean)).size<=1)return e.map(i=>i.instruction).join(`
182
-
183
- `);let t=new Map;for(let i of e){let r=i.pathname||"(unknown)",s=t.get(r)??[];s.push(i.instruction),t.set(r,s)}return[...t.entries()].map(([i,r])=>`\`${i}\`
171
+ 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.`;var Er=`## Project collaboration history
172
+ Popmelt's durable collaboration history lives in the project's \`.popmelt\` directory. High-confidence relevant Imprint explanations may already be surfaced elsewhere in this prompt. Start with that supplied Imprint context and use it directly when it adequately answers the developer's question. For questions about the current implementation, inspect the relevant source only as needed to confirm how that understanding is expressed.
173
+
174
+ For answer-only or explanation-only requests, use a narrow default evidence budget: begin with the supplied Imprint, inspect the selected component once, and inspect at most one directly surrounding layout source only if the component does not adequately explain the observation. Explain the dominant visible phenomenon rather than auditing every property in the screenshot. Stop once the answer is supported. Broaden beyond that only when evidence conflicts, the selected target remains materially ambiguous, or the developer explicitly asks for a comprehensive audit.
175
+
176
+ Search raw \`.popmelt\` records only when the supplied Imprint context is insufficient, when evidence conflicts, or when the developer explicitly asks about provenance, prior discussions or feedback, related work, history, or evolution over time. When raw history is needed, search narrowly using the available selector, React component, route, visible text, source identifier, and terms from the developer's question. Relevant evidence may live in thread records, memory journals, or Imprint data. Avoid generated screenshots and binary artifacts unless the developer asks for visual history.
177
+
178
+ Use Popmelt history to explain why a decision was made or how shared understanding developed. Use git history only when the question depends on chronology or source provenance. Clearly distinguish recorded human or collaboration evidence from your own inference.
179
+
180
+ Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function hn(i,e,t){let n=[];if(i.annotations.length>0){n.push("## Annotations");for(let o of i.annotations){let r=o.elements.map(l=>{let w=[l.selector];return l.reactComponent&&w.push(`(${l.reactComponent})`),w.join(" ")}).join(", "),s=o.instruction||"No text";n.push(`- id=${o.id} [${o.type}] ${s} \u2192 Elements: ${r||"none"}`);let c=e?.[o.id];if(c&&c.length>0)for(let l of c)n.push(` Attached image: use the Read tool to view ${l}`);let d=t?.[o.id];if(d?.length)for(let l of d)n.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(i.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 o of i.styleModifications){let r=o.element?.reactComponent?`(${o.element.reactComponent})`:"";for(let s of o.changes)n.push(`- ${o.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(i.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 o of i.textModifications){let r=o.element?.reactComponent?`(${o.element.reactComponent})`:"",s=JSON.stringify(o.original),c=JSON.stringify(o.modified),d=o.textNodePath.length>0?` textNodePath=${o.textNodePath.join(".")}`:"";n.push(`- ${o.selector} ${r}${d}: ${s} \u2192 ${c}`)}}if(i.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 o of i.domModifications){let r=o.element?.reactComponent?`(${o.element.reactComponent})`:"",s=o.sourceElement?.reactComponent?` from ${o.sourceSelector} (${o.sourceElement.reactComponent})`:o.sourceSelector?` from ${o.sourceSelector}`:"",c=o.referenceSelector?` ${o.placement} ${o.referenceSelector}`:` at index ${o.targetIndex}`;n.push(`- ${o.operation}: ${o.selector} ${r}${s} \u2192 ${o.targetParentSelector}${c}`)}}if(i.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 o of i.spacingTokenChanges){n.push(`
181
+ ### ${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`);for(let r of o.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} ${o.originalPx}px \u2192 ${o.newPx}px`),n.push(` class="${r.className}"`)}}}if(i.inspectedElement){let o=i.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[o.selector];o.reactComponent&&r.push(`(${o.reactComponent})`),o.context&&r.push(`in ${o.context}`),o.textContent&&r.push(`"${o.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
182
+ `)}function _r(i,e,t){let n=[],r=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!r&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let c of t.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${c.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),c.feedbackSummary&&n.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&n.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${c.question}"`);else{if(n.push(`### Round ${s} (assistant)`),c.responseText&&n.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,w=l?` [${l.breadth} ${l.target}]`:"";n.push(`- ${d.annotationId}: ${d.status}${w} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&n.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&n.push(`Tools used: ${c.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t?.designModel){n.push(""),n.push("## Established Design Policies"),n.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=t.designModel.rules;if(Array.isArray(s)&&s.length>0)if(n.push(""),n.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let w=new Map;for(let b of s)if(typeof b=="object"&&b!==null&&"text"in b){let P=b,R=P.scope||"general";w.has(R)||w.set(R,[]),w.get(R).push(P.text)}for(let[b,P]of w){n.push(`**${b.charAt(0).toUpperCase()+b.slice(1)}**`);for(let R of P)n.push(`- ${R}`)}}else for(let w of s)typeof w=="string"&&n.push(`- ${w}`);let c=t.designModel.tokens;c&&typeof c=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(c,null,2)),n.push("```"));let d=t.designModel.components;d&&typeof d=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```")),n.push(""),n.push("### Applied Model-Gap Details"),n.push("Only when you actually modify the project and implement 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), describe that applied gap:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you actually implemented (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),n.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(n.push(""),n.push("## Design Context"),n.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),r){let s=t?.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)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of c){n.push(""),n.push(`## Page: ${d}`);let w=s[d];w&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${w}`):!w&&t?.provider!=="codex"&&(Object.keys(s).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${i}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let b={...e,annotations:l,styleModifications:e.styleModifications},P=hn(b,t?.imagePaths,t?.attachmentFiles);P&&(n.push(""),n.push(P))}}else{let s=hn(e,t?.imagePaths,t?.attachmentFiles);s&&(n.push(""),n.push(s))}return n.push(""),n.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."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),n.push("<resolution>"),n.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),n.push("</resolution>"),n.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
183
+ `)}function Cr(i){return i.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function $r(i,e,t,n){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),t!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(o.push(""),o.push(r.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(o.push(`### Round ${s} (human) \u2014 reply`),o.push(`"${c.replyToQuestion}"`)):(o.push(`### Round ${s} (human)`),c.feedbackSummary&&o.push(`Annotations: ${c.feedbackSummary}`))):c.question?(o.push(`### Round ${s} (assistant) \u2014 question`),o.push(`"${c.question}"`)):(o.push(`### Round ${s} (assistant)`),c.responseText&&o.push(`Response: ${c.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let s of n)o.push(`Attached image: use the Read tool to view the image at: ${s}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),o.push("<resolution>"),o.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),o.push("</resolution>"),o.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
184
+ `)}function Gc(i){if(typeof i!="object"||i===null)return!1;let e=i;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function Vc(i){if(typeof i!="object"||i===null||typeof i.annotationId!="string"||i.status!=="resolved"&&i.status!=="needs_review"||typeof i.summary!="string")return!1;let e=i;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!Gc(e[t]))return!1;return!0}function Or(i){let t=[...i.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!t)return[];try{let n=JSON.parse(t);return(Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.annotations)?n.annotations:[]).filter(Vc)}catch{return[]}}function Kc(i){let e=i.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(n=>{if(typeof n!="object"||n===null)return!1;let o=n;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}function Dr(i,e){return e>0?Kc(i):[]}import{execFile as Qc}from"child_process";import{readdir as Xc,readFile as Yc,stat as Zc}from"fs/promises";import{homedir as gn}from"os";import{join as et}from"path";var ni=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Nr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Nr()}],yn=[{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"}],vn={id:"",label:"Default",source:"cli"},ed=/^\s*-\s+"([^"]+)"/;function td(i){let e=[],t=!1;for(let n of i.split(`
185
+ `)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let o=n.match(ed);if(!o?.[1])continue;let r=o[1];e.push({id:r,label:ao(r),source:"cli"})}return ii([vn,...e])}function nd(i){let e=JSON.parse(i);return(Array.isArray(e.models)?e.models:[]).filter(n=>n.visibility===void 0||n.visibility==="list").sort((n,o)=>{let r=typeof n.priority=="number"?n.priority:Number.MAX_SAFE_INTEGER,s=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(n=>{let o=typeof n.slug=="string"?n.slug:typeof n.id=="string"?n.id:"";if(!o)return[];let r=typeof n.display_name=="string"&&n.display_name.trim()?n.display_name.trim():ao(o),s=Array.isArray(n.supported_reasoning_levels)?n.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(n.service_tiers)?n.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:o,label:r,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function Nr(){return["low","medium","high","xhigh","max"].map(i=>({effort:i}))}function id(i){let e=i.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return ii(e.map(t=>({id:t,label:ao(t),source:"cli"})))}function ao(i){if(!i)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"},t=i.replace(/-\d{8,}$/,"");if(e[i])return e[i];if(e[t])return e[t];let n=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(n){let r=n[1]==="sonnet"?"Sonn":ad(n[1]),s=n[2]&&n[3]?` ${n[2]}.${n[3]}`:"";return`${r}${s}${n[4]?" Fast":""}`}let o=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let r=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${r}`:o[3]==="codex"?`Codex ${r}`:o[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return t}async function Br(i="copilot"){let e=await ti(i,["help","config"]),t=td(e);return t.length>1?t:[vn]}async function Jr(i="codex"){let e=await ti(i,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||et(gn(),".codex");return qr(et(n,"models_cache.json"))}),t=nd(e);return t.length>0?ii([...t,...yn]):yn}async function Lr(i="claude"){let e=et(gn(),".claude"),t=[et(gn(),".claude","stats-cache.json"),et(gn(),".claude","settings.json"),et(gn(),".claude.json"),et(e,"cache","changelog.md")],[n,o,r]=await Promise.all([ti(i,["--help"]).catch(()=>""),ti(i,["--version"]).catch(()=>""),od(e).catch(()=>[])]),s=sd([...t,...r]),c=await Promise.all(s.map(l=>qr(l).catch(()=>""))),d=id([n,o,...c].join(`
186
+ `));return ii([...ni,...d])}function ti(i,e,t=5e3){return new Promise((n,o)=>{Qc(i,e,{encoding:"utf-8",timeout:t},(r,s)=>{if(r){o(r);return}n(s)})})}async function qr(i){return Yc(i,"utf-8")}async function od(i){let e=[et(i,"projects"),et(i,"telemetry")],t=[];for(let n of e)await Fr(n,t,4);return t.sort((n,o)=>o.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function Fr(i,e,t){if(t<0)return;let n;try{n=await Xc(i,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async o=>{let r=et(i,o.name);if(o.isDirectory()){await Fr(r,e,t-1);return}if(!(!o.isFile()||!rd(o.name)))try{let s=await Zc(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function rd(i){return i.endsWith(".json")||i.endsWith(".jsonl")||i.endsWith(".md")||i.endsWith(".txt")}function ii(i){let e=new Set,t=[];for(let n of i)e.has(n.id)||(e.add(n.id),t.push(n));return t}function sd(i){return[...new Set(i)]}function ad(i){return i.charAt(0).toUpperCase()+i.slice(1)}var oi=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,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let t=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){t=r;break}}let n=t>=0?t+1:0,o=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),o}hasActiveThread(e){return this.allActive.some(t=>t.threadId===e)}getQueuedThreadJob(e,t){return this.queue.find(n=>n.threadId===e&&(!t||t(n)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){let o=this.bufferEvent(t,e);for(let r of this.listeners)r(o,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let o={...t,seq:n.nextSeq++};return n.events.push(o),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),o}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(c=>c.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...o},jobActive:r}}accumulateText(e,t,n){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[t]+=n}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,n)}cancelJob(e){let t=this.activeProcesses.get(e),n=this.activeJobs.get(e);return!t||!n?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:"Cancelled by user",cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let t of e)this.cancelJob(t);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 t=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),t.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let n of t)try{n.kill("SIGTERM")}catch{}await Promise.all(t.map(n=>new Promise(o=>{let r=!1,s=()=>{r||(r=!0,o())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!r){try{n.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);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(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),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 st}from"crypto";import{createHash as cd}from"crypto";import{mkdir as dd,open as ld,readFile as Ur,readdir as pd,rename as ud,unlink as md}from"fs/promises";import{dirname as fd,join as Wt}from"path";function $e(i){return structuredClone(i)}function zr(i){return cd("sha256").update(JSON.stringify(i)).digest("hex")}async function Rt(i,e){await dd(fd(i),{recursive:!0});let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await ld(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
187
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await ud(t,i)}catch(o){throw await md(t).catch(()=>{}),o}}function hd(i,e){return{version:1,projectId:i,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function gd(i,e){let t=i.explanations.findIndex(n=>n.id===e.id);t>=0?i.explanations[t]=$e(e):i.explanations.push($e(e))}function ri(i,e){let t=$e(i);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(o=>o.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push($e(n.explanation))}else if(n.op==="replace_explanation")gd(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(o=>o.id!==n.explanationId),t.relations=t.relations.filter(o=>o.fromId!==n.explanationId&&o.toId!==n.explanationId);else if(n.op==="add_concrete")t.concrete.some(o=>o.id===n.concrete.id)||t.concrete.push($e(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(o=>o.id!==n.concreteId),t.relations=t.relations.filter(o=>o.fromId!==n.concreteId&&o.toId!==n.concreteId);else if(n.op==="add_evidence"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);o.evidence.some(r=>r.id===n.evidence.id)||(o.evidence.push($e(n.evidence)),o.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(o,$e(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let o=n.relation,r=t.explanations.find(l=>l.id===o.fromId),s=t.explanations.find(l=>l.id===o.toId),c=t.concrete.some(l=>l.id===o.fromId),d=t.concrete.some(l=>l.id===o.toId);if(lr(o.type)){if(!(o.type==="expresses"?!!((r||c)&&s):!!(r&&s)))throw new Error(`Imprint ${o.type} relation has invalid endpoints: ${o.id}`);if(t.relations.some(w=>w.type===o.type&&w.fromId===o.fromId&&w.toId===o.toId))throw new Error(`Duplicate imprint relation: ${o.type}:${o.fromId}:${o.toId}`);if(o.type==="expresses"&&r&&s){if(Nt(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${o.id}`);let w=new Map;for(let R of t.relations)R.type==="expresses"&&w.set(R.fromId,[...w.get(R.fromId)??[],R.toId]);let b=[o.toId],P=new Set;for(;b.length;){let R=b.pop();if(R===o.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${o.id}`);P.has(R)||(P.add(R),b.push(...w.get(R)??[]))}}}else if(!r||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${o.id}`);t.relations.some(l=>l.id===o.id)||t.relations.push($e(o))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(o=>o.id!==n.relationId));return t}function yd(i,e){let t=[],n=$e(i);for(let o of e){if(o.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:o.explanation.id});else if(o.op==="remove_explanation"){let r=n.explanations.find(s=>s.id===o.explanationId);r&&t.unshift({op:"add_explanation",explanation:$e(r)})}else if(o.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:o.concrete.id});else if(o.op==="remove_concrete"){let r=n.concrete.find(s=>s.id===o.concreteId);r&&t.unshift({op:"add_concrete",concrete:$e(r)})}else if(o.op==="replace_explanation"||o.op==="revise_explanation"||o.op==="add_evidence"){let r=o.op==="replace_explanation"?o.explanation.id:o.explanationId,s=n.explanations.find(c=>c.id===r);s&&t.unshift({op:"replace_explanation",explanation:$e(s)})}else if(o.op==="add_relation")t.unshift({op:"remove_relation",relationId:o.relation.id});else if(o.op==="remove_relation"){let r=n.relations.find(s=>s.id===o.relationId);r&&t.unshift({op:"add_relation",relation:$e(r)})}n=ri(n,[o])}return t}function Wr(i){return i.op==="add_explanation"||i.op==="replace_explanation"?[i.explanation.id]:i.op==="remove_explanation"||i.op==="add_evidence"||i.op==="revise_explanation"?[i.explanationId]:i.op==="add_relation"?[i.relation.fromId,i.relation.toId]:[]}var Ht=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Wt(e,".popmelt","imprint"),this.manifestPath=Wt(this.imprintDir,"manifest.json"),this.graphPath=Wt(this.imprintDir,"graph.json"),this.journalDir=Wt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Ur(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 t=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:t,updatedAt:t,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),n=(await pd(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),o=hd(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<n.length;c++){let d=JSON.parse(await Ur(Wt(this.journalDir,n[c]),"utf8")),{hash:l,...w}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==zr(w))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);o=ri(o,d.mutations),o.updatedAt=d.committedAt,o.head={sequence:d.sequence,hash:d.hash},r.push(d),s=d.hash}return{graph:o,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:Pt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=Pt(t.graph),o=new Map(n.relations.map(s=>[s.id,s])),r=[];for(let s of t.graph.relations){let c=o.get(s.id);c&&c.type===s.type&&c.fromId===s.fromId&&c.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),c&&r.push({op:"add_relation",relation:c}))}if(r.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await Rt(this.graphPath,n),await Rt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(b=>b.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let o=n.graph.head.sequence+1,r=yd(n.graph,e.mutations),s={version:1,sequence:o,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:zr(s)},d=ri(n.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:o,hash:c.hash};let l=`${String(o).padStart(12,"0")}-${e.transactionId}.json`;await Rt(Wt(this.journalDir,l),c);let w={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Rt(this.graphPath,d),await Rt(this.manifestPath,w),t={graph:d,transaction:c}}),await this.writeChain,t}async undo(e,t,n,o){let r=await this.load(),s=r.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(Wr));if(r.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(w=>Wr(w).some(b=>c.has(b)))))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:o,committedAt:n,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Rt(this.graphPath,e.graph),await Rt(this.manifestPath,{version:1,topologyVersion:2,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var vd=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Id=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only","consistent","match","matched","matching","mirror","mirrored","mirroring","align","aligned","aligning"]),wd=[/\bconsistent\s+with\b/i,/\bmatch(?:es|ed|ing)?\b/i,/\bmirror(?:s|ed|ing)?\b/i,/\bthe\s+same\s+as\b/i,/\bborrow(?:s|ed|ing)?\s+from\b/i,/\balign(?:s|ed|ing)?\s+with\b/i,/\b(?:more|look|looks|feel|feels|behave|behaves)\s+like\b/i],bd=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function lo(i){return!!(i&&bd.test(i))}function xd(i){return i.scope.kind==="project"||lo(`${i.statement} ${i.rationale}`)}function Sd(i){let e=i?.scope.values.filter(t=>t!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function Td(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Pd(i){return i.length>4&&i.endsWith("ies")?[i,`${i.slice(0,-3)}y`]:i.length>3&&i.endsWith("s")&&!i.endsWith("ss")?[i,i.slice(0,-1)]:[i]}function rt(i){return new Set(Td(i).split(" ").filter(e=>e.length>2&&!Id.has(e)).flatMap(Pd))}function Hr(i){return i.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function kd(i){if(i)for(let e of wd){let t=e.exec(i);if(!t||t.index<=0)continue;let n=Hr(i.slice(0,t.index)),o=Hr(i.slice(t.index+t[0].length));if(n&&o)return{target:n,reference:o}}}function ht(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function co(i){return!i||!Array.isArray(i.values)||i.values.length===0?{kind:"project",values:["*"]}:{kind:i.kind,values:[...new Set(i.values.map(e=>e.trim()).filter(Boolean))]}}function gt(i,e,t){return{id:st(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:i.threadId,jobId:i.jobId,createdAt:i.occurredAt??new Date().toISOString()}}function ve(i,e=800){return typeof i=="string"?i.trim().slice(0,e):""}function Gr(i){if(!i||typeof i!="object"||Array.isArray(i))return;let e=i;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function Vr(i,e){if(!i||!e.trim())return{found:!1};let t=i;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let o=Number(n);if(!Number.isInteger(o)||o<0||o>=t.length)return{found:!1};t=t[o]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function si(i,e={}){let t=[...i.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=i.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),o=t.at(-1)?.[1],r,s=[];if(o)r=o;else{let d=[...i.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:n,error:"imprint assessment is missing"};try{let l=JSON.parse(d);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let w=l;r=w.imprint,s=Array.isArray(w.annotations)?w.annotations:[]}catch{return{visibleText:n,error:"resolution envelope is invalid"}}}try{let c=typeof r=="string"?JSON.parse(r):r;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("imprint assessment is invalid");if(c.decision==="none"){let f=String(c.reason);if(!vd.has(f))throw new Error("imprint no-op reason is invalid");if(f==="task_specific_detail"&&s.some(E=>{if(!E||typeof E!="object"||Array.isArray(E))return!1;let j=E;return(j.finalScope??j.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let p=Array.isArray(c.usedExplanationIds)?c.usedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],y=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],m=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...p,...y])].some(E=>!m.has(E)))throw new Error("imprint use must cite only surfaced explanations");let M=[...new Set([...p,...e.applicationOccurred?[]:y])],g=e.applicationOccurred?y:[],u;if(g.length){u=g;let E=new Set(e.context?.pendingGroundingExplanationIds??[]),j=g.filter(T=>{let O=e.context?.explanations.find(H=>H.id===T);return m.has(T)&&O&&(O.state==="emerging"||O.state==="testing")&&!E.has(T)});if(j.length){let T=c.grounding,O=typeof T?.explanationId=="string"&&j.includes(T.explanationId)?T.explanationId:j[0],H=ve(T?.question,300);return{draft:{decision:"apply",summary:{title:ve(c.summary?.title,120)||"Applied shared understanding",detail:ve(c.summary?.detail,500)||ve(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:g,grounding:{explanationId:O,question:H||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(f==="duplicate"){let E=ve(c.duplicateOfExplanationId,100),j=c.scopeComparison;if(!E)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(j!=="equivalent"&&j!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let T=e.context?.explanations.find(O=>O.id===E);if(!T)throw new Error("duplicate assessment must cite a surfaced explanation");if(lo(e.requestText)&&!xd(T))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:f,duplicateOfExplanationId:E,scopeComparison:j,...M.length?{usedExplanationIds:M}:{},...u?{appliedExplanationIds:u}:{}},visibleText:n}}return{draft:{decision:"none",reason:f,...M.length?{usedExplanationIds:M}:{},...u?{appliedExplanationIds:u}:{}},visibleText:n}}if(c.decision==="recognize"){let f=ve(c.explanationId,100);if(!f)throw new Error("recognition requires explanationId");let p=e.context?.explanations.find(h=>h.id===f);if(!p)throw new Error("recognition must cite a surfaced explanation");if(p.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let y=c.summary,m={title:ve(y?.title,120),detail:ve(y?.detail,500)};if(!m.title||!m.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:f,summary:m},visibleText:n}}if(c.decision==="apply"){let f=c.summary,p={title:ve(f?.title,120),detail:ve(f?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let y=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[];if(!y.length)throw new Error("application requires appliedExplanationIds");let m=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(y.some(E=>!m.has(E)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(y)]},visibleText:n};let h=new Set(e.context?.pendingGroundingExplanationIds??[]),M=y.filter(E=>{let j=m.get(E);return j&&(j.state==="emerging"||j.state==="testing")&&!h.has(E)});if(!M.length){if(y.every(j=>m.get(j)?.state==="grounded"||h.has(j)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:y},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let g=c.grounding,u=typeof g?.explanationId=="string"&&M.includes(g.explanationId)?g.explanationId:M[0];return{draft:{decision:"apply",summary:p,appliedExplanationIds:y,grounding:{explanationId:u,question:ve(g?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(c.decision!==void 0&&c.decision!=="mutate")throw new Error("imprint decision is invalid");let d=c.summary,l=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let w={kind:l,title:ve(d?.title,120),detail:ve(d?.detail,500)};if(!w.title||!w.detail)throw new Error("summary title and detail are required");let b=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],P=[];for(let f of Array.isArray(c.mutations)?c.mutations:[]){if(!f||typeof f!="object")continue;let p=f;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let y=ve(p.statement),m=ve(p.rationale);if(!y||!m)continue;P.push({op:"add",clientId:ve(p.clientId,100)||void 0,kind:p.kind,statement:y,rationale:m,scope:Gr(p.scope),rootReason:ve(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let y={op:"revise",explanationId:p.explanationId,statement:ve(p.statement)||void 0,rationale:ve(p.rationale)||void 0,scope:Gr(p.scope),reopenGrounding:p.reopenGrounding===!0};(y.statement||y.rationale||y.scope||y.reopenGrounding)&&P.push(y)}else if(p.op==="evidence"&&typeof p.explanationId=="string"&&["supports","challenges","excepts"].includes(String(p.stance))){let y=ve(p.summary);y&&P.push({op:"evidence",explanationId:p.explanationId,stance:p.stance,summary:y})}else if(p.op==="relation"&&typeof p.fromId=="string"&&typeof p.toId=="string"&&["expresses","excepts"].includes(String(p.type))){let y=ve(p.rationale);if(!y)continue;P.push({op:"relation",type:p.type,fromId:p.fromId,toId:p.toId,rationale:y})}else if(p.op==="supersede"&&typeof p.explanationId=="string"&&typeof p.replacementId=="string"){let y=ve(p.reason);y&&P.push({op:"supersede",explanationId:p.explanationId,replacementId:p.replacementId,reason:y})}else if(p.op==="bind_concrete"&&typeof p.explanationId=="string"){let y=ve(p.modelPath,300);y&&P.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:y,rationale:ve(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&P.push({op:"retire",explanationId:p.explanationId,reason:ve(p.reason)})}let R=c.grounding,S=R&&typeof R.explanationId=="string"&&ve(R.question)?{explanationId:R.explanationId,question:ve(R.question,300)}:void 0;return{draft:{decision:"mutate",summary:w,appliedExplanationIds:b,mutations:P,grounding:S},visibleText:n}}catch(c){return{visibleText:n,error:c instanceof Error?c.message:String(c)}}}function ai(i,e={}){let t=i?.explanations??[],n=new Set(i?.pendingGroundingExplanationIds??[]),o=new Set(i?.correctionExplanationIds??[]),r=lo(e.requestText),s=i?.retrievalIntent,c=i?.historicalCaveats??[];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.",...t.length?["","Relevant explanations from the project imprint:",...t.map((d,l)=>[`${l+1}. [${d.state}; ${d.kind}] ${d.statement}`,` - Why: ${d.rationale}`,` - Scope: ${d.scope.kind} ${d.scope.values.join(", ")}`,` - Explanation: ${d.id}`,...n.has(d.id)?[" - Grounding: already pending; do not ask again"]:[],...o.has(d.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...d.concrete.map(w=>` - Concrete terminal: ${w.modelPath} = ${JSON.stringify(w.value)}`)].join(`
188
+ `)),...i?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...i?.relations?.length?["","Known explanation topology:",...i.relations.map(d=>`- ${d.fromId} --${d.type}--> ${d.toId}: ${d.rationale}`)]:[],...s?["","Explicit pattern transfer detected:",`- Target: ${s.target}`,`- Reference: ${s.reference}`,"Before editing, state which dimensions you intend to transfer from the reference and which target-specific behavior you will preserve. Compare the relevant surface, spacing, typography, radius, and interaction behavior; transfer only the dimensions supported by the request and evidence. If the intended transfer remains materially ambiguous after inspecting both anchors, ask one focused question."]:[],...c.length?["","Directly relevant challenged history (historical caveats, not current Imprint truth):",...c.map((d,l)=>[`${l+1}. [challenged; ${d.kind}] ${d.statement}`,` - Why it was previously proposed: ${d.rationale}`,` - Scope: ${d.scope.kind} ${d.scope.values.join(", ")}`,` - Historical explanation: ${d.id}`].join(`
189
+ `)),"Use these caveats only to avoid repeating a rejected or over-broad transfer. Do not cite them as usedExplanationIds or treat them as active guidance."]:[],"","Work normally and preserve developer agency. A testing explanation may guide action as a hypothesis without asking permission first. An emerging explanation is observation-only: use it to recognize recurrence, not to choose behavior. If the developer independently repeats an emerging observation in a meaningfully different occurrence, that new application may promote it into testing and request grounding. Silence is not confirmation.","Assess learning proactively as part of completing every thread. Do not wait for the developer to ask whether there was a learning. Before choosing none, look one abstraction level above the exact edit and ask: would the reasoning behind this outcome change how a future agent handles a meaningfully different occurrence?","The developer's original annotation, ordinary instruction, scope language, and later corrections are already human-supplied evidence. They can support learning when they establish a reusable dependency, boundary, or rationale; a separate post-completion learning prompt is not required. Mere acceptance of completed work is still insufficient.","The default outcome is no imprint mutation. Completing work or making a successful design choice does not by itself constitute learning.","Application evidence is distinct from changing shared understanding. When an emerging or testing explanation materially influenced a completed action, report decision apply even when no explanation wording changed.","Applying grounded understanding does not mutate the graph. Usually report none. Use decision recognize only when visibly acknowledging the grounded explanation closes a correction loop or otherwise makes consequential reuse legible to the developer. Recognition must cite one exact surfaced grounded explanation ID; never infer or invent an ID.","Application and recognition are whole-statement operations. Cite an existing explanation only when the completed behavior is compatible with every material clause, its scope, and its exceptions. Sharing one useful clause is not a match. If the durable behavior is narrower, add one atomic explanation linked to the broader explanation when the admission tests pass; otherwise report none.","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.","Relationship-first admission: before calling any completed change task-specific, compare its requested behavior and effective scope with every surfaced explanation that could plausibly govern the same subject or treatment. The developer does not need to name an Imprint concept or relation. Infer the relationship from the ordinary instruction, the annotated context, the implementation, and the surfaced explanations.","A narrower completed behavior that departs from an applicable broader explanation establishes an applicability boundary even when the developer did not say exception. Add one narrow testing explanation and link it to the broader rule with excepts. If the behaviors concern distinct concepts rather than the same rule, assess the reusable behavior as a sibling explanation instead. Do not manufacture an exception merely because implementations differ.","Scope and Imprint assessment must agree. If any resolved annotation has an effective inferred or final breadth of pattern, do not classify the Imprint decision as task_specific_detail. Either capture the reusable conceptual change, report application of existing understanding, cite a valid duplicate, or use another accurate no-op reason. The bridge rejects pattern-scoped task_specific_detail assessments.","","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 anywhere in the thread, including the original instruction, not merely acceptance of completed work or the model's own implementation choice.","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. Distinguish mechanics from the reusable reasoning they may reveal: a CSS property alone is not learning, but a human-directed causal rule such as keeping optical adjustment out of layout geometry may be. This heuristic never overrides relationship-first admission: a small local change that narrows or contradicts an applicable surfaced explanation may establish an exception or correction. A task-specific edit otherwise becomes learning only if the human establishes a reusable dependency, applicability boundary, 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.","Duplicate means the same reusable claim is already represented at an equivalent or broader conceptual scope. Shared code, a centralized component, or implementation reuse does not establish conceptual duplication. A narrower component-, route-, selector-, or file-scoped explanation is not a duplicate of newly broadened applicability.","Words such as all, every, across, throughout, globally, and project-wide are explicit applicability signals. When the human broadens a grounded explanation, preserve the grounded narrower explanation and add a broader testing explanation. Link the narrower explanation to the broader one with expresses. Do not substitute another no-op reason for that scope change.",...r?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"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.","When an explanation is marked Correction in the supplied context, the developer selected No but the graph has not yet been changed. Interpret the current reply before mutating anything. Decide whether it corrects only the implementation result, the explanation scope, or the reasoning. Do not challenge the whole explanation for a narrow correction, and do not recognize a different explanation merely because one clause overlaps.","Topology assessment is mandatory for every add mutation. Imprint topology has exactly two relation types: expresses and excepts. expresses always points from the more specific, concrete, or lower-level explanation to the more abstract explanation it expresses. excepts points from the narrower exception to the rule whose applicability it limits. Support and challenge belong in evidence; correction belongs in supersede; neither is a topology relation. If an addition is genuinely a new root with no meaningful relative, include rootReason 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 with expresses or excepts. Multiple specific explanations may express the same parent, and one explanation may express multiple parents; never create an expresses cycle.","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 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. The bridge supplies a fallback question when the application is otherwise valid.","","At the end, emit exactly one machine-readable <resolution> envelope after the normal response. Its `annotations` array reports annotation outcomes, and its required `imprint` field completes the learning assessment. The envelope is hidden from the developer. Do not emit a separate <imprint> block.",'As soon as one or more surfaced explanations become actively useful during the work, emit `<imprint-use>{"explanationIds":["<every actively useful surfaced explanation id>"]}</imprint-use>` immediately. This live receipt is hidden from conversational prose. Emit it at the point of use rather than waiting for the final response. Emit a later marker only when additional explanations become actively useful. Never emit it for explanations that were merely retrieved, read, searched, or considered.',"Treat Imprint as actively useful when a surfaced explanation materially informs an answer, recommendation, implementation choice, or other decision. Whenever it is actively useful, always cite every materially used surfaced explanation in `usedExplanationIds`. This produces a usage receipt only; it does not strengthen or mutate shared understanding. Do not cite explanations that were merely retrieved, read, or considered but did not influence the result.","`appliedExplanationIds` is narrower: include an explanation there only when it governed a completed implementation or other observable action that genuinely tests the explanation. Never use `appliedExplanationIds` for an answer-only, informational, research, or read-only request. An explanation may be used without being applied; every applied explanation is also understood to be used.","For no learning, include:",'"imprint":{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change","usedExplanationIds":["<every surfaced explanation that was actively useful, or omit when none>"]}',"A no-op reason cannot suppress genuine application evidence. When a completed action was governed by an ungrounded explanation, report decision apply directly so the summary and grounding question are intentional. Answering a question with that explanation is usage, not application.","When and only when reason is duplicate, also include `duplicateOfExplanationId` naming one surfaced explanation and `scopeComparison` set to `equivalent` or `existing_broader`. The bridge rejects uncited duplicates and duplicates whose cited explanation cannot cover explicit broadening language.","For application evidence without a conceptual change, include:",'"imprint":{"decision":"apply","summary":{"title":"<short expandable-summary title>","detail":"<how the explanation influenced this completed action>"},"appliedExplanationIds":["<surfaced emerging or testing explanation id>"],"grounding":{"explanationId":"<one applied id>","question":"<brief post-application confirmation question>"}}',"For a consequential, non-mutating reuse of grounded understanding that should be visible, include:",'"imprint":{"decision":"recognize","explanationId":"<one exact surfaced grounded explanation id>","summary":{"title":"<short name for the recognized understanding>","detail":"<how it guided this outcome>"}}',"Or, only after every admission test passes for a conceptual change:",'"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":"expresses|excepts","fromId":"<specific id or clientId>","toId":"<abstract rule 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 expresses the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}','The final shape is `<resolution>{"annotations":[...],"imprint":{...}}</resolution>`. The `imprint` field is required even when the decision is none; omission leaves the completed run explicitly unassessed.',"Include only mutation objects actually needed. A new explanation established through completed implementation must include its clientId in appliedExplanationIds; the bridge also derives this application from a completed change as a safeguard. Applying a grounded explanation never requires a mutation, but actively using it still requires its id in appliedExplanationIds. Never claim that a new explanation is grounded."].join(`
190
+ `)}var Gt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Ht(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let t=rt(e.text??""),n=rt((e.subjectHints??[]).join(" ")),o=kd(e.text),r=rt(o?.target??""),s=rt(o?.reference??""),c=new Set(e.pendingGroundingExplanationIds??[]),d=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!c.size&&!d.size)return;let{graph:l}=await this.store.load(),w=l.explanations.filter(g=>g.state!=="retired"&&(g.state!=="challenged"||d.has(g.id))).map(g=>{let u=rt([g.statement,g.rationale].join(" ")),E=rt(g.scope.values.join(" ")),j=ht(u,t),T=ht(E,t),O=ht(E,n),H=ht(u,n),K=j+T*.2+O*.25+H*.75+(g.state==="grounded"?.08:0)+(c.has(g.id)?1:0)+(d.has(g.id)?1:0),G=c.has(g.id)||d.has(g.id)||j>=.12||T>=.5||O>=.2||H>=.2;return{item:g,score:K,relevant:G}}).filter(g=>g.relevant&&g.score>=.18).sort((g,u)=>u.score-g.score||u.item.updatedAt.localeCompare(g.item.updatedAt)),b=Math.max(1,e.maxExplanations??6),P=g=>l.explanations.filter(u=>u.state!=="retired"&&u.state!=="challenged").map(u=>{let E=ht(rt(`${u.statement} ${u.rationale}`),g),j=ht(rt(u.scope.values.join(" ")),g);return{item:u,score:E+j*.35+(u.state==="grounded"?.08:0)}}).filter(u=>u.score>=.18).sort((u,E)=>E.score-u.score||E.item.updatedAt.localeCompare(u.item.updatedAt)),R=[],S=g=>{R.length<b&&!R.some(u=>u.id===g.id)&&R.push(g)};if(o&&(P(r).slice(0,2).forEach(({item:g})=>S(g)),P(s).slice(0,2).forEach(({item:g})=>S(g))),w.forEach(({item:g})=>S(g)),!R.length)return;let f=new Set(R.map(g=>g.id)),p=new Set(l.relations.flatMap(g=>f.has(g.fromId)?[g.toId]:f.has(g.toId)?[g.fromId]:[])),y=new Set(l.explanations.flatMap(g=>p.has(g.id)&&g.state!=="retired"&&g.state!=="challenged"?[g.id]:[])),m=l.explanations.filter(g=>y.has(g.id)&&!f.has(g.id)).sort((g,u)=>u.updatedAt.localeCompare(g.updatedAt)).slice(0,4),h=[...R,...m];for(let g of m)f.add(g.id);let M=o?l.explanations.filter(g=>g.state==="challenged").map(g=>{let u=rt(`${g.statement} ${g.rationale} ${g.scope.values.join(" ")}`),E=ht(u,r),j=ht(u,s);return{item:g,score:E+j,targetScore:E,referenceScore:j}}).filter(g=>g.targetScore>=.12&&g.referenceScore>=.12).sort((g,u)=>u.score-g.score||u.item.updatedAt.localeCompare(g.item.updatedAt)).slice(0,3).map(({item:g})=>({id:g.id,kind:g.kind,statement:g.statement,rationale:g.rationale,scope:g.scope,state:g.state})):[];return{explanations:h.map(g=>{let u=new Set(l.relations.filter(E=>E.toId===g.id&&E.type==="expresses").map(E=>E.fromId));return{id:g.id,kind:g.kind,statement:g.statement,rationale:g.rationale,scope:g.scope,state:g.state,concrete:l.concrete.filter(E=>u.has(E.id)).map(E=>({id:E.id,modelPath:E.modelPath,value:E.value}))}}),truncated:w.length>R.length||m.length<y.size,...o?{retrievalIntent:o}:{},...M.length?{historicalCaveats:M}:{},...c.size?{pendingGroundingExplanationIds:[...c]}:{},...d.size?{correctionExplanationIds:[...d]}:{},relations:l.relations.filter(g=>f.has(g.fromId)&&f.has(g.toId)).map(g=>({id:g.id,type:g.type,fromId:g.fromId,toId:g.toId,rationale:g.rationale}))}}async capture(e,t){let n=e.decision==="mutate"?e.mutations:[],o=t.applicationOccurred?n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...o])];if(n.length===0&&r.length===0)return;let s=t.occurredAt??new Date().toISOString(),c=await this.store.load(),d=new Map(c.graph.explanations.map(x=>[x.id,x])),l=new Map,w=new Map,b=[],P=new Set,R=new Set(t.pendingGroundingExplanationIds??[]),S=new Set(n.flatMap(x=>x.op==="revise"&&n.some(V=>V.op==="evidence"&&V.stance==="challenges"&&V.explanationId===x.explanationId)?[x.explanationId]:[])),f=new Set(n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[])),p=x=>d.has(x)||f.has(x),y=new Set;for(let x of n)x.op==="relation"&&x.fromId!==x.toId&&p(x.fromId)&&p(x.toId)?(y.add(x.fromId),y.add(x.toId)):x.op==="supersede"&&x.explanationId!==x.replacementId&&p(x.explanationId)&&p(x.replacementId)?(y.add(x.explanationId),y.add(x.replacementId)):x.op==="bind_concrete"&&p(x.explanationId)&&Vr(t.concreteModel,x.modelPath).found&&y.add(x.explanationId);let m=c.graph.explanations.length===0;for(let x of n){if(x.op!=="add")continue;let V=!!(x.clientId&&y.has(x.clientId)),L=!!x.rootReason?.trim()||m;if(!V&&!L)continue;m&&(m=!1);let N=st();x.clientId&&l.set(x.clientId,N);let ge=x.clientId?r.includes(x.clientId):!1,J={id:N,kind:x.kind,statement:x.statement,rationale:x.rationale,scope:co(x.scope),state:ge?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[gt(t,"supports",e.summary.detail)]};d.set(N,J),P.add(N),b.push({op:"add_explanation",explanation:J})}let h=x=>l.get(x)??x;for(let x of n){if(x.op!=="revise")continue;let V=h(x.explanationId),L=d.get(V);if(L?.state!=="grounded")continue;let N=st(),ge={id:N,kind:L.kind,statement:x.statement??L.statement,rationale:x.rationale??L.rationale,scope:x.scope?co(x.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[gt(t,"supports",e.summary.detail)]};d.set(N,ge),w.set(V,N),P.add(N),b.push({op:"add_explanation",explanation:ge});let J=Nt(L,ge);J!==0&&b.push({op:"add_relation",relation:{id:st(),type:"expresses",fromId:J>0?V:N,toId:J>0?N:V,rationale:x.rationale??e.summary.detail,createdAt:s}})}let M=x=>{let V=h(x);return w.get(V)??V};for(let x of n){if(x.op==="add")continue;if(x.op==="bind_concrete"){let L=M(x.explanationId);if(!d.has(L))continue;let N=Vr(t.concreteModel,x.modelPath);if(!N.found)continue;let ge=c.graph.concrete.find(J=>J.modelPath===x.modelPath&&JSON.stringify(J.value)===JSON.stringify(N.value));ge||(ge={id:st(),modelPath:x.modelPath,value:structuredClone(N.value),createdAt:s,updatedAt:s},b.push({op:"add_concrete",concrete:ge})),b.push({op:"add_relation",relation:{id:st(),type:"expresses",fromId:ge.id,toId:L,rationale:x.rationale,createdAt:s}}),P.add(L);continue}if(x.op==="relation"){let L=M(x.fromId),N=M(x.toId);if(!d.has(L)||!d.has(N)||L===N)continue;x.type==="expresses"&&Nt(d.get(L),d.get(N))<0&&([L,N]=[N,L]),b.push({op:"add_relation",relation:{id:st(),type:x.type,fromId:L,toId:N,rationale:x.rationale,createdAt:s}}),P.add(L),P.add(N);continue}if(x.op==="supersede"){let L=M(x.explanationId),N=M(x.replacementId);if(!d.has(L)||!d.has(N)||L===N)continue;b.push({op:"add_evidence",explanationId:L,evidence:gt(t,"challenges",x.reason)}),b.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:N},updatedAt:s}),P.add(L),P.add(N);continue}let V=M(x.explanationId);if(d.has(V))if(P.add(V),x.op==="revise"){if(w.has(h(x.explanationId)))continue;let L=d.get(V);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let N={...x.statement?{statement:x.statement}:{},...x.rationale?{rationale:x.rationale}:{},...x.scope?{scope:co(x.scope)}:{},...x.reopenGrounding||S.has(x.explanationId)?{state:"testing"}:{}};b.push({op:"revise_explanation",explanationId:V,patch:N,updatedAt:s})}else if(x.op==="evidence"){if(x.stance==="challenges"&&S.has(x.explanationId))continue;b.push({op:"add_evidence",explanationId:V,evidence:gt(t,x.stance,x.summary)}),x.stance==="challenges"&&b.push({op:"revise_explanation",explanationId:V,patch:{state:"challenged"},updatedAt:s})}else x.op==="retire"&&(b.push({op:"add_evidence",explanationId:V,evidence:gt(t,"challenges",x.reason||"Retired after contradictory collaboration evidence.")}),b.push({op:"revise_explanation",explanationId:V,patch:{state:"retired"},updatedAt:s}))}for(let x of r){let V=M(x),L=d.get(V);!L||L.state==="grounded"||L.state==="retired"||R.has(V)&&!P.has(V)||(P.has(V)||(P.add(V),b.push({op:"add_evidence",explanationId:V,evidence:{...gt(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&b.push({op:"revise_explanation",explanationId:V,patch:{state:"testing"},updatedAt:s}))}let g=new Set(c.graph.relations.map(x=>`${x.type}:${x.fromId}:${x.toId}`)),u=b.filter(x=>{if(x.op!=="add_relation")return!0;let V=`${x.relation.type}:${x.relation.fromId}:${x.relation.toId}`;return g.has(V)?!1:(g.add(V),!0)});if(!u.length)return;let E=st(),j=await this.store.commit({transactionId:E,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:u}),T=new Map(j.graph.explanations.map(x=>[x.id,x])),O=[...P].flatMap(x=>{let V=T.get(x);if(!V)return[];let L=!c.graph.explanations.some(ge=>ge.id===x),N=V.state==="challenged"||V.state==="retired";return[{explanationId:x,action:L?"added":N?"challenged":"revised",statement:V.statement,state:V.state}]}),H=r.map(M).find(x=>T.get(x)?.state==="testing"&&!R.has(x)),K=e.grounding?M(e.grounding.explanationId):H,G=K?T.get(K):void 0,Q=G?.state==="testing"&&!R.has(G.id)?{explanationId:G.id,question:e.grounding?.question||Sd(G),state:"testing"}:void 0;return{transactionId:E,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:O,...Q?{grounding:Q}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(l=>l.id===n);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="yes"?(c.push({op:"add_evidence",explanationId:n,evidence:{...gt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${r.statement}`):e.action==="this_time"&&(c.push({op:"add_evidence",explanationId:n,evidence:{...gt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"emerging"},updatedAt:t}),d=`Observed this time: ${r.statement}`),!c.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:st(),committedAt:t,source:s,summary:d,mutations:c}),"applied"}};import{randomUUID as Rd}from"crypto";var Vt="<imprint-use>",ci="</imprint-use>";function jd(i){let e=Math.min(i.length,Vt.length-1);for(let t=e;t>0;t--)if(Vt.startsWith(i.slice(-t)))return t;return 0}function Kr(i,e,t,n,o=Date.now()){if(!i||typeof i!="object"||Array.isArray(i))return null;let r=i,s=Array.isArray(r.explanationIds)?r.explanationIds.filter(d=>typeof d=="string"&&!!d.trim()):[],c=[...new Set(s)].flatMap(d=>{let l=e?.explanations.find(w=>w.id===d);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return c.length===0?null:{id:Rd(),jobId:t,sequence:n,timestamp:o,explanations:c}}var di=class{constructor(e,t){this.jobId=e;this.context=t;this.buffer="";this.sequence=0;this.explanationIds=new Set;this.optionalClosePending=!1}takeNewExplanations(e){let t=e.explanations.filter(n=>!this.explanationIds.has(n.id));if(t.length===0)return null;for(let n of t)this.explanationIds.add(n.id);return{...e,sequence:this.sequence++,explanations:t}}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(ci.startsWith(l)&&l.length<ci.length||(l.startsWith(ci)&&(this.buffer=this.buffer.slice(d+ci.length)),this.optionalClosePending=!1,!this.buffer))break}let o=this.buffer.indexOf(Vt);if(o<0){let d=jd(this.buffer);t+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}t+=this.buffer.slice(0,o);let r=o+Vt.length,s=zt(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(o);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let c=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=Kr(JSON.parse(c),this.context,this.jobId,this.sequence);if(!d)continue;let l=this.takeNewExplanations(d);l&&n.push(l)}catch{}}return{visibleText:t,usages:n}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],n="",o=0;for(;o<e.length;){let r=e.indexOf(Vt,o);if(r<0){n+=e.slice(o);break}n+=e.slice(o,r);let s=r+Vt.length,c=zt(e,s);if(c.status!=="complete"){o=s;continue}try{let w=Kr(JSON.parse(e.slice(c.start,c.end)),this.context,this.jobId,this.sequence);if(w){let b=this.takeNewExplanations(w);b&&t.push(b)}}catch{}let l=e.slice(c.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;o=c.end+l}return{visibleText:n.trim(),usages:t}}};function In(i,e){return i?.projectId===e.projectId&&i.version===e.version&&i.restartMode===e.restartMode}function li(i){return(Array.isArray(i)?i[0]:i)?.split(",")[0]?.trim()||void 0}function po(i){if(!i)return null;try{let e=new URL(i);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Qr(i){let e=po(li(i.origin));if(e)return e;let t=po(li(i.referer));if(t)return t;let n=li(i["x-forwarded-host"]);if(!n)return null;let o=li(i["x-forwarded-proto"])==="https"?"https":"http";return po(`${o}://${n}`)}function Xr(i,e,t=5){let n=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),o=[...i].sort(n).slice(0,t),r=i.filter(d=>d.status==="applied"||d.status==="failed").sort(n).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:o,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as mi}from"crypto";import{mkdir as bn,readFile as jt,unlink as $d,writeFile as Qt}from"fs/promises";import{dirname as fi,extname as Od,join as Oe}from"path";var Ad={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 Md(i){let e=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i??"")}})();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 Yr(i,e){let t=e??Md(i);return{kind:t,...Ad[t]}}function Kt(i,e){return!i||e||i.attention!=="response_requested"?i:{...i,attention:"response_available"}}function uo(i){let e=Array.from(new Set((i.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],n=i.decisionRequired?"decision_required":i.question||i.groundingRequired?"response_requested":i.reviewRequired||i.resolutions?.some(o=>o.status==="needs_review")?"review_required":"response_available";return i.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:i.imprintTransactionId}),{attention:n,outcomes:t}}import{createHash as Ed,randomUUID as _d}from"crypto";var Zr=i=>`${i}-${_d()}`;function mo(i,...e){return`${i}-${Ed("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function fo(i){return{schemaVersion:1,submissionIds:[Zr("submission")],jobId:i.jobId,threadId:i.threadId,artifactIds:[...new Set(i.artifactIds??[])]}}function wn(i,e=[],t){return{...i,outcomeId:i.outcomeId??Zr("outcome"),imprintEvidenceIds:[...new Set([...i.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function Cd(i){try{return new URL(i).pathname||"/"}catch{return"/"}}function pi(i,e){return e?[`${i||"/"}:${e}`]:[]}function es(i){let e=Cd(i.url);return[...new Set([...i.annotations.flatMap(t=>pi(t.pathname??e,t.linkedSelector)),...i.styleModifications.flatMap(t=>pi(e,t.durableSelector??t.selector)),...(i.textModifications??[]).flatMap(t=>pi(t.pathname??e,t.durableSelector??t.selector)),...(i.domModifications??[]).flatMap(t=>pi(t.pathname??e,t.durableSelector??t.selector))])]}function ts(i,e){return[...new Set([`screenshot:${e}`,...i.annotations.map(t=>`annotation:${t.id}`),...i.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function ui(i,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=mo("submission",i,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:i,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[mo("artifact",i,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:mo("outcome",i,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function ho(i){let e=i.lifecycleVersion!==1;i.lifecycleVersion=1;for(let t of i.messages)e=ui(i.id,t)||e;return e}function ns(i){let e=i.messages.at(-1),t=[...i.messages].reverse().find(o=>o.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:i.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:i.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let n=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:i.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var Dd={version:1,threads:{}},is=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],xn={version:2,updatedAt:0,files:{}};function Nd(i){return JSON.stringify(i,null,2)}function Bd(i){return Object.fromEntries(is.flatMap(e=>i[e]===void 0?[]:[[e,i[e]]]))}function Jd(i){let e={...i};for(let t of is)delete e[t];return e}function Xt(i){let e=i;if(i.error){let t=Yr(i.error,i.errorKind);(i.error!==t.message||i.errorKind!==t.kind||i.responseText!==void 0)&&(e={...i,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=Kt(e.result,!1),n=Kt(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var hi=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=Oe(e,".popmelt");this.legacyFilePath=Oe(t,"threads.json"),this.threadsDir=Oe(t,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(t,"artifacts","thread-messages"),this.mediaDir=Oe(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await jt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[o,r]of Object.entries(e.files)){let s=await this.readThread(Oe(this.threadsDir,r));s&&(t[o]=s)}this.cache={version:1,threads:t};let n=!1;for(let o of Object.values(t))n=ho(o)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await jt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,n])=>[t,{...n,messages:n.messages.map(Xt)}]))},this.index={...xn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))ho(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...Dd,threads:{}},this.index={...xn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let t=await this.load(),n=new Set(e);for(let o of Object.values(t.threads))if(o.elementIdentifiers.some(s=>n.has(s)))return o;return null}async createThread(e,t){let n=await this.load(),o={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=o,await this.persistThread(o),o}async appendMessage(e,t){let o=(await this.load()).threads[e];o&&(ui(e,t),o.messages.push(Xt(t)),o.updatedAt=Date.now(),await this.persistThread(o))}async appendMessageBeforeQueuedReplies(e,t){let o=(await this.load()).threads[e];if(!o)return;ui(e,t);let r=o.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?o.messages.splice(r,0,Xt(t)):o.messages.push(Xt(t)),o.updatedAt=Date.now(),await this.persistThread(o)}async updateMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===t);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,n),c.error){let d=Xt(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===t);return s?(Object.assign(s,n),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,t){let o=(await this.load()).threads[e];if(!o)return;let r=new Set(o.elementIdentifiers);for(let s of t)r.has(s)||o.elementIdentifiers.push(s);o.updatedAt=Date.now(),await this.persistThread(o)}async deleteThread(e){let t=await this.load();return t.threads[e]?(delete t.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let t=await this.load(),n=Object.values(t.threads);return n.sort((o,r)=>r.updatedAt-o.updatedAt),n.slice(0,e).map(o=>{let s=o.messages.find(p=>p.role==="human")?.feedbackSummary||"[thread]",c=o.messages.filter(p=>p.role==="assistant"),d=p=>{if(p.role!=="assistant")return;if(p.question)return p.question;let y=p.imprintSummary?.grounding;if(y?.question&&!p.imprintSummary?.resolvedAction)return y.question},l=o.messages.findLastIndex(p=>!!d(p)),w=o.messages.findLastIndex(p=>p.role==="human"),b=l>w?d(o.messages[l]):void 0,P=o.messages.at(-1)?.role,R=Array.from(new Set(o.messages.slice(0,Math.max(0,w)).filter(p=>p.role==="assistant"&&!!p.jobId).map(p=>p.jobId))),S=c.some(p=>!!p.responseText||!!p.question||!!p.result||!!p.memoryReviewCard||!!p.memoryReceipt),f=c.some(p=>!!p.error);return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:s,messageCount:o.messages.length,hasReply:S,hasError:f,lastMessageRole:P,pendingQuestion:b,acknowledgedJobIds:R,elementIdentifiers:o.elementIdentifiers,lifecycle:ns(o)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let o=n.messages.at(-1);if(!o||o.role!=="human"||/^(imprint|memory)-/.test(o.jobId))continue;let r=wn(o.lifecycle);o.queued&&await this.updateMessage(n.id,o.jobId,{queued:!1}),await this.appendMessage(n.id,{role:"assistant",timestamp:Date.now(),jobId:o.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),t+=1}return t}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await jt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:o,...r})=>{let s={};if(o?.path)try{let c=await jt(Oe(fi(this.legacyFilePath),o.path),"utf8");mi("sha256").update(c).digest("hex")===o.sha256&&(s=JSON.parse(c))}catch{}return Xt({...r,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=Bd(e),n=Jd(e);if(Object.keys(t).length===0)return n;let o=Nd(t),r=mi("sha256").update(o).digest("hex"),s=Oe("artifacts","thread-messages",`${r}.json`);await bn(this.artifactsDir,{recursive:!0});try{await jt(Oe(fi(this.legacyFilePath),s),"utf8")}catch{await Qt(Oe(fi(this.legacyFilePath),s),o)}return{...n,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let t=async n=>{if(fi(n)===this.mediaDir)return n;try{let o=await jt(n),r=mi("sha256").update(o).digest("hex"),s=Oe(this.mediaDir,`${r}${Od(n)||".bin"}`);await bn(this.mediaDir,{recursive:!0});try{await jt(s)}catch{await Qt(s,o)}return s}catch{return n}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([n,o])=>[n,await t(o)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,o])=>[n,await Promise.all(o.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,o])=>[n,await Promise.all(o.map(async r=>({...r,path:await t(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await bn(this.threadsDir,{recursive:!0});let t=this.index??{...xn,files:{}},n=t.files[e.id]??`${mi("sha256").update(e.id).digest("hex").slice(0,32)}.json`,o=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:o};await Qt(Oe(this.threadsDir,n),JSON.stringify(r,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Qt(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),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 bn(this.threadsDir,{recursive:!0}),this.index=this.index??{...xn,files:{}},await Qt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...xn,files:{}},n=t.files[e];n&&await $d(Oe(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await bn(this.threadsDir,{recursive:!0}),await Qt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as Ld,open as qd,readFile as Fd,rename as Ud,unlink as zd}from"fs/promises";import{dirname as Wd,join as Hd}from"path";var os={schemaVersion:1,theme:"auto",updatedAt:null};function rs(i){return i==="light"||i==="dark"||i==="auto"?i:null}async function Gd(i,e){await Ld(Wd(i),{recursive:!0});let t=`${i}.${process.pid}.${Date.now()}.tmp`;try{let n=await qd(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
191
+ `,"utf8"),await n.sync()}finally{await n.close()}await Ud(t,i)}catch(n){throw await zd(t).catch(()=>{}),n}}var gi=class{constructor(e){this.path=Hd(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Fd(this.path,"utf8")),t=rs(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...os}}}catch{return{exists:!1,preferences:{...os}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Gd(this.path,t),t}};function ss(i){return rs(i)!==null}function yt(i,e=240){if(!i)return;let t=i.replace(/\s+/g," ").trim();if(t)return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Yt(i){return i?[yt(i.selector,400),yt(i.context,200),yt(i.reactComponent,120),yt(i.textContent)].filter(e=>!!e):[]}function go(i){return[...new Set(i.filter(e=>!!e))]}function as(i,e){return go([...e,...i.annotations.flatMap(t=>[yt(t.pathname,200),yt(t.linkedSelector,400),...t.elements.flatMap(Yt)]),...i.styleModifications.flatMap(t=>Yt(t.element)),...(i.textModifications??[]).flatMap(t=>Yt(t.element)),...(i.domModifications??[]).flatMap(t=>[...Yt(t.element),...Yt(t.sourceElement)])])}function cs(i,e){let t=[...i].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return go(t?[...e,...t.annotations.flatMap(n=>[yt(n.pathname,200),yt(n.linkedSelector,400),...n.elements.flatMap(Yt)])]:e)}function yi(i){return Kd(i).slice(0,12)}var Vd=[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 Kd(i){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(i)):Qd(i),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let P=7;P>=0;P--)e.push(t/Math.pow(2,P*8)&255);let n=1779033703,o=3144134277,r=1013904242,s=2773480762,c=1359893119,d=2600822924,l=528734635,w=1541459225,b=new Array(64);for(let P=0;P<e.length;P+=64){for(let g=0;g<16;g++){let u=P+g*4;b[g]=(e[u]<<24|e[u+1]<<16|e[u+2]<<8|e[u+3])>>>0}for(let g=16;g<64;g++){let u=tt(b[g-15],7)^tt(b[g-15],18)^b[g-15]>>>3,E=tt(b[g-2],17)^tt(b[g-2],19)^b[g-2]>>>10;b[g]=b[g-16]+u+b[g-7]+E>>>0}let R=n,S=o,f=r,p=s,y=c,m=d,h=l,M=w;for(let g=0;g<64;g++){let u=tt(y,6)^tt(y,11)^tt(y,25),E=y&m^~y&h,j=M+u+E+Vd[g]+b[g]>>>0,T=tt(R,2)^tt(R,13)^tt(R,22),O=R&S^R&f^S&f,H=T+O>>>0;M=h,h=m,m=y,y=p+j>>>0,p=f,f=S,S=R,R=j+H>>>0}n=n+R>>>0,o=o+S>>>0,r=r+f>>>0,s=s+p>>>0,c=c+y>>>0,d=d+m>>>0,l=l+h>>>0,w=w+M>>>0}return[n,o,r,s,c,d,l,w].map(P=>P.toString(16).padStart(8,"0")).join("")}function tt(i,e){return i>>>e|i<<32-e}function Qd(i){let e=[];for(let t=0;t<i.length;t++){let n=i.charCodeAt(t);n<128?e.push(n):n<2048?e.push(192|n>>6,128|n&63):e.push(224|n>>12,128|n>>6&63,128|n&63)}return e}function Xd(i){let e=i.instruction?.trim();return e?i.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function ds(i){let e=i.annotations.flatMap(o=>{let r=Xd(o);return r?[{instruction:r,pathname:o.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(o=>o.pathname).filter(Boolean)).size<=1)return e.map(o=>o.instruction).join(`
192
+
193
+ `);let n=new Map;for(let o of e){let r=o.pathname||"(unknown)",s=n.get(r)??[];s.push(o.instruction),n.set(r,s)}return[...n.entries()].map(([o,r])=>`\`${o}\`
184
194
  ${r.map(s=>`- ${s}`).join(`
185
195
  `)}`).join(`
186
- `)}var Gr={name:"@popmelt.com/core",version:"0.8.17",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.7.0",ws:"8.21.1"},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","@types/ws":"8.18.1",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 it=Gr.version;var Jd=1111,Ld=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],qd=1800*1e3,Fd=3600*1e3,Vr=45e3,Ud=5e3,zd=1e4,Gd=2*1024*1024;function Kr(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(`
187
- `)}function yn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function Qr(o){let e=o.findLastIndex(i=>i.role==="assistant");if(e<0)return[];let n=o[e];if(!n?.question||!n.jobId.startsWith("imprint-"))return[];let t=o.slice(0,e).findLast(i=>i.role==="assistant"&&i.imprintSummary?.resolvedAction==="no"&&!!i.imprintSummary.grounding);return t?.imprintSummary?.grounding?[t.imprintSummary.grounding.explanationId]:[]}function Wd(o,e){if(e.size===1)return[...o].reverse().find(n=>{let t=n.imprintSummary;return n.role==="assistant"&&!!t?.grounding&&!t?.resolvedAction&&e.has(t.grounding.explanationId)})}function es(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Hd(o,e,n){let t=[...n];for(let i of o)if(i.type==="tool_use"){let r=i.tool||"",s=i.file??void 0,c=i.content??void 0,d=s?s.split("/").pop()??s:void 0,u;switch(r){case"Read":u=d?`Reading ${d}`:"Reading file";break;case"Edit":u=d?`Editing ${d}`:"Editing file";break;case"Write":u=d?`Writing ${d}`:"Writing file";break;case"Bash":u=c?c.split(`
188
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":u="Searching files";break;case"Grep":u="Searching code";break;case"WebFetch":u="Fetching page";break;case"WebSearch":u="Searching web";break;default:u=r?`Using ${r}`:"tool";break}let I=s??c??void 0,x=s?Zr(s)?s:Nd(e,s):void 0,T=t[t.length-1];T&&T.kind==="tool_group"&&T.tool===r?T.items.push({label:u,detail:I,...x?{filePath:x}:{}}):t.push({kind:"tool_group",tool:r,items:[{label:u,detail:I,...x?{filePath:x}:{}}]})}return t}function Vd(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(`
189
- `)}function Kd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Xr(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"}`),i=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}`}),r=[...e,...t,...n,...i].map(s=>Kd(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function Qd(o,e){let n=o.headers.origin;es(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function _(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function Oe(o){let e=[],n=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(n+=r.length,n>16384)throw new Error("Request body too large");e.push(r)}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}async function Xd(o,e){let n=[],t=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(t+=r.length,t>e)throw new Error("Request body too large");n.push(r)}return Buffer.concat(n)}function Yd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function Zd(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,i,r]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(i,16)};${parseInt(r,16)}m${e}\x1B[0m`}function uo(o,e){try{o.res.write(`event: ${e.type}
196
+ `)}var ls={name:"@popmelt.com/core",version:"0.9.0",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.7.0",ws:"8.21.1"},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","@types/ws":"8.18.1",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 at=ls.version;var pl=1111,ul=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],ml=1800*1e3,fl=3600*1e3,ms=45e3,hl=5e3,gl=1e4,yl=2*1024*1024;function fs(i){return i.length<=1?i[0]??"":["The developer sent these queued steering messages while you were working:","",...i.map((e,t)=>`${t+1}. ${e}`)].join(`
197
+ `)}function Sn(i){return[...new Set(i.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function hs(i){let e=i.findLastIndex(o=>o.role==="assistant");if(e<0)return[];let t=i[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let n=i.slice(0,e).findLast(o=>o.role==="assistant"&&o.imprintSummary?.resolvedAction==="no"&&!!o.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function vl(i,e){if(e.size===1)return[...i].reverse().find(t=>{let n=t.imprintSummary;return t.role==="assistant"&&!!n?.grounding&&!n?.resolvedAction&&e.has(n.grounding.explanationId)})}function Is(i){if(!i)return!1;try{let e=new URL(i);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Il(i,e,t){let n=[...t];for(let o of i)if(o.type==="tool_use"){let r=o.tool||"",s=o.file??void 0,c=o.content??void 0,d=s?s.split("/").pop()??s:void 0,l;switch(r){case"Read":l=d?`Reading ${d}`:"Reading file";break;case"Edit":l=d?`Editing ${d}`:"Editing file";break;case"Write":l=d?`Writing ${d}`:"Writing file";break;case"Bash":l=c?c.split(`
198
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=r?`Using ${r}`:"tool";break}let w=s??c??void 0,b=s?vs(s)?s:dl(e,s):void 0,P=n[n.length-1];P&&P.kind==="tool_group"&&P.tool===r?P.items.push({label:l,detail:w,...b?{filePath:b}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:l,detail:w,...b?{filePath:b}:{}}]})}return n}function wl(i,e){if(i.processedIds.length===0&&i.success)return"No accepted decisions were ready for model projection.";if(i.success&&i.proposalId)return"";let t=[];return i.success?t.push("Model suggestion ready."):t.push("Model projection failed."),i.proposalId&&t.push("Review the proposed model changes below."),e&&(e.outputStats?t.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"}.`):t.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),i.error&&(t.push(""),t.push(`Error: ${i.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
199
+ `)}function bl(i,e=96){let t=i.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function gs(i){let e=i.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"}`)}),t=(i.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(i.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),o=i.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}`}),r=[...e,...n,...t,...o].map(s=>bl(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function xl(i,e){let t=i.headers.origin;Is(t)&&(e.setHeader("Access-Control-Allow-Origin",t),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(i,e,t){i.writeHead(e,{"Content-Type":"application/json"}),i.end(JSON.stringify(t))}async function De(i){let e=[],t=0;for await(let o of i){let r=typeof o=="string"?Buffer.from(o):o;if(t+=r.length,t>16384)throw new Error("Request body too large");e.push(r)}if(e.length===0)return{};let n=JSON.parse(Buffer.concat(e).toString("utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Expected a JSON object");return n}async function Sl(i,e){let t=[],n=0;for await(let o of i){let r=typeof o=="string"?Buffer.from(o):o;if(n+=r.length,n>e)throw new Error("Request body too large");t.push(r)}return Buffer.concat(t)}function Tl(i,e){let t=i.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function Pl(i,e){if(!i)return e;let t=i.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,o,r]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(o,16)};${parseInt(r,16)}m${e}\x1B[0m`}function wi(i,e){try{i.res.write(`event: ${e.type}
190
200
  data: ${JSON.stringify(e)}
191
201
 
192
- `)}catch{}}function Ht(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function mo(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 el(o,e){return new Promise((n,t)=>{let i=s=>{o.removeListener("listening",r),t(s)},r=()=>{o.removeListener("error",i),n()};o.once("error",i),o.once("listening",r),o.listen(e,"127.0.0.1")})}async function ts(o={}){let e=new Date().toISOString(),n=o.port??Jd,t=o.projectRoot??process.cwd(),i=await Md(t).catch(()=>t),r=co(i),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??De($d(),"popmelt-bridge"),d=o.maxTurns??40,u=o.maxBudgetUsd??1,I=[...o.allowedTools??Ld],x=o.claudePath??"claude",T=o.copilotPath??"copilot",k=o.provider??"claude",S=o.timeoutMs,p=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,l=o.restartMode??"embedded",f=n,m={},h={claude:x,codex:"codex",copilot:T};for(let[a,y]of Object.entries(h))try{let M=y.includes("/")?y:kd("which",[y],{encoding:"utf-8"}).trim();m[a]={available:!0,path:M}}catch{m[a]={available:!1,path:null}}function j(a,y){return new Promise(M=>{let v=Wr(y,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,P=$=>{A||(A=!0,M($))},C=setTimeout(()=>{v.kill("SIGTERM"),P(!0)},5e3);v.on("error",()=>{clearTimeout(C),P(!1)}),v.on("close",$=>{clearTimeout(C),P($===0)})})}await Promise.all([(async()=>{m.claude&&(m.claude.models=m.claude.available&&m.claude.path?await Pr(m.claude.path).catch(()=>Hn):Hn)})(),(async()=>{m.codex&&(m.codex.models=m.codex.available&&m.codex.path?await Tr(m.codex.path).catch(()=>pn):pn)})(),(async()=>{m.copilot&&(m.copilot.models=m.copilot.available&&m.copilot.path?await Sr(m.copilot.path).catch(()=>[un]):[un])})()]);let[b,g,J]=await Promise.all([_o(i),Co(i),$o(i,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=b),m.codex&&(m.codex.mcp=g),m.copilot&&(m.copilot.mcp=J),b.found&&b.name&&I.push(`mcp__${b.name}__*`),await jd(c,{recursive:!0}),Yr(c).catch(()=>{});let E=new Kn(1),R=new En,N=new Cn(Vr),V=null,K=0,W=!1,Q=()=>{K+=1,W=!1,V&&clearTimeout(V),V=null},w=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},H=()=>{if(l!=="detached"||N.size>0||W)return;W=!0;let a=++K,y=Date.now()+zd,M=()=>{if(a!==K)return;if(N.size>0){Q();return}if(!(E.isRunning||E.depth>0||R.isRunning||R.depth>0)||Date.now()>=y){W=!1,V=setTimeout(w,50),V.unref?.();return}V=setTimeout(M,250),V.unref?.()};M()},L=new Set,O=new so(i),he=await O.recoverInterruptedTurns();he>0&&console.warn(`[Popmelt] Recovered ${he} interrupted thread turn(s) from durable history.`);let B=new kn(i);B.sweep();let D=new zn(i),Y=new Ut(i,r);try{let a=await Y.store.migrateTopology();a.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${a.relationMutations} relation mutation(s)).`)}catch(a){console.warn(`[Popmelt] Imprint topology migration deferred: ${a instanceof Error?a.message:String(a)}`)}let ce=new ao(i),Pe=new Sn(i),se=new Mn(i,{claudePath:x,provider:k,timeoutMs:S,loadProjectableDecisions:a=>D.getProjectableDecisions(a),onEvent:a=>{for(let y of L)uo(y,a)}});D.beginAutomaticInitialization({writerVersion:it}).then(async a=>{a.state==="ready"?(await D.migrateImprintSnapshot(),await D.syncImprintGraph(),await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),k!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await ht({provider:k,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${f}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let Ue=20,We=300*1e3,ke=[];function st(){let a=Date.now()-We;for(;ke.length>0&&(ke[0].completedAt<a||ke.length>Ue);)ke.shift()}let He=new Map,at=null,Vt;E.addListener((a,y,M)=>{for(let v of L)(!M||!v.sourceId||v.sourceId===M)&&uo(v,a)}),R.addListener((a,y,M)=>{for(let v of L)(!M||!v.sourceId||v.sourceId===M)&&uo(v,a)}),R.setProcessor(async a=>{let y=a.provider??k;try{let M=await se.run({provider:y,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let v=await se.loadRuns(),A=M.runId?v.runs.find(C=>C.id===M.runId):void 0;if(M.success&&M.proposalId){let C=await se.findModelProposal(M.proposalId),$=await se.loadModel(),q=C?Ei(C,$):null;if(C&&q){let G=C.decisionIds.map(U=>({decisionId:U,status:"projected"}));await D.applyModelProjection({runId:C.runId??C.id,presentationJobId:C.presentationJobId,decisionIds:C.decisionIds,changes:q.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:G}),await se.applySelectedModelProposal(C.id,q.map(U=>({path:U.path,value:U.value})),q.map(U=>({group:U.path[0]==="rules"||U.path[0]==="components"||U.path[0]==="tokens"?U.path[0]:"model",label:U.label??U.id,detail:U.rationale,path:U.path,value:U.value})),"automatic")}}let P=Vd(M,A);if(a.threadId&&(await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:y})),M.success)a.status="done",a.result=P,R.broadcast({type:"done",jobId:a.id,success:!0,responseText:P,threadId:a.threadId},a.id,a.sourceId),ke.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),st();else{if(a.status="error",a.error=M.error??"Projection failed",a.threadId){let C=`Model projection failed.
202
+ `)}catch{}}function Zt(i){return i==="claude"||i==="codex"||i==="copilot"?i:void 0}async function bi(i){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${i}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch{return null}}function kl(i,e){return new Promise((t,n)=>{let o=s=>{i.removeListener("listening",r),n(s)},r=()=>{i.removeListener("error",o),t()};i.once("error",o),i.once("listening",r),i.listen(e,"127.0.0.1")})}async function ws(i={}){let e=new Date().toISOString(),t=i.port??pl,n=i.projectRoot??process.cwd(),o=await nl(n).catch(()=>n),r=yi(o),s=i.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=i.tempDir??Ne(sl(),"popmelt-bridge"),d=i.maxTurns??40,l=i.maxBudgetUsd??1,w=[...i.allowedTools??ul],b=i.claudePath??"claude",P=i.copilotPath??"copilot",R=i.provider??"codex",S=i.timeoutMs,f=i.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,p=i.restartMode??"embedded",y=t,m={},h={claude:b,codex:"codex",copilot:P};for(let[a,v]of Object.entries(h))try{let _=v.includes("/")?v:Zd("which",[v],{encoding:"utf-8"}).trim();m[a]={available:!0,path:_}}catch{m[a]={available:!1,path:null}}function M(a,v){return new Promise(_=>{let I=ps(v,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,k=D=>{A||(A=!0,_(D))},$=setTimeout(()=>{I.kill("SIGTERM"),k(!0)},5e3);I.on("error",()=>{clearTimeout($),k(!1)}),I.on("close",D=>{clearTimeout($),k(D===0)})})}await Promise.all([(async()=>{m.claude&&(m.claude.models=m.claude.available&&m.claude.path?await Lr(m.claude.path).catch(()=>ni):ni)})(),(async()=>{m.codex&&(m.codex.models=m.codex.available&&m.codex.path?await Jr(m.codex.path).catch(()=>yn):yn)})(),(async()=>{m.copilot&&(m.copilot.models=m.copilot.available&&m.copilot.path?await Br(m.copilot.path).catch(()=>[vn]):[vn])})()]);let[g,u,E]=await Promise.all([qi(o),Fi(o),Ui(o,m.copilot?.path??P)]);m.claude&&(m.claude.mcp=g),m.codex&&(m.codex.mcp=u),m.copilot&&(m.copilot.mcp=E),g.found&&g.name&&w.push(`mcp__${g.name}__*`),await el(c,{recursive:!0}),ys(c).catch(()=>{});let j=new oi(1),T=new Ln,O=new Fn(ms),H=null,K=0,G=!1,Q=()=>{K+=1,G=!1,H&&clearTimeout(H),H=null},x=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},V=()=>{if(p!=="detached"||O.size>0||G)return;G=!0;let a=++K,v=Date.now()+gl,_=()=>{if(a!==K)return;if(O.size>0){Q();return}if(!(j.isRunning||j.depth>0||T.isRunning||T.depth>0)||Date.now()>=v){G=!1,H=setTimeout(x,50),H.unref?.();return}H=setTimeout(_,250),H.unref?.()};_()},L=new Set,N=new hi(o),ge=await N.recoverInterruptedTurns();ge>0&&console.warn(`[Popmelt] Recovered ${ge} interrupted thread turn(s) from durable history.`);let J=new Dn(o);J.sweep();let B=new Zn(o),X=new Gt(o,r);try{let a=await X.store.migrateTopology();a.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${a.relationMutations} relation mutation(s)).`)}catch(a){console.warn(`[Popmelt] Imprint topology migration deferred: ${a instanceof Error?a.message:String(a)}`)}let pe=new gi(o),ke=new _n(o),ce=new Jn(o,{claudePath:b,provider:R,timeoutMs:S,loadProjectableDecisions:a=>B.getProjectableDecisions(a),onEvent:a=>{for(let v of L)wi(v,a)}});B.beginAutomaticInitialization({writerVersion:at}).then(async a=>{a.state==="ready"?(await B.migrateImprintSnapshot(),await B.syncImprintGraph(),await ce.applyCanonicalEntries(await B.getCanonicalModelEntries()),R!=="copilot"&&(await ce.getUnprojectedPatternDecisions()).length>0&&await It({provider:R,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 Le=20,ze=300*1e3,Me=[];function dt(){let a=Date.now()-ze;for(;Me.length>0&&(Me[0].completedAt<a||Me.length>Le);)Me.shift()}let We=new Map,lt=null,en;j.addListener((a,v,_)=>{for(let I of L)(!_||!I.sourceId||I.sourceId===_)&&wi(I,a)}),T.addListener((a,v,_)=>{for(let I of L)(!_||!I.sourceId||I.sourceId===_)&&wi(I,a)}),T.setProcessor(async a=>{let v=a.provider??R;try{let _=await ce.run({provider:v,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let I=await ce.loadRuns(),A=_.runId?I.runs.find($=>$.id===_.runId):void 0;if(_.success&&_.proposalId){let $=await ce.findModelProposal(_.proposalId),D=await ce.loadModel(),q=$?Wo($,D):null;if($&&q){let W=$.decisionIds.map(F=>({decisionId:F,status:"projected"}));await B.applyModelProjection({runId:$.runId??$.id,presentationJobId:$.presentationJobId,decisionIds:$.decisionIds,changes:q.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:W}),await ce.applySelectedModelProposal($.id,q.map(F=>({path:F.path,value:F.value})),q.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 k=wl(_,A);if(a.threadId&&(await N.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:k,model:a.model,provider:v})||await N.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:k,model:a.model,provider:v})),_.success)a.status="done",a.result=k,T.broadcast({type:"done",jobId:a.id,success:!0,responseText:k,threadId:a.threadId},a.id,a.sourceId),Me.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),dt();else{if(a.status="error",a.error=_.error??"Projection failed",a.threadId){let $=`Model projection failed.
193
203
 
194
- ${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:y})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:y,model:a.model},a.id,a.sourceId),ke.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),st()}}catch(M){if(a.status==="cancelled")return;if(a.status="error",a.error=M instanceof Error?M.message:String(M),a.threadId){let v=`Model projection failed.
204
+ ${a.error}`;await N.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:$,error:a.error,model:a.model,provider:v})||await N.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:$,error:a.error,model:a.model,provider:v})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),Me.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),dt()}}catch(_){if(a.status==="cancelled")return;if(a.status="error",a.error=_ instanceof Error?_.message:String(_),a.threadId){let I=`Model projection failed.
195
205
 
196
- ${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:y})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:y,model:a.model},a.id,a.sourceId),ke.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),st()}}),E.setProcessor(async a=>{let y=a,M=y._replyPrompt,v=y._replyText,A=y._replyImagePaths,P=a.provider??k,C=!!(a.surfacedProposalIds?.length&&M),$=!C&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&v!==void 0&&await O.updateMessage(a.threadId,a.id,{queued:!1});let q;if(a.threadId){let oe=await O.getThread(a.threadId);if(oe){for(let ue=oe.messages.length-1;ue>=0;ue--)if(oe.messages[ue].sessionId){q=oe.messages[ue].sessionId;break}}}C&&(q=void 0);let G;if(q&&M){if(G=v??M,A&&A.length>0){G+=`
206
+ ${a.error}`;await N.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:I,error:a.error,model:a.model,provider:v})||await N.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:I,error:a.error,model:a.model,provider:v})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),Me.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),dt()}}),j.setProcessor(async a=>{let v=a,_=v._replyPrompt,I=v._replyText,A=v._replyImagePaths,k=a.provider??R,$=!!(a.surfacedProposalIds?.length&&_),D=!$&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&I!==void 0&&await N.updateMessage(a.threadId,a.id,{queued:!1});let q;if(a.threadId){let ee=await N.getThread(a.threadId);if(ee){for(let fe=ee.messages.length-1;fe>=0;fe--)if(ee.messages[fe].sessionId){q=ee.messages[fe].sessionId;break}}}$&&(q=void 0);let W;if(q&&_){if(W=I??_,A&&A.length>0){W+=`
197
207
 
198
- The developer attached reference images with their reply:`;for(let oe of A)G+=`
199
- Attached image: use the Read tool to view the image at: ${oe}`}a.kind==="synthesize"?G+=`
208
+ The developer attached reference images with their reply:`;for(let ee of A)W+=`
209
+ Attached image: use the Read tool to view the image at: ${ee}`}a.kind==="synthesize"?W+=`
200
210
 
201
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:G+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(q)G=dn(a.feedback,a.imagePaths,a.attachmentFiles)+`
211
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:W+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(q)W=hn(a.feedback,a.imagePaths,a.attachmentFiles)+`
202
212
 
203
213
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
204
214
 
205
- After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(P!=="codex"?`
215
+ After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(k!=="codex"?`
216
+
217
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let ee=!_&&a.threadId?await N.getThreadHistory(a.threadId):void 0,fe=_?null:await ce.loadModel();W=_??_r(a.screenshotPath,a.feedback,{threadHistory:ee&&ee.length>0?ee:void 0,provider:k,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:fe??void 0,screenshotPaths:a.screenshotPaths})}W+=Tr(a.memoryReview),D&&(W+=ai(a.imprintContext,{requestText:I??Ut(a.feedback)})),a.threadId&&!$&&(W+=`
206
218
 
207
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let oe=!M&&a.threadId?await O.getThreadHistory(a.threadId):void 0,ue=M?null:await se.loadModel();G=M??yr(a.screenshotPath,a.feedback,{threadHistory:oe&&oe.length>0?oe:void 0,provider:P,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:ue??void 0,screenshotPaths:a.screenshotPaths})}G+=lr(a.memoryReview),$&&(G+=eo(a.imprintContext,{requestText:v??Lt(a.feedback)})),G+=`
219
+ ${Er}`),W+=`
208
220
 
209
- ${gr}`;let U=Zd(a.color,`[\u22B9 ${f}:${a.id}]`),pe=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${U} Reviewing ${pe} (provider: ${P})${a.threadId?` (thread: ${a.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let z=new Gn(a.id),me=(oe,ue)=>{if(oe.type==="delta"&&"text"in oe){let Me=z.push(oe.text);Me.visibleText&&(E.accumulateText(ue,"response",Me.visibleText),E.broadcast({...oe,text:Me.visibleText},ue,a.sourceId));for(let ut of Me.orientations)E.broadcast({type:"orientation",jobId:ue,orientation:ut},ue,a.sourceId);return}else oe.type==="thinking"&&"text"in oe&&E.accumulateText(ue,"thinking",oe.text);E.broadcast(oe,ue,a.sourceId)},{process:le,result:ne}=P==="codex"?xn(a.id,{prompt:G,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:q,model:a.model,sandboxMode:C?"read-only":void 0,configOverrides:In(a.agentSettings),onEvent:me}):P==="copilot"?Ti(a.id,{prompt:G,projectRoot:i,resumeSessionId:q,model:a.model,timeoutMs:S,copilotPath:m.copilot?.path??T,onEvent:me}):wn(a.id,{prompt:G,projectRoot:i,maxTurns:d,maxBudgetUsd:u,allowedTools:C?["Read"]:I,claudePath:x,resumeSessionId:q,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:S,onEvent:me});E.setActiveProcess(a.id,le);let X=await ne,xe=[...(X.fileEdits??[]).map(oe=>oe.file_path),...(X.editEvents??[]).flatMap(oe=>oe.filePath?[oe.filePath]:[])],we=Yo(X.text,a.id),je=z.finalize(X.text),ge=we.visibleText,Z=wr(ge),fe=$?Zn(ge,{context:a.imprintContext,requestText:v??Lt(a.feedback),applicationOccurred:xe.length>0||Z.some(oe=>oe.status==="resolved")}):{visibleText:ge,draft:void 0,error:void 0},Je=fe.visibleText,Ae=$?fe.error?{state:fe.error.includes("missing")?"missing":"invalid",reason:fe.error}:fe.draft?.decision==="none"?{state:"none",reason:fe.draft.reason}:fe.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let oe of je.orientations)E.broadcast({type:"orientation",jobId:a.id,orientation:oe},a.id,a.sourceId);if(a.result=Je,X.success){console.log(`${U} Iteration complete`),X.fileEdits&&X.fileEdits.length>0&&console.log(`${U} Captured ${X.fileEdits.length} file edit(s): ${X.fileEdits.map(re=>`${re.tool} ${re.file_path}`).join(", ")}`),X.editEvents&&X.editEvents.length>0&&console.log(`${U} Captured ${X.editEvents.length} edit event(s): ${X.editEvents.map(re=>`${re.operation} ${re.filePath}`).join(", ")}`),a.status="done";let oe=vr(ge),ue=Z;if(ue.length>0&&a.annotationIds&&a.annotationIds.length>0){let re=new Set(a.annotationIds);ue.every(yt=>re.has(yt.annotationId))||(ue=ue.map((yt,vt)=>({...yt,annotationId:a.annotationIds[vt%a.annotationIds.length]})))}let Me=X.fileEdits&&X.fileEdits.length>0?X.fileEdits.map(re=>`${re.tool} ${re.file_path.split("/").pop()}`):X.toolsUsed,ut=E.getBufferedEvents(a.id),_e=Hd(ut?.events??[],i,we.segments),Le,qe=ur(ge),Se=pr(ge);if(Se)if(!(a.memoryReview?.packets.some(de=>de.proposalId===Se.proposalId)||a.surfacedProposalIds?.includes(Se.proposalId)))Le={status:"rejected",action:Se.action,proposalId:Se.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Le=await D.commitConversationalReview(Se)}catch(de){Le={status:"rejected",action:Se.action,proposalId:Se.proposalId,message:de instanceof Error?de.message:String(de)}}let ee=br(ge,xe.length),F,ae,ve=a.imprintContext?.pendingGroundingExplanationIds??[];fe.draft?.decision==="none"&&Y.recordNoop(fe.draft.reason);let Fe=fe.draft?.decision==="recognize"?fe.draft:void 0;if(Fe&&!Se&&!qe){let re=a.imprintContext?.explanations.find(de=>de.id===Fe.explanationId&&de.state==="grounded");re?ae={explanationId:re.id,title:Fe.summary.title,detail:Fe.summary.detail,statement:re.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let vo=fe.draft?.decision==="mutate"||fe.draft?.decision==="apply"?fe.draft:void 0;if(a.threadId&&vo&&!Se&&!qe)try{F=await Y.capture(vo,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:ve,applicationOccurred:xe.length>0||ue.some(re=>re.status==="resolved")}),F?(Ae={state:"mutated"},await D.recordImprintEvidence({summary:F,threadId:a.threadId,jobId:a.id}).catch(re=>console.warn(`${U} Canonical Imprint evidence linkage failed:`,re))):Ae={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(re){Ae={state:"invalid",reason:re instanceof Error?re.message:String(re)},console.warn(`${U} Continuous imprint update failed; the thread result remains available:`,re instanceof Error?re.message:String(re))}else vo&&(Ae={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});fe.error&&console.warn(`${U} Ignored invalid imprint block: ${fe.error}`),(Ae.state==="missing"||Ae.state==="invalid")&&Y.recordAssessmentFailure(Ae.state);let Io=F?.transactionId;if(a.threadId&&F&&!F.grounding){let re=await O.getThread(a.threadId),de=new Set(F.changes.map(vt=>vt.explanationId)),yt=re?Wd(re.messages,de):void 0;if(yt?.imprintSummary){let vt=yt.imprintSummary;await O.updateAssistantMessage(a.threadId,yt.jobId,{imprintSummary:{...vt,detail:F.detail,changes:F.changes,additionalObservationCount:(vt.additionalObservationCount??0)+1,coalescedTransactionIds:[...vt.coalescedTransactionIds??[],F.transactionId]}}),F=void 0}}let wo=oi({question:oe,resolutions:ue,changedFiles:xe,decisionRequired:!!qe,imprintTransactionId:Io,groundingRequired:!!F?.grounding}),gs=_e?.flatMap(re=>re.kind==="orientation"?[re.orientation]:[])??[],jt=a.lifecycle?fn(a.lifecycle,Io?[Io]:[],Ae):void 0;if(a.threadId){let re=C?qe?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Je;await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:re,resolutions:!C&&ue.length>0?ue:void 0,question:C?void 0:oe??void 0,sessionId:X.sessionId,toolsUsed:C?void 0:Me,editEvents:!C&&X.editEvents&&X.editEvents.length>0?X.editEvents:void 0,segments:!C&&_e&&_e.length>0?_e:void 0,turn:{phase:"complete",orientation:gs,result:wo},result:wo,memoryReviewCard:qe??void 0,memoryReceipt:Le,imprintSummary:F,imprintRecognition:ae,modelDetails:ee.length>0?ee:void 0,model:a.model,provider:P,...jt?{lifecycle:jt}:{}})}if(a.threadId&&!Se&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let re=a.feedback.annotations.flatMap(de=>de.linkedSelector?[de.pathname?`${de.pathname}:${de.linkedSelector}`:de.linkedSelector]:[]);try{await D.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(Lt(a.feedback)||"[request unavailable]"),responseSummary:oe??Je,outcome:oe?"question_asked":ue.some(de=>de.status==="resolved")?"completed":"no_change",execution:{provider:P,model:a.model,sessionId:X.sessionId},subjectHints:re,filePaths:[...(X.fileEdits??[]).map(de=>de.file_path),...(X.editEvents??[]).flatMap(de=>de.filePath?[de.filePath]:[])].map(de=>Zr(de)?Dd(i,de):de),resolutions:ue.map(de=>({status:de.status,summary:de.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(de=>de.id),submissionIds:jt?.submissionIds,outcomeId:jt?.outcomeId,imprintEvidenceIds:jt?.imprintEvidenceIds,imprintAssessment:jt?.imprintAssessment})}catch(de){console.warn(`${U} Canonical memory capture failed; iteration remains available in legacy history:`,de instanceof Error?de.message:String(de))}}Le?.status==="committed"&&Le.decisionId&&P!=="copilot"&&await ht({provider:P,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Le.decisionId}`}),oe&&(console.log(`${U} \u{1F4AC} Question detected: "${oe.slice(0,120)}" \u2192 broadcasting to ${L.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:oe,annotationIds:a.annotationIds},a.id,a.sourceId)),ee.length>0&&(console.log(`${U} Applied model gap(s): ${ee.map(re=>`${re.category}/${re.element}`).join(", ")}`),E.broadcast({type:"novel_patterns",jobId:a.id,patterns:ee,threadId:a.threadId},a.id,a.sourceId)),E.broadcast({type:"done",jobId:a.id,success:!0,resolutions:ue.length>0?ue:void 0,responseText:Je,threadId:a.threadId,annotationIds:a.annotationIds,result:wo},a.id,a.sourceId),ke.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${U} Error: ${X.error}`),a.status="error",a.error=X.error,a.threadId&&await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:X.error||"Unknown error",model:a.model,provider:P,...a.lifecycle?{lifecycle:fn(a.lifecycle)}:{}}),E.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:X.error||"Unknown error",provider:P,model:a.model,recoverable:X.recoverableError,code:X.errorCode},a.id,a.sourceId),ke.push({id:a.id,status:"error",completedAt:Date.now(),error:X.error,threadId:a.threadId,annotationIds:a.annotationIds});st()});let Rt=Cd(async(a,y)=>{if(Qd(a,y),a.method==="OPTIONS"){y.writeHead(204),y.end();return}let M=a.url||"/",v=M.split("?")[0],A=new URL(M,`http://127.0.0.1:${f}`),P=A.pathname,C=Yd(a,A);if(C&&C!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:po(i)});return}if(a.headers.origin){if(!es(a.headers.origin)){_(y,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(C!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:po(i)});return}}try{if(a.method==="POST"&&P==="/draft-attachments"){let $=A.searchParams.get("annotationId")?.trim()??"",q=A.searchParams.get("name")?.trim()??"",G=A.searchParams.get("kind"),U=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!$||$.length>128||!/^[a-z0-9_-]+$/i.test($)){_(y,400,{error:"A valid annotationId is required."});return}if(G!=="svg"&&G!=="text"||G==="svg"&&U!=="image/svg+xml"||G==="text"&&U!=="text/plain"){_(y,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let pe=await Xd(a,Gd);if(pe.length===0){_(y,400,{error:"Attachment is empty."});return}let z=await B.stage({annotationId:$,name:q,mimeType:U,kind:G,data:pe});_(y,201,{attachment:{id:z.id,name:z.name,mimeType:z.mimeType,size:z.size,kind:z.kind}})}else if(a.method==="POST"&&P==="/draft-attachments/claim"){let $=await Oe(a),q=Array.isArray($.ids)?$.ids.filter(G=>typeof G=="string").slice(0,100):[];await B.claim(q),_(y,200,{ok:!0})}else if(a.method==="DELETE"&&P.startsWith("/draft-attachments/"))await B.release([P.slice(19)]),_(y,200,{ok:!0});else if(a.method==="POST"&&P==="/send")await ct(a,y);else if(a.method==="POST"&&P==="/capture/native"){if(!p){_(y,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await Oe(a),q=typeof $.pageUrl=="string"?$.pageUrl:"",G=$.clip&&typeof $.clip=="object"&&!Array.isArray($.clip)?$.clip:null;if(!q||!G){_(y,400,{error:"pageUrl and clip are required."});return}let U=await Ui(p,{pageUrl:q,clip:{x:Number(G.x),y:Number(G.y),width:Number(G.width),height:Number(G.height)},scale:typeof $.scale=="number"?$.scale:1});y.writeHead(200,{"Content-Type":"image/webp","Content-Length":U.length,"Cache-Control":"no-store"}),y.end(U)}else if(a.method==="GET"&&P==="/events")et(a,y);else if(a.method==="GET"&&P==="/status")await dt(a,y,C);else if(a.method==="GET"&&P==="/ui-preferences")await ft(y);else if(a.method==="PATCH"&&P==="/ui-preferences")await ho(a,y);else if(a.method==="PATCH"&&P==="/config")await lt(a,y);else if(a.method==="POST"&&P==="/leases"){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Oe(a),q=typeof $.leaseId=="string"?$.leaseId.trim():"",G=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!q||q.length>128){_(y,400,{error:"A valid leaseId is required."});return}Q();let U=N.acquire(q,G);_(y,201,{ok:!0,lease:U,ttlMs:Vr})}catch{_(y,400,{error:"Invalid lease request."})}}else if(P.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(P.slice(8))}catch{_(y,400,{error:"Invalid lease id."});return}if(!$){_(y,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let q=N.heartbeat($);if(!q){_(y,404,{error:"Lease not found."});return}_(y,200,{ok:!0,lease:q})}else{let q=N.release($);_(y,q.found?200:404,{ok:q.found}),q.becameEmpty&&H()}}else if(a.method==="POST"&&P==="/shutdown"){if(l!=="detached"){_(y,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}_(y,200,{ok:!0}),setTimeout(w,100)}else if(a.method==="POST"&&P==="/restart"){if(l!=="detached"){_(y,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}_(y,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of L)try{$.res.end()}catch{}Rt.close(()=>{Wr(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"&&P==="/capabilities")_(y,200,{providers:m});else if(P.startsWith("/imprint/"))await be(a,y,P);else if(P.startsWith("/memory/"))await fo(a,y,P);else if(a.method==="POST"&&P==="/mcp/install")await yo(a,y);else if(a.method==="POST"&&P==="/reply")await Ee(a,y);else if(a.method==="POST"&&P==="/cancel")go(a,y);else if(a.method==="POST"&&P==="/materialize")_(y,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&P==="/materialization-runs")_(y,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&P==="/projection-runs"){let $=await se.loadRuns();_(y,200,$)}else if(a.method==="GET"&&P==="/projection/proposals"){let $=await se.loadModelProposals();_(y,200,$)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply-selected")){let $=P.slice(22,-15);await Be($,a,y)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply")){let $=P.slice(22,-6);await Ne($,y)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/dismiss")){let $=P.slice(22,-8);await pt($,a,y)}else if(P.startsWith("/model/proposals/"))_(y,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&P==="/model/component")await vn(a,y);else if(a.method==="DELETE"&&P==="/model/component")await ss(a,y);else if(a.method==="PATCH"&&P==="/model/token")await as(a,y);else if(a.method==="DELETE"&&P==="/model/token")await cs(a,y);else if(a.method==="POST"&&P==="/model/consolidate")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&P==="/model/synthesize")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&P==="/model"){let $=await se.loadModel();_(y,200,{model:$})}else if(a.method==="GET"&&P.startsWith("/jobs/")&&P.endsWith("/events")){let $=P.slice(6,P.length-7),q=parseInt(A.searchParams.get("afterSeq")??"-1",10),G=E.getBufferedEvents($,isNaN(q)?-1:q);G?_(y,200,G):_(y,404,{error:"Unknown job"})}else if(a.method==="GET"&&v.startsWith("/files/"))await us(v.slice(7),y);else if(a.method==="GET"&&P==="/threads/recent"){let $=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),q=await O.listRecent($);_(y,200,q)}else if(a.method==="GET"&&P.startsWith("/decision/")){let $=P.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(y,400,{error:"Invalid decision id"});else{let q=await O.getThread($),G=[...q?.messages??[]].reverse().find(U=>U.annotationSnapshot);if(q&&G?.annotationSnapshot){let U=[...q.messages].reverse().find(pe=>pe.resolutions?.length);_(y,200,{decision:{id:q.id,createdAt:G.timestamp,url:G.annotationSnapshot.url,viewport:G.annotationSnapshot.viewport,color:G.annotationSnapshot.color,annotations:G.annotationSnapshot.annotations,resolutions:U?.resolutions??[]},authority:"thread_snapshot"})}else{let U=await Pe.loadDecision($);U?_(y,200,{decision:U,authority:"legacy_archive"}):_(y,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&P.startsWith("/thread/")){let $=P.slice(8);await ms($,y)}else if(a.method==="DELETE"&&P.startsWith("/thread/")){let $=P.slice(8);await fs($,y)}else a.method==="GET"&&(P==="/canvas"||P==="/canvas/")?ds(a,y):a.method==="GET"&&P==="/canvas/manifest"?await ls(y):a.method==="GET"&&P==="/canvas/app.mjs"?await ps(y):_(y,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(y,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function fo(a,y,M){try{if(a.method==="GET"&&M==="/memory/status"){_(y,200,await D.status());return}if(a.method==="GET"&&M==="/memory/diagnostics"){_(y,200,await D.diagnostics());return}if(a.method==="GET"&&M==="/memory/model-view"){_(y,200,await D.getModelView());return}if(a.method==="GET"&&M==="/memory/imprint-view"){let v=await O.load(),A=[...new Set(Object.values(v.threads).flatMap(P=>yn(P.messages)))];_(y,200,await D.getImprintView(A,new Set(Object.keys(v.threads))));return}if(a.method==="POST"&&M==="/memory/constraints"){let v=await Oe(a),A=typeof v.reactComponent=="string"?v.reactComponent.trim():"",P=await D.getModelView(),C=A?P.entries.filter($=>$.key===`components.${A}`||$.key.startsWith(`components.${A}.`)):[];_(y,200,{modelEntries:C});return}if(a.method==="POST"&&M==="/memory/conversation-action"){let v=await Oe(a),A=typeof v.threadId=="string"?v.threadId:"",P=typeof v.proposalId=="string"?v.proposalId:"",C=String(v.action);if(!A||!P||!["accept","edit_and_accept","reject","defer"].includes(C)){_(y,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await O.getThread(A),q=$?.messages.find(X=>X.memoryReviewCard?.proposalId===P)?.memoryReviewCard;if(!$||!q){_(y,409,{error:"This decision review card is not available in the thread."});return}let G=await se.findModelProposalsByThread(A),U=(await Promise.all(G.map(async X=>({proposal:X,matches:(await Promise.all(X.decisionIds.map(xe=>D.findPendingProposalForLegacyDecision(xe)))).some(xe=>xe?.proposalId===P)})))).find(X=>X.matches)?.proposal,pe={proposalId:P,action:C,kind:q.kind,claim:C==="edit_and_accept"&&typeof v.claim=="string"?v.claim.trim():void 0,reason:C==="defer"?void 0:`The owner explicitly chose ${C.replaceAll("_"," ")} from the decision review card.`,taskContext:C==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:C==="defer"?["different_action","owner_request"]:void 0};if(pe.action==="edit_and_accept"&&!pe.claim){_(y,400,{error:"Edited decision wording is required."});return}let z=await D.commitConversationalReview(pe),me=`memory-${rt().slice(0,8)}`,le=C==="accept"?"> Accepted decision":C==="edit_and_accept"?"> Edited and accepted decision":C==="reject"?"> Rejected decision":"> Deferred decision";await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:me,replyToQuestion:le}),await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:me,responseText:"",memoryReceipt:z,provider:Ht(typeof v.provider=="string"?v.provider:void 0),model:typeof v.model=="string"?v.model:void 0}),z.status==="committed"&&U&&await se.dismissModelProposal(U.id);let ne=Ht(typeof v.provider=="string"?v.provider:void 0);z.status==="committed"&&z.decisionId&&ne!=="copilot"&&await ht({provider:ne,model:typeof v.model=="string"?v.model:void 0,agentSettings:At(v),threadId:A,reason:`Project accepted decision ${z.decisionId}`}),_(y,z.status==="committed"?200:409,{receipt:z});return}if(a.method==="POST"&&M==="/memory/analyze"){let v=await Oe(a),A=await D.analyzeLegacy({projectKey:typeof v.projectKey=="string"?v.projectKey:void 0}),P=Object.fromEntries([...new Set(A.issues.map(C=>C.code))].map(C=>[C,A.issues.filter($=>$.code===C).length]));_(y,200,{...A,issues:void 0,issueCounts:P});return}if(a.method==="POST"&&M==="/memory/review"){let v=await Oe(a),A=await D.review(Vo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/context"){let v=await Oe(a),A=await D.contextualize(Vo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/initialize"){let v=await Oe(a),A=await D.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:it});_(y,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&M==="/memory/plan"){let v=await Oe(a),A=await D.planReview(Ho(v.command),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,A.result.ok?200:422,A);return}if(a.method==="POST"&&M==="/memory/commit"){let v=await Oe(a),A=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},P=await D.commitReview(Ho(v.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});_(y,200,{status:await D.status(),journal:P.report});return}if(a.method==="POST"&&M==="/memory/recover"){let v=await Oe(a),A=await D.recover(v.confirm===!0);_(y,200,{status:await D.status(),journal:A.report});return}_(y,404,{error:"Memory endpoint not found."})}catch(v){let A=v instanceof Error?v.message:String(v),P=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),C=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(P||C){_(y,P?409:400,{error:A});return}throw v}}async function be(a,y,M){if(a.method==="GET"&&M==="/imprint/status"){let[v,A]=await Promise.all([Y.store.load(),O.load()]),P=[...new Set(Object.values(A.threads).flatMap(C=>yn(C.messages)))].filter(C=>v.graph.explanations.some($=>$.id===C&&$.state==="testing"));_(y,200,{state:"ready",head:v.graph.head,updatedAt:v.graph.updatedAt,explanationCount:v.graph.explanations.filter(C=>C.state!=="retired").length,concreteCount:v.graph.concrete.length,relationCount:v.graph.relations.length,pendingGroundingCount:P.length,recoveredTransactions:v.recoveredTransactions,admission:Y.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&M==="/imprint/action"){let v=await Oe(a),A=typeof v.threadId=="string"?v.threadId:"",P=typeof v.transactionId=="string"?v.transactionId:"",C=String(v.action);if(!A||!P||!["yes","this_time","no"].includes(C)){_(y,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await O.getThread(A),G=[...q?.messages??[]].reverse().find(ne=>ne.role==="assistant"&&ne.imprintSummary?.transactionId===P),U=G?.imprintSummary;if(!q||!G||!U){_(y,409,{error:"This imprint summary is not available in the thread."});return}if(U.resolvedAction){_(y,409,{error:"This imprint summary has already been resolved."});return}let pe=`imprint-${rt().slice(0,8)}`;await Y.applyGroundingAction({summary:U,action:C,threadId:A,jobId:pe}),C!=="no"&&await D.recordImprintEvidence({summary:U,action:C,threadId:A,jobId:pe}).catch(ne=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ne));let z=zt(G.result,!!G.question),me=G.turn?{...G.turn,result:zt(G.turn.result,!!G.question)}:void 0;await O.updateAssistantMessage(A,G.jobId,{imprintSummary:{...U,resolvedAction:C},...z?{result:z}:{},...me?{turn:me}:{}});let le={yes:"> Yes",this_time:"> This time",no:"> No"};if(await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:pe,replyToQuestion:le[C]}),C==="no"){let ne="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",X=oi({question:ne});await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:pe,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:ne,turn:{phase:"complete",orientation:[],result:X},result:X})}_(y,200,{ok:!0,action:C});return}_(y,404,{error:"Imprint endpoint not found."})}async function ct(a,y){let{screenshot:M,feedback:v,color:A,provider:P,model:C,reasoningEffort:$,serviceTier:q,sourceId:G,pastedImages:U,pageScreenshots:pe}=await Ko(a),z;try{z=JSON.parse(v)}catch{_(y,400,{error:"Invalid feedback JSON"});return}let me=z.annotations.flatMap(ee=>(ee.attachments??[]).map(F=>({id:F.id,annotationId:ee.id}))),le;try{le=me.length>0?await B.promote(me):void 0}catch(ee){_(y,409,{error:ee instanceof Error?ee.message:"Draft attachment unavailable."});return}let ne=rt().slice(0,8),X={};if(pe.length>0)for(let ee of pe){let F=encodeURIComponent(ee.pathname),ae=De(c,`screenshot-${ne}-${F}.webp`);await lo(ae,ee.data),X[ee.pathname]=ae}let xe=De(c,`screenshot-${ne}.webp`);await lo(xe,M);let we={};if(U.length>0)for(let ee of U){let F=De(c,`pasted-${ne}-${ee.annotationId}-${ee.index}.webp`);await lo(F,ee.data),we[ee.annotationId]||(we[ee.annotationId]=[]),we[ee.annotationId].push(F)}let je=Nr(z),ge;if(je.length>0){let ee=await O.findContinuationThread(je);ee?(ge=ee.id,await O.addElementIdentifiers(ge,je)):ge=(await O.createThread(`thread-${rt()}`,je)).id}else ge=(await O.createThread(`thread-${rt()}`,[])).id;let Z=z.annotations.map(ee=>ee.id),fe=Object.keys(X).length>0,Je=await dr(D,z,je,ee=>console.warn(`[\u22B9 ${f}:${ne}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),Ae=(await O.getThread(ge))?.messages??[],oe=await Y.contextualize({text:Lt(z),subjectHints:[...je,...z.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(F=>!!F))],pendingGroundingExplanationIds:yn(Ae),correctionExplanationIds:Qr(Ae)}).catch(ee=>{console.warn(`[\u22B9 ${f}:${ne}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),ue=ri({jobId:ne,threadId:ge,artifactIds:Br(z,ne)}),Me={id:ne,status:"queued",screenshotPath:xe,feedback:z,createdAt:Date.now(),color:A,threadId:ge,annotationIds:Z,provider:Ht(P),model:C||void 0,agentSettings:At({reasoningEffort:$,serviceTier:q}),...Object.keys(we).length>0?{imagePaths:we}:{},...le&&Object.keys(le).length>0?{attachmentFiles:le}:{},sourceId:G||void 0,...fe?{screenshotPaths:X}:{},...Je?{memoryReview:Je}:{},...oe?{imprintContext:oe}:{},lifecycle:ue},ut=new Set(z.annotations.map(ee=>ee.pathname).filter(Boolean)),_e;if(ut.size>1){let ee=new Map;for(let F of z.annotations){let ae=F.pathname||"(unknown)";ee.has(ae)||ee.set(ae,[]),ee.get(ae).push(F.instruction||Xr({...z,annotations:[F]}))}_e=[...ee.entries()].map(([F,ae])=>`\`${F}\`
210
- ${ae.map(ve=>`- ${ve}`).join(`
221
+ ${Mr}`;let F=Pl(a.color,`[\u22B9 ${y}:${a.id}]`),ue=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 ${ue} (provider: ${k})${a.threadId?` (thread: ${a.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let z=new ei(a.id),he=new di(a.id,a.imprintContext),de=(ee,fe)=>{if(ee.type==="delta"&&"text"in ee){let Ce=he.push(ee.text),qe=z.push(Ce.visibleText);qe.visibleText&&(j.accumulateText(fe,"response",qe.visibleText),j.broadcast({...ee,text:qe.visibleText},fe,a.sourceId));for(let Ee of qe.orientations)j.broadcast({type:"orientation",jobId:fe,orientation:Ee},fe,a.sourceId);for(let Ee of Ce.usages)j.broadcast({type:"imprint_used",jobId:fe,usage:Ee},fe,a.sourceId);return}else ee.type==="thinking"&&"text"in ee&&j.accumulateText(fe,"thinking",ee.text);j.broadcast(ee,fe,a.sourceId)},{process:ie,result:ye}=k==="codex"?En(a.id,{prompt:W,projectRoot:o,screenshotPath:a.screenshotPath,resumeSessionId:q,model:a.model,sandboxMode:$?"read-only":void 0,configOverrides:kn(a.agentSettings),onEvent:de}):k==="copilot"?Bo(a.id,{prompt:W,projectRoot:o,resumeSessionId:q,model:a.model,timeoutMs:S,copilotPath:m.copilot?.path??P,onEvent:de}):Rn(a.id,{prompt:W,projectRoot:o,maxTurns:d,maxBudgetUsd:l,allowedTools:$?["Read"]:w,claudePath:b,resumeSessionId:q,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:S,onEvent:de});j.setActiveProcess(a.id,ie);let Y=await ye,Ie=[...(Y.fileEdits??[]).map(ee=>ee.file_path),...(Y.editEvents??[]).flatMap(ee=>ee.filePath?[ee.filePath]:[])],Pe=he.finalize(Y.text),we=so(Pe.visibleText,a.id),Z=z.finalize(Pe.visibleText),Se=we.visibleText,He=Or(Se),me=D?si(Se,{context:a.imprintContext,requestText:I??Ut(a.feedback),applicationOccurred:Ie.length>0||He.some(ee=>ee.status==="resolved")}):{visibleText:Se,draft:void 0,error:void 0},Ge=me.visibleText,Re=D?me.error?{state:me.error.includes("missing")?"missing":"invalid",reason:me.error}:me.draft?.decision==="none"?{state:"none",reason:me.draft.reason}:me.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let ee of Z.orientations)j.broadcast({type:"orientation",jobId:a.id,orientation:ee},a.id,a.sourceId);for(let ee of Pe.usages)j.broadcast({type:"imprint_used",jobId:a.id,usage:ee},a.id,a.sourceId);if(a.result=Ge,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(re=>`${re.tool} ${re.file_path}`).join(", ")}`),Y.editEvents&&Y.editEvents.length>0&&console.log(`${F} Captured ${Y.editEvents.length} edit event(s): ${Y.editEvents.map(re=>`${re.operation} ${re.filePath}`).join(", ")}`),a.status="done";let ee=Cr(Se),fe=He;if(fe.length>0&&a.annotationIds&&a.annotationIds.length>0){let re=new Set(a.annotationIds);fe.every(Ye=>re.has(Ye.annotationId))||(fe=fe.map((Ye,bt)=>({...Ye,annotationId:a.annotationIds[bt%a.annotationIds.length]})))}let Ce=Y.fileEdits&&Y.fileEdits.length>0?Y.fileEdits.map(re=>`${re.tool} ${re.file_path.split("/").pop()}`):Y.toolsUsed,qe=j.getBufferedEvents(a.id),Ee=Il(qe?.events??[],o,we.segments),je,te=kr(Se),U=Pr(Se);if(U)if(!(a.memoryReview?.packets.some(se=>se.proposalId===U.proposalId)||a.surfacedProposalIds?.includes(U.proposalId)))je={status:"rejected",action:U.action,proposalId:U.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{je=await B.commitConversationalReview(U)}catch(se){je={status:"rejected",action:U.action,proposalId:U.proposalId,message:se instanceof Error?se.message:String(se)}}let oe=Dr(Se,Ie.length),le,Ve,xo,So,Os=a.imprintContext?.pendingGroundingExplanationIds??[];if(me.draft){let re=me.draft.decision==="recognize"?[me.draft.explanationId]:[],se=me.draft.decision==="recognize"?re:[...me.draft.usedExplanationIds??[],...me.draft.appliedExplanationIds??[]],Ye=me.draft.decision==="recognize"?[]:me.draft.appliedExplanationIds??[];se.length>0&&(xo=[...new Set(se)]),Ye.length>0&&(So=[...new Set(Ye)])}me.draft?.decision==="none"&&X.recordNoop(me.draft.reason);let Pn=me.draft?.decision==="recognize"?me.draft:void 0;if(Pn&&!U&&!te){let re=a.imprintContext?.explanations.find(se=>se.id===Pn.explanationId&&se.state==="grounded");re?Ve={explanationId:re.id,title:Pn.summary.title,detail:Pn.summary.detail,statement:re.statement}:Re={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let ki=me.draft?.decision==="mutate"||me.draft?.decision==="apply"?me.draft:void 0;if(a.threadId&&ki&&!U&&!te)try{le=await X.capture(ki,{threadId:a.threadId,jobId:a.id,concreteModel:await ce.loadModel(),pendingGroundingExplanationIds:Os,applicationOccurred:Ie.length>0||fe.some(re=>re.status==="resolved")}),le?(Re={state:"mutated"},await B.recordImprintEvidence({summary:le,threadId:a.threadId,jobId:a.id}).catch(re=>console.warn(`${F} Canonical Imprint evidence linkage failed:`,re))):Re={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(re){Re={state:"invalid",reason:re instanceof Error?re.message:String(re)},console.warn(`${F} Continuous imprint update failed; the thread result remains available:`,re instanceof Error?re.message:String(re))}else ki&&(Re={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});me.error&&console.warn(`${F} Ignored invalid imprint block: ${me.error}`),(Re.state==="missing"||Re.state==="invalid")&&X.recordAssessmentFailure(Re.state);let Ri=le?.transactionId;if(a.threadId&&le&&!le.grounding){let re=await N.getThread(a.threadId),se=new Set(le.changes.map(bt=>bt.explanationId)),Ye=re?vl(re.messages,se):void 0;if(Ye?.imprintSummary){let bt=Ye.imprintSummary;await N.updateAssistantMessage(a.threadId,Ye.jobId,{imprintSummary:{...bt,detail:le.detail,changes:le.changes,additionalObservationCount:(bt.additionalObservationCount??0)+1,coalescedTransactionIds:[...bt.coalescedTransactionIds??[],le.transactionId]}}),le=void 0}}let ji=uo({question:ee,resolutions:fe,changedFiles:Ie,decisionRequired:!!te,imprintTransactionId:Ri,groundingRequired:!!le?.grounding}),Ds=Ee?.flatMap(re=>re.kind==="orientation"?[re.orientation]:[])??[],Et=a.lifecycle?wn(a.lifecycle,Ri?[Ri]:[],Re):void 0;if(a.threadId){let re=$?te?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Ge;await N.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:re,resolutions:!$&&fe.length>0?fe:void 0,question:$?void 0:ee??void 0,sessionId:Y.sessionId,toolsUsed:$?void 0:Ce,editEvents:!$&&Y.editEvents&&Y.editEvents.length>0?Y.editEvents:void 0,segments:!$&&Ee&&Ee.length>0?Ee:void 0,turn:{phase:"complete",orientation:Ds,result:ji},result:ji,memoryReviewCard:te??void 0,memoryReceipt:je,imprintSummary:le,imprintRecognition:Ve,imprintUsedExplanationIds:xo,imprintAppliedExplanationIds:So,modelDetails:oe.length>0?oe:void 0,model:a.model,provider:k,...Et?{lifecycle:Et}:{}})}if(a.threadId&&!U&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let re=a.feedback.annotations.flatMap(se=>se.linkedSelector?[se.pathname?`${se.pathname}:${se.linkedSelector}`:se.linkedSelector]:[]);try{await B.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:I??(Ut(a.feedback)||"[request unavailable]"),responseSummary:ee??Ge,outcome:ee?"question_asked":fe.some(se=>se.status==="resolved")?"completed":"no_change",execution:{provider:k,model:a.model,sessionId:Y.sessionId},subjectHints:re,filePaths:[...(Y.fileEdits??[]).map(se=>se.file_path),...(Y.editEvents??[]).flatMap(se=>se.filePath?[se.filePath]:[])].map(se=>vs(se)?cl(o,se):se),resolutions:fe.map(se=>({status:se.status,summary:se.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(se=>se.id),submissionIds:Et?.submissionIds,outcomeId:Et?.outcomeId,imprintEvidenceIds:Et?.imprintEvidenceIds,imprintAssessment:Et?.imprintAssessment})}catch(se){console.warn(`${F} Canonical memory capture failed; iteration remains available in legacy history:`,se instanceof Error?se.message:String(se))}}je?.status==="committed"&&je.decisionId&&k!=="copilot"&&await It({provider:k,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${je.decisionId}`}),ee&&(console.log(`${F} \u{1F4AC} Question detected: "${ee.slice(0,120)}" \u2192 broadcasting to ${L.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),j.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:ee,annotationIds:a.annotationIds},a.id,a.sourceId)),oe.length>0&&(console.log(`${F} Applied model gap(s): ${oe.map(re=>`${re.category}/${re.element}`).join(", ")}`),j.broadcast({type:"novel_patterns",jobId:a.id,patterns:oe,threadId:a.threadId},a.id,a.sourceId)),j.broadcast({type:"done",jobId:a.id,success:!0,resolutions:fe.length>0?fe:void 0,responseText:Ge,threadId:a.threadId,annotationIds:a.annotationIds,result:ji},a.id,a.sourceId),Me.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 N.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:Y.error||"Unknown error",model:a.model,provider:k,...a.lifecycle?{lifecycle:wn(a.lifecycle)}:{}}),j.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:Y.error||"Unknown error",provider:k,model:a.model,recoverable:Y.recoverableError,code:Y.errorCode},a.id,a.sourceId),Me.push({id:a.id,status:"error",completedAt:Date.now(),error:Y.error,threadId:a.threadId,annotationIds:a.annotationIds});dt()});let At=rl(async(a,v)=>{if(xl(a,v),a.method==="OPTIONS"){v.writeHead(204),v.end();return}let _=a.url||"/",I=_.split("?")[0],A=new URL(_,`http://127.0.0.1:${y}`),k=A.pathname,$=Tl(a,A);if($&&$!==r){C(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:$,projectName:Ii(o)});return}if(a.headers.origin){if(!Is(a.headers.origin)){C(v,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if($!==r){C(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:$,projectName:Ii(o)});return}}try{if(a.method==="POST"&&k==="/draft-attachments"){let D=A.searchParams.get("annotationId")?.trim()??"",q=A.searchParams.get("name")?.trim()??"",W=A.searchParams.get("kind"),F=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!D||D.length>128||!/^[a-z0-9_-]+$/i.test(D)){C(v,400,{error:"A valid annotationId is required."});return}if(W!=="svg"&&W!=="text"||W==="svg"&&F!=="image/svg+xml"||W==="text"&&F!=="text/plain"){C(v,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ue=await Sl(a,yl);if(ue.length===0){C(v,400,{error:"Attachment is empty."});return}let z=await J.stage({annotationId:D,name:q,mimeType:F,kind:W,data:ue});C(v,201,{attachment:{id:z.id,name:z.name,mimeType:z.mimeType,size:z.size,kind:z.kind}})}else if(a.method==="POST"&&k==="/draft-attachments/claim"){let D=await De(a),q=Array.isArray(D.ids)?D.ids.filter(W=>typeof W=="string").slice(0,100):[];await J.claim(q),C(v,200,{ok:!0})}else if(a.method==="DELETE"&&k.startsWith("/draft-attachments/"))await J.release([k.slice(19)]),C(v,200,{ok:!0});else if(a.method==="POST"&&k==="/send")await pt(a,v);else if(a.method==="POST"&&k==="/capture/native"){if(!f){C(v,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let D=await De(a),q=typeof D.pageUrl=="string"?D.pageUrl:"",W=D.clip&&typeof D.clip=="object"&&!Array.isArray(D.clip)?D.clip:null;if(!q||!W){C(v,400,{error:"pageUrl and clip are required."});return}let F=await ir(f,{pageUrl:q,clip:{x:Number(W.x),y:Number(W.y),width:Number(W.width),height:Number(W.height)},scale:typeof D.scale=="number"?D.scale:1});v.writeHead(200,{"Content-Type":"image/webp","Content-Length":F.length,"Cache-Control":"no-store"}),v.end(F)}else if(a.method==="GET"&&k==="/events")nt(a,v);else if(a.method==="GET"&&k==="/status")await ut(a,v,$);else if(a.method==="GET"&&k==="/ui-preferences")await vt(v);else if(a.method==="PATCH"&&k==="/ui-preferences")await Si(a,v);else if(a.method==="PATCH"&&k==="/config")await mt(a,v);else if(a.method==="POST"&&k==="/leases"){if(p!=="detached"){C(v,409,{error:"Bridge leases are only available for detached bridges."});return}try{let D=await De(a),q=typeof D.leaseId=="string"?D.leaseId.trim():"",W=typeof D.ownerPid=="number"&&Number.isInteger(D.ownerPid)&&D.ownerPid>0?D.ownerPid:void 0;if(!q||q.length>128){C(v,400,{error:"A valid leaseId is required."});return}Q();let F=O.acquire(q,W);C(v,201,{ok:!0,lease:F,ttlMs:ms})}catch{C(v,400,{error:"Invalid lease request."})}}else if(k.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){C(v,409,{error:"Bridge leases are only available for detached bridges."});return}let D="";try{D=decodeURIComponent(k.slice(8))}catch{C(v,400,{error:"Invalid lease id."});return}if(!D){C(v,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let q=O.heartbeat(D);if(!q){C(v,404,{error:"Lease not found."});return}C(v,200,{ok:!0,lease:q})}else{let q=O.release(D);C(v,q.found?200:404,{ok:q.found}),q.becameEmpty&&V()}}else if(a.method==="POST"&&k==="/shutdown"){if(p!=="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:p});return}C(v,200,{ok:!0}),setTimeout(x,100)}else if(a.method==="POST"&&k==="/restart"){if(p!=="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:p});return}C(v,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let D of L)try{D.res.end()}catch{}At.close(()=>{ps(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"&&k==="/capabilities")C(v,200,{providers:m});else if(k.startsWith("/imprint/"))await xe(a,v,k);else if(k.startsWith("/memory/"))await xi(a,v,k);else if(a.method==="POST"&&k==="/mcp/install")await Pi(a,v);else if(a.method==="POST"&&k==="/reply")await _e(a,v);else if(a.method==="POST"&&k==="/cancel")Ti(a,v);else if(a.method==="POST"&&k==="/materialize")C(v,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&k==="/materialization-runs")C(v,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&k==="/projection-runs"){let D=await ce.loadRuns();C(v,200,D)}else if(a.method==="GET"&&k==="/projection/proposals"){let D=await ce.loadModelProposals();C(v,200,D)}else if(a.method==="POST"&&k.startsWith("/projection/proposals/")&&k.endsWith("/apply-selected")){let D=k.slice(22,-15);await Je(D,a,v)}else if(a.method==="POST"&&k.startsWith("/projection/proposals/")&&k.endsWith("/apply")){let D=k.slice(22,-6);await Be(D,v)}else if(a.method==="POST"&&k.startsWith("/projection/proposals/")&&k.endsWith("/dismiss")){let D=k.slice(22,-8);await ft(D,a,v)}else if(k.startsWith("/model/proposals/"))C(v,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&k==="/model/component")await Tn(a,v);else if(a.method==="DELETE"&&k==="/model/component")await Ps(a,v);else if(a.method==="PATCH"&&k==="/model/token")await ks(a,v);else if(a.method==="DELETE"&&k==="/model/token")await Rs(a,v);else if(a.method==="POST"&&k==="/model/consolidate")C(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&k==="/model/synthesize")C(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&k==="/model"){let D=await ce.loadModel();C(v,200,{model:D})}else if(a.method==="GET"&&k.startsWith("/jobs/")&&k.endsWith("/events")){let D=k.slice(6,k.length-7),q=parseInt(A.searchParams.get("afterSeq")??"-1",10),W=j.getBufferedEvents(D,isNaN(q)?-1:q);W?C(v,200,W):C(v,404,{error:"Unknown job"})}else if(a.method==="GET"&&I.startsWith("/files/"))await Es(I.slice(7),v);else if(a.method==="GET"&&k==="/threads/recent"){let D=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),q=await N.listRecent(D);C(v,200,q)}else if(a.method==="GET"&&k.startsWith("/decision/")){let D=k.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(D))C(v,400,{error:"Invalid decision id"});else{let q=await N.getThread(D),W=[...q?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(q&&W?.annotationSnapshot){let F=[...q.messages].reverse().find(ue=>ue.resolutions?.length);C(v,200,{decision:{id:q.id,createdAt:W.timestamp,url:W.annotationSnapshot.url,viewport:W.annotationSnapshot.viewport,color:W.annotationSnapshot.color,annotations:W.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await ke.loadDecision(D);F?C(v,200,{decision:F,authority:"legacy_archive"}):C(v,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&k.startsWith("/thread/")){let D=k.slice(8);await _s(D,v)}else if(a.method==="DELETE"&&k.startsWith("/thread/")){let D=k.slice(8);await Cs(D,v)}else a.method==="GET"&&(k==="/canvas"||k==="/canvas/")?js(a,v):a.method==="GET"&&k==="/canvas/manifest"?await As(v):a.method==="GET"&&k==="/canvas/app.mjs"?await Ms(v):C(v,404,{error:"Not found"})}catch(D){console.error("[Bridge] Request error:",D),C(v,500,{error:D instanceof Error?D.message:"Internal error"})}});async function xi(a,v,_){try{if(a.method==="GET"&&_==="/memory/status"){C(v,200,await B.status());return}if(a.method==="GET"&&_==="/memory/diagnostics"){C(v,200,await B.diagnostics());return}if(a.method==="GET"&&_==="/memory/model-view"){C(v,200,await B.getModelView());return}if(a.method==="GET"&&_==="/memory/imprint-view"){let I=await N.load(),A=[...new Set(Object.values(I.threads).flatMap(k=>Sn(k.messages)))];C(v,200,await B.getImprintView(A,new Set(Object.keys(I.threads))));return}if(a.method==="POST"&&_==="/memory/constraints"){let I=await De(a),A=typeof I.reactComponent=="string"?I.reactComponent.trim():"",k=await B.getModelView(),$=A?k.entries.filter(D=>D.key===`components.${A}`||D.key.startsWith(`components.${A}.`)):[];C(v,200,{modelEntries:$});return}if(a.method==="POST"&&_==="/memory/conversation-action"){let I=await De(a),A=typeof I.threadId=="string"?I.threadId:"",k=typeof I.proposalId=="string"?I.proposalId:"",$=String(I.action);if(!A||!k||!["accept","edit_and_accept","reject","defer"].includes($)){C(v,400,{error:"A valid thread, proposal, and review action are required."});return}let D=await N.getThread(A),q=D?.messages.find(ye=>ye.memoryReviewCard?.proposalId===k)?.memoryReviewCard;if(!D||!q){C(v,409,{error:"This decision review card is not available in the thread."});return}let W=await ce.findModelProposalsByThread(A),F=(await Promise.all(W.map(async ye=>({proposal:ye,matches:(await Promise.all(ye.decisionIds.map(Y=>B.findPendingProposalForLegacyDecision(Y)))).some(Y=>Y?.proposalId===k)})))).find(ye=>ye.matches)?.proposal,ue={proposalId:k,action:$,kind:q.kind,claim:$==="edit_and_accept"&&typeof I.claim=="string"?I.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(ue.action==="edit_and_accept"&&!ue.claim){C(v,400,{error:"Edited decision wording is required."});return}let z=await B.commitConversationalReview(ue),he=`memory-${ct().slice(0,8)}`,de=$==="accept"?"> Accepted decision":$==="edit_and_accept"?"> Edited and accepted decision":$==="reject"?"> Rejected decision":"> Deferred decision";await N.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:he,replyToQuestion:de}),await N.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:he,responseText:"",memoryReceipt:z,provider:Zt(typeof I.provider=="string"?I.provider:void 0),model:typeof I.model=="string"?I.model:void 0}),z.status==="committed"&&F&&await ce.dismissModelProposal(F.id);let ie=Zt(typeof I.provider=="string"?I.provider:void 0);z.status==="committed"&&z.decisionId&&ie!=="copilot"&&await It({provider:ie,model:typeof I.model=="string"?I.model:void 0,agentSettings:_t(I),threadId:A,reason:`Project accepted decision ${z.decisionId}`}),C(v,z.status==="committed"?200:409,{receipt:z});return}if(a.method==="POST"&&_==="/memory/analyze"){let I=await De(a),A=await B.analyzeLegacy({projectKey:typeof I.projectKey=="string"?I.projectKey:void 0}),k=Object.fromEntries([...new Set(A.issues.map($=>$.code))].map($=>[$,A.issues.filter(D=>D.code===$).length]));C(v,200,{...A,issues:void 0,issueCounts:k});return}if(a.method==="POST"&&_==="/memory/review"){let I=await De(a),A=await B.review(io(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});C(v,200,A);return}if(a.method==="POST"&&_==="/memory/context"){let I=await De(a),A=await B.contextualize(io(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});C(v,200,A);return}if(a.method==="POST"&&_==="/memory/initialize"){let I=await De(a),A=await B.initializeFromLegacy({confirmed:I.confirm===!0,projectKey:typeof I.projectKey=="string"?I.projectKey:void 0,writerVersion:at});C(v,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&_==="/memory/plan"){let I=await De(a),A=await B.planReview(no(I.command),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});C(v,A.result.ok?200:422,A);return}if(a.method==="POST"&&_==="/memory/commit"){let I=await De(a),A=I.transaction&&typeof I.transaction=="object"&&!Array.isArray(I.transaction)?I.transaction:{},k=await B.commitReview(no(I.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});C(v,200,{status:await B.status(),journal:k.report});return}if(a.method==="POST"&&_==="/memory/recover"){let I=await De(a),A=await B.recover(I.confirm===!0);C(v,200,{status:await B.status(),journal:A.report});return}C(v,404,{error:"Memory endpoint not found."})}catch(I){let A=I instanceof Error?I.message:String(I),k=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),$=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(k||$){C(v,k?409:400,{error:A});return}throw I}}async function xe(a,v,_){if(a.method==="GET"&&_==="/imprint/status"){let[I,A]=await Promise.all([X.store.load(),N.load()]),k=[...new Set(Object.values(A.threads).flatMap($=>Sn($.messages)))].filter($=>I.graph.explanations.some(D=>D.id===$&&D.state==="testing"));C(v,200,{state:"ready",head:I.graph.head,updatedAt:I.graph.updatedAt,explanationCount:I.graph.explanations.filter($=>$.state!=="retired").length,concreteCount:I.graph.concrete.length,relationCount:I.graph.relations.length,pendingGroundingCount:k.length,recoveredTransactions:I.recoveredTransactions,admission:X.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&_==="/imprint/action"){let I=await De(a),A=typeof I.threadId=="string"?I.threadId:"",k=typeof I.transactionId=="string"?I.transactionId:"",$=String(I.action);if(!A||!k||!["yes","this_time","no"].includes($)){C(v,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await N.getThread(A),W=[...q?.messages??[]].reverse().find(ie=>ie.role==="assistant"&&ie.imprintSummary?.transactionId===k),F=W?.imprintSummary;if(!q||!W||!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 ue=`imprint-${ct().slice(0,8)}`;await X.applyGroundingAction({summary:F,action:$,threadId:A,jobId:ue}),$!=="no"&&await B.recordImprintEvidence({summary:F,action:$,threadId:A,jobId:ue}).catch(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let z=Kt(W.result,!!W.question),he=W.turn?{...W.turn,result:Kt(W.turn.result,!!W.question)}:void 0;await N.updateAssistantMessage(A,W.jobId,{imprintSummary:{...F,resolvedAction:$},...z?{result:z}:{},...he?{turn:he}:{}});let de={yes:"> Yes",this_time:"> This time",no:"> No"};if(await N.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:ue,replyToQuestion:de[$]}),$==="no"){let ie="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",ye=uo({question:ie});await N.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:ue,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:ie,turn:{phase:"complete",orientation:[],result:ye},result:ye})}C(v,200,{ok:!0,action:$});return}C(v,404,{error:"Imprint endpoint not found."})}async function pt(a,v){let{screenshot:_,feedback:I,color:A,provider:k,model:$,reasoningEffort:D,serviceTier:q,sourceId:W,pastedImages:F,pageScreenshots:ue}=await oo(a),z;try{z=JSON.parse(I)}catch{C(v,400,{error:"Invalid feedback JSON"});return}let he=z.annotations.flatMap(te=>(te.attachments??[]).map(U=>({id:U.id,annotationId:te.id}))),de;try{de=he.length>0?await J.promote(he):void 0}catch(te){C(v,409,{error:te instanceof Error?te.message:"Draft attachment unavailable."});return}let ie=ct().slice(0,8),ye={};if(ue.length>0)for(let te of ue){let U=encodeURIComponent(te.pathname),oe=Ne(c,`screenshot-${ie}-${U}.webp`);await vi(oe,te.data),ye[te.pathname]=oe}let Y=Ne(c,`screenshot-${ie}.webp`);await vi(Y,_);let Ie={};if(F.length>0)for(let te of F){let U=Ne(c,`pasted-${ie}-${te.annotationId}-${te.index}.webp`);await vi(U,te.data),Ie[te.annotationId]||(Ie[te.annotationId]=[]),Ie[te.annotationId].push(U)}let Pe=es(z),we;if(Pe.length>0){let te=await N.findContinuationThread(Pe);te?(we=te.id,await N.addElementIdentifiers(we,Pe)):we=(await N.createThread(`thread-${ct()}`,Pe)).id}else we=(await N.createThread(`thread-${ct()}`,[])).id;let Z=z.annotations.map(te=>te.id),Se=Object.keys(ye).length>0,He=await Sr(B,z,Pe,te=>console.warn(`[\u22B9 ${y}:${ie}] Contextual memory unavailable; continuing without it:`,te instanceof Error?te.message:String(te))),me=(await N.getThread(we))?.messages??[],Ge=await X.contextualize({text:Ut(z),subjectHints:as(z,Pe),pendingGroundingExplanationIds:Sn(me),correctionExplanationIds:hs(me)}).catch(te=>{console.warn(`[\u22B9 ${y}:${ie}] Imprint context unavailable; continuing without it:`,te instanceof Error?te.message:String(te))}),Re=fo({jobId:ie,threadId:we,artifactIds:ts(z,ie)}),ee={id:ie,status:"queued",screenshotPath:Y,feedback:z,createdAt:Date.now(),color:A,threadId:we,annotationIds:Z,provider:Zt(k),model:$||void 0,agentSettings:_t({reasoningEffort:D,serviceTier:q}),...Object.keys(Ie).length>0?{imagePaths:Ie}:{},...de&&Object.keys(de).length>0?{attachmentFiles:de}:{},sourceId:W||void 0,...Se?{screenshotPaths:ye}:{},...He?{memoryReview:He}:{},...Ge?{imprintContext:Ge}:{},lifecycle:Re},fe=new Set(z.annotations.map(te=>te.pathname).filter(Boolean)),Ce;if(fe.size>1){let te=new Map;for(let U of z.annotations){let oe=U.pathname||"(unknown)";te.has(oe)||te.set(oe,[]),te.get(oe).push(U.instruction||gs({...z,annotations:[U]}))}Ce=[...te.entries()].map(([U,oe])=>`\`${U}\`
222
+ ${oe.map(le=>`- ${le}`).join(`
211
223
  `)}`).join(`
212
- `)}else _e=Xr(z);let Le=dn(z,Object.keys(we).length>0?we:void 0,le),qe=zr(z);await O.appendMessage(ge,{role:"human",timestamp:Date.now(),jobId:ne,screenshotPath:xe,...fe?{screenshotPaths:X}:{},...Object.keys(we).length>0?{imagePaths:we}:{},...le&&Object.keys(le).length>0?{attachmentFiles:le}:{},annotationIds:Z,annotationSnapshot:{url:z.url,viewport:z.viewport,annotations:z.annotations,color:A||void 0},feedbackSummary:_e,...qe?{requestText:qe}:{},feedbackContext:Le||void 0,...Je?{memoryReview:Je}:{},...oe?{imprintContext:oe}:{},lifecycle:ue});let Se=E.enqueue(Me);_(y,200,{jobId:ne,position:Se,threadId:ge})}async function Ee(a,y){let M=a.headers["content-type"]||"",v,A,P,C,$,q,G,U,pe=[];if(M.includes("multipart/form-data")){let F=await Ko(a),ae=F.feedback?JSON.parse(F.feedback):{};v=ae.threadId,A=ae.reply,P=ae.color,C=ae.provider,$=ae.model,q=At(ae),G=ae.sourceId||F.sourceId,U=typeof ae.memoryReviewProposalId=="string"?ae.memoryReviewProposalId:void 0;for(let ve of F.pastedImages)pe.push(ve.data)}else{let F=[];for await(let Fe of a)F.push(typeof Fe=="string"?Buffer.from(Fe):Fe);let ae=Buffer.concat(F).toString("utf-8"),ve;try{ve=JSON.parse(ae)}catch{_(y,400,{error:"Invalid JSON"});return}v=ve.threadId,A=ve.reply,P=ve.color,C=ve.provider,$=ve.model,q=At(ve),G=ve.sourceId,U=ve.memoryReviewProposalId}if(!v||!A){_(y,400,{error:"Missing threadId or reply"});return}let z=await O.getThread(v);if(!z){_(y,404,{error:"Thread not found"});return}let me;if(U){let F=await se.findModelProposalsByThread(v);if(me=(await Promise.all(F.flatMap(ve=>ve.authorityStatus==="accepted"?[]:ve.decisionIds.map(async Fe=>({modelProposalId:ve.id,underlying:await D.findPendingProposalForLegacyDecision(Fe)}))))).filter(ve=>!!ve.underlying).find(ve=>ve.underlying.proposalId===U),!me){_(y,409,{error:"The requested memory decision is not pending in this thread."});return}}let le="";{let F=await O.getThreadHistory(v);for(let ae=F.length-1;ae>=0;ae--)if(F[ae].screenshotPath){le=F[ae].screenshotPath;break}}let ne=await gt(v);if(!le&&!ne){_(y,400,{error:"No screenshot available"});return}let X=E.hasActiveThread(v),xe=X?E.getQueuedThreadJob(v,F=>F._replyText!==void 0||F._replyPrompt!==void 0):null,we=xe?.id??rt().slice(0,8),je=ri({jobId:we,threadId:v}),ge=[],Z=`${we}-${Date.now()}`;for(let F=0;F<pe.length;F++){let ae=De(c,`reply-${Z}-${F}.webp`);await lo(ae,pe[F]),ge.push(ae)}await O.appendMessage(v,{role:"human",timestamp:Date.now(),jobId:we,replyToQuestion:A,screenshotPath:le,...X?{queued:!0}:{},...ge.length>0?{replyImagePaths:ge}:{},lifecycle:{...je,artifactIds:ge.map((F,ae)=>`reply-image:${we}:${ae}`)}});let fe=await O.getThreadHistory(v),Je=[...fe].reverse().find(F=>F.memoryReview)?.memoryReview,Ae=await Y.contextualize({text:A,subjectHints:z.elementIdentifiers,pendingGroundingExplanationIds:yn(fe),correctionExplanationIds:Qr(fe)}).catch(F=>{console.warn(`[\u22B9 ${f}:${we}] Imprint context unavailable for reply; continuing without it:`,F instanceof Error?F.message:String(F))}),oe=new Set(fe.flatMap(F=>F.memoryReceipt?.status==="committed"?[F.memoryReceipt.proposalId]:[])),ue=[...fe].reverse().find(F=>F.memoryReviewCard&&!oe.has(F.memoryReviewCard.proposalId))?.memoryReviewCard,Me=[];for(let F of fe)if(F.annotationIds)for(let ae of F.annotationIds)Me.includes(ae)||Me.push(ae);let ut=Ht(C),_e=me,Le=_e?[_e.underlying.proposalId]:ue?[ue.proposalId]:[],qe=Ir(le,fe,ut,ge.length>0?ge:void 0);if(_e?qe+=["","## Decision review card",`Privately review proposal ${_e.underlying.proposalId}: ${_e.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(`
213
- `):ue&&(qe+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(ue)}`,"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(`
214
- `)),xe){let F=xe,ve=[...F._replyTexts??(F._replyText?[F._replyText]:[]),A],Fe=[...F._replyImagePaths??[],...ge];F._replyTexts=ve,F._replyText=Kr(ve),F._replyImagePaths=Fe.length>0?Fe:void 0,F._replyPrompt=qe,F.annotationIds=Me.length>0?Me:F.annotationIds,F.agentSettings=q??F.agentSettings,F.memoryReview=Je??F.memoryReview,F.imprintContext=Ae??F.imprintContext,F.surfacedProposalIds=[...new Set([...F.surfacedProposalIds??[],...Le])],F.lifecycle={...F.lifecycle??je,submissionIds:[...new Set([...F.lifecycle?.submissionIds??[],...je.submissionIds])],artifactIds:[...new Set([...F.lifecycle?.artifactIds??[],...je.artifactIds])]},_(y,200,{jobId:we,position:1,threadId:v,bundled:!0});return}let Se={id:we,status:"queued",screenshotPath:le,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:P,threadId:v,annotationIds:Me.length>0?Me:void 0,provider:ut,model:$||void 0,agentSettings:q,sourceId:G||void 0,...Je?{memoryReview:Je}:{},...Ae?{imprintContext:Ae}:{},...Le.length?{surfacedProposalIds:Le}:{},lifecycle:je};ne&&(Se.kind=ne),Se._replyPrompt=qe,Se._replyTexts=[A],Se._replyText=Kr([A]),ge.length>0&&(Se._replyImagePaths=ge);let ee=X?E.enqueueNext(Se):E.enqueue(Se);_(y,200,{jobId:we,position:ee,threadId:v})}function et(a,y){y.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),y.write(`event: connected
224
+ `)}else Ce=gs(z);let qe=hn(z,Object.keys(Ie).length>0?Ie:void 0,de),Ee=ds(z);await N.appendMessage(we,{role:"human",timestamp:Date.now(),jobId:ie,screenshotPath:Y,...Se?{screenshotPaths:ye}:{},...Object.keys(Ie).length>0?{imagePaths:Ie}:{},...de&&Object.keys(de).length>0?{attachmentFiles:de}:{},annotationIds:Z,annotationSnapshot:{url:z.url,viewport:z.viewport,annotations:z.annotations,color:A||void 0},feedbackSummary:Ce,...Ee?{requestText:Ee}:{},feedbackContext:qe||void 0,...He?{memoryReview:He}:{},...Ge?{imprintContext:Ge}:{},lifecycle:Re});let je=j.enqueue(ee);C(v,200,{jobId:ie,position:je,threadId:we})}async function _e(a,v){let _=a.headers["content-type"]||"",I,A,k,$,D,q,W,F,ue=[];if(_.includes("multipart/form-data")){let U=await oo(a),oe=U.feedback?JSON.parse(U.feedback):{};I=oe.threadId,A=oe.reply,k=oe.color,$=oe.provider,D=oe.model,q=_t(oe),W=oe.sourceId||U.sourceId,F=typeof oe.memoryReviewProposalId=="string"?oe.memoryReviewProposalId:void 0;for(let le of U.pastedImages)ue.push(le.data)}else{let U=[];for await(let Ve of a)U.push(typeof Ve=="string"?Buffer.from(Ve):Ve);let oe=Buffer.concat(U).toString("utf-8"),le;try{le=JSON.parse(oe)}catch{C(v,400,{error:"Invalid JSON"});return}I=le.threadId,A=le.reply,k=le.color,$=le.provider,D=le.model,q=_t(le),W=le.sourceId,F=le.memoryReviewProposalId}if(!I||!A){C(v,400,{error:"Missing threadId or reply"});return}let z=await N.getThread(I);if(!z){C(v,404,{error:"Thread not found"});return}let he;if(F){let U=await ce.findModelProposalsByThread(I);if(he=(await Promise.all(U.flatMap(le=>le.authorityStatus==="accepted"?[]:le.decisionIds.map(async Ve=>({modelProposalId:le.id,underlying:await B.findPendingProposalForLegacyDecision(Ve)}))))).filter(le=>!!le.underlying).find(le=>le.underlying.proposalId===F),!he){C(v,409,{error:"The requested memory decision is not pending in this thread."});return}}let de="";{let U=await N.getThreadHistory(I);for(let oe=U.length-1;oe>=0;oe--)if(U[oe].screenshotPath){de=U[oe].screenshotPath;break}}let ie=await wt(I);if(!de&&!ie){C(v,400,{error:"No screenshot available"});return}let ye=j.hasActiveThread(I),Y=ye?j.getQueuedThreadJob(I,U=>U._replyText!==void 0||U._replyPrompt!==void 0):null,Ie=Y?.id??ct().slice(0,8),Pe=fo({jobId:Ie,threadId:I}),we=[],Z=`${Ie}-${Date.now()}`;for(let U=0;U<ue.length;U++){let oe=Ne(c,`reply-${Z}-${U}.webp`);await vi(oe,ue[U]),we.push(oe)}await N.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:Ie,replyToQuestion:A,screenshotPath:de,...ye?{queued:!0}:{},...we.length>0?{replyImagePaths:we}:{},lifecycle:{...Pe,artifactIds:we.map((U,oe)=>`reply-image:${Ie}:${oe}`)}});let Se=await N.getThreadHistory(I),He=[...Se].reverse().find(U=>U.memoryReview)?.memoryReview,me=await X.contextualize({text:A,subjectHints:cs(Se,z.elementIdentifiers),pendingGroundingExplanationIds:Sn(Se),correctionExplanationIds:hs(Se)}).catch(U=>{console.warn(`[\u22B9 ${y}:${Ie}] Imprint context unavailable for reply; continuing without it:`,U instanceof Error?U.message:String(U))});me&&await N.updateMessage(I,Ie,{imprintContext:me});let Ge=new Set(Se.flatMap(U=>U.memoryReceipt?.status==="committed"?[U.memoryReceipt.proposalId]:[])),Re=[...Se].reverse().find(U=>U.memoryReviewCard&&!Ge.has(U.memoryReviewCard.proposalId))?.memoryReviewCard,ee=[];for(let U of Se)if(U.annotationIds)for(let oe of U.annotationIds)ee.includes(oe)||ee.push(oe);let fe=Zt($),Ce=he,qe=Ce?[Ce.underlying.proposalId]:Re?[Re.proposalId]:[],Ee=$r(de,Se,fe,we.length>0?we:void 0);if(Ce?Ee+=["","## Decision review card",`Privately review proposal ${Ce.underlying.proposalId}: ${Ce.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(`
225
+ `):Re&&(Ee+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Re)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
226
+ `)),Y){let U=Y,le=[...U._replyTexts??(U._replyText?[U._replyText]:[]),A],Ve=[...U._replyImagePaths??[],...we];U._replyTexts=le,U._replyText=fs(le),U._replyImagePaths=Ve.length>0?Ve:void 0,U._replyPrompt=Ee,U.annotationIds=ee.length>0?ee:U.annotationIds,U.agentSettings=q??U.agentSettings,U.memoryReview=He??U.memoryReview,U.imprintContext=me??U.imprintContext,U.surfacedProposalIds=[...new Set([...U.surfacedProposalIds??[],...qe])],U.lifecycle={...U.lifecycle??Pe,submissionIds:[...new Set([...U.lifecycle?.submissionIds??[],...Pe.submissionIds])],artifactIds:[...new Set([...U.lifecycle?.artifactIds??[],...Pe.artifactIds])]},C(v,200,{jobId:Ie,position:1,threadId:I,bundled:!0});return}let je={id:Ie,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:k,threadId:I,annotationIds:ee.length>0?ee:void 0,provider:fe,model:D||void 0,agentSettings:q,sourceId:W||void 0,...He?{memoryReview:He}:{},...me?{imprintContext:me}:{},...qe.length?{surfacedProposalIds:qe}:{},lifecycle:Pe};ie&&(je.kind=ie),je._replyPrompt=Ee,je._replyTexts=[A],je._replyText=fs([A]),we.length>0&&(je._replyImagePaths=we);let te=ye?j.enqueueNext(je):j.enqueue(je);C(v,200,{jobId:Ie,position:te,threadId:I})}function nt(a,v){v.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),v.write(`event: connected
215
227
  data: {"status":"connected"}
216
228
 
217
- `);let v=new URL(a.url||"/",`http://127.0.0.1:${f}`).searchParams.get("sourceId")||void 0,A={id:rt().slice(0,8),res:y,sourceId:v};L.add(A),a.on("close",()=>{L.delete(A)})}async function dt(a,y,M){s??=Cr(a.headers),st();let v=[...E.allActive,...R.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[A,P,C,$,q]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),D.status(),Y.store.load(),O.load()]),G=[],U=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);A.status==="rejected"&&G.push({subsystem:"projection",message:U(A)}),P.status==="rejected"&&G.push({subsystem:"projection",message:U(P)}),C.status==="rejected"?G.push({subsystem:"memory",message:U(C)}):C.value.state==="degraded"&&G.push({subsystem:"memory",message:C.value.error??"Product memory is degraded."}),$.status==="rejected"&&G.push({subsystem:"imprint",message:U($)}),q.status==="rejected"&&G.push({subsystem:"threads",message:U(q)});let pe=A.status==="fulfilled"?A.value.runs:[],z=P.status==="fulfilled"?P.value.proposals:[],me=$r(pe,z),le=me.actionableProposals.map(Z=>({id:Z.id,status:Z.status,title:Z.title,summary:Z.summary,decisionIds:Z.decisionIds,threadId:Z.threadId,runId:Z.runId,presentationJobId:Z.presentationJobId,authorityStatus:Z.authorityStatus,underlyingProposalId:Z.underlyingProposalId,createdAt:Z.createdAt,updatedAt:Z.updatedAt,appliedAt:Z.appliedAt,dismissedAt:Z.dismissedAt,error:Z.error})),ne=C.status==="fulfilled"?C.value:{initialized:!1,state:"degraded",error:U(C)},X=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>yn(Z.messages)))]:[],xe=$.status==="fulfilled"?X.filter(Z=>$.value.graph.explanations.some(fe=>fe.id===Z&&fe.state==="testing")):[],we=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(Z=>Z.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:xe.length,recoveredTransactions:$.value.recoveredTransactions,admission:Y.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:U($),pendingGroundingCount:xe.length,admission:Y.diagnostics(),admissionWindowStartedAt:e},je=G.length>0?"degraded":ne.state==="absent"||ne.state==="initializing"?"initializing":"healthy",ge=new Date().toISOString();_(y,200,{ok:!0,schemaVersion:3,generatedAt:ge,serverStartedAt:e,health:{state:je,issues:G},version:it,restartMode:l,projectId:r,projectName:po(i),projectRoot:i,requestProjectId:M,projectIdVerified:M===r,devOrigin:s,capture:{native:{configured:!!p,endpoint:p?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:v[0]?{id:v[0].id,status:v[0].status}:null,activeJobs:v.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds,color:Z.color,kind:Z.kind,standalone:"standalone"in Z?Z.standalone:void 0})),queueDepth:E.depth+R.depth,projectionQueueDepth:R.depth,leases:{active:N.isActivated,count:N.size,nextExpiryAt:N.nextExpiryAt,shutdownPending:W},projection:{state:A.status==="fulfilled"&&P.status==="fulfilled"?"ready":"degraded",activeJob:R.active?{id:R.active.id,status:R.active.status,threadId:R.active.threadId,annotationIds:R.active.annotationIds??[],provider:R.active.provider,model:R.active.model}:null,queueDepth:R.depth,recentRuns:me.recentRuns,recentAppliedRuns:me.recentAppliedRuns,actionableProposalCounts:me.actionableProposalCounts,actionableProposals:le},memory:ne,imprint:we,recentJobsRetentionMs:We,recentJobs:ke})}async function lt(a,y){let M=await new Promise(v=>{let A="";a.on("data",P=>{A+=P.toString()}),a.on("end",()=>v(A))});try{let v=JSON.parse(M);typeof v.devOrigin=="string"&&(s=v.devOrigin||null),_(y,200,{ok:!0,devOrigin:s})}catch{_(y,400,{error:"Invalid JSON"})}}async function ft(a){let y=await ce.load();_(a,200,{ok:!0,...y})}async function ho(a,y){let M=await Oe(a);if(!Ur(M.theme)){_(y,400,{error:"theme must be light, dark, or auto"});return}let v=await ce.setTheme(M.theme);_(y,200,{ok:!0,exists:!0,preferences:v})}async function go(a,y){let v=new URL(a.url||"/",`http://127.0.0.1:${f}`).searchParams.get("jobId"),A=v?E.allActive.filter(U=>U.id===v):E.allActive,P=v?R.allActive.filter(U=>U.id===v):R.allActive,C=[...A.map(U=>U.threadId),...P.map(U=>U.threadId)].filter(Boolean),$=v?E.cancelJob(v):E.cancelActive(),q=v?R.cancelJob(v):R.cancelActive(),G=!!($||q);for(let U of C)await O.appendMessage(U,{role:"assistant",timestamp:Date.now(),jobId:v||q?.id||"",cancelled:!0});_(y,200,{cancelled:G})}async function ht(a){let y=rt().slice(0,8),M=a.threadId,v=!M;M||(M=(await O.createThread(`thread-${rt()}`,[])).id,He.set(M,"project_model")),v&&await O.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:y,feedbackSummary:a.reason}),await O.appendMessage(M,{role:"assistant",timestamp:Date.now(),jobId:y,responseText:v?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:y,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:M,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:v},P=R.enqueue(A);return{jobId:y,position:P,threadId:M}}async function Ne(a,y){let M=decodeURIComponent(a),v=await se.findModelProposal(M);if(!v){_(y,404,{error:"Model proposal not found"});return}_(y,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:v})}async function Be(a,y,M){let v=decodeURIComponent(a),A=[];for await(let z of y)A.push(typeof z=="string"?Buffer.from(z):z);let P;try{P=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(M,400,{error:"Invalid JSON"});return}let C=(P.changes??[]).flatMap(z=>{if(!Array.isArray(z.path)||z.path.length===0)return[];let me=z.path.filter(ne=>typeof ne=="string"||typeof ne=="number");if(me.length!==z.path.length)return[];let le=Array.isArray(z.decisionIds)?z.decisionIds.filter(ne=>typeof ne=="string"):void 0;return[{path:me,value:z.value,remove:z.remove===!0,decisionIds:le}]});if(C.length===0){_(M,400,{error:"No selected model changes"});return}let $=(P.changeSummaries??[]).flatMap(z=>{if(!z||typeof z!="object")return[];let me=Array.isArray(z.path)?z.path.filter(le=>typeof le=="string"||typeof le=="number"):void 0;return Array.isArray(z.path)&&me?.length!==z.path.length?[]:[{group:typeof z.group=="string"?z.group:void 0,label:typeof z.label=="string"?z.label:void 0,detail:typeof z.detail=="string"?z.detail:void 0,path:me,value:z.value,currentValue:z.currentValue}]}),q=await se.findModelProposal(v);if(!q){_(M,404,{error:"Model proposal not found"});return}if(q.authorityStatus!=="accepted"){_(M,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(q.status!=="pending"){_(M,409,{error:`Model proposal is already ${q.status}.`});return}let G=q.decisionIds.map(z=>{let me=q.changes?.filter(X=>X.decisionIds.includes(z)).length??0,le=C.filter(X=>X.decisionIds?.includes(z)).length,ne=le===0?"unprojected":me>le?"partially_projected":"projected";return{decisionId:z,status:ne}}),U=await D.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:C.map(z=>({path:z.path,value:z.value,decisionIds:z.decisionIds})),coverage:G}),pe=await se.applySelectedModelProposal(v,C,$);if(!pe){_(M,404,{error:"Model proposal not found"});return}if(pe.threadId){let z=Ht(P.provider),me=typeof P.model=="string"&&P.model?P.model:void 0;await O.appendMessage(pe.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${pe.id}`,responseText:"",provider:z,model:me})}_(M,200,{proposal:pe,projection:U})}async function pt(a,y,M){let v=decodeURIComponent(a),{provider:A,model:P}=await kt(y),C=await se.dismissModelProposal(v);if(!C){_(M,404,{error:"Model proposal not found"});return}C.threadId&&await O.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${C.id}`,responseText:"",provider:A,model:P}),_(M,200,{proposal:C})}async function kt(a){try{let y=[];for await(let v of a)y.push(typeof v=="string"?Buffer.from(v):v);if(y.length===0)return{};let M=JSON.parse(Buffer.concat(y).toString());return{provider:Ht(typeof M.provider=="string"?M.provider:void 0),model:typeof M.model=="string"&&M.model?M.model:void 0,agentSettings:At(M)}}catch{return{}}}async function gt(a){let y=He.get(a);if(y)return y;let A=(await O.getThread(a))?.messages.find(P=>P.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return He.set(a,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return He.set(a,"project_model"),"project_model"}async function yo(a,y){let M=[];for await(let q of a)M.push(typeof q=="string"?Buffer.from(q):q);let v;if(M.length>0)try{v=JSON.parse(Buffer.concat(M).toString("utf-8")).serverUrl}catch{}let A=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&A.push(await Li(v)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&A.push(await qi(v)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&A.push(await Fi(v,m.copilot.path??T));let[P,C,$]=await Promise.all([_o(i),Co(i),$o(i,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=P),m.codex&&(m.codex.mcp=C),m.copilot&&(m.copilot.mcp=$),_(y,200,{results:A,capabilities:{providers:m}})}async function vn(a,y){let M=[];for await(let P of a)M.push(typeof P=="string"?Buffer.from(P):P);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${v.name}`,value:{description:""},claim:`${v.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{added:!0,alreadyExists:!1,...A})}async function ss(a,y){let M=[];for await(let P of a)M.push(typeof P=="string"?Buffer.from(P):P);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${v.name}`,value:null,claim:`${v.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}async function as(a,y){let M=[];for await(let C of a)M.push(typeof C=="string"?Buffer.from(C):C);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"||typeof v.value!="string"){_(y,400,{error:"Missing or invalid path/value"});return}let A=v.value;try{let C=JSON.parse(v.value);C&&typeof C=="object"&&(A=C)}catch{}let P=await D.recordDirectModelMutation({key:`tokens.${v.path}`,value:A,claim:`${v.path} uses ${v.value} in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{updated:!0,...P})}async function cs(a,y){let M=[];for await(let P of a)M.push(typeof P=="string"?Buffer.from(P):P);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"){_(y,400,{error:"Missing or invalid path"});return}let A=await D.recordDirectModelMutation({key:`tokens.${v.path}`,value:null,claim:`${v.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}function ds(a,y){let M=s??"http://localhost:3000";if(!s){let A=a.headers.referer||a.headers.origin;if(A)try{let P=new URL(typeof A=="string"?A:A[0]||"");(P.hostname==="localhost"||P.hostname==="127.0.0.1")&&(M=P.origin)}catch{}}let v=ui(f,M);y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(v)}async function ls(a){let y=Date.now();if(at&&y<at.expires){_(a,200,at.data);return}try{let{scanForComponents:M}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:v}=await import("./render-generator-HWFLZYC3.mjs"),A=await M(i);at={data:A,expires:y+5e3},v(A,i,Vt).then(P=>{Vt=P}).catch(P=>console.warn("[Bridge] Render generation failed:",P)),_(a,200,A)}catch(M){console.error("[Bridge] Scanner error:",M),_(a,500,{error:"Failed to scan components"})}}async function ps(a){let y=[De(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),De(i,"packages","popmelt","dist","canvas.mjs")];try{let M=Bd(import.meta.url);y.unshift(De(Od(M),"canvas.mjs"))}catch{}for(let M of y)try{let v=await Hr(M,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(v);return}catch{}console.error("[Bridge] Canvas bundle not found in:",y),_(a,404,{error:"Canvas bundle not found"})}async function us(a,y){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(y,400,{error:"Invalid filename"});return}try{let M=[De(c,a),De(i,".popmelt","artifacts","thread-media",a),De(i,".popmelt","artifacts","eval-screenshots",a),De(i,".popmelt","evals","screenshots",a),De(i,".popmelt","screenshots",a)],v;for(let C of M)try{v=await Hr(C);break}catch{}if(!v)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),P=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";y.writeHead(200,{"Content-Type":P,"Cache-Control":"public, max-age=3600"}),y.end(v)}catch{_(y,404,{error:"File not found"})}}function Kt(a){return`/files/${po(a)}`}async function ms(a,y){let M=await O.getThread(a);if(!M){_(y,404,{error:"Thread not found"});return}let v=M.messages.filter(q=>q.role==="assistant"&&q.responseText?.includes("Model suggestion ready")),A=await(v.length>0?se.findModelProposalsByThread(a):Promise.resolve([])),P=await Promise.all(A.map(async(q,G)=>{if(q.authorityStatus==="accepted")return q;let U=(await Promise.all(q.decisionIds.map(pe=>D.findPendingProposalForLegacyDecision(pe)))).find(Boolean);return{...q,authorityStatus:"legacy_untrusted",presentationJobId:q.presentationJobId??v[G]?.jobId??v.at(-1)?.jobId,underlyingProposalId:U?.proposalId,underlyingClaim:U?.claim}})),C=[...P].sort((q,G)=>G.updatedAt-q.updatedAt)[0]??null,$=M.messages.map(({screenshotPath:q,screenshotPaths:G,imagePaths:U,attachmentFiles:pe,replyImagePaths:z,...me})=>({...me,...q?{screenshotUrl:Kt(q)}:{},...G?{screenshotUrls:Object.fromEntries(Object.entries(G).map(([le,ne])=>[le,Kt(ne)]))}:{},...U?{imageUrls:Object.fromEntries(Object.entries(U).map(([le,ne])=>[le,ne.map(Kt)]))}:{},...pe?{attachments:Object.fromEntries(Object.entries(pe).map(([le,ne])=>[le,ne.map(({path:X,...xe})=>({...xe,url:Kt(X)}))]))}:{},...z?{replyImageUrls:z.map(Kt)}:{}}));_(y,200,{id:M.id,createdAt:M.createdAt,messages:$,modelProposal:C,modelProposals:P})}async function fs(a,y){let M=decodeURIComponent(a);if(!await O.deleteThread(M)){_(y,404,{deleted:!1,error:"Thread not found"});return}_(y,200,{deleted:!0})}let di=9,li=!1;for(let a=n;a<n+di;a++)try{await el(Rt,a),f=a,li=!0,console.log(`[\u22B9 is watching :${f}]`);break}catch(y){if(y.code==="EADDRINUSE"){let M=await mo(a);if(mn(M,{projectId:r,version:it,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw y}if(!li)throw new Error(`[Bridge] All ports ${n}\u2013${n+di-1} in use`);for(let[a,y]of Object.entries(m))!y.available||!y.path||j(a,y.path).then(M=>{if(M)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),y.available=!1,y.path=null;for(let v of L)uo(v,{type:"capabilities_changed",data:{}})}});let hs=setInterval(()=>{Yr(c).catch(()=>{}),B.sweep().catch(()=>{})},qd),pi=setInterval(()=>{N.expireStale().becameEmpty&&H()},Ud);return pi.unref?.(),{port:f,projectId:r,close:async()=>{clearInterval(hs),clearInterval(pi),Q(),N.clear(),await B.cleanupPartials(),await E.destroyAsync(),R.destroy();for(let a of L)try{a.res.end()}catch{}return L.clear(),new Promise(a=>{Rt.close(()=>a())})}}}async function Yr(o){try{let e=await Ad(o),n=Date.now();for(let t of e){let i=De(o,t);try{let r=await Ed(i);n-r.mtimeMs>Fd&&await _d(i)}catch{}}}catch{}}import{randomUUID as tl}from"crypto";var nl=5e3,ol=250;function ai(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function ns(o,e=fetch){let n=`${process.pid}-${tl()}`,t=`http://127.0.0.1:${o.port}`,i=!1,r=!1,s=async()=>(await e(`${t}/leases`,{method:"POST",headers:ai(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(I){return console.warn("[popmelt] failed to register bridge lease:",I instanceof Error?I.message:String(I)),null}let c=async()=>{if(!(i||r)){r=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:ai(o)})).status===404&&!i&&await s()}catch{}finally{r=!1}}},d=setInterval(()=>{c()},nl);return d.unref?.(),{id:n,release:async()=>{if(!i){i=!0,clearInterval(d);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:ai(o),keepalive:!0})}catch{}}}}}function os(o,e=process){let n=!1,t=new Map,i=()=>{if(!n){n=!0;for(let[r,s]of t)e.removeListener(r,s);t.clear()}};for(let r of["SIGINT","SIGTERM"]){let s=()=>{let c=e.listenerCount(r),d=o.release();if(c>0)return;let u=new Promise(I=>{setTimeout(I,ol)});Promise.race([d,u]).finally(()=>{i(),e.kill(e.pid,r)})};t.set(r,s),e.prependOnceListener(r,s)}return i}var ml=1111,is=3e4,fl=8e3;async function hl(o){return ll(o).catch(()=>o)}async function rs(o,e){let t=(await dl(e,"utf8").catch(()=>"")).slice(-fl).trim();return new Error(t?`${o}
229
+ `);let I=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,A={id:ct().slice(0,8),res:v,sourceId:I};L.add(A),a.on("close",()=>{L.delete(A)})}async function ut(a,v,_){s??=Qr(a.headers),dt();let I=[...j.allActive,...T.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[A,k,$,D,q]=await Promise.allSettled([ce.loadRuns(),ce.loadModelProposals(),B.status(),X.store.load(),N.load()]),W=[],F=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);A.status==="rejected"&&W.push({subsystem:"projection",message:F(A)}),k.status==="rejected"&&W.push({subsystem:"projection",message:F(k)}),$.status==="rejected"?W.push({subsystem:"memory",message:F($)}):$.value.state==="degraded"&&W.push({subsystem:"memory",message:$.value.error??"Product memory is degraded."}),D.status==="rejected"&&W.push({subsystem:"imprint",message:F(D)}),q.status==="rejected"&&W.push({subsystem:"threads",message:F(q)});let ue=A.status==="fulfilled"?A.value.runs:[],z=k.status==="fulfilled"?k.value.proposals:[],he=Xr(ue,z),de=he.actionableProposals.map(Z=>({id:Z.id,status:Z.status,title:Z.title,summary:Z.summary,decisionIds:Z.decisionIds,threadId:Z.threadId,runId:Z.runId,presentationJobId:Z.presentationJobId,authorityStatus:Z.authorityStatus,underlyingProposalId:Z.underlyingProposalId,createdAt:Z.createdAt,updatedAt:Z.updatedAt,appliedAt:Z.appliedAt,dismissedAt:Z.dismissedAt,error:Z.error})),ie=$.status==="fulfilled"?$.value:{initialized:!1,state:"degraded",error:F($)},ye=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>Sn(Z.messages)))]:[],Y=D.status==="fulfilled"?ye.filter(Z=>D.value.graph.explanations.some(Se=>Se.id===Z&&Se.state==="testing")):[],Ie=D.status==="fulfilled"?{state:"ready",head:D.value.graph.head,updatedAt:D.value.graph.updatedAt,explanationCount:D.value.graph.explanations.filter(Z=>Z.state!=="retired").length,concreteCount:D.value.graph.concrete.length,relationCount:D.value.graph.relations.length,pendingGroundingCount:Y.length,recoveredTransactions:D.value.recoveredTransactions,admission:X.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(D),pendingGroundingCount:Y.length,admission:X.diagnostics(),admissionWindowStartedAt:e},Pe=W.length>0?"degraded":ie.state==="absent"||ie.state==="initializing"?"initializing":"healthy",we=new Date().toISOString();C(v,200,{ok:!0,schemaVersion:3,generatedAt:we,serverStartedAt:e,health:{state:Pe,issues:W},version:at,restartMode:p,projectId:r,projectName:Ii(o),projectRoot:o,requestProjectId:_,projectIdVerified:_===r,devOrigin:s,capture:{native:{configured:!!f,endpoint:f?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:I[0]?{id:I[0].id,status:I[0].status}:null,activeJobs:I.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds,color:Z.color,kind:Z.kind,standalone:"standalone"in Z?Z.standalone:void 0})),queueDepth:j.depth+T.depth,projectionQueueDepth:T.depth,leases:{active:O.isActivated,count:O.size,nextExpiryAt:O.nextExpiryAt,shutdownPending:G},projection:{state:A.status==="fulfilled"&&k.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:he.recentRuns,recentAppliedRuns:he.recentAppliedRuns,actionableProposalCounts:he.actionableProposalCounts,actionableProposals:de},memory:ie,imprint:Ie,recentJobsRetentionMs:ze,recentJobs:Me})}async function mt(a,v){let _=await new Promise(I=>{let A="";a.on("data",k=>{A+=k.toString()}),a.on("end",()=>I(A))});try{let I=JSON.parse(_);typeof I.devOrigin=="string"&&(s=I.devOrigin||null),C(v,200,{ok:!0,devOrigin:s})}catch{C(v,400,{error:"Invalid JSON"})}}async function vt(a){let v=await pe.load();C(a,200,{ok:!0,...v})}async function Si(a,v){let _=await De(a);if(!ss(_.theme)){C(v,400,{error:"theme must be light, dark, or auto"});return}let I=await pe.setTheme(_.theme);C(v,200,{ok:!0,exists:!0,preferences:I})}async function Ti(a,v){let I=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),A=I?j.allActive.filter(F=>F.id===I):j.allActive,k=I?T.allActive.filter(F=>F.id===I):T.allActive,$=[...A.map(F=>F.threadId),...k.map(F=>F.threadId)].filter(Boolean),D=I?j.cancelJob(I):j.cancelActive(),q=I?T.cancelJob(I):T.cancelActive(),W=!!(D||q);for(let F of $)await N.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:I||q?.id||"",cancelled:!0});C(v,200,{cancelled:W})}async function It(a){let v=ct().slice(0,8),_=a.threadId,I=!_;_||(_=(await N.createThread(`thread-${ct()}`,[])).id,We.set(_,"project_model")),I&&await N.appendMessage(_,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:a.reason}),await N.appendMessage(_,{role:"assistant",timestamp:Date.now(),jobId:v,responseText:I?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:v,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:_,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:I},k=T.enqueue(A);return{jobId:v,position:k,threadId:_}}async function Be(a,v){let _=decodeURIComponent(a),I=await ce.findModelProposal(_);if(!I){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:I})}async function Je(a,v,_){let I=decodeURIComponent(a),A=[];for await(let z of v)A.push(typeof z=="string"?Buffer.from(z):z);let k;try{k=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(_,400,{error:"Invalid JSON"});return}let $=(k.changes??[]).flatMap(z=>{if(!Array.isArray(z.path)||z.path.length===0)return[];let he=z.path.filter(ie=>typeof ie=="string"||typeof ie=="number");if(he.length!==z.path.length)return[];let de=Array.isArray(z.decisionIds)?z.decisionIds.filter(ie=>typeof ie=="string"):void 0;return[{path:he,value:z.value,remove:z.remove===!0,decisionIds:de}]});if($.length===0){C(_,400,{error:"No selected model changes"});return}let D=(k.changeSummaries??[]).flatMap(z=>{if(!z||typeof z!="object")return[];let he=Array.isArray(z.path)?z.path.filter(de=>typeof de=="string"||typeof de=="number"):void 0;return Array.isArray(z.path)&&he?.length!==z.path.length?[]:[{group:typeof z.group=="string"?z.group:void 0,label:typeof z.label=="string"?z.label:void 0,detail:typeof z.detail=="string"?z.detail:void 0,path:he,value:z.value,currentValue:z.currentValue}]}),q=await ce.findModelProposal(I);if(!q){C(_,404,{error:"Model proposal not found"});return}if(q.authorityStatus!=="accepted"){C(_,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(q.status!=="pending"){C(_,409,{error:`Model proposal is already ${q.status}.`});return}let W=q.decisionIds.map(z=>{let he=q.changes?.filter(ye=>ye.decisionIds.includes(z)).length??0,de=$.filter(ye=>ye.decisionIds?.includes(z)).length,ie=de===0?"unprojected":he>de?"partially_projected":"projected";return{decisionId:z,status:ie}}),F=await B.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:$.map(z=>({path:z.path,value:z.value,decisionIds:z.decisionIds})),coverage:W}),ue=await ce.applySelectedModelProposal(I,$,D);if(!ue){C(_,404,{error:"Model proposal not found"});return}if(ue.threadId){let z=Zt(k.provider),he=typeof k.model=="string"&&k.model?k.model:void 0;await N.appendMessage(ue.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ue.id}`,responseText:"",provider:z,model:he})}C(_,200,{proposal:ue,projection:F})}async function ft(a,v,_){let I=decodeURIComponent(a),{provider:A,model:k}=await Mt(v),$=await ce.dismissModelProposal(I);if(!$){C(_,404,{error:"Model proposal not found"});return}$.threadId&&await N.appendMessage($.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${$.id}`,responseText:"",provider:A,model:k}),C(_,200,{proposal:$})}async function Mt(a){try{let v=[];for await(let I of a)v.push(typeof I=="string"?Buffer.from(I):I);if(v.length===0)return{};let _=JSON.parse(Buffer.concat(v).toString());return{provider:Zt(typeof _.provider=="string"?_.provider:void 0),model:typeof _.model=="string"&&_.model?_.model:void 0,agentSettings:_t(_)}}catch{return{}}}async function wt(a){let v=We.get(a);if(v)return v;let A=(await N.getThread(a))?.messages.find(k=>k.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return We.set(a,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return We.set(a,"project_model"),"project_model"}async function Pi(a,v){let _=[];for await(let q of a)_.push(typeof q=="string"?Buffer.from(q):q);let I;if(_.length>0)try{I=JSON.parse(Buffer.concat(_).toString("utf-8")).serverUrl}catch{}let A=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&A.push(await er(I)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&A.push(await tr(I)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&A.push(await nr(I,m.copilot.path??P));let[k,$,D]=await Promise.all([qi(o),Fi(o),Ui(o,m.copilot?.path??P)]);m.claude&&(m.claude.mcp=k),m.codex&&(m.codex.mcp=$),m.copilot&&(m.copilot.mcp=D),C(v,200,{results:A,capabilities:{providers:m}})}async function Tn(a,v){let _=[];for await(let k of a)_.push(typeof k=="string"?Buffer.from(k):k);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){C(v,400,{error:"Missing or invalid name"});return}let A=await B.recordDirectModelMutation({key:`components.${I.name}`,value:{description:""},claim:`${I.name} is an explicitly governed component in the product model.`});await ce.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{added:!0,alreadyExists:!1,...A})}async function Ps(a,v){let _=[];for await(let k of a)_.push(typeof k=="string"?Buffer.from(k):k);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){C(v,400,{error:"Missing or invalid name"});return}let A=await B.recordDirectModelMutation({key:`components.${I.name}`,value:null,claim:`${I.name} is not governed as a component in the product model.`});await ce.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{removed:!0,...A})}async function ks(a,v){let _=[];for await(let $ of a)_.push(typeof $=="string"?Buffer.from($):$);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"||typeof I.value!="string"){C(v,400,{error:"Missing or invalid path/value"});return}let A=I.value;try{let $=JSON.parse(I.value);$&&typeof $=="object"&&(A=$)}catch{}let k=await B.recordDirectModelMutation({key:`tokens.${I.path}`,value:A,claim:`${I.path} uses ${I.value} in the product model.`});await ce.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{updated:!0,...k})}async function Rs(a,v){let _=[];for await(let k of a)_.push(typeof k=="string"?Buffer.from(k):k);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"){C(v,400,{error:"Missing or invalid path"});return}let A=await B.recordDirectModelMutation({key:`tokens.${I.path}`,value:null,claim:`${I.path} is intentionally absent from the product model.`});await ce.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{removed:!0,...A})}function js(a,v){let _=s??"http://localhost:3000";if(!s){let A=a.headers.referer||a.headers.origin;if(A)try{let k=new URL(typeof A=="string"?A:A[0]||"");(k.hostname==="localhost"||k.hostname==="127.0.0.1")&&(_=k.origin)}catch{}}let I=To(y,_);v.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),v.end(I)}async function As(a){let v=Date.now();if(lt&&v<lt.expires){C(a,200,lt.data);return}try{let{scanForComponents:_}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:I}=await import("./render-generator-HWFLZYC3.mjs"),A=await _(o);lt={data:A,expires:v+5e3},I(A,o,en).then(k=>{en=k}).catch(k=>console.warn("[Bridge] Render generation failed:",k)),C(a,200,A)}catch(_){console.error("[Bridge] Scanner error:",_),C(a,500,{error:"Failed to scan components"})}}async function Ms(a){let v=[Ne(o,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ne(o,"packages","popmelt","dist","canvas.mjs")];try{let _=ll(import.meta.url);v.unshift(Ne(al(_),"canvas.mjs"))}catch{}for(let _ of v)try{let I=await us(_,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(I);return}catch{}console.error("[Bridge] Canvas bundle not found in:",v),C(a,404,{error:"Canvas bundle not found"})}async function Es(a,v){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){C(v,400,{error:"Invalid filename"});return}try{let _=[Ne(c,a),Ne(o,".popmelt","artifacts","thread-media",a),Ne(o,".popmelt","artifacts","eval-screenshots",a),Ne(o,".popmelt","evals","screenshots",a),Ne(o,".popmelt","screenshots",a)],I;for(let $ of _)try{I=await us($);break}catch{}if(!I)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),k=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";v.writeHead(200,{"Content-Type":k,"Cache-Control":"public, max-age=3600"}),v.end(I)}catch{C(v,404,{error:"File not found"})}}function tn(a){return`/files/${Ii(a)}`}async function _s(a,v){let _=await N.getThread(a);if(!_){C(v,404,{error:"Thread not found"});return}let I=_.messages.filter(q=>q.role==="assistant"&&q.responseText?.includes("Model suggestion ready")),A=await(I.length>0?ce.findModelProposalsByThread(a):Promise.resolve([])),k=await Promise.all(A.map(async(q,W)=>{if(q.authorityStatus==="accepted")return q;let F=(await Promise.all(q.decisionIds.map(ue=>B.findPendingProposalForLegacyDecision(ue)))).find(Boolean);return{...q,authorityStatus:"legacy_untrusted",presentationJobId:q.presentationJobId??I[W]?.jobId??I.at(-1)?.jobId,underlyingProposalId:F?.proposalId,underlyingClaim:F?.claim}})),$=[...k].sort((q,W)=>W.updatedAt-q.updatedAt)[0]??null,D=_.messages.map(({screenshotPath:q,screenshotPaths:W,imagePaths:F,attachmentFiles:ue,replyImagePaths:z,...he})=>({...he,...q?{screenshotUrl:tn(q)}:{},...W?{screenshotUrls:Object.fromEntries(Object.entries(W).map(([de,ie])=>[de,tn(ie)]))}:{},...F?{imageUrls:Object.fromEntries(Object.entries(F).map(([de,ie])=>[de,ie.map(tn)]))}:{},...ue?{attachments:Object.fromEntries(Object.entries(ue).map(([de,ie])=>[de,ie.map(({path:ye,...Y})=>({...Y,url:tn(ye)}))]))}:{},...z?{replyImageUrls:z.map(tn)}:{}}));C(v,200,{id:_.id,createdAt:_.createdAt,messages:D,modelProposal:$,modelProposals:k})}async function Cs(a,v){let _=decodeURIComponent(a);if(!await N.deleteThread(_)){C(v,404,{deleted:!1,error:"Thread not found"});return}C(v,200,{deleted:!0})}let Io=9,wo=!1;for(let a=t;a<t+Io;a++)try{await kl(At,a),y=a,wo=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(v){if(v.code==="EADDRINUSE"){let _=await bi(a);if(In(_,{projectId:r,version:at,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw v}if(!wo)throw new Error(`[Bridge] All ports ${t}\u2013${t+Io-1} in use`);for(let[a,v]of Object.entries(m))!v.available||!v.path||M(a,v.path).then(_=>{if(_)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 I of L)wi(I,{type:"capabilities_changed",data:{}})}});let $s=setInterval(()=>{ys(c).catch(()=>{}),J.sweep().catch(()=>{})},ml),bo=setInterval(()=>{O.expireStale().becameEmpty&&V()},hl);return bo.unref?.(),{port:y,projectId:r,close:async()=>{clearInterval($s),clearInterval(bo),Q(),O.clear(),await J.cleanupPartials(),await j.destroyAsync(),T.destroy();for(let a of L)try{a.res.end()}catch{}return L.clear(),new Promise(a=>{At.close(()=>a())})}}}async function ys(i){try{let e=await tl(i),t=Date.now();for(let n of e){let o=Ne(i,n);try{let r=await il(o);t-r.mtimeMs>fl&&await ol(o)}catch{}}}catch{}}import{randomUUID as Rl}from"crypto";var jl=5e3,Al=250;function yo(i){return{"Content-Type":"application/json",...i.projectId?{"X-Popmelt-Project-Id":i.projectId}:{}}}async function bs(i,e=fetch){let t=`${process.pid}-${Rl()}`,n=`http://127.0.0.1:${i.port}`,o=!1,r=!1,s=async()=>(await e(`${n}/leases`,{method:"POST",headers:yo(i),body:JSON.stringify({leaseId:t,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(w){return console.warn("[popmelt] failed to register bridge lease:",w instanceof Error?w.message:String(w)),null}let c=async()=>{if(!(o||r)){r=!0;try{(await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"PATCH",headers:yo(i)})).status===404&&!o&&await s()}catch{}finally{r=!1}}},d=setInterval(()=>{c()},jl);return d.unref?.(),{id:t,release:async()=>{if(!o){o=!0,clearInterval(d);try{await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"DELETE",headers:yo(i),keepalive:!0})}catch{}}}}}function xs(i,e=process){let t=!1,n=new Map,o=()=>{if(!t){t=!0;for(let[r,s]of n)e.removeListener(r,s);n.clear()}};for(let r of["SIGINT","SIGTERM"]){let s=()=>{let c=e.listenerCount(r),d=i.release();if(c>0)return;let l=new Promise(w=>{setTimeout(w,Al)});Promise.race([d,l]).finally(()=>{o(),e.kill(e.pid,r)})};n.set(r,s),e.prependOnceListener(r,s)}return o}var Jl=1111,Ss=3e4,Ll=8e3;async function ql(i){return Dl(i).catch(()=>i)}async function Ts(i,e){let n=(await Ol(e,"utf8").catch(()=>"")).slice(-Ll).trim();return new Error(n?`${i}
218
230
  Bridge log (${e}):
219
- ${t}`:o)}async function Mm(o){if(process.env.NODE_ENV==="production"&&!o?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(o?.detached){let n=await gl(o);if(o.manageLease===!1)return n;let t=await ns({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let i=os(t);return{...n,close:async()=>{i(),await t.release()}}}let e=await ts(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function gl(o){let e=o.port??ml,n=await hl(o.projectRoot??process.cwd()),t=co(n);for(let x=e;x<e+10;x++){let T=await mo(x);if(T&&T.projectId===t){if(T.version&&T.version!==it){if(T.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${x}/shutdown`,{method:"POST"})}catch{}await new Promise(S=>setTimeout(S,500));break}continue}if(!mn(T,{projectId:t,version:it,restartMode:"detached"}))continue;let k=o.devOrigin;if(k&&T.devOrigin!==k)try{await fetch(`http://127.0.0.1:${x}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:k})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(x),process.env.POPMELT_PROJECT_ID=t,{port:x,projectId:t,close:async()=>{}}}}let i=ci(pl(ul(import.meta.url)),"bridge-entry.mjs"),r=ci(n,".popmelt"),s=ci(r,"bridge.log");await cl(r,{recursive:!0}),await al(s,`
231
+ ${n}`:i)}async function pf(i){if(process.env.NODE_ENV==="production"&&!i?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(i?.detached){let t=await Fl(i);if(i.manageLease===!1)return t;let n=await bs({port:t.port,projectId:t.projectId});if(!n)return console.warn("[popmelt] detached bridge started without a process lease"),t;let o=xs(n);return{...t,close:async()=>{o(),await n.release()}}}let e=await ws(i);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Fl(i){let e=i.port??Jl,t=await ql(i.projectRoot??process.cwd()),n=yi(t);for(let b=e;b<e+10;b++){let P=await bi(b);if(P&&P.projectId===n){if(P.version&&P.version!==at){if(P.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${b}/shutdown`,{method:"POST"})}catch{}await new Promise(S=>setTimeout(S,500));break}continue}if(!In(P,{projectId:n,version:at,restartMode:"detached"}))continue;let R=i.devOrigin;if(R&&P.devOrigin!==R)try{await fetch(`http://127.0.0.1:${b}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:R})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(b),process.env.POPMELT_PROJECT_ID=n,{port:b,projectId:n,close:async()=>{}}}}let o=vo(Nl(Bl(import.meta.url)),"bridge-entry.mjs"),r=vo(t,".popmelt"),s=vo(r,"bridge.log");await $l(r,{recursive:!0}),await Cl(s,`
220
232
  [${new Date().toISOString()}] Starting detached bridge
221
- `);let c=sl(s,"a"),d;try{d=il(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{rl(c)}let u=null;d.once("error",x=>{u=`spawn error: ${x.message}`}),d.once("exit",(x,T)=>{u=`child exited before becoming healthy (${T?`signal ${T}`:`code ${x??"unknown"}`})`}),d.unref();let I=Date.now()+is;for(;Date.now()<I;){if(await new Promise(x=>setTimeout(x,100)),u)throw await rs(`[Bridge] Detached bridge ${u}`,s);for(let x=e;x<e+10;x++){let T=await mo(x);if(mn(T,{projectId:t,version:it,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(x),process.env.POPMELT_PROJECT_ID=t,{port:x,projectId:t,close:async()=>{}}}}throw d.kill("SIGTERM"),await rs(`[Bridge] Detached bridge failed to start within ${is/1e3}s (port ${e})`,s)}export{Ut as ImprintService,Ft as ImprintStore,eo as formatImprintPrompt,Zn as parseImprintDraft,Mm as startPopmelt};
233
+ `);let c=_l(s,"a"),d;try{d=Ml(process.execPath,[o],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:i.devOrigin??"",POPMELT_COPILOT_PATH:i.copilotPath??""}})}finally{El(c)}let l=null;d.once("error",b=>{l=`spawn error: ${b.message}`}),d.once("exit",(b,P)=>{l=`child exited before becoming healthy (${P?`signal ${P}`:`code ${b??"unknown"}`})`}),d.unref();let w=Date.now()+Ss;for(;Date.now()<w;){if(await new Promise(b=>setTimeout(b,100)),l)throw await Ts(`[Bridge] Detached bridge ${l}`,s);for(let b=e;b<e+10;b++){let P=await bi(b);if(In(P,{projectId:n,version:at,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(b),process.env.POPMELT_PROJECT_ID=n,{port:b,projectId:n,close:async()=>{}}}}throw d.kill("SIGTERM"),await Ts(`[Bridge] Detached bridge failed to start within ${Ss/1e3}s (port ${e})`,s)}export{Gt as ImprintService,Ht as ImprintStore,ai as formatImprintPrompt,si as parseImprintDraft,pf as startPopmelt};