@popmelt.com/core 0.8.7 → 0.8.9
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/README.md +3 -18
- package/dist/bridge-entry.mjs +47 -107
- package/dist/{chunk-ETDSTV4E.mjs → chunk-AX3C7GUE.mjs} +1 -1
- package/dist/cli.mjs +47 -107
- package/dist/index.d.mts +10 -1
- package/dist/index.mjs +68 -47
- package/dist/memory-legacy.d.mts +5 -1
- package/dist/memory-legacy.mjs +1 -1
- package/dist/memory-store.d.mts +6 -94
- package/dist/memory-store.mjs +3 -3
- package/dist/memory.d.mts +5 -10
- package/dist/memory.mjs +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-6UNEV3DE.mjs +182 -0
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +48 -108
- package/package.json +1 -1
- package/dist/server-FZ2YAIA5.mjs +0 -242
package/dist/server-FZ2YAIA5.mjs
DELETED
|
@@ -1,242 +0,0 @@
|
|
|
1
|
-
import{a as Yo,b as Zo}from"./chunk-NOHXTT24.mjs";import{spawn as Ed}from"child_process";import{closeSync as Ad,openSync as Md}from"fs";import{appendFile as _d,mkdir as Cd,readFile as $d,realpath as Od}from"fs/promises";import{dirname as Dd,join as Vo}from"path";import{fileURLToPath as Jd}from"url";import{execFileSync as so,spawn as Ti}from"child_process";import{createHash as Oi,randomUUID as mt}from"crypto";import{mkdir as id,readFile as Ho,readdir as sd,realpath as ad,stat as cd,unlink as dd,writeFile as pn}from"fs/promises";import{createServer as ld}from"http";import{tmpdir as pd}from"os";import{basename as ro,dirname as ud,isAbsolute as Go,join as Ae,relative as ji,resolve as Di}from"path";import{fileURLToPath as md}from"url";function er(o,e){return`<!DOCTYPE html>
|
|
2
|
-
<html>
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="utf-8">
|
|
5
|
-
<title>Popmelt Canvas</title>
|
|
6
|
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
7
|
-
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
8
|
-
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
|
|
9
|
-
<style>*{margin:0;padding:0;box-sizing:border-box}html,body,#root{height:100%;overflow:hidden}</style>
|
|
10
|
-
</head>
|
|
11
|
-
<body>
|
|
12
|
-
<div id="root"></div>
|
|
13
|
-
<script type="importmap">
|
|
14
|
-
{"imports":{
|
|
15
|
-
"react":"https://esm.sh/react@19?dev",
|
|
16
|
-
"react-dom/client":"https://esm.sh/react-dom@19/client?dev",
|
|
17
|
-
"react/jsx-runtime":"https://esm.sh/react@19/jsx-runtime?dev"
|
|
18
|
-
}}
|
|
19
|
-
</script>
|
|
20
|
-
<script type="module">
|
|
21
|
-
import { mountCanvas } from 'http://localhost:${o}/canvas/app.mjs';
|
|
22
|
-
mountCanvas(document.getElementById('root'), {
|
|
23
|
-
devOrigin: '${e}',
|
|
24
|
-
bridgeOrigin: 'http://localhost:${o}',
|
|
25
|
-
});
|
|
26
|
-
</script>
|
|
27
|
-
</body>
|
|
28
|
-
</html>`}var ts=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),ns=new Set(["default","flex","fast","priority"]);function vt(o){let e=typeof o.reasoningEffort=="string"&&ts.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&ns.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function hn(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as os}from"child_process";import{createInterface as rs}from"readline";var is=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"]),tr=1e5;function ss(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!is.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>tr?t.slice(0,tr)+`
|
|
29
|
-
\u2026[truncated]`:t}function gn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:x,timeoutMs:k=3e5,onEvent:P}=e,b=[];d?b.push("--resume",d,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),l&&b.push("--model",l),x&&b.push("--effort",x);for(let y of s)b.push("--allowedTools",y);let m=os(c,b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(y=>{let h,f=[],u=[],E=[],O=!1,R="",C,I,w=!1,M=setTimeout(()=>{w=!0,m.kill("SIGTERM"),setTimeout(()=>{try{m.kill("SIGKILL")}catch{}},5e3)},k),L=rs({input:m.stdout}),G=new Set;L.on("line",ne=>{if(ne.trim())try{let oe=JSON.parse(ne);oe.session_id&&!h&&(h=oe.session_id);let ye=oe.type??(oe.event?.type?`event.${oe.event.type}`:"unknown");if(G.add(ye),oe.type==="result"&&oe.result&&f.length===0){let Y=typeof oe.result=="string"?oe.result:"";Y&&(f.push(Y),P?.({type:"delta",jobId:o,text:Y},o))}if(oe.type==="assistant"&&Array.isArray(oe.message?.content)){typeof oe.error=="string"&&(C=oe.error);for(let Y of oe.message.content){if(Y.type==="text"&&Y.text&&(f.push(Y.text),P?.({type:"delta",jobId:o,text:Y.text},o)),Y.type==="tool_use"&&Y.name){let V=Y.input?.file_path||Y.input?.path||void 0,q=ss(Y);if(P?.({type:"tool_use",jobId:o,tool:Y.name,...V?{file:V}:{},...q?{content:q}:{}},o),Y.name==="Edit"&&Y.input?.file_path){let ge={tool:"Edit",file_path:Y.input.file_path,old_string:Y.input.old_string,new_string:Y.input.new_string,replace_all:Y.input.replace_all};u.push(ge),E.push({sequence:E.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:ge.file_path,oldString:typeof ge.old_string=="string"?ge.old_string:void 0,newString:typeof ge.new_string=="string"?ge.new_string:void 0,replaceAll:typeof ge.replace_all=="boolean"?ge.replace_all:void 0})}else Y.name==="Write"&&Y.input?.file_path&&(u.push({tool:"Write",file_path:Y.input.file_path,content:Y.input.content}),E.push({sequence:E.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:Y.input.file_path,content:typeof Y.input.content=="string"?Y.input.content:void 0}))}Y.type==="thinking"&&Y.thinking&&P?.({type:"thinking",jobId:o,text:Y.thinking},o)}}oe.type==="result"&&oe.is_error===!0&&(O=!0,typeof oe.error=="string"&&(C=oe.error),typeof oe.result=="string"&&(I=oe.result)),oe.type==="user"&&oe.tool_use_result?.file?.filePath&&P?.({type:"tool_use",jobId:o,tool:"Read",file:oe.tool_use_result.file.filePath},o)}catch{}});let U=[];m.stderr?.on("data",ne=>{U.push(ne.toString())}),m.on("close",ne=>{if(clearTimeout(M),L.close(),f.length===0&&G.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...G].join(", ")}`),w)O=!0,R=`Timed out after ${Math.round(k/6e4)} minutes`;else if(ne!==0&&ne!==null){O=!0;let ye=U.join("").trim(),Y=f.join("").trim(),V=f.length===0&&G.size>0?` (no text captured, event types: ${[...G].join(", ")})`:"";R=ye||I||Y||`Claude process exited with code ${ne}${V}`}O&&!R&&I&&(R=I);let oe=as(R,C);y({sessionId:h,text:f.join(""),success:!O,error:O?oe.message:void 0,errorCode:O?oe.code:void 0,recoverableError:O?oe.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:E.length>0?E:void 0})}),m.on("error",ne=>{clearTimeout(M),O=!0,R=ne.message,y({sessionId:h,text:f.join(""),success:!1,error:R,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:u.length>0?u:void 0,editEvents:E.length>0?E:void 0})})});return{process:m,result:p}}function as(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 cs,spawnSync as ar}from"child_process";import{readFileSync as ds,statSync as ls}from"fs";import{basename as ps,extname as us,isAbsolute as ms,relative as cr,resolve as fs}from"path";import{createInterface as hs}from"readline";function nr(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var or=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),uo=2e5,gs=1e5,dr=2e5;function lr(o){let e=ps(o).toLowerCase(),n=us(o).toLowerCase();return or.has(n)||or.has(e)}function Wt(o,e){let n=ms(e)?e:fs(o,e),t=cr(o,n);return t===""||t.startsWith("..")?null:n}function yn(o,e){if(!lr(e))return;let n=Wt(o,e);if(n)try{let t=ls(n);return t.isFile()?t.size>uo?{exists:!0,truncated:!0}:{exists:!0,content:ds(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function ys(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function vs(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 rr(o){return ys(o,["patch","diff","unifiedDiff","unified_diff"])}function mo(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function ir(o,e){let n=ar("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:dr+65536});return n.status!==0?null:n.stdout??""}function Is(o){let e=new Set;for(let n of o.split(`
|
|
30
|
-
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function sr(o){let e=ir(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=ir(o,["diff","--no-ext-diff","HEAD","--"])??"",t=mo(n,dr);return{status:e,changedFiles:Is(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function ws(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function bs(o,e){if(!lr(e))return;let n=Wt(o,e);if(!n)return;let t=cr(o,n);if(t===""||t.startsWith(".."))return;let r=ar("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:uo+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=mo(i,uo);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function xs(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):bs(o,t),i=yn(o,t);return{filePath:t,...r?{before:r}:{},...i?{after:i}:{}}})}function vn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:i,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,x=[];if(i){x.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let b of l)x.push("-c",b);s&&x.push("-m",s),x.push(i),x.push(n),r&&x.push("--image",r)}else{x.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let b of l)x.push("-c",b);s&&x.push("-m",s),x.push(n),r&&x.push("--image",r)}let k=cs("codex",x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),P=new Promise(b=>{let m,p=[],y=[],h=[],f=new Map,u=new Map,E=!1,O="",R=hs({input:k.stdout}),C=new Set;R.on("line",w=>{if(w.trim())try{let M=JSON.parse(w),L=M.type??"unknown";if(C.add(L),L==="thread.started"&&M.thread_id&&!m&&(m=M.thread_id),(L==="item.agentMessage.delta"||L==="item/agentMessage/delta")&&M.delta?.text&&(p.push(M.delta.text),c?.({type:"delta",jobId:o,text:M.delta.text},o)),(L==="item.reasoning.delta"||L==="item/reasoning/delta")&&M.delta?.text&&c?.({type:"thinking",jobId:o,text:M.delta.text},o),(L==="item.started"||L==="item/started")&&M.item){let G=M.item.type;if(G==="command_execution"){let U=M.item.command,ne=U?nr(U):void 0,oe=sr(t),ye=new Map;for(let V of oe?.changedFiles??[])ye.set(V,yn(t,V));typeof M.item.id=="string"&&u.set(M.item.id,{...U?{rawCommand:U}:{},...ne?{command:ne}:{},...oe?{beforeWorktree:oe}:{},beforeSnapshots:ye});let Y=ne?`Bash: ${ne.split(`
|
|
31
|
-
`)[0].slice(0,80)}`:"Bash";y.push(Y),c?.({type:"tool_use",jobId:o,tool:"Bash",...ne?{content:ne}:{}},o)}else if(G==="file_change"){let U=M.item.filename||M.item.path;U&&!f.has(U)&&f.set(U,yn(t,U)),y.push(U?`Edit ${U.split("/").pop()}`:"Edit");let ne=U?Wt(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...ne?{file:ne}:{}},o)}else if(G==="file_read"){let U=M.item.filename||M.item.path;y.push(U?`Read ${U.split("/").pop()}`:"Read");let ne=U?Wt(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...ne?{file:ne}:{}},o)}else if(G==="web_search")y.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(G==="mcp_tool_call"){let U=M.item.tool_name||M.item.name||"MCP";y.push(U),c?.({type:"tool_use",jobId:o,tool:U},o)}}if((L==="item.completed"||L==="item/completed")&&M.item){if(M.item.type==="agent_message"){let G=M.item.text;typeof G=="string"&&G&&(p.push(G),c?.({type:"delta",jobId:o,text:G},o))}else if(M.item.type==="reasoning"){let G=M.item.text;typeof G=="string"&&G&&c?.({type:"thinking",jobId:o,text:G},o)}else if(M.item.type==="file_change"&&Array.isArray(M.item.changes))for(let G of M.item.changes){let U=G.path||G.filename,ne=G.kind==="add"?"Write":"Edit";if(U){y.push(`${ne} ${U.split("/").pop()}`);let oe=Wt(t,U)??U;c?.({type:"tool_use",jobId:o,tool:ne,file:oe},o);let ye=G,Y=typeof ye.kind=="string"?ye.kind:void 0,V=vs(Y),q=f.get(U),ge=yn(t,U);h.push({sequence:h.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:V,filePath:U,...q?{before:q}:{},...ge?{after:ge}:{},...rr(ye)?{patch:rr(ye)}:{},...Y?{rawKind:Y}:{}}),f.set(U,ge)}}else if(M.item.type==="command_execution"){let G=typeof M.item.id=="string"?M.item.id:void 0,U=G?u.get(G):void 0,ne=typeof M.item.command=="string"?M.item.command:U?.rawCommand,oe=ne?nr(ne):U?.command,ye=sr(t);if(ws(U?.beforeWorktree,ye)){let Y=[...new Set([...U?.beforeWorktree?.changedFiles??[],...ye?.changedFiles??[]])],V=typeof M.item.aggregated_output=="string"?mo(M.item.aggregated_output,gs):void 0,q=typeof M.item.exit_code=="number"?M.item.exit_code:M.item.exit_code===null?null:void 0,ge=typeof M.item.status=="string"?M.item.status:void 0;h.push({sequence:h.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...ne?{rawCommand:ne}:{},...oe?{command:oe}:{},...q!==void 0?{exitCode:q}:{},...ge?{status:ge}:{},...V?{output:V.text}:{},...V?.truncated?{outputTruncated:!0}:{},...U?.beforeWorktree?{beforeWorktree:U.beforeWorktree}:{},...ye?{afterWorktree:ye}:{},...Y.length>0?{touchedFiles:xs(t,Y,U?.beforeSnapshots??new Map)}:{}})}G&&u.delete(G)}}L==="turn.failed"&&(E=!0,O=M.error?.message||M.message||"Turn failed")}catch{}});let I=[];k.stderr?.on("data",w=>{I.push(w.toString())}),k.on("close",w=>{R.close(),p.length===0&&C.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...C].join(", ")}`),w!==0&&w!==null&&(E=!0,O=I.join("")||`Codex process exited with code ${w}`),b({sessionId:m,text:p.join(""),success:!E,error:E?O:void 0,editEvents:h.length>0?h:void 0,toolsUsed:y.length>0?y:void 0})}),k.on("error",w=>{E=!0,O=w.message,b({sessionId:m,text:p.join(""),success:!1,error:O,editEvents:h.length>0?h:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:k,result:P}}import{spawn as Ss}from"child_process";import{createInterface as Rs}from"readline";function pr(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 ur(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),i&&l.push("--model",i),l.push("-p",n);let x=Ss(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),k=new Promise(P=>{let b,m=[],p=[],y=!1,h="",f=!1,u=setTimeout(()=>{f=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},s),E=Rs({input:x.stdout}),O=new Set,R=[];E.on("line",I=>{if(I.trim())try{let w=JSON.parse(I),M=Gt(w);O.add(M),R.length<5&&ks(M)&&R.push(I.slice(0,800));let L=Ht(w,["sessionId","session_id","id"],["session","conversation","thread"]);L&&!b&&(b=L);let G=Ps(w,m.length===0);G&&(m.push(G),c?.({type:"delta",jobId:o,text:G},o));let U=Ts(w);U&&c?.({type:"thinking",jobId:o,text:U},o);let ne=js(w);ne&&(p.push(ne.label),c?.({type:"tool_use",jobId:o,tool:ne.tool,...ne.file?{file:ne.file}:{},...ne.content?{content:ne.content}:{}},o));let oe=Es(w);oe&&(y=!0,h=oe)}catch{}});let C=[];x.stderr?.on("data",I=>{C.push(I.toString())}),x.on("close",I=>{clearTimeout(u),E.close(),m.length===0&&O.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...O].join(", ")}`),R.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${R.join(`
|
|
32
|
-
`)}`)),f?(y=!0,h=`Timed out after ${Math.round(s/6e4)} minutes`):I!==0&&I!==null&&(y=!0,h=C.join("").trim()||h||`Copilot process exited with code ${I}`);let w=y?pr(h,i):null;P({sessionId:b,text:m.join(""),success:!y,error:w?.message,errorCode:w?.code,recoverableError:w?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),x.on("error",I=>{clearTimeout(u);let w=pr(I.message,i);P({sessionId:b,text:m.join(""),success:!1,error:w.message,errorCode:w.code,recoverableError:w.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:x,result:k}}function Gt(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function Ps(o,e=!1){let n=Gt(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Le(o.delta)??Le(o.content)??Le(o.message);if(n==="assistant.message"&&e)return Le(o.message)??Le(o.content)??Le(o);if(n==="result"&&e)return Le(o.result)??Le(o.output)??Le(o.message)??Le(o);let i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof o.text=="string"&&fo(o))return o.text;if(typeof o.message=="string"&&fo(o))return o.message;if(typeof o.delta=="string"&&fo(o))return o.delta}function Le(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Le).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Le(e[n]);if(t)return t}}function ks(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function Ts(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 js(o){let e=Ht(o,["tool","toolName","tool_name","name"]),n=Ht(o,["command","cmd"]),t=Ht(o,["file","path","filename","filePath"]),r=Gt(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
33
|
-
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let i=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function Es(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&Gt(o).toLowerCase().includes("error"))return o.message}function Ht(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let i=Ht(r,e);if(i)return i}}function fo(o){let e=Gt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as As,readFile as Ms}from"fs/promises";import{join as ho}from"path";var In=class{constructor(e){let n=ho(e,".popmelt");this.decisionsDir=ho(n,"decisions")}async listDecisionIds(){try{return(await As(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 Ms(ho(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}};function fr(o,e){let n=o.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),r=Bs(t.assertionResults,e),i=Ls(r);return{status:i,summary:ot(t.summary)||vr(i),assertionResults:r,tooling:Fs(t.tooling)}}catch{}return{status:"needs_review",summary:zs(o.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function hr(o,e){let n=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length?[f.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(f=>f.path),i=[...new Set(r.map(f=>f.map(String).join(".")).filter(Boolean))].map(f=>({kind:"model_path",value:f}));if(i.length===0||o.decisionIds.length===0)return[];let s=new Set(o.decisionIds),c=new Set(i.map(f=>f.value)),d=e.cases.find(f=>f.status!=="rejected"&&(f.sourceDecisionIds.some(u=>s.has(u))||(f.dependencies??[]).some(u=>u.kind==="model_path"&&c.has(u.value)))),l=(o.selectedChanges??[]).find(f=>f.label?.trim())?.label?.trim()??t.find(f=>f.label?.trim())?.label?.trim()??o.title,x=d?.id.startsWith("eval-model-")??!1,k=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length>0?[{path:f.path,value:f.value,label:f.label,detail:f.detail}]:[]),b=(k.length>0?k:t.map(f=>({path:f.path,value:f.value,label:f.label,detail:f.rationale}))).flatMap(f=>_s(f,o.decisionIds)),m=bn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!x?d.assertions:[],...b,...b.length===0&&m?[m]:[]])],y=i[0].value,h=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!x?d.title:l,status:"pending",category:d?.category??h,prompt:d&&!x?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!x?d.rationale:Os(y),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...i].map(f=>[`${f.kind}:${f.value}`,f])).values()]}]}function _s(o,e){let n=String(o.path[0]??"");if(n==="rules")return Cs(o.value,e);if(n==="components"){let s=gr(String(o.path[1]??o.label??"component")),c=wn(o.value),d=c?Kt(c.usage):[];if(d.length>0){let x=Ds(d),k=d.length===1?"uses":"use";return[`The ${x} ${k} the same shared implementation for the ${s} pattern.`]}if(c?.shared===!0)return[`The product uses a shared implementation for the ${s} pattern.`];let l=c?ot(c.constraint):"";if(l){let x=$s(l,s);if(x)return[x]}}if(n==="tokens"){let s=o.path.slice(1).map(String).join("."),c=wn(o.value),d=c&&"value"in c?c.value:o.value,l=Js(d);if(s&&l)return[`The ${s} token resolves to ${l}.`]}let t=wn(o.value),r=t?ot(t.text)||ot(t.constraint):typeof o.value=="string"?o.value:"",i=bn(r||o.detail||"");return i?[i]:[]}function Cs(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(s=>{let c=wn(s),d=c?ot(c.text):"";return d?[{text:d,sources:c?Kt(c.sources):[]}]:[]}),r=t.filter(s=>s.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(s=>bn(s.text)).filter(s=>!!s)}function $s(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?kt(`Wherever ${Vt(n[1])}, the shared ${e} implementation is used instead of ${Vt(n[2])}`):bn(o)}function go(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return kt(`${mr(n[1])} is ${Vt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return kt(mr(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return kt(`The product uses ${Vt(r[1])}`);let i=e.match(/^Do not (.+?)\.?$/i);return i?kt(`The product does not ${Vt(i[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":kt(e)}var bn=go;function Os(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${gr(e[1]??"component")} contract across its declared product surfaces.`:e[0]==="tokens"?`Protects the ${e.slice(1).join(".")} token from implementation drift.`:e[0]==="rules"?"Protects an enforceable product rule across its declared scope.":"Protects an enforceable product expectation across its declared scope."}function wn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function gr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function Ds(o){return o.length<=1?o[0]??"":o.length===2?`${o[0]} and ${o[1]}`:`${o.slice(0,-1).join(", ")}, and ${o.at(-1)}`}function Js(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function kt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function mr(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Vt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function yr(o){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
|
|
34
|
-
|
|
35
|
-
## Eval
|
|
36
|
-
\`\`\`json
|
|
37
|
-
${JSON.stringify(o.evalCase,null,2)}
|
|
38
|
-
\`\`\`
|
|
39
|
-
|
|
40
|
-
## Scope
|
|
41
|
-
\`\`\`json
|
|
42
|
-
${JSON.stringify(o.scope,null,2)}
|
|
43
|
-
\`\`\`
|
|
44
|
-
|
|
45
|
-
## Current Design Model
|
|
46
|
-
\`\`\`json
|
|
47
|
-
${JSON.stringify(o.model??null,null,2)}
|
|
48
|
-
\`\`\`
|
|
49
|
-
|
|
50
|
-
## Evidence
|
|
51
|
-
- Current page screenshot: ${o.screenshotPath}
|
|
52
|
-
- Chrome DevTools MCP is ${o.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
|
|
53
|
-
|
|
54
|
-
## Instructions
|
|
55
|
-
1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
|
|
56
|
-
2. Compare the runtime URL, component evidence, and visible state with the eval's declared scenarios. If the runtime does not satisfy an applicable declared scenario, mark affected assertions "needs_review" and name the scope mismatch instead of guessing.
|
|
57
|
-
3. Use the screenshot as baseline evidence.
|
|
58
|
-
4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
|
|
59
|
-
5. Judge each assertion independently as "pass", "fail", or "needs_review".
|
|
60
|
-
6. Keep failures actionable and grounded in observed evidence.
|
|
61
|
-
7. Do not propose visual markers yet.
|
|
62
|
-
8. End with exactly one machine-readable <eval_run_result> block.
|
|
63
|
-
9. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
|
|
64
|
-
10. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
|
|
65
|
-
|
|
66
|
-
The block must be valid JSON with this shape:
|
|
67
|
-
|
|
68
|
-
\`\`\`json
|
|
69
|
-
{
|
|
70
|
-
"status": "pass",
|
|
71
|
-
"summary": "Short run summary.",
|
|
72
|
-
"assertionResults": [
|
|
73
|
-
{
|
|
74
|
-
"assertion": "Original assertion text",
|
|
75
|
-
"status": "pass",
|
|
76
|
-
"summary": "What was observed.",
|
|
77
|
-
"evidence": ["Screenshot shows ...", "DOM selector ..."]
|
|
78
|
-
}
|
|
79
|
-
],
|
|
80
|
-
"tooling": {
|
|
81
|
-
"chromeDevtools": "available",
|
|
82
|
-
"evidenceTypes": ["screenshot", "dom", "computed_styles"]
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
\`\`\`
|
|
87
|
-
|
|
88
|
-
Allowed statuses: pass, fail, needs_review.
|
|
89
|
-
Allowed chromeDevtools values: available, unavailable, unknown.`}function ot(o){return typeof o=="string"?o.trim():""}function Kt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Ns(o){let e=ot(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Bs(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let i=r,s=ot(i.assertion);return s?{assertion:s,status:Ns(i.status)??"needs_review",summary:ot(i.summary)||vr("needs_review"),evidence:Kt(i.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Ls(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Fs(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=ot(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Kt(e.evidenceTypes).length>0?Kt(e.evidenceTypes):["screenshot"]}}function vr(o){return o==="pass"?"The current page appears to satisfy this eval.":o==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function zs(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Us}from"crypto";import{mkdir as qs,writeFile as Ws}from"fs/promises";import{join as yo}from"path";var xn=class{constructor(e){this.root=yo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=yo(this.root,"eval-screenshots"),t=Us("sha256").update(e).digest("hex"),r=yo(n,`${t}.webp`);return await qs(n,{recursive:!0}),await Ws(r,e,{flag:"wx"}).catch(i=>{if(i.code!=="EEXIST")throw i}),r}};import{randomUUID as Ir}from"crypto";import{mkdir as vo,readFile as Io,writeFile as Sn}from"fs/promises";import{dirname as wo,join as Tt}from"path";var We="[ProjectionWorker]",Hs={version:1,runs:[]},Gs={version:1,updatedAt:0,proposals:[]},Vs=12;function Ks(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 wr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function Qs(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Xs(o,e,n){let t=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let m of i){if(!m||typeof m!="object")continue;let p=m.sources;if(Array.isArray(p))for(let y of p)typeof y=="string"&&t.has(y)&&r.add(y)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=i.filter(m=>{if(!m||typeof m!="object")return!1;let p=m.id,y=typeof p=="string"?d.find(h=>h&&typeof h=="object"&&h.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(m)}).length,x=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},k=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},P=Object.keys(s).filter(m=>JSON.stringify(s[m])!==JSON.stringify(x[m])).length,b=Object.keys(c).filter(m=>JSON.stringify(c[m])!==JSON.stringify(k[m])).length;return{ruleCount:l,tokenSectionCount:P,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(m=>!r.has(m))}}function Ys(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Zs(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function Rn(o,e,n){let t=o;for(let i=0;i<e.length-1;i++)t=Zs(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=Ys(n)}function br(o,e){let n=o;for(let r=0;r<e.length-1;r++){let i=n[String(e[r])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function ea(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 ta(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 xr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=ea(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?ta(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Pn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Tt(e,".popmelt");this.runsPath=Tt(t,"projection-runs.json"),this.legacyRunsPath=Tt(t,"materialization-runs.json"),this.proposalsPath=Tt(t,"projection-queue.json"),this.legacyProposalsPath=Tt(t,"model-proposals.json"),this.modelPath=Tt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Io(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Ks(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let r=t.key.split(".");t.value===null?br(n,r):Rn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Vs),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(m=>m.id);console.log(`${We} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=ia(r,s),d=Qs(r,t.totalCandidateDecisionCount,c);n=Ir().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:i,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let x=!0,k,P,b;try{let m=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(m,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let h=await y;if(!h.success)x=!1,k=h.error,console.error(`${We} ${p} spawn error:`,k);else{let f=ra(h.text,i);if(f){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let R of f)Rn(u,R.path,R.value);Array.isArray(u.rules)&&(u.rules=wr(u.rules));let E=Xs(u,i,s);if(f){let R=[...new Set(f.flatMap(C=>C.decisionIds))];E.coveredDecisionIds=R,E.uncoveredDecisionIds=i.filter(C=>!R.includes(C))}P=E;let O=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:P,changes:f});b=O.id,console.log(`${We} Created model proposal ${O.id} for ${i.length} decision(s)`)}else x=!1,k="No valid bounded <model-changes> block found in response",console.error(`${We} ${k}`)}}catch(m){x=!1,k=m instanceof Error?m.message:String(m),console.error(`${We} Error:`,k)}return await this.persistRun({...l,status:x?"proposed":"failed",completedAt:Date.now(),error:k,outputStats:P,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:x,error:k}),{processedIds:i,success:x,error:k,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=wr(e.rules)),await Sn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await vo(wo(this.runsPath),{recursive:!0}),await Sn(this.runsPath,JSON.stringify(n,null,2)),n):{...Hs,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(i=>i.authorityStatus==="accepted"&&Array.isArray(i.changes)&&i.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Gs,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(t);for(let s of r.changes??[])Rn(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let i=await this.findModelProposal(e);if(!i)return null;if(i.status==="dismissed")return i;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?br(s,d.path):Rn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),i=new Map((t.evalProjections??[]).map(s=>[s.evalId,s]));for(let s of n){let c=typeof s=="string"?{evalId:s,title:s,action:"created"}:s;r.add(c.evalId),i.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...i.values()]})}async createModelProposal(e){let n={id:Ir().slice(0,8),status:"pending",title:na(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"}.`:oa(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(r={...i,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await vo(wo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await Sn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await vo(wo(this.runsPath),{recursive:!0}),await Sn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await Io(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await Io(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let i=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return i==="codex"?{provider:"codex",...vn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:hn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...gn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function na(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function oa(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function ra(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),i=t.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(k=>typeof k=="string"||typeof k=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let x=Array.isArray(d.decisionIds)?d.decisionIds.filter(k=>typeof k=="string"&&r.has(k)):[];return x.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:x,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===t.length?i:null}catch{return null}}function ia(o,e){let n=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
|
|
90
|
-
Kind: ${i.kind}
|
|
91
|
-
Claim: ${i.claim}
|
|
92
|
-
${i.rationale?`Rationale: ${i.rationale}`:""}
|
|
93
|
-
Subjects: ${i.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
|
|
94
|
-
Authority: ${i.authority.level}/${i.authority.mode}`).join(`
|
|
95
|
-
|
|
96
|
-
`),t=o.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
|
|
97
|
-
|
|
98
|
-
## Instructions
|
|
99
|
-
1. Review the current model (if any) and the new decisions below.
|
|
100
|
-
2. Determine the smallest concrete set of design-token, component-pattern, and rule changes supported by those decisions.
|
|
101
|
-
3. Attribute every change to one or more accepted decision IDs from this prompt.
|
|
102
|
-
4. Output no more than 40 changes as a JSON array inside <model-changes> tags.
|
|
103
|
-
5. Do not edit files or run commands. Return only the <model-changes> block.
|
|
104
|
-
|
|
105
|
-
${e?`## Current Model
|
|
106
|
-
\`\`\`json
|
|
107
|
-
${JSON.stringify(e,null,2)}
|
|
108
|
-
\`\`\`
|
|
109
|
-
|
|
110
|
-
Use this only to understand the existing state and avoid proposing unchanged values.`:"No model exists yet. Propose only the entries directly supported by the accepted decisions below."}
|
|
111
|
-
|
|
112
|
-
## Accepted Decisions to Project
|
|
113
|
-
${n}
|
|
114
|
-
|
|
115
|
-
## Output Format
|
|
116
|
-
Each change is a JSON object with:
|
|
117
|
-
- \`id\`: stable descriptive identifier for this proposed change
|
|
118
|
-
- \`path\`: JSON path in the derived model; the first segment must be \`tokens\`, \`components\`, or \`rules\`
|
|
119
|
-
- \`label\`: short human-readable label
|
|
120
|
-
- \`value\`: complete JSON value to set at that path
|
|
121
|
-
- \`decisionIds\`: one or more IDs from ${JSON.stringify(t)} that directly support the change
|
|
122
|
-
- \`rationale\`: concise explanation of the projection from decision to model entry
|
|
123
|
-
|
|
124
|
-
For tokens and components, choose the narrowest durable path. For rules, emit a single change at path \`["rules"]\` whose value is the complete next rules array. Preserve unchanged rule IDs and order, and keep the array at 30 rules maximum.
|
|
125
|
-
|
|
126
|
-
### Rule format
|
|
127
|
-
Each rule is a JSON object:
|
|
128
|
-
\`\`\`json
|
|
129
|
-
{ "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] }
|
|
130
|
-
\`\`\`
|
|
131
|
-
|
|
132
|
-
Fields:
|
|
133
|
-
- \`id\`: 8-character hex string. Preserve IDs for unchanged rules. Generate new IDs for new or merged rules.
|
|
134
|
-
- \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
|
|
135
|
-
- \`text\`: A clear, enforceable design rule
|
|
136
|
-
- \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(t)}
|
|
137
|
-
|
|
138
|
-
### Rule guidelines
|
|
139
|
-
- **Hard cap: 30 rules maximum.** Merge rules covering the same concern into one.
|
|
140
|
-
- **Reject:** workflow advice ("After fixing X, verify Y"), instance-level observations ("The hero section uses 32px gap"), rules that merely restate a token or component already in the model.
|
|
141
|
-
- **Keep:** Enforceable patterns, constraints, relationships between elements, accessibility requirements.
|
|
142
|
-
|
|
143
|
-
Example:
|
|
144
|
-
<model-changes>
|
|
145
|
-
[
|
|
146
|
-
{
|
|
147
|
-
"id": "primary-color",
|
|
148
|
-
"path": ["tokens", "colors", "primary"],
|
|
149
|
-
"label": "Primary color",
|
|
150
|
-
"value": "#3b82f6",
|
|
151
|
-
"decisionIds": [${JSON.stringify(t[0]??"")}],
|
|
152
|
-
"rationale": "The accepted decision establishes this as the shared primary action color."
|
|
153
|
-
}
|
|
154
|
-
]
|
|
155
|
-
</model-changes>
|
|
156
|
-
|
|
157
|
-
## Guidelines
|
|
158
|
-
- Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
|
|
159
|
-
- Extract clear, enforceable rules into the \`rules\` array as structured objects.
|
|
160
|
-
- Do not silently override conflicting existing values; propose the explicit change for owner review.
|
|
161
|
-
- Keep the model concise \u2014 only include patterns with clear evidence from decisions.
|
|
162
|
-
- Do not emit unchanged entries or copy the complete model.
|
|
163
|
-
- Do NOT output resolution or question blocks. Just output the <model-changes> block.
|
|
164
|
-
- Spacing tokens can be plain strings ("8px") or objects with code bindings:
|
|
165
|
-
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
166
|
-
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
167
|
-
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
168
|
-
Include property and bindings when the decision context has class-level evidence.`}var kn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as sa}from"child_process";import{readFile as xo}from"fs/promises";import{homedir as jn}from"os";import{join as Be}from"path";var So=/popmelt/i,aa=/chrome|devtools/i;function It(){return{found:!1,name:null,scope:null,disabled:!1}}function jt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Qt(o){for(let e of Object.keys(o))if(So.test(e))return e;return null}async function Tn(o){try{let e=await xo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function Ro(o){let e=jn(),n=await Tn(Be(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Qt(r.mcpServers);if(i)return jt(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[o];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Qt(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(x=>So.test(x));return jt(d,"project",l)}}}}}let t=await Tn(Be(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Qt(r.mcpServers);if(s){let c=await Sr(o,s);return jt(s,"mcp.json",c)}}let i=Qt(r);if(i&&i!=="mcpServers"){let s=await Sr(o,i);return jt(i,"mcp.json",s)}}return It()}async function Sr(o,e){let n=Be(o,".claude","settings.local.json"),t=await Tn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var ca=/^\[mcp_servers\.([^\]]+)\]/;function da(o){return o.replace(/^"(.+)"$/,"$1")}function la(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function Pr(o){let e=o.split(`
|
|
169
|
-
`),n=[],t=null;for(let r of e){let i=r.match(ca);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
170
|
-
`)}),t={name:i[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
171
|
-
`)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
172
|
-
`)}),n}function kr(o){return/enabled\s*=\s*false/i.test(o)}async function Po(o){let e=process.env.CODEX_HOME||Be(jn(),".codex"),n=await Rr(Be(e,"config.toml"),"user");if(n.found)return n;let t=await Rr(Be(o,".codex","config.toml"),"project");return t.found?t:It()}async function pa(o,e){let n=process.env.CODEX_HOME||Be(jn(),".codex"),t=new Set;for(let r of[Be(n,"config.toml"),Be(o,".codex","config.toml")])try{let i=await xo(r,"utf-8");for(let s of Pr(i)){if(la(s.name)||kr(s.body))continue;let c=da(s.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function Tr(o){return pa(o,aa)}async function ko(o,e="copilot"){let n=await ua(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Be(jn(),".copilot"),r=await bo(Be(t,"mcp-config.json"),"user");if(r.found)return r;let i=await bo(Be(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await bo(Be(o,".github","mcp.json"),"mcp.json");return s.found?s:It()}async function ua(o){try{let e=await new Promise((n,t)=>{sa(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return jr(JSON.parse(e),"user")}catch{return It()}}async function bo(o,e){let n=await Tn(o);return jr(n,e)}function jr(o,e){if(!o||typeof o!="object")return It();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Qt(t);return r?jt(r,e):It()}async function Rr(o,e){try{let n=await xo(o,"utf-8"),t=Pr(n);for(let r of t)if(So.test(r.name)){let i=kr(r.body);return jt(r.name,e,i)}}catch{}return It()}import{execFile as Er}from"child_process";import{mkdir as ma,readFile as Ar,writeFile as Mr}from"fs/promises";import{homedir as _r}from"os";import{dirname as fa,join as To}from"path";var jo="https://mcp.popmelt.com/mcp";async function Cr(o=jo){let e=To(_r(),".claude.json"),n;try{let r=await Ar(e,"utf-8");n=JSON.parse(r)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let r of Object.keys(t))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await Mr(e,JSON.stringify(n,null,2)+`
|
|
173
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function $r(o=jo){let e=process.env.CODEX_HOME||To(_r(),".codex"),n=To(e,"config.toml"),t;try{t=await Ar(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await ma(fa(n),{recursive:!0});let r=`
|
|
174
|
-
[mcp_servers.popmelt]
|
|
175
|
-
url = "${o}"
|
|
176
|
-
`;return await Mr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Or(o=jo,e="copilot"){let n=await ha(e);if(ga(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{Er(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function ha(o){try{let e=await new Promise((n,t)=>{Er(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return JSON.parse(e)}catch{return null}}function ga(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var En=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as Jo,readFile as ut,writeFile as No}from"fs/promises";import{join as Xe}from"path";var ya=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Eo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function An(o){return new Set(Eo(o).split(" ").filter(e=>e.length>2&&!ya.has(e)))}function Dr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function va(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function Ia(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Eo).filter(Boolean),i=An([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(t.has(s.id)){n.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of va(s)){let l=Eo(d.value);for(let P of r){let b=l===P?95:l.includes(P)||P.includes(l)?75:0;b>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:d.by,score:b})}let k=["/","#","[","]","="].some(P=>d.value.includes(P))?0:Math.round(Dr(An(l),i)*55);k>=30&&k>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:k>=45?"strong":"weak",matchedBy:"query_text",score:k})}c&&n.set(s.id,c)}return n}function wa(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let i=new Set(r.map(s=>s.state));return{state:i.size>1?"mixed":i.has("completed")?"completed":"attempted",attemptIds:r.map(s=>s.id)}}function ba(o){return Math.ceil(JSON.stringify(o).length/4)}function Ao(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let h=[...o.events].reverse().find(f=>f.entity.entityType==="proposal"&&f.entity.entityId===y.id&&f.toState==="deferred"&&f.transitionContext?.kind==="proposal_deferral")?.transitionContext;return h?h.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||h.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||h.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||h.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||h.resurfaceWhen.includes("after_date")&&!!(h.revisitAfter&&Date.parse(t)>=Date.parse(h.revisitAfter)):!1}),s=o.records.filter(y=>y.recordType==="implementation_attempt"),c=Ia(n,e),d=[...c.values()].sort((y,h)=>h.score-y.score),l=An([e.action,e.text].filter(Boolean).join(" ")),x=i.flatMap(y=>{let h=y.subjects.map(O=>c.get(O.subjectId)).filter(O=>!!O),f=Math.max(0,...h.map(O=>O.score)),u=Math.round(Dr(An(y.claim),l)*35),E=f+u;return E>=50?[{proposal:y,proposalMatches:h,score:E}]:[]}).sort((y,h)=>h.score-y.score||y.proposal.id.localeCompare(h.proposal.id)),k=Math.max(1,e.maxPackets??3),P=Math.max(200,e.maxEstimatedTokens??1200),b=[],m=0;for(let y of x){if(b.length>=k)break;let h=y.proposal.sourceRefs.slice(0,4),f={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(E=>E.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:E,...O})=>O)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(E=>E.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:wa(y.proposal,s),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:h},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...h]},u={...f,estimatedTokens:ba(f)};if(m+u.estimatedTokens>P)break;b.push(u),m+=u.estimatedTokens}let p=Math.max(0,x.length-b.length);return{packets:b,subjectMatches:d.map(({score:y,...h})=>h),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:x.length,omittedPacketCount:p,maxEstimatedTokens:P,estimatedTokens:m},uncertainty:c.size===0?"subject_unresolved":x.length===0?"no_relevant_pending_proposal":void 0}}var xa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Mo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Mn(o){return new Set(Mo(o).split(" ").filter(e=>e.length>2&&!xa.has(e)))}function Jr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Sa(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(Mo).filter(Boolean),r=Mn([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of o){if(n.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let x=Mo(l.value);for(let b of t){let m=x===b?95:x.includes(b)||b.includes(x)?75:0;m>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:m>=90?"exact":"strong",matchedBy:l.by,score:m})}let P=["/","#","[","]","="].some(b=>l.value.includes(b))?0:Math.round(Jr(Mn(x),r)*55);P>=30&&P>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:P>=45?"strong":"weak",matchedBy:"semantic",score:P})}c&&i.push(c)}return i.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Ra(o){return Math.ceil(JSON.stringify(o).length/4)}function Et(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Pa(o,e){let n=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(i=>i.state==="completed"),r=t.some(i=>i.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(i=>i.id)}}function ka(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),i=t[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function Nr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(C=>C.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(C=>C.recordType==="decision"&&C.state==="active"),c=i?s.filter(C=>i.has(C.id)):s,d=o.records.filter(C=>C.recordType==="implementation_attempt"),l=o.records.filter(C=>C.recordType==="verification_attempt"),x=o.records.filter(C=>C.recordType==="freshness_signal"&&C.state==="open"),k=o.records.filter(C=>C.recordType==="evidence"),P=o.records.filter(C=>C.recordType==="model_entry"),b=[...o.records].reverse().filter(C=>C.recordType==="eval_spec").filter((C,I,w)=>w.findIndex(M=>M.legacyId===C.legacyId)===I),m=Sa(r,e),p=new Map(m.map(C=>[C.subjectId,C.score])),y=Mn([e.action,e.text].filter(Boolean).join(" ")),h=c.flatMap(C=>{let I=Math.max(0,...C.subjects.map(L=>p.get(L.subjectId)??0)),w=Math.round(Jr(Mn(C.claim),y)*35),M=I+w;return M>=50?[{decision:C,score:M}]:[]}).sort((C,I)=>I.score-C.score||C.decision.id.localeCompare(I.decision.id)),f=new Map;for(let C of h.slice(0,t))f.set(C.decision.id,C.decision);for(let C of o.relationships){if(!Et(C,"excepts")&&!Et(C,"contradicts"))continue;let I=s.find(M=>M.id===C.from.entityId),w=s.find(M=>M.id===C.to.entityId);!I||!w||!f.has(I.id)&&!f.has(w.id)||(f.size<t&&f.set(I.id,I),f.size<t&&f.set(w.id,w))}let u=[...f.values()],E=C=>C.from.entityType==="decision"&&C.to.entityType==="decision"&&f.has(C.from.entityId)&&f.has(C.to.entityId),O=(C,I=!1)=>{let w=new Set(C.map($=>$.id)),M=x.filter($=>$.target.entityType==="decision"&&w.has($.target.entityId)),L=new Set(o.relationships.filter($=>Et($,"excepts")&&w.has($.from.entityId)&&w.has($.to.entityId)).flatMap($=>[$.from.entityId,$.to.entityId])),U=o.relationships.filter($=>Et($,"contradicts")&&w.has($.from.entityId)&&w.has($.to.entityId)).map($=>({id:$.id,decisionIds:[$.from.entityId,$.to.entityId],unresolvedQuestion:$.reason,expansionRefs:[{kind:"record",id:$.id}]})),ne=new Set(U.flatMap($=>$.decisionIds)),oe=k.filter($=>$.sourceRefs.some(Z=>Z.kind==="record"&&w.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===$.id&&Z.to.entityType==="decision"&&w.has(Z.to.entityId))),ye=Math.max(0,h.length-C.length),Y=o.relationships.some($=>Et($,"contradicts")&&E($)&&(!w.has($.from.entityId)||!w.has($.to.entityId))),V=I||ye>0||Y,q=[];m.length===0&&(e.subjectHints?.length??0)>0?q.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):C.length===0&&q.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),U.length&&q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:U.flatMap($=>$.expansionRefs)}),oe.some($=>$.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map($=>({kind:"record",id:$.id}))}),V&&q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let ge={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:m.map(({score:$,...Z})=>Z),modelEntries:P.filter($=>$.decisionIds.some(Z=>w.has(Z))).map($=>({id:$.id,key:$.key,value:$.value,decisionIds:$.decisionIds})),evalSpecs:b.filter($=>$.decisionIds.some(Z=>w.has(Z))).map($=>({id:$.id,legacyId:$.legacyId,state:$.state,title:$.title,assertionCount:$.assertions.length,decisionIds:$.decisionIds,expansionRef:{kind:"record",id:$.id}})),decisions:C.map($=>({id:$.id,kind:$.kind,claim:$.claim,subjectIds:$.subjects.map(Z=>Z.subjectId),authority:$.authority,effectiveState:ne.has($.id)?"conflicted":L.has($.id)?"excepted":"active",freshness:M.filter(Z=>Z.target.entityId===$.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:$.id}})),conflicts:U,uncertainties:q,implementation:C.map($=>Pa($.id,d)),verification:C.map($=>ka($.id,l,M)),evidence:oe.map($=>({evidenceId:$.id,summary:$.summary,availability:$.availability,sourceRefs:$.sourceRefs})),completeness:{status:V?"truncated":"complete",omittedDecisionCount:ye,omittedEvidenceCount:0,conflictsComplete:!Y}};return ge.budget.estimatedTokens=Ra(ge),ge},R=O(u);for(;R.budget.estimatedTokens>n&&u.length>0;){let C=u.pop(),I=o.relationships.filter(w=>Et(w,"contradicts")&&(w.from.entityId===C.id||w.to.entityId===C.id)).flatMap(w=>[w.from.entityId,w.to.entityId]);u=u.filter(w=>!I.includes(w.id)),R=O(u,!0)}return R}var Ta=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function At(o){return Ta.test(o)}function ja(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ae(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function _o(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){At(n)||ae(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function He(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ae(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(o,e,n,t=!1){t&&n.level==="contributor"&&ae(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ae(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Ea={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),advisory_explanation:new Set(["null->emerging","null->testing","null->grounded","null->challenged","null->retired","emerging->testing","emerging->grounded","emerging->challenged","emerging->retired","testing->grounded","testing->challenged","testing->retired","grounded->challenged","grounded->retired","challenged->testing","challenged->retired"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},Aa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ma(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),He(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=Ea[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ae(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(Aa.has(i)&&(wt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ae(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&ae(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ae(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&He(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function _a(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),He(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ae(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ae(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ae(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ae(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(wt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ae(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&_o(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&ae(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),He(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ae(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&ae(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&ae(o,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),He(o,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),He(o,`${n}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ae(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(He(o,`${n}.appliedAt`,e.appliedAt),wt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ae(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&ae(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ae(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&_o(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&_o(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ca(o,e,n){if(Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),He(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ae(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let r=e.from.entityType==="decision"&&e.to.entityType==="decision",i=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!i&&ae(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?ae(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&wt(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ae(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ae(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&ae(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ae(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function bt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),He(e,"manifest.createdAt",o.manifest.createdAt),He(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,y)=>{let h=n.get(p);h?ae(e,y,"duplicate_id",`ID is already used at ${h}.`):n.set(p,y)};o.records.forEach((p,y)=>{let h=`records[${y}]`;t(p.id,h),_a(e,p,h,o.manifest.projectId)}),o.events.forEach((p,y)=>{let h=`events[${y}]`;t(p.id,h),Ma(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let h=`relationships[${y}]`;t(p.id,h),Ca(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let h=`tombstones[${y}]`;t(p.id,h),Te(e,`${h}.id`,p.id),Te(e,`${h}.objectId`,p.objectId),Te(e,`${h}.deletedById`,p.deletedById),He(e,`${h}.deletedAt`,p.deletedAt),wt(e,`${h}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),i=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,y)=>{let h=`${p.entityType}:${p.entityId}`;!r.has(h)&&!i.has(h)&&ae(e,y,"dangling_entity_reference",`No record or tombstone exists for ${h}.`)};o.events.forEach((p,y)=>s(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{s(p.from,`relationships[${y}].from`),s(p.to,`relationships[${y}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,y)=>{c.has(p)||ae(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,h)=>{!r.has(`${p}:${y}`)&&!i.has(`${p}:${y}`)&&ae(e,h,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let h=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${h}.granteeId`),l("participant",p.grantedById,`${h}.grantedById`),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`));break;case"observation":p.captureContext.subjectIds.forEach((f,u)=>l("subject",f,`${h}.captureContext.subjectIds[${u}]`)),p.captureContext.artifactIds.forEach((f,u)=>d(f,`${h}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":p.subjects.forEach((f,u)=>l("subject",f.subjectId,`${h}.subjects[${u}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((f,u)=>d(f,`${h}.messageArtifactIds[${u}]`)),p.resultRefs.forEach((f,u)=>s(f,`${h}.resultRefs[${u}]`));break;case"iteration":p.threadIds.forEach((f,u)=>l("thread",f,`${h}.threadIds[${u}]`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"evidence":p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"advisory_explanation":p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`)),p.supersededById&&l("advisory_explanation",p.supersededById,`${h}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((f,u)=>l("iteration",f,`${h}.iterationIds[${u}]`)),p.coverageClaims.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverageClaims[${u}].decisionId`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${h}.replacesSpecId`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),(p.dependencies??[]).forEach((f,u)=>{f.kind==="subject"&&f.subjectId&&l("subject",f.subjectId,`${h}.dependencies[${u}].subjectId`)}),(p.scenarios??[]).forEach((f,u)=>{f.subjectIds?.forEach((E,O)=>l("subject",E,`${h}.scenarios[${u}].subjectIds[${O}]`))}),p.targets.forEach((f,u)=>l(f.entityType,f.entityId,`${h}.targets[${u}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${h}.evalSpecId`),p.targets.forEach((f,u)=>l(f.entityType,f.entityId,`${h}.targets[${u}]`)),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`));break;case"model_entry":p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`));break;case"model_projection":wt(e,`${h}.authority`,p.authority,!0),l("participant",p.appliedById,`${h}.appliedById`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.entryIds.forEach((f,u)=>l("model_entry",f,`${h}.entryIds[${u}]`)),p.coverage.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverage[${u}].decisionId`));break;case"freshness_signal":s(p.target,`${h}.target`),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`));break;default:break}});let x=new Map(o.events.map(p=>[p.id,p])),k=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),P=new Map;o.events.forEach((p,y)=>{let h=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,f=P.get(h)??new Set;f.add(p.toState),P.set(h,f),f.size>1&&ae(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),m=(p,y,h,f,u)=>{if(p.level!=="delegate"||!p.grantId)return;let E=b.get(p.grantId);if(!E){ae(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(E.granteeId!==y||E.level!=="delegate")&&ae(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let O=Date.parse(h);(O<Date.parse(E.startsAt)||E.endsAt&&O>Date.parse(E.endsAt)||E.revokedAt&&O>=Date.parse(E.revokedAt))&&ae(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),E.subjectIds.length&&f.length&&!f.every(R=>E.subjectIds.includes(R))&&ae(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&m(p.authority,p.acceptedById,p.createdAt,p.subjects.map(y=>y.subjectId),`records:${p.id}.authority`);o.events.forEach((p,y)=>{let h=k.get(`${p.entity.entityType}:${p.entity.entityId}`),f=h&&"subjects"in h?h.subjects.map(u=>u.subjectId):[];m(p.authority,p.participantId,p.createdAt,f,`events[${y}].authority`)}),o.relationships.forEach((p,y)=>{if(!p.authority)return;let h=[p.from,p.to].flatMap(f=>{let u=k.get(`${f.entityType}:${f.entityId}`);return u&&"subjects"in u?u.subjects.map(E=>E.subjectId):[]});m(p.authority,p.participantId,p.createdAt,h,`relationships[${y}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let y=x.get(p.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==p.proposalId||y.toState!=="accepted")&&ae(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==p.acceptedById&&ae(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),k.has(`proposal:${p.proposalId}`)||ae(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(f=>f.relationshipType==="supersedes"&&f.to.entityType==="decision"&&f.to.entityId===p.id)||ae(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(f=>f.entity.entityType==="decision"&&f.entity.entityId===p.id&&f.toState==="revoked"&&!!f.reason?.trim())||ae(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(h=>h.recordType==="decision"&&h.proposalId===p.id)||ae(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return ja(e)}function Xt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Br(o,e,n,t,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function $a(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function _n(o,e){let n=[],t=o.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),At(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of $a(e))At(i)||n.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Br(o,t,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Xt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Xt(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Br(o,i,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i,d],events:[s,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Oa}from"crypto";import{readFile as Da,readdir as Ja,realpath as Na}from"fs/promises";import{join as Yt,relative as Ba}from"path";var La=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Mt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Fe(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Lr(...o){return o.find(e=>!!e?.trim())?.trim()}function le(o,e,n,t){let i=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=Oa("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function Co(o,e){try{return JSON.parse(await Da(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Fa(o){let e=Mt(o);if(!e)return 0;let n=0,t=r=>{let i=Mt(r);if(!i){n+=1;return}for(let s of Object.values(i))t(s)};for(let r of Object.values(e))t(r);return n}function za(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Zt(o){let e=[],n=await Na(o.projectRoot).catch(()=>o.projectRoot),t=Yt(n,".popmelt"),r=await Co(Yt(t,"threads.json"),e),i=await Co(Yt(t,"model.json"),e),s=Mt(r),c=Mt(s?.threads)??{},d=Object.entries(c).map(([$,Z])=>({key:$,value:Mt(Z)})).filter($=>!!$.value),l=Yt(t,"decisions"),x=await Ja(l).catch(()=>[]),k=[];for(let $ of x.filter(Z=>Z.endsWith(".json")).sort()){let Z=Mt(await Co(Yt(l,$),e));Z&&k.push({file:$,value:Z})}let P=d.flatMap(({value:$})=>[$.createdAt,$.updatedAt]).filter($=>typeof $=="number"&&Number.isFinite($)),b=P.length?Math.min(...P):0,m=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=le(m,"project",m,b),y=le(m,"participant","legacy-owner",b),h=le(m,"participant","legacy-agent",b),f=le(m,"subject","project",b),u=Fe(Math.max(b,...P)),E=[],O=[],R=new Map,C=new Map,I=new Map(k.map($=>[$.value.id??$.file.replace(/^d-|\.json$/g,""),$.value])),w=new Map,M=($,Z,ue,se,De)=>{let Je=R.get(ue);if(Je)return Je;let Re=le(m,"artifact",$,se);return O.push({id:Re,kind:Z,mediaType:De,location:ue,availability:"available"}),R.set(ue,Re),Re};for(let{file:$,value:Z}of k){let ue=Z.id??$.replace(/^d-|\.json$/g,""),se=Z.createdAt??b,De=[M(`${ue}:envelope`,"other",`.popmelt/decisions/${$}`,se,"application/json")];Z.screenshotPath&&De.push(M(`${ue}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,se,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Je,Re]of(Z.pastedImagePaths??[]).entries())De.push(M(`${ue}:image:${Je}`,"image",Re,se));w.set(ue,De)}let L=($,Z,ue)=>({id:$,schemaVersion:1,projectId:p,createdAt:u,participantId:Z,sourceRefs:ue}),G=($,Z)=>{E.push(Z);let ue=C.get($)??[];ue.push(Z.id),C.set($,ue)},U=[{...L(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...L(h,h,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];E.push(...U),E.push({...L(f,y,[]),recordType:"subject",subjectType:"project",label:Ba(process.cwd(),n)||n,aliases:[],locators:[{id:le(m,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:Fe(b),sourceRefs:[]}]});let ne=new Map,oe=($,Z)=>{let ue=ne.get($);if(ue)return ue;let se=le(m,"subject",$,Z),De={...L(se,y,[{kind:"external",id:$}]),createdAt:Fe(Z),recordType:"subject",subjectType:"element",label:$,aliases:[],locators:[{id:le(m,"locator",$,Z),kind:"dom_selector",value:$,status:"current",validFrom:Fe(Z),sourceRefs:[{kind:"external",id:$}]}]};return E.push(De),ne.set($,se),se};for(let{key:$,value:Z}of d){let ue=Z.id??$,se=Z.createdAt??b,De=le(m,"thread",ue,se),Je={kind:"thread",id:ue},Re=[],Ue=[],Ve=Array.isArray(Z.messages)?Z.messages:[],et,at,ft=0;Ve.forEach((we,ct)=>{let Me=we.timestamp??se,tt=le(m,"artifact",`${ue}:message:${ct}`,Me);if(Re.push(tt),O.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${ct}`,availability:"available"}),R.set(`.popmelt/threads.json#/threads/${ue}/messages/${ct}`,tt),we.screenshotPath&&M(`${ue}:message:${ct}:screenshot`,"screenshot",we.screenshotPath,Me),we.role==="human"){et=we;let Ee=we.feedbackSummary??we.replyToQuestion;if(Ee?.trim()){let Ne=le(m,"observation",`${ue}:${ct}`,Me),pt=Z.elementIdentifiers??[],Pt={...L(Ne,y,[Je,{kind:"message",id:tt}]),createdAt:Fe(Me),recordType:"observation",state:"open",statement:Ee,captureContext:{subjectIds:pt.map(gt=>oe(gt,se)),artifactIds:[tt]},resolvedByIds:[]};G(ue,Pt),at=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let dt=we.jobId??`${ue}:${ct}`,lt=le(m,"iteration",dt,Me),ht=I.get(dt),co=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",lo={...L(lt,h,[Je,{kind:"message",id:tt},...(w.get(dt)??[]).map(Ee=>({kind:"artifact",id:Ee}))]),createdAt:Fe(Me),recordType:"iteration",threadIds:[De],startedAt:Fe(et?.timestamp,Me),completedAt:Fe(Me),requestSummary:Lr(et?.feedbackSummary,et?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:co,execution:{provider:we.provider??ht?.provider,model:we.model??ht?.model,sessionId:we.sessionId??ht?.sessionId},artifactIds:[tt,...w.get(dt)??[]]};G(ue,lo),Ue.push({entityType:"iteration",entityId:lt});let Ut=we.resolutions??ht?.resolutions??[];for(let[Ee,Ne]of Ut.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let pt=Z.elementIdentifiers??[],Pt=(pt.length?pt:[n]).map(mn=>({subjectId:mn===n?f:oe(mn,se),role:"governed"})),gt=le(m,"proposal",`${dt}:${Ne.annotationId??"resolution"}:${Ee}`,Me),po={...L(gt,h,[Je,{kind:"iteration",id:lt}]),createdAt:Fe(Me),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:Pt,subjectSemantics:Pt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Lr(et?.feedbackSummary,et?.replyToQuestion,Ne.summary),iterationId:lt,inferredById:h}};G(ue,po),Ue.push({entityType:"proposal",entityId:gt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${gt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Ut.some(Ee=>Ee.status==="resolved")||ht?.gitDiff){let Ee=le(m,"implementation",dt,Me),Ne={...L(Ee,h,[Je,{kind:"iteration",id:lt}]),createdAt:Fe(Me),recordType:"implementation_attempt",state:"completed",iterationIds:[lt],coverageClaims:[],summary:Ut.map(pt=>pt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};G(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:Ee}),ft+=1}at&&(at=void 0)});let Ft=Ve.at(-1),zt={...L(De,y,[Je]),createdAt:Fe(se),recordType:"thread",state:Ft?.question?"open":"resolved",messageArtifactIds:Re,outcome:Ft?.question?"question_unresolved":ft?"implementation_only":"no_outcome",resultRefs:Ue};E.push(zt),C.set(ue,[De,...C.get(ue)??[]])}let ye=Fa(i);ye&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ye} model values were not promoted because their accepted decision provenance is unresolved.`});let Y={manifest:{formatVersion:1,projectId:p,createdAt:Fe(b),updatedAt:u,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:E,events:[],relationships:[],artifacts:O,tombstones:[]},V=bt(Y),ge=(o.proofCaseIds??La).map($=>({legacyId:$,threadFound:d.some(({key:Z,value:ue})=>(ue.id??Z)===$),decisionEnvelopeFound:I.has($),recordIds:C.get($)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce(($,Z)=>$+(Z.value.messages?.length??0),0),decisionEnvelopes:k.length,modelEntries:ye,artifactsReferenced:O.length},imported:za(E),unresolvedAcceptance:e.filter($=>$.code==="acceptance_unresolved").length,deferredModelEntries:ye,proofCases:ge,issues:e,schemaIssues:V.issues}}}import{createHash as Ua}from"crypto";import{mkdir as Fr,open as $o,readFile as Oo,readdir as qa,rename as Wa,unlink as Do}from"fs/promises";import{join as rt}from"path";var Ha={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function $n(o){return Ua("sha256").update(JSON.stringify(o)).digest("hex")}function zr(o){return $n(o)}function Ur(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let r=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(r<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let i=o.records[r];if(i.projectId!==t.projectId||i.createdAt!==t.createdAt||i.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[r]=structuredClone(t)}for(let t of e.projectionUpdates){let r=o.records.find(i=>i.recordType===t.entityType&&i.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Ga(o,e,n){return Ur(structuredClone(o),e,n)}async function xt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await $o(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
177
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Wa(n,o)}catch(r){throw await Do(n).catch(()=>{}),r}}async function Cn(o){return JSON.parse(await Oo(o,"utf8"))}var On=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=rt(e,".popmelt","memory"),this.journalDir=rt(this.memoryDir,"journal"),this.manifestPath=rt(this.memoryDir,"manifest.json"),this.checkpointPath=rt(this.memoryDir,"checkpoint.json"),this.lockPath=rt(this.memoryDir,"writer.lock")}async initialize(e){let n=bt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Fr(this.journalDir,{recursive:!0});try{throw await Oo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await Oo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=$n(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await xt(this.checkpointPath,r),await xt(this.manifestPath,i)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await xt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=$n(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await xt(rt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await xt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!At(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...i,hash:zr(i)},c=Ga(t.bundle,e,n.committedAt),d=bt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await xt(rt(this.journalDir,l),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await xt(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Ha,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Cn(this.manifestPath),n=await Cn(rt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==$n(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await qa(this.journalDir),r=t.filter(P=>P.endsWith(".tmp")),s=t.filter(P=>/^\d{12}-[0-9a-f-]+\.json$/i.test(P)).sort().filter(P=>Number(P.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,x=new Set;for(let P of s){let b=await Cn(rt(this.journalDir,P)),{hash:m,...p}=b;if(m!==zr(p))throw new Error(`Journal hash mismatch: ${P}`);if(b.sequence!==d+1)throw new Error(`Journal sequence gap at ${P}`);if(b.previousHash!==l)throw new Error(`Journal chain mismatch at ${P}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${P}`);if(x.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);Ur(c,b.mutation,b.committedAt),d=b.sequence,l=b.hash,x.add(b.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let k=bt(c);if(!k.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(k.issues)}`);return{bundle:c,manifest:e,transactionIds:x,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Fr(this.memoryDir,{recursive:!0});let n;try{n=await $o(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Cn(this.lockPath).catch(()=>({})),i=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(s){i=s.code!=="ESRCH"}if(i)throw new Error("Memory journal is locked by another writer.");await Do(this.lockPath),n=await $o(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Do(this.lockPath).catch(()=>{})}}};import{randomBytes as Va}from"crypto";function fe(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Va(10).toString("hex"),r=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${r}${t.slice(4,7)}-${t.slice(7,19)}`}var Ka=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function qr(o,e){let n=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),t=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Ka(),l=d.records,x=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(E=>E.kind==="thread"&&E.id===e.threadId));x||(x={id:le(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(x));let k=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let E=o.records.find(O=>O.recordType==="subject"&&O.locators.some(R=>R.value===u&&R.status==="current"));E||(E={id:le(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(E)),k.push(E)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let E=o.records.find(O=>O.recordType==="subject"&&O.locators.some(R=>R.kind==="source_file"&&R.value===u&&R.status==="current"));E||(E={id:le(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(E)),k.push(E)}let P=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),b;if(P.length>0){b=le(r,"live-observation",i,e.createdAt);let u={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:P.map(E=>E.claim.trim()).join(" "),captureContext:{subjectIds:k.map(E=>E.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let m=le(r,"live-iteration",i,e.completedAt),p={id:m,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[x.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let y=[],h=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),f=k.length>0?k:o.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(P.length>0&&f.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,E]of P.entries()){let O=le(r,"live-proposal",`${i}:${u}`,e.completedAt),R=f.map(I=>({subjectId:I.id,role:"governed"})),C={id:O,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:m},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:E.claim.trim(),rationale:E.rationale?.trim()||void 0,proposedKind:E.proposedKind,subjects:R,subjectSemantics:R.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:E.sourceText?.trim()||e.requestSummary,iterationId:m,inferredById:t.id}};l.push(C),y.push(O)}if(h.length>0){let u=new Set(e.governingDecisionIds??[]),E=o.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&u.has(R.id)),O={id:le(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:m}],recordType:"implementation_attempt",state:"completed",iterationIds:[m],coverageClaims:E.map(R=>({decisionId:R.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${h.map(C=>C.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:m}]})),summary:h.map(R=>R.summary).join(" "),artifactIds:[]};l.push(O)}return{mutation:d,iterationId:m,proposalIds:y,observationId:b}}import{createHash as Qa}from"crypto";import{mkdir as Xa,open as Ya,readFile as Za,rename as ec,unlink as tc}from"fs/promises";import{join as Wr}from"path";function Hr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Gr(o){return Qa("sha256").update(JSON.stringify(o)).digest("hex")}async function nc(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ya(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await ec(n,o)}catch(r){throw await tc(n).catch(()=>{}),r}}function oc(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,l,x)=>{let k=d[l]??=[];k.includes(x)||k.push(x)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let x of[l.label,...l.aliases,...l.locators.filter(k=>k.status==="current").map(k=>k.value)]){let k=Hr(x);k&&s(t,k,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...c,checksum:Gr(c)}}function Vr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Hr(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var Dn=class{constructor(e){this.indexDir=Wr(e,".popmelt","memory","indexes"),this.indexPath=Wr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Za(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&i===Gr(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=oc(e,n);return await Xa(this.indexDir,{recursive:!0}),await nc(this.indexPath,t),t}};var en="popmelt:imprint",Kr="popmelt:imprint-evidence",_t="popmelt:imprint-relation";function Jn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===en)?.id}function Bo(o){let e=new Set;return o.filter(n=>{let t=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(t)?!1:(e.add(t),!0)})}function Nn(o,e){if(!o)return[];let n=new Set(o.relations.flatMap(t=>t.type==="instantiates"&&t.fromId===e?[t.toId]:[]));return o.concrete.filter(t=>n.has(t.id)).map(t=>({id:t.id,modelPath:t.modelPath,value:structuredClone(t.value),createdAt:t.createdAt,updatedAt:t.updatedAt}))}var Bn=class{constructor(e){this.projectRoot=e;this.store=new On(e),this.indexStore=new Dn(e),this.manifestPath=Xe(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await ut(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Zt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Zt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=Xe(this.projectRoot,".popmelt","memory","migrations"),n=Xe(e,"legacy-evals-v1.json");try{let i=JSON.parse(await ut(n,"utf8"));return{migrated:!1,specs:i.specs??0,runs:i.runs??0}}catch{}let t=[],r=[];try{let i=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(i.cases)?i.cases:[]}catch{}try{let i=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(i.runs)?i.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await Jo(e,{recursive:!0}),await No(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:r.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:r.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=Xe(this.projectRoot,".popmelt","memory","migrations"),n=Xe(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await ut(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Jo(e,{recursive:!0}),await No(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??i,d=r.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,x=new Set(r.bundle.records.map(u=>u.id)),k=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(E=>E.kind==="external"&&E.uri===_t?[E.id]:[]))),P=new Map,b=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let E=b.find(O=>Jn(O)===u.id);P.set(u.id,E?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let m=[],p=[],y=[],h=0;for(let u of t.explanations){let E=P.get(u.id),O=b.find(w=>w.id===E),R=[],C=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let w of C){let M=le(l,"imprint-evidence-record",w.id,Date.parse(w.createdAt));R.push(M),!x.has(M)&&(m.push({id:M,schemaVersion:1,projectId:l,createdAt:w.createdAt,participantId:c.id,sourceRefs:Bo([{kind:"external",id:w.id,uri:Kr},{kind:"external",id:u.id,uri:en},{kind:"thread",id:w.threadId},{kind:"message",id:w.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(w.kind)?"user_feedback":"judgment",summary:w.summary,availability:"available",artifactIds:[]}),y.push({id:le(l,"imprint-evidence-link",`${u.id}:${w.id}`,Date.parse(w.createdAt)),schemaVersion:1,projectId:l,createdAt:w.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:w.id,uri:Kr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),h+=1)}let I={id:E,schemaVersion:1,projectId:l,createdAt:O?.createdAt??u.createdAt,participantId:O?.participantId??c.id,sourceRefs:Bo([...O?.sourceRefs??[],{kind:"external",id:u.id,uri:en}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...O?.evidenceIds??[],...R])],concreteBindings:Nn(t,u.id),supersededById:u.supersededBy?P.get(u.supersededBy):void 0,updatedAt:u.updatedAt};O?p.push(I):m.push(I)}for(let u of t.relations){let E=P.get(u.fromId),O=P.get(u.toId);!E||!O||k.has(u.id)||y.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:u.id,uri:_t}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:O},reason:u.rationale||"The Imprint graph connected these explanations."})}let f=new Date().toISOString();if(m.length||p.length||y.length)try{let u=await this.store.commit({records:m,recordReplacements:p,events:[],relationships:y,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(l,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:f});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await Jo(e,{recursive:!0}),await No(n,JSON.stringify({version:2,migratedAt:f,explanations:t.explanations.length,evidence:h,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:h}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Ao(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Nr(t.bundle,r),reviewSelection:Ao(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:_n(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Zt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=_n(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let i=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(i),i}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(P=>P.recordType==="proposal"&&P.id===e.proposalId),r=n.bundle.records.find(P=>P.recordType==="participant"&&P.kind==="human"&&P.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:fe(i),decisionId:fe(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:fe(i),replacementProposalId:fe(i),acceptanceEventId:fe(i),decisionId:fe(i),relationshipId:fe(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:fe(i),reason:e.reason}:{...c,action:"defer",eventId:fe(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(P=>P.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=_n(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(P=>P.message).join(" ")};let x=await this.store.commitReviewPlan(l.plan,{transactionId:fe(i),committedAt:s});await this.refreshIndex(x);let k=l.plan.resultRefs.find(P=>P.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:k,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:x.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=qr(n.bundle,e),r=le(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),r=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active"),i=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="ai"&&f.status==="active"),s=e.action?r:i??r,c=t.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),x=t.bundle.manifest.projectId,k=[],P=[],b=[],m=t.bundle.records.filter(f=>f.recordType==="advisory_explanation"),p=new Map(m.flatMap(f=>{let u=Jn(f);return u?[[u,f.id]]:[]}));for(let f of e.summary.changes)if(!p.has(f.explanationId)){let u=n?.explanations.find(E=>E.id===f.explanationId);p.set(f.explanationId,le(x,"imprint-explanation",f.explanationId,Date.parse(u?.createdAt??d)))}for(let f of e.summary.changes){let u={kind:"external",id:f.explanationId,uri:en},E=p.get(f.explanationId),O=m.find(w=>w.id===E),R=n?.explanations.find(w=>w.id===f.explanationId),C={id:le(x,"imprint-live-evidence",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};k.push(C);let I={id:E,schemaVersion:1,projectId:x,createdAt:O?.createdAt??R?.createdAt??d,participantId:O?.participantId??s.id,sourceRefs:Bo([...O?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:R?.kind??O?.kind??"pattern",state:R?.state??f.state,statement:R?.statement??f.statement,rationale:R?.rationale??O?.rationale??e.summary.detail,scope:structuredClone(R?.scope??O?.scope??{kind:"project",values:[]}),subjectIds:O?.subjectIds??[c.id],evidenceIds:[...new Set([...O?.evidenceIds??[],C.id])],concreteBindings:R?Nn(n,f.explanationId):O?.concreteBindings??[],supersededById:R?.supersededBy?p.get(R.supersededBy):O?.supersededById,updatedAt:R?.updatedAt??d};O?P.push(I):k.push(I),b.push({id:le(x,"imprint-live-evidence-link",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:I.id},to:{entityType:"evidence",entityId:C.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let y=new Set(t.bundle.relationships.flatMap(f=>f.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===_t?[u.id]:[])));for(let f of n?.relations??[]){let u=p.get(f.fromId),E=p.get(f.toId);!u||!E||y.has(f.id)||b.push({id:le(x,"imprint-relation",f.id,Date.parse(f.createdAt)),schemaVersion:1,projectId:x,createdAt:f.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:f.id,uri:_t}],recordType:"relationship",relationshipType:f.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId:E},reason:f.rationale||"The Imprint graph connected these explanations."})}let h=le(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let f=await this.store.commit({records:k,recordReplacements:P,events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:h,committedAt:d});await this.refreshIndex(f)}catch(f){if(!(f instanceof Error)||!f.message.includes("Transaction already exists"))throw f}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=JSON.parse(await ut(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),t=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),i=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="ai"&&R.status==="active")??t;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(R=>R.recordType==="advisory_explanation"),l=new Map(d.flatMap(R=>{let C=Jn(R);return C?[[C,R]]:[]})),x=new Map([...[...l].map(([R,C])=>[R,C.id]),...e.explanations.filter(R=>!l.has(R.id)).map(R=>[R.id,le(c,"imprint-explanation",R.id,Date.parse(R.createdAt))])]),k=[],P=[],b=new Set(e.explanations.map(R=>R.id));for(let R of e.explanations){let C=l.get(R.id);if(!C){k.push({id:x.get(R.id),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:R.id,uri:en}],recordType:"advisory_explanation",kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Nn(e,R.id),supersededById:R.supersededBy?x.get(R.supersededBy):void 0,updatedAt:R.updatedAt});continue}let I={...structuredClone(C),kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),concreteBindings:Nn(e,R.id),supersededById:R.supersededBy?x.get(R.supersededBy):void 0,updatedAt:R.updatedAt},w=M=>JSON.stringify({kind:M.kind,state:M.state,statement:M.statement,rationale:M.rationale,scope:M.scope,concreteBindings:M.concreteBindings,supersededById:M.supersededById,updatedAt:M.updatedAt});w(C)!==w(I)&&P.push(I)}for(let[R,C]of l)b.has(R)||C.state==="retired"||P.push({...structuredClone(C),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let m=new Set(n.bundle.tombstones.flatMap(R=>R.objectType==="relationship"?[R.objectId]:[])),p=new Map(n.bundle.relationships.flatMap(R=>{if(m.has(R.id))return[];let C=R.sourceRefs.find(I=>I.kind==="external"&&I.uri===_t)?.id;return C?[[C,R]]:[]})),y=new Set(p.keys()),h=[];for(let R of e.relations){let C=x.get(R.fromId),I=x.get(R.toId);!C||!I||y.has(R.id)||h.push({id:le(c,"imprint-relation",R.id,Date.parse(R.createdAt)),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:R.id,uri:_t}],recordType:"relationship",relationshipType:R.type,from:{entityType:"advisory_explanation",entityId:C},to:{entityType:"advisory_explanation",entityId:I},reason:R.rationale||"The Imprint graph connected these explanations."})}let f=new Set(e.relations.map(R=>R.id)),u=t?[...p].filter(([R])=>!f.has(R)).map(([,R])=>({id:le(c,"imprint-relationship-tombstone",R.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:R.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:t.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!k.length&&!P.length&&!h.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let E=e.updatedAt,O=le(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(E));try{let R=await this.store.commit({records:k,recordReplacements:P,events:[],relationships:h,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:O,committedAt:E});return await this.refreshIndex(R),{status:"synced",relationships:h.length+u.length,explanations:k.length+P.length,headSequence:R.report.headSequence}}catch(R){if(!(R instanceof Error)||!R.message.includes("Transaction already exists"))throw R;return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(i=>i.recordType==="model_entry").sort((i,s)=>i.createdAt.localeCompare(s.createdAt)))r.decisionIds.some(i=>n.has(i))&&t.set(r.key,r);return[...t.values()]}async getImprintView(e=[]){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let t=await this.store.load(),r=t.bundle.records.filter(p=>p.recordType==="advisory_explanation"),i=new Map(r.map(p=>[p.id,p])),s=new Map(r.flatMap(p=>{let y=Jn(p);return y?[[y,p.id]]:[]})),c=new Set(e.map(p=>s.get(p)??p)),d=new Map(t.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),l=new Map(t.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),x=new Set(t.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),k=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),P={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=r.map(p=>{let y=p.evidenceIds.flatMap(u=>{let E=l.get(u);if(!E)return[];let O=E.sourceRefs.find(w=>w.kind==="thread")?.id,R=E.sourceRefs.find(w=>w.kind==="message")?.id,C=E.kind==="judgment"||E.kind==="user_feedback"||E.kind==="project_state"?E.kind:"other",I=d.get(E.participantId)??"unknown";return[{id:E.id,kind:C,summary:E.summary,createdAt:E.createdAt,participantKind:I,threadId:O,jobId:R}]}).sort((u,E)=>E.createdAt.localeCompare(u.createdAt)),h=t.bundle.relationships.flatMap(u=>{if(x.has(u.id))return[];if(!k.has(u.relationshipType))return[];let E=u.from.entityType==="advisory_explanation"&&u.from.entityId===p.id&&u.to.entityType==="advisory_explanation",O=u.to.entityType==="advisory_explanation"&&u.to.entityId===p.id&&u.from.entityType==="advisory_explanation";if(!E&&!O)return[];let R=E?u.to.entityId:u.from.entityId,C=i.get(R);return C?[{id:u.id,type:u.relationshipType,direction:E?"outgoing":"incoming",explanationId:C.id,statement:C.statement,rationale:u.reason}]:[]}),f=[...new Set([...p.sourceRefs.flatMap(u=>u.kind==="thread"?[u.id]:[]),...y.flatMap(u=>u.threadId?[u.threadId]:[])])];return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:y.length,recentEvidence:y.slice(0,4),concrete:p.concreteBindings.map(u=>({...structuredClone(u)})),relations:h,sourceThreadIds:f,needsGrounding:p.state==="testing"&&c.has(p.id)}}).sort((p,y)=>Number(y.needsGrounding)-Number(p.needsGrounding)||P[p.state]-P[y.state]||y.updatedAt.localeCompare(p.updatedAt)),m={total:b.filter(p=>p.state!=="retired").length,emerging:b.filter(p=>p.state==="emerging").length,testing:b.filter(p=>p.state==="testing").length,grounded:b.filter(p=>p.state==="grounded").length,challenged:b.filter(p=>p.state==="challenged").length,retired:b.filter(p=>p.state==="retired").length,needsGrounding:b.filter(p=>p.needsGrounding).length};return{head:{sequence:t.report.headSequence,updatedAt:t.bundle.manifest.updatedAt},counts:m,explanations:b}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let r=[...t.values()],i=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=i.filter(l=>l.targets.some(x=>x.entityType==="decision"&&x.entityId===c.id)).sort((l,x)=>x.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="decision"&&e.includes(i.id)?i.subjects.map(s=>s.subjectId):[])),r=[];for(let i of n.records)if(!(i.recordType!=="subject"||!t.has(i.id)))for(let s of i.locators.filter(c=>c.status==="current"))s.kind==="source_file"?r.push({kind:"source_file",value:s.value,subjectId:i.id}):s.kind==="route_pattern"?r.push({kind:"route",value:s.value,subjectId:i.id}):s.kind==="token_path"?r.push({kind:"model_path",value:s.value,subjectId:i.id}):(s.kind==="dom_selector"||s.kind==="file_export"||s.kind==="source_span")&&r.push({kind:"subject",value:s.value,subjectId:i.id});return[...new Map(r.map(i=>[`${i.kind}:${i.value}:${i.subjectId??""}`,i])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active"),r=n.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),c=fe(i),d=fe(i),l=fe(i),x=fe(i),k=fe(i),P=new Set(n.bundle.records.flatMap(w=>w.recordType==="model_entry"&&w.key===e.key?w.decisionIds:[])),b=n.bundle.records.filter(w=>w.recordType==="decision"&&w.state==="active"&&P.has(w.id)),m={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],y={...m,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},h={...m,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},f={...m,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:s},u={...m,id:x,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},E={...m,id:k,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[x],coverage:[{decisionId:l,status:"projected"}]},O={...m,id:fe(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},R=b.map(w=>({...m,id:fe(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:w.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),C=b.map(w=>({...m,id:fe(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:f.id},to:{entityType:"decision",entityId:w.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),I=await this.store.commit({records:[y,f,u,E],events:[h,...R],relationships:[O,...C],artifacts:[],tombstones:[],projectionUpdates:b.map(w=>({entityType:"decision",entityId:w.id,fromState:"active",state:"superseded"}))},{transactionId:fe(i),committedAt:s});return await this.refreshIndex(I),{decisionId:l,entryId:x}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),i=n.bundle.records.flatMap(m=>m.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===m.id||m.sourceRefs.some(y=>y.id===p))?[m.id]:[]),s=[...new Set(n.bundle.records.flatMap(m=>m.recordType==="decision"&&i.includes(m.id)?m.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:i,subjectIds:s,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!l)throw new Error("No active local owner participant is available.");let x=Date.now(),k=new Date(x).toISOString(),P={id:fe(x),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:k,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...i.map(m=>({kind:"record",id:m}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:i.map(m=>({entityType:"decision",entityId:m})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},b=r?[{id:fe(x),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:k,participantId:l.id,sourceRefs:[{kind:"record",id:P.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:P.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[P],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(x),committedAt:k})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(s=>s.objectType==="eval_spec").map(s=>s.objectId)),t=e.records.filter(s=>s.recordType==="eval_spec").reverse().filter((s,c,d)=>d.findIndex(l=>l.legacyId===s.legacyId)===c).filter(s=>!n.has(s.id)),r=e.records.filter(s=>s.recordType==="verification_attempt"),i=e.records.filter(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.targetKind==="verification_result");return t.map(s=>{let c=r.filter(x=>x.evalSpecId===s.id).sort((x,k)=>k.createdAt.localeCompare(x.createdAt))[0],d=c&&i.some(x=>x.target.entityType==="verification_attempt"&&x.target.entityId===c.id),l=s.state==="draft"?"draft":s.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:s.legacyId,canonicalSpecId:s.id,verificationState:l,title:s.title,status:s.state==="draft"?"pending":s.state==="active"?"approved":"rejected",category:s.category,prompt:s.prompt,assertions:s.assertions,rationale:s.rationale,sourceDecisionIds:s.decisionIds,sourceThreadIds:s.threadRefs,dependencies:s.dependencies??[],scenarios:s.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let i=t.evalRun,s=Date.parse(t.createdAt);return[{id:i?.id??t.id,evalId:r.legacyId,threadId:i?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:i?.createdAt??s,completedAt:i?.completedAt??s,durationMs:i?.durationMs??0,scope:i?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:i?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:i?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:i?.provider,model:i?.model,screenshotPath:i?.screenshotPath,codeFingerprint:i?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(P=>P.recordType==="verification_attempt"&&P.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let i=t.bundle.records.find(P=>P.recordType==="participant"&&P.status==="active"&&P.kind==="ai")??t.bundle.records.find(P=>P.recordType==="participant"&&P.status==="active");if(!i)return;let s=n.completedAt,c=new Date(s).toISOString(),d={id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:i.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},x=r.targets.map(P=>({id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:P,reason:n.summary})),k=await this.store.commit({records:[d,l],events:[],relationships:x,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});await this.refreshIndex(k)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((i,s)=>i.completedAt-s.completedAt)){let i=t.get(r.evalId);i&&await this.recordEvalVerification(i,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let i=Date.now(),s=new Date(i).toISOString(),c={id:fe(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(i),committedAt:s});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),r=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),i=e.filter(d=>!r.includes(d)).map(d=>d.id);if(i.length===0)return{valid:r,discardedIds:i};let s=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!s)return{valid:r,discardedIds:i};let c=i.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(x=>({id:fe(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:x.id,objectType:"eval_spec",deletedAt:l,deletedById:s.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:fe(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:i}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(m=>m.recordType==="model_projection"&&m.state==="applied"&&m.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(m=>m.recordType==="decision"&&e.decisionIds.includes(m.id)&&m.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=fe(s),l=e.changes.map(m=>{let p=m.decisionIds?.filter(f=>e.decisionIds.includes(f)),y=p?.length?p:e.decisionIds,h=[...new Set(r.filter(f=>y.includes(f.id)).flatMap(f=>f.subjects.map(u=>u.subjectId)))];return{id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:y.map(f=>({kind:"record",id:f})),recordType:"model_entry",key:m.path.map(String).join("."),subjectIds:h,decisionIds:y,value:m.value}}),x=new Set(l.flatMap(m=>m.decisionIds)),k={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:e.decisionIds.map(m=>({kind:"record",id:m})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(m=>m.id),coverage:e.decisionIds.map(m=>e.coverage?.find(p=>p.decisionId===m)??{decisionId:m,status:x.has(m)?"projected":"unprojected"})},P=l.flatMap(m=>m.decisionIds.map(p=>({id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:k.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:m.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...l,k],events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});return await this.refreshIndex(b),{projectionId:d,entryIds:l.map(m=>m.id),headSequence:b.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Zt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Vr(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function $t(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Ct(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Lo(o){let e=$t(o),n=$t(e.authority),t=n.level,r=n.mode,i=Ct(t,"authority.level",["owner","delegate","contributor"]),s=Ct(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:Ct(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=$t(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>Ct(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:Ct(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=$t(d);return{subjectId:Se(l.subjectId,"subjectId"),role:Ct(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Fo(o){let e=$t(o),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(c=>Se(c,s))}},t=(i,s)=>{if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<=0)throw new Error(`${s} must be a positive number.`);return i}},r=e.resurface===void 0?void 0:$t(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Ln(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
179
|
-
`)}async function Qr(o,e,n,t){let r=Ln(e);if(!(!r&&n.length===0))try{let i=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(i.actionPacket.decisions.length===0&&i.reviewSelection.packets.length===0)return;let s=new Map(i.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(i.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:i.source,...i.actionPacket.decisions.length>0?{acceptedTruth:{decisions:i.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:i.actionPacket.conflicts,truncated:i.actionPacket.completeness.status==="truncated"}}:{},packets:i.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:i.reviewSelection.completeness.status==="truncated",estimatedTokens:i.actionPacket.budget.estimatedTokens+i.reviewSelection.completeness.estimatedTokens}}catch(i){t?.(i);return}}function Xr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,r)=>["",`${r+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,r)=>["",`${r+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
180
|
-
`)}function Yr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!r||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let i=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&i.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function Zr(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!t||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:t,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function Fn(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],r=await rc(o),i=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,l,x,k,P,b,m,p,y,h,f,u,E,O=[],R=[],C=0,I=[];for(;C<r.length;){let w=r.indexOf(i,C);if(w===-1)break;let M=w+i.length;if(r.slice(w,w+s.length).equals(s))break;let L=M;r[L]===13&&r[L+1]===10&&(L+=2);let G=r.indexOf(`\r
|
|
181
|
-
\r
|
|
182
|
-
`,L);if(G===-1)break;let U=r.slice(L,G).toString("utf-8"),ne=G+4,oe=r.indexOf(i,ne),ye=oe!==-1?oe-2:r.length;I.push({headers:U,body:r.slice(ne,ye)}),C=oe!==-1?oe:r.length}for(let w of I){let M=w.headers.match(/name="([^"]+)"/);if(!M)continue;let L=M[1];if(L==="screenshot")c=w.body;else if(L==="feedback")d=w.body.toString("utf-8");else if(L==="color")l=w.body.toString("utf-8");else if(L==="provider")x=w.body.toString("utf-8");else if(L==="model")k=w.body.toString("utf-8");else if(L==="reasoningEffort")P=w.body.toString("utf-8");else if(L==="serviceTier")b=w.body.toString("utf-8");else if(L==="goal")m=w.body.toString("utf-8");else if(L==="pageUrl")p=w.body.toString("utf-8");else if(L==="viewport")y=w.body.toString("utf-8");else if(L==="planId")h=w.body.toString("utf-8");else if(L==="manifest")f=w.body.toString("utf-8");else if(L==="tasks")u=w.body.toString("utf-8");else if(L==="sourceId")E=w.body.toString("utf-8");else if(L.startsWith("screenshot-")){let G=L.slice(11);try{let U=decodeURIComponent(G);R.push({pathname:U,data:w.body})}catch{}}else if(L.startsWith("image-")){let G=L.split("-"),U=parseInt(G[G.length-1],10),ne=G.slice(1,-1).join("-");ne&&!isNaN(U)&&O.push({annotationId:ne,index:U,data:w.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:x,model:k,reasoningEffort:P,serviceTier:b,goal:m,pageUrl:p,viewport:y,planId:h,manifest:f,tasks:u,sourceId:E,pastedImages:O,pageScreenshots:R}}function rc(o){return new Promise((e,n)=>{let t=[];o.on("data",r=>t.push(r)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as ic}from"crypto";var sc=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,ac=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),cc=new Set(["strengthened","weakened","mixed","unknown"]);function tn(o,e=180){if(typeof o!="string")return;let n=o.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function dc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function ei(o,e,n,t=Date.now()){let r=dc(o);if(!r)return null;let i=typeof r.transition=="string"&&ac.has(r.transition)?r.transition:null,s=tn(r.focus);if(!i||!s)return null;let c=typeof r.evidencePosture=="string"&&cc.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:ic(),jobId:e,sequence:n,timestamp:t,transition:i,snapshot:{focus:s,seeking:tn(r.seeking),workingHypothesis:tn(r.workingHypothesis),evidencePosture:c,update:tn(r.update),nextObservation:tn(r.nextObservation)},contextPolicy:"exclude"}}function zo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function lc(o,e,n=0){let t=[],r=new Set,i=n;return{visibleText:o.replace(sc,(c,d)=>{try{let l=ei(JSON.parse(d),e,i);if(!l)return"";let x=zo(l);if(r.has(x))return"";r.add(x),t.push(l),i++}catch{}return""}).replace(/\n{3,}/g,`
|
|
183
|
-
|
|
184
|
-
`).trim(),orientations:t}}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 zn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let c=pc(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,r);let i=this.buffer.indexOf("</orientation>",r+13);if(i<0){this.buffer=this.buffer.slice(r);break}let s=this.buffer.slice(r+13,i).trim();this.buffer=this.buffer.slice(i+14);try{let c=ei(JSON.parse(s),this.jobId,this.sequence);if(!c)continue;let d=zo(c);if(this.signatures.has(d))continue;this.signatures.add(d),t.push(c),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=lc(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let i=zo(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},ti=`## Public orientation updates
|
|
185
|
-
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
186
|
-
<orientation>{"transition":"focus_shifted","focus":"Investigating the responsive overflow","seeking":"Which container introduces the extra width","update":"Padding is no longer the leading explanation","nextObservation":"Inspect computed widths at the failing breakpoint"}</orientation>
|
|
187
|
-
|
|
188
|
-
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
189
|
-
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
190
|
-
|
|
191
|
-
These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function nn(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${r||"none"}`);let s=e?.[t.id];if(s&&s.length>0)for(let c of s)n.push(` Attached image: use the Read tool to view ${c}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${r}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=JSON.stringify(t.original),s=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${c}: ${i} \u2192 ${s}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",s=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${i} \u2192 ${t.targetParentSelector}${s}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
|
|
192
|
-
### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let r of t.affectedElements){let i=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${i}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${i}: ${r.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let t=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[t.selector];t.reactComponent&&r.push(`(${t.reactComponent})`),t.context&&r.push(`in ${t.context}`),t.textContent&&r.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
|
|
193
|
-
`)}function ni(o,e,n){let t=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!i&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let s=0;for(let c of n.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(t.push(`### Round ${s} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${s} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${s} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${s} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,x=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${x} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=n.designModel.rules;if(Array.isArray(s)&&s.length>0)if(t.push(""),t.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let x=new Map;for(let k of s)if(typeof k=="object"&&k!==null&&"text"in k){let P=k,b=P.scope||"general";x.has(b)||x.set(b,[]),x.get(b).push(P.text)}for(let[k,P]of x){t.push(`**${k.charAt(0).toUpperCase()+k.slice(1)}**`);for(let b of P)t.push(`- ${b}`)}}else for(let x of s)typeof x=="string"&&t.push(`- ${x}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;c.has(l)||c.set(l,[]),c.get(l).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of c){t.push(""),t.push(`## Page: ${d}`);let x=s[d];x&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${x}`):!x&&n?.provider!=="codex"&&(Object.keys(s).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let k={...e,annotations:l,styleModifications:e.styleModifications},P=nn(k,n?.imagePaths);P&&(t.push(""),t.push(P))}}else{let s=nn(e,n?.imagePaths);s&&(t.push(""),t.push(s))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
|
|
194
|
-
`)}function oi(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function ri(o,e,n,t){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${c.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),c.feedbackSummary&&r.push(`Annotations: ${c.feedbackSummary}`))):c.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${c.question}"`)):(r.push(`### Round ${s} (assistant)`),c.responseText&&r.push(`Response: ${c.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of t)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
|
|
195
|
-
`)}function uc(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 mc(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&&!uc(e[n]))return!1;return!0}function ii(o){let e=o.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(mc):[]}catch{return[]}}function si(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let r=t;return(r.category==="token"||r.category==="component"||r.category==="element")&&typeof r.element=="string"&&typeof r.decision=="string"&&typeof r.reason=="string"}):[]}catch{return[]}}import{execFile as fc}from"child_process";import{readdir as hc,readFile as gc,stat as yc}from"fs/promises";import{homedir as on}from"os";import{join as Ye}from"path";var qn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:ai()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:ai()}],rn=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],sn={id:"",label:"Default",source:"cli"},vc=/^\s*-\s+"([^"]+)"/;function Ic(o){let e=[],n=!1;for(let t of o.split(`
|
|
196
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(vc);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Uo(i),source:"cli"})}return Wn([sn,...e])}function wc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,r)=>{let i=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(t=>{let r=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!r)return[];let i=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Uo(r),s=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function ai(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function bc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Wn(e.map(n=>({id:n,label:Uo(n),source:"cli"})))}function Uo(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let i=t[1]==="sonnet"?"Sonn":Pc(t[1]),s=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${s}${t[4]?" Fast":""}`}let r=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let i=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${i}`:r[3]==="codex"?`Codex ${i}`:r[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function ci(o="copilot"){let e=await Un(o,["help","config"]),n=Ic(e);return n.length>1?n:[sn]}async function di(o="codex"){let e=await Un(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Ye(on(),".codex");return pi(Ye(t,"models_cache.json"))}),n=wc(e);return n.length>0?Wn([...n,...rn]):rn}async function li(o="claude"){let e=Ye(on(),".claude"),n=[Ye(on(),".claude","stats-cache.json"),Ye(on(),".claude","settings.json"),Ye(on(),".claude.json"),Ye(e,"cache","changelog.md")],[t,r,i]=await Promise.all([Un(o,["--help"]).catch(()=>""),Un(o,["--version"]).catch(()=>""),xc(e).catch(()=>[])]),s=Rc([...n,...i]),c=await Promise.all(s.map(l=>pi(l).catch(()=>""))),d=bc([t,r,...c].join(`
|
|
197
|
-
`));return Wn([...qn,...d])}function Un(o,e,n=5e3){return new Promise((t,r)=>{fc(o,e,{encoding:"utf-8",timeout:n},(i,s)=>{if(i){r(i);return}t(s)})})}async function pi(o){return gc(o,"utf-8")}async function xc(o){let e=[Ye(o,"projects"),Ye(o,"telemetry")],n=[];for(let t of e)await ui(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function ui(o,e,n){if(n<0)return;let t;try{t=await hc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let i=Ye(o,r.name);if(r.isDirectory()){await ui(i,e,n-1);return}if(!(!r.isFile()||!Sc(r.name)))try{let s=await yc(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function Sc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Wn(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 Rc(o){return[...new Set(o)]}function Pc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Hn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let i of this.listeners)i(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let s=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:s,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};t.on("exit",s),t.on("error",s),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as Ge}from"crypto";import{createHash as kc}from"crypto";import{mkdir as Tc,open as jc,readFile as mi,readdir as Ec,rename as Ac,unlink as Mc}from"fs/promises";import{dirname as _c,join as Ot}from"path";function $e(o){return structuredClone(o)}function fi(o){return kc("sha256").update(JSON.stringify(o)).digest("hex")}async function an(o,e){await Tc(_c(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await jc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
198
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ac(n,o)}catch(r){throw await Mc(n).catch(()=>{}),r}}function Cc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function $c(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=$e(e):o.explanations.push($e(e))}function Gn(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")$c(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(i=>i.id===t.evidence.id)||(r.evidence.push($e(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,$e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(s=>s.id===t.relation.fromId),i=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!r||!i)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(s=>s.id===t.relation.id)||n.relations.push($e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Oc(o,e){let n=[],t=$e(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=t.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:$e(i)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=t.concrete.find(s=>s.id===r.concreteId);i&&n.unshift({op:"add_concrete",concrete:$e(i)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let i=r.op==="replace_explanation"?r.explanation.id:r.explanationId,s=t.explanations.find(c=>c.id===i);s&&n.unshift({op:"replace_explanation",explanation:$e(s)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=t.relations.find(s=>s.id===r.relationId);i&&n.unshift({op:"add_relation",relation:$e(i)})}t=Gn(t,[r])}return n}function hi(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Dt=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ot(e,".popmelt","imprint"),this.manifestPath=Ot(this.imprintDir,"manifest.json"),this.graphPath=Ot(this.imprintDir,"graph.json"),this.journalDir=Ot(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await mi(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async load(){let e=await this.readManifest(),t=(await Ec(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=Cc(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await mi(Ot(this.journalDir,t[c]),"utf8")),{hash:l,...x}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==fi(x))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Gn(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},i.push(d),s=d.hash}return{graph:r,transactions:i,recoveredTransactions:Math.max(0,i.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(k=>k.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,i=Oc(t.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:fi(s)},d=Gn(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await an(Ot(this.journalDir,l),c);let x={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await an(this.graphPath,d),await an(this.manifestPath,x),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(hi));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(x=>hi(x).some(k=>c.has(k)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await an(this.graphPath,e.graph),await an(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Dc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Jc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Nc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Vn(o){return new Set(Nc(o).split(" ").filter(e=>e.length>2&&!Jc.has(e)))}function Kn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function qo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function it(o,e,n){return{id:Ge(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function gi(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 yi(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Qn(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let P=String(r.reason);if(!Dc.has(P))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:P},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let i=r.summary,s=i?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:je(i?.title,120),detail:je(i?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(P=>typeof P=="string"&&!!P.trim()):[],l=[];for(let P of Array.isArray(r.mutations)?r.mutations:[]){if(!P||typeof P!="object")continue;let b=P;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let m=je(b.statement),p=je(b.rationale);if(!m||!p)continue;l.push({op:"add",clientId:je(b.clientId,100)||void 0,kind:b.kind,statement:m,rationale:p,scope:gi(b.scope),rootReason:je(b.rootReason,300)||void 0})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let m={op:"revise",explanationId:b.explanationId,statement:je(b.statement)||void 0,rationale:je(b.rationale)||void 0,scope:gi(b.scope),reopenGrounding:b.reopenGrounding===!0};(m.statement||m.rationale||m.scope||m.reopenGrounding)&&l.push(m)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let m=je(b.summary);m&&l.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:m})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type))){let m=je(b.rationale);if(!m)continue;l.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:m})}else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let m=je(b.reason);m&&l.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:m})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let m=je(b.modelPath,300);m&&l.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:m,rationale:je(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&l.push({op:"retire",explanationId:b.explanationId,reason:je(b.reason)})}let x=r.grounding,k=x&&typeof x.explanationId=="string"&&je(x.question)?{explanationId:x.explanationId,question:je(x.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:k},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Xn(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(i=>` - Concrete terminal: ${i.modelPath} = ${JSON.stringify(i.value)}`)].join(`
|
|
199
|
-
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(t=>`- ${t.fromId} --${t.type}--> ${t.toId}: ${t.rationale}`)]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Topology assessment is mandatory for every add mutation. Connect the new clientId with relation or supersede mutations whenever it overlaps, specializes, operationalizes, supports, contradicts, or excepts another surfaced or newly-added explanation. If it is genuinely a new root with no meaningful relative, include rootReason on the add mutation explaining why. Unmapped additions without rootReason are rejected.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
|
|
200
|
-
`)}var Jt=class{constructor(e,n){this.noopCounts=new Map;this.store=new Dt(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Vn(e.text??""),t=Vn((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:i}=await this.store.load(),s=i.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let p=Vn([m.statement,m.rationale].join(" ")),y=Vn(m.scope.values.join(" ")),h=Kn(p,n),f=Kn(y,n),u=Kn(y,t),E=Kn(p,t),O=h+f*.2+u*.25+E*.1+(m.state==="grounded"?.08:0)+(r.has(m.id)?1:0),R=r.has(m.id)||(n.size?h>=.12||f>=.5:u>=.2||E>=.2);return{item:m,score:O,relevant:R}}).filter(m=>m.relevant&&m.score>=.18).sort((m,p)=>p.score-m.score||p.item.updatedAt.localeCompare(m.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:m})=>m),l=new Set(d.map(m=>m.id)),x=new Set(i.relations.flatMap(m=>l.has(m.fromId)?[m.toId]:l.has(m.toId)?[m.fromId]:[])),k=new Set(i.explanations.flatMap(m=>x.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),P=i.explanations.filter(m=>k.has(m.id)&&!l.has(m.id)).sort((m,p)=>p.updatedAt.localeCompare(m.updatedAt)).slice(0,4),b=[...d,...P];for(let m of P)l.add(m.id);return{explanations:b.map(m=>{let p=new Set(i.relations.filter(y=>y.fromId===m.id&&y.type==="instantiates").map(y=>y.toId));return{id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state,concrete:i.concrete.filter(y=>p.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||P.length<k.size,...r.size?{pendingGroundingExplanationIds:[...r]}:{},relations:i.relations.filter(m=>l.has(m.fromId)&&l.has(m.toId)&&m.type!=="instantiates").map(m=>({id:m.id,type:m.type,fromId:m.fromId,toId:m.toId,rationale:m.rationale}))}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),i=new Map(r.graph.explanations.map(I=>[I.id,I])),s=new Map,c=new Map,d=[],l=new Set,x=new Set(n.pendingGroundingExplanationIds??[]),k=new Set(e.mutations.flatMap(I=>I.op==="add"&&I.clientId?[I.clientId]:[])),P=I=>i.has(I)||k.has(I),b=new Set;for(let I of e.mutations)I.op==="relation"&&I.fromId!==I.toId&&P(I.fromId)&&P(I.toId)?(b.add(I.fromId),b.add(I.toId)):I.op==="supersede"&&I.explanationId!==I.replacementId&&P(I.explanationId)&&P(I.replacementId)?(b.add(I.explanationId),b.add(I.replacementId)):I.op==="bind_concrete"&&P(I.explanationId)&&yi(n.concreteModel,I.modelPath).found&&b.add(I.explanationId);let m=r.graph.explanations.length===0;for(let I of e.mutations){if(I.op!=="add")continue;let w=!!(I.clientId&&b.has(I.clientId)),M=!!I.rootReason?.trim()||m;if(!w&&!M)continue;m&&(m=!1);let L=Ge();I.clientId&&s.set(I.clientId,L);let G=I.clientId?e.appliedExplanationIds.includes(I.clientId):!1,U={id:L,kind:I.kind,statement:I.statement,rationale:I.rationale,scope:qo(I.scope),state:G?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[it(n,"supports",e.summary.detail)]};i.set(L,U),l.add(L),d.push({op:"add_explanation",explanation:U})}let p=I=>s.get(I)??I;for(let I of e.mutations){if(I.op!=="revise")continue;let w=p(I.explanationId),M=i.get(w);if(M?.state!=="grounded")continue;let L=Ge(),G={id:L,kind:M.kind,statement:I.statement??M.statement,rationale:I.rationale??M.rationale,scope:I.scope?qo(I.scope):M.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[it(n,"supports",e.summary.detail)]};i.set(L,G),c.set(w,L),l.add(L),d.push({op:"add_explanation",explanation:G}),d.push({op:"add_relation",relation:{id:Ge(),type:"refines",fromId:L,toId:w,rationale:I.rationale??e.summary.detail,createdAt:t}})}let y=I=>{let w=p(I);return c.get(w)??w};for(let I of e.mutations){if(I.op==="add")continue;if(I.op==="bind_concrete"){let M=y(I.explanationId);if(!i.has(M))continue;let L=yi(n.concreteModel,I.modelPath);if(!L.found)continue;let G=r.graph.concrete.find(U=>U.modelPath===I.modelPath&&JSON.stringify(U.value)===JSON.stringify(L.value));G||(G={id:Ge(),modelPath:I.modelPath,value:structuredClone(L.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:G})),d.push({op:"add_relation",relation:{id:Ge(),type:"instantiates",fromId:M,toId:G.id,rationale:I.rationale,createdAt:t}}),l.add(M);continue}if(I.op==="relation"){let M=y(I.fromId),L=y(I.toId);if(!i.has(M)||!i.has(L)||M===L)continue;d.push({op:"add_relation",relation:{id:Ge(),type:I.type,fromId:M,toId:L,rationale:I.rationale,createdAt:t}}),l.add(M),l.add(L);continue}if(I.op==="supersede"){let M=y(I.explanationId),L=y(I.replacementId);if(!i.has(M)||!i.has(L)||M===L)continue;d.push({op:"add_evidence",explanationId:M,evidence:it(n,"challenges",I.reason)}),d.push({op:"revise_explanation",explanationId:M,patch:{state:"challenged",supersededBy:L},updatedAt:t}),d.push({op:"add_relation",relation:{id:Ge(),type:"contradicts",fromId:L,toId:M,rationale:I.reason,createdAt:t}}),l.add(M),l.add(L);continue}let w=y(I.explanationId);if(i.has(w))if(l.add(w),I.op==="revise"){if(c.has(p(I.explanationId)))continue;let M={...I.statement?{statement:I.statement}:{},...I.rationale?{rationale:I.rationale}:{},...I.scope?{scope:qo(I.scope)}:{},...I.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:w,patch:M,updatedAt:t})}else I.op==="evidence"?(d.push({op:"add_evidence",explanationId:w,evidence:it(n,I.stance,I.summary)}),I.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:w,patch:{state:"challenged"},updatedAt:t})):I.op==="retire"&&(d.push({op:"add_evidence",explanationId:w,evidence:it(n,"challenges",I.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:w,patch:{state:"retired"},updatedAt:t}))}for(let I of e.appliedExplanationIds){let w=y(I),M=i.get(w);!M||M.state==="grounded"||M.state==="retired"||x.has(w)&&!l.has(w)||(l.has(w)||(l.add(w),d.push({op:"add_evidence",explanationId:w,evidence:{...it(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),M.state==="emerging"&&d.push({op:"revise_explanation",explanationId:w,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let h=Ge(),f=await this.store.commit({transactionId:h,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),u=new Map(f.graph.explanations.map(I=>[I.id,I])),E=[...l].flatMap(I=>{let w=u.get(I);if(!w)return[];let M=!r.graph.explanations.some(G=>G.id===I),L=w.state==="challenged"||w.state==="retired";return[{explanationId:I,action:M?"added":L?"challenged":"revised",statement:w.statement,state:w.state}]}),O=e.grounding?y(e.grounding.explanationId):void 0,R=O?u.get(O):void 0,C=R?.state==="testing"&&!x.has(R.id)?{explanationId:R.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:h,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:E,...C?{grounding:C}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let x of l)await this.store.undo(x,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,Ge());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...it(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${i.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...it(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${i.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(x=>x.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:i.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${i.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...it(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${i.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:Ge(),committedAt:n,source:s,summary:d,mutations:c})}};function cn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Yn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Wo(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 vi(o){let e=Wo(Yn(o.origin));if(e)return e;let n=Wo(Yn(o.referer));if(n)return n;let t=Yn(o["x-forwarded-host"]);if(!t)return null;let r=Yn(o["x-forwarded-proto"])==="https"?"https":"http";return Wo(`${r}://${t}`)}function Ii(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),i=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Zn}from"crypto";import{mkdir as dn,readFile as St,unlink as Fc,writeFile as Bt}from"fs/promises";import{dirname as eo,extname as zc,join as Oe}from"path";var Bc={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 Lc(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 wi(o,e){let n=e??Lc(o);return{kind:n,...Bc[n]}}function Nt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function bi(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Uc={version:1,threads:{}},xi=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],ln={version:2,updatedAt:0,files:{}};function qc(o){return JSON.stringify(o,null,2)}function Wc(o){return Object.fromEntries(xi.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Hc(o){let e={...o};for(let n of xi)delete e[n];return e}function Lt(o){let e=o;if(o.error){let n=wi(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=Nt(e.result,!1),t=Nt(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var to=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Oe(e,".popmelt");this.legacyFilePath=Oe(n,"threads.json"),this.threadsDir=Oe(n,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(n,"artifacts","thread-messages"),this.mediaDir=Oe(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await St(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let i=await this.readThread(Oe(this.threadsDir,r));i&&(n[t]=i)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await St(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Lt)}]))},this.index={...ln,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Uc,threads:{}},this.index={...ln,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(s=>t.has(s)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Lt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,Lt(n)):r.messages.push(Lt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=Lt(c);Object.assign(c,d),delete c.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of n)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,i)=>i.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let s=r.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(y=>y.role==="assistant"),d=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let h=y.imprintSummary?.grounding;if(h?.question&&!y.imprintSummary?.resolvedAction)return h.question},l=r.messages.findLastIndex(y=>!!d(y)),x=r.messages.findLastIndex(y=>y.role==="human"),k=l>x?d(r.messages[l]):void 0,P=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,x)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),m=c.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=c.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:m,hasError:p,lastMessageRole:P,pendingQuestion:k,acknowledgedJobIds:b,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await St(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...i})=>{let s={};if(r?.path)try{let c=await St(Oe(eo(this.legacyFilePath),r.path),"utf8");Zn("sha256").update(c).digest("hex")===r.sha256&&(s=JSON.parse(c))}catch{}return Lt({...i,...s})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Wc(e),t=Hc(e);if(Object.keys(n).length===0)return t;let r=qc(n),i=Zn("sha256").update(r).digest("hex"),s=Oe("artifacts","thread-messages",`${i}.json`);await dn(this.artifactsDir,{recursive:!0});try{await St(Oe(eo(this.legacyFilePath),s),"utf8")}catch{await Bt(Oe(eo(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(eo(t)===this.mediaDir)return t;try{let r=await St(t),i=Zn("sha256").update(r).digest("hex"),s=Oe(this.mediaDir,`${i}${zc(t)||".bin"}`);await dn(this.mediaDir,{recursive:!0});try{await St(s)}catch{await Bt(s,r)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await dn(this.threadsDir,{recursive:!0});let n=this.index??{...ln,files:{}},t=n.files[e.id]??`${Zn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await Bt(Oe(this.threadsDir,t),JSON.stringify(i,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Bt(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await dn(this.threadsDir,{recursive:!0}),this.index=this.index??{...ln,files:{}},await Bt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...ln,files:{}},t=n.files[e];t&&await Fc(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await dn(this.threadsDir,{recursive:!0}),await Bt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Gc,open as Vc,readFile as Kc,rename as Qc,unlink as Xc}from"fs/promises";import{dirname as Yc,join as Zc}from"path";var Si={schemaVersion:1,theme:"auto",updatedAt:null};function Ri(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function ed(o,e){await Gc(Yc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Vc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
201
|
-
`,"utf8"),await t.sync()}finally{await t.close()}await Qc(n,o)}catch(t){throw await Xc(n).catch(()=>{}),t}}var no=class{constructor(e){this.path=Zc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Kc(this.path,"utf8")),n=Ri(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Si}}}catch{return{exists:!1,preferences:{...Si}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await ed(this.path,n),n}};function Pi(o){return Ri(o)!==null}function oo(o){return nd(o).slice(0,12)}var td=[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 nd(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):od(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let P=7;P>=0;P--)e.push(n/Math.pow(2,P*8)&255);let t=1779033703,r=3144134277,i=1013904242,s=2773480762,c=1359893119,d=2600822924,l=528734635,x=1541459225,k=new Array(64);for(let P=0;P<e.length;P+=64){for(let O=0;O<16;O++){let R=P+O*4;k[O]=(e[R]<<24|e[R+1]<<16|e[R+2]<<8|e[R+3])>>>0}for(let O=16;O<64;O++){let R=Ze(k[O-15],7)^Ze(k[O-15],18)^k[O-15]>>>3,C=Ze(k[O-2],17)^Ze(k[O-2],19)^k[O-2]>>>10;k[O]=k[O-16]+R+k[O-7]+C>>>0}let b=t,m=r,p=i,y=s,h=c,f=d,u=l,E=x;for(let O=0;O<64;O++){let R=Ze(h,6)^Ze(h,11)^Ze(h,25),C=h&f^~h&u,I=E+R+C+td[O]+k[O]>>>0,w=Ze(b,2)^Ze(b,13)^Ze(b,22),M=b&m^b&p^m&p,L=w+M>>>0;E=u,u=f,f=h,h=y+I>>>0,y=p,p=m,m=b,b=I+L>>>0}t=t+b>>>0,r=r+m>>>0,i=i+p>>>0,s=s+y>>>0,c=c+h>>>0,d=d+f>>>0,l=l+u>>>0,x=x+E>>>0}return[t,r,i,s,c,d,l,x].map(P=>P.toString(16).padStart(8,"0")).join("")}function Ze(o,e){return o>>>e|o<<32-e}function od(o){let e=[];for(let n=0;n<o.length;n++){let t=o.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var ki={name:"@popmelt.com/core",version:"0.8.7",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var st=ki.version;var fd=1111,hd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],gd=1800*1e3,yd=3600*1e3,Ei=45e3,vd=5e3,Id=1e4;function Ai(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
202
|
-
`)}function un(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function 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 Ji(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 bd(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let i=n[n.length-1];i&&i.kind==="text"?i.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",i=t.file??void 0,s=t.content??void 0,c=i?i.split("/").pop()??i:void 0,d;switch(r){case"Read":d=c?`Reading ${c}`:"Reading file";break;case"Edit":d=c?`Editing ${c}`:"Editing file";break;case"Write":d=c?`Writing ${c}`:"Writing file";break;case"Bash":d=s?s.split(`
|
|
203
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let l=i??s??void 0,x=i?Go(i)?i:Di(e,i):void 0,k=n[n.length-1];k&&k.kind==="tool_group"&&k.tool===r?k.items.push({label:d,detail:l,...x?{filePath:x}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...x?{filePath:x}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function xd(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let n=[];return o.success?n.push("Model suggestion ready."):n.push("Model projection failed."),o.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(n.push(""),n.push(`Error: ${o.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
|
|
204
|
-
`)}function Sd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Mi(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),t=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),i=[...e,...t,...n,...r].map(s=>Sd(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Rd(o,e){let n=o.headers.origin;Ji(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function _(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function ze(o){let e=[],n=0;for await(let r of o){let i=typeof r=="string"?Buffer.from(r):r;if(n+=i.length,n>16384)throw new Error("Request body too large");e.push(i)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Pd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function kd(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,r,i]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function io(o,e){try{o.res.write(`event: ${e.type}
|
|
205
|
-
data: ${JSON.stringify(e)}
|
|
206
|
-
|
|
207
|
-
`)}catch{}}function Rt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function ao(o){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function Td(o,e){return new Promise((n,t)=>{let r=s=>{o.removeListener("listening",i),t(s)},i=()=>{o.removeListener("error",r),n()};o.once("error",r),o.once("listening",i),o.listen(e,"127.0.0.1")})}function _i(o){try{let e=so("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=so("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=so("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Oi("sha256").update(`${e}
|
|
208
|
-
${t}
|
|
209
|
-
${r}`).digest("hex").slice(0,16)}catch{return}}function jd(o,e){let n=o;for(let t of e.split(".").filter(Boolean)){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[t]}return n}async function Ci(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let i of[...t].sort((s,c)=>`${s.kind}:${s.value}`.localeCompare(`${c.kind}:${c.value}`)))if(i.kind==="model_path")r.push([i.kind,i.value,jd(n,i.value)]);else if(i.kind==="source_file"){let s=Di(o,i.value),d=s===o||s.startsWith(`${o}/`)?await Ho(s,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([i.kind,i.value,d])}else r.push([i.kind,i.value]);return Oi("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ni(o={}){let e=new Date().toISOString(),n=o.port??fd,t=o.projectRoot??process.cwd(),r=await ad(t).catch(()=>t),i=oo(r),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ae(pd(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,x=[...o.allowedTools??hd],k=o.claudePath??"claude",P=o.copilotPath??"copilot",b=o.provider??"claude",m=o.timeoutMs,p=o.restartMode??"embedded",y=n,h={},f={claude:k,codex:"codex",copilot:P};for(let[a,g]of Object.entries(f))try{let j=g.includes("/")?g:so("which",[g],{encoding:"utf-8"}).trim();h[a]={available:!0,path:j}}catch{h[a]={available:!1,path:null}}function u(a,g){return new Promise(j=>{let v=Ti(g,["--version"],{stdio:["ignore","ignore","ignore"]}),T=!1,S=J=>{T||(T=!0,j(J))},A=setTimeout(()=>{v.kill("SIGTERM"),S(!0)},5e3);v.on("error",()=>{clearTimeout(A),S(!1)}),v.on("close",J=>{clearTimeout(A),S(J===0)})})}await Promise.all([(async()=>{h.claude&&(h.claude.models=h.claude.available&&h.claude.path?await li(h.claude.path).catch(()=>qn):qn)})(),(async()=>{h.codex&&(h.codex.models=h.codex.available&&h.codex.path?await di(h.codex.path).catch(()=>rn):rn)})(),(async()=>{h.copilot&&(h.copilot.models=h.copilot.available&&h.copilot.path?await ci(h.copilot.path).catch(()=>[sn]):[sn])})()]);let[E,O,R]=await Promise.all([Ro(r),Po(r),ko(r,h.copilot?.path??P)]),C=await Tr(r);h.claude&&(h.claude.mcp=E),h.codex&&(h.codex.mcp=O),h.copilot&&(h.copilot.mcp=R),E.found&&E.name&&x.push(`mcp__${E.name}__*`),await id(c,{recursive:!0}),$i(c).catch(()=>{});let I=new Hn(1),w=new kn,M=new En(Ei),L=null,G=0,U=!1,ne=()=>{G+=1,U=!1,L&&clearTimeout(L),L=null},oe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ye=()=>{if(p!=="detached"||M.size>0||U)return;U=!0;let a=++G,g=Date.now()+Id,j=()=>{if(a!==G)return;if(M.size>0){ne();return}if(!(I.isRunning||I.depth>0||w.isRunning||w.depth>0)||Date.now()>=g){U=!1,L=setTimeout(oe,50),L.unref?.();return}L=setTimeout(j,250),L.unref?.()};j()},Y=new Set,V=new to(r),q=new Bn(r),ge=new Jt(r,i),$=new no(r),Z=new In(r),ue=new xn(r),se=new Pn(r,{claudePath:k,provider:b,timeoutMs:m,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let g of Y)io(g,a)}});q.beginAutomaticInitialization({writerVersion:st}).then(async a=>{a.state==="ready"?(await q.migrateLegacyEvals(),await q.migrateImprintSnapshot(),await q.syncImprintGraph(),await se.applyCanonicalEntries(await q.getCanonicalModelEntries()),b!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await Ee({provider:b,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let De=20,Je=300*1e3,Re=[];function Ue(){let a=Date.now()-Je;for(;Re.length>0&&(Re[0].completedAt<a||Re.length>De);)Re.shift()}let Ve=new Map;async function et(a){if(a.status!=="applied")return[];let g={version:1,updatedAt:Date.now(),cases:await q.getJournalEvalCases()},j=hr(a,g);if(j.length===0)return[];let v=await q.getEvalDependenciesForDecisions(a.decisionIds),T=a.threadId?await V.getThread(a.threadId):null,S=[...new Set((T?.messages??[]).flatMap(B=>(B.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])).map(B=>Go(B)?ji(r,B):B))].map(B=>({kind:"source_file",value:B})),A=j.map(B=>{let z=[...new Map([...B.dependencies??[],...v,...S].map(H=>[`${H.kind}:${H.value}:${"subjectId"in H?H.subjectId??"":""}`,H])).values()],F=z.filter(H=>H.kind==="route"),D=z.flatMap(H=>H.kind==="model_path"&&H.value.startsWith("components.")?[H.value.slice(11).split(".")[0]]:[]),N=[...new Set(z.flatMap(H=>"subjectId"in H&&H.subjectId?[H.subjectId]:[]))],Q=F.length>0?F.map((H,ie)=>({id:`route-${ie+1}`,...H.value.includes("*")?{routePattern:H.value}:{route:H.value},components:D.map(ce=>({name:ce})),subjectIds:N})):[{id:D.length>0?`component-${D[0]}`:"current-page",components:D.map(H=>({name:H})),subjectIds:N}];return{...B,dependencies:z,scenarios:B.scenarios?.length?B.scenarios:Q}}),J=new Set(g.cases.map(B=>B.id));return await q.syncEvalSpecs(A),await se.attachGeneratedEvals(a.id,A.map(B=>({evalId:B.id,title:B.title,action:J.has(B.id)&&(a.evalProjections?.some(z=>z.evalId===B.id)||!a.generatedEvalIds?.includes(B.id))?"extended":"created"}))),A.map(B=>B.id)}async function at(a){let g=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",j=go(a.claim)||"The product satisfies the declared model constraint.",v={id:`eval-decision-${a.decisionId}`,title:g.charAt(0).toUpperCase()+g.slice(1),status:"pending",category:a.modelPath.startsWith("components.")?"component":a.modelPath.startsWith("tokens.")?"visual":"workflow",prompt:"Verify this product expectation across the declared scenarios.",assertions:[j],rationale:`Protects the ${a.modelPath} constraint from implementation drift.`,sourceDecisionIds:[a.decisionId],sourceThreadIds:[],dependencies:[{kind:"model_path",value:a.modelPath}],scenarios:[{id:a.modelPath.startsWith("components.")?`component-${g.replace(/\s+/g,"-")}`:"current-page",components:a.modelPath.startsWith("components.")?[{name:a.modelPath.slice(11).split(".")[0]}]:void 0}]};return await q.syncEvalSpecs([v]),v.id}let ft=null,Ft;I.addListener((a,g,j)=>{for(let v of Y)(!j||!v.sourceId||v.sourceId===j)&&io(v,a)}),w.addListener((a,g,j)=>{for(let v of Y)(!j||!v.sourceId||v.sourceId===j)&&io(v,a)}),w.setProcessor(async a=>{let g=a.provider??b;try{let j=await se.run({provider:g,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let v=await se.loadRuns(),T=j.runId?v.runs.find(A=>A.id===j.runId):void 0;if(j.success&&j.proposalId){let A=await se.findModelProposal(j.proposalId),J=await se.loadModel(),B=A?xr(A,J):null;if(A&&B){let z=A.decisionIds.map(D=>({decisionId:D,status:"projected"}));await q.applyModelProjection({runId:A.runId??A.id,presentationJobId:A.presentationJobId,decisionIds:A.decisionIds,changes:B.map(D=>({path:D.path,value:D.value,decisionIds:D.decisionIds})),coverage:z});let F=await se.applySelectedModelProposal(A.id,B.map(D=>({path:D.path,value:D.value})),B.map(D=>({group:D.path[0]==="rules"||D.path[0]==="components"||D.path[0]==="tokens"?D.path[0]:"model",label:D.label??D.id,detail:D.rationale,path:D.path,value:D.value})),"automatic");F&&await et(F)}}let S=xd(j,T);if(a.threadId&&(await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:g})),j.success)a.status="done",a.result=S,w.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue();else{if(a.status="error",a.error=j.error??"Projection failed",a.threadId){let A=`Model projection failed.
|
|
210
|
-
|
|
211
|
-
${a.error}`;await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:A,error:a.error,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:A,error:a.error,model:a.model,provider:g})}w.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:g,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}catch(j){if(a.status==="cancelled")return;if(a.status="error",a.error=j instanceof Error?j.message:String(j),a.threadId){let v=`Model projection failed.
|
|
212
|
-
|
|
213
|
-
${a.error}`;await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:g})}w.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:g,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}),I.setProcessor(async a=>{let g=a,j=g._replyPrompt,v=g._replyText,T=g._replyImagePaths,S=a.provider??b,A=!!(a.surfacedProposalIds?.length&&j),J=!!g._evalRemediation,B=!A&&!["run_eval","synthesize_evals","synthesize","project_model"].includes(a.kind??"");a.threadId&&v!==void 0&&await V.updateMessage(a.threadId,a.id,{queued:!1});let z;if(a.threadId){let de=await V.getThread(a.threadId);if(de){for(let pe=de.messages.length-1;pe>=0;pe--)if(de.messages[pe].sessionId){z=de.messages[pe].sessionId;break}}}(A||J)&&(z=void 0);let F;if(z&&j){if(F=v??j,T&&T.length>0){F+=`
|
|
214
|
-
|
|
215
|
-
The developer attached reference images with their reply:`;for(let de of T)F+=`
|
|
216
|
-
Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?F+=`
|
|
217
|
-
|
|
218
|
-
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+=`
|
|
219
|
-
|
|
220
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(z)F=nn(a.feedback,a.imagePaths)+`
|
|
221
|
-
|
|
222
|
-
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
223
|
-
|
|
224
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
|
|
225
|
-
|
|
226
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!j&&a.threadId?await V.getThreadHistory(a.threadId):void 0,pe=j?null:await se.loadModel();F=j??ni(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:S,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}F+=Xr(a.memoryReview),B&&(F+=Xn(a.imprintContext)),F+=`
|
|
227
|
-
|
|
228
|
-
${ti}`;let D=kd(a.color,`[\u22B9 ${y}:${a.id}]`),N=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${D} Reviewing ${N} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${z?` (resuming: ${z.slice(0,8)})`:""}`);let Q=new zn(a.id),H=(de,pe)=>{if(de.type==="delta"&&"text"in de){let _e=Q.push(de.text);_e.visibleText&&(I.accumulateText(pe,"response",_e.visibleText),I.broadcast({...de,text:_e.visibleText},pe,a.sourceId));for(let Ce of _e.orientations)I.broadcast({type:"orientation",jobId:pe,orientation:Ce},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&I.accumulateText(pe,"thinking",de.text);I.broadcast(de,pe,a.sourceId)},{process:ie,result:ce}=S==="codex"?vn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:z,model:a.model,sandboxMode:A?"read-only":void 0,configOverrides:hn(a.agentSettings),onEvent:H}):S==="copilot"?ur(a.id,{prompt:F,projectRoot:r,resumeSessionId:z,model:a.model,timeoutMs:m,copilotPath:h.copilot?.path??P,onEvent:H}):gn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:A?["Read"]:x,claudePath:k,resumeSessionId:z,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:m,onEvent:H});I.setActiveProcess(a.id,ie);let te=await ce,be=Q.finalize(te.text),Ie=be.visibleText,ve=B?Qn(Ie):{visibleText:Ie,draft:void 0,error:void 0},K=ve.visibleText;for(let de of be.orientations)I.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=K,te.success){console.log(`${D} Iteration complete`),te.fileEdits&&te.fileEdits.length>0&&console.log(`${D} Captured ${te.fileEdits.length} file edit(s): ${te.fileEdits.map(W=>`${W.tool} ${W.file_path}`).join(", ")}`),te.editEvents&&te.editEvents.length>0&&console.log(`${D} Captured ${te.editEvents.length} edit event(s): ${te.editEvents.map(W=>`${W.operation} ${W.filePath}`).join(", ")}`),a.status="done";let de=oi(Ie),pe=ii(Ie);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let W=new Set(a.annotationIds);pe.every(Ke=>W.has(Ke.annotationId))||(pe=pe.map((Ke,Qe)=>({...Ke,annotationId:a.annotationIds[Qe%a.annotationIds.length]})))}let _e=te.fileEdits&&te.fileEdits.length>0?te.fileEdits.map(W=>`${W.tool} ${W.file_path.split("/").pop()}`):te.toolsUsed,Ce=I.getBufferedEvents(a.id),nt=Ce?bd(Ce.events,r):void 0,Pe,ee=Zr(Ie),he=Yr(Ie);if(he)if(!(a.memoryReview?.packets.some(re=>re.proposalId===he.proposalId)||a.surfacedProposalIds?.includes(he.proposalId)))Pe={status:"rejected",action:he.action,proposalId:he.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Pe=await q.commitConversationalReview(he)}catch(re){Pe={status:"rejected",action:he.action,proposalId:he.proposalId,message:re instanceof Error?re.message:String(re)}}let ke=[...(te.fileEdits??[]).map(W=>W.file_path),...(te.editEvents??[]).flatMap(W=>W.filePath?[W.filePath]:[])],xe,yt=a.imprintContext?.pendingGroundingExplanationIds??[];if(ve.draft?.decision==="none"&&ge.recordNoop(ve.draft.reason),a.threadId&&ve.draft?.decision==="mutate"&&!he&&!ee)try{xe=await ge.capture(ve.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:yt}),xe&&await q.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(W=>console.warn(`${D} Canonical Imprint evidence linkage failed:`,W))}catch(W){console.warn(`${D} Continuous imprint update failed; the thread result remains available:`,W instanceof Error?W.message:String(W))}else ve.error&&console.warn(`${D} Ignored invalid imprint block: ${ve.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let W=await V.getThread(a.threadId),re=new Set(xe.changes.map(Qe=>Qe.explanationId)),Ke=W?wd(W.messages,re):void 0;if(Ke?.imprintSummary){let Qe=Ke.imprintSummary;await V.updateAssistantMessage(a.threadId,Ke.jobId,{imprintSummary:{...Qe,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Qe.additionalObservationCount??0)+1,coalescedTransactionIds:[...Qe.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let qt=bi({question:de,resolutions:pe,changedFiles:ke,decisionRequired:!!ee,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),X=nt?.flatMap(W=>W.kind==="orientation"?[W.orientation]:[])??[];if(a.threadId){let W=A?ee?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":K;await V.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:W,resolutions:!A&&pe.length>0?pe:void 0,question:A?void 0:de??void 0,sessionId:te.sessionId,toolsUsed:A?void 0:_e,editEvents:!A&&te.editEvents&&te.editEvents.length>0?te.editEvents:void 0,segments:!A&&nt&&nt.length>0?nt:void 0,turn:{phase:"complete",orientation:X,result:qt},result:qt,memoryReviewCard:ee??void 0,memoryReceipt:Pe,imprintSummary:xe,model:a.model,provider:S})}if(a.threadId&&!he&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let W=a.feedback.annotations.flatMap(re=>re.linkedSelector?[re.pathname?`${re.pathname}:${re.linkedSelector}`:re.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(Ln(a.feedback)||"[request unavailable]"),responseSummary:de??K,outcome:de?"question_asked":pe.some(re=>re.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:te.sessionId},subjectHints:W,filePaths:[...(te.fileEdits??[]).map(re=>re.file_path),...(te.editEvents??[]).flatMap(re=>re.filePath?[re.filePath]:[])].map(re=>Go(re)?ji(r,re):re),resolutions:pe.map(re=>({status:re.status,summary:re.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(re=>re.id)})}catch(re){console.warn(`${D} Canonical memory capture failed; iteration remains available in legacy history:`,re instanceof Error?re.message:String(re))}}if(Pe?.status==="committed"&&Pe.decisionId&&S!=="copilot"&&await Ee({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Pe.decisionId}`}),a.kind==="run_eval"&&K&&a.evalId&&a.evalRunId){let W=await q.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(W&&re){let Ke=fr(Ie,W.assertions),Qe=Date.now(),es={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Qe,durationMs:Qe-a.createdAt,scope:re,provider:S,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:_i(r),rawResponse:Ie,scopeFingerprint:a._evalScopeFingerprint,...Ke};await q.recordEvalVerification(W,es),console.log(`${D} Eval run: ${W.title} \u2192 ${Ke.status}`)}}de&&(console.log(`${D} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${Y.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),I.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:de,annotationIds:a.annotationIds},a.id,a.sourceId));let me=si(Ie);me.length>0&&(console.log(`${D} Novel pattern(s): ${me.map(W=>`${W.category}/${W.element}`).join(", ")}`),I.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),I.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:K,threadId:a.threadId,annotationIds:a.annotationIds,result:qt},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${D} Error: ${te.error}`),a.status="error",a.error=te.error,a.threadId&&await V.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:te.error||"Unknown error",model:a.model,provider:S}),I.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:te.error||"Unknown error",provider:S,model:a.model,recoverable:te.recoverableError,code:te.errorCode},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:te.error,threadId:a.threadId,annotationIds:a.annotationIds});Ue()});let zt=ld(async(a,g)=>{if(Rd(a,g),a.method==="OPTIONS"){g.writeHead(204),g.end();return}let j=a.url||"/",v=j.split("?")[0],T=new URL(j,`http://127.0.0.1:${y}`),S=T.pathname,A=Pd(a,T);if(A&&A!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:A,projectName:ro(r)});return}if(a.headers.origin){if(!Ji(a.headers.origin)){_(g,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(A!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:A,projectName:ro(r)});return}}try{if(a.method==="POST"&&S==="/send")await Me(a,g);else if(a.method==="GET"&&S==="/events")dt(a,g);else if(a.method==="GET"&&S==="/status")await lt(a,g,A);else if(a.method==="GET"&&S==="/ui-preferences")await co(g);else if(a.method==="PATCH"&&S==="/ui-preferences")await lo(a,g);else if(a.method==="PATCH"&&S==="/config")await ht(a,g);else if(a.method==="POST"&&S==="/leases"){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}try{let J=await ze(a),B=typeof J.leaseId=="string"?J.leaseId.trim():"",z=typeof J.ownerPid=="number"&&Number.isInteger(J.ownerPid)&&J.ownerPid>0?J.ownerPid:void 0;if(!B||B.length>128){_(g,400,{error:"A valid leaseId is required."});return}ne();let F=M.acquire(B,z);_(g,201,{ok:!0,lease:F,ttlMs:Ei})}catch{_(g,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(S.slice(8))}catch{_(g,400,{error:"Invalid lease id."});return}if(!J){_(g,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let B=M.heartbeat(J);if(!B){_(g,404,{error:"Lease not found."});return}_(g,200,{ok:!0,lease:B})}else{let B=M.release(J);_(g,B.found?200:404,{ok:B.found}),B.becameEmpty&&ye()}}else if(a.method==="POST"&&S==="/shutdown"){if(p!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}_(g,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&S==="/restart"){if(p!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}_(g,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of Y)try{J.res.end()}catch{}zt.close(()=>{Ti(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&S==="/capabilities")_(g,200,{providers:h});else if(S.startsWith("/imprint/"))await ct(a,g,S);else if(S.startsWith("/memory/"))await we(a,g,S);else if(a.method==="POST"&&S==="/mcp/install")await zi(a,g);else if(a.method==="POST"&&S==="/reply")await tt(a,g);else if(a.method==="POST"&&S==="/cancel")Ut(a,g);else if(a.method==="POST"&&S==="/materialize")_(g,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(g,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let J=await se.loadRuns();_(g,200,J)}else if(a.method==="GET"&&S==="/projection/proposals"){let J=await se.loadModelProposals();_(g,200,J)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let J=S.slice(22,-15);await pt(J,a,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let J=S.slice(22,-6);await Ne(J,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let J=S.slice(22,-8);await Pt(J,a,g)}else if(S.startsWith("/model/proposals/"))_(g,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await Ui(a,g);else if(a.method==="DELETE"&&S==="/model/component")await qi(a,g);else if(a.method==="PATCH"&&S==="/model/token")await Wi(a,g);else if(a.method==="DELETE"&&S==="/model/token")await Hi(a,g);else if(a.method==="POST"&&S==="/model/consolidate")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/evals/synthesize")_(g,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&S==="/evals"){let J=await se.loadModel(),B=await Promise.all((await q.getJournalEvalCases()).map(async D=>{let N=await Ci(r,D,J);return D.verificationState==="passing"&&(!D.verifiedScopeFingerprint||!N||D.verifiedScopeFingerprint!==N)?{...D,verificationState:"stale"}:D})),z=_i(r),F=(await q.getJournalEvalRuns()).filter(D=>!D.codeFingerprint||D.codeFingerprint===z);_(g,200,{version:1,updatedAt:Date.now(),cases:B,runs:F,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&S.startsWith("/evals/")&&S.endsWith("/run")){let J=S.slice(7,-4);await po(J,a,g)}else if(a.method==="PATCH"&&S.startsWith("/evals/"))await mn(S.slice(7),a,g);else if(a.method==="GET"&&S==="/model"){let J=await se.loadModel();_(g,200,{model:J})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let J=S.slice(6,S.length-7),B=parseInt(T.searchParams.get("afterSeq")??"-1",10),z=I.getBufferedEvents(J,isNaN(B)?-1:B);z?_(g,200,z):_(g,404,{error:"Unknown job"})}else if(a.method==="GET"&&v.startsWith("/files/"))await Qi(v.slice(7),g);else if(a.method==="GET"&&S==="/threads/recent"){let J=Math.min(Math.max(parseInt(T.searchParams.get("limit")??"5",10)||5,1),20),B=await V.listRecent(J);_(g,200,B)}else if(a.method==="GET"&&S.startsWith("/decision/")){let J=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(J))_(g,400,{error:"Invalid decision id"});else{let B=await V.getThread(J),z=[...B?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(B&&z?.annotationSnapshot){let F=[...B.messages].reverse().find(D=>D.resolutions?.length);_(g,200,{decision:{id:B.id,createdAt:z.timestamp,url:z.annotationSnapshot.url,viewport:z.annotationSnapshot.viewport,color:z.annotationSnapshot.color,annotations:z.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await Z.loadDecision(J);F?_(g,200,{decision:F,authority:"legacy_archive"}):_(g,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let J=S.slice(8);await Xi(J,g)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let J=S.slice(8);await Yi(J,g)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?Gi(a,g):a.method==="GET"&&S==="/canvas/manifest"?await Vi(g):a.method==="GET"&&S==="/canvas/app.mjs"?await Ki(g):_(g,404,{error:"Not found"})}catch(J){console.error("[Bridge] Request error:",J),_(g,500,{error:J instanceof Error?J.message:"Internal error"})}});async function we(a,g,j){try{if(a.method==="GET"&&j==="/memory/status"){_(g,200,await q.status());return}if(a.method==="GET"&&j==="/memory/diagnostics"){_(g,200,await q.diagnostics());return}if(a.method==="GET"&&j==="/memory/model-view"){_(g,200,await q.getModelView());return}if(a.method==="GET"&&j==="/memory/imprint-view"){let v=await V.load(),T=[...new Set(Object.values(v.threads).flatMap(S=>un(S.messages)))];_(g,200,await q.getImprintView(T));return}if(a.method==="POST"&&j==="/memory/constraints"){let v=await ze(a),T=typeof v.reactComponent=="string"?v.reactComponent.trim():"",S=typeof v.pathname=="string"?v.pathname.trim():"",A=typeof v.selector=="string"?v.selector.trim():"",J=await q.getModelView(),B=T?J.entries.filter(D=>D.key===`components.${T}`||D.key.startsWith(`components.${T}.`)):[],z=(D,N)=>{if(!N)return!1;if(!D.includes("*"))return D===N;let Q=D.split("*").map(H=>H.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`).test(N)},F=(await q.getJournalEvalCases()).filter(D=>{if(D.status==="rejected")return!1;let N=(D.dependencies??[]).some(H=>H.kind==="route"&&z(H.value,S)||H.kind==="subject"&&H.value===A),Q=(D.scenarios??[]).some(H=>!!T&&(H.components??[]).some(ie=>ie.name===T||ie.exportName===T)||!!S&&!!H.route&&H.route===S||!!S&&!!H.routePattern&&z(H.routePattern,S));return N||Q}).map(D=>({id:D.id,title:D.title,verificationState:D.verificationState,assertions:D.assertions}));_(g,200,{modelEntries:B,evals:F});return}if(a.method==="POST"&&j==="/memory/conversation-action"){let v=await ze(a),T=typeof v.threadId=="string"?v.threadId:"",S=typeof v.proposalId=="string"?v.proposalId:"",A=String(v.action);if(!T||!S||!["accept","edit_and_accept","reject","defer"].includes(A)){_(g,400,{error:"A valid thread, proposal, and review action are required."});return}let J=await V.getThread(T),B=J?.messages.find(ce=>ce.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!J||!B){_(g,409,{error:"This decision review card is not available in the thread."});return}let z=await se.findModelProposalsByThread(T),F=(await Promise.all(z.map(async ce=>({proposal:ce,matches:(await Promise.all(ce.decisionIds.map(te=>q.findPendingProposalForLegacyDecision(te)))).some(te=>te?.proposalId===S)})))).find(ce=>ce.matches)?.proposal,D={proposalId:S,action:A,kind:B.kind,claim:A==="edit_and_accept"&&typeof v.claim=="string"?v.claim.trim():void 0,reason:A==="defer"?void 0:`The owner explicitly chose ${A.replaceAll("_"," ")} from the decision review card.`,taskContext:A==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:A==="defer"?["different_action","owner_request"]:void 0};if(D.action==="edit_and_accept"&&!D.claim){_(g,400,{error:"Edited decision wording is required."});return}let N=await q.commitConversationalReview(D),Q=`memory-${mt().slice(0,8)}`,H=A==="accept"?"> Accepted decision":A==="edit_and_accept"?"> Edited and accepted decision":A==="reject"?"> Rejected decision":"> Deferred decision";await V.appendMessage(T,{role:"human",timestamp:Date.now(),jobId:Q,replyToQuestion:H}),await V.appendMessage(T,{role:"assistant",timestamp:Date.now(),jobId:Q,responseText:"",memoryReceipt:N,provider:Rt(typeof v.provider=="string"?v.provider:void 0),model:typeof v.model=="string"?v.model:void 0}),N.status==="committed"&&F&&await se.dismissModelProposal(F.id);let ie=Rt(typeof v.provider=="string"?v.provider:void 0);N.status==="committed"&&N.decisionId&&ie!=="copilot"&&await Ee({provider:ie,model:typeof v.model=="string"?v.model:void 0,agentSettings:vt(v),threadId:T,reason:`Project accepted decision ${N.decisionId}`}),_(g,N.status==="committed"?200:409,{receipt:N});return}if(a.method==="POST"&&j==="/memory/analyze"){let v=await ze(a),T=await q.analyzeLegacy({projectKey:typeof v.projectKey=="string"?v.projectKey:void 0}),S=Object.fromEntries([...new Set(T.issues.map(A=>A.code))].map(A=>[A,T.issues.filter(J=>J.code===A).length]));_(g,200,{...T,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&j==="/memory/review"){let v=await ze(a),T=await q.review(Fo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,T);return}if(a.method==="POST"&&j==="/memory/context"){let v=await ze(a),T=await q.contextualize(Fo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,T);return}if(a.method==="POST"&&j==="/memory/initialize"){let v=await ze(a),T=await q.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:st});_(g,201,{status:T.status,report:{source:T.report.source,imported:T.report.imported,unresolvedAcceptance:T.report.unresolvedAcceptance,deferredModelEntries:T.report.deferredModelEntries,proofCases:T.report.proofCases,schemaIssues:T.report.schemaIssues}});return}if(a.method==="POST"&&j==="/memory/plan"){let v=await ze(a),T=await q.planReview(Lo(v.command),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,T.result.ok?200:422,T);return}if(a.method==="POST"&&j==="/memory/commit"){let v=await ze(a),T=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},S=await q.commitReview(Lo(v.command),{transactionId:typeof T.transactionId=="string"?T.transactionId:"",committedAt:typeof T.committedAt=="string"?T.committedAt:""});_(g,200,{status:await q.status(),journal:S.report});return}if(a.method==="POST"&&j==="/memory/recover"){let v=await ze(a),T=await q.recover(v.confirm===!0);_(g,200,{status:await q.status(),journal:T.report});return}_(g,404,{error:"Memory endpoint not found."})}catch(v){let T=v instanceof Error?v.message:String(v),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(T),A=/required|invalid|unsupported|expected|must be|confirmation/i.test(T);if(S||A){_(g,S?409:400,{error:T});return}throw v}}async function ct(a,g,j){if(a.method==="GET"&&j==="/imprint/status"){let[v,T]=await Promise.all([ge.store.load(),V.load()]),S=[...new Set(Object.values(T.threads).flatMap(A=>un(A.messages)))].filter(A=>v.graph.explanations.some(J=>J.id===A&&J.state==="testing"));_(g,200,{state:"ready",head:v.graph.head,updatedAt:v.graph.updatedAt,explanationCount:v.graph.explanations.filter(A=>A.state!=="retired").length,concreteCount:v.graph.concrete.length,relationCount:v.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:v.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&j==="/imprint/action"){let v=await ze(a),T=typeof v.threadId=="string"?v.threadId:"",S=typeof v.transactionId=="string"?v.transactionId:"",A=String(v.action);if(!T||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(A)){_(g,400,{error:"A valid thread, imprint update, and action are required."});return}let B=await V.getThread(T),z=[...B?.messages??[]].reverse().find(ie=>ie.role==="assistant"&&ie.imprintSummary?.transactionId===S),F=z?.imprintSummary;if(!B||!z||!F){_(g,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){_(g,409,{error:"This imprint summary has already been resolved."});return}let D=`imprint-${mt().slice(0,8)}`;await ge.applyGroundingAction({summary:F,action:A,value:typeof v.value=="string"?v.value:void 0,threadId:T,jobId:D}),await q.recordImprintEvidence({summary:F,action:A,threadId:T,jobId:D}).catch(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let N=Nt(z.result,!!z.question),Q=z.turn?{...z.turn,result:Nt(z.turn.result,!!z.question)}:void 0;await V.updateAssistantMessage(T,z.jobId,{imprintSummary:{...F,resolvedAction:A},...N?{result:N}:{},...Q?{turn:Q}:{}});let H={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await V.appendMessage(T,{role:"human",timestamp:Date.now(),jobId:D,replyToQuestion:H[A]}),_(g,200,{ok:!0,action:A});return}_(g,404,{error:"Imprint endpoint not found."})}async function Me(a,g){let{screenshot:j,feedback:v,color:T,provider:S,model:A,reasoningEffort:J,serviceTier:B,sourceId:z,pastedImages:F,pageScreenshots:D}=await Fn(a),N;try{N=JSON.parse(v)}catch{_(g,400,{error:"Invalid feedback JSON"});return}let Q=mt().slice(0,8),H={};if(D.length>0)for(let ee of D){let he=encodeURIComponent(ee.pathname),ke=Ae(c,`screenshot-${Q}-${he}.webp`);await pn(ke,ee.data),H[ee.pathname]=ke}let ie=Ae(c,`screenshot-${Q}.webp`);await pn(ie,j);let ce={};if(F.length>0)for(let ee of F){let he=Ae(c,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await pn(he,ee.data),ce[ee.annotationId]||(ce[ee.annotationId]=[]),ce[ee.annotationId].push(he)}let te=N.annotations.map(ee=>ee.linkedSelector?ee.pathname?`${ee.pathname}:${ee.linkedSelector}`:ee.linkedSelector:null).filter(ee=>!!ee),be;if(te.length>0){let ee=await V.findContinuationThread(te);ee?(be=ee.id,await V.addElementIdentifiers(be,te)):be=(await V.createThread(Q,te)).id}else be=(await V.createThread(Q,[])).id;let Ie=N.annotations.map(ee=>ee.id),ve=Object.keys(H).length>0,K=await Qr(q,N,te,ee=>console.warn(`[\u22B9 ${y}:${Q}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),de=await ge.contextualize({text:Ln(N),subjectHints:[...te,...N.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(he=>!!he))],pendingGroundingExplanationIds:un((await V.getThread(be))?.messages??[])}).catch(ee=>{console.warn(`[\u22B9 ${y}:${Q}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),pe={id:Q,status:"queued",screenshotPath:ie,feedback:N,createdAt:Date.now(),color:T,threadId:be,annotationIds:Ie,provider:Rt(S),model:A||void 0,agentSettings:vt({reasoningEffort:J,serviceTier:B}),...Object.keys(ce).length>0?{imagePaths:ce}:{},sourceId:z||void 0,...ve?{screenshotPaths:H}:{},...K?{memoryReview:K}:{},...de?{imprintContext:de}:{}},_e=new Set(N.annotations.map(ee=>ee.pathname).filter(Boolean)),Ce;if(_e.size>1){let ee=new Map;for(let he of N.annotations){let ke=he.pathname||"(unknown)";ee.has(ke)||ee.set(ke,[]),ee.get(ke).push(he.instruction||Mi({...N,annotations:[he]}))}Ce=[...ee.entries()].map(([he,ke])=>`\`${he}\`
|
|
229
|
-
${ke.map(xe=>`- ${xe}`).join(`
|
|
230
|
-
`)}`).join(`
|
|
231
|
-
`)}else Ce=Mi(N);let nt=nn(N,Object.keys(ce).length>0?ce:void 0);await V.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:Q,screenshotPath:ie,...ve?{screenshotPaths:H}:{},...Object.keys(ce).length>0?{imagePaths:ce}:{},annotationIds:Ie,annotationSnapshot:{url:N.url,viewport:N.viewport,annotations:N.annotations,color:T||void 0},feedbackSummary:Ce,feedbackContext:nt||void 0,...K?{memoryReview:K}:{},...de?{imprintContext:de}:{}});let Pe=I.enqueue(pe);_(g,200,{jobId:Q,position:Pe,threadId:be})}async function tt(a,g){let j=a.headers["content-type"]||"",v,T,S,A,J,B,z,F,D,N=[];if(j.includes("multipart/form-data")){let X=await Fn(a),me=X.feedback?JSON.parse(X.feedback):{};v=me.threadId,T=me.reply,S=me.color,A=me.provider,J=me.model,B=vt(me),z=me.sourceId||X.sourceId,F=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0,D=me.evalRemediation?.action==="resolve"&&typeof me.evalRemediation.evalId=="string"?{evalId:me.evalRemediation.evalId,action:"resolve"}:void 0;for(let W of X.pastedImages)N.push(W.data)}else{let X=[];for await(let re of a)X.push(typeof re=="string"?Buffer.from(re):re);let me=Buffer.concat(X).toString("utf-8"),W;try{W=JSON.parse(me)}catch{_(g,400,{error:"Invalid JSON"});return}v=W.threadId,T=W.reply,S=W.color,A=W.provider,J=W.model,B=vt(W),z=W.sourceId,F=W.memoryReviewProposalId,D=W.evalRemediation?.action==="resolve"&&typeof W.evalRemediation.evalId=="string"?{evalId:W.evalRemediation.evalId,action:"resolve"}:void 0}if(!v||!T){_(g,400,{error:"Missing threadId or reply"});return}let Q=await V.getThread(v);if(!Q){_(g,404,{error:"Thread not found"});return}let H,ie;if(D){let X=await q.findJournalEvalCase(D.evalId),me=(await q.getJournalEvalRuns()).filter(W=>W.evalId===D.evalId&&W.threadId===v).sort((W,re)=>re.completedAt-W.completedAt)[0];if(!X||!me){_(g,409,{error:"The failed eval run is not available in this thread."});return}if(me.status!=="fail"){_(g,409,{error:"Only a failed eval can start remediation."});return}ie={evalCase:X,run:me}}if(F){let X=await se.findModelProposalsByThread(v);if(H=(await Promise.all(X.flatMap(W=>W.authorityStatus==="accepted"?[]:W.decisionIds.map(async re=>({modelProposalId:W.id,underlying:await q.findPendingProposalForLegacyDecision(re)}))))).filter(W=>!!W.underlying).find(W=>W.underlying.proposalId===F),!H){_(g,409,{error:"The requested memory decision is not pending in this thread."});return}}let ce="";{let X=await V.getThreadHistory(v);for(let me=X.length-1;me>=0;me--)if(X[me].screenshotPath){ce=X[me].screenshotPath;break}}let te=await Fi(v);if(!ce&&!te){_(g,400,{error:"No screenshot available"});return}let be=I.hasActiveThread(v),Ie=be?I.getQueuedThreadJob(v,X=>X._replyText!==void 0||X._replyPrompt!==void 0):null,ve=Ie?.id??mt().slice(0,8),K=[],de=`${ve}-${Date.now()}`;for(let X=0;X<N.length;X++){let me=Ae(c,`reply-${de}-${X}.webp`);await pn(me,N[X]),K.push(me)}await V.appendMessage(v,{role:"human",timestamp:Date.now(),jobId:ve,replyToQuestion:T,screenshotPath:ce,...be?{queued:!0}:{},...K.length>0?{replyImagePaths:K}:{}});let pe=await V.getThreadHistory(v),_e=[...pe].reverse().find(X=>X.memoryReview)?.memoryReview,Ce=await ge.contextualize({text:T,subjectHints:Q.elementIdentifiers,pendingGroundingExplanationIds:un(pe)}).catch(X=>{console.warn(`[\u22B9 ${y}:${ve}] Imprint context unavailable for reply; continuing without it:`,X instanceof Error?X.message:String(X))}),nt=new Set(pe.flatMap(X=>X.memoryReceipt?.status==="committed"?[X.memoryReceipt.proposalId]:[])),Pe=[...pe].reverse().find(X=>X.memoryReviewCard&&!nt.has(X.memoryReviewCard.proposalId))?.memoryReviewCard,ee=[];for(let X of pe)if(X.annotationIds)for(let me of X.annotationIds)ee.includes(me)||ee.push(me);let he=Rt(A),ke=H,xe=ke?[ke.underlying.proposalId]:Pe?[Pe.proposalId]:[],yt=ri(ce,pe,he,K.length>0?K:void 0);if(ie?yt+=["","## Failed eval remediation","This is a new implementation goal based on a failed Popmelt eval. Fix the product gaps identified by the evaluator.","Do not weaken, rewrite, approve, retire, or otherwise modify the eval specification unless the developer explicitly asks.","Treat the accepted product decision as governing truth; the failed implementation is what should change.",`Eval: ${JSON.stringify(ie.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:ie.run.summary,assertionResults:ie.run.assertionResults,scope:ie.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
|
|
232
|
-
`):ke?yt+=["","## Decision review card",`Privately review proposal ${ke.underlying.proposalId}: ${ke.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
|
|
233
|
-
`):Pe&&(yt+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Pe)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
|
|
234
|
-
`)),Ie){let X=Ie,W=[...X._replyTexts??(X._replyText?[X._replyText]:[]),T],re=[...X._replyImagePaths??[],...K];X._replyTexts=W,X._replyText=Ai(W),X._replyImagePaths=re.length>0?re:void 0,X._replyPrompt=yt,X.annotationIds=ee.length>0?ee:X.annotationIds,X.agentSettings=B??X.agentSettings,X.memoryReview=_e??X.memoryReview,X.imprintContext=Ce??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...xe])],_(g,200,{jobId:ve,position:1,threadId:v,bundled:!0});return}let qe={id:ve,status:"queued",screenshotPath:ce,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:v,annotationIds:ee.length>0?ee:void 0,provider:he,model:J||void 0,agentSettings:B,sourceId:z||void 0,..._e?{memoryReview:_e}:{},...Ce?{imprintContext:Ce}:{},...xe.length?{surfacedProposalIds:xe}:{}};ie?qe.kind="resolve_eval":te&&(qe.kind=te),qe._replyPrompt=yt,qe._evalRemediation=!!ie,qe._replyTexts=[T],qe._replyText=Ai([T]),K.length>0&&(qe._replyImagePaths=K);let qt=be?I.enqueueNext(qe):I.enqueue(qe);_(g,200,{jobId:ve,position:qt,threadId:v})}function dt(a,g){g.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),g.write(`event: connected
|
|
235
|
-
data: {"status":"connected"}
|
|
236
|
-
|
|
237
|
-
`);let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,T={id:mt().slice(0,8),res:g,sourceId:v};Y.add(T),a.on("close",()=>{Y.delete(T)})}async function lt(a,g,j){s??=vi(a.headers),Ue();let v=[...I.allActive,...w.allActive.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds??[],color:"#000000",kind:"project_model",standalone:K.standalone}))],[T,S,A,J,B]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),q.status(),ge.store.load(),V.load()]),z=[],F=K=>K.reason instanceof Error?K.reason.message:String(K.reason);T.status==="rejected"&&z.push({subsystem:"projection",message:F(T)}),S.status==="rejected"&&z.push({subsystem:"projection",message:F(S)}),A.status==="rejected"?z.push({subsystem:"memory",message:F(A)}):A.value.state==="degraded"&&z.push({subsystem:"memory",message:A.value.error??"Product memory is degraded."}),J.status==="rejected"&&z.push({subsystem:"imprint",message:F(J)}),B.status==="rejected"&&z.push({subsystem:"threads",message:F(B)});let D=T.status==="fulfilled"?T.value.runs:[],N=S.status==="fulfilled"?S.value.proposals:[],Q=Ii(D,N),H=Q.actionableProposals.map(K=>({id:K.id,status:K.status,title:K.title,summary:K.summary,decisionIds:K.decisionIds,threadId:K.threadId,runId:K.runId,presentationJobId:K.presentationJobId,authorityStatus:K.authorityStatus,underlyingProposalId:K.underlyingProposalId,createdAt:K.createdAt,updatedAt:K.updatedAt,appliedAt:K.appliedAt,dismissedAt:K.dismissedAt,generatedEvalIds:K.generatedEvalIds,evalProjections:K.evalProjections,error:K.error})),ie=A.status==="fulfilled"?A.value:{initialized:!1,state:"degraded",error:F(A)},ce=B.status==="fulfilled"?[...new Set(Object.values(B.value.threads).flatMap(K=>un(K.messages)))]:[],te=J.status==="fulfilled"?ce.filter(K=>J.value.graph.explanations.some(de=>de.id===K&&de.state==="testing")):[],be=J.status==="fulfilled"?{state:"ready",head:J.value.graph.head,updatedAt:J.value.graph.updatedAt,explanationCount:J.value.graph.explanations.filter(K=>K.state!=="retired").length,concreteCount:J.value.graph.concrete.length,relationCount:J.value.graph.relations.length,pendingGroundingCount:te.length,recoveredTransactions:J.value.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(J),pendingGroundingCount:te.length,admission:ge.diagnostics(),admissionWindowStartedAt:e},Ie=z.length>0?"degraded":ie.state==="absent"||ie.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();_(g,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:Ie,issues:z},version:st,restartMode:p,projectId:i,projectName:ro(r),projectRoot:r,requestProjectId:j,projectIdVerified:j===i,devOrigin:s,activeJob:v[0]?{id:v[0].id,status:v[0].status}:null,activeJobs:v.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds,color:K.color,kind:K.kind,standalone:"standalone"in K?K.standalone:void 0})),queueDepth:I.depth+w.depth,projectionQueueDepth:w.depth,leases:{active:M.isActivated,count:M.size,nextExpiryAt:M.nextExpiryAt,shutdownPending:U},projection:{state:T.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:w.active?{id:w.active.id,status:w.active.status,threadId:w.active.threadId,annotationIds:w.active.annotationIds??[],provider:w.active.provider,model:w.active.model}:null,queueDepth:w.depth,recentRuns:Q.recentRuns,recentAppliedRuns:Q.recentAppliedRuns,actionableProposalCounts:Q.actionableProposalCounts,actionableProposals:H},memory:ie,imprint:be,recentJobsRetentionMs:Je,recentJobs:Re})}async function ht(a,g){let j=await new Promise(v=>{let T="";a.on("data",S=>{T+=S.toString()}),a.on("end",()=>v(T))});try{let v=JSON.parse(j);typeof v.devOrigin=="string"&&(s=v.devOrigin||null),_(g,200,{ok:!0,devOrigin:s})}catch{_(g,400,{error:"Invalid JSON"})}}async function co(a){let g=await $.load();_(a,200,{ok:!0,...g})}async function lo(a,g){let j=await ze(a);if(!Pi(j.theme)){_(g,400,{error:"theme must be light, dark, or auto"});return}let v=await $.setTheme(j.theme);_(g,200,{ok:!0,exists:!0,preferences:v})}async function Ut(a,g){let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),T=v?I.allActive.filter(F=>F.id===v):I.allActive,S=v?w.allActive.filter(F=>F.id===v):w.allActive,A=[...T.map(F=>F.threadId),...S.map(F=>F.threadId)].filter(Boolean),J=v?I.cancelJob(v):I.cancelActive(),B=v?w.cancelJob(v):w.cancelActive(),z=!!(J||B);for(let F of A)await V.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:v||B?.id||"",cancelled:!0});_(g,200,{cancelled:z})}async function Ee(a){let g=mt().slice(0,8),j=a.threadId,v=!j;j||(j=(await V.createThread(g,[])).id,Ve.set(j,"project_model")),v&&await V.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:a.reason}),await V.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:g,responseText:v?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let T={id:g,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:j,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:v},S=w.enqueue(T);return{jobId:g,position:S,threadId:j}}async function Ne(a,g){let j=decodeURIComponent(a),v=await se.findModelProposal(j);if(!v){_(g,404,{error:"Model proposal not found"});return}_(g,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:v})}async function pt(a,g,j){let v=decodeURIComponent(a),T=[];for await(let N of g)T.push(typeof N=="string"?Buffer.from(N):N);let S;try{S=JSON.parse(Buffer.concat(T).toString("utf-8"))}catch{_(j,400,{error:"Invalid JSON"});return}let A=(S.changes??[]).flatMap(N=>{if(!Array.isArray(N.path)||N.path.length===0)return[];let Q=N.path.filter(ie=>typeof ie=="string"||typeof ie=="number");if(Q.length!==N.path.length)return[];let H=Array.isArray(N.decisionIds)?N.decisionIds.filter(ie=>typeof ie=="string"):void 0;return[{path:Q,value:N.value,remove:N.remove===!0,decisionIds:H}]});if(A.length===0){_(j,400,{error:"No selected model changes"});return}let J=(S.changeSummaries??[]).flatMap(N=>{if(!N||typeof N!="object")return[];let Q=Array.isArray(N.path)?N.path.filter(H=>typeof H=="string"||typeof H=="number"):void 0;return Array.isArray(N.path)&&Q?.length!==N.path.length?[]:[{group:typeof N.group=="string"?N.group:void 0,label:typeof N.label=="string"?N.label:void 0,detail:typeof N.detail=="string"?N.detail:void 0,path:Q,value:N.value,currentValue:N.currentValue}]}),B=await se.findModelProposal(v);if(!B){_(j,404,{error:"Model proposal not found"});return}if(B.authorityStatus!=="accepted"){_(j,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(B.status!=="pending"){_(j,409,{error:`Model proposal is already ${B.status}.`});return}let z=B.decisionIds.map(N=>{let Q=B.changes?.filter(ce=>ce.decisionIds.includes(N)).length??0,H=A.filter(ce=>ce.decisionIds?.includes(N)).length,ie=H===0?"unprojected":Q>H?"partially_projected":"projected";return{decisionId:N,status:ie}}),F=await q.applyModelProjection({runId:B.runId??B.id,presentationJobId:B.presentationJobId,decisionIds:B.decisionIds,changes:A.map(N=>({path:N.path,value:N.value,decisionIds:N.decisionIds})),coverage:z}),D=await se.applySelectedModelProposal(v,A,J);if(!D){_(j,404,{error:"Model proposal not found"});return}if(await et(D),D.threadId){let N=Rt(S.provider),Q=typeof S.model=="string"&&S.model?S.model:void 0;await V.appendMessage(D.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${D.id}`,responseText:"",provider:N,model:Q})}_(j,200,{proposal:D,projection:F})}async function Pt(a,g,j){let v=decodeURIComponent(a),{provider:T,model:S}=await gt(g),A=await se.dismissModelProposal(v);if(!A){_(j,404,{error:"Model proposal not found"});return}A.threadId&&await V.appendMessage(A.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${A.id}`,responseText:"",provider:T,model:S}),_(j,200,{proposal:A})}async function gt(a){try{let g=[];for await(let v of a)g.push(typeof v=="string"?Buffer.from(v):v);if(g.length===0)return{};let j=JSON.parse(Buffer.concat(g).toString());return{provider:Rt(typeof j.provider=="string"?j.provider:void 0),model:typeof j.model=="string"&&j.model?j.model:void 0,agentSettings:vt(j)}}catch{return{}}}async function po(a,g,j){let v=decodeURIComponent(a),T=await q.findJournalEvalCase(v);if(!T){_(j,404,{error:"Eval not found"});return}if(T.status!=="approved"){_(j,400,{error:"Only approved evals can be run"});return}let{screenshot:S,feedback:A,provider:J,model:B,reasoningEffort:z,serviceTier:F,sourceId:D}=await Fn(g),N=Rt(J)??b;if(N==="copilot"){_(j,400,{error:"Eval runs are not available for Copilot yet."});return}let Q={};try{Q=A?JSON.parse(A):{}}catch{_(j,400,{error:"Invalid eval run context JSON"});return}let H=mt().slice(0,8),ie=mt().slice(0,8),ce=Ae(c,`eval-run-${H}.webp`);await pn(ce,S);let te=await ue.persistEvalScreenshot(S),be=Q.viewport,Ie=be&&typeof be=="object"?be:{},ve={type:"current_page",url:typeof Q.url=="string"?Q.url:"",viewport:{width:typeof Ie.width=="number"?Ie.width:0,height:typeof Ie.height=="number"?Ie.height:0}},K=await se.loadModel(),de=await Ci(r,T,K),pe=N==="claude"?E.name:N==="codex"?O.name:null,_e=N==="codex"?C.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=yr({evalCase:T,scope:ve,model:K,screenshotPath:ce,chromeDevtoolsAvailable:_e}),Pe=(await V.createThread(ie,[])).id;Ve.set(Pe,"run_eval");let ee={timestamp:new Date().toISOString(),url:ve.url,viewport:ve.viewport,scrollPosition:{x:typeof Q.scrollX=="number"?Q.scrollX:0,y:typeof Q.scrollY=="number"?Q.scrollY:0},annotations:[],styleModifications:[]};await V.appendMessage(Pe,{role:"human",timestamp:Date.now(),jobId:ie,screenshotPath:ce,feedbackSummary:`Run eval \u2014 ${T.title}`,feedbackContext:[`Eval: ${T.title}`,"Scope: current page",`URL: ${ve.url||"unknown"}`,"Assertions:",...T.assertions.map(xe=>`- ${xe}`)].join(`
|
|
238
|
-
`)});let he={id:ie,status:"queued",screenshotPath:ce,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:Pe,kind:"run_eval",evalId:v,evalRunId:H,provider:N,model:B||void 0,agentSettings:vt({reasoningEffort:z,serviceTier:F}),sourceId:D||void 0};he._replyPrompt=Ce,he._evalRunScope=ve,he._evalScreenshotPath=te,he._evalScopeFingerprint=de;let ke=I.enqueue(he);_(j,200,{jobId:ie,runId:H,position:ke,threadId:Pe,screenshotPath:te})}async function mn(a,g,j){let v=decodeURIComponent(a),T={},S,A,J;try{let z=[];for await(let D of g)z.push(typeof D=="string"?Buffer.from(D):D);let F=JSON.parse(Buffer.concat(z).toString());S=F.status,A=F.title,J=F.assertions}catch{_(j,400,{error:"Invalid JSON"});return}if(S!==void 0&&S!=="pending"&&S!=="approved"&&S!=="rejected"){_(j,400,{error:"Invalid status"});return}if(S&&(T.status=S),A!==void 0){if(typeof A!="string"||A.trim().length===0){_(j,400,{error:"Invalid title"});return}T.title=A.trim()}if(J!==void 0){if(!Array.isArray(J)){_(j,400,{error:"Invalid assertions"});return}let z=J.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(z.length===0){_(j,400,{error:"Invalid assertions"});return}T.assertions=z}if(!T.status&&!T.title&&!T.assertions){_(j,400,{error:"No eval changes provided"});return}let B=await q.updateJournalEvalCase(v,T);if(!B){_(j,404,{error:"Eval not found"});return}_(j,200,{eval:B})}async function Fi(a){let g=Ve.get(a);if(g)return g;let T=(await V.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(T.startsWith("Synthesize evals"))return Ve.set(a,"synthesize_evals"),"synthesize_evals";if(T.startsWith("Synthesize rules"))return Ve.set(a,"synthesize"),"synthesize";if(T.startsWith("Run eval"))return Ve.set(a,"run_eval"),"run_eval";if(T.startsWith("Materialize model")||T.startsWith("Project model"))return Ve.set(a,"project_model"),"project_model"}async function zi(a,g){let j=[];for await(let B of a)j.push(typeof B=="string"?Buffer.from(B):B);let v;if(j.length>0)try{v=JSON.parse(Buffer.concat(j).toString("utf-8")).serverUrl}catch{}let T=[];h.claude?.available&&h.claude.mcp&&!h.claude.mcp.found&&T.push(await Cr(v)),h.codex?.available&&h.codex.mcp&&!h.codex.mcp.found&&T.push(await $r(v)),h.copilot?.available&&h.copilot.mcp&&!h.copilot.mcp.found&&T.push(await Or(v,h.copilot.path??P));let[S,A,J]=await Promise.all([Ro(r),Po(r),ko(r,h.copilot?.path??P)]);h.claude&&(h.claude.mcp=S),h.codex&&(h.codex.mcp=A),h.copilot&&(h.copilot.mcp=J),_(g,200,{results:T,capabilities:{providers:h}})}async function Ui(a,g){let j=[];for await(let A of a)j.push(typeof A=="string"?Buffer.from(A):A);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let T=await q.recordDirectModelMutation({key:`components.${v.name}`,value:{description:""},claim:`${v.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await at({decisionId:T.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is an explicitly governed component in the product model.`});_(g,200,{added:!0,alreadyExists:!1,...T,evalId:S})}async function qi(a,g){let j=[];for await(let A of a)j.push(typeof A=="string"?Buffer.from(A):A);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let T=await q.recordDirectModelMutation({key:`components.${v.name}`,value:null,claim:`${v.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await at({decisionId:T.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is not governed as a component in the product model.`});_(g,200,{removed:!0,...T,evalId:S})}async function Wi(a,g){let j=[];for await(let J of a)j.push(typeof J=="string"?Buffer.from(J):J);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"||typeof v.value!="string"){_(g,400,{error:"Missing or invalid path/value"});return}let T=v.value;try{let J=JSON.parse(v.value);J&&typeof J=="object"&&(T=J)}catch{}let S=await q.recordDirectModelMutation({key:`tokens.${v.path}`,value:T,claim:`${v.path} uses ${v.value} in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let A=await at({decisionId:S.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} uses ${v.value} in the product model.`});_(g,200,{updated:!0,...S,evalId:A})}async function Hi(a,g){let j=[];for await(let A of a)j.push(typeof A=="string"?Buffer.from(A):A);let v;try{v=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"){_(g,400,{error:"Missing or invalid path"});return}let T=await q.recordDirectModelMutation({key:`tokens.${v.path}`,value:null,claim:`${v.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await at({decisionId:T.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} is intentionally absent from the product model.`});_(g,200,{removed:!0,...T,evalId:S})}function Gi(a,g){let j=s??"http://localhost:3000";if(!s){let T=a.headers.referer||a.headers.origin;if(T)try{let S=new URL(typeof T=="string"?T:T[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(j=S.origin)}catch{}}let v=er(y,j);g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(v)}async function Vi(a){let g=Date.now();if(ft&&g<ft.expires){_(a,200,ft.data);return}try{let{scanForComponents:j}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:v}=await import("./render-generator-HWFLZYC3.mjs"),T=await j(r);ft={data:T,expires:g+5e3},v(T,r,Ft).then(S=>{Ft=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,T)}catch(j){console.error("[Bridge] Scanner error:",j),_(a,500,{error:"Failed to scan components"})}}async function Ki(a){let g=[Ae(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ae(r,"packages","popmelt","dist","canvas.mjs")];try{let j=md(import.meta.url);g.unshift(Ae(ud(j),"canvas.mjs"))}catch{}for(let j of g)try{let v=await Ho(j,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(v);return}catch{}console.error("[Bridge] Canvas bundle not found in:",g),_(a,404,{error:"Canvas bundle not found"})}async function Qi(a,g){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(g,400,{error:"Invalid filename"});return}try{let j=[Ae(c,a),Ae(r,".popmelt","artifacts","thread-media",a),Ae(r,".popmelt","artifacts","eval-screenshots",a),Ae(r,".popmelt","evals","screenshots",a),Ae(r,".popmelt","screenshots",a)],v;for(let A of j)try{v=await Ho(A);break}catch{}if(!v)throw new Error("File not found");let T=a.split(".").pop()?.toLowerCase(),S=T==="png"?"image/png":T==="webp"?"image/webp":T==="jpg"||T==="jpeg"?"image/jpeg":"application/octet-stream";g.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),g.end(v)}catch{_(g,404,{error:"File not found"})}}function fn(a){return`/files/${ro(a)}`}async function Xi(a,g){let j=await V.getThread(a);if(!j){_(g,404,{error:"Thread not found"});return}let v=j.messages.some(D=>D.role==="assistant"&&D.responseText?.includes("<eval_run_result>")),T=j.messages.filter(D=>D.role==="assistant"&&D.responseText?.includes("Model suggestion ready")),[S,A]=await Promise.all([v?q.getJournalEvalRuns().then(D=>D.filter(N=>N.threadId===a).sort((N,Q)=>Q.completedAt-N.completedAt)[0]):Promise.resolve(void 0),T.length>0?se.findModelProposalsByThread(a):Promise.resolve([])]),J=S?await q.findJournalEvalCase(S.evalId):null,B=await Promise.all(A.map(async(D,N)=>{if(D.authorityStatus==="accepted")return D;let Q=(await Promise.all(D.decisionIds.map(H=>q.findPendingProposalForLegacyDecision(H)))).find(Boolean);return{...D,authorityStatus:"legacy_untrusted",presentationJobId:D.presentationJobId??T[N]?.jobId??T.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),z=[...B].sort((D,N)=>N.updatedAt-D.updatedAt)[0]??null,F=j.messages.map(({screenshotPath:D,screenshotPaths:N,imagePaths:Q,replyImagePaths:H,...ie})=>({...ie,...ie.role==="assistant"&&S&&ie.responseText?.includes("<eval_run_result>")?{evalRun:{...S,title:J?.title}}:{},...D?{screenshotUrl:fn(D)}:{},...N?{screenshotUrls:Object.fromEntries(Object.entries(N).map(([ce,te])=>[ce,fn(te)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ce,te])=>[ce,te.map(fn)]))}:{},...H?{replyImageUrls:H.map(fn)}:{}}));_(g,200,{id:j.id,createdAt:j.createdAt,messages:F,modelProposal:z,modelProposals:B})}async function Yi(a,g){let j=decodeURIComponent(a);if(!await V.deleteThread(j)){_(g,404,{deleted:!1,error:"Thread not found"});return}_(g,200,{deleted:!0})}let Ko=9,Qo=!1;for(let a=n;a<n+Ko;a++)try{await Td(zt,a),y=a,Qo=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(g){if(g.code==="EADDRINUSE"){let j=await ao(a);if(cn(j,{projectId:i,version:st,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw g}if(!Qo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Ko-1} in use`);for(let[a,g]of Object.entries(h))!g.available||!g.path||u(a,g.path).then(j=>{if(j)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),g.available=!1,g.path=null;for(let v of Y)io(v,{type:"capabilities_changed",data:{}})}});let Zi=setInterval(()=>{$i(c).catch(()=>{})},gd),Xo=setInterval(()=>{M.expireStale().becameEmpty&&ye()},vd);return Xo.unref?.(),{port:y,projectId:i,close:async()=>{clearInterval(Zi),clearInterval(Xo),ne(),M.clear(),await I.destroyAsync(),w.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{zt.close(()=>a())})}}}async function $i(o){try{let e=await sd(o),n=Date.now();for(let t of e){let r=Ae(o,t);try{let i=await cd(r);n-i.mtimeMs>yd&&await dd(r)}catch{}}}catch{}}var Nd=1111,Bi=3e4,Bd=8e3;async function Ld(o){return Od(o).catch(()=>o)}async function Li(o,e){let t=(await $d(e,"utf8").catch(()=>"")).slice(-Bd).trim();return new Error(t?`${o}
|
|
239
|
-
Bridge log (${e}):
|
|
240
|
-
${t}`:o)}async function Nu(o){if(process.env.NODE_ENV==="production"&&!o?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(o?.detached){let n=await Fd(o);if(o.manageLease===!1)return n;let t=await Yo({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let r=Zo(t);return{...n,close:async()=>{r(),await t.release()}}}let e=await Ni(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Fd(o){let e=o.port??Nd,n=await Ld(o.projectRoot??process.cwd()),t=oo(n);for(let k=e;k<e+10;k++){let P=await ao(k);if(P&&P.projectId===t){if(P.version&&P.version!==st){if(P.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${k}/shutdown`,{method:"POST"})}catch{}await new Promise(m=>setTimeout(m,500));break}continue}if(!cn(P,{projectId:t,version:st,restartMode:"detached"}))continue;let b=o.devOrigin;if(b&&P.devOrigin!==b)try{await fetch(`http://127.0.0.1:${k}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:b})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(k),process.env.POPMELT_PROJECT_ID=t,{port:k,projectId:t,close:async()=>{}}}}let r=Vo(Dd(Jd(import.meta.url)),"bridge-entry.mjs"),i=Vo(n,".popmelt"),s=Vo(i,"bridge.log");await Cd(i,{recursive:!0}),await _d(s,`
|
|
241
|
-
[${new Date().toISOString()}] Starting detached bridge
|
|
242
|
-
`);let c=Md(s,"a"),d;try{d=Ed(process.execPath,[r],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{Ad(c)}let l=null;d.once("error",k=>{l=`spawn error: ${k.message}`}),d.once("exit",(k,P)=>{l=`child exited before becoming healthy (${P?`signal ${P}`:`code ${k??"unknown"}`})`}),d.unref();let x=Date.now()+Bi;for(;Date.now()<x;){if(await new Promise(k=>setTimeout(k,100)),l)throw await Li(`[Bridge] Detached bridge ${l}`,s);for(let k=e;k<e+10;k++){let P=await ao(k);if(cn(P,{projectId:t,version:st,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(k),process.env.POPMELT_PROJECT_ID=t,{port:k,projectId:t,close:async()=>{}}}}throw d.kill("SIGTERM"),await Li(`[Bridge] Detached bridge failed to start within ${Bi/1e3}s (port ${e})`,s)}export{Jt as ImprintService,Dt as ImprintStore,Xn as formatImprintPrompt,Qn as parseImprintDraft,Nu as startPopmelt};
|