@popmelt.com/core 0.8.6 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +60 -60
- package/dist/{chunk-EYFN72RC.mjs → chunk-ETDSTV4E.mjs} +1 -1
- package/dist/cli.mjs +58 -58
- package/dist/index.mjs +47 -40
- package/dist/memory-legacy.d.mts +35 -4
- package/dist/memory-legacy.mjs +1 -1
- package/dist/memory-store.d.mts +111 -9
- package/dist/memory-store.mjs +3 -3
- package/dist/memory.d.mts +36 -5
- package/dist/memory.mjs +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-FZ2YAIA5.mjs +242 -0
- package/dist/server.d.mts +2 -0
- package/dist/server.mjs +59 -59
- package/package.json +1 -1
- package/dist/server-KCVEM3PH.mjs +0 -242
package/dist/bridge-entry.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir as
|
|
1
|
+
import{mkdir as Ad,unlink as Ed,writeFile as Md}from"fs/promises";import{join as Dr}from"path";import{execFileSync as to,spawn as Sr}from"child_process";import{createHash as Mr,randomUUID as ut}from"crypto";import{mkdir as id,readFile as Uo,readdir as rd,realpath as sd,stat as ad,unlink as cd,writeFile as dn}from"fs/promises";import{createServer as dd}from"http";import{tmpdir as ld}from"os";import{basename as Zn,dirname as pd,isAbsolute as qo,join as Ee,relative as Rr,resolve as _r}from"path";import{fileURLToPath as ud}from"url";function Vo(o,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -25,12 +25,12 @@ import{mkdir as Sd,unlink as Pd,writeFile as kd}from"fs/promises";import{join as
|
|
|
25
25
|
});
|
|
26
26
|
</script>
|
|
27
27
|
</body>
|
|
28
|
-
</html>`}var
|
|
29
|
-
\u2026[truncated]`:t}function
|
|
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
|
|
31
|
-
`)[0].slice(0,80)}`:"Bash";
|
|
32
|
-
`)}`)),
|
|
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&&(
|
|
28
|
+
</html>`}var es=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),ts=new Set(["default","flex","fast","priority"]);function yt(o){let e=typeof o.reasoningEffort=="string"&&es.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&ts.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function mn(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 ns}from"child_process";import{createInterface as os}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"]),Ko=1e5;function rs(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>Ko?t.slice(0,Ko)+`
|
|
29
|
+
\u2026[truncated]`:t}function fn(o,e){let{prompt:n,projectRoot:t,maxTurns:i=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:b,timeoutMs:j=3e5,onEvent:T}=e,x=[];d?x.push("--resume",d,"-p",n):x.push("-p",n),x.push("--output-format","stream-json","--verbose","--max-turns",String(i),"--max-budget-usd",String(r)),l&&x.push("--model",l),b&&x.push("--effort",b);for(let y of s)x.push("--allowedTools",y);let m=ns(c,x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(y=>{let h,f=[],u=[],A=[],D=!1,R="",C,I,w=!1,M=setTimeout(()=>{w=!0,m.kill("SIGTERM"),setTimeout(()=>{try{m.kill("SIGKILL")}catch{}},5e3)},j),F=os({input:m.stdout}),H=new Set;F.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(H.add(ye),oe.type==="result"&&oe.result&&f.length===0){let Y=typeof oe.result=="string"?oe.result:"";Y&&(f.push(Y),T?.({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),T?.({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=rs(Y);if(T?.({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),A.push({sequence:A.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}),A.push({sequence:A.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&&T?.({type:"thinking",jobId:o,text:Y.thinking},o)}}oe.type==="result"&&oe.is_error===!0&&(D=!0,typeof oe.error=="string"&&(C=oe.error),typeof oe.result=="string"&&(I=oe.result)),oe.type==="user"&&oe.tool_use_result?.file?.filePath&&T?.({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),F.close(),f.length===0&&H.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...H].join(", ")}`),w)D=!0,R=`Timed out after ${Math.round(j/6e4)} minutes`;else if(ne!==0&&ne!==null){D=!0;let ye=U.join("").trim(),Y=f.join("").trim(),V=f.length===0&&H.size>0?` (no text captured, event types: ${[...H].join(", ")})`:"";R=ye||I||Y||`Claude process exited with code ${ne}${V}`}D&&!R&&I&&(R=I);let oe=ss(R,C);y({sessionId:h,text:f.join(""),success:!D,error:D?oe.message:void 0,errorCode:D?oe.code:void 0,recoverableError:D?oe.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:A.length>0?A:void 0})}),m.on("error",ne=>{clearTimeout(M),D=!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:A.length>0?A:void 0})})});return{process:m,result:p}}function ss(o,e){let n=o.trim()||"Claude CLI failed",t=`${e??""} ${n}`.toLowerCase();return t.includes("authentication_failed")||t.includes("not logged in")||t.includes("please run /login")||t.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:t.includes("model")&&(t.includes("not found")||t.includes("unknown")||t.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as as,spawnSync as ti}from"child_process";import{readFileSync as cs,statSync as ds}from"fs";import{basename as ls,extname as ps,isAbsolute as us,relative as ni,resolve as ms}from"path";import{createInterface as fs}from"readline";function Qo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Xo=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),ro=2e5,hs=1e5,oi=2e5;function ii(o){let e=ls(o).toLowerCase(),n=ps(o).toLowerCase();return Xo.has(n)||Xo.has(e)}function zt(o,e){let n=us(e)?e:ms(o,e),t=ni(o,n);return t===""||t.startsWith("..")?null:n}function hn(o,e){if(!ii(e))return;let n=zt(o,e);if(n)try{let t=ds(n);return t.isFile()?t.size>ro?{exists:!0,truncated:!0}:{exists:!0,content:cs(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function gs(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function ys(o){let e=o?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Yo(o){return gs(o,["patch","diff","unifiedDiff","unified_diff"])}function so(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Zo(o,e){let n=ti("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:oi+65536});return n.status!==0?null:n.stdout??""}function vs(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 i=t.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function ei(o){let e=Zo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Zo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=so(n,oi);return{status:e,changedFiles:vs(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Is(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function ws(o,e){if(!ii(e))return;let n=zt(o,e);if(!n)return;let t=ni(o,n);if(t===""||t.startsWith(".."))return;let i=ti("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:ro+65536});if(i.status!==0)return{exists:!1};let r=i.stdout??"",s=so(r,ro);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function bs(o,e,n){return e.map(t=>{let i=n.has(t)?n.get(t):ws(o,t),r=hn(o,t);return{filePath:t,...i?{before:i}:{},...r?{after:r}:{}}})}function gn(o,e){let{prompt:n,projectRoot:t,screenshotPath:i,resumeSessionId:r,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,b=[];if(r){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let x of l)b.push("-c",x);s&&b.push("-m",s),b.push(r),b.push(n),i&&b.push("--image",i)}else{b.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let x of l)b.push("-c",x);s&&b.push("-m",s),b.push(n),i&&b.push("--image",i)}let j=as("codex",b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),T=new Promise(x=>{let m,p=[],y=[],h=[],f=new Map,u=new Map,A=!1,D="",R=fs({input:j.stdout}),C=new Set;R.on("line",w=>{if(w.trim())try{let M=JSON.parse(w),F=M.type??"unknown";if(C.add(F),F==="thread.started"&&M.thread_id&&!m&&(m=M.thread_id),(F==="item.agentMessage.delta"||F==="item/agentMessage/delta")&&M.delta?.text&&(p.push(M.delta.text),c?.({type:"delta",jobId:o,text:M.delta.text},o)),(F==="item.reasoning.delta"||F==="item/reasoning/delta")&&M.delta?.text&&c?.({type:"thinking",jobId:o,text:M.delta.text},o),(F==="item.started"||F==="item/started")&&M.item){let H=M.item.type;if(H==="command_execution"){let U=M.item.command,ne=U?Qo(U):void 0,oe=ei(t),ye=new Map;for(let V of oe?.changedFiles??[])ye.set(V,hn(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(H==="file_change"){let U=M.item.filename||M.item.path;U&&!f.has(U)&&f.set(U,hn(t,U)),y.push(U?`Edit ${U.split("/").pop()}`:"Edit");let ne=U?zt(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...ne?{file:ne}:{}},o)}else if(H==="file_read"){let U=M.item.filename||M.item.path;y.push(U?`Read ${U.split("/").pop()}`:"Read");let ne=U?zt(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...ne?{file:ne}:{}},o)}else if(H==="web_search")y.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(H==="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((F==="item.completed"||F==="item/completed")&&M.item){if(M.item.type==="agent_message"){let H=M.item.text;typeof H=="string"&&H&&(p.push(H),c?.({type:"delta",jobId:o,text:H},o))}else if(M.item.type==="reasoning"){let H=M.item.text;typeof H=="string"&&H&&c?.({type:"thinking",jobId:o,text:H},o)}else if(M.item.type==="file_change"&&Array.isArray(M.item.changes))for(let H of M.item.changes){let U=H.path||H.filename,ne=H.kind==="add"?"Write":"Edit";if(U){y.push(`${ne} ${U.split("/").pop()}`);let oe=zt(t,U)??U;c?.({type:"tool_use",jobId:o,tool:ne,file:oe},o);let ye=H,Y=typeof ye.kind=="string"?ye.kind:void 0,V=ys(Y),q=f.get(U),ge=hn(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}:{},...Yo(ye)?{patch:Yo(ye)}:{},...Y?{rawKind:Y}:{}}),f.set(U,ge)}}else if(M.item.type==="command_execution"){let H=typeof M.item.id=="string"?M.item.id:void 0,U=H?u.get(H):void 0,ne=typeof M.item.command=="string"?M.item.command:U?.rawCommand,oe=ne?Qo(ne):U?.command,ye=ei(t);if(Is(U?.beforeWorktree,ye)){let Y=[...new Set([...U?.beforeWorktree?.changedFiles??[],...ye?.changedFiles??[]])],V=typeof M.item.aggregated_output=="string"?so(M.item.aggregated_output,hs):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:bs(t,Y,U?.beforeSnapshots??new Map)}:{}})}H&&u.delete(H)}}F==="turn.failed"&&(A=!0,D=M.error?.message||M.message||"Turn failed")}catch{}});let I=[];j.stderr?.on("data",w=>{I.push(w.toString())}),j.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&&(A=!0,D=I.join("")||`Codex process exited with code ${w}`),x({sessionId:m,text:p.join(""),success:!A,error:A?D:void 0,editEvents:h.length>0?h:void 0,toolsUsed:y.length>0?y:void 0})}),j.on("error",w=>{A=!0,D=w.message,x({sessionId:m,text:p.join(""),success:!1,error:D,editEvents:h.length>0?h:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:j,result:T}}import{spawn as xs}from"child_process";import{createInterface as Ss}from"readline";function ri(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 si(o,e){let{prompt:n,projectRoot:t,resumeSessionId:i,model:r,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];i&&l.push(`--resume=${i}`),r&&l.push("--model",r),l.push("-p",n);let b=xs(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),j=new Promise(T=>{let x,m=[],p=[],y=!1,h="",f=!1,u=setTimeout(()=>{f=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},s),A=Ss({input:b.stdout}),D=new Set,R=[];A.on("line",I=>{if(I.trim())try{let w=JSON.parse(I),M=qt(w);D.add(M),R.length<5&&ks(M)&&R.push(I.slice(0,800));let F=Ut(w,["sessionId","session_id","id"],["session","conversation","thread"]);F&&!x&&(x=F);let H=Rs(w,m.length===0);H&&(m.push(H),c?.({type:"delta",jobId:o,text:H},o));let U=Ps(w);U&&c?.({type:"thinking",jobId:o,text:U},o);let ne=Ts(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=js(w);oe&&(y=!0,h=oe)}catch{}});let C=[];b.stderr?.on("data",I=>{C.push(I.toString())}),b.on("close",I=>{clearTimeout(u),A.close(),m.length===0&&D.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...D].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?ri(h,r):null;T({sessionId:x,text:m.join(""),success:!y,error:w?.message,errorCode:w?.code,recoverableError:w?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),b.on("error",I=>{clearTimeout(u);let w=ri(I.message,r);T({sessionId:x,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:b,result:j}}function qt(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 Rs(o,e=!1){let n=qt(o).toLowerCase(),t=o.update,i=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&i?.type==="text"&&typeof i.text=="string")return i.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Fe(o.delta)??Fe(o.content)??Fe(o.message);if(n==="assistant.message"&&e)return Fe(o.message)??Fe(o.content)??Fe(o);if(n==="result"&&e)return Fe(o.result)??Fe(o.output)??Fe(o.message)??Fe(o);let r=o.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof o.text=="string"&&ao(o))return o.text;if(typeof o.message=="string"&&ao(o))return o.message;if(typeof o.delta=="string"&&ao(o))return o.delta}function Fe(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Fe).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Fe(e[n]);if(t)return t}}function ks(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function Ps(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 Ts(o){let e=Ut(o,["tool","toolName","tool_name","name"]),n=Ut(o,["command","cmd"]),t=Ut(o,["file","path","filename","filePath"]),i=qt(o);if(n||i.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&&(i.includes("file")||i.includes("write")||i.includes("edit"))){let r=i.includes("write")?"Write":i.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${t.split("/").pop()}`,file:t}}}function js(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"&&qt(o).toLowerCase().includes("error"))return o.message}function Ut(o,e,n=[]){for(let t of e){let i=o[t];if(typeof i=="string")return i}for(let[t,i]of Object.entries(o)){if(!i||typeof i!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let r=Ut(i,e);if(r)return r}}function ao(o){let e=qt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as As,readFile as Es}from"fs/promises";import{join as co}from"path";var yn=class{constructor(e){let n=co(e,".popmelt");this.decisionsDir=co(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 Es(co(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 ci(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]),i=Ns(t.assertionResults,e),r=Bs(i);return{status:r,summary:ot(t.summary)||ui(r),assertionResults:i,tooling:Fs(t.tooling)}}catch{}return{status:"needs_review",summary:Ls(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 di(o,e){let n=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length?[f.path]:[]),t=o.changes??[],i=n.length>0?n:t.map(f=>f.path),r=[...new Set(i.map(f=>f.map(String).join(".")).filter(Boolean))].map(f=>({kind:"model_path",value:f}));if(r.length===0||o.decisionIds.length===0)return[];let s=new Set(o.decisionIds),c=new Set(r.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,b=d?.id.startsWith("eval-model-")??!1,j=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length>0?[{path:f.path,value:f.value,label:f.label,detail:f.detail}]:[]),x=(j.length>0?j:t.map(f=>({path:f.path,value:f.value,label:f.label,detail:f.rationale}))).flatMap(f=>Ms(f,o.decisionIds)),m=In(o.underlyingClaim??o.summary),p=[...new Set([...d&&!b?d.assertions:[],...x,...x.length===0&&m?[m]:[]])],y=r[0].value,h=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!b?d.title:l,status:"pending",category:d?.category??h,prompt:d&&!b?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!b?d.rationale:$s(y),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...r].map(f=>[`${f.kind}:${f.value}`,f])).values()]}]}function Ms(o,e){let n=String(o.path[0]??"");if(n==="rules")return _s(o.value,e);if(n==="components"){let s=li(String(o.path[1]??o.label??"component")),c=vn(o.value),d=c?Gt(c.usage):[];if(d.length>0){let b=Ds(d),j=d.length===1?"uses":"use";return[`The ${b} ${j} 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 b=Cs(l,s);if(b)return[b]}}if(n==="tokens"){let s=o.path.slice(1).map(String).join("."),c=vn(o.value),d=c&&"value"in c?c.value:o.value,l=Os(d);if(s&&l)return[`The ${s} token resolves to ${l}.`]}let t=vn(o.value),i=t?ot(t.text)||ot(t.constraint):typeof o.value=="string"?o.value:"",r=In(i||o.detail||"");return r?[r]:[]}function _s(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(s=>{let c=vn(s),d=c?ot(c.text):"";return d?[{text:d,sources:c?Gt(c.sources):[]}]:[]}),i=t.filter(s=>s.sources.some(c=>n.has(c)));return(i.length>0?i:t.length===1?t:[]).map(s=>In(s.text)).filter(s=>!!s)}function Cs(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?kt(`Wherever ${Wt(n[1])}, the shared ${e} implementation is used instead of ${Wt(n[2])}`):In(o)}function lo(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return kt(`${ai(n[1])} is ${Wt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return kt(ai(t[1]));let i=e.match(/^Use (.+?)\.?$/i);if(i)return kt(`The product uses ${Wt(i[1])}`);let r=e.match(/^Do not (.+?)\.?$/i);return r?kt(`The product does not ${Wt(r[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":kt(e)}var In=lo;function $s(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${li(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 vn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function li(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 Os(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 ai(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Wt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function pi(o){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
|
|
34
34
|
|
|
35
35
|
## Eval
|
|
36
36
|
\`\`\`json
|
|
@@ -86,14 +86,14 @@ The block must be valid JSON with this shape:
|
|
|
86
86
|
\`\`\`
|
|
87
87
|
|
|
88
88
|
Allowed statuses: pass, fail, needs_review.
|
|
89
|
-
Allowed chromeDevtools values: available, unavailable, unknown.`}function tt(o){return typeof o=="string"?o.trim():""}function Wt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Mi(o){let e=tt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ai(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let s=r,i=tt(s.assertion);return i?{assertion:i,status:Mi(s.status)??"needs_review",summary:tt(s.summary)||ar("needs_review"),evidence:Wt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function _i(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Ci(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=tt(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Wt(e.evidenceTypes).length>0?Wt(e.evidenceTypes):["screenshot"]}}function ar(o){return o==="pass"?"The current page appears to satisfy this eval.":o==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function $i(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Oi}from"crypto";import{mkdir as Di,writeFile as Ji}from"fs/promises";import{join as io}from"path";var yn=class{constructor(e){this.root=io(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=io(this.root,"eval-screenshots"),t=Oi("sha256").update(e).digest("hex"),r=io(n,`${t}.webp`);return await Di(n,{recursive:!0}),await Ji(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as cr}from"crypto";import{mkdir as ao,readFile as co,writeFile as vn}from"fs/promises";import{dirname as lo,join as kt}from"path";var We="[ProjectionWorker]",Ni={version:1,runs:[]},Bi={version:1,updatedAt:0,proposals:[]},Fi=12;function Li(o){return Array.isArray(o)?o.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function dr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function zi(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ui(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let g of s){if(!g||typeof g!="object")continue;let p=g.sources;if(Array.isArray(p))for(let h of p)typeof h=="string"&&t.has(h)&&r.add(h)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,h=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(h)!==JSON.stringify(g)}).length,v=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(v[g])).length,I=Object.keys(c).filter(g=>JSON.stringify(c[g])!==JSON.stringify(R[g])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:I,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function qi(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Wi(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function wn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Wi(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=qi(n)}function lr(o,e){let n=o;for(let r=0;r<e.length-1;r++){let s=n[String(e[r])];if(!s||typeof s!="object")return;n=s}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Hi(o,e){if(!o)return{exists:!1};let n=o;for(let t of e){if(!n||typeof n!="object"||!(String(t)in n))return{exists:!1};n=n[String(t)]}return{exists:!0,value:n}}function Gi(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((n,t)=>JSON.stringify(n)===JSON.stringify(e[t])):!1}function pr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Hi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Gi(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var In=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=kt(e,".popmelt");this.runsPath=kt(t,"projection-runs.json"),this.legacyRunsPath=kt(t,"materialization-runs.json"),this.proposalsPath=kt(t,"projection-queue.json"),this.legacyProposalsPath=kt(t,"model-proposals.json"),this.modelPath=kt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await co(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Li(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let r=t.key.split(".");t.value===null?lr(n,r):wn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Fi),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let s=r.map(g=>g.id);console.log(`${We} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),c=Xi(r,i),d=zi(r,t.totalCandidateDecisionCount,c);n=cr().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:s,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let v=!0,R,b,I;try{let g=`projection-${Date.now()}`,{provider:p,result:h}=this.spawnModelAgent(g,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await h;if(!f.success)v=!1,R=f.error,console.error(`${We} ${p} spawn error:`,R);else{let y=Qi(f.text,s);if(y){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of y)wn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=dr(x.rules));let S=Ui(x,s,i);if(y){let J=[...new Set(y.flatMap(_=>_.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(_=>!J.includes(_))}b=S;let A=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:b,changes:y});I=A.id,console.log(`${We} Created model proposal ${A.id} for ${s.length} decision(s)`)}else v=!1,R="No valid bounded <model-changes> block found in response",console.error(`${We} ${R}`)}}catch(g){v=!1,R=g instanceof Error?g.message:String(g),console.error(`${We} Error:`,R)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:b,proposalId:I}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:v,error:R}),{processedIds:s,success:v,error:R,runId:n,proposalId:I}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=dr(e.rules)),await vn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await ao(lo(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2)),n):{...Ni,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(s=>s.authorityStatus==="accepted"&&Array.isArray(s.changes)&&s.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Bi,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let s=structuredClone(t);for(let i of r.changes??[])wn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?lr(i,d.path):wn(i,d.path,d.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let c=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(c.evalId),s.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:cr().slice(0,8),status:"pending",title:Vi(e.proposedModel),summary:e.outputStats?`Proposes ${e.outputStats.ruleCount} rule, ${e.outputStats.componentCount} component, and ${e.outputStats.tokenSectionCount} token change${e.outputStats.ruleCount+e.outputStats.componentCount+e.outputStats.tokenSectionCount===1?"":"s"} from ${e.decisionIds.length} accepted decision${e.decisionIds.length===1?"":"s"}.`:Ki(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(s=>s.id!==e?s:(r={...s,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await ao(lo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await vn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await ao(lo(this.runsPath),{recursive:!0}),await vn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await co(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await co(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return s==="codex"?{provider:"codex",...mn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:ln(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...pn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:s==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:i})})}};function Vi(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Ki(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Qi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,c)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let d=i;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(R=>typeof R=="string"||typeof R=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let v=Array.isArray(d.decisionIds)?d.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Xi(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
|
|
90
|
-
Kind: ${
|
|
91
|
-
Claim: ${
|
|
92
|
-
${
|
|
93
|
-
Subjects: ${
|
|
94
|
-
Authority: ${
|
|
89
|
+
Allowed chromeDevtools values: available, unavailable, unknown.`}function ot(o){return typeof o=="string"?o.trim():""}function Gt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Js(o){let e=ot(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ns(o,e){let t=(Array.isArray(o)?o:[]).map(i=>{if(!i||typeof i!="object")return null;let r=i,s=ot(r.assertion);return s?{assertion:s,status:Js(r.status)??"needs_review",summary:ot(r.summary)||ui("needs_review"),evidence:Gt(r.evidence)}:null}).filter(i=>i!==null);return t.length>0?t:e.map(i=>({assertion:i,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Bs(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:Gt(e.evidenceTypes).length>0?Gt(e.evidenceTypes):["screenshot"]}}function ui(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 Ls(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as zs}from"crypto";import{mkdir as Us,writeFile as qs}from"fs/promises";import{join as po}from"path";var wn=class{constructor(e){this.root=po(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=po(this.root,"eval-screenshots"),t=zs("sha256").update(e).digest("hex"),i=po(n,`${t}.webp`);return await Us(n,{recursive:!0}),await qs(i,e,{flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r}),i}};import{randomUUID as mi}from"crypto";import{mkdir as uo,readFile as mo,writeFile as bn}from"fs/promises";import{dirname as fo,join as Pt}from"path";var We="[ProjectionWorker]",Ws={version:1,runs:[]},Gs={version:1,updatedAt:0,proposals:[]},Hs=12;function Vs(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 fi(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(i=>typeof i=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function Ks(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Qs(o,e,n){let t=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let m of r){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)&&i.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=r.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,b=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},j=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},T=Object.keys(s).filter(m=>JSON.stringify(s[m])!==JSON.stringify(b[m])).length,x=Object.keys(c).filter(m=>JSON.stringify(c[m])!==JSON.stringify(j[m])).length;return{ruleCount:l,tokenSectionCount:T,componentCount:x,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(m=>!i.has(m))}}function Xs(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ys(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let i=typeof n=="number"?[]:{};return o[String(e)]=i,i}function xn(o,e,n){let t=o;for(let r=0;r<e.length-1;r++)t=Ys(t,e[r],e[r+1]);let i=e[e.length-1];t[String(i)]=Xs(n)}function hi(o,e){let n=o;for(let i=0;i<e.length-1;i++){let r=n[String(e[i])];if(!r||typeof r!="object")return;n=r}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Zs(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 ea(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 gi(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Zs(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?ea(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Sn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Pt(e,".popmelt");this.runsPath=Pt(t,"projection-runs.json"),this.legacyRunsPath=Pt(t,"materialization-runs.json"),this.proposalsPath=Pt(t,"projection-queue.json"),this.legacyProposalsPath=Pt(t,"model-proposals.json"),this.modelPath=Pt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await mo(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Vs(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let i=t.key.split(".");t.value===null?hi(n,i):xn(n,i,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Hs),n=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!n.has(i.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),i=t.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(m=>m.id);console.log(`${We} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=ia(i,s),d=Ks(i,t.totalCandidateDecisionCount,c);n=mi().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:r,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let b=!0,j,T,x;try{let m=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(m,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let h=await y;if(!h.success)b=!1,j=h.error,console.error(`${We} ${p} spawn error:`,j);else{let f=oa(h.text,r);if(f){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let R of f)xn(u,R.path,R.value);Array.isArray(u.rules)&&(u.rules=fi(u.rules));let A=Qs(u,r,s);if(f){let R=[...new Set(f.flatMap(C=>C.decisionIds))];A.coveredDecisionIds=R,A.uncoveredDecisionIds=r.filter(C=>!R.includes(C))}T=A;let D=await this.createModelProposal({decisionIds:r,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:T,changes:f});x=D.id,console.log(`${We} Created model proposal ${D.id} for ${r.length} decision(s)`)}else b=!1,j="No valid bounded <model-changes> block found in response",console.error(`${We} ${j}`)}}catch(m){b=!1,j=m instanceof Error?m.message:String(m),console.error(`${We} Error:`,j)}return await this.persistRun({...l,status:b?"proposed":"failed",completedAt:Date.now(),error:j,outputStats:T,proposalId:x}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:b,error:j}),{processedIds:r,success:b,error:j,runId:n,proposalId:x}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=fi(e.rules)),await bn(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 uo(fo(this.runsPath),{recursive:!0}),await bn(this.runsPath,JSON.stringify(n,null,2)),n):{...Ws,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let i=await this.readProposalStore(this.legacyProposalsPath);i&&(e={version:1,updatedAt:Date.now(),proposals:i.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Gs,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(t);for(let s of i.changes??[])xn(r,s.path,s.value);return{...i,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>i.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>t.createdAt-i.createdAt||t.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,n,t,i="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?hi(s,d.path):xn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:i,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let i=new Set(t.generatedEvalIds??[]),r=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;i.add(c.evalId),r.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...i],evalProjections:[...r.values()]})}async createModelProposal(e){let n={id:mi().slice(0,8),status:"pending",title:ta(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"}.`:na(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(i=>i.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),i=null;return t.proposals=t.proposals.map(r=>r.id!==e?r:(i={...r,...n,updatedAt:Date.now()},i)),i?(t.updatedAt=Date.now(),await this.persistModelProposals(t),i):null}async persistModelProposals(e){try{await uo(fo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...i})=>i)};await bn(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(i=>i.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await uo(fo(this.runsPath),{recursive:!0}),await bn(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 mo(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await mo(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,i){let r=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...gn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:mn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...fn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function ta(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function na(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,i=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function oa(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let i=new Set(e),r=t.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(j=>typeof j=="string"||typeof j=="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 b=Array.isArray(d.decisionIds)?d.decisionIds.filter(j=>typeof j=="string"&&i.has(j)):[];return b.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:b,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===t.length?r:null}catch{return null}}function ia(o,e){let n=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
90
|
+
Kind: ${r.kind}
|
|
91
|
+
Claim: ${r.claim}
|
|
92
|
+
${r.rationale?`Rationale: ${r.rationale}`:""}
|
|
93
|
+
Subjects: ${r.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
|
|
94
|
+
Authority: ${r.authority.level}/${r.authority.mode}`).join(`
|
|
95
95
|
|
|
96
|
-
`),t=o.map(
|
|
96
|
+
`),t=o.map(r=>r.id);return`You are extracting a local design model from accumulated design decisions.
|
|
97
97
|
|
|
98
98
|
## Instructions
|
|
99
99
|
1. Review the current model (if any) and the new decisions below.
|
|
@@ -165,75 +165,75 @@ Example:
|
|
|
165
165
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
166
166
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
167
167
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
168
|
-
Include property and bindings when the decision context has class-level evidence.`}var
|
|
169
|
-
`),n=[],t=null;for(let
|
|
170
|
-
`)}),t={name:
|
|
171
|
-
`)}),t=null):t&&t.bodyLines.push(
|
|
172
|
-
`)}),n}function
|
|
173
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
168
|
+
Include property and bindings when the decision context has class-level evidence.`}var Rn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let i of this.listeners)i(e,n,t)}cancelJob(e){let n=this.queue.findIndex(i=>i.id===e);if(n>=0){let[i]=this.queue.splice(n,1);return i?(i.status="cancelled",i.error="Cancelled by user",this.broadcast({type:"error",jobId:i.id,threadId:i.threadId,message:i.error,cancelled:!0,provider:i.provider,model:i.model},i.id,i.sourceId),i):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as ra}from"child_process";import{readFile as go}from"fs/promises";import{homedir as Pn}from"os";import{join as Be}from"path";var yo=/popmelt/i,sa=/chrome|devtools/i;function vt(){return{found:!1,name:null,scope:null,disabled:!1}}function Tt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Ht(o){for(let e of Object.keys(o))if(yo.test(e))return e;return null}async function kn(o){try{let e=await go(o,"utf-8");return JSON.parse(e)}catch{return null}}async function vo(o){let e=Pn(),n=await kn(Be(e,".claude.json"));if(n&&typeof n=="object"){let i=n;if(i.mcpServers&&typeof i.mcpServers=="object"){let r=Ht(i.mcpServers);if(r)return Tt(r,"user")}if(i.projects&&typeof i.projects=="object"){let s=i.projects[o];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Ht(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(b=>yo.test(b));return Tt(d,"project",l)}}}}}let t=await kn(Be(o,".mcp.json"));if(t&&typeof t=="object"){let i=t;if(i.mcpServers&&typeof i.mcpServers=="object"){let s=Ht(i.mcpServers);if(s){let c=await yi(o,s);return Tt(s,"mcp.json",c)}}let r=Ht(i);if(r&&r!=="mcpServers"){let s=await yi(o,r);return Tt(r,"mcp.json",s)}}return vt()}async function yi(o,e){let n=Be(o,".claude","settings.local.json"),t=await kn(n);if(t&&typeof t=="object"){let i=t;if(Array.isArray(i.disabledMcpjsonServers))return i.disabledMcpjsonServers.some(r=>r===e)}return!1}var aa=/^\[mcp_servers\.([^\]]+)\]/;function ca(o){return o.replace(/^"(.+)"$/,"$1")}function da(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function Ii(o){let e=o.split(`
|
|
169
|
+
`),n=[],t=null;for(let i of e){let r=i.match(aa);r?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
170
|
+
`)}),t={name:r[1],bodyLines:[]}):i.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
171
|
+
`)}),t=null):t&&t.bodyLines.push(i)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
172
|
+
`)}),n}function wi(o){return/enabled\s*=\s*false/i.test(o)}async function Io(o){let e=process.env.CODEX_HOME||Be(Pn(),".codex"),n=await vi(Be(e,"config.toml"),"user");if(n.found)return n;let t=await vi(Be(o,".codex","config.toml"),"project");return t.found?t:vt()}async function la(o,e){let n=process.env.CODEX_HOME||Be(Pn(),".codex"),t=new Set;for(let i of[Be(n,"config.toml"),Be(o,".codex","config.toml")])try{let r=await go(i,"utf-8");for(let s of Ii(r)){if(da(s.name)||wi(s.body))continue;let c=ca(s.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function bi(o){return la(o,sa)}async function wo(o,e="copilot"){let n=await pa(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Be(Pn(),".copilot"),i=await ho(Be(t,"mcp-config.json"),"user");if(i.found)return i;let r=await ho(Be(o,".mcp.json"),"mcp.json");if(r.found)return r;let s=await ho(Be(o,".github","mcp.json"),"mcp.json");return s.found?s:vt()}async function pa(o){try{let e=await new Promise((n,t)=>{ra(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return xi(JSON.parse(e),"user")}catch{return vt()}}async function ho(o,e){let n=await kn(o);return xi(n,e)}function xi(o,e){if(!o||typeof o!="object")return vt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,i=Ht(t);return i?Tt(i,e):vt()}async function vi(o,e){try{let n=await go(o,"utf-8"),t=Ii(n);for(let i of t)if(yo.test(i.name)){let r=wi(i.body);return Tt(i.name,e,r)}}catch{}return vt()}import{execFile as Si}from"child_process";import{mkdir as ua,readFile as Ri,writeFile as ki}from"fs/promises";import{homedir as Pi}from"os";import{dirname as ma,join as bo}from"path";var xo="https://mcp.popmelt.com/mcp";async function Ti(o=xo){let e=bo(Pi(),".claude.json"),n;try{let i=await Ri(e,"utf-8");n=JSON.parse(i)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let i of Object.keys(t))if(/popmelt/i.test(i))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await ki(e,JSON.stringify(n,null,2)+`
|
|
173
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function ji(o=xo){let e=process.env.CODEX_HOME||bo(Pi(),".codex"),n=bo(e,"config.toml"),t;try{t=await Ri(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await ua(ma(n),{recursive:!0});let i=`
|
|
174
174
|
[mcp_servers.popmelt]
|
|
175
175
|
url = "${o}"
|
|
176
|
-
`;return await Ir(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Pr(o=vo,e="copilot"){let n=await aa(e);if(ca(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{vr(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},s=>{if(s){r(s);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function aa(o){try{let e=await new Promise((n,t)=>{vr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return JSON.parse(e)}catch{return null}}function ca(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var Pn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),s={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,s),s}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as To,readFile as Mt,writeFile as jo}from"fs/promises";import{join as lt}from"path";var da=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function wo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function kn(o){return new Set(wo(o).split(" ").filter(e=>e.length>2&&!da.has(e)))}function kr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function la(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function pa(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(wo).filter(Boolean),s=kn([e.action,e.text].filter(Boolean).join(" "));for(let i of o){if(t.has(i.id)){n.set(i.id,{subjectId:i.id,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of la(i)){let l=wo(d.value);for(let b of r){let I=l===b?95:l.includes(b)||b.includes(l)?75:0;I>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:I>=90?"exact":"strong",matchedBy:d.by,score:I})}let R=["/","#","[","]","="].some(b=>d.value.includes(b))?0:Math.round(kr(kn(l),s)*55);R>=30&&R>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}c&&n.set(i.id,c)}return n}function ua(o,e){let n=new Set(o.sourceRefs.filter(i=>i.kind==="iteration").map(i=>i.id)),t=new Set(o.sourceRefs.filter(i=>i.kind==="thread").map(i=>i.id)),r=e.filter(i=>i.iterationIds.some(c=>n.has(c))||i.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let s=new Set(r.map(i=>i.state));return{state:s.size>1?"mixed":s.has("completed")?"completed":"attempted",attemptIds:r.map(i=>i.id)}}function ma(o){return Math.ceil(JSON.stringify(o).length/4)}function Io(o,e){let n=o.records.filter(h=>h.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(h=>{if(h.recordType!=="proposal"||r&&!r.has(h.id))return!1;if(h.state==="pending")return!0;if(h.state!=="deferred")return!1;let f=[...o.events].reverse().find(y=>y.entity.entityType==="proposal"&&y.entity.entityId===h.id&&y.toState==="deferred"&&y.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(h=>h.recordType==="implementation_attempt"),c=pa(n,e),d=[...c.values()].sort((h,f)=>f.score-h.score),l=kn([e.action,e.text].filter(Boolean).join(" ")),v=s.flatMap(h=>{let f=h.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),y=Math.max(0,...f.map(A=>A.score)),x=Math.round(kr(kn(h.claim),l)*35),S=y+x;return S>=50?[{proposal:h,proposalMatches:f,score:S}]:[]}).sort((h,f)=>f.score-h.score||h.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),I=[],g=0;for(let h of v){if(I.length>=R)break;let f=h.proposal.sourceRefs.slice(0,4),y={contractVersion:1,packetId:`review:${h.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:h.proposalMatches.length?`Historical proposal intersects ${h.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:h.proposalMatches.map(({score:S,...A})=>A)},proposal:{id:h.proposal.id,claim:h.proposal.claim,state:h.proposal.state,proposedKind:h.proposal.proposedKind,subjectIds:h.proposal.subjects.map(S=>S.subjectId),origin:h.proposal.origin.mode},authority:"unaccepted",presentation:h.score>=100&&["constraint","rule"].includes(h.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ua(h.proposal,i),evidence:{sourceCount:h.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:h.proposal.id},...f]},x={...y,estimatedTokens:ma(y)};if(g+x.estimatedTokens>b)break;I.push(x),g+=x.estimatedTokens}let p=Math.max(0,v.length-I.length);return{packets:I,subjectMatches:d.map(({score:h,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:p,maxEstimatedTokens:b,estimatedTokens:g},uncertainty:c.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var fa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function bo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Rn(o){return new Set(bo(o).split(" ").filter(e=>e.length>2&&!fa.has(e)))}function Rr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ha(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(bo).filter(Boolean),r=Rn([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=bo(l.value);for(let I of t){let g=v===I?95:v.includes(I)||I.includes(v)?75:0;g>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let b=["/","#","[","]","="].some(I=>l.value.includes(I))?0:Math.round(Rr(Rn(v),r)*55);b>=30&&b>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}c&&s.push(c)}return s.sort((i,c)=>c.score-i.score||i.subjectId.localeCompare(c.subjectId))}function ga(o){return Math.ceil(JSON.stringify(o).length/4)}function Tt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ya(o,e){let n=e.filter(s=>s.coverageClaims.some(i=>i.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(s=>s.state==="completed"),r=t.some(s=>s.coverageClaims.some(i=>i.decisionId===o&&i.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(s=>s.id)}}function va(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),s=t[0],i=r?"stale":s?s.state==="passed"?"passing":s.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(s.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:i,attemptIds:t.map(c=>c.id)}}function Tr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(_=>_.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(_=>_.recordType==="decision"&&_.state==="active"),c=s?i.filter(_=>s.has(_.id)):i,d=o.records.filter(_=>_.recordType==="implementation_attempt"),l=o.records.filter(_=>_.recordType==="verification_attempt"),v=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),R=o.records.filter(_=>_.recordType==="evidence"),b=o.records.filter(_=>_.recordType==="model_entry"),I=[...o.records].reverse().filter(_=>_.recordType==="eval_spec").filter((_,N,T)=>T.findIndex(B=>B.legacyId===_.legacyId)===N),g=ha(r,e),p=new Map(g.map(_=>[_.subjectId,_.score])),h=Rn([e.action,e.text].filter(Boolean).join(" ")),f=c.flatMap(_=>{let N=Math.max(0,..._.subjects.map(W=>p.get(W.subjectId)??0)),T=Math.round(Rr(Rn(_.claim),h)*35),B=N+T;return B>=50?[{decision:_,score:B}]:[]}).sort((_,N)=>N.score-_.score||_.decision.id.localeCompare(N.decision.id)),y=new Map;for(let _ of f.slice(0,t))y.set(_.decision.id,_.decision);for(let _ of o.relationships){if(!Tt(_,"excepts")&&!Tt(_,"contradicts"))continue;let N=i.find(B=>B.id===_.from.entityId),T=i.find(B=>B.id===_.to.entityId);!N||!T||!y.has(N.id)&&!y.has(T.id)||(y.size<t&&y.set(N.id,N),y.size<t&&y.set(T.id,T))}let x=[...y.values()],S=_=>_.from.entityType==="decision"&&_.to.entityType==="decision"&&y.has(_.from.entityId)&&y.has(_.to.entityId),A=(_,N=!1)=>{let T=new Set(_.map(M=>M.id)),B=v.filter(M=>M.target.entityType==="decision"&&T.has(M.target.entityId)),W=new Set(o.relationships.filter(M=>Tt(M,"excepts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).flatMap(M=>[M.from.entityId,M.to.entityId])),H=o.relationships.filter(M=>Tt(M,"contradicts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).map(M=>({id:M.id,decisionIds:[M.from.entityId,M.to.entityId],unresolvedQuestion:M.reason,expansionRefs:[{kind:"record",id:M.id}]})),te=new Set(H.flatMap(M=>M.decisionIds)),ne=R.filter(M=>M.sourceRefs.some(Y=>Y.kind==="record"&&T.has(Y.id))||o.relationships.some(Y=>Y.relationshipType==="supports"&&Y.from.entityType==="evidence"&&Y.from.entityId===M.id&&Y.to.entityType==="decision"&&T.has(Y.to.entityId))),ge=Math.max(0,f.length-_.length),X=o.relationships.some(M=>Tt(M,"contradicts")&&S(M)&&(!T.has(M.from.entityId)||!T.has(M.to.entityId))),G=N||ge>0||X,U=[];g.length===0&&(e.subjectHints?.length??0)>0?U.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):_.length===0&&U.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),H.length&&U.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.flatMap(M=>M.expansionRefs)}),ne.some(M=>M.availability!=="available")&&U.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:ne.map(M=>({kind:"record",id:M.id}))}),G&&U.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let he={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:g.map(({score:M,...Y})=>Y),modelEntries:b.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,key:M.key,value:M.value,decisionIds:M.decisionIds})),evalSpecs:I.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,legacyId:M.legacyId,state:M.state,title:M.title,assertionCount:M.assertions.length,decisionIds:M.decisionIds,expansionRef:{kind:"record",id:M.id}})),decisions:_.map(M=>({id:M.id,kind:M.kind,claim:M.claim,subjectIds:M.subjects.map(Y=>Y.subjectId),authority:M.authority,effectiveState:te.has(M.id)?"conflicted":W.has(M.id)?"excepted":"active",freshness:B.filter(Y=>Y.target.entityId===M.id).map(Y=>Y.signalType),expansionRef:{kind:"record",id:M.id}})),conflicts:H,uncertainties:U,implementation:_.map(M=>ya(M.id,d)),verification:_.map(M=>va(M.id,l,B)),evidence:ne.map(M=>({evidenceId:M.id,summary:M.summary,availability:M.availability,sourceRefs:M.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:ge,omittedEvidenceCount:0,conflictsComplete:!X}};return he.budget.estimatedTokens=ga(he),he},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>Tt(T,"contradicts")&&(T.from.entityId===_.id||T.to.entityId===_.id)).flatMap(T=>[T.from.entityId,T.to.entityId]);x=x.filter(T=>!N.includes(T.id)),J=A(x,!0)}return J}var wa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function jt(o){return wa.test(o)}function Ia(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ce(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function xo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){jt(n)||ce(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function dt(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ce(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function vt(o,e,n,t=!1){t&&n.level==="contributor"&&ce(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ce(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ba={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},xa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Sa(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),dt(o,`${n}.createdAt`,e.createdAt),vt(o,`${n}.authority`,e.authority);let t=ba[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ce(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let s=`${e.entity.entityType}:${e.toState}`;if(xa.has(s)&&(vt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ce(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let i=e.transitionContext;(i?.kind!=="proposal_deferral"||i.resurfaceWhen.length===0)&&ce(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),i?.resurfaceWhen.includes("after_date")&&!i.revisitAfter&&ce(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),i?.revisitAfter&&dt(o,`${n}.transitionContext.revisitAfter`,i.revisitAfter)}}function Pa(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),dt(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ce(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ce(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ce(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ce(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(vt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ce(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&xo(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ce(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(dt(o,`${n}.appliedAt`,e.appliedAt),vt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ce(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&ce(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ce(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&xo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&xo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ka(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),dt(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ce(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)&&((e.from.entityType!=="decision"||e.to.entityType!=="decision")&&ce(o,n,"invalid_normative_relationship","Normative relationships connect decisions to decisions."),e.authority?vt(o,`${n}.authority`,e.authority,!0):ce(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context.")),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ce(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&ce(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ce(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function wt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),dt(e,"manifest.createdAt",o.manifest.createdAt),dt(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,h)=>{let f=n.get(p);f?ce(e,h,"duplicate_id",`ID is already used at ${f}.`):n.set(p,h)};o.records.forEach((p,h)=>{let f=`records[${h}]`;t(p.id,f),Pa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,h)=>{let f=`events[${h}]`;t(p.id,f),Sa(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,h)=>{let f=`relationships[${h}]`;t(p.id,f),ka(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,h)=>{t(p.id,`artifacts[${h}]`),Te(e,`artifacts[${h}].id`,p.id)}),o.tombstones.forEach((p,h)=>{let f=`tombstones[${h}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),dt(e,`${f}.deletedAt`,p.deletedAt),vt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,h)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,h,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,h)=>i(p.entity,`events[${h}].entity`)),o.relationships.forEach((p,h)=>{i(p.from,`relationships[${h}].from`),i(p.to,`relationships[${h}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,h)=>{c.has(p)||ce(e,h,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,h,f)=>{!r.has(`${p}:${h}`)&&!s.has(`${p}:${h}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,h)=>{let f=`records[${h}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((y,x)=>l("subject",y,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((y,x)=>d(y,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((y,x)=>l("subject",y.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((y,x)=>d(y,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((y,x)=>i(y,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((y,x)=>l("thread",y,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((y,x)=>l("iteration",y,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((y,x)=>d(y,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((y,x)=>{y.kind==="subject"&&y.subjectId&&l("subject",y.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((y,x)=>{y.subjectIds?.forEach((S,A)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${A}]`))}),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((y,x)=>l(y.entityType,y.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((y,x)=>l("subject",y,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`));break;case"model_projection":vt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((y,x)=>l("decision",y,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((y,x)=>l("model_entry",y,`${f}.entryIds[${x}]`)),p.coverage.forEach((y,x)=>l("decision",y.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((y,x)=>l("evidence",y,`${f}.evidenceIds[${x}]`));break;default:break}});let v=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),b=new Map;o.events.forEach((p,h)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,y=b.get(f)??new Set;y.add(p.toState),b.set(f,y),y.size>1&&ce(e,`events[${h}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let I=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,h,f,y,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=I.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==h||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(f);(A<Date.parse(S.startsAt)||S.endsAt&&A>Date.parse(S.endsAt)||S.revokedAt&&A>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&y.length&&!y.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(h=>h.subjectId),`records:${p.id}.authority`);o.events.forEach((p,h)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),y=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,y,`events[${h}].authority`)}),o.relationships.forEach((p,h)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(y=>{let x=R.get(`${y.entityType}:${y.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${h}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let h=v.get(p.acceptanceEventId);(!h||h.entity.entityType!=="proposal"||h.entity.entityId!==p.proposalId||h.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),h&&h.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(y=>y.relationshipType==="supersedes"&&y.to.entityType==="decision"&&y.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(y=>y.entity.entityType==="decision"&&y.entity.entityId===p.id&&y.toState==="revoked"&&!!y.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ia(e)}function Gt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function jr(o,e,n,t,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Ra(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function Tn(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),jt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of Ra(e))jt(s)||n.push({code:"invalid_generated_id",message:`${s} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=jr(o,t,e,s.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:i.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let s={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},i={...Gt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Gt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=jr(o,s,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,d],events:[i,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ta}from"crypto";import{readFile as ja,readdir as Ea,realpath as Ma}from"fs/promises";import{join as Vt,relative as Aa}from"path";var _a=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Et(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Le(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Er(...o){return o.find(e=>!!e?.trim())?.trim()}function ye(o,e,n,t){let s=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),i=Ta("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${c}${i.slice(4,7)}-${i.slice(7,19)}`}async function So(o,e){try{return JSON.parse(await ja(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Ca(o){let e=Et(o);if(!e)return 0;let n=0,t=r=>{let s=Et(r);if(!s){n+=1;return}for(let i of Object.values(s))t(i)};for(let r of Object.values(e))t(r);return n}function $a(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Kt(o){let e=[],n=await Ma(o.projectRoot).catch(()=>o.projectRoot),t=Vt(n,".popmelt"),r=await So(Vt(t,"threads.json"),e),s=await So(Vt(t,"model.json"),e),i=Et(r),c=Et(i?.threads)??{},d=Object.entries(c).map(([M,Y])=>({key:M,value:Et(Y)})).filter(M=>!!M.value),l=Vt(t,"decisions"),v=await Ea(l).catch(()=>[]),R=[];for(let M of v.filter(Y=>Y.endsWith(".json")).sort()){let Y=Et(await So(Vt(l,M),e));Y&&R.push({file:M,value:Y})}let b=d.flatMap(({value:M})=>[M.createdAt,M.updatedAt]).filter(M=>typeof M=="number"&&Number.isFinite(M)),I=b.length?Math.min(...b):0,g=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ye(g,"project",g,I),h=ye(g,"participant","legacy-owner",I),f=ye(g,"participant","legacy-agent",I),y=ye(g,"subject","project",I),x=Le(Math.max(I,...b)),S=[],A=[],J=new Map,_=new Map,N=new Map(R.map(M=>[M.value.id??M.file.replace(/^d-|\.json$/g,""),M.value])),T=new Map,B=(M,Y,ue,ie,De)=>{let Je=J.get(ue);if(Je)return Je;let Pe=ye(g,"artifact",M,ie);return A.push({id:Pe,kind:Y,mediaType:De,location:ue,availability:"available"}),J.set(ue,Pe),Pe};for(let{file:M,value:Y}of R){let ue=Y.id??M.replace(/^d-|\.json$/g,""),ie=Y.createdAt??I,De=[B(`${ue}:envelope`,"other",`.popmelt/decisions/${M}`,ie,"application/json")];Y.screenshotPath&&De.push(B(`${ue}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,ie,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Je,Pe]of(Y.pastedImagePaths??[]).entries())De.push(B(`${ue}:image:${Je}`,"image",Pe,ie));T.set(ue,De)}let W=(M,Y,ue)=>({id:M,schemaVersion:1,projectId:p,createdAt:x,participantId:Y,sourceRefs:ue}),ee=(M,Y)=>{S.push(Y);let ue=_.get(M)??[];ue.push(Y.id),_.set(M,ue)},H=[{...W(h,h,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...W(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...H),S.push({...W(y,h,[]),recordType:"subject",subjectType:"project",label:Aa(process.cwd(),n)||n,aliases:[],locators:[{id:ye(g,"locator",n,I),kind:"project_root",value:n,status:"current",validFrom:Le(I),sourceRefs:[]}]});let te=new Map,ne=(M,Y)=>{let ue=te.get(M);if(ue)return ue;let ie=ye(g,"subject",M,Y),De={...W(ie,h,[{kind:"external",id:M}]),createdAt:Le(Y),recordType:"subject",subjectType:"element",label:M,aliases:[],locators:[{id:ye(g,"locator",M,Y),kind:"dom_selector",value:M,status:"current",validFrom:Le(Y),sourceRefs:[{kind:"external",id:M}]}]};return S.push(De),te.set(M,ie),ie};for(let{key:M,value:Y}of d){let ue=Y.id??M,ie=Y.createdAt??I,De=ye(g,"thread",ue,ie),Je={kind:"thread",id:ue},Pe=[],Ue=[],Ge=Array.isArray(Y.messages)?Y.messages:[],Ye,rt,ut=0;Ge.forEach((we,st)=>{let Ae=we.timestamp??ie,Ze=ye(g,"artifact",`${ue}:message:${st}`,Ae);if(Pe.push(Ze),A.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${st}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${ue}/messages/${st}`,Ze),we.screenshotPath&&B(`${ue}:message:${st}:screenshot`,"screenshot",we.screenshotPath,Ae),we.role==="human"){Ye=we;let je=we.feedbackSummary??we.replyToQuestion;if(je?.trim()){let Ne=ye(g,"observation",`${ue}:${st}`,Ae),ct=Y.elementIdentifiers??[],St={...W(Ne,h,[Je,{kind:"message",id:Ze}]),createdAt:Le(Ae),recordType:"observation",state:"open",statement:je,captureContext:{subjectIds:ct.map(ft=>ne(ft,ie)),artifactIds:[Ze]},resolvedByIds:[]};ee(ue,St),rt=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let it=we.jobId??`${ue}:${st}`,at=ye(g,"iteration",it,Ae),mt=N.get(it),Yn=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",Zn={...W(at,f,[Je,{kind:"message",id:Ze},...(T.get(it)??[]).map(je=>({kind:"artifact",id:je}))]),createdAt:Le(Ae),recordType:"iteration",threadIds:[De],startedAt:Le(Ye?.timestamp,Ae),completedAt:Le(Ae),requestSummary:Er(Ye?.feedbackSummary,Ye?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:Yn,execution:{provider:we.provider??mt?.provider,model:we.model??mt?.model,sessionId:we.sessionId??mt?.sessionId},artifactIds:[Ze,...T.get(it)??[]]};ee(ue,Zn),Ue.push({entityType:"iteration",entityId:at});let Bt=we.resolutions??mt?.resolutions??[];for(let[je,Ne]of Bt.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let ct=Y.elementIdentifiers??[],St=(ct.length?ct:[n]).map(cn=>({subjectId:cn===n?y:ne(cn,ie),role:"governed"})),ft=ye(g,"proposal",`${it}:${Ne.annotationId??"resolution"}:${je}`,Ae),eo={...W(ft,f,[Je,{kind:"iteration",id:at}]),createdAt:Le(Ae),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:St,subjectSemantics:St.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Er(Ye?.feedbackSummary,Ye?.replyToQuestion,Ne.summary),iterationId:at,inferredById:f}};ee(ue,eo),Ue.push({entityType:"proposal",entityId:ft}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${ft} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Bt.some(je=>je.status==="resolved")||mt?.gitDiff){let je=ye(g,"implementation",it,Ae),Ne={...W(je,f,[Je,{kind:"iteration",id:at}]),createdAt:Le(Ae),recordType:"implementation_attempt",state:"completed",iterationIds:[at],coverageClaims:[],summary:Bt.map(ct=>ct.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};ee(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:je}),ut+=1}rt&&(rt=void 0)});let Jt=Ge.at(-1),Nt={...W(De,h,[Je]),createdAt:Le(ie),recordType:"thread",state:Jt?.question?"open":"resolved",messageArtifactIds:Pe,outcome:Jt?.question?"question_unresolved":ut?"implementation_only":"no_outcome",resultRefs:Ue};S.push(Nt),_.set(ue,[De,..._.get(ue)??[]])}let ge=Ca(s);ge&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ge} model values were not promoted because their accepted decision provenance is unresolved.`});let X={manifest:{formatVersion:1,projectId:p,createdAt:Le(I),updatedAt:x,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:S,events:[],relationships:[],artifacts:A,tombstones:[]},G=wt(X),he=(o.proofCaseIds??_a).map(M=>({legacyId:M,threadFound:d.some(({key:Y,value:ue})=>(ue.id??Y)===M),decisionEnvelopeFound:N.has(M),recordIds:_.get(M)??[]}));return{bundle:X,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((M,Y)=>M+(Y.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:ge,artifactsReferenced:A.length},imported:$a(S),unresolvedAcceptance:e.filter(M=>M.code==="acceptance_unresolved").length,deferredModelEntries:ge,proofCases:he,issues:e,schemaIssues:G.issues}}}import{createHash as Oa}from"crypto";import{mkdir as Mr,open as Po,readFile as ko,readdir as Da,rename as Ja,unlink as Ro}from"fs/promises";import{join as nt}from"path";var Na={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function En(o){return Oa("sha256").update(JSON.stringify(o)).digest("hex")}function Ar(o){return En(o)}function _r(o,e,n){for(let t of e.projectionUpdates){let r=o.records.find(s=>s.recordType===t.entityType&&s.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Ba(o,e,n){return _r(structuredClone(o),e,n)}async function It(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Po(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
177
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ja(n,o)}catch(r){throw await Ro(n).catch(()=>{}),r}}async function jn(o){return JSON.parse(await ko(o,"utf8"))}var Mn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=nt(e,".popmelt","memory"),this.journalDir=nt(this.memoryDir,"journal"),this.manifestPath=nt(this.memoryDir,"manifest.json"),this.checkpointPath=nt(this.memoryDir,"checkpoint.json"),this.lockPath=nt(this.memoryDir,"writer.lock")}async initialize(e){let n=wt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Mr(this.journalDir,{recursive:!0});try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await ko(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}let t=En(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},s={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await It(this.checkpointPath,r),await It(this.manifestPath,s)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await It(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=En(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await It(nt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await It(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!jt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,s={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},i={...s,hash:Ar(s)},c=Ba(t.bundle,e,n.committedAt),d=wt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await It(nt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await It(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:i.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Na,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await jn(this.manifestPath),n=await jn(nt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==En(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Da(this.journalDir),r=t.filter(b=>b.endsWith(".tmp")),i=t.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,v=new Set;for(let b of i){let I=await jn(nt(this.journalDir,b)),{hash:g,...p}=I;if(g!==Ar(p))throw new Error(`Journal hash mismatch: ${b}`);if(I.sequence!==d+1)throw new Error(`Journal sequence gap at ${b}`);if(I.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(I.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(v.has(I.transactionId))throw new Error(`Duplicate transaction ID: ${I.transactionId}`);_r(c,I.mutation,I.committedAt),d=I.sequence,l=I.hash,v.add(I.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=wt(c);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:c,manifest:e,transactionIds:v,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Mr(this.memoryDir,{recursive:!0});let n;try{n=await Po(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await jn(this.lockPath).catch(()=>({})),s=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(i){s=i.code!=="ESRCH"}if(s)throw new Error("Memory journal is locked by another writer.");await Ro(this.lockPath),n=await Po(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Ro(this.lockPath).catch(()=>{})}}};import{randomBytes as Fa}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Fa(10).toString("hex"),r=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${r}${t.slice(4,7)}-${t.slice(7,19)}`}var La=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Cr(o,e){let n=o.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active"),t=o.records.find(x=>x.recordType==="participant"&&x.kind==="ai"&&x.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,s=`${e.threadId}:${e.jobId}`,i=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=La(),l=d.records,v=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));v||(v={id:ye(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(x=>x.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(v));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"element",label:x,aliases:[],locators:[{id:ye(r,"live-locator",x,e.createdAt),kind:"dom_selector",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}for(let x of[...new Set((e.filePaths??[]).filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.kind==="source_file"&&J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-file-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"file",label:x,aliases:[],locators:[{id:ye(r,"live-file-locator",x,e.createdAt),kind:"source_file",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}let b=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),I;if(b.length>0){I=ye(r,"live-observation",s,e.createdAt);let x={id:I,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds:R.map(S=>S.id),artifactIds:[]},resolvedByIds:[]};l.push(x)}let g=ye(r,"live-iteration",s,e.completedAt),p={id:g,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...I?[{kind:"record",id:I}]:[]],recordType:"iteration",threadIds:[v.id],startedAt:i,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let h=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),y=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(b.length>0&&y.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of b.entries()){let A=ye(r,"live-proposal",`${s}:${x}`,e.completedAt),J=y.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:S.claim.trim(),rationale:S.rationale?.trim()||void 0,proposedKind:S.proposedKind,subjects:J,subjectSemantics:J.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:S.sourceText?.trim()||e.requestSummary,iterationId:g,inferredById:t.id}};l.push(_),h.push(A)}if(f.length>0){let x=new Set(e.governingDecisionIds??[]),S=o.records.filter(J=>J.recordType==="decision"&&J.state==="active"&&x.has(J.id)),A={id:ye(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:g}],recordType:"implementation_attempt",state:"completed",iterationIds:[g],coverageClaims:S.map(J=>({decisionId:J.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(_=>_.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:d,iterationId:g,proposalIds:h,observationId:I}}import{createHash as za}from"crypto";import{mkdir as Ua,open as qa,readFile as Wa,rename as Ha,unlink as Ga}from"fs/promises";import{join as $r}from"path";function Or(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dr(o){return za("sha256").update(JSON.stringify(o)).digest("hex")}async function Va(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await qa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ha(n,o)}catch(r){throw await Ga(n).catch(()=>{}),r}}function Ka(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(d,l,v)=>{let R=d[l]??=[];R.includes(v)||R.push(v)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Or(v);R&&i(t,R,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)i(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)i(s,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...c,checksum:Dr(c)}}function Jr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Or(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var An=class{constructor(e){this.indexDir=$r(e,".popmelt","memory","indexes"),this.indexPath=$r(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Wa(this.indexPath,"utf8")),{checksum:s,...i}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&s===Dr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ka(e,n);return await Ua(this.indexDir,{recursive:!0}),await Va(this.indexPath,t),t}};var _n=class{constructor(e){this.projectRoot=e;this.store=new Mn(e),this.indexStore=new An(e),this.manifestPath=lt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Mt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Kt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Kt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"legacy-evals-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(s.runs)?s.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:r.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:r.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=lt(this.projectRoot,".popmelt","memory","migrations"),n=lt(e,"imprint-evidence-v1.json");try{let s=JSON.parse(await Mt(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await Mt(lt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=0;for(let s of t.explanations){let i=s.evidence.length?s.evidence:[{id:s.id,kind:"observation",stance:"supports",summary:s.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:s.createdAt}];for(let c of i){let d=c.kind==="confirmation"?"confirm":c.kind==="correction"||c.kind==="rejection"?"reason_wrong":c.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:c.id,kind:d?"strengthened":"added",title:s.statement.slice(0,120),detail:c.summary,changes:[{explanationId:s.id,action:d==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:c.threadId,jobId:c.jobId,action:d,occurredAt:c.createdAt}),r+=1}}return await To(e,{recursive:!0}),await jo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:t.explanations.length,evidence:r,source:".popmelt/imprint (linked projection)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:r}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Io(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Tr(t.bundle,r),reviewSelection:Io(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Tn(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Kt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=Tn(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},d=e.action==="accept"?{...c,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:le(s),reason:e.reason}:{...c,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=Tn(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(v);let R=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:v.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Cr(n.bundle,e),r=ye(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let s=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(s),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:s.report.headSequence}}catch(s){if(s instanceof Error&&s.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw s}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active"),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="ai"&&b.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(b=>b.recordType==="subject"&&b.subjectType==="project");if(!s||!i)return;let c=e.occurredAt??new Date().toISOString(),d=Date.parse(c),l=[],v=[];for(let b of e.summary.changes){let I={kind:"external",id:b.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(h=>h.recordType==="observation"&&h.sourceRefs.some(f=>f.kind==="external"&&f.id===b.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:b.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),v.push({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ye(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,d);try{let b=await this.store.commit({records:l,events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:c});await this.refreshIndex(b)}catch(b){if(!(b instanceof Error)||!b.message.includes("Transaction already exists"))throw b}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="model_projection"&&i.state==="applied"?i.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(i=>i.relationshipType==="contradicts"&&i.from.entityType==="decision"&&i.to.entityType==="decision"?[i.from.entityId,i.to.entityId]:[])),s=new Set(n.records.flatMap(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.target.entityType==="decision"?[i.target.entityId]:[]));return n.records.filter(i=>i.recordType==="decision"&&i.state==="active"&&!t.has(i.id)&&!r.has(i.id)&&!s.has(i.id)).sort((i,c)=>c.createdAt.localeCompare(i.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(s=>s.recordType==="model_entry").sort((s,i)=>s.createdAt.localeCompare(i.createdAt)))r.decisionIds.some(s=>n.has(s))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let r=[...t.values()],s=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=s.filter(l=>l.targets.some(v=>v.entityType==="decision"&&v.entityId===c.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(c=>c.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),c=le(s),d=le(s),l=le(s),v=le(s),R=le(s),b=new Set(n.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),I=n.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&b.has(T.id)),g={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],h={...g,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},y={...g,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...g,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${s}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:i,decisionIds:[l],entryIds:[v],coverage:[{decisionId:l,status:"projected"}]},A={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=I.map(T=>({...g,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=I.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:y.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[h,y,x,S],events:[f,...J],relationships:[A,..._],artifacts:[],tombstones:[],projectionUpdates:I.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:v}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),s=n.bundle.records.flatMap(g=>g.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===g.id||g.sourceRefs.some(h=>h.id===p))?[g.id]:[]),i=[...new Set(n.bundle.records.flatMap(g=>g.recordType==="decision"&&s.includes(g.id)?g.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!l)throw new Error("No active local owner participant is available.");let v=Date.now(),R=new Date(v).toISOString(),b={id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},I=r?[{id:le(v),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:b.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:b.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[b],events:[],relationships:I,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(v),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(i=>i.objectType==="eval_spec").map(i=>i.objectId)),t=e.records.filter(i=>i.recordType==="eval_spec").reverse().filter((i,c,d)=>d.findIndex(l=>l.legacyId===i.legacyId)===c).filter(i=>!n.has(i.id)),r=e.records.filter(i=>i.recordType==="verification_attempt"),s=e.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.targetKind==="verification_result");return t.map(i=>{let c=r.filter(v=>v.evalSpecId===i.id).sort((v,R)=>R.createdAt.localeCompare(v.createdAt))[0],d=c&&s.some(v=>v.target.entityType==="verification_attempt"&&v.target.entityId===c.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(b=>b.recordType==="verification_attempt"&&b.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active"&&b.kind==="ai")??t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active");if(!s)return;let i=n.completedAt,c=new Date(i).toISOString(),d={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},v=r.targets.map(b=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:b,reason:n.summary})),R=await this.store.commit({records:[d,l],events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),c={id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),r=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(d=>!r.includes(d)).map(d=>d.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!i)return{valid:r,discardedIds:s};let c=s.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(v=>({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:v.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="model_projection"&&g.state==="applied"&&g.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(g=>g.recordType==="decision"&&e.decisionIds.includes(g.id)&&g.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let s=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),c=new Date(i).toISOString(),d=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(y=>e.decisionIds.includes(y)),h=p?.length?p:e.decisionIds,f=[...new Set(r.filter(y=>h.includes(y.id)).flatMap(y=>y.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:h.map(y=>({kind:"record",id:y})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:h,value:g.value}}),v=new Set(l.flatMap(g=>g.decisionIds)),R={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:e.decisionIds.map(g=>({kind:"record",id:g})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:v.has(g)?"projected":"unprojected"})},b=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),I=await this.store.commit({records:[...l,R],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});return await this.refreshIndex(I),{projectionId:d,entryIds:l.map(g=>g.id),headSequence:I.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Kt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Jr(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function _t(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function At(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Eo(o){let e=_t(o),n=_t(e.authority),t=n.level,r=n.mode,s=At(t,"authority.level",["owner","delegate","contributor"]),i=At(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:At(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=_t(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>At(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:At(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=_t(d);return{subjectId:Se(l.subjectId,"subjectId"),role:At(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Mo(o){let e=_t(o),n=(s,i)=>{if(s!==void 0){if(!Array.isArray(s))throw new Error(`${i} must be an array.`);return s.map(c=>Se(c,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0:_t(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Cn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
179
|
-
`)}async function
|
|
180
|
-
`)}function
|
|
176
|
+
`;return await ki(n,t+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Ai(o=xo,e="copilot"){let n=await fa(e);if(ha(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,i)=>{Si(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function fa(o){try{let e=await new Promise((n,t)=>{Si(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return JSON.parse(e)}catch{return null}}function ha(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 Tn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let i=this.leases.get(e),r={id:e,ownerPid:n,createdAt:i?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,i]of this.leases)i.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as Mo,readFile as pt,writeFile as _o}from"fs/promises";import{join as Xe}from"path";var ga=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function So(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function jn(o){return new Set(So(o).split(" ").filter(e=>e.length>2&&!ga.has(e)))}function Ei(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ya(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function va(o,e){let n=new Map,t=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(So).filter(Boolean),r=jn([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 ya(s)){let l=So(d.value);for(let T of i){let x=l===T?95:l.includes(T)||T.includes(l)?75:0;x>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:x>=90?"exact":"strong",matchedBy:d.by,score:x})}let j=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(Ei(jn(l),r)*55);j>=30&&j>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:j>=45?"strong":"weak",matchedBy:"query_text",score:j})}c&&n.set(s.id,c)}return n}function Ia(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),i=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!i.length)return{state:"none_found",attemptIds:[]};let r=new Set(i.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:i.map(s=>s.id)}}function wa(o){return Math.ceil(JSON.stringify(o).length/4)}function Ro(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),i=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=o.records.filter(y=>{if(y.recordType!=="proposal"||i&&!i.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=va(n,e),d=[...c.values()].sort((y,h)=>h.score-y.score),l=jn([e.action,e.text].filter(Boolean).join(" ")),b=r.flatMap(y=>{let h=y.subjects.map(D=>c.get(D.subjectId)).filter(D=>!!D),f=Math.max(0,...h.map(D=>D.score)),u=Math.round(Ei(jn(y.claim),l)*35),A=f+u;return A>=50?[{proposal:y,proposalMatches:h,score:A}]:[]}).sort((y,h)=>h.score-y.score||y.proposal.id.localeCompare(h.proposal.id)),j=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),x=[],m=0;for(let y of b){if(x.length>=j)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(A=>A.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:A,...D})=>D)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(A=>A.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Ia(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:wa(f)};if(m+u.estimatedTokens>T)break;x.push(u),m+=u.estimatedTokens}let p=Math.max(0,b.length-x.length);return{packets:x,subjectMatches:d.map(({score:y,...h})=>h),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:b.length,omittedPacketCount:p,maxEstimatedTokens:T,estimatedTokens:m},uncertainty:c.size===0?"subject_unresolved":b.length===0?"no_relevant_pending_proposal":void 0}}var ba=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ko(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function An(o){return new Set(ko(o).split(" ").filter(e=>e.length>2&&!ba.has(e)))}function Mi(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 xa(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(ko).filter(Boolean),i=An([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(n.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let b=ko(l.value);for(let x of t){let m=b===x?95:b.includes(x)||x.includes(b)?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 T=["/","#","[","]","="].some(x=>l.value.includes(x))?0:Math.round(Mi(An(b),i)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"semantic",score:T})}c&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Sa(o){return Math.ceil(JSON.stringify(o).length/4)}function jt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Ra(o,e){let n=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(r=>r.state==="completed"),i=t.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":t.length?"partial":"unknown",attemptIds:n.map(r=>r.id)}}function 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)),i=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),r=t[0],s=i?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function _i(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),i=o.records.filter(C=>C.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(C=>C.recordType==="decision"&&C.state==="active"),c=r?s.filter(C=>r.has(C.id)):s,d=o.records.filter(C=>C.recordType==="implementation_attempt"),l=o.records.filter(C=>C.recordType==="verification_attempt"),b=o.records.filter(C=>C.recordType==="freshness_signal"&&C.state==="open"),j=o.records.filter(C=>C.recordType==="evidence"),T=o.records.filter(C=>C.recordType==="model_entry"),x=[...o.records].reverse().filter(C=>C.recordType==="eval_spec").filter((C,I,w)=>w.findIndex(M=>M.legacyId===C.legacyId)===I),m=xa(i,e),p=new Map(m.map(C=>[C.subjectId,C.score])),y=An([e.action,e.text].filter(Boolean).join(" ")),h=c.flatMap(C=>{let I=Math.max(0,...C.subjects.map(F=>p.get(F.subjectId)??0)),w=Math.round(Mi(An(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(!jt(C,"excepts")&&!jt(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()],A=C=>C.from.entityType==="decision"&&C.to.entityType==="decision"&&f.has(C.from.entityId)&&f.has(C.to.entityId),D=(C,I=!1)=>{let w=new Set(C.map($=>$.id)),M=b.filter($=>$.target.entityType==="decision"&&w.has($.target.entityId)),F=new Set(o.relationships.filter($=>jt($,"excepts")&&w.has($.from.entityId)&&w.has($.to.entityId)).flatMap($=>[$.from.entityId,$.to.entityId])),U=o.relationships.filter($=>jt($,"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=j.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($=>jt($,"contradicts")&&A($)&&(!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:T.filter($=>$.decisionIds.some(Z=>w.has(Z))).map($=>({id:$.id,key:$.key,value:$.value,decisionIds:$.decisionIds})),evalSpecs:x.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":F.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($=>Ra($.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=Sa(ge),ge},R=D(u);for(;R.budget.estimatedTokens>n&&u.length>0;){let C=u.pop(),I=o.relationships.filter(w=>jt(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=D(u,!0)}return R}var Pa=/^[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 Pa.test(o)}function Ta(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 Po(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 Ge(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ae(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function It(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 ja={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 Ea(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),Ge(o,`${n}.createdAt`,e.createdAt),It(o,`${n}.authority`,e.authority);let t=ja[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(i)&&ae(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(Aa.has(r)&&(It(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&&Ge(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function Ma(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Ge(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"&&(It(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"&&Po(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."),Ge(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ae(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&ae(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&ae(o,`${n}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Ge(o,`${n}.concreteBindings[${r}].createdAt`,i.createdAt),Ge(o,`${n}.concreteBindings[${r}].updatedAt`,i.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"&&(Ge(o,`${n}.appliedAt`,e.appliedAt),It(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(i=>!i.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&&Po(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Po(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function _a(o,e,n){if(Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),Ge(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 i=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!i&&!r&&ae(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?ae(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&It(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 wt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),Ge(e,"manifest.createdAt",o.manifest.createdAt),Ge(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),Ma(e,p,h,o.manifest.projectId)}),o.events.forEach((p,y)=>{let h=`events[${y}]`;t(p.id,h),Ea(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let h=`relationships[${y}]`;t(p.id,h),_a(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let h=`tombstones[${y}]`;t(p.id,h),Te(e,`${h}.id`,p.id),Te(e,`${h}.objectId`,p.objectId),Te(e,`${h}.deletedById`,p.deletedById),Ge(e,`${h}.deletedAt`,p.deletedAt),It(e,`${h}.authority`,p.authority,!0)});let i=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),r=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,y)=>{let h=`${p.entityType}:${p.entityId}`;!i.has(h)&&!r.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)=>{!i.has(`${p}:${y}`)&&!r.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((A,D)=>l("subject",A,`${h}.scenarios[${u}].subjectIds[${D}]`))}),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":It(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 b=new Map(o.events.map(p=>[p.id,p])),j=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),T=new Map;o.events.forEach((p,y)=>{let h=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,f=T.get(h)??new Set;f.add(p.toState),T.set(h,f),f.size>1&&ae(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let x=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),m=(p,y,h,f,u)=>{if(p.level!=="delegate"||!p.grantId)return;let A=x.get(p.grantId);if(!A){ae(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(A.granteeId!==y||A.level!=="delegate")&&ae(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let D=Date.parse(h);(D<Date.parse(A.startsAt)||A.endsAt&&D>Date.parse(A.endsAt)||A.revokedAt&&D>=Date.parse(A.revokedAt))&&ae(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),A.subjectIds.length&&f.length&&!f.every(R=>A.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=j.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=j.get(`${f.entityType}:${f.entityId}`);return u&&"subjects"in u?u.subjects.map(A=>A.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=b.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."),j.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 Ta(e)}function Vt(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 Ci(o,e,n,t,i){return{id:i,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Ca(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function En(o,e){let n=[],t=o.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),At(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of Ca(e))At(r)||n.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...Vt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Ci(o,t,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Vt(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={...Vt(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Ci(o,r,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:r.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[r,d],events:[s,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let r={...Vt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let i={...Vt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as $a}from"crypto";import{readFile as Da,readdir as Oa,realpath as Ja}from"fs/promises";import{join as Kt,relative as Na}from"path";var Ba=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Et(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Le(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function $i(...o){return o.find(e=>!!e?.trim())?.trim()}function le(o,e,n,t){let r=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=$a("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function To(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=Et(o);if(!e)return 0;let n=0,t=i=>{let r=Et(i);if(!r){n+=1;return}for(let s of Object.values(r))t(s)};for(let i of Object.values(e))t(i);return n}function La(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Qt(o){let e=[],n=await Ja(o.projectRoot).catch(()=>o.projectRoot),t=Kt(n,".popmelt"),i=await To(Kt(t,"threads.json"),e),r=await To(Kt(t,"model.json"),e),s=Et(i),c=Et(s?.threads)??{},d=Object.entries(c).map(([$,Z])=>({key:$,value:Et(Z)})).filter($=>!!$.value),l=Kt(t,"decisions"),b=await Oa(l).catch(()=>[]),j=[];for(let $ of b.filter(Z=>Z.endsWith(".json")).sort()){let Z=Et(await To(Kt(l,$),e));Z&&j.push({file:$,value:Z})}let T=d.flatMap(({value:$})=>[$.createdAt,$.updatedAt]).filter($=>typeof $=="number"&&Number.isFinite($)),x=T.length?Math.min(...T):0,m=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=le(m,"project",m,x),y=le(m,"participant","legacy-owner",x),h=le(m,"participant","legacy-agent",x),f=le(m,"subject","project",x),u=Le(Math.max(x,...T)),A=[],D=[],R=new Map,C=new Map,I=new Map(j.map($=>[$.value.id??$.file.replace(/^d-|\.json$/g,""),$.value])),w=new Map,M=($,Z,ue,se,Oe)=>{let Je=R.get(ue);if(Je)return Je;let Re=le(m,"artifact",$,se);return D.push({id:Re,kind:Z,mediaType:Oe,location:ue,availability:"available"}),R.set(ue,Re),Re};for(let{file:$,value:Z}of j){let ue=Z.id??$.replace(/^d-|\.json$/g,""),se=Z.createdAt??x,Oe=[M(`${ue}:envelope`,"other",`.popmelt/decisions/${$}`,se,"application/json")];Z.screenshotPath&&Oe.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())Oe.push(M(`${ue}:image:${Je}`,"image",Re,se));w.set(ue,Oe)}let F=($,Z,ue)=>({id:$,schemaVersion:1,projectId:p,createdAt:u,participantId:Z,sourceRefs:ue}),H=($,Z)=>{A.push(Z);let ue=C.get($)??[];ue.push(Z.id),C.set($,ue)},U=[{...F(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...F(h,h,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];A.push(...U),A.push({...F(f,y,[]),recordType:"subject",subjectType:"project",label:Na(process.cwd(),n)||n,aliases:[],locators:[{id:le(m,"locator",n,x),kind:"project_root",value:n,status:"current",validFrom:Le(x),sourceRefs:[]}]});let ne=new Map,oe=($,Z)=>{let ue=ne.get($);if(ue)return ue;let se=le(m,"subject",$,Z),Oe={...F(se,y,[{kind:"external",id:$}]),createdAt:Le(Z),recordType:"subject",subjectType:"element",label:$,aliases:[],locators:[{id:le(m,"locator",$,Z),kind:"dom_selector",value:$,status:"current",validFrom:Le(Z),sourceRefs:[{kind:"external",id:$}]}]};return A.push(Oe),ne.set($,se),se};for(let{key:$,value:Z}of d){let ue=Z.id??$,se=Z.createdAt??x,Oe=le(m,"thread",ue,se),Je={kind:"thread",id:ue},Re=[],Ue=[],Ve=Array.isArray(Z.messages)?Z.messages:[],et,st,mt=0;Ve.forEach((we,at)=>{let Me=we.timestamp??se,tt=le(m,"artifact",`${ue}:message:${at}`,Me);if(Re.push(tt),D.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${at}`,availability:"available"}),R.set(`.popmelt/threads.json#/threads/${ue}/messages/${at}`,tt),we.screenshotPath&&M(`${ue}:message:${at}:screenshot`,"screenshot",we.screenshotPath,Me),we.role==="human"){et=we;let Ae=we.feedbackSummary??we.replyToQuestion;if(Ae?.trim()){let Ne=le(m,"observation",`${ue}:${at}`,Me),lt=Z.elementIdentifiers??[],Rt={...F(Ne,y,[Je,{kind:"message",id:tt}]),createdAt:Le(Me),recordType:"observation",state:"open",statement:Ae,captureContext:{subjectIds:lt.map(ht=>oe(ht,se)),artifactIds:[tt]},resolvedByIds:[]};H(ue,Rt),st=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let ct=we.jobId??`${ue}:${at}`,dt=le(m,"iteration",ct,Me),ft=I.get(ct),no=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",oo={...F(dt,h,[Je,{kind:"message",id:tt},...(w.get(ct)??[]).map(Ae=>({kind:"artifact",id:Ae}))]),createdAt:Le(Me),recordType:"iteration",threadIds:[Oe],startedAt:Le(et?.timestamp,Me),completedAt:Le(Me),requestSummary:$i(et?.feedbackSummary,et?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:no,execution:{provider:we.provider??ft?.provider,model:we.model??ft?.model,sessionId:we.sessionId??ft?.sessionId},artifactIds:[tt,...w.get(ct)??[]]};H(ue,oo),Ue.push({entityType:"iteration",entityId:dt});let Ft=we.resolutions??ft?.resolutions??[];for(let[Ae,Ne]of Ft.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let lt=Z.elementIdentifiers??[],Rt=(lt.length?lt:[n]).map(pn=>({subjectId:pn===n?f:oe(pn,se),role:"governed"})),ht=le(m,"proposal",`${ct}:${Ne.annotationId??"resolution"}:${Ae}`,Me),io={...F(ht,h,[Je,{kind:"iteration",id:dt}]),createdAt:Le(Me),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:Rt,subjectSemantics:Rt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:$i(et?.feedbackSummary,et?.replyToQuestion,Ne.summary),iterationId:dt,inferredById:h}};H(ue,io),Ue.push({entityType:"proposal",entityId:ht}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${ht} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Ft.some(Ae=>Ae.status==="resolved")||ft?.gitDiff){let Ae=le(m,"implementation",ct,Me),Ne={...F(Ae,h,[Je,{kind:"iteration",id:dt}]),createdAt:Le(Me),recordType:"implementation_attempt",state:"completed",iterationIds:[dt],coverageClaims:[],summary:Ft.map(lt=>lt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};H(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:Ae}),mt+=1}st&&(st=void 0)});let Nt=Ve.at(-1),Bt={...F(Oe,y,[Je]),createdAt:Le(se),recordType:"thread",state:Nt?.question?"open":"resolved",messageArtifactIds:Re,outcome:Nt?.question?"question_unresolved":mt?"implementation_only":"no_outcome",resultRefs:Ue};A.push(Bt),C.set(ue,[Oe,...C.get(ue)??[]])}let ye=Fa(r);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:Le(x),updatedAt:u,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:A,events:[],relationships:[],artifacts:D,tombstones:[]},V=wt(Y),ge=(o.proofCaseIds??Ba).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:j.length,modelEntries:ye,artifactsReferenced:D.length},imported:La(A),unresolvedAcceptance:e.filter($=>$.code==="acceptance_unresolved").length,deferredModelEntries:ye,proofCases:ge,issues:e,schemaIssues:V.issues}}}import{createHash as za}from"crypto";import{mkdir as Di,open as jo,readFile as Ao,readdir as Ua,rename as qa,unlink as Eo}from"fs/promises";import{join as it}from"path";var Wa={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function _n(o){return za("sha256").update(JSON.stringify(o)).digest("hex")}function Oi(o){return _n(o)}function Ji(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let i=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(i<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let r=o.records[i];if(r.projectId!==t.projectId||r.createdAt!==t.createdAt||r.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[i]=structuredClone(t)}for(let t of e.projectionUpdates){let i=o.records.find(r=>r.recordType===t.entityType&&r.id===t.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(i.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${i.state}`);i.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Ga(o,e,n){return Ji(structuredClone(o),e,n)}async function bt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await jo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
177
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await qa(n,o)}catch(i){throw await Eo(n).catch(()=>{}),i}}async function Mn(o){return JSON.parse(await Ao(o,"utf8"))}var Cn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=it(e,".popmelt","memory"),this.journalDir=it(this.memoryDir,"journal"),this.manifestPath=it(this.memoryDir,"manifest.json"),this.checkpointPath=it(this.memoryDir,"checkpoint.json"),this.lockPath=it(this.memoryDir,"writer.lock")}async initialize(e){let n=wt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Di(this.journalDir,{recursive:!0});try{throw await Ao(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await Ao(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=_n(e),i={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await bt(this.checkpointPath,i),await bt(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await bt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=_n(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await bt(it(this.memoryDir,t),i),e.manifest.checkpoint={file:t,sequence:i.sequence,hash:n},await bt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!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 i=t.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...r,hash:Oi(r)},c=Ga(t.bundle,e,n.committedAt),d=wt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(i).padStart(12,"0")}-${n.transactionId}.json`;return await bt(it(this.journalDir,l),s),t.manifest.head={sequence:i,hash:s.hash},t.manifest.updatedAt=n.committedAt,await bt(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Wa,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Mn(this.manifestPath),n=await Mn(it(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 Ua(this.journalDir),i=t.filter(T=>T.endsWith(".tmp")),s=t.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,b=new Set;for(let T of s){let x=await Mn(it(this.journalDir,T)),{hash:m,...p}=x;if(m!==Oi(p))throw new Error(`Journal hash mismatch: ${T}`);if(x.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(x.previousHash!==l)throw new Error(`Journal chain mismatch at ${T}`);if(x.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(b.has(x.transactionId))throw new Error(`Duplicate transaction ID: ${x.transactionId}`);Ji(c,x.mutation,x.committedAt),d=x.sequence,l=x.hash,b.add(x.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let j=wt(c);if(!j.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(j.issues)}`);return{bundle:c,manifest:e,transactionIds:b,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Di(this.memoryDir,{recursive:!0});let n;try{n=await jo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let i=await Mn(this.lockPath).catch(()=>({})),r=!0;if(typeof i.pid=="number")try{process.kill(i.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await Eo(this.lockPath),n=await jo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Eo(this.lockPath).catch(()=>{})}}};import{randomBytes as Ha}from"crypto";function fe(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Ha(10).toString("hex"),i=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${i}${t.slice(4,7)}-${t.slice(7,19)}`}var Va=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Ni(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 i=o.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Va(),l=d.records,b=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(A=>A.kind==="thread"&&A.id===e.threadId));b||(b={id:le(i,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(b));let j=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let A=o.records.find(D=>D.recordType==="subject"&&D.locators.some(R=>R.value===u&&R.status==="current"));A||(A={id:le(i,"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(i,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(A)),j.push(A)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let A=o.records.find(D=>D.recordType==="subject"&&D.locators.some(R=>R.kind==="source_file"&&R.value===u&&R.status==="current"));A||(A={id:le(i,"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(i,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(A)),j.push(A)}let T=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),x;if(T.length>0){x=le(i,"live-observation",r,e.createdAt);let u={id:x,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(A=>A.claim.trim()).join(" "),captureContext:{subjectIds:j.map(A=>A.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let m=le(i,"live-iteration",r,e.completedAt),p={id:m,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...x?[{kind:"record",id:x}]:[]],recordType:"iteration",threadIds:[b.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=j.length>0?j:o.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(T.length>0&&f.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,A]of T.entries()){let D=le(i,"live-proposal",`${r}:${u}`,e.completedAt),R=f.map(I=>({subjectId:I.id,role:"governed"})),C={id:D,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:A.claim.trim(),rationale:A.rationale?.trim()||void 0,proposedKind:A.proposedKind,subjects:R,subjectSemantics:R.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:A.sourceText?.trim()||e.requestSummary,iterationId:m,inferredById:t.id}};l.push(C),y.push(D)}if(h.length>0){let u=new Set(e.governingDecisionIds??[]),A=o.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&u.has(R.id)),D={id:le(i,"live-implementation",r,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:A.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(D)}return{mutation:d,iterationId:m,proposalIds:y,observationId:x}}import{createHash as Ka}from"crypto";import{mkdir as Qa,open as Xa,readFile as Ya,rename as Za,unlink as ec}from"fs/promises";import{join as Bi}from"path";function Fi(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Li(o){return Ka("sha256").update(JSON.stringify(o)).digest("hex")}async function tc(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Xa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Za(n,o)}catch(i){throw await ec(n).catch(()=>{}),i}}function nc(o,e,n=new Date().toISOString()){let t={},i={},r={},s=(d,l,b)=>{let j=d[l]??=[];j.includes(b)||j.push(b)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let b of[l.label,...l.aliases,...l.locators.filter(j=>j.status==="current").map(j=>j.value)]){let j=Fi(b);j&&s(t,j,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(i,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(r,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...c,checksum:Li(c)}}function zi(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Fi(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 $n=class{constructor(e){this.indexDir=Bi(e,".popmelt","memory","indexes"),this.indexPath=Bi(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let i=JSON.parse(await Ya(this.indexPath,"utf8")),{checksum:r,...s}=i;if(i.version===1&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===n.sequence&&i.journalHead.hash===n.hash&&r===Li(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let t=nc(e,n);return await Qa(this.indexDir,{recursive:!0}),await tc(this.indexPath,t),t}};var Xt="popmelt:imprint",Ui="popmelt:imprint-evidence",Mt="popmelt:imprint-relation";function Dn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===Xt)?.id}function Co(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 On(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 Jn=class{constructor(e){this.projectRoot=e;this.store=new Cn(e),this.indexStore=new $n(e),this.manifestPath=Xe(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await pt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let i=await this.store.load();return i.report.recoveredTransactions>0&&(i=await this.store.recover()),await this.refreshIndex(i),await this.status()}let t=await Qt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(i=>i.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(i){if(!(i instanceof Error)||!i.message.includes("already initialized"))throw i}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Qt({...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 r=JSON.parse(await pt(n,"utf8"));return{migrated:!1,specs:r.specs??0,runs:r.runs??0}}catch{}let t=[],i=[];try{let r=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(r.cases)?r.cases:[]}catch{}try{let r=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));i=Array.isArray(r.runs)?r.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,i)),await Mo(e,{recursive:!0}),await _o(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:i.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:i.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 pt(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Mo(e,{recursive:!0}),await _o(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let i=await this.store.load(),r=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??r,d=i.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let l=i.bundle.manifest.projectId,b=new Set(i.bundle.records.map(u=>u.id)),j=new Set(i.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(A=>A.kind==="external"&&A.uri===Mt?[A.id]:[]))),T=new Map,x=i.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let A=x.find(D=>Dn(D)===u.id);T.set(u.id,A?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let m=[],p=[],y=[],h=0;for(let u of t.explanations){let A=T.get(u.id),D=x.find(w=>w.id===A),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),!b.has(M)&&(m.push({id:M,schemaVersion:1,projectId:l,createdAt:w.createdAt,participantId:c.id,sourceRefs:Co([{kind:"external",id:w.id,uri:Ui},{kind:"external",id:u.id,uri:Xt},{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:Ui}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:A},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),h+=1)}let I={id:A,schemaVersion:1,projectId:l,createdAt:D?.createdAt??u.createdAt,participantId:D?.participantId??c.id,sourceRefs:Co([...D?.sourceRefs??[],{kind:"external",id:u.id,uri:Xt}]),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([...D?.evidenceIds??[],...R])],concreteBindings:On(t,u.id),supersededById:u.supersededBy?T.get(u.supersededBy):void 0,updatedAt:u.updatedAt};D?p.push(I):m.push(I)}for(let u of t.relations){let A=T.get(u.fromId),D=T.get(u.toId);!A||!D||j.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:Mt}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:A},to:{entityType:"advisory_explanation",entityId:D},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 Mo(e,{recursive:!0}),await _o(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),i=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Ro(t.bundle,i)}}async contextualize(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:_i(t.bundle,i),reviewSelection:Ro(t.bundle,i)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:En(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Qt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),i=En(t.bundle,e);if(!i.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(i.errors)}`);let r=await this.store.commitReviewPlan(i.plan,n);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),i=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!t||t.state!=="pending"||!i)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),c={proposalId:t.id,participantId:i.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:fe(r),decisionId:fe(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:fe(r),replacementProposalId:fe(r),acceptanceEventId:fe(r),decisionId:fe(r),relationshipId:fe(r),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:fe(r),reason:e.reason}:{...c,action:"defer",eventId:fe(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=En(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(T=>T.message).join(" ")};let b=await this.store.commitReviewPlan(l.plan,{transactionId:fe(r),committedAt:s});await this.refreshIndex(b);let j=l.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:j,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:b.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=Ni(n.bundle,e),i=le(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(t.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),i=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active"),r=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="ai"&&f.status==="active"),s=e.action?i:r??i,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),b=t.bundle.manifest.projectId,j=[],T=[],x=[],m=t.bundle.records.filter(f=>f.recordType==="advisory_explanation"),p=new Map(m.flatMap(f=>{let u=Dn(f);return u?[[u,f.id]]:[]}));for(let f of e.summary.changes)if(!p.has(f.explanationId)){let u=n?.explanations.find(A=>A.id===f.explanationId);p.set(f.explanationId,le(b,"imprint-explanation",f.explanationId,Date.parse(u?.createdAt??d)))}for(let f of e.summary.changes){let u={kind:"external",id:f.explanationId,uri:Xt},A=p.get(f.explanationId),D=m.find(w=>w.id===A),R=n?.explanations.find(w=>w.id===f.explanationId),C={id:le(b,"imprint-live-evidence",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:b,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:[]};j.push(C);let I={id:A,schemaVersion:1,projectId:b,createdAt:D?.createdAt??R?.createdAt??d,participantId:D?.participantId??s.id,sourceRefs:Co([...D?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:R?.kind??D?.kind??"pattern",state:R?.state??f.state,statement:R?.statement??f.statement,rationale:R?.rationale??D?.rationale??e.summary.detail,scope:structuredClone(R?.scope??D?.scope??{kind:"project",values:[]}),subjectIds:D?.subjectIds??[c.id],evidenceIds:[...new Set([...D?.evidenceIds??[],C.id])],concreteBindings:R?On(n,f.explanationId):D?.concreteBindings??[],supersededById:R?.supersededBy?p.get(R.supersededBy):D?.supersededById,updatedAt:R?.updatedAt??d};D?T.push(I):j.push(I),x.push({id:le(b,"imprint-live-evidence-link",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:b,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===Mt?[u.id]:[])));for(let f of n?.relations??[]){let u=p.get(f.fromId),A=p.get(f.toId);!u||!A||y.has(f.id)||x.push({id:le(b,"imprint-relation",f.id,Date.parse(f.createdAt)),schemaVersion:1,projectId:b,createdAt:f.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:f.id,uri:Mt}],recordType:"relationship",relationshipType:f.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId:A},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:j,recordReplacements:T,events:[],relationships:x,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:h,committedAt:d});await this.refreshIndex(f)}catch(f){if(!(f instanceof Error)||!f.message.includes("Transaction already exists"))throw f}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=JSON.parse(await pt(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"),r=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="ai"&&R.status==="active")??t;if(!r)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=Dn(R);return C?[[C,R]]:[]})),b=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))])]),j=[],T=[],x=new Set(e.explanations.map(R=>R.id));for(let R of e.explanations){let C=l.get(R.id);if(!C){j.push({id:b.get(R.id),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:R.id,uri:Xt}],recordType:"advisory_explanation",kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:On(e,R.id),supersededById:R.supersededBy?b.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:On(e,R.id),supersededById:R.supersededBy?b.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)&&T.push(I)}for(let[R,C]of l)x.has(R)||C.state==="retired"||T.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===Mt)?.id;return C?[[C,R]]:[]})),y=new Set(p.keys()),h=[];for(let R of e.relations){let C=b.get(R.fromId),I=b.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:r.id,sourceRefs:[{kind:"external",id:R.id,uri:Mt}],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(!j.length&&!T.length&&!h.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let A=e.updatedAt,D=le(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(A));try{let R=await this.store.commit({records:j,recordReplacements:T,events:[],relationships:h,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:D,committedAt:A});return await this.refreshIndex(R),{status:"synced",relationships:h.length+u.length,explanations:j.length+T.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 i of n.bundle.records)t[i.recordType]=(t[i.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:n.bundle.records.filter(i=>i.recordType==="evidence"&&i.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),i=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!i.has(s.id)&&!r.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),t=new Map;for(let i of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))i.decisionIds.some(r=>n.has(r))&&t.set(i.key,i);return[...t.values()]}async getImprintView(e=[]){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(),i=t.bundle.records.filter(p=>p.recordType==="advisory_explanation"),r=new Map(i.map(p=>[p.id,p])),s=new Map(i.flatMap(p=>{let y=Dn(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]]:[])),b=new Set(t.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),j=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),T={testing:0,emerging:1,grounded:2,challenged:3,retired:4},x=i.map(p=>{let y=p.evidenceIds.flatMap(u=>{let A=l.get(u);if(!A)return[];let D=A.sourceRefs.find(w=>w.kind==="thread")?.id,R=A.sourceRefs.find(w=>w.kind==="message")?.id,C=A.kind==="judgment"||A.kind==="user_feedback"||A.kind==="project_state"?A.kind:"other",I=d.get(A.participantId)??"unknown";return[{id:A.id,kind:C,summary:A.summary,createdAt:A.createdAt,participantKind:I,threadId:D,jobId:R}]}).sort((u,A)=>A.createdAt.localeCompare(u.createdAt)),h=t.bundle.relationships.flatMap(u=>{if(b.has(u.id))return[];if(!j.has(u.relationshipType))return[];let A=u.from.entityType==="advisory_explanation"&&u.from.entityId===p.id&&u.to.entityType==="advisory_explanation",D=u.to.entityType==="advisory_explanation"&&u.to.entityId===p.id&&u.from.entityType==="advisory_explanation";if(!A&&!D)return[];let R=A?u.to.entityId:u.from.entityId,C=r.get(R);return C?[{id:u.id,type:u.relationshipType,direction:A?"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)||T[p.state]-T[y.state]||y.updatedAt.localeCompare(p.updatedAt)),m={total:x.filter(p=>p.state!=="retired").length,emerging:x.filter(p=>p.state==="emerging").length,testing:x.filter(p=>p.state==="testing").length,grounded:x.filter(p=>p.state==="grounded").length,challenged:x.filter(p=>p.state==="challenged").length,retired:x.filter(p=>p.state==="retired").length,needsGrounding:x.filter(p=>p.needsGrounding).length};return{head:{sequence:t.report.headSequence,updatedAt:t.bundle.manifest.updatedAt},counts:m,explanations:x}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let i=[...t.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(l=>l.targets.some(b=>b.entityType==="decision"&&b.entityId===c.id)).sort((l,b)=>b.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:i.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:i.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(r=>r.recordType==="decision"&&e.includes(r.id)?r.subjects.map(s=>s.subjectId):[])),i=[];for(let r of n.records)if(!(r.recordType!=="subject"||!t.has(r.id)))for(let s of r.locators.filter(c=>c.status==="current"))s.kind==="source_file"?i.push({kind:"source_file",value:s.value,subjectId:r.id}):s.kind==="route_pattern"?i.push({kind:"route",value:s.value,subjectId:r.id}):s.kind==="token_path"?i.push({kind:"model_path",value:s.value,subjectId:r.id}):(s.kind==="dom_selector"||s.kind==="file_export"||s.kind==="source_span")&&i.push({kind:"subject",value:s.value,subjectId:r.id});return[...new Map(i.map(r=>[`${r.kind}:${r.value}:${r.subjectId??""}`,r])).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"),i=n.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!t||!i)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=fe(r),d=fe(r),l=fe(r),b=fe(r),j=fe(r),T=new Set(n.bundle.records.flatMap(w=>w.recordType==="model_entry"&&w.key===e.key?w.decisionIds:[])),x=n.bundle.records.filter(w=>w.recordType==="decision"&&w.state==="active"&&T.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:i.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:b,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[l],value:e.value},A={...m,id:j,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[b],coverage:[{decisionId:l,status:"projected"}]},D={...m,id:fe(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:b},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},R=x.map(w=>({...m,id:fe(r),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=x.map(w=>({...m,id:fe(r),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,A],events:[h,...R],relationships:[D,...C],artifacts:[],tombstones:[],projectionUpdates:x.map(w=>({entityType:"decision",entityId:w.id,fromState:"active",state:"superseded"}))},{transactionId:fe(r),committedAt:s});return await this.refreshIndex(I),{decisionId:l,entryId:b}}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 i=this.latestEvalSpec(n.bundle,t.id),r=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"&&r.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:r,subjectIds:s,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(i&&JSON.stringify({state:i.state,title:i.title,category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,decisionIds:i.decisionIds,subjectIds:i.subjectIds,threadRefs:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.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 b=Date.now(),j=new Date(b).toISOString(),T={id:fe(b),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:j,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...r.map(m=>({kind:"record",id:m}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:i?.id,...d,targets:r.map(m=>({entityType:"decision",entityId:m})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},x=i?[{id:fe(b),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:j,participantId:l.id,sourceRefs:[{kind:"record",id:T.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:T.id},to:{entityType:"eval_spec",entityId:i.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[T],events:[],relationships:x,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(b),committedAt:j})}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)),i=e.records.filter(s=>s.recordType==="verification_attempt"),r=e.records.filter(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.targetKind==="verification_result");return t.map(s=>{let c=i.filter(b=>b.evalSpecId===s.id).sort((b,j)=>j.createdAt.localeCompare(b.createdAt))[0],d=c&&r.some(b=>b.target.entityType==="verification_attempt"&&b.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[i]=await this.syncEvalSpecs([{...t,...n}]);return i??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 i=n.get(t.evalSpecId);if(!i)return[];let r=t.evalRun,s=Date.parse(t.createdAt);return[{id:r?.id??t.id,evalId:i.legacyId,threadId:r?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:r?.createdAt??s,completedAt:r?.completedAt??s,durationMs:r?.durationMs??0,scope:r?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:r?.assertionResults??i.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:r?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:r?.provider,model:r?.model,screenshotPath:r?.screenshotPath,codeFingerprint:r?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,i)=>t.completedAt-i.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(T=>T.recordType==="verification_attempt"&&T.evalRun?.id===n.id))return;let i=this.latestEvalSpec(t.bundle,e.id);if(!i)return;let r=t.bundle.records.find(T=>T.recordType==="participant"&&T.status==="active"&&T.kind==="ai")??t.bundle.records.find(T=>T.recordType==="participant"&&T.status==="active");if(!r)return;let s=n.completedAt,c=new Date(s).toISOString(),d={id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:i.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:r.id,sourceRefs:[{kind:"record",id:i.id}],recordType:"verification_attempt",evalSpecId:i.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:r.id,name:n.model??n.provider??"Popmelt eval runner"},targets:i.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}},b=i.targets.map(T=>({id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:T,reason:n.summary})),j=await this.store.commit({records:[d,l],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});await this.refreshIndex(j)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(i=>[i.id,i]));for(let i of[...n].sort((r,s)=>r.completedAt-s.completedAt)){let r=t.get(i.evalId);r&&await this.recordEvalVerification(r,i)}}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),i=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||!i)return;let r=Date.now(),s=new Date(r).toISOString(),c={id:fe(r),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:i.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(r),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)]:[])),i=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),r=e.filter(d=>!i.includes(d)).map(d=>d.id);if(r.length===0)return{valid:i,discardedIds:r};let s=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!s)return{valid:i,discardedIds:r};let c=r.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(b=>({id:fe(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:b.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:i,discardedIds:r}}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(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(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 i=n.bundle.records.filter(m=>m.recordType==="decision"&&e.decisionIds.includes(m.id)&&m.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!r)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(i.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:r.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}}),b=new Set(l.flatMap(m=>m.decisionIds)),j={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(m=>({kind:"record",id:m})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(m=>m.id),coverage:e.decisionIds.map(m=>e.coverage?.find(p=>p.decisionId===m)??{decisionId:m,status:b.has(m)?"projected":"unprojected"})},T=l.flatMap(m=>m.decisionIds.map(p=>({id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:j.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:m.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),x=await this.store.commit({records:[...l,j],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});return await this.refreshIndex(x),{projectionId:d,entryIds:l.map(m=>m.id),headSequence:x.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Qt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),i=zi(t,n.subjectHints??[]);return i?{...n,subjectIds:[...new Set([...n.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Ct(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function _t(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function $o(o){let e=Ct(o),n=Ct(e.authority),t=n.level,i=n.mode,r=_t(t,"authority.level",["owner","delegate","contributor"]),s=_t(i,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=Ct(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>_t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=Ct(d);return{subjectId:Se(l.subjectId,"subjectId"),role:_t(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Do(o){let e=Ct(o),n=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>Se(c,s))}},t=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},i=e.resurface===void 0?void 0:Ct(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:i?{differentAction:i.differentAction===!0,newEvidence:i.newEvidence===!0,newConflict:i.newConflict===!0,ownerRequested:i.ownerRequested===!0}:void 0}}function Nn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
179
|
+
`)}async function qi(o,e,n,t){let i=Nn(e);if(!(!i&&n.length===0))try{let r=await o.contextualize({action:i||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(r.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){t?.(r);return}}function Wi(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,i)=>["",`${i+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,i)=>["",`${i+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
180
|
+
`)}function Gi(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,i=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!i||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&r.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:i,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function Hi(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 Bn(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],i=await oc(o),r=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,l,b,j,T,x,m,p,y,h,f,u,A,D=[],R=[],C=0,I=[];for(;C<i.length;){let w=i.indexOf(r,C);if(w===-1)break;let M=w+r.length;if(i.slice(w,w+s.length).equals(s))break;let F=M;i[F]===13&&i[F+1]===10&&(F+=2);let H=i.indexOf(`\r
|
|
181
181
|
\r
|
|
182
|
-
`,
|
|
182
|
+
`,F);if(H===-1)break;let U=i.slice(F,H).toString("utf-8"),ne=H+4,oe=i.indexOf(r,ne),ye=oe!==-1?oe-2:i.length;I.push({headers:U,body:i.slice(ne,ye)}),C=oe!==-1?oe:i.length}for(let w of I){let M=w.headers.match(/name="([^"]+)"/);if(!M)continue;let F=M[1];if(F==="screenshot")c=w.body;else if(F==="feedback")d=w.body.toString("utf-8");else if(F==="color")l=w.body.toString("utf-8");else if(F==="provider")b=w.body.toString("utf-8");else if(F==="model")j=w.body.toString("utf-8");else if(F==="reasoningEffort")T=w.body.toString("utf-8");else if(F==="serviceTier")x=w.body.toString("utf-8");else if(F==="goal")m=w.body.toString("utf-8");else if(F==="pageUrl")p=w.body.toString("utf-8");else if(F==="viewport")y=w.body.toString("utf-8");else if(F==="planId")h=w.body.toString("utf-8");else if(F==="manifest")f=w.body.toString("utf-8");else if(F==="tasks")u=w.body.toString("utf-8");else if(F==="sourceId")A=w.body.toString("utf-8");else if(F.startsWith("screenshot-")){let H=F.slice(11);try{let U=decodeURIComponent(H);R.push({pathname:U,data:w.body})}catch{}}else if(F.startsWith("image-")){let H=F.split("-"),U=parseInt(H[H.length-1],10),ne=H.slice(1,-1).join("-");ne&&!isNaN(U)&&D.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:b,model:j,reasoningEffort:T,serviceTier:x,goal:m,pageUrl:p,viewport:y,planId:h,manifest:f,tasks:u,sourceId:A,pastedImages:D,pageScreenshots:R}}function oc(o){return new Promise((e,n)=>{let t=[];o.on("data",i=>t.push(i)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as ic}from"crypto";var rc=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,sc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),ac=new Set(["strengthened","weakened","mixed","unknown"]);function Yt(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 cc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Vi(o,e,n,t=Date.now()){let i=cc(o);if(!i)return null;let r=typeof i.transition=="string"&&sc.has(i.transition)?i.transition:null,s=Yt(i.focus);if(!r||!s)return null;let c=typeof i.evidencePosture=="string"&&ac.has(i.evidencePosture)?i.evidencePosture:void 0;return{id:ic(),jobId:e,sequence:n,timestamp:t,transition:r,snapshot:{focus:s,seeking:Yt(i.seeking),workingHypothesis:Yt(i.workingHypothesis),evidencePosture:c,update:Yt(i.update),nextObservation:Yt(i.nextObservation)},contextPolicy:"exclude"}}function Oo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function dc(o,e,n=0){let t=[],i=new Set,r=n;return{visibleText:o.replace(rc,(c,d)=>{try{let l=Vi(JSON.parse(d),e,r);if(!l)return"";let b=Oo(l);if(i.has(b))return"";i.add(b),t.push(l),r++}catch{}return""}).replace(/\n{3,}/g,`
|
|
183
183
|
|
|
184
|
-
`).trim(),orientations:t}}function
|
|
184
|
+
`).trim(),orientations:t}}function lc(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 Fn=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 i=this.buffer.indexOf("<orientation>");if(i<0){let c=lc(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,i);let r=this.buffer.indexOf("</orientation>",i+13);if(r<0){this.buffer=this.buffer.slice(i);break}let s=this.buffer.slice(i+13,r).trim();this.buffer=this.buffer.slice(r+14);try{let c=Vi(JSON.parse(s),this.jobId,this.sequence);if(!c)continue;let d=Oo(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=dc(e,this.jobId,this.sequence),t=n.orientations.filter(i=>{let r=Oo(i);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Ki=`## Public orientation updates
|
|
185
185
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
186
186
|
<orientation>{"transition":"focus_shifted","focus":"Investigating the responsive overflow","seeking":"Which container introduces the extra width","update":"Padding is no longer the leading explanation","nextObservation":"Inspect computed widths at the failing breakpoint"}</orientation>
|
|
187
187
|
|
|
188
188
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
189
189
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
190
190
|
|
|
191
|
-
These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function
|
|
192
|
-
### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let
|
|
193
|
-
`)}function
|
|
194
|
-
`)}function
|
|
195
|
-
`)}function
|
|
196
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let
|
|
197
|
-
`));return
|
|
198
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await xc(n,o)}catch(r){throw await Sc(n).catch(()=>{}),r}}function kc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Rc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=$e(e):o.explanations.push($e(e))}function Co(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")Rc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(s=>s.id===t.evidence.id)||(r.evidence.push($e(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,$e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(i=>i.id===t.relation.fromId),s=n.explanations.some(i=>i.id===t.relation.toId)||n.concrete.some(i=>i.id===t.relation.toId);if(!r||!s)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(i=>i.id===t.relation.id)||n.relations.push($e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Tc(o,e){let n=[],t=$e(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let s=t.explanations.find(i=>i.id===r.explanationId);s&&n.unshift({op:"add_explanation",explanation:$e(s)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let s=t.concrete.find(i=>i.id===r.concreteId);s&&n.unshift({op:"add_concrete",concrete:$e(s)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let s=r.op==="replace_explanation"?r.explanation.id:r.explanationId,i=t.explanations.find(c=>c.id===s);i&&n.unshift({op:"replace_explanation",explanation:$e(i)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let s=t.relations.find(i=>i.id===r.relationId);s&&n.unshift({op:"add_relation",relation:$e(s)})}t=Co(t,[r])}return n}function os(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Fn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ct(e,".popmelt","imprint"),this.manifestPath=Ct(this.imprintDir,"manifest.json"),this.graphPath=Ct(this.imprintDir,"graph.json"),this.journalDir=Ct(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ts(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async load(){let e=await this.readManifest(),t=(await bc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=kc(this.projectId,e.createdAt),s=[],i=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await ts(Ct(this.journalDir,t[c]),"utf8")),{hash:l,...v}=d;if(d.sequence!==c+1||d.previousHash!==i||l!==ns(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Co(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},s.push(d),i=d.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=Tc(t.graph,e.mutations),i={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:s,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...i,hash:ns(i)},d=Co(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await tn(Ct(this.journalDir,l),c);let v={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await tn(this.graphPath,d),await tn(this.manifestPath,v),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(i.mutations.flatMap(os));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(v=>os(v).some(R=>c.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await tn(this.graphPath,e.graph),await tn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var jc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ec=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Mc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ln(o){return new Set(Mc(o).split(" ").filter(e=>e.length>2&&!Ec.has(e)))}function zn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function $o(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function ot(o,e,n){return{id:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function Ee(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function rs(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let n=e.values.filter(t=>typeof t=="string"&&!!t.trim());return n.length?{kind:e.kind,values:n}:void 0}function Ac(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Oo(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let b=String(r.reason);if(!jc.has(b))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:b},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let s=r.summary,i=s?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(i)))throw new Error("summary.kind is invalid");let c={kind:i,title:Ee(s?.title,120),detail:Ee(s?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(b=>typeof b=="string"&&!!b.trim()):[],l=[];for(let b of Array.isArray(r.mutations)?r.mutations:[]){if(!b||typeof b!="object")continue;let I=b;if(I.op==="add"&&["intention","principle","pattern"].includes(String(I.kind))){let g=Ee(I.statement),p=Ee(I.rationale);if(!g||!p)continue;l.push({op:"add",clientId:Ee(I.clientId,100)||void 0,kind:I.kind,statement:g,rationale:p,scope:rs(I.scope)})}else if(I.op==="revise"&&typeof I.explanationId=="string"){let g={op:"revise",explanationId:I.explanationId,statement:Ee(I.statement)||void 0,rationale:Ee(I.rationale)||void 0,scope:rs(I.scope),reopenGrounding:I.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(I.op==="evidence"&&typeof I.explanationId=="string"&&["supports","challenges","excepts"].includes(String(I.stance))){let g=Ee(I.summary);g&&l.push({op:"evidence",explanationId:I.explanationId,stance:I.stance,summary:g})}else if(I.op==="relation"&&typeof I.fromId=="string"&&typeof I.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(I.type)))l.push({op:"relation",type:I.type,fromId:I.fromId,toId:I.toId,rationale:Ee(I.rationale)});else if(I.op==="supersede"&&typeof I.explanationId=="string"&&typeof I.replacementId=="string"){let g=Ee(I.reason);g&&l.push({op:"supersede",explanationId:I.explanationId,replacementId:I.replacementId,reason:g})}else if(I.op==="bind_concrete"&&typeof I.explanationId=="string"){let g=Ee(I.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:I.explanationId,modelPath:g,rationale:Ee(I.rationale)})}else I.op==="retire"&&typeof I.explanationId=="string"&&l.push({op:"retire",explanationId:I.explanationId,reason:Ee(I.reason)})}let v=r.grounding,R=v&&typeof v.explanationId=="string"&&Ee(v.question)?{explanationId:v.explanationId,question:Ee(v.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Do(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(s=>` - Concrete terminal: ${s.modelPath} = ${JSON.stringify(s.value)}`)].join(`
|
|
199
|
-
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]}},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
|
|
200
|
-
`)}var nn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Fn(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Ln(e.text??""),t=Ln((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:s}=await this.store.load(),i=s.explanations.filter(d=>d.state!=="retired"&&d.state!=="challenged").map(d=>{let l=Ln([d.statement,d.rationale].join(" ")),v=Ln(d.scope.values.join(" ")),R=zn(l,n),b=zn(v,n),I=zn(v,t),g=zn(l,t),p=R+b*.2+I*.25+g*.1+(d.state==="grounded"?.08:0)+(r.has(d.id)?1:0),h=r.has(d.id)||(n.size?R>=.12||b>=.5:I>=.2||g>=.2);return{item:d,score:p,relevant:h}}).filter(d=>d.relevant&&d.score>=.18).sort((d,l)=>l.score-d.score||l.item.updatedAt.localeCompare(d.item.updatedAt)),c=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,c).map(({item:d})=>{let l=new Set(s.relations.filter(v=>v.fromId===d.id&&v.type==="instantiates").map(v=>v.toId));return{id:d.id,kind:d.kind,statement:d.statement,rationale:d.rationale,scope:d.scope,state:d.state,concrete:s.concrete.filter(v=>l.has(v.id)).map(v=>({id:v.id,modelPath:v.modelPath,value:v.value}))}}),truncated:i.length>c,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,c=new Map,d=[],l=new Set,v=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=He();S.clientId&&i.set(S.clientId,A);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,_={id:A,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:$o(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(A,_),l.add(A),d.push({op:"add_explanation",explanation:_})}let R=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let A=R(S.explanationId),J=s.get(A);if(J?.state!=="grounded")continue;let _=He(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?$o(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(_,N),c.set(A,_),l.add(_),d.push({op:"add_explanation",explanation:N}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let b=S=>{let A=R(S);return c.get(A)??A};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=b(S.explanationId);if(!s.has(J))continue;let _=Ac(n.concreteModel,S.modelPath);if(!_.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(_.value));N||(N={id:He(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:N})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=b(S.fromId),_=b(S.toId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_relation",relation:{id:He(),type:S.type,fromId:J,toId:_,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(_);continue}if(S.op==="supersede"){let J=b(S.explanationId),_=b(S.replacementId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_evidence",explanationId:J,evidence:ot(n,"challenges",S.reason)}),d.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:_},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"contradicts",fromId:_,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(_);continue}let A=b(S.explanationId);if(s.has(A))if(l.add(A),S.op==="revise"){if(c.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:$o(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:A,patch:J,updatedAt:t})}else S.op==="evidence"?(d.push({op:"add_evidence",explanationId:A,evidence:ot(n,S.stance,S.summary)}),S.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(d.push({op:"add_evidence",explanationId:A,evidence:ot(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let A=b(S),J=s.get(A);!J||J.state==="grounded"||J.state==="retired"||v.has(A)&&!l.has(A)||(l.has(A)||(l.add(A),d.push({op:"add_evidence",explanationId:A,evidence:{...ot(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=He(),g=await this.store.commit({transactionId:I,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),h=[...l].flatMap(S=>{let A=p.get(S);if(!A)return[];let J=!r.graph.explanations.some(N=>N.id===S),_=A.state==="challenged"||A.state==="retired";return[{explanationId:S,action:J?"added":_?"challenged":"revised",statement:A.statement,state:A.state}]}),f=e.grounding?b(e.grounding.explanationId):void 0,y=f?p.get(f):void 0,x=y?.state==="testing"&&!v.has(y.id)?{explanationId:y.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:I,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:h,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let v of l)await this.store.undo(v,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(v=>v.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:i,summary:d,mutations:c})}};function ss(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Un(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Jo(o){if(!o)return null;try{let e=new URL(o);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function is(o){let e=Jo(Un(o.origin));if(e)return e;let n=Jo(Un(o.referer));if(n)return n;let t=Un(o["x-forwarded-host"]);if(!t)return null;let r=Un(o["x-forwarded-proto"])==="https"?"https":"http";return Jo(`${r}://${t}`)}function as(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),i=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=i.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:c,actionableProposals:i}}import{createHash as qn}from"crypto";import{mkdir as on,readFile as bt,unlink as $c,writeFile as Ot}from"fs/promises";import{dirname as Wn,extname as Oc,join as Oe}from"path";var _c={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function Cc(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function cs(o,e){let n=e??Cc(o);return{kind:n,..._c[n]}}function $t(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ds(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Dc={version:1,threads:{}},ls=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],rn={version:2,updatedAt:0,files:{}};function Jc(o){return JSON.stringify(o,null,2)}function Nc(o){return Object.fromEntries(ls.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Bc(o){let e={...o};for(let n of ls)delete e[n];return e}function Dt(o){let e=o;if(o.error){let n=cs(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=$t(e.result,!1),t=$t(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Hn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Oe(e,".popmelt");this.legacyFilePath=Oe(n,"threads.json"),this.threadsDir=Oe(n,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(n,"artifacts","thread-messages"),this.mediaDir=Oe(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await bt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let s=await this.readThread(Oe(this.threadsDir,r));s&&(n[t]=s)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await bt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Dt)}]))},this.index={...rn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Dc,threads:{}},this.index={...rn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Dt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=r.messages.findIndex(i=>i.role==="human"&&!!i.replyToQuestion&&i.queued);s>=0?r.messages.splice(s,0,Dt(n)):r.messages.push(Dt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=s.messages.filter(c=>c.jobId===n);if(i.length===0)return!1;for(let c of i)if(Object.assign(c,t),c.error){let d=Dt(c);Object.assign(c,d),delete c.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(h=>h.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(h=>h.role==="assistant"),d=h=>{if(h.role!=="assistant")return;if(h.question)return h.question;let f=h.imprintSummary?.grounding;if(f?.question&&!h.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(h=>!!d(h)),v=r.messages.findLastIndex(h=>h.role==="human"),R=l>v?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,I=Array.from(new Set(r.messages.slice(0,Math.max(0,v)).filter(h=>h.role==="assistant"&&!!h.jobId).map(h=>h.jobId))),g=c.some(h=>!!h.responseText||!!h.question||!!h.result||!!h.memoryReviewCard||!!h.memoryReceipt),p=c.some(h=>!!h.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:b,pendingQuestion:R,acknowledgedJobIds:I,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await bt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...s})=>{let i={};if(r?.path)try{let c=await bt(Oe(Wn(this.legacyFilePath),r.path),"utf8");qn("sha256").update(c).digest("hex")===r.sha256&&(i=JSON.parse(c))}catch{}return Dt({...s,...i})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Nc(e),t=Bc(e);if(Object.keys(n).length===0)return t;let r=Jc(n),s=qn("sha256").update(r).digest("hex"),i=Oe("artifacts","thread-messages",`${s}.json`);await on(this.artifactsDir,{recursive:!0});try{await bt(Oe(Wn(this.legacyFilePath),i),"utf8")}catch{await Ot(Oe(Wn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Wn(t)===this.mediaDir)return t;try{let r=await bt(t),s=qn("sha256").update(r).digest("hex"),i=Oe(this.mediaDir,`${s}${Oc(t)||".bin"}`);await on(this.mediaDir,{recursive:!0});try{await bt(i)}catch{await Ot(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await on(this.threadsDir,{recursive:!0});let n=this.index??{...rn,files:{}},t=n.files[e.id]??`${qn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(i=>this.encodeMessage(i))),s={...e,version:2,messages:r};await Ot(Oe(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Ot(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await on(this.threadsDir,{recursive:!0}),this.index=this.index??{...rn,files:{}},await Ot(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...rn,files:{}},t=n.files[e];t&&await $c(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await on(this.threadsDir,{recursive:!0}),await Ot(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Fc,open as Lc,readFile as zc,rename as Uc,unlink as qc}from"fs/promises";import{dirname as Wc,join as Hc}from"path";var ps={schemaVersion:1,theme:"auto",updatedAt:null};function us(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Gc(o,e){await Fc(Wc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Lc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
201
|
-
`,"utf8"),await t.sync()}finally{await t.close()}await
|
|
202
|
-
`)}function
|
|
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=
|
|
204
|
-
`)}function
|
|
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 Zt(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let i=t.elements.map(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),r=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${r} \u2192 Elements: ${i||"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 i=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let r of t.changes)n.push(`- ${t.selector} ${i}: ${r.property} ${r.original} \u2192 ${r.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 i=t.element?.reactComponent?`(${t.element.reactComponent})`:"",r=JSON.stringify(t.original),s=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${i}${c}: ${r} \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 i=t.element?.reactComponent?`(${t.element.reactComponent})`:"",r=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} ${i}${r} \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 i of t.affectedElements){let r=i.reactComponent?` (${i.reactComponent})`:"";i.matchedClass&&i.suggestedClass?n.push(`- ${i.selector}${r}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):n.push(`- ${i.selector}${r}: ${i.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${i.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 i=[t.selector];t.reactComponent&&i.push(`(${t.reactComponent})`),t.context&&i.push(`in ${t.context}`),t.textContent&&i.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${i.join(" ")}`)}return n.join(`
|
|
193
|
+
`)}function Qi(o,e,n){let t=[],r=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!r&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let s=0;for(let c of n.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(t.push(`### Round ${s} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${s} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${s} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${s} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,b=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${b} \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 b=new Map;for(let j of s)if(typeof j=="object"&&j!==null&&"text"in j){let T=j,x=T.scope||"general";b.has(x)||b.set(x,[]),b.get(x).push(T.text)}for(let[j,T]of b){t.push(`**${j.charAt(0).toUpperCase()+j.slice(1)}**`);for(let x of T)t.push(`- ${x}`)}}else for(let b of s)typeof b=="string"&&t.push(`- ${b}`);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.")),r){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 b=s[d];b&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${b}`):!b&&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 j={...e,annotations:l,styleModifications:e.styleModifications},T=Zt(j,n?.imagePaths);T&&(t.push(""),t.push(T))}}else{let s=Zt(e,n?.imagePaths);s&&(t.push(""),t.push(s))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
|
|
194
|
+
`)}function Xi(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Yi(o,e,n,t){let i=[];i.push("You are continuing work on a UI based on the developer's reply to your question."),i.push(""),n!=="codex"&&i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(i.push(""),i.push(r.feedbackContext)),e.length>0){i.push(""),i.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(i.push(`### Round ${s} (human) \u2014 reply`),i.push(`"${c.replyToQuestion}"`)):(i.push(`### Round ${s} (human)`),c.feedbackSummary&&i.push(`Annotations: ${c.feedbackSummary}`))):c.question?(i.push(`### Round ${s} (assistant) \u2014 question`),i.push(`"${c.question}"`)):(i.push(`### Round ${s} (assistant)`),c.responseText&&i.push(`Response: ${c.responseText}`))}if(i.push(""),i.push("The developer answered your question. Continue working based on their reply."),i.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),i.push(""),i.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){i.push(""),i.push("## Attached Images"),i.push("The developer attached reference images with their reply:");for(let s of t)i.push(`Attached image: use the Read tool to view the image at: ${s}`)}return i.push(""),i.push("## Resolution"),i.push("After completing all work, output a resolution block listing what you did for each annotation:"),i.push("<resolution>"),i.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),i.push("</resolution>"),i.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),i.push(""),i.push("### Scope classification"),i.push("Each resolution MUST include scope fields:"),i.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),i.push("- `inferredScope`: What scope the change actually has, based on what you modified."),i.push("Scope has two dimensions:"),i.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),i.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),i.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),i.push("If you cannot confidently determine scope, set it to null."),i.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),i.push(""),i.push("## Questions"),i.push("If you still need clarification, output:"),i.push("<question>Your question here</question>"),i.push("You may output BOTH a <resolution> and a <question> in the same response."),i.join(`
|
|
195
|
+
`)}function pc(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 uc(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&&!pc(e[n]))return!1;return!0}function Zi(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(uc):[]}catch{return[]}}function er(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let i=t;return(i.category==="token"||i.category==="component"||i.category==="element")&&typeof i.element=="string"&&typeof i.decision=="string"&&typeof i.reason=="string"}):[]}catch{return[]}}import{execFile as mc}from"child_process";import{readdir as fc,readFile as hc,stat as gc}from"fs/promises";import{homedir as en}from"os";import{join as Ye}from"path";var zn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:tr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:tr()}],tn=[{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"}],nn={id:"",label:"Default",source:"cli"},yc=/^\s*-\s+"([^"]+)"/;function vc(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 i=t.match(yc);if(!i?.[1])continue;let r=i[1];e.push({id:r,label:Jo(r),source:"cli"})}return Un([nn,...e])}function Ic(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,i)=>{let r=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,s=typeof i.priority=="number"?i.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(t=>{let i=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!i)return[];let r=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Jo(i),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:i,label:r,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function tr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function wc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Un(e.map(n=>({id:n,label:Jo(n),source:"cli"})))}function Jo(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let r=t[1]==="sonnet"?"Sonn":Rc(t[1]),s=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${r}${s}${t[4]?" Fast":""}`}let i=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(i){let r=i[2]?`${i[1]}.${i[2]}`:i[1];return i[3]==="mini"?`Mini ${r}`:i[3]==="codex"?`Codex ${r}`:i[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return n}async function nr(o="copilot"){let e=await Ln(o,["help","config"]),n=vc(e);return n.length>1?n:[nn]}async function or(o="codex"){let e=await Ln(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Ye(en(),".codex");return rr(Ye(t,"models_cache.json"))}),n=Ic(e);return n.length>0?Un([...n,...tn]):tn}async function ir(o="claude"){let e=Ye(en(),".claude"),n=[Ye(en(),".claude","stats-cache.json"),Ye(en(),".claude","settings.json"),Ye(en(),".claude.json"),Ye(e,"cache","changelog.md")],[t,i,r]=await Promise.all([Ln(o,["--help"]).catch(()=>""),Ln(o,["--version"]).catch(()=>""),bc(e).catch(()=>[])]),s=Sc([...n,...r]),c=await Promise.all(s.map(l=>rr(l).catch(()=>""))),d=wc([t,i,...c].join(`
|
|
197
|
+
`));return Un([...zn,...d])}function Ln(o,e,n=5e3){return new Promise((t,i)=>{mc(o,e,{encoding:"utf-8",timeout:n},(r,s)=>{if(r){i(r);return}t(s)})})}async function rr(o){return hc(o,"utf-8")}async function bc(o){let e=[Ye(o,"projects"),Ye(o,"telemetry")],n=[];for(let t of e)await sr(t,n,4);return n.sort((t,i)=>i.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function sr(o,e,n){if(n<0)return;let t;try{t=await fc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async i=>{let r=Ye(o,i.name);if(i.isDirectory()){await sr(r,e,n-1);return}if(!(!i.isFile()||!xc(i.name)))try{let s=await gc(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function xc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Un(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 Sc(o){return[...new Set(o)]}function Rc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var qn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){n=r;break}}let t=n>=0?n+1:0,i=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),i}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let i=this.bufferEvent(n,e);for(let r of this.listeners)r(i,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let i={...n,seq:t.nextSeq++};return t.events.push(i),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),i}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),i=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!t)return null;let s=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:s,currentSeq:t.nextSeq-1,accumulated:{...i},jobActive:r}}accumulateText(e,n,t){let i=this.accumulators.get(e);i||(i={response:"",thinking:""},this.accumulators.set(e,i)),i[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(i=>{let r=!1,s=()=>{r||(r=!0,i())};t.on("exit",s),t.on("error",s),setTimeout(()=>{if(!r){try{t.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as He}from"crypto";import{createHash as kc}from"crypto";import{mkdir as Pc,open as Tc,readFile as ar,readdir as jc,rename as Ac,unlink as Ec}from"fs/promises";import{dirname as Mc,join as $t}from"path";function $e(o){return structuredClone(o)}function cr(o){return kc("sha256").update(JSON.stringify(o)).digest("hex")}async function on(o,e){await Pc(Mc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Tc(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(i){throw await Ec(n).catch(()=>{}),i}}function _c(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Cc(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 No(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(i=>i.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")Cc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(i=>i.id!==t.explanationId),n.relations=n.relations.filter(i=>i.fromId!==t.explanationId&&i.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(i=>i.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(i=>i.id!==t.concreteId),n.relations=n.relations.filter(i=>i.fromId!==t.concreteId&&i.toId!==t.concreteId);else if(t.op==="add_evidence"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);i.evidence.some(r=>r.id===t.evidence.id)||(i.evidence.push($e(t.evidence)),i.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(i,$e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let i=n.explanations.some(s=>s.id===t.relation.fromId),r=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!i||!r)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(i=>i.id!==t.relationId));return n}function $c(o,e){let n=[],t=$e(o);for(let i of e){if(i.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=t.explanations.find(s=>s.id===i.explanationId);r&&n.unshift({op:"add_explanation",explanation:$e(r)})}else if(i.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=t.concrete.find(s=>s.id===i.concreteId);r&&n.unshift({op:"add_concrete",concrete:$e(r)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let r=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=t.explanations.find(c=>c.id===r);s&&n.unshift({op:"replace_explanation",explanation:$e(s)})}else if(i.op==="add_relation")n.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=t.relations.find(s=>s.id===i.relationId);r&&n.unshift({op:"add_relation",relation:$e(r)})}t=No(t,[i])}return n}function dr(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 Wn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=$t(e,".popmelt","imprint"),this.manifestPath=$t(this.imprintDir,"manifest.json"),this.graphPath=$t(this.imprintDir,"graph.json"),this.journalDir=$t(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ar(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 jc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),i=_c(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await ar($t(this.journalDir,t[c]),"utf8")),{hash:l,...b}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==cr(b))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);i=No(i,d.mutations),i.updatedAt=d.committedAt,i.head={sequence:d.sequence,hash:d.hash},r.push(d),s=d.hash}return{graph:i,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(j=>j.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=t.graph.head.sequence+1,r=$c(t.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:cr(s)},d=No(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:i,hash:c.hash};let l=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await on($t(this.journalDir,l),c);let b={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await on(this.graphPath,d),await on(this.manifestPath,b),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,i){let r=await this.load(),s=r.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(dr));if(r.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(b=>dr(b).some(j=>c.has(j)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await on(this.graphPath,e.graph),await on(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"]),Oc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Jc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Gn(o){return new Set(Jc(o).split(" ").filter(e=>e.length>2&&!Oc.has(e)))}function Hn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Bo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function rt(o,e,n){return{id:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function lr(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 pr(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let i=Number(t);if(!Number.isInteger(i)||i<0||i>=n.length)return{found:!1};n=n[i]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Fo(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 i=JSON.parse(t);if(i.decision==="none"){let T=String(i.reason);if(!Dc.has(T))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:T},visibleText:n}}if(i.decision!==void 0&&i.decision!=="mutate")throw new Error("imprint decision is invalid");let r=i.summary,s=r?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:je(r?.title,120),detail:je(r?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(i.appliedExplanationIds)?i.appliedExplanationIds.filter(T=>typeof T=="string"&&!!T.trim()):[],l=[];for(let T of Array.isArray(i.mutations)?i.mutations:[]){if(!T||typeof T!="object")continue;let x=T;if(x.op==="add"&&["intention","principle","pattern"].includes(String(x.kind))){let m=je(x.statement),p=je(x.rationale);if(!m||!p)continue;l.push({op:"add",clientId:je(x.clientId,100)||void 0,kind:x.kind,statement:m,rationale:p,scope:lr(x.scope),rootReason:je(x.rootReason,300)||void 0})}else if(x.op==="revise"&&typeof x.explanationId=="string"){let m={op:"revise",explanationId:x.explanationId,statement:je(x.statement)||void 0,rationale:je(x.rationale)||void 0,scope:lr(x.scope),reopenGrounding:x.reopenGrounding===!0};(m.statement||m.rationale||m.scope||m.reopenGrounding)&&l.push(m)}else if(x.op==="evidence"&&typeof x.explanationId=="string"&&["supports","challenges","excepts"].includes(String(x.stance))){let m=je(x.summary);m&&l.push({op:"evidence",explanationId:x.explanationId,stance:x.stance,summary:m})}else if(x.op==="relation"&&typeof x.fromId=="string"&&typeof x.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(x.type))){let m=je(x.rationale);if(!m)continue;l.push({op:"relation",type:x.type,fromId:x.fromId,toId:x.toId,rationale:m})}else if(x.op==="supersede"&&typeof x.explanationId=="string"&&typeof x.replacementId=="string"){let m=je(x.reason);m&&l.push({op:"supersede",explanationId:x.explanationId,replacementId:x.replacementId,reason:m})}else if(x.op==="bind_concrete"&&typeof x.explanationId=="string"){let m=je(x.modelPath,300);m&&l.push({op:"bind_concrete",explanationId:x.explanationId,modelPath:m,rationale:je(x.rationale)})}else x.op==="retire"&&typeof x.explanationId=="string"&&l.push({op:"retire",explanationId:x.explanationId,reason:je(x.reason)})}let b=i.grounding,j=b&&typeof b.explanationId=="string"&&je(b.question)?{explanationId:b.explanationId,question:je(b.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:j},visibleText:n}}catch(i){return{visibleText:n,error:i instanceof Error?i.message:String(i)}}}function Lo(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,i)=>[`${i+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(r=>` - Concrete terminal: ${r.modelPath} = ${JSON.stringify(r.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 rn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Wn(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=Gn(e.text??""),t=Gn((e.subjectHints??[]).join(" ")),i=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!i.size)return;let{graph:r}=await this.store.load(),s=r.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let p=Gn([m.statement,m.rationale].join(" ")),y=Gn(m.scope.values.join(" ")),h=Hn(p,n),f=Hn(y,n),u=Hn(y,t),A=Hn(p,t),D=h+f*.2+u*.25+A*.1+(m.state==="grounded"?.08:0)+(i.has(m.id)?1:0),R=i.has(m.id)||(n.size?h>=.12||f>=.5:u>=.2||A>=.2);return{item:m,score:D,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)),b=new Set(r.relations.flatMap(m=>l.has(m.fromId)?[m.toId]:l.has(m.toId)?[m.fromId]:[])),j=new Set(r.explanations.flatMap(m=>b.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),T=r.explanations.filter(m=>j.has(m.id)&&!l.has(m.id)).sort((m,p)=>p.updatedAt.localeCompare(m.updatedAt)).slice(0,4),x=[...d,...T];for(let m of T)l.add(m.id);return{explanations:x.map(m=>{let p=new Set(r.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:r.concrete.filter(y=>p.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||T.length<j.size,...i.size?{pendingGroundingExplanationIds:[...i]}:{},relations:r.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(),i=await this.store.load(),r=new Map(i.graph.explanations.map(I=>[I.id,I])),s=new Map,c=new Map,d=[],l=new Set,b=new Set(n.pendingGroundingExplanationIds??[]),j=new Set(e.mutations.flatMap(I=>I.op==="add"&&I.clientId?[I.clientId]:[])),T=I=>r.has(I)||j.has(I),x=new Set;for(let I of e.mutations)I.op==="relation"&&I.fromId!==I.toId&&T(I.fromId)&&T(I.toId)?(x.add(I.fromId),x.add(I.toId)):I.op==="supersede"&&I.explanationId!==I.replacementId&&T(I.explanationId)&&T(I.replacementId)?(x.add(I.explanationId),x.add(I.replacementId)):I.op==="bind_concrete"&&T(I.explanationId)&&pr(n.concreteModel,I.modelPath).found&&x.add(I.explanationId);let m=i.graph.explanations.length===0;for(let I of e.mutations){if(I.op!=="add")continue;let w=!!(I.clientId&&x.has(I.clientId)),M=!!I.rootReason?.trim()||m;if(!w&&!M)continue;m&&(m=!1);let F=He();I.clientId&&s.set(I.clientId,F);let H=I.clientId?e.appliedExplanationIds.includes(I.clientId):!1,U={id:F,kind:I.kind,statement:I.statement,rationale:I.rationale,scope:Bo(I.scope),state:H?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[rt(n,"supports",e.summary.detail)]};r.set(F,U),l.add(F),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=r.get(w);if(M?.state!=="grounded")continue;let F=He(),H={id:F,kind:M.kind,statement:I.statement??M.statement,rationale:I.rationale??M.rationale,scope:I.scope?Bo(I.scope):M.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[rt(n,"supports",e.summary.detail)]};r.set(F,H),c.set(w,F),l.add(F),d.push({op:"add_explanation",explanation:H}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:F,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(!r.has(M))continue;let F=pr(n.concreteModel,I.modelPath);if(!F.found)continue;let H=i.graph.concrete.find(U=>U.modelPath===I.modelPath&&JSON.stringify(U.value)===JSON.stringify(F.value));H||(H={id:He(),modelPath:I.modelPath,value:structuredClone(F.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:H})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:M,toId:H.id,rationale:I.rationale,createdAt:t}}),l.add(M);continue}if(I.op==="relation"){let M=y(I.fromId),F=y(I.toId);if(!r.has(M)||!r.has(F)||M===F)continue;d.push({op:"add_relation",relation:{id:He(),type:I.type,fromId:M,toId:F,rationale:I.rationale,createdAt:t}}),l.add(M),l.add(F);continue}if(I.op==="supersede"){let M=y(I.explanationId),F=y(I.replacementId);if(!r.has(M)||!r.has(F)||M===F)continue;d.push({op:"add_evidence",explanationId:M,evidence:rt(n,"challenges",I.reason)}),d.push({op:"revise_explanation",explanationId:M,patch:{state:"challenged",supersededBy:F},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"contradicts",fromId:F,toId:M,rationale:I.reason,createdAt:t}}),l.add(M),l.add(F);continue}let w=y(I.explanationId);if(r.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:Bo(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:rt(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:rt(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=r.get(w);!M||M.state==="grounded"||M.state==="retired"||b.has(w)&&!l.has(w)||(l.has(w)||(l.add(w),d.push({op:"add_evidence",explanationId:w,evidence:{...rt(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=He(),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])),A=[...l].flatMap(I=>{let w=u.get(I);if(!w)return[];let M=!i.graph.explanations.some(H=>H.id===I),F=w.state==="challenged"||w.state==="retired";return[{explanationId:I,action:M?"added":F?"challenged":"revised",statement:w.statement,state:w.state}]}),D=e.grounding?y(e.grounding.explanationId):void 0,R=D?u.get(D):void 0,C=R?.state==="testing"&&!b.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:A,...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 b of l)await this.store.undo(b,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!r||r.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:{...rt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${r.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(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: ${r.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(b=>b.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:r.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${r.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${r.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:s,summary:d,mutations:c})}};function ur(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Vn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function zo(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 mr(o){let e=zo(Vn(o.origin));if(e)return e;let n=zo(Vn(o.referer));if(n)return n;let t=Vn(o["x-forwarded-host"]);if(!t)return null;let i=Vn(o["x-forwarded-proto"])==="https"?"https":"http";return zo(`${i}://${t}`)}function fr(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),i=[...o].sort(t).slice(0,n),r=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:i,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Kn}from"crypto";import{mkdir as sn,readFile as xt,unlink as Fc,writeFile as Ot}from"fs/promises";import{dirname as Qn,extname as Lc,join as De}from"path";var Nc={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 Bc(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 hr(o,e){let n=e??Bc(o);return{kind:n,...Nc[n]}}function Dt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function gr(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(i=>i.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var zc={version:1,threads:{}},yr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],an={version:2,updatedAt:0,files:{}};function Uc(o){return JSON.stringify(o,null,2)}function qc(o){return Object.fromEntries(yr.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Wc(o){let e={...o};for(let n of yr)delete e[n];return e}function Jt(o){let e=o;if(o.error){let n=hr(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=Dt(e.result,!1),t=Dt(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Xn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=De(e,".popmelt");this.legacyFilePath=De(n,"threads.json"),this.threadsDir=De(n,"threads"),this.indexPath=De(this.threadsDir,"index.json"),this.artifactsDir=De(n,"artifacts","thread-messages"),this.mediaDir=De(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await xt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,i]of Object.entries(e.files)){let r=await this.readThread(De(this.threadsDir,i));r&&(n[t]=r)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await xt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Jt)}]))},this.index={...an,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...zc,threads:{}},this.index={...an,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let i of Object.values(n.threads))if(i.elementIdentifiers.some(s=>t.has(s)))return i;return null}async createThread(e,n){let t=await this.load(),i={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,n){let i=(await this.load()).threads[e];i&&(i.messages.push(Jt(n)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,Jt(n)):i.messages.push(Jt(n)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=Jt(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of n)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((i,r)=>r.updatedAt-i.updatedAt),t.slice(0,e).map(i=>{let s=i.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",c=i.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=i.messages.findLastIndex(y=>!!d(y)),b=i.messages.findLastIndex(y=>y.role==="human"),j=l>b?d(i.messages[l]):void 0,T=i.messages.at(-1)?.role,x=Array.from(new Set(i.messages.slice(0,Math.max(0,b)).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:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:m,hasError:p,lastMessageRole:T,pendingQuestion:j,acknowledgedJobIds:x,elementIdentifiers:i.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await xt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let c=await xt(De(Qn(this.legacyFilePath),i.path),"utf8");Kn("sha256").update(c).digest("hex")===i.sha256&&(s=JSON.parse(c))}catch{}return Jt({...r,...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=qc(e),t=Wc(e);if(Object.keys(n).length===0)return t;let i=Uc(n),r=Kn("sha256").update(i).digest("hex"),s=De("artifacts","thread-messages",`${r}.json`);await sn(this.artifactsDir,{recursive:!0});try{await xt(De(Qn(this.legacyFilePath),s),"utf8")}catch{await Ot(De(Qn(this.legacyFilePath),s),i)}return{...t,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let n=async t=>{if(Qn(t)===this.mediaDir)return t;try{let i=await xt(t),r=Kn("sha256").update(i).digest("hex"),s=De(this.mediaDir,`${r}${Lc(t)||".bin"}`);await sn(this.mediaDir,{recursive:!0});try{await xt(s)}catch{await Ot(s,i)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,i])=>[t,await n(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,i])=>[t,await Promise.all(i.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await sn(this.threadsDir,{recursive:!0});let n=this.index??{...an,files:{}},t=n.files[e.id]??`${Kn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,i=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:i};await Ot(De(this.threadsDir,t),JSON.stringify(r,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Ot(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await sn(this.threadsDir,{recursive:!0}),this.index=this.index??{...an,files:{}},await Ot(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...an,files:{}},t=n.files[e];t&&await Fc(De(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await sn(this.threadsDir,{recursive:!0}),await Ot(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Gc,open as Hc,readFile as Vc,rename as Kc,unlink as Qc}from"fs/promises";import{dirname as Xc,join as Yc}from"path";var vr={schemaVersion:1,theme:"auto",updatedAt:null};function Ir(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Zc(o,e){await Gc(Xc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Hc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
201
|
+
`,"utf8"),await t.sync()}finally{await t.close()}await Kc(n,o)}catch(t){throw await Qc(n).catch(()=>{}),t}}var Yn=class{constructor(e){this.path=Yc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Vc(this.path,"utf8")),n=Ir(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...vr}}}catch{return{exists:!1,preferences:{...vr}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Zc(this.path,n),n}};function wr(o){return Ir(o)!==null}function br(o){return td(o).slice(0,12)}var ed=[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 td(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):nd(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let T=7;T>=0;T--)e.push(n/Math.pow(2,T*8)&255);let t=1779033703,i=3144134277,r=1013904242,s=2773480762,c=1359893119,d=2600822924,l=528734635,b=1541459225,j=new Array(64);for(let T=0;T<e.length;T+=64){for(let D=0;D<16;D++){let R=T+D*4;j[D]=(e[R]<<24|e[R+1]<<16|e[R+2]<<8|e[R+3])>>>0}for(let D=16;D<64;D++){let R=Ze(j[D-15],7)^Ze(j[D-15],18)^j[D-15]>>>3,C=Ze(j[D-2],17)^Ze(j[D-2],19)^j[D-2]>>>10;j[D]=j[D-16]+R+j[D-7]+C>>>0}let x=t,m=i,p=r,y=s,h=c,f=d,u=l,A=b;for(let D=0;D<64;D++){let R=Ze(h,6)^Ze(h,11)^Ze(h,25),C=h&f^~h&u,I=A+R+C+ed[D]+j[D]>>>0,w=Ze(x,2)^Ze(x,13)^Ze(x,22),M=x&m^x&p^m&p,F=w+M>>>0;A=u,u=f,f=h,h=y+I>>>0,y=p,p=m,m=x,x=I+F>>>0}t=t+x>>>0,i=i+m>>>0,r=r+p>>>0,s=s+y>>>0,c=c+h>>>0,d=d+f>>>0,l=l+u>>>0,b=b+A>>>0}return[t,i,r,s,c,d,l,b].map(T=>T.toString(16).padStart(8,"0")).join("")}function Ze(o,e){return o>>>e|o<<32-e}function nd(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 xr={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 cn=xr.version;var md=1111,fd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],hd=1800*1e3,gd=3600*1e3,kr=45e3,yd=5e3,vd=1e4;function Pr(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 ln(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function Id(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 Cr(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 wd(o,e){let n=[];for(let t of o)if(t.type==="delta"){let i=t.text;if(!i)continue;let r=n[n.length-1];r&&r.kind==="text"?r.text+=i:n.push({kind:"text",text:i})}else if(t.type==="tool_use"){let i=t.tool||"",r=t.file??void 0,s=t.content??void 0,c=r?r.split("/").pop()??r:void 0,d;switch(i){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=i?`Using ${i}`:"tool";break}let l=r??s??void 0,b=r?qo(r)?r:_r(e,r):void 0,j=n[n.length-1];j&&j.kind==="tool_group"&&j.tool===i?j.items.push({label:d,detail:l,...b?{filePath:b}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:d,detail:l,...b?{filePath:b}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function bd(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 xd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Tr(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),t=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),i=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),r=[...e,...t,...n,...i].map(s=>xd(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function Sd(o,e){let n=o.headers.origin;Cr(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 i of o){let r=typeof i=="string"?Buffer.from(i):i;if(n+=r.length,n>16384)throw new Error("Request body too large");e.push(r)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Rd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function 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,i,r]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(i,16)};${parseInt(r,16)}m${e}\x1B[0m`}function eo(o,e){try{o.res.write(`event: ${e.type}
|
|
205
205
|
data: ${JSON.stringify(e)}
|
|
206
206
|
|
|
207
|
-
`)}catch{}}function
|
|
207
|
+
`)}catch{}}function St(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function Pd(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 i=s=>{o.removeListener("listening",r),t(s)},r=()=>{o.removeListener("error",i),n()};o.once("error",i),o.once("listening",r),o.listen(e,"127.0.0.1")})}function jr(o){try{let e=to("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=to("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),i=to("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Mr("sha256").update(`${e}
|
|
208
208
|
${t}
|
|
209
|
-
${
|
|
209
|
+
${i}`).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 Ar(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let i=[["scenarios",e.scenarios??[]]];for(let r of[...t].sort((s,c)=>`${s.kind}:${s.value}`.localeCompare(`${c.kind}:${c.value}`)))if(r.kind==="model_path")i.push([r.kind,r.value,jd(n,r.value)]);else if(r.kind==="source_file"){let s=_r(o,r.value),d=s===o||s.startsWith(`${o}/`)?await Uo(s,"utf8").catch(()=>"[missing]"):"[outside-project]";i.push([r.kind,r.value,d])}else i.push([r.kind,r.value]);return Mr("sha256").update(JSON.stringify(i)).digest("hex").slice(0,16)}async function $r(o={}){let e=new Date().toISOString(),n=o.port??md,t=o.projectRoot??process.cwd(),i=await sd(t).catch(()=>t),r=br(i),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ee(ld(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,b=[...o.allowedTools??fd],j=o.claudePath??"claude",T=o.copilotPath??"copilot",x=o.provider??"claude",m=o.timeoutMs,p=o.restartMode??"embedded",y=n,h={},f={claude:j,codex:"codex",copilot:T};for(let[a,g]of Object.entries(f))try{let P=g.includes("/")?g:to("which",[g],{encoding:"utf-8"}).trim();h[a]={available:!0,path:P}}catch{h[a]={available:!1,path:null}}function u(a,g){return new Promise(P=>{let v=Sr(g,["--version"],{stdio:["ignore","ignore","ignore"]}),k=!1,S=J=>{k||(k=!0,P(J))},E=setTimeout(()=>{v.kill("SIGTERM"),S(!0)},5e3);v.on("error",()=>{clearTimeout(E),S(!1)}),v.on("close",J=>{clearTimeout(E),S(J===0)})})}await Promise.all([(async()=>{h.claude&&(h.claude.models=h.claude.available&&h.claude.path?await ir(h.claude.path).catch(()=>zn):zn)})(),(async()=>{h.codex&&(h.codex.models=h.codex.available&&h.codex.path?await or(h.codex.path).catch(()=>tn):tn)})(),(async()=>{h.copilot&&(h.copilot.models=h.copilot.available&&h.copilot.path?await nr(h.copilot.path).catch(()=>[nn]):[nn])})()]);let[A,D,R]=await Promise.all([vo(i),Io(i),wo(i,h.copilot?.path??T)]),C=await bi(i);h.claude&&(h.claude.mcp=A),h.codex&&(h.codex.mcp=D),h.copilot&&(h.copilot.mcp=R),A.found&&A.name&&b.push(`mcp__${A.name}__*`),await id(c,{recursive:!0}),Er(c).catch(()=>{});let I=new qn(1),w=new Rn,M=new Tn(kr),F=null,H=0,U=!1,ne=()=>{H+=1,U=!1,F&&clearTimeout(F),F=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=++H,g=Date.now()+vd,P=()=>{if(a!==H)return;if(M.size>0){ne();return}if(!(I.isRunning||I.depth>0||w.isRunning||w.depth>0)||Date.now()>=g){U=!1,F=setTimeout(oe,50),F.unref?.();return}F=setTimeout(P,250),F.unref?.()};P()},Y=new Set,V=new Xn(i),q=new Jn(i),ge=new rn(i,r),$=new Yn(i),Z=new yn(i),ue=new wn(i),se=new Sn(i,{claudePath:j,provider:x,timeoutMs:m,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let g of Y)eo(g,a)}});q.beginAutomaticInitialization({writerVersion:cn}).then(async a=>{a.state==="ready"?(await q.migrateLegacyEvals(),await q.migrateImprintSnapshot(),await q.syncImprintGraph(),await se.applyCanonicalEntries(await q.getCanonicalModelEntries()),x!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await Ae({provider:x,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let Oe=20,Je=300*1e3,Re=[];function Ue(){let a=Date.now()-Je;for(;Re.length>0&&(Re[0].completedAt<a||Re.length>Oe);)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()},P=di(a,g);if(P.length===0)return[];let v=await q.getEvalDependenciesForDecisions(a.decisionIds),k=a.threadId?await V.getThread(a.threadId):null,S=[...new Set((k?.messages??[]).flatMap(B=>(B.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])).map(B=>qo(B)?Rr(i,B):B))].map(B=>({kind:"source_file",value:B})),E=P.map(B=>{let z=[...new Map([...B.dependencies??[],...v,...S].map(G=>[`${G.kind}:${G.value}:${"subjectId"in G?G.subjectId??"":""}`,G])).values()],L=z.filter(G=>G.kind==="route"),O=z.flatMap(G=>G.kind==="model_path"&&G.value.startsWith("components.")?[G.value.slice(11).split(".")[0]]:[]),N=[...new Set(z.flatMap(G=>"subjectId"in G&&G.subjectId?[G.subjectId]:[]))],Q=L.length>0?L.map((G,re)=>({id:`route-${re+1}`,...G.value.includes("*")?{routePattern:G.value}:{route:G.value},components:O.map(ce=>({name:ce})),subjectIds:N})):[{id:O.length>0?`component-${O[0]}`:"current-page",components:O.map(G=>({name:G})),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(E),await se.attachGeneratedEvals(a.id,E.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"}))),E.map(B=>B.id)}async function st(a){let g=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",P=lo(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:[P],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 mt=null,Nt;I.addListener((a,g,P)=>{for(let v of Y)(!P||!v.sourceId||v.sourceId===P)&&eo(v,a)}),w.addListener((a,g,P)=>{for(let v of Y)(!P||!v.sourceId||v.sourceId===P)&&eo(v,a)}),w.setProcessor(async a=>{let g=a.provider??x;try{let P=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(),k=P.runId?v.runs.find(E=>E.id===P.runId):void 0;if(P.success&&P.proposalId){let E=await se.findModelProposal(P.proposalId),J=await se.loadModel(),B=E?gi(E,J):null;if(E&&B){let z=E.decisionIds.map(O=>({decisionId:O,status:"projected"}));await q.applyModelProjection({runId:E.runId??E.id,presentationJobId:E.presentationJobId,decisionIds:E.decisionIds,changes:B.map(O=>({path:O.path,value:O.value,decisionIds:O.decisionIds})),coverage:z});let L=await se.applySelectedModelProposal(E.id,B.map(O=>({path:O.path,value:O.value})),B.map(O=>({group:O.path[0]==="rules"||O.path[0]==="components"||O.path[0]==="tokens"?O.path[0]:"model",label:O.label??O.id,detail:O.rationale,path:O.path,value:O.value})),"automatic");L&&await et(L)}}let S=bd(P,k);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})),P.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=P.error??"Projection failed",a.threadId){let E=`Model projection failed.
|
|
210
210
|
|
|
211
|
-
${a.error}`;await
|
|
211
|
+
${a.error}`;await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:E,error:a.error,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:E,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(P){if(a.status==="cancelled")return;if(a.status="error",a.error=P instanceof Error?P.message:String(P),a.threadId){let v=`Model projection failed.
|
|
212
212
|
|
|
213
|
-
${a.error}`;await
|
|
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,P=g._replyPrompt,v=g._replyText,k=g._replyImagePaths,S=a.provider??x,E=!!(a.surfacedProposalIds?.length&&P),J=!!g._evalRemediation,B=!E&&!["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}}}(E||J)&&(z=void 0);let L;if(z&&P){if(L=v??P,k&&k.length>0){L+=`
|
|
214
214
|
|
|
215
|
-
The developer attached reference images with their reply:`;for(let de of
|
|
216
|
-
Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?
|
|
215
|
+
The developer attached reference images with their reply:`;for(let de of k)L+=`
|
|
216
|
+
Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?L+=`
|
|
217
217
|
|
|
218
|
-
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:
|
|
218
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:L+=`
|
|
219
219
|
|
|
220
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(L
|
|
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)L=Zt(a.feedback,a.imagePaths)+`
|
|
221
221
|
|
|
222
222
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
223
223
|
|
|
224
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(
|
|
224
|
+
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
|
|
225
225
|
|
|
226
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!
|
|
226
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!P&&a.threadId?await V.getThreadHistory(a.threadId):void 0,pe=P?null:await se.loadModel();L=P??Qi(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:S,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}L+=Wi(a.memoryReview),B&&(L+=Lo(a.imprintContext)),L+=`
|
|
227
227
|
|
|
228
|
-
${Ur}`;let C=wd(a.color,`[\u22B9 ${h}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${C} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${L?` (resuming: ${L.slice(0,8)})`:""}`);let K=new On(a.id),q=(de,pe)=>{if(de.type==="delta"&&"text"in de){let _e=K.push(de.text);_e.visibleText&&(N.accumulateText(pe,"response",_e.visibleText),N.broadcast({...de,text:_e.visibleText},pe,a.sourceId));for(let Ce of _e.orientations)N.broadcast({type:"orientation",jobId:pe,orientation:Ce},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&N.accumulateText(pe,"thinking",de.text);N.broadcast(de,pe,a.sourceId)},{process:se,result:ae}=w==="codex"?mn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:L,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:ln(a.agentSettings),onEvent:q}):w==="copilot"?tr(a.id,{prompt:F,projectRoot:r,resumeSessionId:L,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??b,onEvent:q}):pn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:j?["Read"]:v,claudePath:R,resumeSessionId:L,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:g,onEvent:q});N.setActiveProcess(a.id,se);let oe=await ae,be=K.finalize(oe.text),ve=be.visibleText,V=D?Oo(ve):{visibleText:ve,draft:void 0,error:void 0},Ie=V.visibleText;for(let de of be.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=Ie,oe.success){console.log(`${C} Iteration complete`),oe.fileEdits&&oe.fileEdits.length>0&&console.log(`${C} Captured ${oe.fileEdits.length} file edit(s): ${oe.fileEdits.map(z=>`${z.tool} ${z.file_path}`).join(", ")}`),oe.editEvents&&oe.editEvents.length>0&&console.log(`${C} Captured ${oe.editEvents.length} edit event(s): ${oe.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Wr(ve),pe=Gr(ve);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let z=new Set(a.annotationIds);pe.every(Ve=>z.has(Ve.annotationId))||(pe=pe.map((Ve,Ke)=>({...Ve,annotationId:a.annotationIds[Ke%a.annotationIds.length]})))}let _e=oe.fileEdits&&oe.fileEdits.length>0?oe.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):oe.toolsUsed,Ce=N.getBufferedEvents(a.id),et=Ce?fd(Ce.events,r):void 0,ke,Z=Lr(ve),fe=Fr(ve);if(fe)if(!(a.memoryReview?.packets.some(re=>re.proposalId===fe.proposalId)||a.surfacedProposalIds?.includes(fe.proposalId)))ke={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{ke=await U.commitConversationalReview(fe)}catch(re){ke={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:re instanceof Error?re.message:String(re)}}let Re=[...(oe.fileEdits??[]).map(z=>z.file_path),...(oe.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],xe,ht=a.imprintContext?.pendingGroundingExplanationIds??[];if(V.draft?.decision==="none"&&he.recordNoop(V.draft.reason),a.threadId&&V.draft?.decision==="mutate"&&!fe&&!Z)try{xe=await he.capture(V.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await ie.loadModel(),pendingGroundingExplanationIds:ht}),xe&&await U.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(z=>console.warn(`${C} Canonical Imprint evidence linkage failed:`,z))}catch(z){console.warn(`${C} Continuous imprint update failed; the thread result remains available:`,z instanceof Error?z.message:String(z))}else V.error&&console.warn(`${C} Ignored invalid imprint block: ${V.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let z=await G.getThread(a.threadId),re=new Set(xe.changes.map(Ke=>Ke.explanationId)),Ve=z?md(z.messages,re):void 0;if(Ve?.imprintSummary){let Ke=Ve.imprintSummary;await G.updateAssistantMessage(a.threadId,Ve.jobId,{imprintSummary:{...Ke,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Ke.additionalObservationCount??0)+1,coalescedTransactionIds:[...Ke.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let Ft=ds({question:de,resolutions:pe,changedFiles:Re,decisionRequired:!!Z,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),Q=et?.flatMap(z=>z.kind==="orientation"?[z.orientation]:[])??[];if(a.threadId){let z=j?Z?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Ie;await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:z,resolutions:!j&&pe.length>0?pe:void 0,question:j?void 0:de??void 0,sessionId:oe.sessionId,toolsUsed:j?void 0:_e,editEvents:!j&&oe.editEvents&&oe.editEvents.length>0?oe.editEvents:void 0,segments:!j&&et&&et.length>0?et:void 0,turn:{phase:"complete",orientation:Q,result:Ft},result:Ft,memoryReviewCard:Z??void 0,memoryReceipt:ke,imprintSummary:xe,model:a.model,provider:w})}if(a.threadId&&!fe&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let z=a.feedback.annotations.flatMap(re=>re.linkedSelector?[re.pathname?`${re.pathname}:${re.linkedSelector}`:re.linkedSelector]:[]);try{await U.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:m??(Cn(a.feedback)||"[request unavailable]"),responseSummary:de??Ie,outcome:de?"question_asked":pe.some(re=>re.status==="resolved")?"completed":"no_change",execution:{provider:w,model:a.model,sessionId:oe.sessionId},subjectHints:z,filePaths:[...(oe.fileEdits??[]).map(re=>re.file_path),...(oe.editEvents??[]).flatMap(re=>re.filePath?[re.filePath]:[])].map(re=>Bo(re)?ys(r,re):re),resolutions:pe.map(re=>({status:re.status,summary:re.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(re=>re.id)})}catch(re){console.warn(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,re instanceof Error?re.message:String(re))}}if(ke?.status==="committed"&&ke.decisionId&&w!=="copilot"&&await je({provider:w,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${ke.decisionId}`}),a.kind==="run_eval"&&Ie&&a.evalId&&a.evalRunId){let z=await U.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(z&&re){let Ve=or(ve,z.assertions),Ke=Date.now(),Hs={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:re,provider:w,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:bs(r),rawResponse:ve,scopeFingerprint:a._evalScopeFingerprint,...Ve};await U.recordEvalVerification(z,Hs),console.log(`${C} Eval run: ${z.title} \u2192 ${Ve.status}`)}}de&&(console.log(`${C} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${X.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),N.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:de,annotationIds:a.annotationIds},a.id,a.sourceId));let me=Vr(ve);me.length>0&&(console.log(`${C} Novel pattern(s): ${me.map(z=>`${z.category}/${z.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),N.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:Ie,threadId:a.threadId,annotationIds:a.annotationIds,result:Ft},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${C} Error: ${oe.error}`),a.status="error",a.error=oe.error,a.threadId&&await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:oe.error||"Unknown error",model:a.model,provider:w}),N.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:oe.error||"Unknown error",provider:w,model:a.model,recoverable:oe.recoverableError,code:oe.errorCode},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:oe.error,threadId:a.threadId,annotationIds:a.annotationIds});Ue()});let Nt=od(async(a,u)=>{if(yd(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let k=a.url||"/",m=k.split("?")[0],P=new URL(k,`http://127.0.0.1:${h}`),w=P.pathname,j=vd(a,P);if(j&&j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Vn(r)});return}if(a.headers.origin){if(!Rs(a.headers.origin)){E(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Vn(r)});return}}try{if(a.method==="POST"&&w==="/send")await Ae(a,u);else if(a.method==="GET"&&w==="/events")it(a,u);else if(a.method==="GET"&&w==="/status")await at(a,u,j);else if(a.method==="GET"&&w==="/ui-preferences")await Yn(u);else if(a.method==="PATCH"&&w==="/ui-preferences")await Zn(a,u);else if(a.method==="PATCH"&&w==="/config")await mt(a,u);else if(a.method==="POST"&&w==="/leases"){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await ze(a),D=typeof $.leaseId=="string"?$.leaseId.trim():"",L=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){E(u,400,{error:"A valid leaseId is required."});return}te();let F=B.acquire(D,L);E(u,201,{ok:!0,lease:F,ttlMs:vs})}catch{E(u,400,{error:"Invalid lease request."})}}else if(w.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(w.slice(8))}catch{E(u,400,{error:"Invalid lease id."});return}if(!$){E(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat($);if(!D){E(u,404,{error:"Lease not found."});return}E(u,200,{ok:!0,lease:D})}else{let D=B.release($);E(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&ge()}}else if(a.method==="POST"&&w==="/shutdown"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0}),setTimeout(ne,100)}else if(a.method==="POST"&&w==="/restart"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of X)try{$.res.end()}catch{}Nt.close(()=>{gs(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&w==="/capabilities")E(u,200,{providers:f});else if(w.startsWith("/imprint/"))await st(a,u,w);else if(w.startsWith("/memory/"))await we(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await $s(a,u);else if(a.method==="POST"&&w==="/reply")await Ze(a,u);else if(a.method==="POST"&&w==="/cancel")Bt(a,u);else if(a.method==="POST"&&w==="/materialize")E(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&w==="/materialization-runs")E(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&w==="/projection-runs"){let $=await ie.loadRuns();E(u,200,$)}else if(a.method==="GET"&&w==="/projection/proposals"){let $=await ie.loadModelProposals();E(u,200,$)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply-selected")){let $=w.slice(22,-15);await ct($,a,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply")){let $=w.slice(22,-6);await Ne($,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/dismiss")){let $=w.slice(22,-8);await St($,a,u)}else if(w.startsWith("/model/proposals/"))E(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await Os(a,u);else if(a.method==="DELETE"&&w==="/model/component")await Ds(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Js(a,u);else if(a.method==="DELETE"&&w==="/model/token")await Ns(a,u);else if(a.method==="POST"&&w==="/model/consolidate")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/model/synthesize")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/evals/synthesize")E(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&w==="/evals"){let $=await ie.loadModel(),D=await Promise.all((await U.getJournalEvalCases()).map(async C=>{let O=await xs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),L=bs(r),F=(await U.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===L);E(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:F,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&w.startsWith("/evals/")&&w.endsWith("/run")){let $=w.slice(7,-4);await eo($,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await cn(w.slice(7),a,u);else if(a.method==="GET"&&w==="/model"){let $=await ie.loadModel();E(u,200,{model:$})}else if(a.method==="GET"&&w.startsWith("/jobs/")&&w.endsWith("/events")){let $=w.slice(6,w.length-7),D=parseInt(P.searchParams.get("afterSeq")??"-1",10),L=N.getBufferedEvents($,isNaN(D)?-1:D);L?E(u,200,L):E(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await zs(m.slice(7),u);else if(a.method==="GET"&&w==="/threads/recent"){let $=Math.min(Math.max(parseInt(P.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent($);E(u,200,D)}else if(a.method==="GET"&&w.startsWith("/decision/")){let $=w.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))E(u,400,{error:"Invalid decision id"});else{let D=await G.getThread($),L=[...D?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(D&&L?.annotationSnapshot){let F=[...D.messages].reverse().find(C=>C.resolutions?.length);E(u,200,{decision:{id:D.id,createdAt:L.timestamp,url:L.annotationSnapshot.url,viewport:L.annotationSnapshot.viewport,color:L.annotationSnapshot.color,annotations:L.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await Y.loadDecision($);F?E(u,200,{decision:F,authority:"legacy_archive"}):E(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let $=w.slice(8);await Us($,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let $=w.slice(8);await qs($,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?Bs(a,u):a.method==="GET"&&w==="/canvas/manifest"?await Fs(u):a.method==="GET"&&w==="/canvas/app.mjs"?await Ls(u):E(u,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),E(u,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function we(a,u,k){try{if(a.method==="GET"&&k==="/memory/status"){E(u,200,await U.status());return}if(a.method==="GET"&&k==="/memory/diagnostics"){E(u,200,await U.diagnostics());return}if(a.method==="GET"&&k==="/memory/model-view"){E(u,200,await U.getModelView());return}if(a.method==="POST"&&k==="/memory/constraints"){let m=await ze(a),P=typeof m.reactComponent=="string"?m.reactComponent.trim():"",w=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",$=await U.getModelView(),D=P?$.entries.filter(C=>C.key===`components.${P}`||C.key.startsWith(`components.${P}.`)):[],L=(C,O)=>{if(!O)return!1;if(!C.includes("*"))return C===O;let K=C.split("*").map(q=>q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${K}$`).test(O)},F=(await U.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(q=>q.kind==="route"&&L(q.value,w)||q.kind==="subject"&&q.value===j),K=(C.scenarios??[]).some(q=>!!P&&(q.components??[]).some(se=>se.name===P||se.exportName===P)||!!w&&!!q.route&&q.route===w||!!w&&!!q.routePattern&&L(q.routePattern,w));return O||K}).map(C=>({id:C.id,title:C.title,verificationState:C.verificationState,assertions:C.assertions}));E(u,200,{modelEntries:D,evals:F});return}if(a.method==="POST"&&k==="/memory/conversation-action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!P||!w||!["accept","edit_and_accept","reject","defer"].includes(j)){E(u,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await G.getThread(P),D=$?.messages.find(ae=>ae.memoryReviewCard?.proposalId===w)?.memoryReviewCard;if(!$||!D){E(u,409,{error:"This decision review card is not available in the thread."});return}let L=await ie.findModelProposalsByThread(P),F=(await Promise.all(L.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(oe=>U.findPendingProposalForLegacyDecision(oe)))).some(oe=>oe?.proposalId===w)})))).find(ae=>ae.matches)?.proposal,C={proposalId:w,action:j,kind:D.kind,claim:j==="edit_and_accept"&&typeof m.claim=="string"?m.claim.trim():void 0,reason:j==="defer"?void 0:`The owner explicitly chose ${j.replaceAll("_"," ")} from the decision review card.`,taskContext:j==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:j==="defer"?["different_action","owner_request"]:void 0};if(C.action==="edit_and_accept"&&!C.claim){E(u,400,{error:"Edited decision wording is required."});return}let O=await U.commitConversationalReview(C),K=`memory-${pt().slice(0,8)}`,q=j==="accept"?"> Accepted decision":j==="edit_and_accept"?"> Edited and accepted decision":j==="reject"?"> Rejected decision":"> Deferred decision";await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:q}),await G.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:K,responseText:"",memoryReceipt:O,provider:xt(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&F&&await ie.dismissModelProposal(F.id);let se=xt(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&se!=="copilot"&&await je({provider:se,model:typeof m.model=="string"?m.model:void 0,agentSettings:gt(m),threadId:P,reason:`Project accepted decision ${O.decisionId}`}),E(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&k==="/memory/analyze"){let m=await ze(a),P=await U.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),w=Object.fromEntries([...new Set(P.issues.map(j=>j.code))].map(j=>[j,P.issues.filter($=>$.code===j).length]));E(u,200,{...P,issues:void 0,issueCounts:w});return}if(a.method==="POST"&&k==="/memory/review"){let m=await ze(a),P=await U.review(Mo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/context"){let m=await ze(a),P=await U.contextualize(Mo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/initialize"){let m=await ze(a),P=await U.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:sn});E(u,201,{status:P.status,report:{source:P.report.source,imported:P.report.imported,unresolvedAcceptance:P.report.unresolvedAcceptance,deferredModelEntries:P.report.deferredModelEntries,proofCases:P.report.proofCases,schemaIssues:P.report.schemaIssues}});return}if(a.method==="POST"&&k==="/memory/plan"){let m=await ze(a),P=await U.planReview(Eo(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,P.result.ok?200:422,P);return}if(a.method==="POST"&&k==="/memory/commit"){let m=await ze(a),P=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},w=await U.commitReview(Eo(m.command),{transactionId:typeof P.transactionId=="string"?P.transactionId:"",committedAt:typeof P.committedAt=="string"?P.committedAt:""});E(u,200,{status:await U.status(),journal:w.report});return}if(a.method==="POST"&&k==="/memory/recover"){let m=await ze(a),P=await U.recover(m.confirm===!0);E(u,200,{status:await U.status(),journal:P.report});return}E(u,404,{error:"Memory endpoint not found."})}catch(m){let P=m instanceof Error?m.message:String(m),w=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(P),j=/required|invalid|unsupported|expected|must be|confirmation/i.test(P);if(w||j){E(u,w?409:400,{error:P});return}throw m}}async function st(a,u,k){if(a.method==="GET"&&k==="/imprint/status"){let[m,P]=await Promise.all([he.store.load(),G.load()]),w=[...new Set(Object.values(P.threads).flatMap(j=>Kn(j.messages)))];E(u,200,{state:"ready",head:m.graph.head,updatedAt:m.graph.updatedAt,explanationCount:m.graph.explanations.filter(j=>j.state!=="retired").length,concreteCount:m.graph.concrete.length,relationCount:m.graph.relations.length,pendingGroundingCount:w.length,recoveredTransactions:m.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&k==="/imprint/action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!P||!w||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(j)){E(u,400,{error:"A valid thread, imprint update, and action are required."});return}let D=await G.getThread(P),L=[...D?.messages??[]].reverse().find(se=>se.role==="assistant"&&se.imprintSummary?.transactionId===w),F=L?.imprintSummary;if(!D||!L||!F){E(u,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){E(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${pt().slice(0,8)}`;await he.applyGroundingAction({summary:F,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:P,jobId:C}),await U.recordImprintEvidence({summary:F,action:j,threadId:P,jobId:C}).catch(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));let O=$t(L.result,!!L.question),K=L.turn?{...L.turn,result:$t(L.turn.result,!!L.question)}:void 0;await G.updateAssistantMessage(P,L.jobId,{imprintSummary:{...F,resolvedAction:j},...O?{result:O}:{},...K?{turn:K}:{}});let q={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:C,replyToQuestion:q[j]}),E(u,200,{ok:!0,action:j});return}E(u,404,{error:"Imprint endpoint not found."})}async function Ae(a,u){let{screenshot:k,feedback:m,color:P,provider:w,model:j,reasoningEffort:$,serviceTier:D,sourceId:L,pastedImages:F,pageScreenshots:C}=await $n(a),O;try{O=JSON.parse(m)}catch{E(u,400,{error:"Invalid feedback JSON"});return}let K=pt().slice(0,8),q={};if(C.length>0)for(let Z of C){let fe=encodeURIComponent(Z.pathname),Re=Me(c,`screenshot-${K}-${fe}.webp`);await an(Re,Z.data),q[Z.pathname]=Re}let se=Me(c,`screenshot-${K}.webp`);await an(se,k);let ae={};if(F.length>0)for(let Z of F){let fe=Me(c,`pasted-${K}-${Z.annotationId}-${Z.index}.webp`);await an(fe,Z.data),ae[Z.annotationId]||(ae[Z.annotationId]=[]),ae[Z.annotationId].push(fe)}let oe=O.annotations.map(Z=>Z.linkedSelector?Z.pathname?`${Z.pathname}:${Z.linkedSelector}`:Z.linkedSelector:null).filter(Z=>!!Z),be;if(oe.length>0){let Z=await G.findContinuationThread(oe);Z?(be=Z.id,await G.addElementIdentifiers(be,oe)):be=(await G.createThread(K,oe)).id}else be=(await G.createThread(K,[])).id;let ve=O.annotations.map(Z=>Z.id),V=Object.keys(q).length>0,Ie=await Nr(U,O,oe,Z=>console.warn(`[\u22B9 ${h}:${K}] Contextual memory unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))),de=await he.contextualize({text:Cn(O),subjectHints:[...oe,...O.annotations.flatMap(Z=>[Z.pathname,Z.elements?.[0]?.reactComponent].filter(fe=>!!fe))],pendingGroundingExplanationIds:Kn((await G.getThread(be))?.messages??[])}).catch(Z=>{console.warn(`[\u22B9 ${h}:${K}] Imprint context unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))}),pe={id:K,status:"queued",screenshotPath:se,feedback:O,createdAt:Date.now(),color:P,threadId:be,annotationIds:ve,provider:xt(w),model:j||void 0,agentSettings:gt({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:L||void 0,...V?{screenshotPaths:q}:{},...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}},_e=new Set(O.annotations.map(Z=>Z.pathname).filter(Boolean)),Ce;if(_e.size>1){let Z=new Map;for(let fe of O.annotations){let Re=fe.pathname||"(unknown)";Z.has(Re)||Z.set(Re,[]),Z.get(Re).push(fe.instruction||Is({...O,annotations:[fe]}))}Ce=[...Z.entries()].map(([fe,Re])=>`\`${fe}\`
|
|
229
|
-
${
|
|
228
|
+
${Ki}`;let O=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(`${O} Reviewing ${N} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${z?` (resuming: ${z.slice(0,8)})`:""}`);let Q=new Fn(a.id),G=(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:re,result:ce}=S==="codex"?gn(a.id,{prompt:L,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:z,model:a.model,sandboxMode:E?"read-only":void 0,configOverrides:mn(a.agentSettings),onEvent:G}):S==="copilot"?si(a.id,{prompt:L,projectRoot:i,resumeSessionId:z,model:a.model,timeoutMs:m,copilotPath:h.copilot?.path??T,onEvent:G}):fn(a.id,{prompt:L,projectRoot:i,maxTurns:d,maxBudgetUsd:l,allowedTools:E?["Read"]:b,claudePath:j,resumeSessionId:z,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:m,onEvent:G});I.setActiveProcess(a.id,re);let te=await ce,be=Q.finalize(te.text),Ie=be.visibleText,ve=B?Fo(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(`${O} Iteration complete`),te.fileEdits&&te.fileEdits.length>0&&console.log(`${O} 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(`${O} Captured ${te.editEvents.length} edit event(s): ${te.editEvents.map(W=>`${W.operation} ${W.filePath}`).join(", ")}`),a.status="done";let de=Xi(Ie),pe=Zi(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?wd(Ce.events,i):void 0,ke,ee=Hi(Ie),he=Gi(Ie);if(he)if(!(a.memoryReview?.packets.some(ie=>ie.proposalId===he.proposalId)||a.surfacedProposalIds?.includes(he.proposalId)))ke={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{ke=await q.commitConversationalReview(he)}catch(ie){ke={status:"rejected",action:he.action,proposalId:he.proposalId,message:ie instanceof Error?ie.message:String(ie)}}let Pe=[...(te.fileEdits??[]).map(W=>W.file_path),...(te.editEvents??[]).flatMap(W=>W.filePath?[W.filePath]:[])],xe,gt=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:gt}),xe&&await q.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(W=>console.warn(`${O} Canonical Imprint evidence linkage failed:`,W))}catch(W){console.warn(`${O} Continuous imprint update failed; the thread result remains available:`,W instanceof Error?W.message:String(W))}else ve.error&&console.warn(`${O} Ignored invalid imprint block: ${ve.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let W=await V.getThread(a.threadId),ie=new Set(xe.changes.map(Qe=>Qe.explanationId)),Ke=W?Id(W.messages,ie):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 Lt=gr({question:de,resolutions:pe,changedFiles:Pe,decisionRequired:!!ee,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),X=nt?.flatMap(W=>W.kind==="orientation"?[W.orientation]:[])??[];if(a.threadId){let W=E?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:!E&&pe.length>0?pe:void 0,question:E?void 0:de??void 0,sessionId:te.sessionId,toolsUsed:E?void 0:_e,editEvents:!E&&te.editEvents&&te.editEvents.length>0?te.editEvents:void 0,segments:!E&&nt&&nt.length>0?nt:void 0,turn:{phase:"complete",orientation:X,result:Lt},result:Lt,memoryReviewCard:ee??void 0,memoryReceipt:ke,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(ie=>ie.linkedSelector?[ie.pathname?`${ie.pathname}:${ie.linkedSelector}`:ie.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(Nn(a.feedback)||"[request unavailable]"),responseSummary:de??K,outcome:de?"question_asked":pe.some(ie=>ie.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:te.sessionId},subjectHints:W,filePaths:[...(te.fileEdits??[]).map(ie=>ie.file_path),...(te.editEvents??[]).flatMap(ie=>ie.filePath?[ie.filePath]:[])].map(ie=>qo(ie)?Rr(i,ie):ie),resolutions:pe.map(ie=>({status:ie.status,summary:ie.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ie=>ie.id)})}catch(ie){console.warn(`${O} Canonical memory capture failed; iteration remains available in legacy history:`,ie instanceof Error?ie.message:String(ie))}}if(ke?.status==="committed"&&ke.decisionId&&S!=="copilot"&&await Ae({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${ke.decisionId}`}),a.kind==="run_eval"&&K&&a.evalId&&a.evalRunId){let W=await q.findJournalEvalCase(a.evalId),ie=a._evalRunScope;if(W&&ie){let Ke=ci(Ie,W.assertions),Qe=Date.now(),Zr={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Qe,durationMs:Qe-a.createdAt,scope:ie,provider:S,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:jr(i),rawResponse:Ie,scopeFingerprint:a._evalScopeFingerprint,...Ke};await q.recordEvalVerification(W,Zr),console.log(`${O} Eval run: ${W.title} \u2192 ${Ke.status}`)}}de&&(console.log(`${O} \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=er(Ie);me.length>0&&(console.log(`${O} 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:Lt},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${O} 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 Bt=dd(async(a,g)=>{if(Sd(a,g),a.method==="OPTIONS"){g.writeHead(204),g.end();return}let P=a.url||"/",v=P.split("?")[0],k=new URL(P,`http://127.0.0.1:${y}`),S=k.pathname,E=Rd(a,k);if(E&&E!==r){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:E,projectName:Zn(i)});return}if(a.headers.origin){if(!Cr(a.headers.origin)){_(g,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(E!==r){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:E,projectName:Zn(i)});return}}try{if(a.method==="POST"&&S==="/send")await Me(a,g);else if(a.method==="GET"&&S==="/events")ct(a,g);else if(a.method==="GET"&&S==="/status")await dt(a,g,E);else if(a.method==="GET"&&S==="/ui-preferences")await no(g);else if(a.method==="PATCH"&&S==="/ui-preferences")await oo(a,g);else if(a.method==="PATCH"&&S==="/config")await ft(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 L=M.acquire(B,z);_(g,201,{ok:!0,lease:L,ttlMs:kr})}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{}Bt.close(()=>{Sr(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 at(a,g,S);else if(S.startsWith("/memory/"))await we(a,g,S);else if(a.method==="POST"&&S==="/mcp/install")await Lr(a,g);else if(a.method==="POST"&&S==="/reply")await tt(a,g);else if(a.method==="POST"&&S==="/cancel")Ft(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 lt(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 Rt(J,a,g)}else if(S.startsWith("/model/proposals/"))_(g,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await zr(a,g);else if(a.method==="DELETE"&&S==="/model/component")await Ur(a,g);else if(a.method==="PATCH"&&S==="/model/token")await qr(a,g);else if(a.method==="DELETE"&&S==="/model/token")await Wr(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 O=>{let N=await Ar(i,O,J);return O.verificationState==="passing"&&(!O.verifiedScopeFingerprint||!N||O.verifiedScopeFingerprint!==N)?{...O,verificationState:"stale"}:O})),z=jr(i),L=(await q.getJournalEvalRuns()).filter(O=>!O.codeFingerprint||O.codeFingerprint===z);_(g,200,{version:1,updatedAt:Date.now(),cases:B,runs:L,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&S.startsWith("/evals/")&&S.endsWith("/run")){let J=S.slice(7,-4);await io(J,a,g)}else if(a.method==="PATCH"&&S.startsWith("/evals/"))await pn(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(k.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 Kr(v.slice(7),g);else if(a.method==="GET"&&S==="/threads/recent"){let J=Math.min(Math.max(parseInt(k.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(L=>L.annotationSnapshot);if(B&&z?.annotationSnapshot){let L=[...B.messages].reverse().find(O=>O.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:L?.resolutions??[]},authority:"thread_snapshot"})}else{let L=await Z.loadDecision(J);L?_(g,200,{decision:L,authority:"legacy_archive"}):_(g,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let J=S.slice(8);await Qr(J,g)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let J=S.slice(8);await Xr(J,g)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?Gr(a,g):a.method==="GET"&&S==="/canvas/manifest"?await Hr(g):a.method==="GET"&&S==="/canvas/app.mjs"?await Vr(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,P){try{if(a.method==="GET"&&P==="/memory/status"){_(g,200,await q.status());return}if(a.method==="GET"&&P==="/memory/diagnostics"){_(g,200,await q.diagnostics());return}if(a.method==="GET"&&P==="/memory/model-view"){_(g,200,await q.getModelView());return}if(a.method==="GET"&&P==="/memory/imprint-view"){let v=await V.load(),k=[...new Set(Object.values(v.threads).flatMap(S=>ln(S.messages)))];_(g,200,await q.getImprintView(k));return}if(a.method==="POST"&&P==="/memory/constraints"){let v=await ze(a),k=typeof v.reactComponent=="string"?v.reactComponent.trim():"",S=typeof v.pathname=="string"?v.pathname.trim():"",E=typeof v.selector=="string"?v.selector.trim():"",J=await q.getModelView(),B=k?J.entries.filter(O=>O.key===`components.${k}`||O.key.startsWith(`components.${k}.`)):[],z=(O,N)=>{if(!N)return!1;if(!O.includes("*"))return O===N;let Q=O.split("*").map(G=>G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`).test(N)},L=(await q.getJournalEvalCases()).filter(O=>{if(O.status==="rejected")return!1;let N=(O.dependencies??[]).some(G=>G.kind==="route"&&z(G.value,S)||G.kind==="subject"&&G.value===E),Q=(O.scenarios??[]).some(G=>!!k&&(G.components??[]).some(re=>re.name===k||re.exportName===k)||!!S&&!!G.route&&G.route===S||!!S&&!!G.routePattern&&z(G.routePattern,S));return N||Q}).map(O=>({id:O.id,title:O.title,verificationState:O.verificationState,assertions:O.assertions}));_(g,200,{modelEntries:B,evals:L});return}if(a.method==="POST"&&P==="/memory/conversation-action"){let v=await ze(a),k=typeof v.threadId=="string"?v.threadId:"",S=typeof v.proposalId=="string"?v.proposalId:"",E=String(v.action);if(!k||!S||!["accept","edit_and_accept","reject","defer"].includes(E)){_(g,400,{error:"A valid thread, proposal, and review action are required."});return}let J=await V.getThread(k),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(k),L=(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,O={proposalId:S,action:E,kind:B.kind,claim:E==="edit_and_accept"&&typeof v.claim=="string"?v.claim.trim():void 0,reason:E==="defer"?void 0:`The owner explicitly chose ${E.replaceAll("_"," ")} from the decision review card.`,taskContext:E==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:E==="defer"?["different_action","owner_request"]:void 0};if(O.action==="edit_and_accept"&&!O.claim){_(g,400,{error:"Edited decision wording is required."});return}let N=await q.commitConversationalReview(O),Q=`memory-${ut().slice(0,8)}`,G=E==="accept"?"> Accepted decision":E==="edit_and_accept"?"> Edited and accepted decision":E==="reject"?"> Rejected decision":"> Deferred decision";await V.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:Q,replyToQuestion:G}),await V.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:Q,responseText:"",memoryReceipt:N,provider:St(typeof v.provider=="string"?v.provider:void 0),model:typeof v.model=="string"?v.model:void 0}),N.status==="committed"&&L&&await se.dismissModelProposal(L.id);let re=St(typeof v.provider=="string"?v.provider:void 0);N.status==="committed"&&N.decisionId&&re!=="copilot"&&await Ae({provider:re,model:typeof v.model=="string"?v.model:void 0,agentSettings:yt(v),threadId:k,reason:`Project accepted decision ${N.decisionId}`}),_(g,N.status==="committed"?200:409,{receipt:N});return}if(a.method==="POST"&&P==="/memory/analyze"){let v=await ze(a),k=await q.analyzeLegacy({projectKey:typeof v.projectKey=="string"?v.projectKey:void 0}),S=Object.fromEntries([...new Set(k.issues.map(E=>E.code))].map(E=>[E,k.issues.filter(J=>J.code===E).length]));_(g,200,{...k,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&P==="/memory/review"){let v=await ze(a),k=await q.review(Do(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&P==="/memory/context"){let v=await ze(a),k=await q.contextualize(Do(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&P==="/memory/initialize"){let v=await ze(a),k=await q.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:cn});_(g,201,{status:k.status,report:{source:k.report.source,imported:k.report.imported,unresolvedAcceptance:k.report.unresolvedAcceptance,deferredModelEntries:k.report.deferredModelEntries,proofCases:k.report.proofCases,schemaIssues:k.report.schemaIssues}});return}if(a.method==="POST"&&P==="/memory/plan"){let v=await ze(a),k=await q.planReview($o(v.command),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,k.result.ok?200:422,k);return}if(a.method==="POST"&&P==="/memory/commit"){let v=await ze(a),k=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},S=await q.commitReview($o(v.command),{transactionId:typeof k.transactionId=="string"?k.transactionId:"",committedAt:typeof k.committedAt=="string"?k.committedAt:""});_(g,200,{status:await q.status(),journal:S.report});return}if(a.method==="POST"&&P==="/memory/recover"){let v=await ze(a),k=await q.recover(v.confirm===!0);_(g,200,{status:await q.status(),journal:k.report});return}_(g,404,{error:"Memory endpoint not found."})}catch(v){let k=v instanceof Error?v.message:String(v),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(k),E=/required|invalid|unsupported|expected|must be|confirmation/i.test(k);if(S||E){_(g,S?409:400,{error:k});return}throw v}}async function at(a,g,P){if(a.method==="GET"&&P==="/imprint/status"){let[v,k]=await Promise.all([ge.store.load(),V.load()]),S=[...new Set(Object.values(k.threads).flatMap(E=>ln(E.messages)))].filter(E=>v.graph.explanations.some(J=>J.id===E&&J.state==="testing"));_(g,200,{state:"ready",head:v.graph.head,updatedAt:v.graph.updatedAt,explanationCount:v.graph.explanations.filter(E=>E.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"&&P==="/imprint/action"){let v=await ze(a),k=typeof v.threadId=="string"?v.threadId:"",S=typeof v.transactionId=="string"?v.transactionId:"",E=String(v.action);if(!k||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(E)){_(g,400,{error:"A valid thread, imprint update, and action are required."});return}let B=await V.getThread(k),z=[...B?.messages??[]].reverse().find(re=>re.role==="assistant"&&re.imprintSummary?.transactionId===S),L=z?.imprintSummary;if(!B||!z||!L){_(g,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){_(g,409,{error:"This imprint summary has already been resolved."});return}let O=`imprint-${ut().slice(0,8)}`;await ge.applyGroundingAction({summary:L,action:E,value:typeof v.value=="string"?v.value:void 0,threadId:k,jobId:O}),await q.recordImprintEvidence({summary:L,action:E,threadId:k,jobId:O}).catch(re=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",re));let N=Dt(z.result,!!z.question),Q=z.turn?{...z.turn,result:Dt(z.turn.result,!!z.question)}:void 0;await V.updateAssistantMessage(k,z.jobId,{imprintSummary:{...L,resolvedAction:E},...N?{result:N}:{},...Q?{turn:Q}:{}});let G={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(k,{role:"human",timestamp:Date.now(),jobId:O,replyToQuestion:G[E]}),_(g,200,{ok:!0,action:E});return}_(g,404,{error:"Imprint endpoint not found."})}async function Me(a,g){let{screenshot:P,feedback:v,color:k,provider:S,model:E,reasoningEffort:J,serviceTier:B,sourceId:z,pastedImages:L,pageScreenshots:O}=await Bn(a),N;try{N=JSON.parse(v)}catch{_(g,400,{error:"Invalid feedback JSON"});return}let Q=ut().slice(0,8),G={};if(O.length>0)for(let ee of O){let he=encodeURIComponent(ee.pathname),Pe=Ee(c,`screenshot-${Q}-${he}.webp`);await dn(Pe,ee.data),G[ee.pathname]=Pe}let re=Ee(c,`screenshot-${Q}.webp`);await dn(re,P);let ce={};if(L.length>0)for(let ee of L){let he=Ee(c,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await dn(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(G).length>0,K=await qi(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:Nn(N),subjectHints:[...te,...N.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(he=>!!he))],pendingGroundingExplanationIds:ln((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:re,feedback:N,createdAt:Date.now(),color:k,threadId:be,annotationIds:Ie,provider:St(S),model:E||void 0,agentSettings:yt({reasoningEffort:J,serviceTier:B}),...Object.keys(ce).length>0?{imagePaths:ce}:{},sourceId:z||void 0,...ve?{screenshotPaths:G}:{},...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 Pe=he.pathname||"(unknown)";ee.has(Pe)||ee.set(Pe,[]),ee.get(Pe).push(he.instruction||Tr({...N,annotations:[he]}))}Ce=[...ee.entries()].map(([he,Pe])=>`\`${he}\`
|
|
229
|
+
${Pe.map(xe=>`- ${xe}`).join(`
|
|
230
230
|
`)}`).join(`
|
|
231
|
-
`)}else Ce=
|
|
232
|
-
`):
|
|
233
|
-
`):ke&&(
|
|
234
|
-
`)),
|
|
231
|
+
`)}else Ce=Tr(N);let nt=Zt(N,Object.keys(ce).length>0?ce:void 0);await V.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:Q,screenshotPath:re,...ve?{screenshotPaths:G}:{},...Object.keys(ce).length>0?{imagePaths:ce}:{},annotationIds:Ie,annotationSnapshot:{url:N.url,viewport:N.viewport,annotations:N.annotations,color:k||void 0},feedbackSummary:Ce,feedbackContext:nt||void 0,...K?{memoryReview:K}:{},...de?{imprintContext:de}:{}});let ke=I.enqueue(pe);_(g,200,{jobId:Q,position:ke,threadId:be})}async function tt(a,g){let P=a.headers["content-type"]||"",v,k,S,E,J,B,z,L,O,N=[];if(P.includes("multipart/form-data")){let X=await Bn(a),me=X.feedback?JSON.parse(X.feedback):{};v=me.threadId,k=me.reply,S=me.color,E=me.provider,J=me.model,B=yt(me),z=me.sourceId||X.sourceId,L=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0,O=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 ie of a)X.push(typeof ie=="string"?Buffer.from(ie):ie);let me=Buffer.concat(X).toString("utf-8"),W;try{W=JSON.parse(me)}catch{_(g,400,{error:"Invalid JSON"});return}v=W.threadId,k=W.reply,S=W.color,E=W.provider,J=W.model,B=yt(W),z=W.sourceId,L=W.memoryReviewProposalId,O=W.evalRemediation?.action==="resolve"&&typeof W.evalRemediation.evalId=="string"?{evalId:W.evalRemediation.evalId,action:"resolve"}:void 0}if(!v||!k){_(g,400,{error:"Missing threadId or reply"});return}let Q=await V.getThread(v);if(!Q){_(g,404,{error:"Thread not found"});return}let G,re;if(O){let X=await q.findJournalEvalCase(O.evalId),me=(await q.getJournalEvalRuns()).filter(W=>W.evalId===O.evalId&&W.threadId===v).sort((W,ie)=>ie.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}re={evalCase:X,run:me}}if(L){let X=await se.findModelProposalsByThread(v);if(G=(await Promise.all(X.flatMap(W=>W.authorityStatus==="accepted"?[]:W.decisionIds.map(async ie=>({modelProposalId:W.id,underlying:await q.findPendingProposalForLegacyDecision(ie)}))))).filter(W=>!!W.underlying).find(W=>W.underlying.proposalId===L),!G){_(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 Fr(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??ut().slice(0,8),K=[],de=`${ve}-${Date.now()}`;for(let X=0;X<N.length;X++){let me=Ee(c,`reply-${de}-${X}.webp`);await dn(me,N[X]),K.push(me)}await V.appendMessage(v,{role:"human",timestamp:Date.now(),jobId:ve,replyToQuestion:k,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:k,subjectHints:Q.elementIdentifiers,pendingGroundingExplanationIds:ln(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]:[])),ke=[...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=St(E),Pe=G,xe=Pe?[Pe.underlying.proposalId]:ke?[ke.proposalId]:[],gt=Yi(ce,pe,he,K.length>0?K:void 0);if(re?gt+=["","## Failed eval remediation","This is a new implementation goal based on a failed Popmelt eval. Fix the product gaps identified by the evaluator.","Do not weaken, rewrite, approve, retire, or otherwise modify the eval specification unless the developer explicitly asks.","Treat the accepted product decision as governing truth; the failed implementation is what should change.",`Eval: ${JSON.stringify(re.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:re.run.summary,assertionResults:re.run.assertionResults,scope:re.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
|
|
232
|
+
`):Pe?gt+=["","## Decision review card",`Privately review proposal ${Pe.underlying.proposalId}: ${Pe.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
|
|
233
|
+
`):ke&&(gt+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(ke)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
|
|
234
|
+
`)),Ie){let X=Ie,W=[...X._replyTexts??(X._replyText?[X._replyText]:[]),k],ie=[...X._replyImagePaths??[],...K];X._replyTexts=W,X._replyText=Pr(W),X._replyImagePaths=ie.length>0?ie:void 0,X._replyPrompt=gt,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}:{}};re?qe.kind="resolve_eval":te&&(qe.kind=te),qe._replyPrompt=gt,qe._evalRemediation=!!re,qe._replyTexts=[k],qe._replyText=Pr([k]),K.length>0&&(qe._replyImagePaths=K);let Lt=be?I.enqueueNext(qe):I.enqueue(qe);_(g,200,{jobId:ve,position:Lt,threadId:v})}function ct(a,g){g.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),g.write(`event: connected
|
|
235
235
|
data: {"status":"connected"}
|
|
236
236
|
|
|
237
|
-
`);let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,P={id:pt().slice(0,8),res:u,sourceId:m};X.add(P),a.on("close",()=>{X.delete(P)})}async function at(a,u,k){i??=is(a.headers),Ue();let m=[...N.allActive,...T.allActive.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds??[],color:"#000000",kind:"project_model",standalone:V.standalone}))],[P,w,j,$,D]=await Promise.allSettled([ie.loadRuns(),ie.loadModelProposals(),U.status(),he.store.load(),G.load()]),L=[],F=V=>V.reason instanceof Error?V.reason.message:String(V.reason);P.status==="rejected"&&L.push({subsystem:"projection",message:F(P)}),w.status==="rejected"&&L.push({subsystem:"projection",message:F(w)}),j.status==="rejected"?L.push({subsystem:"memory",message:F(j)}):j.value.state==="degraded"&&L.push({subsystem:"memory",message:j.value.error??"Product memory is degraded."}),$.status==="rejected"&&L.push({subsystem:"imprint",message:F($)}),D.status==="rejected"&&L.push({subsystem:"threads",message:F(D)});let C=P.status==="fulfilled"?P.value.runs:[],O=w.status==="fulfilled"?w.value.proposals:[],K=as(C,O),q=K.actionableProposals.map(V=>({id:V.id,status:V.status,title:V.title,summary:V.summary,decisionIds:V.decisionIds,threadId:V.threadId,runId:V.runId,presentationJobId:V.presentationJobId,authorityStatus:V.authorityStatus,underlyingProposalId:V.underlyingProposalId,createdAt:V.createdAt,updatedAt:V.updatedAt,appliedAt:V.appliedAt,dismissedAt:V.dismissedAt,generatedEvalIds:V.generatedEvalIds,evalProjections:V.evalProjections,error:V.error})),se=j.status==="fulfilled"?j.value:{initialized:!1,state:"degraded",error:F(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(V=>Kn(V.messages)))]:[],oe=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(V=>V.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:$.value.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F($),pendingGroundingCount:ae.length,admission:he.diagnostics(),admissionWindowStartedAt:e},be=L.length>0?"degraded":se.state==="absent"||se.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();E(u,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:be,issues:L},version:sn,restartMode:p,projectId:s,projectName:Vn(r),projectRoot:r,requestProjectId:k,projectIdVerified:k===s,devOrigin:i,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds,color:V.color,kind:V.kind,standalone:"standalone"in V?V.standalone:void 0})),queueDepth:N.depth+T.depth,projectionQueueDepth:T.depth,leases:{active:B.isActivated,count:B.size,nextExpiryAt:B.nextExpiryAt,shutdownPending:H},projection:{state:P.status==="fulfilled"&&w.status==="fulfilled"?"ready":"degraded",activeJob:T.active?{id:T.active.id,status:T.active.status,threadId:T.active.threadId,annotationIds:T.active.annotationIds??[],provider:T.active.provider,model:T.active.model}:null,queueDepth:T.depth,recentRuns:K.recentRuns,recentAppliedRuns:K.recentAppliedRuns,actionableProposalCounts:K.actionableProposalCounts,actionableProposals:q},memory:se,imprint:oe,recentJobsRetentionMs:Je,recentJobs:Pe})}async function mt(a,u){let k=await new Promise(m=>{let P="";a.on("data",w=>{P+=w.toString()}),a.on("end",()=>m(P))});try{let m=JSON.parse(k);typeof m.devOrigin=="string"&&(i=m.devOrigin||null),E(u,200,{ok:!0,devOrigin:i})}catch{E(u,400,{error:"Invalid JSON"})}}async function Yn(a){let u=await M.load();E(a,200,{ok:!0,...u})}async function Zn(a,u){let k=await ze(a);if(!ms(k.theme)){E(u,400,{error:"theme must be light, dark, or auto"});return}let m=await M.setTheme(k.theme);E(u,200,{ok:!0,exists:!0,preferences:m})}async function Bt(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("jobId"),P=m?N.allActive.filter(F=>F.id===m):N.allActive,w=m?T.allActive.filter(F=>F.id===m):T.allActive,j=[...P.map(F=>F.threadId),...w.map(F=>F.threadId)].filter(Boolean),$=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),L=!!($||D);for(let F of j)await G.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});E(u,200,{cancelled:L})}async function je(a){let u=pt().slice(0,8),k=a.threadId,m=!k;k||(k=(await G.createThread(u,[])).id,Ge.set(k,"project_model")),m&&await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:u,feedbackSummary:a.reason}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:u,responseText:m?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let P={id:u,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:k,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:m},w=T.enqueue(P);return{jobId:u,position:w,threadId:k}}async function Ne(a,u){let k=decodeURIComponent(a),m=await ie.findModelProposal(k);if(!m){E(u,404,{error:"Model proposal not found"});return}E(u,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:m})}async function ct(a,u,k){let m=decodeURIComponent(a),P=[];for await(let O of u)P.push(typeof O=="string"?Buffer.from(O):O);let w;try{w=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{E(k,400,{error:"Invalid JSON"});return}let j=(w.changes??[]).flatMap(O=>{if(!Array.isArray(O.path)||O.path.length===0)return[];let K=O.path.filter(se=>typeof se=="string"||typeof se=="number");if(K.length!==O.path.length)return[];let q=Array.isArray(O.decisionIds)?O.decisionIds.filter(se=>typeof se=="string"):void 0;return[{path:K,value:O.value,remove:O.remove===!0,decisionIds:q}]});if(j.length===0){E(k,400,{error:"No selected model changes"});return}let $=(w.changeSummaries??[]).flatMap(O=>{if(!O||typeof O!="object")return[];let K=Array.isArray(O.path)?O.path.filter(q=>typeof q=="string"||typeof q=="number"):void 0;return Array.isArray(O.path)&&K?.length!==O.path.length?[]:[{group:typeof O.group=="string"?O.group:void 0,label:typeof O.label=="string"?O.label:void 0,detail:typeof O.detail=="string"?O.detail:void 0,path:K,value:O.value,currentValue:O.currentValue}]}),D=await ie.findModelProposal(m);if(!D){E(k,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){E(k,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){E(k,409,{error:`Model proposal is already ${D.status}.`});return}let L=D.decisionIds.map(O=>{let K=D.changes?.filter(ae=>ae.decisionIds.includes(O)).length??0,q=j.filter(ae=>ae.decisionIds?.includes(O)).length,se=q===0?"unprojected":K>q?"partially_projected":"projected";return{decisionId:O,status:se}}),F=await U.applyModelProjection({runId:D.runId??D.id,presentationJobId:D.presentationJobId,decisionIds:D.decisionIds,changes:j.map(O=>({path:O.path,value:O.value,decisionIds:O.decisionIds})),coverage:L}),C=await ie.applySelectedModelProposal(m,j,$);if(!C){E(k,404,{error:"Model proposal not found"});return}if(await Ye(C),C.threadId){let O=xt(w.provider),K=typeof w.model=="string"&&w.model?w.model:void 0;await G.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${C.id}`,responseText:"",provider:O,model:K})}E(k,200,{proposal:C,projection:F})}async function St(a,u,k){let m=decodeURIComponent(a),{provider:P,model:w}=await ft(u),j=await ie.dismissModelProposal(m);if(!j){E(k,404,{error:"Model proposal not found"});return}j.threadId&&await G.appendMessage(j.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${j.id}`,responseText:"",provider:P,model:w}),E(k,200,{proposal:j})}async function ft(a){try{let u=[];for await(let m of a)u.push(typeof m=="string"?Buffer.from(m):m);if(u.length===0)return{};let k=JSON.parse(Buffer.concat(u).toString());return{provider:xt(typeof k.provider=="string"?k.provider:void 0),model:typeof k.model=="string"&&k.model?k.model:void 0,agentSettings:gt(k)}}catch{return{}}}async function eo(a,u,k){let m=decodeURIComponent(a),P=await U.findJournalEvalCase(m);if(!P){E(k,404,{error:"Eval not found"});return}if(P.status!=="approved"){E(k,400,{error:"Only approved evals can be run"});return}let{screenshot:w,feedback:j,provider:$,model:D,reasoningEffort:L,serviceTier:F,sourceId:C}=await $n(u),O=xt($)??I;if(O==="copilot"){E(k,400,{error:"Eval runs are not available for Copilot yet."});return}let K={};try{K=j?JSON.parse(j):{}}catch{E(k,400,{error:"Invalid eval run context JSON"});return}let q=pt().slice(0,8),se=pt().slice(0,8),ae=Me(c,`eval-run-${q}.webp`);await an(ae,w);let oe=await ue.persistEvalScreenshot(w),be=K.viewport,ve=be&&typeof be=="object"?be:{},V={type:"current_page",url:typeof K.url=="string"?K.url:"",viewport:{width:typeof ve.width=="number"?ve.width:0,height:typeof ve.height=="number"?ve.height:0}},Ie=await ie.loadModel(),de=await xs(r,P,Ie),pe=O==="claude"?S.name:O==="codex"?A.name:null,_e=O==="codex"?_.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=ir({evalCase:P,scope:V,model:Ie,screenshotPath:ae,chromeDevtoolsAvailable:_e}),ke=(await G.createThread(se,[])).id;Ge.set(ke,"run_eval");let Z={timestamp:new Date().toISOString(),url:V.url,viewport:V.viewport,scrollPosition:{x:typeof K.scrollX=="number"?K.scrollX:0,y:typeof K.scrollY=="number"?K.scrollY:0},annotations:[],styleModifications:[]};await G.appendMessage(ke,{role:"human",timestamp:Date.now(),jobId:se,screenshotPath:ae,feedbackSummary:`Run eval \u2014 ${P.title}`,feedbackContext:[`Eval: ${P.title}`,"Scope: current page",`URL: ${V.url||"unknown"}`,"Assertions:",...P.assertions.map(xe=>`- ${xe}`)].join(`
|
|
238
|
-
`)});let fe={id:se,status:"queued",screenshotPath:ae,feedback:Z,createdAt:Date.now(),color:"#111827",threadId:ke,kind:"run_eval",evalId:m,evalRunId:q,provider:O,model:D||void 0,agentSettings:gt({reasoningEffort:L,serviceTier:F}),sourceId:C||void 0};fe._replyPrompt=Ce,fe._evalRunScope=V,fe._evalScreenshotPath=oe,fe._evalScopeFingerprint=de;let Re=N.enqueue(fe);E(k,200,{jobId:se,runId:q,position:Re,threadId:ke,screenshotPath:oe})}async function cn(a,u,k){let m=decodeURIComponent(a),P={},w,j,$;try{let L=[];for await(let C of u)L.push(typeof C=="string"?Buffer.from(C):C);let F=JSON.parse(Buffer.concat(L).toString());w=F.status,j=F.title,$=F.assertions}catch{E(k,400,{error:"Invalid JSON"});return}if(w!==void 0&&w!=="pending"&&w!=="approved"&&w!=="rejected"){E(k,400,{error:"Invalid status"});return}if(w&&(P.status=w),j!==void 0){if(typeof j!="string"||j.trim().length===0){E(k,400,{error:"Invalid title"});return}P.title=j.trim()}if($!==void 0){if(!Array.isArray($)){E(k,400,{error:"Invalid assertions"});return}let L=$.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(L.length===0){E(k,400,{error:"Invalid assertions"});return}P.assertions=L}if(!P.status&&!P.title&&!P.assertions){E(k,400,{error:"No eval changes provided"});return}let D=await U.updateJournalEvalCase(m,P);if(!D){E(k,404,{error:"Eval not found"});return}E(k,200,{eval:D})}async function Cs(a){let u=Ge.get(a);if(u)return u;let P=(await G.getThread(a))?.messages.find(w=>w.role==="human")?.feedbackSummary??"";if(P.startsWith("Synthesize evals"))return Ge.set(a,"synthesize_evals"),"synthesize_evals";if(P.startsWith("Synthesize rules"))return Ge.set(a,"synthesize"),"synthesize";if(P.startsWith("Run eval"))return Ge.set(a,"run_eval"),"run_eval";if(P.startsWith("Materialize model")||P.startsWith("Project model"))return Ge.set(a,"project_model"),"project_model"}async function $s(a,u){let k=[];for await(let D of a)k.push(typeof D=="string"?Buffer.from(D):D);let m;if(k.length>0)try{m=JSON.parse(Buffer.concat(k).toString("utf-8")).serverUrl}catch{}let P=[];f.claude?.available&&f.claude.mcp&&!f.claude.mcp.found&&P.push(await xr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&P.push(await Sr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&P.push(await Pr(m,f.copilot.path??b));let[w,j,$]=await Promise.all([fo(r),ho(r),go(r,f.copilot?.path??b)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),E(u,200,{results:P,capabilities:{providers:f}})}async function Os(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:{description:""},claim:`${m.name} is an explicitly governed component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await rt({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});E(u,200,{added:!0,alreadyExists:!1,...P,evalId:w})}async function Ds(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:null,claim:`${m.name} is not governed as a component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await rt({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});E(u,200,{removed:!0,...P,evalId:w})}async function Js(a,u){let k=[];for await(let $ of a)k.push(typeof $=="string"?Buffer.from($):$);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){E(u,400,{error:"Missing or invalid path/value"});return}let P=m.value;try{let $=JSON.parse(m.value);$&&typeof $=="object"&&(P=$)}catch{}let w=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:P,claim:`${m.path} uses ${m.value} in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let j=await rt({decisionId:w.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});E(u,200,{updated:!0,...w,evalId:j})}async function Ns(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){E(u,400,{error:"Missing or invalid path"});return}let P=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:null,claim:`${m.path} is intentionally absent from the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await rt({decisionId:P.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});E(u,200,{removed:!0,...P,evalId:w})}function Bs(a,u){let k=i??"http://localhost:3000";if(!i){let P=a.headers.referer||a.headers.origin;if(P)try{let w=new URL(typeof P=="string"?P:P[0]||"");(w.hostname==="localhost"||w.hostname==="127.0.0.1")&&(k=w.origin)}catch{}}let m=Uo(h,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Fs(a){let u=Date.now();if(ut&&u<ut.expires){E(a,200,ut.data);return}try{let{scanForComponents:k}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),P=await k(r);ut={data:P,expires:u+5e3},m(P,r,Jt).then(w=>{Jt=w}).catch(w=>console.warn("[Bridge] Render generation failed:",w)),E(a,200,P)}catch(k){console.error("[Bridge] Scanner error:",k),E(a,500,{error:"Failed to scan components"})}}async function Ls(a){let u=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let k=id(import.meta.url);u.unshift(Me(sd(k),"canvas.mjs"))}catch{}for(let k of u)try{let m=await No(k,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(m);return}catch{}console.error("[Bridge] Canvas bundle not found in:",u),E(a,404,{error:"Canvas bundle not found"})}async function zs(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(u,400,{error:"Invalid filename"});return}try{let k=[Me(c,a),Me(r,".popmelt","artifacts","thread-media",a),Me(r,".popmelt","artifacts","eval-screenshots",a),Me(r,".popmelt","evals","screenshots",a),Me(r,".popmelt","screenshots",a)],m;for(let j of k)try{m=await No(j);break}catch{}if(!m)throw new Error("File not found");let P=a.split(".").pop()?.toLowerCase(),w=P==="png"?"image/png":P==="webp"?"image/webp":P==="jpg"||P==="jpeg"?"image/jpeg":"application/octet-stream";u.writeHead(200,{"Content-Type":w,"Cache-Control":"public, max-age=3600"}),u.end(m)}catch{E(u,404,{error:"File not found"})}}function dn(a){return`/files/${Vn(a)}`}async function Us(a,u){let k=await G.getThread(a);if(!k){E(u,404,{error:"Thread not found"});return}let m=k.messages.some(C=>C.role==="assistant"&&C.responseText?.includes("<eval_run_result>")),P=k.messages.filter(C=>C.role==="assistant"&&C.responseText?.includes("Model suggestion ready")),[w,j]=await Promise.all([m?U.getJournalEvalRuns().then(C=>C.filter(O=>O.threadId===a).sort((O,K)=>K.completedAt-O.completedAt)[0]):Promise.resolve(void 0),P.length>0?ie.findModelProposalsByThread(a):Promise.resolve([])]),$=w?await U.findJournalEvalCase(w.evalId):null,D=await Promise.all(j.map(async(C,O)=>{if(C.authorityStatus==="accepted")return C;let K=(await Promise.all(C.decisionIds.map(q=>U.findPendingProposalForLegacyDecision(q)))).find(Boolean);return{...C,authorityStatus:"legacy_untrusted",presentationJobId:C.presentationJobId??P[O]?.jobId??P.at(-1)?.jobId,underlyingProposalId:K?.proposalId,underlyingClaim:K?.claim}})),L=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,F=k.messages.map(({screenshotPath:C,screenshotPaths:O,imagePaths:K,replyImagePaths:q,...se})=>({...se,...se.role==="assistant"&&w&&se.responseText?.includes("<eval_run_result>")?{evalRun:{...w,title:$?.title}}:{},...C?{screenshotUrl:dn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,oe])=>[ae,dn(oe)]))}:{},...K?{imageUrls:Object.fromEntries(Object.entries(K).map(([ae,oe])=>[ae,oe.map(dn)]))}:{},...q?{replyImageUrls:q.map(dn)}:{}}));E(u,200,{id:k.id,createdAt:k.createdAt,messages:F,modelProposal:L,modelProposals:D})}async function qs(a,u){let k=decodeURIComponent(a);if(!await G.deleteThread(k)){E(u,404,{deleted:!1,error:"Thread not found"});return}E(u,200,{deleted:!0})}let Fo=9,Lo=!1;for(let a=n;a<n+Fo;a++)try{await bd(Nt,a),h=a,Lo=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await Id(a);if(ss(k,{projectId:s,version:sn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Lo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Fo-1} in use`);for(let[a,u]of Object.entries(f))!u.available||!u.path||x(a,u.path).then(k=>{if(k)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),u.available=!1,u.path=null;for(let m of X)Qn(m,{type:"capabilities_changed",data:{}})}});let Ws=setInterval(()=>{Ss(c).catch(()=>{})},dd),zo=setInterval(()=>{B.expireStale().becameEmpty&&ge()},pd);return zo.unref?.(),{port:h,projectId:s,close:async()=>{clearInterval(Ws),clearInterval(zo),te(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of X)try{a.res.end()}catch{}return X.clear(),new Promise(a=>{Nt.close(()=>a())})}}}async function Ss(o){try{let e=await Zc(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let s=await td(r);n-s.mtimeMs>ld&&await nd(r)}catch{}}}catch{}}var Rd=parseInt(process.env.POPMELT_PORT||"1111",10),Es=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Td=process.env.POPMELT_DEV_ORIGIN||void 0,jd=process.env.POPMELT_COPILOT_PATH||void 0,Ms=js(Es,".popmelt"),As=js(Ms,"bridge.lock");async function Ed(o){await Sd(Ms,{recursive:!0}),await kd(As,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
|
|
239
|
-
`)}async function
|
|
237
|
+
`);let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,k={id:ut().slice(0,8),res:g,sourceId:v};Y.add(k),a.on("close",()=>{Y.delete(k)})}async function dt(a,g,P){s??=mr(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}))],[k,S,E,J,B]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),q.status(),ge.store.load(),V.load()]),z=[],L=K=>K.reason instanceof Error?K.reason.message:String(K.reason);k.status==="rejected"&&z.push({subsystem:"projection",message:L(k)}),S.status==="rejected"&&z.push({subsystem:"projection",message:L(S)}),E.status==="rejected"?z.push({subsystem:"memory",message:L(E)}):E.value.state==="degraded"&&z.push({subsystem:"memory",message:E.value.error??"Product memory is degraded."}),J.status==="rejected"&&z.push({subsystem:"imprint",message:L(J)}),B.status==="rejected"&&z.push({subsystem:"threads",message:L(B)});let O=k.status==="fulfilled"?k.value.runs:[],N=S.status==="fulfilled"?S.value.proposals:[],Q=fr(O,N),G=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})),re=E.status==="fulfilled"?E.value:{initialized:!1,state:"degraded",error:L(E)},ce=B.status==="fulfilled"?[...new Set(Object.values(B.value.threads).flatMap(K=>ln(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:L(J),pendingGroundingCount:te.length,admission:ge.diagnostics(),admissionWindowStartedAt:e},Ie=z.length>0?"degraded":re.state==="absent"||re.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();_(g,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:Ie,issues:z},version:cn,restartMode:p,projectId:r,projectName:Zn(i),projectRoot:i,requestProjectId:P,projectIdVerified:P===r,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:k.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:G},memory:re,imprint:be,recentJobsRetentionMs:Je,recentJobs:Re})}async function ft(a,g){let P=await new Promise(v=>{let k="";a.on("data",S=>{k+=S.toString()}),a.on("end",()=>v(k))});try{let v=JSON.parse(P);typeof v.devOrigin=="string"&&(s=v.devOrigin||null),_(g,200,{ok:!0,devOrigin:s})}catch{_(g,400,{error:"Invalid JSON"})}}async function no(a){let g=await $.load();_(a,200,{ok:!0,...g})}async function oo(a,g){let P=await ze(a);if(!wr(P.theme)){_(g,400,{error:"theme must be light, dark, or auto"});return}let v=await $.setTheme(P.theme);_(g,200,{ok:!0,exists:!0,preferences:v})}async function Ft(a,g){let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),k=v?I.allActive.filter(L=>L.id===v):I.allActive,S=v?w.allActive.filter(L=>L.id===v):w.allActive,E=[...k.map(L=>L.threadId),...S.map(L=>L.threadId)].filter(Boolean),J=v?I.cancelJob(v):I.cancelActive(),B=v?w.cancelJob(v):w.cancelActive(),z=!!(J||B);for(let L of E)await V.appendMessage(L,{role:"assistant",timestamp:Date.now(),jobId:v||B?.id||"",cancelled:!0});_(g,200,{cancelled:z})}async function Ae(a){let g=ut().slice(0,8),P=a.threadId,v=!P;P||(P=(await V.createThread(g,[])).id,Ve.set(P,"project_model")),v&&await V.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:a.reason}),await V.appendMessage(P,{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 k={id:g,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:P,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:v},S=w.enqueue(k);return{jobId:g,position:S,threadId:P}}async function Ne(a,g){let P=decodeURIComponent(a),v=await se.findModelProposal(P);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 lt(a,g,P){let v=decodeURIComponent(a),k=[];for await(let N of g)k.push(typeof N=="string"?Buffer.from(N):N);let S;try{S=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{_(P,400,{error:"Invalid JSON"});return}let E=(S.changes??[]).flatMap(N=>{if(!Array.isArray(N.path)||N.path.length===0)return[];let Q=N.path.filter(re=>typeof re=="string"||typeof re=="number");if(Q.length!==N.path.length)return[];let G=Array.isArray(N.decisionIds)?N.decisionIds.filter(re=>typeof re=="string"):void 0;return[{path:Q,value:N.value,remove:N.remove===!0,decisionIds:G}]});if(E.length===0){_(P,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(G=>typeof G=="string"||typeof G=="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){_(P,404,{error:"Model proposal not found"});return}if(B.authorityStatus!=="accepted"){_(P,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(B.status!=="pending"){_(P,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,G=E.filter(ce=>ce.decisionIds?.includes(N)).length,re=G===0?"unprojected":Q>G?"partially_projected":"projected";return{decisionId:N,status:re}}),L=await q.applyModelProjection({runId:B.runId??B.id,presentationJobId:B.presentationJobId,decisionIds:B.decisionIds,changes:E.map(N=>({path:N.path,value:N.value,decisionIds:N.decisionIds})),coverage:z}),O=await se.applySelectedModelProposal(v,E,J);if(!O){_(P,404,{error:"Model proposal not found"});return}if(await et(O),O.threadId){let N=St(S.provider),Q=typeof S.model=="string"&&S.model?S.model:void 0;await V.appendMessage(O.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${O.id}`,responseText:"",provider:N,model:Q})}_(P,200,{proposal:O,projection:L})}async function Rt(a,g,P){let v=decodeURIComponent(a),{provider:k,model:S}=await ht(g),E=await se.dismissModelProposal(v);if(!E){_(P,404,{error:"Model proposal not found"});return}E.threadId&&await V.appendMessage(E.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${E.id}`,responseText:"",provider:k,model:S}),_(P,200,{proposal:E})}async function ht(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 P=JSON.parse(Buffer.concat(g).toString());return{provider:St(typeof P.provider=="string"?P.provider:void 0),model:typeof P.model=="string"&&P.model?P.model:void 0,agentSettings:yt(P)}}catch{return{}}}async function io(a,g,P){let v=decodeURIComponent(a),k=await q.findJournalEvalCase(v);if(!k){_(P,404,{error:"Eval not found"});return}if(k.status!=="approved"){_(P,400,{error:"Only approved evals can be run"});return}let{screenshot:S,feedback:E,provider:J,model:B,reasoningEffort:z,serviceTier:L,sourceId:O}=await Bn(g),N=St(J)??x;if(N==="copilot"){_(P,400,{error:"Eval runs are not available for Copilot yet."});return}let Q={};try{Q=E?JSON.parse(E):{}}catch{_(P,400,{error:"Invalid eval run context JSON"});return}let G=ut().slice(0,8),re=ut().slice(0,8),ce=Ee(c,`eval-run-${G}.webp`);await dn(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 Ar(i,k,K),pe=N==="claude"?A.name:N==="codex"?D.name:null,_e=N==="codex"?C.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=pi({evalCase:k,scope:ve,model:K,screenshotPath:ce,chromeDevtoolsAvailable:_e}),ke=(await V.createThread(re,[])).id;Ve.set(ke,"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(ke,{role:"human",timestamp:Date.now(),jobId:re,screenshotPath:ce,feedbackSummary:`Run eval \u2014 ${k.title}`,feedbackContext:[`Eval: ${k.title}`,"Scope: current page",`URL: ${ve.url||"unknown"}`,"Assertions:",...k.assertions.map(xe=>`- ${xe}`)].join(`
|
|
238
|
+
`)});let he={id:re,status:"queued",screenshotPath:ce,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:ke,kind:"run_eval",evalId:v,evalRunId:G,provider:N,model:B||void 0,agentSettings:yt({reasoningEffort:z,serviceTier:L}),sourceId:O||void 0};he._replyPrompt=Ce,he._evalRunScope=ve,he._evalScreenshotPath=te,he._evalScopeFingerprint=de;let Pe=I.enqueue(he);_(P,200,{jobId:re,runId:G,position:Pe,threadId:ke,screenshotPath:te})}async function pn(a,g,P){let v=decodeURIComponent(a),k={},S,E,J;try{let z=[];for await(let O of g)z.push(typeof O=="string"?Buffer.from(O):O);let L=JSON.parse(Buffer.concat(z).toString());S=L.status,E=L.title,J=L.assertions}catch{_(P,400,{error:"Invalid JSON"});return}if(S!==void 0&&S!=="pending"&&S!=="approved"&&S!=="rejected"){_(P,400,{error:"Invalid status"});return}if(S&&(k.status=S),E!==void 0){if(typeof E!="string"||E.trim().length===0){_(P,400,{error:"Invalid title"});return}k.title=E.trim()}if(J!==void 0){if(!Array.isArray(J)){_(P,400,{error:"Invalid assertions"});return}let z=J.filter(L=>typeof L=="string").map(L=>L.trim()).filter(Boolean);if(z.length===0){_(P,400,{error:"Invalid assertions"});return}k.assertions=z}if(!k.status&&!k.title&&!k.assertions){_(P,400,{error:"No eval changes provided"});return}let B=await q.updateJournalEvalCase(v,k);if(!B){_(P,404,{error:"Eval not found"});return}_(P,200,{eval:B})}async function Fr(a){let g=Ve.get(a);if(g)return g;let k=(await V.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(k.startsWith("Synthesize evals"))return Ve.set(a,"synthesize_evals"),"synthesize_evals";if(k.startsWith("Synthesize rules"))return Ve.set(a,"synthesize"),"synthesize";if(k.startsWith("Run eval"))return Ve.set(a,"run_eval"),"run_eval";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return Ve.set(a,"project_model"),"project_model"}async function Lr(a,g){let P=[];for await(let B of a)P.push(typeof B=="string"?Buffer.from(B):B);let v;if(P.length>0)try{v=JSON.parse(Buffer.concat(P).toString("utf-8")).serverUrl}catch{}let k=[];h.claude?.available&&h.claude.mcp&&!h.claude.mcp.found&&k.push(await Ti(v)),h.codex?.available&&h.codex.mcp&&!h.codex.mcp.found&&k.push(await ji(v)),h.copilot?.available&&h.copilot.mcp&&!h.copilot.mcp.found&&k.push(await Ai(v,h.copilot.path??T));let[S,E,J]=await Promise.all([vo(i),Io(i),wo(i,h.copilot?.path??T)]);h.claude&&(h.claude.mcp=S),h.codex&&(h.codex.mcp=E),h.copilot&&(h.copilot.mcp=J),_(g,200,{results:k,capabilities:{providers:h}})}async function zr(a,g){let P=[];for await(let E of a)P.push(typeof E=="string"?Buffer.from(E):E);let v;try{v=JSON.parse(Buffer.concat(P).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 k=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 st({decisionId:k.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is an explicitly governed component in the product model.`});_(g,200,{added:!0,alreadyExists:!1,...k,evalId:S})}async function Ur(a,g){let P=[];for await(let E of a)P.push(typeof E=="string"?Buffer.from(E):E);let v;try{v=JSON.parse(Buffer.concat(P).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 k=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 st({decisionId:k.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is not governed as a component in the product model.`});_(g,200,{removed:!0,...k,evalId:S})}async function qr(a,g){let P=[];for await(let J of a)P.push(typeof J=="string"?Buffer.from(J):J);let v;try{v=JSON.parse(Buffer.concat(P).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 k=v.value;try{let J=JSON.parse(v.value);J&&typeof J=="object"&&(k=J)}catch{}let S=await q.recordDirectModelMutation({key:`tokens.${v.path}`,value:k,claim:`${v.path} uses ${v.value} in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let E=await st({decisionId:S.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} uses ${v.value} in the product model.`});_(g,200,{updated:!0,...S,evalId:E})}async function Wr(a,g){let P=[];for await(let E of a)P.push(typeof E=="string"?Buffer.from(E):E);let v;try{v=JSON.parse(Buffer.concat(P).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 k=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 st({decisionId:k.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} is intentionally absent from the product model.`});_(g,200,{removed:!0,...k,evalId:S})}function Gr(a,g){let P=s??"http://localhost:3000";if(!s){let k=a.headers.referer||a.headers.origin;if(k)try{let S=new URL(typeof k=="string"?k:k[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(P=S.origin)}catch{}}let v=Vo(y,P);g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(v)}async function Hr(a){let g=Date.now();if(mt&&g<mt.expires){_(a,200,mt.data);return}try{let{scanForComponents:P}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:v}=await import("./render-generator-HWFLZYC3.mjs"),k=await P(i);mt={data:k,expires:g+5e3},v(k,i,Nt).then(S=>{Nt=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,k)}catch(P){console.error("[Bridge] Scanner error:",P),_(a,500,{error:"Failed to scan components"})}}async function Vr(a){let g=[Ee(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ee(i,"packages","popmelt","dist","canvas.mjs")];try{let P=ud(import.meta.url);g.unshift(Ee(pd(P),"canvas.mjs"))}catch{}for(let P of g)try{let v=await Uo(P,"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 Kr(a,g){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(g,400,{error:"Invalid filename"});return}try{let P=[Ee(c,a),Ee(i,".popmelt","artifacts","thread-media",a),Ee(i,".popmelt","artifacts","eval-screenshots",a),Ee(i,".popmelt","evals","screenshots",a),Ee(i,".popmelt","screenshots",a)],v;for(let E of P)try{v=await Uo(E);break}catch{}if(!v)throw new Error("File not found");let k=a.split(".").pop()?.toLowerCase(),S=k==="png"?"image/png":k==="webp"?"image/webp":k==="jpg"||k==="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 un(a){return`/files/${Zn(a)}`}async function Qr(a,g){let P=await V.getThread(a);if(!P){_(g,404,{error:"Thread not found"});return}let v=P.messages.some(O=>O.role==="assistant"&&O.responseText?.includes("<eval_run_result>")),k=P.messages.filter(O=>O.role==="assistant"&&O.responseText?.includes("Model suggestion ready")),[S,E]=await Promise.all([v?q.getJournalEvalRuns().then(O=>O.filter(N=>N.threadId===a).sort((N,Q)=>Q.completedAt-N.completedAt)[0]):Promise.resolve(void 0),k.length>0?se.findModelProposalsByThread(a):Promise.resolve([])]),J=S?await q.findJournalEvalCase(S.evalId):null,B=await Promise.all(E.map(async(O,N)=>{if(O.authorityStatus==="accepted")return O;let Q=(await Promise.all(O.decisionIds.map(G=>q.findPendingProposalForLegacyDecision(G)))).find(Boolean);return{...O,authorityStatus:"legacy_untrusted",presentationJobId:O.presentationJobId??k[N]?.jobId??k.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),z=[...B].sort((O,N)=>N.updatedAt-O.updatedAt)[0]??null,L=P.messages.map(({screenshotPath:O,screenshotPaths:N,imagePaths:Q,replyImagePaths:G,...re})=>({...re,...re.role==="assistant"&&S&&re.responseText?.includes("<eval_run_result>")?{evalRun:{...S,title:J?.title}}:{},...O?{screenshotUrl:un(O)}:{},...N?{screenshotUrls:Object.fromEntries(Object.entries(N).map(([ce,te])=>[ce,un(te)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ce,te])=>[ce,te.map(un)]))}:{},...G?{replyImageUrls:G.map(un)}:{}}));_(g,200,{id:P.id,createdAt:P.createdAt,messages:L,modelProposal:z,modelProposals:B})}async function Xr(a,g){let P=decodeURIComponent(a);if(!await V.deleteThread(P)){_(g,404,{deleted:!1,error:"Thread not found"});return}_(g,200,{deleted:!0})}let Wo=9,Go=!1;for(let a=n;a<n+Wo;a++)try{await Td(Bt,a),y=a,Go=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(g){if(g.code==="EADDRINUSE"){let P=await Pd(a);if(ur(P,{projectId:r,version:cn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw g}if(!Go)throw new Error(`[Bridge] All ports ${n}\u2013${n+Wo-1} in use`);for(let[a,g]of Object.entries(h))!g.available||!g.path||u(a,g.path).then(P=>{if(P)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)eo(v,{type:"capabilities_changed",data:{}})}});let Yr=setInterval(()=>{Er(c).catch(()=>{})},hd),Ho=setInterval(()=>{M.expireStale().becameEmpty&&ye()},yd);return Ho.unref?.(),{port:y,projectId:r,close:async()=>{clearInterval(Yr),clearInterval(Ho),ne(),M.clear(),await I.destroyAsync(),w.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{Bt.close(()=>a())})}}}async function Er(o){try{let e=await rd(o),n=Date.now();for(let t of e){let i=Ee(o,t);try{let r=await ad(i);n-r.mtimeMs>gd&&await cd(i)}catch{}}}catch{}}var _d=parseInt(process.env.POPMELT_PORT||"1111",10),Or=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Cd=process.env.POPMELT_DEV_ORIGIN||void 0,$d=process.env.POPMELT_COPILOT_PATH||void 0,Jr=Dr(Or,".popmelt"),Nr=Dr(Jr,"bridge.lock");async function Dd(o){await Ad(Jr,{recursive:!0}),await Md(Nr,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
|
|
239
|
+
`)}async function Br(){try{await Ed(Nr)}catch{}}async function Od(){let o=await $r({port:_d,projectRoot:Or,devOrigin:Cd,copilotPath:$d,restartMode:"detached"});await Dd(o.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await o.close(),await Br(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}Od().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),Br().finally(()=>process.exit(1))});
|