@popmelt.com/core 0.8.5 → 0.8.6
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 +44 -43
- package/dist/{chunk-AK32Z7EA.mjs → chunk-EYFN72RC.mjs} +1 -1
- package/dist/cli.mjs +44 -43
- package/dist/index.mjs +45 -45
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/{server-AQ4RRAIQ.mjs → server-KCVEM3PH.mjs} +46 -45
- package/dist/server.mjs +46 -45
- package/package.json +1 -1
package/dist/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as Td}from"child_process";import{closeSync as jd,openSync as Ed}from"fs";import{appendFile as Md,mkdir as Ad,readFile as _d,realpath as Cd}from"fs/promises";import{dirname as $d,join as qo}from"path";import{fileURLToPath as Od}from"url";import{execFileSync as no,spawn as ws}from"child_process";import{createHash as Ts,randomUUID as ut}from"crypto";import{mkdir as ed,readFile as Fo,readdir as td,realpath as nd,stat as od,unlink as rd,writeFile as dn}from"fs/promises";import{createServer as sd}from"http";import{tmpdir as id}from"os";import{basename as Zn,dirname as ad,isAbsolute as zo,join as Me,relative as Is,resolve as js}from"path";import{fileURLToPath as cd}from"url";function Vo(o,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -25,12 +25,12 @@ import{spawn as ud}from"child_process";import{closeSync as md,openSync as fd}fro
|
|
|
25
25
|
});
|
|
26
26
|
</script>
|
|
27
27
|
</body>
|
|
28
|
-
</html>`}var
|
|
29
|
-
\u2026[truncated]`:t}function mn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:d="claude",resumeSessionId:c,model:l,reasoningEffort:h,timeoutMs:R=3e5,onEvent:
|
|
30
|
-
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let s of r)s&&e.add(s)}return[...e]}function
|
|
31
|
-
`)[0].slice(0,80)}`:"Bash";y.push(
|
|
32
|
-
`)}`)),v?(y=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(y=!0,f=
|
|
33
|
-
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let s=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:s,label:`${s} ${t.split("/").pop()}`,file:t}}}function
|
|
28
|
+
</html>`}var Ks=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Qs=new Set(["default","flex","fast","priority"]);function yt(o){let e=typeof o.reasoningEffort=="string"&&Ks.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Qs.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function un(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as Xs}from"child_process";import{createInterface as Ys}from"readline";var Zs=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Ko=1e5;function ei(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Zs.has(n))return;let t;if(o.name==="Write"&&typeof o.input?.content=="string"?t=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(t=o.input.new_string),!!t)return t.length>Ko?t.slice(0,Ko)+`
|
|
29
|
+
\u2026[truncated]`:t}function mn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:d="claude",resumeSessionId:c,model:l,reasoningEffort:h,timeoutMs:R=3e5,onEvent:I}=e,b=[];c?b.push("--resume",c,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(s)),l&&b.push("--model",l),h&&b.push("--effort",h);for(let y of i)b.push("--allowedTools",y);let g=Xs(d,b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(y=>{let f,v=[],x=[],S=[],A=!1,J="",_,N,T=!1,B=setTimeout(()=>{T=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},R),H=Ys({input:g.stdout}),ee=new Set;H.on("line",te=>{if(te.trim())try{let ne=JSON.parse(te);ne.session_id&&!f&&(f=ne.session_id);let ge=ne.type??(ne.event?.type?`event.${ne.event.type}`:"unknown");if(ee.add(ge),ne.type==="result"&&ne.result&&v.length===0){let X=typeof ne.result=="string"?ne.result:"";X&&(v.push(X),I?.({type:"delta",jobId:o,text:X},o))}if(ne.type==="assistant"&&Array.isArray(ne.message?.content)){typeof ne.error=="string"&&(_=ne.error);for(let X of ne.message.content){if(X.type==="text"&&X.text&&(v.push(X.text),I?.({type:"delta",jobId:o,text:X.text},o)),X.type==="tool_use"&&X.name){let G=X.input?.file_path||X.input?.path||void 0,U=ei(X);if(I?.({type:"tool_use",jobId:o,tool:X.name,...G?{file:G}:{},...U?{content:U}:{}},o),X.name==="Edit"&&X.input?.file_path){let he={tool:"Edit",file_path:X.input.file_path,old_string:X.input.old_string,new_string:X.input.new_string,replace_all:X.input.replace_all};x.push(he),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:he.file_path,oldString:typeof he.old_string=="string"?he.old_string:void 0,newString:typeof he.new_string=="string"?he.new_string:void 0,replaceAll:typeof he.replace_all=="boolean"?he.replace_all:void 0})}else X.name==="Write"&&X.input?.file_path&&(x.push({tool:"Write",file_path:X.input.file_path,content:X.input.content}),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:X.input.file_path,content:typeof X.input.content=="string"?X.input.content:void 0}))}X.type==="thinking"&&X.thinking&&I?.({type:"thinking",jobId:o,text:X.thinking},o)}}ne.type==="result"&&ne.is_error===!0&&(A=!0,typeof ne.error=="string"&&(_=ne.error),typeof ne.result=="string"&&(N=ne.result)),ne.type==="user"&&ne.tool_use_result?.file?.filePath&&I?.({type:"tool_use",jobId:o,tool:"Read",file:ne.tool_use_result.file.filePath},o)}catch{}});let W=[];g.stderr?.on("data",te=>{W.push(te.toString())}),g.on("close",te=>{if(clearTimeout(B),H.close(),v.length===0&&ee.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...ee].join(", ")}`),T)A=!0,J=`Timed out after ${Math.round(R/6e4)} minutes`;else if(te!==0&&te!==null){A=!0;let ge=W.join("").trim(),X=v.join("").trim(),G=v.length===0&&ee.size>0?` (no text captured, event types: ${[...ee].join(", ")})`:"";J=ge||N||X||`Claude process exited with code ${te}${G}`}A&&!J&&N&&(J=N);let ne=ti(J,_);y({sessionId:f,text:v.join(""),success:!A,error:A?ne.message:void 0,errorCode:A?ne.code:void 0,recoverableError:A?ne.recoverable:void 0,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})}),g.on("error",te=>{clearTimeout(B),A=!0,J=te.message,y({sessionId:f,text:v.join(""),success:!1,error:J,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:x.length>0?x:void 0,editEvents:S.length>0?S:void 0})})});return{process:g,result:p}}function ti(o,e){let n=o.trim()||"Claude CLI failed",t=`${e??""} ${n}`.toLowerCase();return t.includes("authentication_failed")||t.includes("not logged in")||t.includes("please run /login")||t.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:t.includes("model")&&(t.includes("not found")||t.includes("unknown")||t.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as ni,spawnSync as tr}from"child_process";import{readFileSync as oi,statSync as ri}from"fs";import{basename as si,extname as ii,isAbsolute as ai,relative as nr,resolve as ci}from"path";import{createInterface as di}from"readline";function Qo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Xo=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),ao=2e5,li=1e5,or=2e5;function rr(o){let e=si(o).toLowerCase(),n=ii(o).toLowerCase();return Xo.has(n)||Xo.has(e)}function qt(o,e){let n=ai(e)?e:ci(o,e),t=nr(o,n);return t===""||t.startsWith("..")?null:n}function fn(o,e){if(!rr(e))return;let n=qt(o,e);if(n)try{let t=ri(n);return t.isFile()?t.size>ao?{exists:!0,truncated:!0}:{exists:!0,content:oi(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function pi(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function ui(o){let e=o?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Yo(o){return pi(o,["patch","diff","unifiedDiff","unified_diff"])}function co(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Zo(o,e){let n=tr("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:or+65536});return n.status!==0?null:n.stdout??""}function mi(o){let e=new Set;for(let n of o.split(`
|
|
30
|
+
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let s of r)s&&e.add(s)}return[...e]}function er(o){let e=Zo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Zo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=co(n,or);return{status:e,changedFiles:mi(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function fi(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function hi(o,e){if(!rr(e))return;let n=qt(o,e);if(!n)return;let t=nr(o,n);if(t===""||t.startsWith(".."))return;let r=tr("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:ao+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=co(s,ao);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function gi(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):hi(o,t),s=fn(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function hn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:d,sandboxMode:c="workspace-write",configOverrides:l=[]}=e,h=[];if(s){h.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let b of l)h.push("-c",b);i&&h.push("-m",i),h.push(s),h.push(n),r&&h.push("--image",r)}else{h.push("exec","--skip-git-repo-check","--json","--sandbox",c);for(let b of l)h.push("-c",b);i&&h.push("-m",i),h.push(n),r&&h.push("--image",r)}let R=ni("codex",h,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),I=new Promise(b=>{let g,p=[],y=[],f=[],v=new Map,x=new Map,S=!1,A="",J=di({input:R.stdout}),_=new Set;J.on("line",T=>{if(T.trim())try{let B=JSON.parse(T),H=B.type??"unknown";if(_.add(H),H==="thread.started"&&B.thread_id&&!g&&(g=B.thread_id),(H==="item.agentMessage.delta"||H==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),d?.({type:"delta",jobId:o,text:B.delta.text},o)),(H==="item.reasoning.delta"||H==="item/reasoning/delta")&&B.delta?.text&&d?.({type:"thinking",jobId:o,text:B.delta.text},o),(H==="item.started"||H==="item/started")&&B.item){let ee=B.item.type;if(ee==="command_execution"){let W=B.item.command,te=W?Qo(W):void 0,ne=er(t),ge=new Map;for(let G of ne?.changedFiles??[])ge.set(G,fn(t,G));typeof B.item.id=="string"&&x.set(B.item.id,{...W?{rawCommand:W}:{},...te?{command:te}:{},...ne?{beforeWorktree:ne}:{},beforeSnapshots:ge});let X=te?`Bash: ${te.split(`
|
|
31
|
+
`)[0].slice(0,80)}`:"Bash";y.push(X),d?.({type:"tool_use",jobId:o,tool:"Bash",...te?{content:te}:{}},o)}else if(ee==="file_change"){let W=B.item.filename||B.item.path;W&&!v.has(W)&&v.set(W,fn(t,W)),y.push(W?`Edit ${W.split("/").pop()}`:"Edit");let te=W?qt(t,W)??W:void 0;d?.({type:"tool_use",jobId:o,tool:"Edit",...te?{file:te}:{}},o)}else if(ee==="file_read"){let W=B.item.filename||B.item.path;y.push(W?`Read ${W.split("/").pop()}`:"Read");let te=W?qt(t,W)??W:void 0;d?.({type:"tool_use",jobId:o,tool:"Read",...te?{file:te}:{}},o)}else if(ee==="web_search")y.push("WebSearch"),d?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(ee==="mcp_tool_call"){let W=B.item.tool_name||B.item.name||"MCP";y.push(W),d?.({type:"tool_use",jobId:o,tool:W},o)}}if((H==="item.completed"||H==="item/completed")&&B.item){if(B.item.type==="agent_message"){let ee=B.item.text;typeof ee=="string"&&ee&&(p.push(ee),d?.({type:"delta",jobId:o,text:ee},o))}else if(B.item.type==="reasoning"){let ee=B.item.text;typeof ee=="string"&&ee&&d?.({type:"thinking",jobId:o,text:ee},o)}else if(B.item.type==="file_change"&&Array.isArray(B.item.changes))for(let ee of B.item.changes){let W=ee.path||ee.filename,te=ee.kind==="add"?"Write":"Edit";if(W){y.push(`${te} ${W.split("/").pop()}`);let ne=qt(t,W)??W;d?.({type:"tool_use",jobId:o,tool:te,file:ne},o);let ge=ee,X=typeof ge.kind=="string"?ge.kind:void 0,G=ui(X),U=v.get(W),he=fn(t,W);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:W,...U?{before:U}:{},...he?{after:he}:{},...Yo(ge)?{patch:Yo(ge)}:{},...X?{rawKind:X}:{}}),v.set(W,he)}}else if(B.item.type==="command_execution"){let ee=typeof B.item.id=="string"?B.item.id:void 0,W=ee?x.get(ee):void 0,te=typeof B.item.command=="string"?B.item.command:W?.rawCommand,ne=te?Qo(te):W?.command,ge=er(t);if(fi(W?.beforeWorktree,ge)){let X=[...new Set([...W?.beforeWorktree?.changedFiles??[],...ge?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?co(B.item.aggregated_output,li):void 0,U=typeof B.item.exit_code=="number"?B.item.exit_code:B.item.exit_code===null?null:void 0,he=typeof B.item.status=="string"?B.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...te?{rawCommand:te}:{},...ne?{command:ne}:{},...U!==void 0?{exitCode:U}:{},...he?{status:he}:{},...G?{output:G.text}:{},...G?.truncated?{outputTruncated:!0}:{},...W?.beforeWorktree?{beforeWorktree:W.beforeWorktree}:{},...ge?{afterWorktree:ge}:{},...X.length>0?{touchedFiles:gi(t,X,W?.beforeSnapshots??new Map)}:{}})}ee&&x.delete(ee)}}H==="turn.failed"&&(S=!0,A=B.error?.message||B.message||"Turn failed")}catch{}});let N=[];R.stderr?.on("data",T=>{N.push(T.toString())}),R.on("close",T=>{J.close(),p.length===0&&_.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[..._].join(", ")}`),T!==0&&T!==null&&(S=!0,A=N.join("")||`Codex process exited with code ${T}`),b({sessionId:g,text:p.join(""),success:!S,error:S?A:void 0,editEvents:f.length>0?f:void 0,toolsUsed:y.length>0?y:void 0})}),R.on("error",T=>{S=!0,A=T.message,b({sessionId:g,text:p.join(""),success:!1,error:A,editEvents:f.length>0?f:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:R,result:I}}import{spawn as yi}from"child_process";import{createInterface as vi}from"readline";function sr(o,e){let n=o.trim()||"Copilot CLI failed",t=n.toLowerCase();return t.includes("no authentication information")||t.includes("not authenticated")||t.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:t.includes("model")&&(t.includes("not available")||t.includes("not found")||t.includes("disabled")||t.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:n}:t.includes("mcp")&&(t.includes("blocked")||t.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:t.includes("permission")||t.includes("denied")||t.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function ir(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:s,timeoutMs:i=3e5,onEvent:d,copilotPath:c="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),s&&l.push("--model",s),l.push("-p",n);let h=yi(c,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(I=>{let b,g=[],p=[],y=!1,f="",v=!1,x=setTimeout(()=>{v=!0,h.kill("SIGTERM"),setTimeout(()=>{try{h.kill("SIGKILL")}catch{}},5e3)},i),S=vi({input:h.stdout}),A=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Wt(T);A.add(B),J.length<5&&Ii(B)&&J.push(N.slice(0,800));let H=Ht(T,["sessionId","session_id","id"],["session","conversation","thread"]);H&&!b&&(b=H);let ee=wi(T,g.length===0);ee&&(g.push(ee),d?.({type:"delta",jobId:o,text:ee},o));let W=bi(T);W&&d?.({type:"thinking",jobId:o,text:W},o);let te=xi(T);te&&(p.push(te.label),d?.({type:"tool_use",jobId:o,tool:te.tool,...te.file?{file:te.file}:{},...te.content?{content:te.content}:{}},o));let ne=Si(T);ne&&(y=!0,f=ne)}catch{}});let _=[];h.stderr?.on("data",N=>{_.push(N.toString())}),h.on("close",N=>{clearTimeout(x),S.close(),g.length===0&&A.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),J.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${J.join(`
|
|
32
|
+
`)}`)),v?(y=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(y=!0,f=_.join("").trim()||f||`Copilot process exited with code ${N}`);let T=y?sr(f,s):null;I({sessionId:b,text:g.join(""),success:!y,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),h.on("error",N=>{clearTimeout(x);let T=sr(N.message,s);I({sessionId:b,text:g.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:h,result:R}}function Wt(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function wi(o,e=!1){let n=Wt(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Le(o.delta)??Le(o.content)??Le(o.message);if(n==="assistant.message"&&e)return Le(o.message)??Le(o.content)??Le(o);if(n==="result"&&e)return Le(o.result)??Le(o.output)??Le(o.message)??Le(o);let s=o.content;if(s?.type==="text"&&typeof s.text=="string")return s.text;if(typeof o.text=="string"&&lo(o))return o.text;if(typeof o.message=="string"&&lo(o))return o.message;if(typeof o.delta=="string"&&lo(o))return o.delta}function Le(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Le).filter(t=>!!t);return n.length>0?n.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=Le(e[n]);if(t)return t}}function Ii(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function bi(o){if(typeof o.thinking=="string")return o.thinking;if(typeof o.reasoning=="string")return o.reasoning;let e=o.update;if(e?.sessionUpdate==="reasoning_chunk"){let n=e.content;if(typeof n?.text=="string")return n.text}}function xi(o){let e=Ht(o,["tool","toolName","tool_name","name"]),n=Ht(o,["command","cmd"]),t=Ht(o,["file","path","filename","filePath"]),r=Wt(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
33
|
+
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let s=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:s,label:`${s} ${t.split("/").pop()}`,file:t}}}function Si(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&Wt(o).toLowerCase().includes("error"))return o.message}function Ht(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(i=>t.toLowerCase().includes(i)))continue;let s=Ht(r,e);if(s)return s}}function lo(o){let e=Wt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as Pi,readFile as Ri}from"fs/promises";import{join as po}from"path";var gn=class{constructor(e){let n=po(e,".popmelt");this.decisionsDir=po(n,"decisions")}async listDecisionIds(){try{return(await Pi(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await Ri(po(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}};function cr(o,e){let n=o.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),r=Ci(t.assertionResults,e),s=$i(r);return{status:s,summary:tt(t.summary)||ur(s),assertionResults:r,tooling:Oi(t.tooling)}}catch{}return{status:"needs_review",summary:Di(o.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function dr(o,e){let n=(o.selectedChanges??[]).flatMap(v=>Array.isArray(v.path)&&v.path.length?[v.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(v=>v.path),s=[...new Set(r.map(v=>v.map(String).join(".")).filter(Boolean))].map(v=>({kind:"model_path",value:v}));if(s.length===0||o.decisionIds.length===0)return[];let i=new Set(o.decisionIds),d=new Set(s.map(v=>v.value)),c=e.cases.find(v=>v.status!=="rejected"&&(v.sourceDecisionIds.some(x=>i.has(x))||(v.dependencies??[]).some(x=>x.kind==="model_path"&&d.has(x.value)))),l=(o.selectedChanges??[]).find(v=>v.label?.trim())?.label?.trim()??t.find(v=>v.label?.trim())?.label?.trim()??o.title,h=c?.id.startsWith("eval-model-")??!1,R=(o.selectedChanges??[]).flatMap(v=>Array.isArray(v.path)&&v.path.length>0?[{path:v.path,value:v.value,label:v.label,detail:v.detail}]:[]),b=(R.length>0?R:t.map(v=>({path:v.path,value:v.value,label:v.label,detail:v.rationale}))).flatMap(v=>ki(v,o.decisionIds)),g=vn(o.underlyingClaim??o.summary),p=[...new Set([...c&&!h?c.assertions:[],...b,...b.length===0&&g?[g]:[]])],y=s[0].value,f=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:c?.id??`eval-model-${o.id}`,title:c&&!h?c.title:l,status:"pending",category:c?.category??f,prompt:c&&!h?c.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:c&&!h?c.rationale:Ei(y),sourceDecisionIds:[...new Set([...c?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...c?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...c?.dependencies??[],...s].map(v=>[`${v.kind}:${v.value}`,v])).values()]}]}function ki(o,e){let n=String(o.path[0]??"");if(n==="rules")return Ti(o.value,e);if(n==="components"){let i=lr(String(o.path[1]??o.label??"component")),d=yn(o.value),c=d?Vt(d.usage):[];if(c.length>0){let h=Mi(c),R=c.length===1?"uses":"use";return[`The ${h} ${R} the same shared implementation for the ${i} pattern.`]}if(d?.shared===!0)return[`The product uses a shared implementation for the ${i} pattern.`];let l=d?tt(d.constraint):"";if(l){let h=ji(l,i);if(h)return[h]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),d=yn(o.value),c=d&&"value"in d?d.value:o.value,l=Ai(c);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=yn(o.value),r=t?tt(t.text)||tt(t.constraint):typeof o.value=="string"?o.value:"",s=vn(r||o.detail||"");return s?[s]:[]}function Ti(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let d=yn(i),c=d?tt(d.text):"";return c?[{text:c,sources:d?Vt(d.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(d=>n.has(d)));return(r.length>0?r:t.length===1?t:[]).map(i=>vn(i.text)).filter(i=>!!i)}function ji(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?Rt(`Wherever ${Gt(n[1])}, the shared ${e} implementation is used instead of ${Gt(n[2])}`):vn(o)}function uo(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Rt(`${ar(n[1])} is ${Gt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Rt(ar(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Rt(`The product uses ${Gt(r[1])}`);let s=e.match(/^Do not (.+?)\.?$/i);return s?Rt(`The product does not ${Gt(s[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Rt(e)}var vn=uo;function Ei(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${lr(e[1]??"component")} contract across its declared product surfaces.`:e[0]==="tokens"?`Protects the ${e.slice(1).join(".")} token from implementation drift.`:e[0]==="rules"?"Protects an enforceable product rule across its declared scope.":"Protects an enforceable product expectation across its declared scope."}function yn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function lr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function Mi(o){return o.length<=1?o[0]??"":o.length===2?`${o[0]} and ${o[1]}`:`${o.slice(0,-1).join(", ")}, and ${o.at(-1)}`}function Ai(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function Rt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function ar(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Gt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function pr(o){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
|
|
34
34
|
|
|
35
35
|
## Eval
|
|
36
36
|
\`\`\`json
|
|
@@ -86,7 +86,7 @@ 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 et(o){return typeof o=="string"?o.trim():""}function Vt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Ri(o){let e=et(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function ki(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let s=r,i=et(s.assertion);return i?{assertion:i,status:Ri(s.status)??"needs_review",summary:et(s.summary)||pr("needs_review"),evidence:Vt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Ti(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function ji(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=et(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Vt(e.evidenceTypes).length>0?Vt(e.evidenceTypes):["screenshot"]}}function pr(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 Ei(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Mi}from"crypto";import{mkdir as _i,writeFile as Ai}from"fs/promises";import{join as uo}from"path";var wn=class{constructor(e){this.root=uo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=uo(this.root,"eval-screenshots"),t=Mi("sha256").update(e).digest("hex"),r=uo(n,`${t}.webp`);return await _i(n,{recursive:!0}),await Ai(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as ur}from"crypto";import{mkdir as mo,readFile as fo,writeFile as In}from"fs/promises";import{dirname as ho,join as Rt}from"path";var He="[ProjectionWorker]",Ci={version:1,runs:[]},$i={version:1,updatedAt:0,proposals:[]},Oi=12;function Di(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 mr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${He} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${He} Rule count ${e.length} exceeds cap of 30`),e}function Ji(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ni(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let g of s){if(!g||typeof g!="object")continue;let p=g.sources;if(Array.isArray(p))for(let y of p)typeof y=="string"&&t.has(y)&&r.add(y)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},d=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},c=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,y=typeof p=="string"?c.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(g)}).length,h=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},w=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(h[g])).length,b=Object.keys(d).filter(g=>JSON.stringify(d[g])!==JSON.stringify(R[g])).length;return{ruleCount:l,tokenSectionCount:w,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function Bi(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Li(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function bn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Li(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=Bi(n)}function fr(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 Fi(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 zi(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 hr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Fi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?zi(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var xn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Rt(e,".popmelt");this.runsPath=Rt(t,"projection-runs.json"),this.legacyRunsPath=Rt(t,"materialization-runs.json"),this.proposalsPath=Rt(t,"projection-queue.json"),this.legacyProposalsPath=Rt(t,"model-proposals.json"),this.modelPath=Rt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await fo(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Di(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?fr(n,r):bn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Oi),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let s=r.map(g=>g.id);console.log(`${He} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),d=Wi(r,i),c=Ji(r,t.totalCandidateDecisionCount,d);n=ur().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:s,startedAt:Date.now(),promptStats:c};await this.persistRun(l);let h=!0,R,w,b;try{let g=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(g,d,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await y;if(!f.success)h=!1,R=f.error,console.error(`${He} ${p} spawn error:`,R);else{let v=Hi(f.text,s);if(v){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of v)bn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=mr(x.rules));let S=Ni(x,s,i);if(v){let J=[...new Set(v.flatMap(A=>A.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(A=>!J.includes(A))}w=S;let _=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:w,changes:v});b=_.id,console.log(`${He} Created model proposal ${_.id} for ${s.length} decision(s)`)}else h=!1,R="No valid bounded <model-changes> block found in response",console.error(`${He} ${R}`)}}catch(g){h=!1,R=g instanceof Error?g.message:String(g),console.error(`${He} Error:`,R)}return await this.persistRun({...l,status:h?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:w,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:h,error:R}),{processedIds:s,success:h,error:R,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=mr(e.rules)),await In(this.modelPath,JSON.stringify(e,null,2)),console.log(`${He} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await mo(ho(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2)),n):{...Ci,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??{...$i,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let s=structuredClone(t);for(let i of r.changes??[])bn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let c of n)!Array.isArray(c.path)||c.path.length===0||(c.remove?fr(i,c.path):bn(i,c.path,c.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let d=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(d.evalId),s.set(d.evalId,d)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:ur().slice(0,8),status:"pending",title:qi(e.proposedModel),summary:e.outputStats?`Proposes ${e.outputStats.ruleCount} rule, ${e.outputStats.componentCount} component, and ${e.outputStats.tokenSectionCount} token change${e.outputStats.ruleCount+e.outputStats.componentCount+e.outputStats.tokenSectionCount===1?"":"s"} from ${e.decisionIds.length} accepted decision${e.decisionIds.length===1?"":"s"}.`:Ui(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 mo(ho(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await In(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await mo(ho(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await fo(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await fo(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(d,c)=>this.options.onEvent?.(d):void 0;return s==="codex"?{provider:"codex",...hn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:un(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${He} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...mn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:s==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:i})})}};function qi(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Ui(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 Hi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,d)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let c=i;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(R=>typeof R=="string"||typeof R=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let h=Array.isArray(c.decisionIds)?c.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return h.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${d+1}`,path:c.path,value:c.value,decisionIds:h,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Wi(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
|
|
89
|
+
Allowed chromeDevtools values: available, unavailable, unknown.`}function tt(o){return typeof o=="string"?o.trim():""}function Vt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function _i(o){let e=tt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ci(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let s=r,i=tt(s.assertion);return i?{assertion:i,status:_i(s.status)??"needs_review",summary:tt(s.summary)||ur("needs_review"),evidence:Vt(s.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function $i(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Oi(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=tt(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Vt(e.evidenceTypes).length>0?Vt(e.evidenceTypes):["screenshot"]}}function ur(o){return o==="pass"?"The current page appears to satisfy this eval.":o==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function Di(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Ji}from"crypto";import{mkdir as Ni,writeFile as Bi}from"fs/promises";import{join as mo}from"path";var wn=class{constructor(e){this.root=mo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=mo(this.root,"eval-screenshots"),t=Ji("sha256").update(e).digest("hex"),r=mo(n,`${t}.webp`);return await Ni(n,{recursive:!0}),await Bi(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as mr}from"crypto";import{mkdir as fo,readFile as ho,writeFile as In}from"fs/promises";import{dirname as go,join as kt}from"path";var He="[ProjectionWorker]",Li={version:1,runs:[]},Fi={version:1,updatedAt:0,proposals:[]},zi=12;function Ui(o){return Array.isArray(o)?o.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function fr(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${He} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${He} Rule count ${e.length} exceeds cap of 30`),e}function qi(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Hi(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let g of s){if(!g||typeof g!="object")continue;let p=g.sources;if(Array.isArray(p))for(let y of p)typeof y=="string"&&t.has(y)&&r.add(y)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},d=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},c=Array.isArray(n?.rules)?n.rules:[],l=s.filter(g=>{if(!g||typeof g!="object")return!1;let p=g.id,y=typeof p=="string"?c.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(g)}).length,h=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},I=Object.keys(i).filter(g=>JSON.stringify(i[g])!==JSON.stringify(h[g])).length,b=Object.keys(d).filter(g=>JSON.stringify(d[g])!==JSON.stringify(R[g])).length;return{ruleCount:l,tokenSectionCount:I,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(g=>!r.has(g))}}function Wi(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Gi(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function bn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=Gi(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=Wi(n)}function hr(o,e){let n=o;for(let r=0;r<e.length-1;r++){let s=n[String(e[r])];if(!s||typeof s!="object")return;n=s}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Vi(o,e){if(!o)return{exists:!1};let n=o;for(let t of e){if(!n||typeof n!="object"||!(String(t)in n))return{exists:!1};n=n[String(t)]}return{exists:!0,value:n}}function Ki(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((n,t)=>JSON.stringify(n)===JSON.stringify(e[t])):!1}function gr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Vi(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Ki(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var xn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=kt(e,".popmelt");this.runsPath=kt(t,"projection-runs.json"),this.legacyRunsPath=kt(t,"materialization-runs.json"),this.proposalsPath=kt(t,"projection-queue.json"),this.legacyProposalsPath=kt(t,"model-proposals.json"),this.modelPath=kt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ho(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Ui(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let r=t.key.split(".");t.value===null?hr(n,r):bn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(zi),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let s=r.map(g=>g.id);console.log(`${He} Processing ${s.length} pattern-scoped decision(s): ${s.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:s});let i=await this.loadModel(),d=Zi(r,i),c=qi(r,t.totalCandidateDecisionCount,d);n=mr().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:s,startedAt:Date.now(),promptStats:c};await this.persistRun(l);let h=!0,R,I,b;try{let g=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(g,d,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await y;if(!f.success)h=!1,R=f.error,console.error(`${He} ${p} spawn error:`,R);else{let v=Yi(f.text,s);if(v){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of v)bn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=fr(x.rules));let S=Hi(x,s,i);if(v){let J=[...new Set(v.flatMap(_=>_.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(_=>!J.includes(_))}I=S;let A=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:I,changes:v});b=A.id,console.log(`${He} Created model proposal ${A.id} for ${s.length} decision(s)`)}else h=!1,R="No valid bounded <model-changes> block found in response",console.error(`${He} ${R}`)}}catch(g){h=!1,R=g instanceof Error?g.message:String(g),console.error(`${He} Error:`,R)}return await this.persistRun({...l,status:h?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:I,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:h,error:R}),{processedIds:s,success:h,error:R,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=fr(e.rules)),await In(this.modelPath,JSON.stringify(e,null,2)),console.log(`${He} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await fo(go(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2)),n):{...Li,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(s=>s.authorityStatus==="accepted"&&Array.isArray(s.changes)&&s.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Fi,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let s=structuredClone(t);for(let i of r.changes??[])bn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let c of n)!Array.isArray(c.path)||c.path.length===0||(c.remove?hr(i,c.path):bn(i,c.path,c.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let d=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(d.evalId),s.set(d.evalId,d)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:mr().slice(0,8),status:"pending",title:Qi(e.proposedModel),summary:e.outputStats?`Proposes ${e.outputStats.ruleCount} rule, ${e.outputStats.componentCount} component, and ${e.outputStats.tokenSectionCount} token change${e.outputStats.ruleCount+e.outputStats.componentCount+e.outputStats.tokenSectionCount===1?"":"s"} from ${e.decisionIds.length} accepted decision${e.decisionIds.length===1?"":"s"}.`:Xi(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(s=>s.id!==e?s:(r={...s,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await fo(go(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await In(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await fo(go(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${He} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await ho(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await ho(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(d,c)=>this.options.onEvent?.(d):void 0;return s==="codex"?{provider:"codex",...hn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:un(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${He} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...mn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:s==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:i})})}};function Qi(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Xi(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Yi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,d)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let c=i;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(R=>typeof R=="string"||typeof R=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let h=Array.isArray(c.decisionIds)?c.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return h.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${d+1}`,path:c.path,value:c.value,decisionIds:h,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Zi(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
|
|
90
90
|
Kind: ${s.kind}
|
|
91
91
|
Claim: ${s.claim}
|
|
92
92
|
${s.rationale?`Rationale: ${s.rationale}`:""}
|
|
@@ -165,23 +165,23 @@ Example:
|
|
|
165
165
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
166
166
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
167
167
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
168
|
-
Include property and bindings when the decision context has class-level evidence.`}var Sn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as
|
|
169
|
-
`),n=[],t=null;for(let r of e){let s=r.match(
|
|
168
|
+
Include property and bindings when the decision context has class-level evidence.`}var Sn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as ea}from"child_process";import{readFile as vo}from"fs/promises";import{homedir as Rn}from"os";import{join as Be}from"path";var wo=/popmelt/i,ta=/chrome|devtools/i;function vt(){return{found:!1,name:null,scope:null,disabled:!1}}function Tt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Kt(o){for(let e of Object.keys(o))if(wo.test(e))return e;return null}async function Pn(o){try{let e=await vo(o,"utf-8");return JSON.parse(e)}catch{return null}}async function Io(o){let e=Rn(),n=await Pn(Be(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Kt(r.mcpServers);if(s)return Tt(s,"user")}if(r.projects&&typeof r.projects=="object"){let i=r.projects[o];if(i&&typeof i=="object"){let d=i;if(d.mcpServers&&typeof d.mcpServers=="object"){let c=Kt(d.mcpServers);if(c){let l=Array.isArray(d.disabledMcpjsonServers)&&d.disabledMcpjsonServers.some(h=>wo.test(h));return Tt(c,"project",l)}}}}}let t=await Pn(Be(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Kt(r.mcpServers);if(i){let d=await yr(o,i);return Tt(i,"mcp.json",d)}}let s=Kt(r);if(s&&s!=="mcpServers"){let i=await yr(o,s);return Tt(s,"mcp.json",i)}}return vt()}async function yr(o,e){let n=Be(o,".claude","settings.local.json"),t=await Pn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(s=>s===e)}return!1}var na=/^\[mcp_servers\.([^\]]+)\]/;function oa(o){return o.replace(/^"(.+)"$/,"$1")}function ra(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function wr(o){let e=o.split(`
|
|
169
|
+
`),n=[],t=null;for(let r of e){let s=r.match(na);s?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
170
170
|
`)}),t={name:s[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
171
171
|
`)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
172
|
-
`)}),n}function
|
|
173
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
172
|
+
`)}),n}function Ir(o){return/enabled\s*=\s*false/i.test(o)}async function bo(o){let e=process.env.CODEX_HOME||Be(Rn(),".codex"),n=await vr(Be(e,"config.toml"),"user");if(n.found)return n;let t=await vr(Be(o,".codex","config.toml"),"project");return t.found?t:vt()}async function sa(o,e){let n=process.env.CODEX_HOME||Be(Rn(),".codex"),t=new Set;for(let r of[Be(n,"config.toml"),Be(o,".codex","config.toml")])try{let s=await vo(r,"utf-8");for(let i of wr(s)){if(ra(i.name)||Ir(i.body))continue;let d=oa(i.name);e.test(d)&&t.add(d)}}catch{}return[...t]}async function br(o){return sa(o,ta)}async function xo(o,e="copilot"){let n=await ia(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Be(Rn(),".copilot"),r=await yo(Be(t,"mcp-config.json"),"user");if(r.found)return r;let s=await yo(Be(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await yo(Be(o,".github","mcp.json"),"mcp.json");return i.found?i:vt()}async function ia(o){try{let e=await new Promise((n,t)=>{ea(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return xr(JSON.parse(e),"user")}catch{return vt()}}async function yo(o,e){let n=await Pn(o);return xr(n,e)}function xr(o,e){if(!o||typeof o!="object")return vt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Kt(t);return r?Tt(r,e):vt()}async function vr(o,e){try{let n=await vo(o,"utf-8"),t=wr(n);for(let r of t)if(wo.test(r.name)){let s=Ir(r.body);return Tt(r.name,e,s)}}catch{}return vt()}import{execFile as Sr}from"child_process";import{mkdir as aa,readFile as Pr,writeFile as Rr}from"fs/promises";import{homedir as kr}from"os";import{dirname as ca,join as So}from"path";var Po="https://mcp.popmelt.com/mcp";async function Tr(o=Po){let e=So(kr(),".claude.json"),n;try{let r=await Pr(e,"utf-8");n=JSON.parse(r)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let r of Object.keys(t))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await Rr(e,JSON.stringify(n,null,2)+`
|
|
173
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function jr(o=Po){let e=process.env.CODEX_HOME||So(kr(),".codex"),n=So(e,"config.toml"),t;try{t=await Pr(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await aa(ca(n),{recursive:!0});let r=`
|
|
174
174
|
[mcp_servers.popmelt]
|
|
175
175
|
url = "${o}"
|
|
176
|
-
`;return await Pr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function jr(o=So,e="copilot"){let n=await na(e);if(oa(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{xr(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 na(o){try{let e=await new Promise((n,t)=>{xr(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 oa(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var kn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),s={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,s),s}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as Ao,readFile as Mt,writeFile as Co}from"fs/promises";import{join as lt}from"path";var ra=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Po(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Tn(o){return new Set(Po(o).split(" ").filter(e=>e.length>2&&!ra.has(e)))}function Er(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function sa(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function ia(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Po).filter(Boolean),s=Tn([e.action,e.text].filter(Boolean).join(" "));for(let i of o){if(t.has(i.id)){n.set(i.id,{subjectId:i.id,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let d;for(let c of sa(i)){let l=Po(c.value);for(let w of r){let b=l===w?95:l.includes(w)||w.includes(l)?75:0;b>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:b>=90?"exact":"strong",matchedBy:c.by,score:b})}let R=["/","#","[","]","="].some(w=>c.value.includes(w))?0:Math.round(Er(Tn(l),s)*55);R>=30&&R>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}d&&n.set(i.id,d)}return n}function aa(o,e){let n=new Set(o.sourceRefs.filter(i=>i.kind==="iteration").map(i=>i.id)),t=new Set(o.sourceRefs.filter(i=>i.kind==="thread").map(i=>i.id)),r=e.filter(i=>i.iterationIds.some(d=>n.has(d))||i.sourceRefs.some(d=>d.kind==="thread"&&t.has(d.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let s=new Set(r.map(i=>i.state));return{state:s.size>1?"mixed":s.has("completed")?"completed":"attempted",attemptIds:r.map(i=>i.id)}}function ca(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(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let f=[...o.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===y.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(y=>y.recordType==="implementation_attempt"),d=ia(n,e),c=[...d.values()].sort((y,f)=>f.score-y.score),l=Tn([e.action,e.text].filter(Boolean).join(" ")),h=s.flatMap(y=>{let f=y.subjects.map(_=>d.get(_.subjectId)).filter(_=>!!_),v=Math.max(0,...f.map(_=>_.score)),x=Math.round(Er(Tn(y.claim),l)*35),S=v+x;return S>=50?[{proposal:y,proposalMatches:f,score:S}]:[]}).sort((y,f)=>f.score-y.score||y.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),w=Math.max(200,e.maxEstimatedTokens??1200),b=[],g=0;for(let y of h){if(b.length>=R)break;let f=y.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:S,..._})=>_)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(S=>S.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:aa(y.proposal,i),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...f]},x={...v,estimatedTokens:ca(v)};if(g+x.estimatedTokens>w)break;b.push(x),g+=x.estimatedTokens}let p=Math.max(0,h.length-b.length);return{packets:b,subjectMatches:c.map(({score:y,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:h.length,omittedPacketCount:p,maxEstimatedTokens:w,estimatedTokens:g},uncertainty:d.size===0?"subject_unresolved":h.length===0?"no_relevant_pending_proposal":void 0}}var da=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 jn(o){return new Set(ko(o).split(" ").filter(e=>e.length>2&&!da.has(e)))}function Mr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function la(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(ko).filter(Boolean),r=jn([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let d,c=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of c){let h=ko(l.value);for(let b of t){let g=h===b?95:h.includes(b)||b.includes(h)?75:0;g>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let w=["/","#","[","]","="].some(b=>l.value.includes(b))?0:Math.round(Mr(jn(h),r)*55);w>=30&&w>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:w>=45?"strong":"weak",matchedBy:"semantic",score:w})}d&&s.push(d)}return s.sort((i,d)=>d.score-i.score||i.subjectId.localeCompare(d.subjectId))}function pa(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 ua(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 ma(o,e,n){let t=e.filter(d=>d.targets.some(c=>c.entityType==="decision"&&c.entityId===o)).sort((d,c)=>c.createdAt.localeCompare(d.createdAt)),r=n.some(d=>d.signalType==="verification_expired"&&d.target.entityType==="decision"&&d.target.entityId===o),s=t[0],i=r?"stale":s?s.state==="passed"?"passing":s.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(s.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:i,attemptIds:t.map(d=>d.id)}}function _r(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(A=>A.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(A=>A.recordType==="decision"&&A.state==="active"),d=s?i.filter(A=>s.has(A.id)):i,c=o.records.filter(A=>A.recordType==="implementation_attempt"),l=o.records.filter(A=>A.recordType==="verification_attempt"),h=o.records.filter(A=>A.recordType==="freshness_signal"&&A.state==="open"),R=o.records.filter(A=>A.recordType==="evidence"),w=o.records.filter(A=>A.recordType==="model_entry"),b=[...o.records].reverse().filter(A=>A.recordType==="eval_spec").filter((A,N,T)=>T.findIndex(B=>B.legacyId===A.legacyId)===N),g=la(r,e),p=new Map(g.map(A=>[A.subjectId,A.score])),y=jn([e.action,e.text].filter(Boolean).join(" ")),f=d.flatMap(A=>{let N=Math.max(0,...A.subjects.map(H=>p.get(H.subjectId)??0)),T=Math.round(Mr(jn(A.claim),y)*35),B=N+T;return B>=50?[{decision:A,score:B}]:[]}).sort((A,N)=>N.score-A.score||A.decision.id.localeCompare(N.decision.id)),v=new Map;for(let A of f.slice(0,t))v.set(A.decision.id,A.decision);for(let A of o.relationships){if(!Tt(A,"excepts")&&!Tt(A,"contradicts"))continue;let N=i.find(B=>B.id===A.from.entityId),T=i.find(B=>B.id===A.to.entityId);!N||!T||!v.has(N.id)&&!v.has(T.id)||(v.size<t&&v.set(N.id,N),v.size<t&&v.set(T.id,T))}let x=[...v.values()],S=A=>A.from.entityType==="decision"&&A.to.entityType==="decision"&&v.has(A.from.entityId)&&v.has(A.to.entityId),_=(A,N=!1)=>{let T=new Set(A.map(E=>E.id)),B=h.filter(E=>E.target.entityType==="decision"&&T.has(E.target.entityId)),H=new Set(o.relationships.filter(E=>Tt(E,"excepts")&&T.has(E.from.entityId)&&T.has(E.to.entityId)).flatMap(E=>[E.from.entityId,E.to.entityId])),W=o.relationships.filter(E=>Tt(E,"contradicts")&&T.has(E.from.entityId)&&T.has(E.to.entityId)).map(E=>({id:E.id,decisionIds:[E.from.entityId,E.to.entityId],unresolvedQuestion:E.reason,expansionRefs:[{kind:"record",id:E.id}]})),ne=new Set(W.flatMap(E=>E.decisionIds)),oe=R.filter(E=>E.sourceRefs.some(Z=>Z.kind==="record"&&T.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===E.id&&Z.to.entityType==="decision"&&T.has(Z.to.entityId))),he=Math.max(0,f.length-A.length),Y=o.relationships.some(E=>Tt(E,"contradicts")&&S(E)&&(!T.has(E.from.entityId)||!T.has(E.to.entityId))),G=N||he>0||Y,q=[];g.length===0&&(e.subjectHints?.length??0)>0?q.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):A.length===0&&q.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),W.length&&q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:W.flatMap(E=>E.expansionRefs)}),oe.some(E=>E.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map(E=>({kind:"record",id:E.id}))}),G&&q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let fe={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:E,...Z})=>Z),modelEntries:w.filter(E=>E.decisionIds.some(Z=>T.has(Z))).map(E=>({id:E.id,key:E.key,value:E.value,decisionIds:E.decisionIds})),evalSpecs:b.filter(E=>E.decisionIds.some(Z=>T.has(Z))).map(E=>({id:E.id,legacyId:E.legacyId,state:E.state,title:E.title,assertionCount:E.assertions.length,decisionIds:E.decisionIds,expansionRef:{kind:"record",id:E.id}})),decisions:A.map(E=>({id:E.id,kind:E.kind,claim:E.claim,subjectIds:E.subjects.map(Z=>Z.subjectId),authority:E.authority,effectiveState:ne.has(E.id)?"conflicted":H.has(E.id)?"excepted":"active",freshness:B.filter(Z=>Z.target.entityId===E.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:E.id}})),conflicts:W,uncertainties:q,implementation:A.map(E=>ua(E.id,c)),verification:A.map(E=>ma(E.id,l,B)),evidence:oe.map(E=>({evidenceId:E.id,summary:E.summary,availability:E.availability,sourceRefs:E.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:he,omittedEvidenceCount:0,conflictsComplete:!Y}};return fe.budget.estimatedTokens=pa(fe),fe},J=_(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let A=x.pop(),N=o.relationships.filter(T=>Tt(T,"contradicts")&&(T.from.entityId===A.id||T.to.entityId===A.id)).flatMap(T=>[T.from.entityId,T.to.entityId]);x=x.filter(T=>!N.includes(T.id)),J=_(x,!0)}return J}var fa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function jt(o){return fa.test(o)}function ha(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 To(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 yt(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 ga={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"])},ya=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function va(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),yt(o,`${n}.authority`,e.authority);let t=ga[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(ya.has(s)&&(yt(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 wa(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"&&(yt(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"&&To(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),yt(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&&To(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&To(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ia(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?yt(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 vt(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,y)=>{let f=n.get(p);f?ce(e,y,"duplicate_id",`ID is already used at ${f}.`):n.set(p,y)};o.records.forEach((p,y)=>{let f=`records[${y}]`;t(p.id,f),wa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,y)=>{let f=`events[${y}]`;t(p.id,f),va(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let f=`relationships[${y}]`;t(p.id,f),Ia(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let f=`tombstones[${y}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),dt(e,`${f}.deletedAt`,p.deletedAt),yt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,y)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,y,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,y)=>i(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{i(p.from,`relationships[${y}].from`),i(p.to,`relationships[${y}].to`)});let d=new Set(o.artifacts.map(p=>p.id)),c=(p,y)=>{d.has(p)||ce(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,f)=>{!r.has(`${p}:${y}`)&&!s.has(`${p}:${y}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let f=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((v,x)=>l("subject",v,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((v,x)=>c(v,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((v,x)=>l("subject",v.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((v,x)=>c(v,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((v,x)=>i(v,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((v,x)=>l("thread",v,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((v,x)=>l("iteration",v,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((v,x)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((v,x)=>{v.subjectIds?.forEach((S,_)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${_}]`))}),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`));break;case"model_projection":yt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((v,x)=>l("model_entry",v,`${f}.entryIds[${x}]`)),p.coverage.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;default:break}});let h=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),w=new Map;o.events.forEach((p,y)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,v=w.get(f)??new Set;v.add(p.toState),w.set(f,v),v.size>1&&ce(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,y,f,v,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=b.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==y||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let _=Date.parse(f);(_<Date.parse(S.startsAt)||S.endsAt&&_>Date.parse(S.endsAt)||S.revokedAt&&_>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&v.length&&!v.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(y=>y.subjectId),`records:${p.id}.authority`);o.events.forEach((p,y)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),v=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,v,`events[${y}].authority`)}),o.relationships.forEach((p,y)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(v=>{let x=R.get(`${v.entityType}:${v.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${y}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let y=h.get(p.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==p.proposalId||y.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===p.id&&v.toState==="revoked"&&!!v.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return ha(e)}function Qt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Ar(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 ba(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function En(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),jt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of ba(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={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=Ar(o,t,e,s.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:i.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let s={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},i={...Qt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},d={...Qt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Ar(o,s,e,d.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,c],events:[i,d],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as xa}from"crypto";import{readFile as Sa,readdir as Pa,realpath as Ra}from"fs/promises";import{join as Xt,relative as ka}from"path";var Ta=["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 ze(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Cr(...o){return o.find(e=>!!e?.trim())?.trim()}function ge(o,e,n,t){let s=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),i=xa("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),d=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${d}${i.slice(4,7)}-${i.slice(7,19)}`}async function jo(o,e){try{return JSON.parse(await Sa(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function ja(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 Ea(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Yt(o){let e=[],n=await Ra(o.projectRoot).catch(()=>o.projectRoot),t=Xt(n,".popmelt"),r=await jo(Xt(t,"threads.json"),e),s=await jo(Xt(t,"model.json"),e),i=Et(r),d=Et(i?.threads)??{},c=Object.entries(d).map(([E,Z])=>({key:E,value:Et(Z)})).filter(E=>!!E.value),l=Xt(t,"decisions"),h=await Pa(l).catch(()=>[]),R=[];for(let E of h.filter(Z=>Z.endsWith(".json")).sort()){let Z=Et(await jo(Xt(l,E),e));Z&&R.push({file:E,value:Z})}let w=c.flatMap(({value:E})=>[E.createdAt,E.updatedAt]).filter(E=>typeof E=="number"&&Number.isFinite(E)),b=w.length?Math.min(...w):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=ge(g,"project",g,b),y=ge(g,"participant","legacy-owner",b),f=ge(g,"participant","legacy-agent",b),v=ge(g,"subject","project",b),x=ze(Math.max(b,...w)),S=[],_=[],J=new Map,A=new Map,N=new Map(R.map(E=>[E.value.id??E.file.replace(/^d-|\.json$/g,""),E.value])),T=new Map,B=(E,Z,V,ke,Me)=>{let Ie=J.get(V);if(Ie)return Ie;let _e=ge(g,"artifact",E,ke);return _.push({id:_e,kind:Z,mediaType:Me,location:V,availability:"available"}),J.set(V,_e),_e};for(let{file:E,value:Z}of R){let V=Z.id??E.replace(/^d-|\.json$/g,""),ke=Z.createdAt??b,Me=[B(`${V}:envelope`,"other",`.popmelt/decisions/${E}`,ke,"application/json")];Z.screenshotPath&&Me.push(B(`${V}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ie,_e]of(Z.pastedImagePaths??[]).entries())Me.push(B(`${V}:image:${Ie}`,"image",_e,ke));T.set(V,Me)}let H=(E,Z,V)=>({id:E,schemaVersion:1,projectId:p,createdAt:x,participantId:Z,sourceRefs:V}),te=(E,Z)=>{S.push(Z);let V=A.get(E)??[];V.push(Z.id),A.set(E,V)},W=[{...H(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...H(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...W),S.push({...H(v,y,[]),recordType:"subject",subjectType:"project",label:ka(process.cwd(),n)||n,aliases:[],locators:[{id:ge(g,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:ze(b),sourceRefs:[]}]});let ne=new Map,oe=(E,Z)=>{let V=ne.get(E);if(V)return V;let ke=ge(g,"subject",E,Z),Me={...H(ke,y,[{kind:"external",id:E}]),createdAt:ze(Z),recordType:"subject",subjectType:"element",label:E,aliases:[],locators:[{id:ge(g,"locator",E,Z),kind:"dom_selector",value:E,status:"current",validFrom:ze(Z),sourceRefs:[{kind:"external",id:E}]}]};return S.push(Me),ne.set(E,ke),ke};for(let{key:E,value:Z}of c){let V=Z.id??E,ke=Z.createdAt??b,Me=ge(g,"thread",V,ke),Ie={kind:"thread",id:V},_e=[],Je=[],Bt=Array.isArray(Z.messages)?Z.messages:[],qe,rt,Lt=0;Bt.forEach((ve,st)=>{let Ae=ve.timestamp??ke,Ye=ge(g,"artifact",`${V}:message:${st}`,Ae);if(_e.push(Ye),_.push({id:Ye,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${V}/messages/${st}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${V}/messages/${st}`,Ye),ve.screenshotPath&&B(`${V}:message:${st}:screenshot`,"screenshot",ve.screenshotPath,Ae),ve.role==="human"){qe=ve;let Ne=ve.feedbackSummary??ve.replyToQuestion;if(Ne?.trim()){let Be=ge(g,"observation",`${V}:${st}`,Ae),ct=Z.elementIdentifiers??[],St={...H(Be,y,[Ie,{kind:"message",id:Ye}]),createdAt:ze(Ae),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:ct.map(mt=>oe(mt,ke)),artifactIds:[Ye]},resolvedByIds:[]};te(V,St),rt=Be,Je.push({entityType:"observation",entityId:Be})}return}if(ve.role!=="assistant")return;let it=ve.jobId??`${V}:${st}`,at=ge(g,"iteration",it,Ae),ut=N.get(it),Ft=ve.cancelled?"cancelled":ve.error?"failed":ve.question?"question_asked":(ve.resolutions?.length??0)>0?"completed":"no_change",ro={...H(at,f,[Ie,{kind:"message",id:Ye},...(T.get(it)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:ze(Ae),recordType:"iteration",threadIds:[Me],startedAt:ze(qe?.timestamp,Ae),completedAt:ze(Ae),requestSummary:Cr(qe?.feedbackSummary,qe?.replyToQuestion)??"[legacy request unavailable]",responseSummary:ve.question??ve.error??ve.responseText?.slice(0,1e3),outcome:Ft,execution:{provider:ve.provider??ut?.provider,model:ve.model??ut?.model,sessionId:ve.sessionId??ut?.sessionId},artifactIds:[Ye,...T.get(it)??[]]};te(V,ro),Je.push({entityType:"iteration",entityId:at});let zt=ve.resolutions??ut?.resolutions??[];for(let[Ne,Be]of zt.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let ct=Z.elementIdentifiers??[],St=(ct.length?ct:[n]).map(ln=>({subjectId:ln===n?v:oe(ln,ke),role:"governed"})),mt=ge(g,"proposal",`${it}:${Be.annotationId??"resolution"}:${Ne}`,Ae),so={...H(mt,f,[Ie,{kind:"iteration",id:at}]),createdAt:ze(Ae),recordType:"proposal",state:"pending",claim:Be.summary,subjects:St,subjectSemantics:St.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Cr(qe?.feedbackSummary,qe?.replyToQuestion,Be.summary),iterationId:at,inferredById:f}};te(V,so),Je.push({entityType:"proposal",entityId:mt}),e.push({severity:"warning",code:"acceptance_unresolved",source:V,message:`Proposal ${mt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(zt.some(Ne=>Ne.status==="resolved")||ut?.gitDiff){let Ne=ge(g,"implementation",it,Ae),Be={...H(Ne,f,[Ie,{kind:"iteration",id:at}]),createdAt:ze(Ae),recordType:"implementation_attempt",state:"completed",iterationIds:[at],coverageClaims:[],summary:zt.map(ct=>ct.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};te(V,Be),Je.push({entityType:"implementation_attempt",entityId:Ne}),Lt+=1}rt&&(rt=void 0)});let xt=Bt.at(-1),oo={...H(Me,y,[Ie]),createdAt:ze(ke),recordType:"thread",state:xt?.question?"open":"resolved",messageArtifactIds:_e,outcome:xt?.question?"question_unresolved":Lt?"implementation_only":"no_outcome",resultRefs:Je};S.push(oo),A.set(V,[Me,...A.get(V)??[]])}let he=ja(s);he&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${he} model values were not promoted because their accepted decision provenance is unresolved.`});let Y={manifest:{formatVersion:1,projectId:p,createdAt:ze(b),updatedAt:x,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:S,events:[],relationships:[],artifacts:_,tombstones:[]},G=vt(Y),fe=(o.proofCaseIds??Ta).map(E=>({legacyId:E,threadFound:c.some(({key:Z,value:V})=>(V.id??Z)===E),decisionEnvelopeFound:N.has(E),recordIds:A.get(E)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:c.length,messages:c.reduce((E,Z)=>E+(Z.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:he,artifactsReferenced:_.length},imported:Ea(S),unresolvedAcceptance:e.filter(E=>E.code==="acceptance_unresolved").length,deferredModelEntries:he,proofCases:fe,issues:e,schemaIssues:G.issues}}}import{createHash as Ma}from"crypto";import{mkdir as $r,open as Eo,readFile as Mo,readdir as _a,rename as Aa,unlink as _o}from"fs/promises";import{join as tt}from"path";var Ca={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function _n(o){return Ma("sha256").update(JSON.stringify(o)).digest("hex")}function Or(o){return _n(o)}function Dr(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 $a(o,e,n){return Dr(structuredClone(o),e,n)}async function wt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Eo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
177
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Aa(n,o)}catch(r){throw await _o(n).catch(()=>{}),r}}async function Mn(o){return JSON.parse(await Mo(o,"utf8"))}var An=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=tt(e,".popmelt","memory"),this.journalDir=tt(this.memoryDir,"journal"),this.manifestPath=tt(this.memoryDir,"manifest.json"),this.checkpointPath=tt(this.memoryDir,"checkpoint.json"),this.lockPath=tt(this.memoryDir,"writer.lock")}async initialize(e){let n=vt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await $r(this.journalDir,{recursive:!0});try{throw await Mo(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 Mo(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=_n(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 wt(this.checkpointPath,r),await wt(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 wt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=_n(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await wt(tt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await wt(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:Or(s)},d=$a(t.bundle,e,n.committedAt),c=vt(d);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await wt(tt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await wt(this.manifestPath,t.manifest),{bundle:d,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:i.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Ca,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(tt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==_n(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await _a(this.journalDir),r=t.filter(w=>w.endsWith(".tmp")),i=t.filter(w=>/^\d{12}-[0-9a-f-]+\.json$/i.test(w)).sort().filter(w=>Number(w.slice(0,12))>n.sequence),d=structuredClone(n.bundle),c=n.sequence,l=n.journalHash??null,h=new Set;for(let w of i){let b=await Mn(tt(this.journalDir,w)),{hash:g,...p}=b;if(g!==Or(p))throw new Error(`Journal hash mismatch: ${w}`);if(b.sequence!==c+1)throw new Error(`Journal sequence gap at ${w}`);if(b.previousHash!==l)throw new Error(`Journal chain mismatch at ${w}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${w}`);if(h.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);Dr(d,b.mutation,b.committedAt),c=b.sequence,l=b.hash,h.add(b.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=vt(d);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:d,manifest:e,transactionIds:h,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:c,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await $r(this.memoryDir,{recursive:!0});let n;try{n=await Eo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Mn(this.lockPath).catch(()=>({})),s=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(i){s=i.code!=="ESRCH"}if(s)throw new Error("Memory journal is locked by another writer.");await _o(this.lockPath),n=await Eo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await _o(this.lockPath).catch(()=>{})}}};import{randomBytes as Oa}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Oa(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 Da=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Jr(o,e){let n=o.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active"),t=o.records.find(x=>x.recordType==="participant"&&x.kind==="ai"&&x.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,s=`${e.threadId}:${e.jobId}`,i=new Date(e.createdAt).toISOString(),d=new Date(e.completedAt).toISOString(),c=Da(),l=c.records,h=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));h||(h={id:ge(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(x=>x.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(h));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(_=>_.recordType==="subject"&&_.locators.some(J=>J.value===x&&J.status==="current"));S||(S={id:ge(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:ge(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(_=>_.recordType==="subject"&&_.locators.some(J=>J.kind==="source_file"&&J.value===x&&J.status==="current"));S||(S={id:ge(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:ge(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 w=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),b;if(w.length>0){b=ge(r,"live-observation",s,e.createdAt);let x={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:w.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds:R.map(S=>S.id),artifactIds:[]},resolvedByIds:[]};l.push(x)}let g=ge(r,"live-iteration",s,e.completedAt),p={id:g,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[h.id],startedAt:i,completedAt:d,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let y=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),v=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(w.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of w.entries()){let _=ge(r,"live-proposal",`${s}:${x}`,e.completedAt),J=v.map(N=>({subjectId:N.id,role:"governed"})),A={id:_,schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"iteration",id:g},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:S.claim.trim(),rationale:S.rationale?.trim()||void 0,proposedKind:S.proposedKind,subjects:J,subjectSemantics:J.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:S.sourceText?.trim()||e.requestSummary,iterationId:g,inferredById:t.id}};l.push(A),y.push(_)}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)),_={id:ge(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"iteration",id:g}],recordType:"implementation_attempt",state:"completed",iterationIds:[g],coverageClaims:S.map(J=>({decisionId:J.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(A=>A.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(_)}return{mutation:c,iterationId:g,proposalIds:y,observationId:b}}import{createHash as Ja}from"crypto";import{mkdir as Na,open as Ba,readFile as La,rename as Fa,unlink as za}from"fs/promises";import{join as Nr}from"path";function Br(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Lr(o){return Ja("sha256").update(JSON.stringify(o)).digest("hex")}async function qa(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ba(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Fa(n,o)}catch(r){throw await za(n).catch(()=>{}),r}}function Ua(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(c,l,h)=>{let R=c[l]??=[];R.includes(h)||R.push(h)};for(let c of o.records)if(c.recordType==="subject"){let l=c;for(let h of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Br(h);R&&i(t,R,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)i(r,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)i(s,l.subjectId,c.id);let d={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...d,checksum:Lr(d)}}function Fr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Br(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var Cn=class{constructor(e){this.indexDir=Nr(e,".popmelt","memory","indexes"),this.indexPath=Nr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await La(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===Lr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ua(e,n);return await Na(this.indexDir,{recursive:!0}),await qa(this.indexPath,t),t}};var $n=class{constructor(e){this.projectRoot=e;this.store=new An(e),this.indexStore=new Cn(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 Yt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Yt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=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 Ao(e,{recursive:!0}),await Co(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 Ao(e,{recursive:!0}),await Co(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=0;for(let s of t.explanations){let i=s.evidence.length?s.evidence:[{id:s.id,kind:"observation",stance:"supports",summary:s.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:s.createdAt}];for(let d of i){let c=d.kind==="confirmation"?"confirm":d.kind==="correction"||d.kind==="rejection"?"reason_wrong":d.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:d.id,kind:c?"strengthened":"added",title:s.statement.slice(0,120),detail:d.summary,changes:[{explanationId:s.id,action:c==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:d.threadId,jobId:d.jobId,action:c,occurredAt:d.createdAt}),r+=1}}return await Ao(e,{recursive:!0}),await Co(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:Ro(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:_r(t.bundle,r),reviewSelection:Ro(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:En(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Yt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=En(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(w=>w.recordType==="proposal"&&w.id===e.proposalId),r=n.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),d={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},c=e.action==="accept"?{...d,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...d,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...d,action:"reject",eventId:le(s),reason:e.reason}:{...d,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(w=>w.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=En(n.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(w=>w.message).join(" ")};let h=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(h);let R=l.plan.resultRefs.find(w=>w.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:h.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Jr(n.bundle,e),r=ge(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(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active"),r=n.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="ai"&&w.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!s||!i)return;let d=e.occurredAt??new Date().toISOString(),c=Date.parse(d),l=[],h=[];for(let w of e.summary.changes){let b={kind:"external",id:w.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(y=>y.recordType==="observation"&&y.sourceRefs.some(f=>f.kind==="external"&&f.id===w.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:w.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),h.push({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ge(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,c);try{let w=await this.store.commit({records:l,events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:d});await this.refreshIndex(w)}catch(w){if(!(w instanceof Error)||!w.message.includes("Transaction already exists"))throw w}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="model_projection"&&i.state==="applied"?i.coverage.filter(d=>d.status==="projected").map(d=>d.decisionId):[])),r=new Set(n.relationships.flatMap(i=>i.relationshipType==="contradicts"&&i.from.entityType==="decision"&&i.to.entityType==="decision"?[i.from.entityId,i.to.entityId]:[])),s=new Set(n.records.flatMap(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.target.entityType==="decision"?[i.target.entityId]:[]));return n.records.filter(i=>i.recordType==="decision"&&i.state==="active"&&!t.has(i.id)&&!r.has(i.id)&&!s.has(i.id)).sort((i,d)=>d.createdAt.localeCompare(i.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(s=>s.recordType==="model_entry").sort((s,i)=>s.createdAt.localeCompare(i.createdAt)))r.decisionIds.some(s=>n.has(s))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id]:[])),t=new Map;for(let d of e.records.filter(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))d.decisionIds.some(c=>n.has(c))&&t.set(d.key,d);let r=[...t.values()],s=e.records.filter(d=>d.recordType==="verification_attempt");return{decisions:e.records.filter(d=>d.recordType==="decision"&&d.state==="active").map(d=>{let c=s.filter(l=>l.targets.some(h=>h.entityType==="decision"&&h.entityId===d.id)).sort((l,h)=>h.createdAt.localeCompare(l.createdAt))[0];return{id:d.id,kind:d.kind,claim:d.claim,projected:r.some(l=>l.decisionIds.includes(d.id)),verification:c?c.state:"unverified"}}),entries:r.map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(d=>d.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),d=le(s),c=le(s),l=le(s),h=le(s),R=le(s),w=new Set(n.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),b=n.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&w.has(T.id)),g={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],y={...g,id:d,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:c,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:d},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...g,id:l,recordType:"decision",proposalId:d,acceptanceEventId:c,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...g,id:h,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${s}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:i,decisionIds:[l],entryIds:[h],coverage:[{decisionId:l,status:"projected"}]},_={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=b.map(T=>({...g,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),A=b.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[y,v,x,S],events:[f,...J],relationships:[_,...A],artifacts:[],tombstones:[],projectionUpdates:b.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:h}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),s=n.bundle.records.flatMap(g=>g.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===g.id||g.sourceRefs.some(y=>y.id===p))?[g.id]:[]),i=[...new Set(n.bundle.records.flatMap(g=>g.recordType==="decision"&&s.includes(g.id)?g.subjects.map(p=>p.subjectId):[]))],c={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(c))continue;let l=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!l)throw new Error("No active local owner participant is available.");let h=Date.now(),R=new Date(h).toISOString(),w={id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...c,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},b=r?[{id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:w.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:w.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[w],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(h),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(i=>i.objectType==="eval_spec").map(i=>i.objectId)),t=e.records.filter(i=>i.recordType==="eval_spec").reverse().filter((i,d,c)=>c.findIndex(l=>l.legacyId===i.legacyId)===d).filter(i=>!n.has(i.id)),r=e.records.filter(i=>i.recordType==="verification_attempt"),s=e.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.targetKind==="verification_result");return t.map(i=>{let d=r.filter(h=>h.evalSpecId===i.id).sort((h,R)=>R.createdAt.localeCompare(h.createdAt))[0],c=d&&s.some(h=>h.target.entityType==="verification_attempt"&&h.target.entityId===d.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":d?c?"stale":d.state==="passed"?"passing":d.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:d?.scopeFingerprint,verificationAttemptId:d?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(d=>({assertion:d,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(w=>w.recordType==="verification_attempt"&&w.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(w=>w.recordType==="participant"&&w.status==="active"&&w.kind==="ai")??t.bundle.records.find(w=>w.recordType==="participant"&&w.status==="active");if(!s)return;let i=n.completedAt,d=new Date(i).toISOString(),c={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[c.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},h=r.targets.map(w=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:c.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:w,reason:n.summary})),R=await this.store.commit({records:[c,l],events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),d={id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},c=await this.store.commit({records:[d],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(c)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id,...c.sourceRefs.map(l=>l.id)]:[])),r=e.filter(c=>(c.dependencies?.length??0)>0||c.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(c=>!r.includes(c)).map(c=>c.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(c=>c.recordType==="participant"&&c.kind==="human"&&c.status==="active");if(!i)return{valid:r,discardedIds:s};let d=s.flatMap(c=>{let l=this.latestEvalSpec(n.bundle,c);return l?[l]:[]}).filter(c=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===c.id));if(d.length>0){let c=Date.now(),l=new Date(c).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:d.map(h=>({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:h.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(c),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="model_projection"&&g.state==="applied"&&g.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(g=>g.recordType==="decision"&&e.decisionIds.includes(g.id)&&g.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let s=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),d=new Date(i).toISOString(),c=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(v=>e.decisionIds.includes(v)),y=p?.length?p:e.decisionIds,f=[...new Set(r.filter(v=>y.includes(v.id)).flatMap(v=>v.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:y.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:y,value:g.value}}),h=new Set(l.flatMap(g=>g.decisionIds)),R={id:c,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:e.decisionIds.map(g=>({kind:"record",id:g})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:d,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:h.has(g)?"projected":"unprojected"})},w=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...l,R],events:[],relationships:w,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});return await this.refreshIndex(b),{projectionId:c,entryIds:l.map(g=>g.id),headSequence:b.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Yt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Fr(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 At(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=At(o),n=At(e.authority),t=n.level,r=n.mode,s=_t(t,"authority.level",["owner","delegate","contributor"]),i=_t(r,"authority.mode",["local_trusted","hosted"]),d={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...d,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...d,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let c=At(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...d,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>_t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...d,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=At(c);return{subjectId:Se(l.subjectId,"subjectId"),role:_t(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Oo(o){let e=At(o),n=(s,i)=>{if(s!==void 0){if(!Array.isArray(s))throw new Error(`${i} must be an array.`);return s.map(d=>Se(d,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0:At(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function On(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
179
|
-
`)}async function
|
|
180
|
-
`)}function
|
|
176
|
+
`;return await Rr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Er(o=Po,e="copilot"){let n=await da(e);if(la(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{Sr(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},s=>{if(s){r(s);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function da(o){try{let e=await new Promise((n,t)=>{Sr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return JSON.parse(e)}catch{return null}}function la(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var kn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),s={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,s),s}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as Co,readFile as At,writeFile as $o}from"fs/promises";import{join as pt}from"path";var pa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Ro(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Tn(o){return new Set(Ro(o).split(" ").filter(e=>e.length>2&&!pa.has(e)))}function Mr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ua(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function ma(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Ro).filter(Boolean),s=Tn([e.action,e.text].filter(Boolean).join(" "));for(let i of o){if(t.has(i.id)){n.set(i.id,{subjectId:i.id,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let d;for(let c of ua(i)){let l=Ro(c.value);for(let I of r){let b=l===I?95:l.includes(I)||I.includes(l)?75:0;b>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:b>=90?"exact":"strong",matchedBy:c.by,score:b})}let R=["/","#","[","]","="].some(I=>c.value.includes(I))?0:Math.round(Mr(Tn(l),s)*55);R>=30&&R>(d?.score??0)&&(d={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}d&&n.set(i.id,d)}return n}function fa(o,e){let n=new Set(o.sourceRefs.filter(i=>i.kind==="iteration").map(i=>i.id)),t=new Set(o.sourceRefs.filter(i=>i.kind==="thread").map(i=>i.id)),r=e.filter(i=>i.iterationIds.some(d=>n.has(d))||i.sourceRefs.some(d=>d.kind==="thread"&&t.has(d.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let s=new Set(r.map(i=>i.state));return{state:s.size>1?"mixed":s.has("completed")?"completed":"attempted",attemptIds:r.map(i=>i.id)}}function ha(o){return Math.ceil(JSON.stringify(o).length/4)}function ko(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let f=[...o.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===y.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(t)>=Date.parse(f.revisitAfter)):!1}),i=o.records.filter(y=>y.recordType==="implementation_attempt"),d=ma(n,e),c=[...d.values()].sort((y,f)=>f.score-y.score),l=Tn([e.action,e.text].filter(Boolean).join(" ")),h=s.flatMap(y=>{let f=y.subjects.map(A=>d.get(A.subjectId)).filter(A=>!!A),v=Math.max(0,...f.map(A=>A.score)),x=Math.round(Mr(Tn(y.claim),l)*35),S=v+x;return S>=50?[{proposal:y,proposalMatches:f,score:S}]:[]}).sort((y,f)=>f.score-y.score||y.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),I=Math.max(200,e.maxEstimatedTokens??1200),b=[],g=0;for(let y of h){if(b.length>=R)break;let f=y.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:S,...A})=>A)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(S=>S.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:fa(y.proposal,i),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...f]},x={...v,estimatedTokens:ha(v)};if(g+x.estimatedTokens>I)break;b.push(x),g+=x.estimatedTokens}let p=Math.max(0,h.length-b.length);return{packets:b,subjectMatches:c.map(({score:y,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:h.length,omittedPacketCount:p,maxEstimatedTokens:I,estimatedTokens:g},uncertainty:d.size===0?"subject_unresolved":h.length===0?"no_relevant_pending_proposal":void 0}}var ga=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function To(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function jn(o){return new Set(To(o).split(" ").filter(e=>e.length>2&&!ga.has(e)))}function Ar(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ya(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(To).filter(Boolean),r=jn([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let d,c=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of c){let h=To(l.value);for(let b of t){let g=h===b?95:h.includes(b)||b.includes(h)?75:0;g>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:g>=90?"exact":"strong",matchedBy:l.by,score:g})}let I=["/","#","[","]","="].some(b=>l.value.includes(b))?0:Math.round(Ar(jn(h),r)*55);I>=30&&I>(d?.score??0)&&(d={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:I>=45?"strong":"weak",matchedBy:"semantic",score:I})}d&&s.push(d)}return s.sort((i,d)=>d.score-i.score||i.subjectId.localeCompare(d.subjectId))}function va(o){return Math.ceil(JSON.stringify(o).length/4)}function jt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function wa(o,e){let n=e.filter(s=>s.coverageClaims.some(i=>i.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(s=>s.state==="completed"),r=t.some(s=>s.coverageClaims.some(i=>i.decisionId===o&&i.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(s=>s.id)}}function Ia(o,e,n){let t=e.filter(d=>d.targets.some(c=>c.entityType==="decision"&&c.entityId===o)).sort((d,c)=>c.createdAt.localeCompare(d.createdAt)),r=n.some(d=>d.signalType==="verification_expired"&&d.target.entityType==="decision"&&d.target.entityId===o),s=t[0],i=r?"stale":s?s.state==="passed"?"passing":s.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(s.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:i,attemptIds:t.map(d=>d.id)}}function _r(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(_=>_.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(_=>_.recordType==="decision"&&_.state==="active"),d=s?i.filter(_=>s.has(_.id)):i,c=o.records.filter(_=>_.recordType==="implementation_attempt"),l=o.records.filter(_=>_.recordType==="verification_attempt"),h=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),R=o.records.filter(_=>_.recordType==="evidence"),I=o.records.filter(_=>_.recordType==="model_entry"),b=[...o.records].reverse().filter(_=>_.recordType==="eval_spec").filter((_,N,T)=>T.findIndex(B=>B.legacyId===_.legacyId)===N),g=ya(r,e),p=new Map(g.map(_=>[_.subjectId,_.score])),y=jn([e.action,e.text].filter(Boolean).join(" ")),f=d.flatMap(_=>{let N=Math.max(0,..._.subjects.map(H=>p.get(H.subjectId)??0)),T=Math.round(Ar(jn(_.claim),y)*35),B=N+T;return B>=50?[{decision:_,score:B}]:[]}).sort((_,N)=>N.score-_.score||_.decision.id.localeCompare(N.decision.id)),v=new Map;for(let _ of f.slice(0,t))v.set(_.decision.id,_.decision);for(let _ of o.relationships){if(!jt(_,"excepts")&&!jt(_,"contradicts"))continue;let N=i.find(B=>B.id===_.from.entityId),T=i.find(B=>B.id===_.to.entityId);!N||!T||!v.has(N.id)&&!v.has(T.id)||(v.size<t&&v.set(N.id,N),v.size<t&&v.set(T.id,T))}let x=[...v.values()],S=_=>_.from.entityType==="decision"&&_.to.entityType==="decision"&&v.has(_.from.entityId)&&v.has(_.to.entityId),A=(_,N=!1)=>{let T=new Set(_.map(M=>M.id)),B=h.filter(M=>M.target.entityType==="decision"&&T.has(M.target.entityId)),H=new Set(o.relationships.filter(M=>jt(M,"excepts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).flatMap(M=>[M.from.entityId,M.to.entityId])),W=o.relationships.filter(M=>jt(M,"contradicts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).map(M=>({id:M.id,decisionIds:[M.from.entityId,M.to.entityId],unresolvedQuestion:M.reason,expansionRefs:[{kind:"record",id:M.id}]})),te=new Set(W.flatMap(M=>M.decisionIds)),ne=R.filter(M=>M.sourceRefs.some(Y=>Y.kind==="record"&&T.has(Y.id))||o.relationships.some(Y=>Y.relationshipType==="supports"&&Y.from.entityType==="evidence"&&Y.from.entityId===M.id&&Y.to.entityType==="decision"&&T.has(Y.to.entityId))),ge=Math.max(0,f.length-_.length),X=o.relationships.some(M=>jt(M,"contradicts")&&S(M)&&(!T.has(M.from.entityId)||!T.has(M.to.entityId))),G=N||ge>0||X,U=[];g.length===0&&(e.subjectHints?.length??0)>0?U.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):_.length===0&&U.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),W.length&&U.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:W.flatMap(M=>M.expansionRefs)}),ne.some(M=>M.availability!=="available")&&U.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:ne.map(M=>({kind:"record",id:M.id}))}),G&&U.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let he={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:g.map(({score:M,...Y})=>Y),modelEntries:I.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,key:M.key,value:M.value,decisionIds:M.decisionIds})),evalSpecs:b.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,legacyId:M.legacyId,state:M.state,title:M.title,assertionCount:M.assertions.length,decisionIds:M.decisionIds,expansionRef:{kind:"record",id:M.id}})),decisions:_.map(M=>({id:M.id,kind:M.kind,claim:M.claim,subjectIds:M.subjects.map(Y=>Y.subjectId),authority:M.authority,effectiveState:te.has(M.id)?"conflicted":H.has(M.id)?"excepted":"active",freshness:B.filter(Y=>Y.target.entityId===M.id).map(Y=>Y.signalType),expansionRef:{kind:"record",id:M.id}})),conflicts:W,uncertainties:U,implementation:_.map(M=>wa(M.id,c)),verification:_.map(M=>Ia(M.id,l,B)),evidence:ne.map(M=>({evidenceId:M.id,summary:M.summary,availability:M.availability,sourceRefs:M.sourceRefs})),completeness:{status:G?"truncated":"complete",omittedDecisionCount:ge,omittedEvidenceCount:0,conflictsComplete:!X}};return he.budget.estimatedTokens=va(he),he},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>jt(T,"contradicts")&&(T.from.entityId===_.id||T.to.entityId===_.id)).flatMap(T=>[T.from.entityId,T.to.entityId]);x=x.filter(T=>!N.includes(T.id)),J=A(x,!0)}return J}var ba=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Et(o){return ba.test(o)}function xa(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ce(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function jo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){Et(n)||ce(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function lt(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ce(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(o,e,n,t=!1){t&&n.level==="contributor"&&ce(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ce(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Sa={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},Pa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ra(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),lt(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=Sa[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ce(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let s=`${e.entity.entityType}:${e.toState}`;if(Pa.has(s)&&(wt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ce(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let i=e.transitionContext;(i?.kind!=="proposal_deferral"||i.resurfaceWhen.length===0)&&ce(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),i?.resurfaceWhen.includes("after_date")&&!i.revisitAfter&&ce(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),i?.revisitAfter&<(o,`${n}.transitionContext.revisitAfter`,i.revisitAfter)}}function ka(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),lt(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ce(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ce(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ce(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ce(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(wt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ce(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&jo(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ce(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(lt(o,`${n}.appliedAt`,e.appliedAt),wt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ce(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&ce(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ce(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&jo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&jo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ta(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),lt(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ce(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)&&((e.from.entityType!=="decision"||e.to.entityType!=="decision")&&ce(o,n,"invalid_normative_relationship","Normative relationships connect decisions to decisions."),e.authority?wt(o,`${n}.authority`,e.authority,!0):ce(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context.")),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ce(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&ce(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ce(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function It(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),lt(e,"manifest.createdAt",o.manifest.createdAt),lt(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,y)=>{let f=n.get(p);f?ce(e,y,"duplicate_id",`ID is already used at ${f}.`):n.set(p,y)};o.records.forEach((p,y)=>{let f=`records[${y}]`;t(p.id,f),ka(e,p,f,o.manifest.projectId)}),o.events.forEach((p,y)=>{let f=`events[${y}]`;t(p.id,f),Ra(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let f=`relationships[${y}]`;t(p.id,f),Ta(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let f=`tombstones[${y}]`;t(p.id,f),Te(e,`${f}.id`,p.id),Te(e,`${f}.objectId`,p.objectId),Te(e,`${f}.deletedById`,p.deletedById),lt(e,`${f}.deletedAt`,p.deletedAt),wt(e,`${f}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),s=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),i=(p,y)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,y,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,y)=>i(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{i(p.from,`relationships[${y}].from`),i(p.to,`relationships[${y}].to`)});let d=new Set(o.artifacts.map(p=>p.id)),c=(p,y)=>{d.has(p)||ce(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,f)=>{!r.has(`${p}:${y}`)&&!s.has(`${p}:${y}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let f=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`));break;case"observation":p.captureContext.subjectIds.forEach((v,x)=>l("subject",v,`${f}.captureContext.subjectIds[${x}]`)),p.captureContext.artifactIds.forEach((v,x)=>c(v,`${f}.captureContext.artifactIds[${x}]`));break;case"proposal":case"decision":p.subjects.forEach((v,x)=>l("subject",v.subjectId,`${f}.subjects[${x}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((v,x)=>c(v,`${f}.messageArtifactIds[${x}]`)),p.resultRefs.forEach((v,x)=>i(v,`${f}.resultRefs[${x}]`));break;case"iteration":p.threadIds.forEach((v,x)=>l("thread",v,`${f}.threadIds[${x}]`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"implementation_attempt":p.iterationIds.forEach((v,x)=>l("iteration",v,`${f}.iterationIds[${x}]`)),p.coverageClaims.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverageClaims[${x}].decisionId`)),p.artifactIds.forEach((v,x)=>c(v,`${f}.artifactIds[${x}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),(p.dependencies??[]).forEach((v,x)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${f}.dependencies[${x}].subjectId`)}),(p.scenarios??[]).forEach((v,x)=>{v.subjectIds?.forEach((S,A)=>l("subject",S,`${f}.scenarios[${x}].subjectIds[${A}]`))}),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((v,x)=>l(v.entityType,v.entityId,`${f}.targets[${x}]`)),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;case"model_entry":p.subjectIds.forEach((v,x)=>l("subject",v,`${f}.subjectIds[${x}]`)),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`));break;case"model_projection":wt(e,`${f}.authority`,p.authority,!0),l("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((v,x)=>l("decision",v,`${f}.decisionIds[${x}]`)),p.entryIds.forEach((v,x)=>l("model_entry",v,`${f}.entryIds[${x}]`)),p.coverage.forEach((v,x)=>l("decision",v.decisionId,`${f}.coverage[${x}].decisionId`));break;case"freshness_signal":i(p.target,`${f}.target`),p.evidenceIds.forEach((v,x)=>l("evidence",v,`${f}.evidenceIds[${x}]`));break;default:break}});let h=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),I=new Map;o.events.forEach((p,y)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,v=I.get(f)??new Set;v.add(p.toState),I.set(f,v),v.size>1&&ce(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),g=(p,y,f,v,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=b.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==y||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(f);(A<Date.parse(S.startsAt)||S.endsAt&&A>Date.parse(S.endsAt)||S.revokedAt&&A>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&v.length&&!v.every(J=>S.subjectIds.includes(J))&&ce(e,x,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&g(p.authority,p.acceptedById,p.createdAt,p.subjects.map(y=>y.subjectId),`records:${p.id}.authority`);o.events.forEach((p,y)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),v=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];g(p.authority,p.participantId,p.createdAt,v,`events[${y}].authority`)}),o.relationships.forEach((p,y)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(v=>{let x=R.get(`${v.entityType}:${v.entityId}`);return x&&"subjects"in x?x.subjects.map(S=>S.subjectId):[]});g(p.authority,p.participantId,p.createdAt,f,`relationships[${y}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let y=h.get(p.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==p.proposalId||y.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===p.id)||ce(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===p.id&&v.toState==="revoked"&&!!v.reason?.trim())||ce(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||ce(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return xa(e)}function Qt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Cr(o,e,n,t,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function ja(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function En(o,e){let n=[],t=o.records.find(s=>s.recordType==="proposal"&&s.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Et(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of ja(e))Et(s)||n.push({code:"invalid_generated_id",message:`${s} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let s={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},i=Cr(o,t,e,s.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:i.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let s={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},i={...Qt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},d={...Qt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Cr(o,s,e,d.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,c],events:[i,d],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ea}from"crypto";import{readFile as Ma,readdir as Aa,realpath as _a}from"fs/promises";import{join as Xt,relative as Ca}from"path";var $a=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Mt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Fe(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function $r(...o){return o.find(e=>!!e?.trim())?.trim()}function ye(o,e,n,t){let s=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),i=Ea("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),d=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${d}${i.slice(4,7)}-${i.slice(7,19)}`}async function Eo(o,e){try{return JSON.parse(await Ma(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Oa(o){let e=Mt(o);if(!e)return 0;let n=0,t=r=>{let s=Mt(r);if(!s){n+=1;return}for(let i of Object.values(s))t(i)};for(let r of Object.values(e))t(r);return n}function Da(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Yt(o){let e=[],n=await _a(o.projectRoot).catch(()=>o.projectRoot),t=Xt(n,".popmelt"),r=await Eo(Xt(t,"threads.json"),e),s=await Eo(Xt(t,"model.json"),e),i=Mt(r),d=Mt(i?.threads)??{},c=Object.entries(d).map(([M,Y])=>({key:M,value:Mt(Y)})).filter(M=>!!M.value),l=Xt(t,"decisions"),h=await Aa(l).catch(()=>[]),R=[];for(let M of h.filter(Y=>Y.endsWith(".json")).sort()){let Y=Mt(await Eo(Xt(l,M),e));Y&&R.push({file:M,value:Y})}let I=c.flatMap(({value:M})=>[M.createdAt,M.updatedAt]).filter(M=>typeof M=="number"&&Number.isFinite(M)),b=I.length?Math.min(...I):0,g=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ye(g,"project",g,b),y=ye(g,"participant","legacy-owner",b),f=ye(g,"participant","legacy-agent",b),v=ye(g,"subject","project",b),x=Fe(Math.max(b,...I)),S=[],A=[],J=new Map,_=new Map,N=new Map(R.map(M=>[M.value.id??M.file.replace(/^d-|\.json$/g,""),M.value])),T=new Map,B=(M,Y,ue,ie,De)=>{let Je=J.get(ue);if(Je)return Je;let Pe=ye(g,"artifact",M,ie);return A.push({id:Pe,kind:Y,mediaType:De,location:ue,availability:"available"}),J.set(ue,Pe),Pe};for(let{file:M,value:Y}of R){let ue=Y.id??M.replace(/^d-|\.json$/g,""),ie=Y.createdAt??b,De=[B(`${ue}:envelope`,"other",`.popmelt/decisions/${M}`,ie,"application/json")];Y.screenshotPath&&De.push(B(`${ue}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,ie,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Je,Pe]of(Y.pastedImagePaths??[]).entries())De.push(B(`${ue}:image:${Je}`,"image",Pe,ie));T.set(ue,De)}let H=(M,Y,ue)=>({id:M,schemaVersion:1,projectId:p,createdAt:x,participantId:Y,sourceRefs:ue}),ee=(M,Y)=>{S.push(Y);let ue=_.get(M)??[];ue.push(Y.id),_.set(M,ue)},W=[{...H(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...H(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...W),S.push({...H(v,y,[]),recordType:"subject",subjectType:"project",label:Ca(process.cwd(),n)||n,aliases:[],locators:[{id:ye(g,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:Fe(b),sourceRefs:[]}]});let te=new Map,ne=(M,Y)=>{let ue=te.get(M);if(ue)return ue;let ie=ye(g,"subject",M,Y),De={...H(ie,y,[{kind:"external",id:M}]),createdAt:Fe(Y),recordType:"subject",subjectType:"element",label:M,aliases:[],locators:[{id:ye(g,"locator",M,Y),kind:"dom_selector",value:M,status:"current",validFrom:Fe(Y),sourceRefs:[{kind:"external",id:M}]}]};return S.push(De),te.set(M,ie),ie};for(let{key:M,value:Y}of c){let ue=Y.id??M,ie=Y.createdAt??b,De=ye(g,"thread",ue,ie),Je={kind:"thread",id:ue},Pe=[],Ue=[],Ge=Array.isArray(Y.messages)?Y.messages:[],Ye,st,mt=0;Ge.forEach((we,it)=>{let Ae=we.timestamp??ie,Ze=ye(g,"artifact",`${ue}:message:${it}`,Ae);if(Pe.push(Ze),A.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${it}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${ue}/messages/${it}`,Ze),we.screenshotPath&&B(`${ue}:message:${it}:screenshot`,"screenshot",we.screenshotPath,Ae),we.role==="human"){Ye=we;let je=we.feedbackSummary??we.replyToQuestion;if(je?.trim()){let Ne=ye(g,"observation",`${ue}:${it}`,Ae),dt=Y.elementIdentifiers??[],Pt={...H(Ne,y,[Je,{kind:"message",id:Ze}]),createdAt:Fe(Ae),recordType:"observation",state:"open",statement:je,captureContext:{subjectIds:dt.map(ht=>ne(ht,ie)),artifactIds:[Ze]},resolvedByIds:[]};ee(ue,Pt),st=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let at=we.jobId??`${ue}:${it}`,ct=ye(g,"iteration",at,Ae),ft=N.get(at),ro=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",so={...H(ct,f,[Je,{kind:"message",id:Ze},...(T.get(at)??[]).map(je=>({kind:"artifact",id:je}))]),createdAt:Fe(Ae),recordType:"iteration",threadIds:[De],startedAt:Fe(Ye?.timestamp,Ae),completedAt:Fe(Ae),requestSummary:$r(Ye?.feedbackSummary,Ye?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:ro,execution:{provider:we.provider??ft?.provider,model:we.model??ft?.model,sessionId:we.sessionId??ft?.sessionId},artifactIds:[Ze,...T.get(at)??[]]};ee(ue,so),Ue.push({entityType:"iteration",entityId:ct});let zt=we.resolutions??ft?.resolutions??[];for(let[je,Ne]of zt.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let dt=Y.elementIdentifiers??[],Pt=(dt.length?dt:[n]).map(ln=>({subjectId:ln===n?v:ne(ln,ie),role:"governed"})),ht=ye(g,"proposal",`${at}:${Ne.annotationId??"resolution"}:${je}`,Ae),io={...H(ht,f,[Je,{kind:"iteration",id:ct}]),createdAt:Fe(Ae),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:Pt,subjectSemantics:Pt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:$r(Ye?.feedbackSummary,Ye?.replyToQuestion,Ne.summary),iterationId:ct,inferredById:f}};ee(ue,io),Ue.push({entityType:"proposal",entityId:ht}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${ht} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(zt.some(je=>je.status==="resolved")||ft?.gitDiff){let je=ye(g,"implementation",at,Ae),Ne={...H(je,f,[Je,{kind:"iteration",id:ct}]),createdAt:Fe(Ae),recordType:"implementation_attempt",state:"completed",iterationIds:[ct],coverageClaims:[],summary:zt.map(dt=>dt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};ee(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:je}),mt+=1}st&&(st=void 0)});let Lt=Ge.at(-1),Ft={...H(De,y,[Je]),createdAt:Fe(ie),recordType:"thread",state:Lt?.question?"open":"resolved",messageArtifactIds:Pe,outcome:Lt?.question?"question_unresolved":mt?"implementation_only":"no_outcome",resultRefs:Ue};S.push(Ft),_.set(ue,[De,..._.get(ue)??[]])}let ge=Oa(s);ge&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ge} model values were not promoted because their accepted decision provenance is unresolved.`});let X={manifest:{formatVersion:1,projectId:p,createdAt:Fe(b),updatedAt:x,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:S,events:[],relationships:[],artifacts:A,tombstones:[]},G=It(X),he=(o.proofCaseIds??$a).map(M=>({legacyId:M,threadFound:c.some(({key:Y,value:ue})=>(ue.id??Y)===M),decisionEnvelopeFound:N.has(M),recordIds:_.get(M)??[]}));return{bundle:X,report:{projectRoot:n,source:{threads:c.length,messages:c.reduce((M,Y)=>M+(Y.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:ge,artifactsReferenced:A.length},imported:Da(S),unresolvedAcceptance:e.filter(M=>M.code==="acceptance_unresolved").length,deferredModelEntries:ge,proofCases:he,issues:e,schemaIssues:G.issues}}}import{createHash as Ja}from"crypto";import{mkdir as Or,open as Mo,readFile as Ao,readdir as Na,rename as Ba,unlink as _o}from"fs/promises";import{join as nt}from"path";var La={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function An(o){return Ja("sha256").update(JSON.stringify(o)).digest("hex")}function Dr(o){return An(o)}function Jr(o,e,n){for(let t of e.projectionUpdates){let r=o.records.find(s=>s.recordType===t.entityType&&s.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Fa(o,e,n){return Jr(structuredClone(o),e,n)}async function bt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Mo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
177
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ba(n,o)}catch(r){throw await _o(n).catch(()=>{}),r}}async function Mn(o){return JSON.parse(await Ao(o,"utf8"))}var _n=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=nt(e,".popmelt","memory"),this.journalDir=nt(this.memoryDir,"journal"),this.manifestPath=nt(this.memoryDir,"manifest.json"),this.checkpointPath=nt(this.memoryDir,"checkpoint.json"),this.lockPath=nt(this.memoryDir,"writer.lock")}async initialize(e){let n=It(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Or(this.journalDir,{recursive:!0});try{throw await Ao(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await Ao(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}let t=An(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},s={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await bt(this.checkpointPath,r),await bt(this.manifestPath,s)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await bt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=An(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await bt(nt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await bt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Et(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,s={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},i={...s,hash:Dr(s)},d=Fa(t.bundle,e,n.committedAt),c=It(d);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await bt(nt(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await bt(this.manifestPath,t.manifest),{bundle:d,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:i.hash}}}))}async commitReviewPlan(e,n){return this.commit({...La,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Mn(this.manifestPath),n=await Mn(nt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==An(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Na(this.journalDir),r=t.filter(I=>I.endsWith(".tmp")),i=t.filter(I=>/^\d{12}-[0-9a-f-]+\.json$/i.test(I)).sort().filter(I=>Number(I.slice(0,12))>n.sequence),d=structuredClone(n.bundle),c=n.sequence,l=n.journalHash??null,h=new Set;for(let I of i){let b=await Mn(nt(this.journalDir,I)),{hash:g,...p}=b;if(g!==Dr(p))throw new Error(`Journal hash mismatch: ${I}`);if(b.sequence!==c+1)throw new Error(`Journal sequence gap at ${I}`);if(b.previousHash!==l)throw new Error(`Journal chain mismatch at ${I}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${I}`);if(h.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);Jr(d,b.mutation,b.committedAt),c=b.sequence,l=b.hash,h.add(b.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=It(d);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:d,manifest:e,transactionIds:h,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:c,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Or(this.memoryDir,{recursive:!0});let n;try{n=await Mo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Mn(this.lockPath).catch(()=>({})),s=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(i){s=i.code!=="ESRCH"}if(s)throw new Error("Memory journal is locked by another writer.");await _o(this.lockPath),n=await Mo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await _o(this.lockPath).catch(()=>{})}}};import{randomBytes as za}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=za(10).toString("hex"),r=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${r}${t.slice(4,7)}-${t.slice(7,19)}`}var Ua=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Nr(o,e){let n=o.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active"),t=o.records.find(x=>x.recordType==="participant"&&x.kind==="ai"&&x.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,s=`${e.threadId}:${e.jobId}`,i=new Date(e.createdAt).toISOString(),d=new Date(e.completedAt).toISOString(),c=Ua(),l=c.records,h=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));h||(h={id:ye(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(x=>x.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(h));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"element",label:x,aliases:[],locators:[{id:ye(r,"live-locator",x,e.createdAt),kind:"dom_selector",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}for(let x of[...new Set((e.filePaths??[]).filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.kind==="source_file"&&J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-file-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"file",label:x,aliases:[],locators:[{id:ye(r,"live-file-locator",x,e.createdAt),kind:"source_file",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}let I=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),b;if(I.length>0){b=ye(r,"live-observation",s,e.createdAt);let x={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:I.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds:R.map(S=>S.id),artifactIds:[]},resolvedByIds:[]};l.push(x)}let g=ye(r,"live-iteration",s,e.completedAt),p={id:g,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[h.id],startedAt:i,completedAt:d,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let y=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),v=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(I.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of I.entries()){let A=ye(r,"live-proposal",`${s}:${x}`,e.completedAt),J=v.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"iteration",id:g},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:S.claim.trim(),rationale:S.rationale?.trim()||void 0,proposedKind:S.proposedKind,subjects:J,subjectSemantics:J.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:S.sourceText?.trim()||e.requestSummary,iterationId:g,inferredById:t.id}};l.push(_),y.push(A)}if(f.length>0){let x=new Set(e.governingDecisionIds??[]),S=o.records.filter(J=>J.recordType==="decision"&&J.state==="active"&&x.has(J.id)),A={id:ye(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"iteration",id:g}],recordType:"implementation_attempt",state:"completed",iterationIds:[g],coverageClaims:S.map(J=>({decisionId:J.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(_=>_.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:g}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:c,iterationId:g,proposalIds:y,observationId:b}}import{createHash as qa}from"crypto";import{mkdir as Ha,open as Wa,readFile as Ga,rename as Va,unlink as Ka}from"fs/promises";import{join as Br}from"path";function Lr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Fr(o){return qa("sha256").update(JSON.stringify(o)).digest("hex")}async function Qa(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Wa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Va(n,o)}catch(r){throw await Ka(n).catch(()=>{}),r}}function Xa(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(c,l,h)=>{let R=c[l]??=[];R.includes(h)||R.push(h)};for(let c of o.records)if(c.recordType==="subject"){let l=c;for(let h of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Lr(h);R&&i(t,R,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)i(r,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)i(s,l.subjectId,c.id);let d={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...d,checksum:Fr(d)}}function zr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Lr(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var Cn=class{constructor(e){this.indexDir=Br(e,".popmelt","memory","indexes"),this.indexPath=Br(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Ga(this.indexPath,"utf8")),{checksum:s,...i}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&s===Fr(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Xa(e,n);return await Ha(this.indexDir,{recursive:!0}),await Qa(this.indexPath,t),t}};var $n=class{constructor(e){this.projectRoot=e;this.store=new _n(e),this.indexStore=new Cn(e),this.manifestPath=pt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await At(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Yt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Yt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=pt(this.projectRoot,".popmelt","memory","migrations"),n=pt(e,"legacy-evals-v1.json");try{let s=JSON.parse(await At(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await At(pt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await At(pt(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(s.runs)?s.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await Co(e,{recursive:!0}),await $o(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:r.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:r.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=pt(this.projectRoot,".popmelt","memory","migrations"),n=pt(e,"imprint-evidence-v1.json");try{let s=JSON.parse(await At(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await At(pt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Co(e,{recursive:!0}),await $o(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=0;for(let s of t.explanations){let i=s.evidence.length?s.evidence:[{id:s.id,kind:"observation",stance:"supports",summary:s.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:s.createdAt}];for(let d of i){let c=d.kind==="confirmation"?"confirm":d.kind==="correction"||d.kind==="rejection"?"reason_wrong":d.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:d.id,kind:c?"strengthened":"added",title:s.statement.slice(0,120),detail:d.summary,changes:[{explanationId:s.id,action:c==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:d.threadId,jobId:d.jobId,action:c,occurredAt:d.createdAt}),r+=1}}return await Co(e,{recursive:!0}),await $o(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:t.explanations.length,evidence:r,source:".popmelt/imprint (linked projection)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:r}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:ko(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:_r(t.bundle,r),reviewSelection:ko(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:En(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Yt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=En(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(I=>I.recordType==="proposal"&&I.id===e.proposalId),r=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),d={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},c=e.action==="accept"?{...d,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...d,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...d,action:"reject",eventId:le(s),reason:e.reason}:{...d,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(I=>I.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=En(n.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(I=>I.message).join(" ")};let h=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(h);let R=l.plan.resultRefs.find(I=>I.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:h.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Nr(n.bundle,e),r=ye(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let s=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(s),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:s.report.headSequence}}catch(s){if(s instanceof Error&&s.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw s}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n=await this.store.load(),t=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active"),r=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="ai"&&I.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(I=>I.recordType==="subject"&&I.subjectType==="project");if(!s||!i)return;let d=e.occurredAt??new Date().toISOString(),c=Date.parse(d),l=[],h=[];for(let I of e.summary.changes){let b={kind:"external",id:I.explanationId,uri:"popmelt:imprint"},g=n.bundle.records.find(y=>y.recordType==="observation"&&y.sourceRefs.some(f=>f.kind==="external"&&f.id===I.explanationId&&f.uri==="popmelt:imprint"));g||(g={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:I.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(g));let p={id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),h.push({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[b],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:g.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ye(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,c);try{let I=await this.store.commit({records:l,events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:d});await this.refreshIndex(I)}catch(I){if(!(I instanceof Error)||!I.message.includes("Transaction already exists"))throw I}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="model_projection"&&i.state==="applied"?i.coverage.filter(d=>d.status==="projected").map(d=>d.decisionId):[])),r=new Set(n.relationships.flatMap(i=>i.relationshipType==="contradicts"&&i.from.entityType==="decision"&&i.to.entityType==="decision"?[i.from.entityId,i.to.entityId]:[])),s=new Set(n.records.flatMap(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.target.entityType==="decision"?[i.target.entityId]:[]));return n.records.filter(i=>i.recordType==="decision"&&i.state==="active"&&!t.has(i.id)&&!r.has(i.id)&&!s.has(i.id)).sort((i,d)=>d.createdAt.localeCompare(i.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(s=>s.recordType==="model_entry").sort((s,i)=>s.createdAt.localeCompare(i.createdAt)))r.decisionIds.some(s=>n.has(s))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id]:[])),t=new Map;for(let d of e.records.filter(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))d.decisionIds.some(c=>n.has(c))&&t.set(d.key,d);let r=[...t.values()],s=e.records.filter(d=>d.recordType==="verification_attempt");return{decisions:e.records.filter(d=>d.recordType==="decision"&&d.state==="active").map(d=>{let c=s.filter(l=>l.targets.some(h=>h.entityType==="decision"&&h.entityId===d.id)).sort((l,h)=>h.createdAt.localeCompare(l.createdAt))[0];return{id:d.id,kind:d.kind,claim:d.claim,projected:r.some(l=>l.decisionIds.includes(d.id)),verification:c?c.state:"unverified"}}),entries:r.map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(d=>d.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),d=le(s),c=le(s),l=le(s),h=le(s),R=le(s),I=new Set(n.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),b=n.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&I.has(T.id)),g={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],y={...g,id:d,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...g,id:c,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:d},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...g,id:l,recordType:"decision",proposalId:d,acceptanceEventId:c,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...g,id:h,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...g,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${s}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:i,decisionIds:[l],entryIds:[h],coverage:[{decisionId:l,status:"projected"}]},A={...g,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=b.map(T=>({...g,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=b.map(T=>({...g,id:le(s),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),N=await this.store.commit({records:[y,v,x,S],events:[f,...J],relationships:[A,..._],artifacts:[],tombstones:[],projectionUpdates:b.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:h}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),s=n.bundle.records.flatMap(g=>g.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===g.id||g.sourceRefs.some(y=>y.id===p))?[g.id]:[]),i=[...new Set(n.bundle.records.flatMap(g=>g.recordType==="decision"&&s.includes(g.id)?g.subjects.map(p=>p.subjectId):[]))],c={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(c))continue;let l=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!l)throw new Error("No active local owner participant is available.");let h=Date.now(),R=new Date(h).toISOString(),I={id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(g=>({kind:"record",id:g}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...c,targets:s.map(g=>({entityType:"decision",entityId:g})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},b=r?[{id:le(h),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:I.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:I.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[I],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(h),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(i=>i.objectType==="eval_spec").map(i=>i.objectId)),t=e.records.filter(i=>i.recordType==="eval_spec").reverse().filter((i,d,c)=>c.findIndex(l=>l.legacyId===i.legacyId)===d).filter(i=>!n.has(i.id)),r=e.records.filter(i=>i.recordType==="verification_attempt"),s=e.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.targetKind==="verification_result");return t.map(i=>{let d=r.filter(h=>h.evalSpecId===i.id).sort((h,R)=>R.createdAt.localeCompare(h.createdAt))[0],c=d&&s.some(h=>h.target.entityType==="verification_attempt"&&h.target.entityId===d.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":d?c?"stale":d.state==="passed"?"passing":d.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:d?.scopeFingerprint,verificationAttemptId:d?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(d=>({assertion:d,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(I=>I.recordType==="verification_attempt"&&I.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(I=>I.recordType==="participant"&&I.status==="active"&&I.kind==="ai")??t.bundle.records.find(I=>I.recordType==="participant"&&I.status==="active");if(!s)return;let i=n.completedAt,d=new Date(i).toISOString(),c={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[c.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},h=r.targets.map(I=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:c.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:I,reason:n.summary})),R=await this.store.commit({records:[c,l],events:[],relationships:h,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),d={id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},c=await this.store.commit({records:[d],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(c)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id,...c.sourceRefs.map(l=>l.id)]:[])),r=e.filter(c=>(c.dependencies?.length??0)>0||c.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(c=>!r.includes(c)).map(c=>c.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(c=>c.recordType==="participant"&&c.kind==="human"&&c.status==="active");if(!i)return{valid:r,discardedIds:s};let d=s.flatMap(c=>{let l=this.latestEvalSpec(n.bundle,c);return l?[l]:[]}).filter(c=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===c.id));if(d.length>0){let c=Date.now(),l=new Date(c).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:d.map(h=>({id:le(c),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:h.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(c),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="model_projection"&&g.state==="applied"&&g.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(g=>g.recordType==="decision"&&e.decisionIds.includes(g.id)&&g.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let s=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),d=new Date(i).toISOString(),c=le(i),l=e.changes.map(g=>{let p=g.decisionIds?.filter(v=>e.decisionIds.includes(v)),y=p?.length?p:e.decisionIds,f=[...new Set(r.filter(v=>y.includes(v.id)).flatMap(v=>v.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:y.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:g.path.map(String).join("."),subjectIds:f,decisionIds:y,value:g.value}}),h=new Set(l.flatMap(g=>g.decisionIds)),R={id:c,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:e.decisionIds.map(g=>({kind:"record",id:g})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:d,decisionIds:e.decisionIds,entryIds:l.map(g=>g.id),coverage:e.decisionIds.map(g=>e.coverage?.find(p=>p.decisionId===g)??{decisionId:g,status:h.has(g)?"projected":"unprojected"})},I=l.flatMap(g=>g.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:d,participantId:s.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...l,R],events:[],relationships:I,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:d});return await this.refreshIndex(b),{projectionId:c,entryIds:l.map(g=>g.id),headSequence:b.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Yt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=zr(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Ct(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function _t(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Oo(o){let e=Ct(o),n=Ct(e.authority),t=n.level,r=n.mode,s=_t(t,"authority.level",["owner","delegate","contributor"]),i=_t(r,"authority.mode",["local_trusted","hosted"]),d={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...d,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...d,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let c=Ct(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...d,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>_t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...d,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=Ct(c);return{subjectId:Se(l.subjectId,"subjectId"),role:_t(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Do(o){let e=Ct(o),n=(s,i)=>{if(s!==void 0){if(!Array.isArray(s))throw new Error(`${i} must be an array.`);return s.map(d=>Se(d,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0:Ct(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function On(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
179
|
+
`)}async function Ur(o,e,n,t){let r=On(e);if(!(!r&&n.length===0))try{let s=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(s.actionPacket.decisions.length===0&&s.reviewSelection.packets.length===0)return;let i=new Map(s.actionPacket.implementation.map(c=>[c.decisionId,c.state])),d=new Map(s.actionPacket.verification.map(c=>[c.target.entityId,c.state]));return{source:s.source,...s.actionPacket.decisions.length>0?{acceptedTruth:{decisions:s.actionPacket.decisions.map(c=>({...c,implementation:i.get(c.id)??"unknown",verification:d.get(c.id)??"unverified"})),conflicts:s.actionPacket.conflicts,truncated:s.actionPacket.completeness.status==="truncated"}}:{},packets:s.reviewSelection.packets.map(c=>({packetId:c.packetId,proposalId:c.proposal.id,claim:c.proposal.claim,proposedKind:c.proposal.proposedKind,authority:c.authority,presentation:c.presentation,subjectLabels:c.trigger.subjectMatches.map(l=>l.label),evidenceCount:c.evidence.sourceCount,expansionRefs:c.expansionRefs})),truncated:s.reviewSelection.completeness.status==="truncated",estimatedTokens:s.actionPacket.budget.estimatedTokens+s.reviewSelection.completeness.estimatedTokens}}catch(s){t?.(s);return}}function qr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,r)=>["",`${r+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,r)=>["",`${r+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
180
|
+
`)}function Hr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!r||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let s=new Set(["different_action","new_evidence","new_conflict","owner_request"]),i=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(d=>typeof d=="string"&&s.has(d)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:i}}catch{return null}}function Wr(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!t||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:t,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function Dn(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],r=await Ya(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),d,c,l,h,R,I,b,g,p,y,f,v,x,S,A=[],J=[],_=0,N=[];for(;_<r.length;){let T=r.indexOf(s,_);if(T===-1)break;let B=T+s.length;if(r.slice(T,T+i.length).equals(i))break;let H=B;r[H]===13&&r[H+1]===10&&(H+=2);let ee=r.indexOf(`\r
|
|
181
181
|
\r
|
|
182
|
-
`,H);if(
|
|
182
|
+
`,H);if(ee===-1)break;let W=r.slice(H,ee).toString("utf-8"),te=ee+4,ne=r.indexOf(s,te),ge=ne!==-1?ne-2:r.length;N.push({headers:W,body:r.slice(te,ge)}),_=ne!==-1?ne:r.length}for(let T of N){let B=T.headers.match(/name="([^"]+)"/);if(!B)continue;let H=B[1];if(H==="screenshot")d=T.body;else if(H==="feedback")c=T.body.toString("utf-8");else if(H==="color")l=T.body.toString("utf-8");else if(H==="provider")h=T.body.toString("utf-8");else if(H==="model")R=T.body.toString("utf-8");else if(H==="reasoningEffort")I=T.body.toString("utf-8");else if(H==="serviceTier")b=T.body.toString("utf-8");else if(H==="goal")g=T.body.toString("utf-8");else if(H==="pageUrl")p=T.body.toString("utf-8");else if(H==="viewport")y=T.body.toString("utf-8");else if(H==="planId")f=T.body.toString("utf-8");else if(H==="manifest")v=T.body.toString("utf-8");else if(H==="tasks")x=T.body.toString("utf-8");else if(H==="sourceId")S=T.body.toString("utf-8");else if(H.startsWith("screenshot-")){let ee=H.slice(11);try{let W=decodeURIComponent(ee);J.push({pathname:W,data:T.body})}catch{}}else if(H.startsWith("image-")){let ee=H.split("-"),W=parseInt(ee[ee.length-1],10),te=ee.slice(1,-1).join("-");te&&!isNaN(W)&&A.push({annotationId:te,index:W,data:T.body})}}if(!d)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:d,feedback:c,color:l,provider:h,model:R,reasoningEffort:I,serviceTier:b,goal:g,pageUrl:p,viewport:y,planId:f,manifest:v,tasks:x,sourceId:S,pastedImages:A,pageScreenshots:J}}function Ya(o){return new Promise((e,n)=>{let t=[];o.on("data",r=>t.push(r)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as Za}from"crypto";var ec=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,tc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),nc=new Set(["strengthened","weakened","mixed","unknown"]);function Zt(o,e=180){if(typeof o!="string")return;let n=o.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function oc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Gr(o,e,n,t=Date.now()){let r=oc(o);if(!r)return null;let s=typeof r.transition=="string"&&tc.has(r.transition)?r.transition:null,i=Zt(r.focus);if(!s||!i)return null;let d=typeof r.evidencePosture=="string"&&nc.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Za(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Zt(r.seeking),workingHypothesis:Zt(r.workingHypothesis),evidencePosture:d,update:Zt(r.update),nextObservation:Zt(r.nextObservation)},contextPolicy:"exclude"}}function Jo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function rc(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(ec,(d,c)=>{try{let l=Gr(JSON.parse(c),e,s);if(!l)return"";let h=Jo(l);if(r.has(h))return"";r.add(h),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
|
|
183
183
|
|
|
184
|
-
`).trim(),orientations:t}}function
|
|
184
|
+
`).trim(),orientations:t}}function sc(o){let e="<orientation>",n=Math.min(o.length,e.length-1);for(let t=n;t>0;t--)if(e.startsWith(o.slice(-t)))return t;return 0}var Jn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let d=sc(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}n+=this.buffer.slice(0,r);let s=this.buffer.indexOf("</orientation>",r+13);if(s<0){this.buffer=this.buffer.slice(r);break}let i=this.buffer.slice(r+13,s).trim();this.buffer=this.buffer.slice(s+14);try{let d=Gr(JSON.parse(i),this.jobId,this.sequence);if(!d)continue;let c=Jo(d);if(this.signatures.has(c))continue;this.signatures.add(c),t.push(d),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=rc(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=Jo(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Vr=`## Public orientation updates
|
|
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
|
|
|
@@ -190,26 +190,27 @@ Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weak
|
|
|
190
190
|
|
|
191
191
|
These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function en(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(d=>{let c=[d.selector];return d.reactComponent&&c.push(`(${d.reactComponent})`),c.join(" ")}).join(", "),s=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${s} \u2192 Elements: ${r||"none"}`);let i=e?.[t.id];if(i&&i.length>0)for(let d of i)n.push(` Attached image: use the Read tool to view ${d}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let s of t.changes)n.push(`- ${t.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=JSON.stringify(t.original),i=JSON.stringify(t.modified),d=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${d}: ${s} \u2192 ${i}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",i=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${s} \u2192 ${t.targetParentSelector}${i}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
|
|
192
192
|
### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let r of t.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let t=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[t.selector];t.reactComponent&&r.push(`(${t.reactComponent})`),t.context&&r.push(`in ${t.context}`),t.textContent&&r.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
|
|
193
|
-
`)}function
|
|
194
|
-
`)}function
|
|
195
|
-
`)}function
|
|
196
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(
|
|
197
|
-
`));return Ln([...Bn,...c])}function Nn(o,e,n=5e3){return new Promise((t,r)=>{
|
|
198
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await yc(n,o)}catch(r){throw await vc(n).catch(()=>{}),r}}function Ic(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function bc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Oe(e):o.explanations.push(Oe(e))}function zn(o,e){let n=Oe(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(Oe(t.explanation))}else if(t.op==="replace_explanation")bc(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(Oe(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(Oe(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,Oe(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(Oe(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function xc(o,e){let n=[],t=Oe(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:Oe(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:Oe(s)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let s=r.op==="replace_explanation"?r.explanation.id:r.explanationId,i=t.explanations.find(d=>d.id===s);i&&n.unshift({op:"replace_explanation",explanation:Oe(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:Oe(s)})}t=zn(t,[r])}return n}function as(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 $t=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 ss(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 gc(this.journalDir).catch(d=>{if(d.code==="ENOENT")return[];throw d})).filter(d=>/^\d{12}-.+\.json$/.test(d)).sort(),r=Ic(this.projectId,e.createdAt),s=[],i=null;for(let d=0;d<t.length;d++){let c=JSON.parse(await ss(Ct(this.journalDir,t[d]),"utf8")),{hash:l,...h}=c;if(c.sequence!==d+1||c.previousHash!==i||l!==is(h))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);r=zn(r,c.mutations),r.updatedAt=c.committedAt,r.head={sequence:c.sequence,hash:c.hash},s.push(c),i=c.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=xc(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:Oe(e.mutations),inverseMutations:s,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},d={...i,hash:is(i)},c=zn(t.graph,d.mutations);c.updatedAt=e.committedAt,c.head={sequence:r,hash:d.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await rn(Ct(this.journalDir,l),d);let h={version:1,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await rn(this.graphPath,c),await rn(this.manifestPath,h),n={graph:c,transaction:d}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let d=new Set(i.mutations.flatMap(as));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(h=>as(h).some(R=>d.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await rn(this.graphPath,e.graph),await rn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Sc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Pc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Rc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function qn(o){return new Set(Rc(o).split(" ").filter(e=>e.length>2&&!Pc.has(e)))}function Un(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 No(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 nt(o,e,n){return{id:We(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function cs(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 kc(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Hn(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let w=String(r.reason);if(!Sc.has(w))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:w},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let s=r.summary,i=s?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(i)))throw new Error("summary.kind is invalid");let d={kind:i,title:je(s?.title,120),detail:je(s?.detail,500)};if(!d.title||!d.detail)throw new Error("summary title and detail are required");let c=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(w=>typeof w=="string"&&!!w.trim()):[],l=[];for(let w of Array.isArray(r.mutations)?r.mutations:[]){if(!w||typeof w!="object")continue;let b=w;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let g=je(b.statement),p=je(b.rationale);if(!g||!p)continue;l.push({op:"add",clientId:je(b.clientId,100)||void 0,kind:b.kind,statement:g,rationale:p,scope:cs(b.scope)})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let g={op:"revise",explanationId:b.explanationId,statement:je(b.statement)||void 0,rationale:je(b.rationale)||void 0,scope:cs(b.scope),reopenGrounding:b.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let g=je(b.summary);g&&l.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:g})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type)))l.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:je(b.rationale)});else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let g=je(b.reason);g&&l.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:g})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let g=je(b.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:g,rationale:je(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&l.push({op:"retire",explanationId:b.explanationId,reason:je(b.reason)})}let h=r.grounding,R=h&&typeof h.explanationId=="string"&&je(h.question)?{explanationId:h.explanationId,question:je(h.question,300)}:void 0;return{draft:{decision:"mutate",summary:d,appliedExplanationIds:c,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Wn(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(s=>` - Concrete terminal: ${s.modelPath} = ${JSON.stringify(s.value)}`)].join(`
|
|
193
|
+
`)}function Kr(o,e,n){let t=[],s=new Set(e.annotations.map(i=>i.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!s&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let i=0;for(let d of n.threadHistory)if(d.role==="human")i++,d.replyToQuestion?(t.push(`### Round ${i} (human) \u2014 reply`),t.push(`"${d.replyToQuestion}"`)):(t.push(`### Round ${i} (human)`),d.feedbackSummary&&t.push(`Annotations: ${d.feedbackSummary}`),d.annotationIds&&d.annotationIds.length>0&&t.push(`Annotation IDs: ${d.annotationIds.join(", ")}`));else if(d.question)t.push(`### Round ${i} (assistant) \u2014 question`),t.push(`"${d.question}"`);else{if(t.push(`### Round ${i} (assistant)`),d.responseText&&t.push(`Response: ${d.responseText}`),d.resolutions&&d.resolutions.length>0)for(let c of d.resolutions){let l=c.finalScope??c.inferredScope,h=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${c.annotationId}: ${c.status}${h} \u2014 ${c.summary}`),c.filesModified&&c.filesModified.length>0&&t.push(` Files: ${c.filesModified.join(", ")}`)}d.toolsUsed&&d.toolsUsed.length>0&&t.push(`Tools used: ${d.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0)if(t.push(""),t.push("Rules:"),i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"scope"in i[0]){let h=new Map;for(let R of i)if(typeof R=="object"&&R!==null&&"text"in R){let I=R,b=I.scope||"general";h.has(b)||h.set(b,[]),h.get(b).push(I.text)}for(let[R,I]of h){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let b of I)t.push(`- ${b}`)}}else for(let h of i)typeof h=="string"&&t.push(`- ${h}`);let d=n.designModel.tokens;d&&typeof d=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```"));let c=n.designModel.components;c&&typeof c=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),s){let i=n?.screenshotPaths??{},d=new Map;for(let c of e.annotations){let l=c.pathname||new URL(e.url).pathname;d.has(l)||d.set(l,[]),d.get(l).push(c)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,l]of d){t.push(""),t.push(`## Page: ${c}`);let h=i[c];h&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${h}`):!h&&n?.provider!=="codex"&&(Object.keys(i).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:l,styleModifications:e.styleModifications},I=en(R,n?.imagePaths);I&&(t.push(""),t.push(I))}}else{let i=en(e,n?.imagePaths);i&&(t.push(""),t.push(i))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
|
|
194
|
+
`)}function Qr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Xr(o,e,n,t){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let s=e.find(i=>i.role==="human"&&i.feedbackContext);if(s?.feedbackContext&&(r.push(""),r.push(s.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let i=0;for(let d of e)d.role==="human"?(i++,d.replyToQuestion?(r.push(`### Round ${i} (human) \u2014 reply`),r.push(`"${d.replyToQuestion}"`)):(r.push(`### Round ${i} (human)`),d.feedbackSummary&&r.push(`Annotations: ${d.feedbackSummary}`))):d.question?(r.push(`### Round ${i} (assistant) \u2014 question`),r.push(`"${d.question}"`)):(r.push(`### Round ${i} (assistant)`),d.responseText&&r.push(`Response: ${d.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let i of t)r.push(`Attached image: use the Read tool to view the image at: ${i}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
|
|
195
|
+
`)}function ic(o){if(typeof o!="object"||o===null)return!1;let e=o;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function ac(o){if(typeof o!="object"||o===null||typeof o.annotationId!="string"||o.status!=="resolved"&&o.status!=="needs_review"||typeof o.summary!="string")return!1;let e=o;for(let n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!ic(e[n]))return!1;return!0}function Yr(o){let e=o.match(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/);if(!e||!e[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(ac):[]}catch{return[]}}function Zr(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let r=t;return(r.category==="token"||r.category==="component"||r.category==="element")&&typeof r.element=="string"&&typeof r.decision=="string"&&typeof r.reason=="string"}):[]}catch{return[]}}import{execFile as cc}from"child_process";import{readdir as dc,readFile as lc,stat as pc}from"fs/promises";import{homedir as tn}from"os";import{join as Qe}from"path";var Bn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:es()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:es()}],nn=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],on={id:"",label:"Default",source:"cli"},uc=/^\s*-\s+"([^"]+)"/;function mc(o){let e=[],n=!1;for(let t of o.split(`
|
|
196
|
+
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(uc);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:No(s),source:"cli"})}return Ln([on,...e])}function fc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,r)=>{let s=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,i=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return s-i}).flatMap(t=>{let r=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!r)return[];let s=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():No(r),i=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,d=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:s,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...i&&i.length>0?{supportedReasoningLevels:i}:{},...d&&d.length>0?{speedTiers:d}:{}}]})}function es(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function hc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ln(e.map(n=>({id:n,label:No(n),source:"cli"})))}function No(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let s=t[1]==="sonnet"?"Sonn":wc(t[1]),i=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${s}${i}${t[4]?" Fast":""}`}let r=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let s=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${s}`:r[3]==="codex"?`Codex ${s}`:r[3]==="spark"?`Spark ${s}`:`GPT ${s}`}return n}async function ts(o="copilot"){let e=await Nn(o,["help","config"]),n=mc(e);return n.length>1?n:[on]}async function ns(o="codex"){let e=await Nn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(tn(),".codex");return rs(Qe(t,"models_cache.json"))}),n=fc(e);return n.length>0?Ln([...n,...nn]):nn}async function os(o="claude"){let e=Qe(tn(),".claude"),n=[Qe(tn(),".claude","stats-cache.json"),Qe(tn(),".claude","settings.json"),Qe(tn(),".claude.json"),Qe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Nn(o,["--help"]).catch(()=>""),Nn(o,["--version"]).catch(()=>""),gc(e).catch(()=>[])]),i=vc([...n,...s]),d=await Promise.all(i.map(l=>rs(l).catch(()=>""))),c=hc([t,r,...d].join(`
|
|
197
|
+
`));return Ln([...Bn,...c])}function Nn(o,e,n=5e3){return new Promise((t,r)=>{cc(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function rs(o){return lc(o,"utf-8")}async function gc(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await ss(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function ss(o,e,n){if(n<0)return;let t;try{t=await dc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Qe(o,r.name);if(r.isDirectory()){await ss(s,e,n-1);return}if(!(!r.isFile()||!yc(r.name)))try{let i=await pc(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function yc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Ln(o){let e=new Set,n=[];for(let t of o)e.has(t.id)||(e.add(t.id),n.push(t));return n}function vc(o){return[...new Set(o)]}function wc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Fn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let s=this.queue.length-1;s>=0;s--)if(this.queue[s]?.threadId===e.threadId){n=s;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let s of this.listeners)s(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},s=this.activeJobs.has(e);if(!t)return null;let i=n<0?t.events:t.events.filter(d=>d.seq>n);return{jobId:e,events:i,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:s}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let s=!1,i=()=>{s||(s=!0,r())};t.on("exit",i),t.on("error",i),setTimeout(()=>{if(!s){try{t.kill("SIGKILL")}catch{}setTimeout(i,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as We}from"crypto";import{createHash as Ic}from"crypto";import{mkdir as bc,open as xc,readFile as is,readdir as Sc,rename as Pc,unlink as Rc}from"fs/promises";import{dirname as kc,join as $t}from"path";function $e(o){return structuredClone(o)}function as(o){return Ic("sha256").update(JSON.stringify(o)).digest("hex")}async function rn(o,e){await bc(kc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await xc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
198
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Pc(n,o)}catch(r){throw await Rc(n).catch(()=>{}),r}}function Tc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function jc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=$e(e):o.explanations.push($e(e))}function zn(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")jc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(s=>s.id===t.evidence.id)||(r.evidence.push($e(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(s=>s.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,$e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(i=>i.id===t.relation.fromId),s=n.explanations.some(i=>i.id===t.relation.toId)||n.concrete.some(i=>i.id===t.relation.toId);if(!r||!s)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(i=>i.id===t.relation.id)||n.relations.push($e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Ec(o,e){let n=[],t=$e(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let s=t.explanations.find(i=>i.id===r.explanationId);s&&n.unshift({op:"add_explanation",explanation:$e(s)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let s=t.concrete.find(i=>i.id===r.concreteId);s&&n.unshift({op:"add_concrete",concrete:$e(s)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let s=r.op==="replace_explanation"?r.explanation.id:r.explanationId,i=t.explanations.find(d=>d.id===s);i&&n.unshift({op:"replace_explanation",explanation:$e(i)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let s=t.relations.find(i=>i.id===r.relationId);s&&n.unshift({op:"add_relation",relation:$e(s)})}t=zn(t,[r])}return n}function cs(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Ot=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=$t(e,".popmelt","imprint"),this.manifestPath=$t(this.imprintDir,"manifest.json"),this.graphPath=$t(this.imprintDir,"graph.json"),this.journalDir=$t(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await is(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async load(){let e=await this.readManifest(),t=(await Sc(this.journalDir).catch(d=>{if(d.code==="ENOENT")return[];throw d})).filter(d=>/^\d{12}-.+\.json$/.test(d)).sort(),r=Tc(this.projectId,e.createdAt),s=[],i=null;for(let d=0;d<t.length;d++){let c=JSON.parse(await is($t(this.journalDir,t[d]),"utf8")),{hash:l,...h}=c;if(c.sequence!==d+1||c.previousHash!==i||l!==as(h))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);r=zn(r,c.mutations),r.updatedAt=c.committedAt,r.head={sequence:c.sequence,hash:c.hash},s.push(c),i=c.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=Ec(t.graph,e.mutations),i={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:s,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},d={...i,hash:as(i)},c=zn(t.graph,d.mutations);c.updatedAt=e.committedAt,c.head={sequence:r,hash:d.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await rn($t(this.journalDir,l),d);let h={version:1,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await rn(this.graphPath,c),await rn(this.manifestPath,h),n={graph:c,transaction:d}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let d=new Set(i.mutations.flatMap(cs));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(h=>cs(h).some(R=>d.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await rn(this.graphPath,e.graph),await rn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Mc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ac=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function _c(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Un(o){return new Set(_c(o).split(" ").filter(e=>e.length>2&&!Ac.has(e)))}function qn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Bo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function ot(o,e,n){return{id:We(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function Ee(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function ds(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let n=e.values.filter(t=>typeof t=="string"&&!!t.trim());return n.length?{kind:e.kind,values:n}:void 0}function Cc(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Hn(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let I=String(r.reason);if(!Mc.has(I))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:I},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let s=r.summary,i=s?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(i)))throw new Error("summary.kind is invalid");let d={kind:i,title:Ee(s?.title,120),detail:Ee(s?.detail,500)};if(!d.title||!d.detail)throw new Error("summary title and detail are required");let c=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(I=>typeof I=="string"&&!!I.trim()):[],l=[];for(let I of Array.isArray(r.mutations)?r.mutations:[]){if(!I||typeof I!="object")continue;let b=I;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let g=Ee(b.statement),p=Ee(b.rationale);if(!g||!p)continue;l.push({op:"add",clientId:Ee(b.clientId,100)||void 0,kind:b.kind,statement:g,rationale:p,scope:ds(b.scope)})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let g={op:"revise",explanationId:b.explanationId,statement:Ee(b.statement)||void 0,rationale:Ee(b.rationale)||void 0,scope:ds(b.scope),reopenGrounding:b.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&l.push(g)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let g=Ee(b.summary);g&&l.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:g})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type)))l.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:Ee(b.rationale)});else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let g=Ee(b.reason);g&&l.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:g})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let g=Ee(b.modelPath,300);g&&l.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:g,rationale:Ee(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&l.push({op:"retire",explanationId:b.explanationId,reason:Ee(b.reason)})}let h=r.grounding,R=h&&typeof h.explanationId=="string"&&Ee(h.question)?{explanationId:h.explanationId,question:Ee(h.question,300)}:void 0;return{draft:{decision:"mutate",summary:d,appliedExplanationIds:c,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Wn(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(s=>` - Concrete terminal: ${s.modelPath} = ${JSON.stringify(s.value)}`)].join(`
|
|
199
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 Ot=class{constructor(e,n){this.noopCounts=new Map;this.store=new $t(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=qn(e.text??""),t=qn((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:s}=await this.store.load(),i=s.explanations.filter(c=>c.state!=="retired"&&c.state!=="challenged").map(c=>{let l=qn([c.statement,c.rationale].join(" ")),h=qn(c.scope.values.join(" ")),R=Un(l,n),w=Un(h,n),b=Un(h,t),g=Un(l,t),p=R+w*.2+b*.25+g*.1+(c.state==="grounded"?.08:0)+(r.has(c.id)?1:0),y=r.has(c.id)||(n.size?R>=.12||w>=.5:b>=.2||g>=.2);return{item:c,score:p,relevant:y}}).filter(c=>c.relevant&&c.score>=.18).sort((c,l)=>l.score-c.score||l.item.updatedAt.localeCompare(c.item.updatedAt)),d=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,d).map(({item:c})=>{let l=new Set(s.relations.filter(h=>h.fromId===c.id&&h.type==="instantiates").map(h=>h.toId));return{id:c.id,kind:c.kind,statement:c.statement,rationale:c.rationale,scope:c.scope,state:c.state,concrete:s.concrete.filter(h=>l.has(h.id)).map(h=>({id:h.id,modelPath:h.modelPath,value:h.value}))}}),truncated:i.length>d,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,d=new Map,c=[],l=new Set,h=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let _=We();S.clientId&&i.set(S.clientId,_);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,A={id:_,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:No(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[nt(n,"supports",e.summary.detail)]};s.set(_,A),l.add(_),c.push({op:"add_explanation",explanation:A})}let R=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let _=R(S.explanationId),J=s.get(_);if(J?.state!=="grounded")continue;let A=We(),N={id:A,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?No(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[nt(n,"supports",e.summary.detail)]};s.set(A,N),d.set(_,A),l.add(A),c.push({op:"add_explanation",explanation:N}),c.push({op:"add_relation",relation:{id:We(),type:"refines",fromId:A,toId:_,rationale:S.rationale??e.summary.detail,createdAt:t}})}let w=S=>{let _=R(S);return d.get(_)??_};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=w(S.explanationId);if(!s.has(J))continue;let A=kc(n.concreteModel,S.modelPath);if(!A.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(A.value));N||(N={id:We(),modelPath:S.modelPath,value:structuredClone(A.value),createdAt:t,updatedAt:t},c.push({op:"add_concrete",concrete:N})),c.push({op:"add_relation",relation:{id:We(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=w(S.fromId),A=w(S.toId);if(!s.has(J)||!s.has(A)||J===A)continue;c.push({op:"add_relation",relation:{id:We(),type:S.type,fromId:J,toId:A,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(A);continue}if(S.op==="supersede"){let J=w(S.explanationId),A=w(S.replacementId);if(!s.has(J)||!s.has(A)||J===A)continue;c.push({op:"add_evidence",explanationId:J,evidence:nt(n,"challenges",S.reason)}),c.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:A},updatedAt:t}),c.push({op:"add_relation",relation:{id:We(),type:"contradicts",fromId:A,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(A);continue}let _=w(S.explanationId);if(s.has(_))if(l.add(_),S.op==="revise"){if(d.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:No(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};c.push({op:"revise_explanation",explanationId:_,patch:J,updatedAt:t})}else S.op==="evidence"?(c.push({op:"add_evidence",explanationId:_,evidence:nt(n,S.stance,S.summary)}),S.stance==="challenges"&&c.push({op:"revise_explanation",explanationId:_,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(c.push({op:"add_evidence",explanationId:_,evidence:nt(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),c.push({op:"revise_explanation",explanationId:_,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let _=w(S),J=s.get(_);!J||J.state==="grounded"||J.state==="retired"||h.has(_)&&!l.has(_)||(l.has(_)||(l.add(_),c.push({op:"add_evidence",explanationId:_,evidence:{...nt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&c.push({op:"revise_explanation",explanationId:_,patch:{state:"testing"},updatedAt:t}))}if(!c.length)return;let b=We(),g=await this.store.commit({transactionId:b,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:c}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),y=[...l].flatMap(S=>{let _=p.get(S);if(!_)return[];let J=!r.graph.explanations.some(N=>N.id===S),A=_.state==="challenged"||_.state==="retired";return[{explanationId:S,action:J?"added":A?"challenged":"revised",statement:_.statement,state:_.state}]}),f=e.grounding?w(e.grounding.explanationId):void 0,v=f?p.get(f):void 0,x=v?.state==="testing"&&!h.has(v.id)?{explanationId:v.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:b,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:y,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let h of l)await this.store.undo(h,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,We());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},d=[],c="";if(e.action==="confirm")d.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),c=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")d.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),c=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(h=>h.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");d.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),c=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")d.push({op:"add_evidence",explanationId:t,evidence:{...nt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),c=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");d.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),c=`Edited: ${l}`}if(!d.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:We(),committedAt:n,source:i,summary:c,mutations:d})}};function sn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Gn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Bo(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 ds(o){let e=Bo(Gn(o.origin));if(e)return e;let n=Bo(Gn(o.referer));if(n)return n;let t=Gn(o["x-forwarded-host"]);if(!t)return null;let r=Gn(o["x-forwarded-proto"])==="https"?"https":"http";return Bo(`${r}://${t}`)}function ls(o,e,n=5){let t=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(c=>c.status==="applied"||c.status==="failed").sort(t).slice(0,n),i=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),d=i.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:d,actionableProposals:i}}import{createHash as Vn}from"crypto";import{mkdir as an,readFile as It,unlink as Ec,writeFile as Jt}from"fs/promises";import{dirname as Kn,extname as Mc,join as De}from"path";var Tc={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 jc(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 ps(o,e){let n=e??jc(o);return{kind:n,...Tc[n]}}function Dt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function us(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 _c={version:1,threads:{}},ms=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],cn={version:2,updatedAt:0,files:{}};function Ac(o){return JSON.stringify(o,null,2)}function Cc(o){return Object.fromEntries(ms.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function $c(o){let e={...o};for(let n of ms)delete e[n];return e}function Nt(o){let e=o;if(o.error){let n=ps(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 Qn=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 It(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(De(this.threadsDir,r));s&&(n[t]=s)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await It(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(Nt)}]))},this.index={...cn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={..._c,threads:{}},this.index={...cn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Nt(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,Nt(n)):r.messages.push(Nt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=s.messages.filter(d=>d.jobId===n);if(i.length===0)return!1;for(let d of i)if(Object.assign(d,t),d.error){let c=Nt(d);Object.assign(d,c),delete d.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(d=>d.role==="assistant"&&d.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",d=r.messages.filter(y=>y.role==="assistant"),c=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let f=y.imprintSummary?.grounding;if(f?.question&&!y.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(y=>!!c(y)),h=r.messages.findLastIndex(y=>y.role==="human"),R=l>h?c(r.messages[l]):void 0,w=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,h)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),g=d.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=d.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:w,pendingQuestion:R,acknowledgedJobIds:b,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await It(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...s})=>{let i={};if(r?.path)try{let d=await It(De(Kn(this.legacyFilePath),r.path),"utf8");Vn("sha256").update(d).digest("hex")===r.sha256&&(i=JSON.parse(d))}catch{}return Nt({...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=Cc(e),t=$c(e);if(Object.keys(n).length===0)return t;let r=Ac(n),s=Vn("sha256").update(r).digest("hex"),i=De("artifacts","thread-messages",`${s}.json`);await an(this.artifactsDir,{recursive:!0});try{await It(De(Kn(this.legacyFilePath),i),"utf8")}catch{await Jt(De(Kn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Kn(t)===this.mediaDir)return t;try{let r=await It(t),s=Vn("sha256").update(r).digest("hex"),i=De(this.mediaDir,`${s}${Mc(t)||".bin"}`);await an(this.mediaDir,{recursive:!0});try{await It(i)}catch{await Jt(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await an(this.threadsDir,{recursive:!0});let n=this.index??{...cn,files:{}},t=n.files[e.id]??`${Vn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(i=>this.encodeMessage(i))),s={...e,version:2,messages:r};await Jt(De(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Jt(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await an(this.threadsDir,{recursive:!0}),this.index=this.index??{...cn,files:{}},await Jt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...cn,files:{}},t=n.files[e];t&&await Ec(De(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await an(this.threadsDir,{recursive:!0}),await Jt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};function Xn(o){return Dc(o).slice(0,12)}var Oc=[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 Dc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Jc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let w=7;w>=0;w--)e.push(n/Math.pow(2,w*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,d=1359893119,c=2600822924,l=528734635,h=1541459225,R=new Array(64);for(let w=0;w<e.length;w+=64){for(let _=0;_<16;_++){let J=w+_*4;R[_]=(e[J]<<24|e[J+1]<<16|e[J+2]<<8|e[J+3])>>>0}for(let _=16;_<64;_++){let J=Xe(R[_-15],7)^Xe(R[_-15],18)^R[_-15]>>>3,A=Xe(R[_-2],17)^Xe(R[_-2],19)^R[_-2]>>>10;R[_]=R[_-16]+J+R[_-7]+A>>>0}let b=t,g=r,p=s,y=i,f=d,v=c,x=l,S=h;for(let _=0;_<64;_++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),A=f&v^~f&x,N=S+J+A+Oc[_]+R[_]>>>0,T=Xe(b,2)^Xe(b,13)^Xe(b,22),B=b&g^b&p^g&p,H=T+B>>>0;S=x,x=v,v=f,f=y+N>>>0,y=p,p=g,g=b,b=N+H>>>0}t=t+b>>>0,r=r+g>>>0,s=s+p>>>0,i=i+y>>>0,d=d+f>>>0,c=c+v>>>0,l=l+x>>>0,h=h+S>>>0}return[t,r,s,i,d,c,l,h].map(w=>w.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Jc(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 fs={name:"@popmelt.com/core",version:"0.8.5",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 ot=fs.version;var Vc=1111,Kc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Qc=1800*1e3,Xc=3600*1e3,ys=45e3,Yc=5e3,Zc=1e4;function vs(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(`
|
|
201
|
-
|
|
202
|
-
`)[
|
|
203
|
-
`)
|
|
200
|
+
`)}var Dt=class{constructor(e,n){this.noopCounts=new Map;this.store=new Ot(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Un(e.text??""),t=Un((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:s}=await this.store.load(),i=s.explanations.filter(c=>c.state!=="retired"&&c.state!=="challenged").map(c=>{let l=Un([c.statement,c.rationale].join(" ")),h=Un(c.scope.values.join(" ")),R=qn(l,n),I=qn(h,n),b=qn(h,t),g=qn(l,t),p=R+I*.2+b*.25+g*.1+(c.state==="grounded"?.08:0)+(r.has(c.id)?1:0),y=r.has(c.id)||(n.size?R>=.12||I>=.5:b>=.2||g>=.2);return{item:c,score:p,relevant:y}}).filter(c=>c.relevant&&c.score>=.18).sort((c,l)=>l.score-c.score||l.item.updatedAt.localeCompare(c.item.updatedAt)),d=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,d).map(({item:c})=>{let l=new Set(s.relations.filter(h=>h.fromId===c.id&&h.type==="instantiates").map(h=>h.toId));return{id:c.id,kind:c.kind,statement:c.statement,rationale:c.rationale,scope:c.scope,state:c.state,concrete:s.concrete.filter(h=>l.has(h.id)).map(h=>({id:h.id,modelPath:h.modelPath,value:h.value}))}}),truncated:i.length>d,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,d=new Map,c=[],l=new Set,h=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=We();S.clientId&&i.set(S.clientId,A);let J=S.clientId?e.appliedExplanationIds.includes(S.clientId):!1,_={id:A,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:Bo(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(A,_),l.add(A),c.push({op:"add_explanation",explanation:_})}let R=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let A=R(S.explanationId),J=s.get(A);if(J?.state!=="grounded")continue;let _=We(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?Bo(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};s.set(_,N),d.set(A,_),l.add(_),c.push({op:"add_explanation",explanation:N}),c.push({op:"add_relation",relation:{id:We(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let I=S=>{let A=R(S);return d.get(A)??A};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=I(S.explanationId);if(!s.has(J))continue;let _=Cc(n.concreteModel,S.modelPath);if(!_.found)continue;let N=r.graph.concrete.find(T=>T.modelPath===S.modelPath&&JSON.stringify(T.value)===JSON.stringify(_.value));N||(N={id:We(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},c.push({op:"add_concrete",concrete:N})),c.push({op:"add_relation",relation:{id:We(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=I(S.fromId),_=I(S.toId);if(!s.has(J)||!s.has(_)||J===_)continue;c.push({op:"add_relation",relation:{id:We(),type:S.type,fromId:J,toId:_,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(_);continue}if(S.op==="supersede"){let J=I(S.explanationId),_=I(S.replacementId);if(!s.has(J)||!s.has(_)||J===_)continue;c.push({op:"add_evidence",explanationId:J,evidence:ot(n,"challenges",S.reason)}),c.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:_},updatedAt:t}),c.push({op:"add_relation",relation:{id:We(),type:"contradicts",fromId:_,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(_);continue}let A=I(S.explanationId);if(s.has(A))if(l.add(A),S.op==="revise"){if(d.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:Bo(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};c.push({op:"revise_explanation",explanationId:A,patch:J,updatedAt:t})}else S.op==="evidence"?(c.push({op:"add_evidence",explanationId:A,evidence:ot(n,S.stance,S.summary)}),S.stance==="challenges"&&c.push({op:"revise_explanation",explanationId:A,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(c.push({op:"add_evidence",explanationId:A,evidence:ot(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),c.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let A=I(S),J=s.get(A);!J||J.state==="grounded"||J.state==="retired"||h.has(A)&&!l.has(A)||(l.has(A)||(l.add(A),c.push({op:"add_evidence",explanationId:A,evidence:{...ot(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&c.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!c.length)return;let b=We(),g=await this.store.commit({transactionId:b,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:c}),p=new Map(g.graph.explanations.map(S=>[S.id,S])),y=[...l].flatMap(S=>{let A=p.get(S);if(!A)return[];let J=!r.graph.explanations.some(N=>N.id===S),_=A.state==="challenged"||A.state==="retired";return[{explanationId:S,action:J?"added":_?"challenged":"revised",statement:A.statement,state:A.state}]}),f=e.grounding?I(e.grounding.explanationId):void 0,v=f?p.get(f):void 0,x=v?.state==="testing"&&!h.has(v.id)?{explanationId:v.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:b,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:y,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let h of l)await this.store.undo(h,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,We());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},d=[],c="";if(e.action==="confirm")d.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),c=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")d.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),d.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),c=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(h=>h.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");d.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),c=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")d.push({op:"add_evidence",explanationId:t,evidence:{...ot(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),c=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");d.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),c=`Edited: ${l}`}if(!d.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:We(),committedAt:n,source:i,summary:c,mutations:d})}};function sn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Gn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Lo(o){if(!o)return null;try{let e=new URL(o);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function ls(o){let e=Lo(Gn(o.origin));if(e)return e;let n=Lo(Gn(o.referer));if(n)return n;let t=Gn(o["x-forwarded-host"]);if(!t)return null;let r=Gn(o["x-forwarded-proto"])==="https"?"https":"http";return Lo(`${r}://${t}`)}function ps(o,e,n=5){let t=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(c=>c.status==="applied"||c.status==="failed").sort(t).slice(0,n),i=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),d=i.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:d,actionableProposals:i}}import{createHash as Vn}from"crypto";import{mkdir as an,readFile as xt,unlink as Dc,writeFile as Nt}from"fs/promises";import{dirname as Kn,extname as Jc,join as Oe}from"path";var $c={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function Oc(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function us(o,e){let n=e??Oc(o);return{kind:n,...$c[n]}}function Jt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ms(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Nc={version:1,threads:{}},fs=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],cn={version:2,updatedAt:0,files:{}};function Bc(o){return JSON.stringify(o,null,2)}function Lc(o){return Object.fromEntries(fs.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Fc(o){let e={...o};for(let n of fs)delete e[n];return e}function Bt(o){let e=o;if(o.error){let n=us(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=Jt(e.result,!1),t=Jt(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Qn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Oe(e,".popmelt");this.legacyFilePath=Oe(n,"threads.json"),this.threadsDir=Oe(n,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(n,"artifacts","thread-messages"),this.mediaDir=Oe(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await xt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let s=await this.readThread(Oe(this.threadsDir,r));s&&(n[t]=s)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await xt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Bt)}]))},this.index={...cn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Nc,threads:{}},this.index={...cn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(i=>t.has(i)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Bt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=r.messages.findIndex(i=>i.role==="human"&&!!i.replyToQuestion&&i.queued);s>=0?r.messages.splice(s,0,Bt(n)):r.messages.push(Bt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=s.messages.filter(d=>d.jobId===n);if(i.length===0)return!1;for(let d of i)if(Object.assign(d,t),d.error){let c=Bt(d);Object.assign(d,c),delete d.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(d=>d.role==="assistant"&&d.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",d=r.messages.filter(y=>y.role==="assistant"),c=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let f=y.imprintSummary?.grounding;if(f?.question&&!y.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(y=>!!c(y)),h=r.messages.findLastIndex(y=>y.role==="human"),R=l>h?c(r.messages[l]):void 0,I=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,h)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),g=d.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=d.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:g,hasError:p,lastMessageRole:I,pendingQuestion:R,acknowledgedJobIds:b,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await xt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...s})=>{let i={};if(r?.path)try{let d=await xt(Oe(Kn(this.legacyFilePath),r.path),"utf8");Vn("sha256").update(d).digest("hex")===r.sha256&&(i=JSON.parse(d))}catch{}return Bt({...s,...i})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Lc(e),t=Fc(e);if(Object.keys(n).length===0)return t;let r=Bc(n),s=Vn("sha256").update(r).digest("hex"),i=Oe("artifacts","thread-messages",`${s}.json`);await an(this.artifactsDir,{recursive:!0});try{await xt(Oe(Kn(this.legacyFilePath),i),"utf8")}catch{await Nt(Oe(Kn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Kn(t)===this.mediaDir)return t;try{let r=await xt(t),s=Vn("sha256").update(r).digest("hex"),i=Oe(this.mediaDir,`${s}${Jc(t)||".bin"}`);await an(this.mediaDir,{recursive:!0});try{await xt(i)}catch{await Nt(i,r)}return i}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await an(this.threadsDir,{recursive:!0});let n=this.index??{...cn,files:{}},t=n.files[e.id]??`${Vn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(i=>this.encodeMessage(i))),s={...e,version:2,messages:r};await Nt(Oe(this.threadsDir,t),JSON.stringify(s,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Nt(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await an(this.threadsDir,{recursive:!0}),this.index=this.index??{...cn,files:{}},await Nt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...cn,files:{}},t=n.files[e];t&&await Dc(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await an(this.threadsDir,{recursive:!0}),await Nt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as zc,open as Uc,readFile as qc,rename as Hc,unlink as Wc}from"fs/promises";import{dirname as Gc,join as Vc}from"path";var hs={schemaVersion:1,theme:"auto",updatedAt:null};function gs(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Kc(o,e){await zc(Gc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Uc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
201
|
+
`,"utf8"),await t.sync()}finally{await t.close()}await Hc(n,o)}catch(t){throw await Wc(n).catch(()=>{}),t}}var Xn=class{constructor(e){this.path=Vc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await qc(this.path,"utf8")),n=gs(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...hs}}}catch{return{exists:!1,preferences:{...hs}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Kc(this.path,n),n}};function ys(o){return gs(o)!==null}function Yn(o){return Xc(o).slice(0,12)}var Qc=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Xc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Yc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let I=7;I>=0;I--)e.push(n/Math.pow(2,I*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,d=1359893119,c=2600822924,l=528734635,h=1541459225,R=new Array(64);for(let I=0;I<e.length;I+=64){for(let A=0;A<16;A++){let J=I+A*4;R[A]=(e[J]<<24|e[J+1]<<16|e[J+2]<<8|e[J+3])>>>0}for(let A=16;A<64;A++){let J=Xe(R[A-15],7)^Xe(R[A-15],18)^R[A-15]>>>3,_=Xe(R[A-2],17)^Xe(R[A-2],19)^R[A-2]>>>10;R[A]=R[A-16]+J+R[A-7]+_>>>0}let b=t,g=r,p=s,y=i,f=d,v=c,x=l,S=h;for(let A=0;A<64;A++){let J=Xe(f,6)^Xe(f,11)^Xe(f,25),_=f&v^~f&x,N=S+J+_+Qc[A]+R[A]>>>0,T=Xe(b,2)^Xe(b,13)^Xe(b,22),B=b&g^b&p^g&p,H=T+B>>>0;S=x,x=v,v=f,f=y+N>>>0,y=p,p=g,g=b,b=N+H>>>0}t=t+b>>>0,r=r+g>>>0,s=s+p>>>0,i=i+y>>>0,d=d+f>>>0,c=c+v>>>0,l=l+x>>>0,h=h+S>>>0}return[t,r,s,i,d,c,l,h].map(I=>I.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Yc(o){let e=[];for(let n=0;n<o.length;n++){let t=o.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var vs={name:"@popmelt.com/core",version:"0.8.6",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.4.39"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var rt=vs.version;var dd=1111,ld=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],pd=1800*1e3,ud=3600*1e3,bs=45e3,md=5e3,fd=1e4;function xs(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
202
|
+
`)}function eo(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function hd(o,e){if(e.size===1)return[...o].reverse().find(n=>{let t=n.imprintSummary;return n.role==="assistant"&&!!t?.grounding&&!t?.resolvedAction&&e.has(t.grounding.explanationId)})}function Es(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function gd(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let s=n[n.length-1];s&&s.kind==="text"?s.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",s=t.file??void 0,i=t.content??void 0,d=s?s.split("/").pop()??s:void 0,c;switch(r){case"Read":c=d?`Reading ${d}`:"Reading file";break;case"Edit":c=d?`Editing ${d}`:"Editing file";break;case"Write":c=d?`Writing ${d}`:"Writing file";break;case"Bash":c=i?i.split(`
|
|
203
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=r?`Using ${r}`:"tool";break}let l=s??i??void 0,h=s?zo(s)?s:js(e,s):void 0,R=n[n.length-1];R&&R.kind==="tool_group"&&R.tool===r?R.items.push({label:c,detail:l,...h?{filePath:h}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:c,detail:l,...h?{filePath:h}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function yd(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let n=[];return o.success?n.push("Model suggestion ready."):n.push("Model projection failed."),o.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(n.push(""),n.push(`Error: ${o.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
|
|
204
|
+
`)}function vd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Ss(o){let e=o.styleModifications.flatMap(i=>{let d=i.element?.reactComponent||i.element?.tagName||i.selector;return i.changes.map(c=>`${d}: ${c.property} ${c.original||"unset"} -> ${c.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(i=>`${i.tokenName}: ${i.originalPx}px -> ${i.newPx}px`),t=(o.textModifications??[]).map(i=>`${i.element?.reactComponent||i.element?.tagName||i.selector}: text ${i.original||"empty"} -> ${i.modified||"empty"}`),r=o.annotations.map(i=>{let d=i.instruction?.trim();if(d)return d;if(i.imageCount&&i.imageCount>0)return`${i.imageCount} image${i.imageCount===1?"":"s"}`;let c=i.elements?.[0]?.reactComponent||i.elements?.[0]?.selector||i.linkedSelector||i.type;return`${i.type==="annotation"?"Annotation":`${i.type} annotation`} on ${c}`}),s=[...e,...t,...n,...r].map(i=>vd(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function wd(o,e){let n=o.headers.origin;Es(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function E(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function ze(o){let e=[],n=0;for await(let r of o){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>16384)throw new Error("Request body too large");e.push(s)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Id(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function bd(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,r,s]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(r,16)};${parseInt(s,16)}m${e}\x1B[0m`}function to(o,e){try{o.res.write(`event: ${e.type}
|
|
204
205
|
data: ${JSON.stringify(e)}
|
|
205
206
|
|
|
206
|
-
`)}catch{}}function
|
|
207
|
+
`)}catch{}}function St(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function oo(o){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function xd(o,e){return new Promise((n,t)=>{let r=i=>{o.removeListener("listening",s),t(i)},s=()=>{o.removeListener("error",r),n()};o.once("error",r),o.once("listening",s),o.listen(e,"127.0.0.1")})}function Ps(o){try{let e=no("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=no("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=no("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Ts("sha256").update(`${e}
|
|
207
208
|
${t}
|
|
208
|
-
${r}`).digest("hex").slice(0,16)}catch{return}}function
|
|
209
|
+
${r}`).digest("hex").slice(0,16)}catch{return}}function Sd(o,e){let n=o;for(let t of e.split(".").filter(Boolean)){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[t]}return n}async function Rs(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let s of[...t].sort((i,d)=>`${i.kind}:${i.value}`.localeCompare(`${d.kind}:${d.value}`)))if(s.kind==="model_path")r.push([s.kind,s.value,Sd(n,s.value)]);else if(s.kind==="source_file"){let i=js(o,s.value),c=i===o||i.startsWith(`${o}/`)?await Fo(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,c])}else r.push([s.kind,s.value]);return Ts("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ms(o={}){let e=new Date().toISOString(),n=o.port??dd,t=o.projectRoot??process.cwd(),r=await nd(t).catch(()=>t),s=Yn(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=o.tempDir??Me(id(),"popmelt-bridge"),c=o.maxTurns??40,l=o.maxBudgetUsd??1,h=[...o.allowedTools??ld],R=o.claudePath??"claude",I=o.copilotPath??"copilot",b=o.provider??"claude",g=o.timeoutMs,p=o.restartMode??"embedded",y=n,f={},v={claude:R,codex:"codex",copilot:I};for(let[a,u]of Object.entries(v))try{let k=u.includes("/")?u:no("which",[u],{encoding:"utf-8"}).trim();f[a]={available:!0,path:k}}catch{f[a]={available:!1,path:null}}function x(a,u){return new Promise(k=>{let m=ws(u,["--version"],{stdio:["ignore","ignore","ignore"]}),P=!1,w=$=>{P||(P=!0,k($))},j=setTimeout(()=>{m.kill("SIGTERM"),w(!0)},5e3);m.on("error",()=>{clearTimeout(j),w(!1)}),m.on("close",$=>{clearTimeout(j),w($===0)})})}await Promise.all([(async()=>{f.claude&&(f.claude.models=f.claude.available&&f.claude.path?await os(f.claude.path).catch(()=>Bn):Bn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await ns(f.codex.path).catch(()=>nn):nn)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await ts(f.copilot.path).catch(()=>[on]):[on])})()]);let[S,A,J]=await Promise.all([Io(r),bo(r),xo(r,f.copilot?.path??I)]),_=await br(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=A),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&h.push(`mcp__${S.name}__*`),await ed(d,{recursive:!0}),ks(d).catch(()=>{});let N=new Fn(1),T=new Sn,B=new kn(bs),H=null,ee=0,W=!1,te=()=>{ee+=1,W=!1,H&&clearTimeout(H),H=null},ne=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ge=()=>{if(p!=="detached"||B.size>0||W)return;W=!0;let a=++ee,u=Date.now()+fd,k=()=>{if(a!==ee)return;if(B.size>0){te();return}if(!(N.isRunning||N.depth>0||T.isRunning||T.depth>0)||Date.now()>=u){W=!1,H=setTimeout(ne,50),H.unref?.();return}H=setTimeout(k,250),H.unref?.()};k()},X=new Set,G=new Qn(r),U=new $n(r),he=new Dt(r,s),M=new Xn(r),Y=new gn(r),ue=new wn(r),ie=new xn(r,{claudePath:R,provider:b,timeoutMs:g,loadProjectableDecisions:a=>U.getProjectableDecisions(a),onEvent:a=>{for(let u of X)to(u,a)}});U.beginAutomaticInitialization({writerVersion:rt}).then(async a=>{a.state==="ready"?(await U.migrateLegacyEvals(),await U.migrateImprintSnapshot(),await ie.applyCanonicalEntries(await U.getCanonicalModelEntries()),b!=="copilot"&&(await ie.getUnprojectedPatternDecisions()).length>0&&await je({provider:b,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let De=20,Je=300*1e3,Pe=[];function Ue(){let a=Date.now()-Je;for(;Pe.length>0&&(Pe[0].completedAt<a||Pe.length>De);)Pe.shift()}let Ge=new Map;async function Ye(a){if(a.status!=="applied")return[];let u={version:1,updatedAt:Date.now(),cases:await U.getJournalEvalCases()},k=dr(a,u);if(k.length===0)return[];let m=await U.getEvalDependenciesForDecisions(a.decisionIds),P=a.threadId?await G.getThread(a.threadId):null,w=[...new Set((P?.messages??[]).flatMap(D=>(D.editEvents??[]).flatMap(F=>F.filePath?[F.filePath]:[])).map(D=>zo(D)?Is(r,D):D))].map(D=>({kind:"source_file",value:D})),j=k.map(D=>{let F=[...new Map([...D.dependencies??[],...m,...w].map(q=>[`${q.kind}:${q.value}:${"subjectId"in q?q.subjectId??"":""}`,q])).values()],L=F.filter(q=>q.kind==="route"),C=F.flatMap(q=>q.kind==="model_path"&&q.value.startsWith("components.")?[q.value.slice(11).split(".")[0]]:[]),O=[...new Set(F.flatMap(q=>"subjectId"in q&&q.subjectId?[q.subjectId]:[]))],K=L.length>0?L.map((q,se)=>({id:`route-${se+1}`,...q.value.includes("*")?{routePattern:q.value}:{route:q.value},components:C.map(ae=>({name:ae})),subjectIds:O})):[{id:C.length>0?`component-${C[0]}`:"current-page",components:C.map(q=>({name:q})),subjectIds:O}];return{...D,dependencies:F,scenarios:D.scenarios?.length?D.scenarios:K}}),$=new Set(u.cases.map(D=>D.id));return await U.syncEvalSpecs(j),await ie.attachGeneratedEvals(a.id,j.map(D=>({evalId:D.id,title:D.title,action:$.has(D.id)&&(a.evalProjections?.some(F=>F.evalId===D.id)||!a.generatedEvalIds?.includes(D.id))?"extended":"created"}))),j.map(D=>D.id)}async function st(a){let u=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",k=uo(a.claim)||"The product satisfies the declared model constraint.",m={id:`eval-decision-${a.decisionId}`,title:u.charAt(0).toUpperCase()+u.slice(1),status:"pending",category:a.modelPath.startsWith("components.")?"component":a.modelPath.startsWith("tokens.")?"visual":"workflow",prompt:"Verify this product expectation across the declared scenarios.",assertions:[k],rationale:`Protects the ${a.modelPath} constraint from implementation drift.`,sourceDecisionIds:[a.decisionId],sourceThreadIds:[],dependencies:[{kind:"model_path",value:a.modelPath}],scenarios:[{id:a.modelPath.startsWith("components.")?`component-${u.replace(/\s+/g,"-")}`:"current-page",components:a.modelPath.startsWith("components.")?[{name:a.modelPath.slice(11).split(".")[0]}]:void 0}]};return await U.syncEvalSpecs([m]),m.id}let mt=null,Lt;N.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&to(m,a)}),T.addListener((a,u,k)=>{for(let m of X)(!k||!m.sourceId||m.sourceId===k)&&to(m,a)}),T.setProcessor(async a=>{let u=a.provider??b;try{let k=await ie.run({provider:u,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let m=await ie.loadRuns(),P=k.runId?m.runs.find(j=>j.id===k.runId):void 0;if(k.success&&k.proposalId){let j=await ie.findModelProposal(k.proposalId),$=await ie.loadModel(),D=j?gr(j,$):null;if(j&&D){let F=j.decisionIds.map(C=>({decisionId:C,status:"projected"}));await U.applyModelProjection({runId:j.runId??j.id,presentationJobId:j.presentationJobId,decisionIds:j.decisionIds,changes:D.map(C=>({path:C.path,value:C.value,decisionIds:C.decisionIds})),coverage:F});let L=await ie.applySelectedModelProposal(j.id,D.map(C=>({path:C.path,value:C.value})),D.map(C=>({group:C.path[0]==="rules"||C.path[0]==="components"||C.path[0]==="tokens"?C.path[0]:"model",label:C.label??C.id,detail:C.rationale,path:C.path,value:C.value})),"automatic");L&&await Ye(L)}}let w=yd(k,P);if(a.threadId&&(await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,model:a.model,provider:u})),k.success)a.status="done",a.result=w,T.broadcast({type:"done",jobId:a.id,success:!0,responseText:w,threadId:a.threadId},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue();else{if(a.status="error",a.error=k.error??"Projection failed",a.threadId){let j=`Model projection failed.
|
|
209
210
|
|
|
210
|
-
${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),
|
|
211
|
+
${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:j,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}catch(k){if(a.status==="cancelled")return;if(a.status="error",a.error=k instanceof Error?k.message:String(k),a.threadId){let m=`Model projection failed.
|
|
211
212
|
|
|
212
|
-
${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),
|
|
213
|
+
${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})||await G.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:m,error:a.error,model:a.model,provider:u})}T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:u,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue()}}),N.setProcessor(async a=>{let u=a,k=u._replyPrompt,m=u._replyText,P=u._replyImagePaths,w=a.provider??b,j=!!(a.surfacedProposalIds?.length&&k),$=!!u._evalRemediation,D=!j&&!["run_eval","synthesize_evals","synthesize","project_model"].includes(a.kind??"");a.threadId&&m!==void 0&&await G.updateMessage(a.threadId,a.id,{queued:!1});let F;if(a.threadId){let de=await G.getThread(a.threadId);if(de){for(let pe=de.messages.length-1;pe>=0;pe--)if(de.messages[pe].sessionId){F=de.messages[pe].sessionId;break}}}(j||$)&&(F=void 0);let L;if(F&&k){if(L=m??k,P&&P.length>0){L+=`
|
|
213
214
|
|
|
214
215
|
The developer attached reference images with their reply:`;for(let de of P)L+=`
|
|
215
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+=`
|
|
@@ -220,22 +221,22 @@ After completing work, output a <resolution> block with declaredScope and inferr
|
|
|
220
221
|
|
|
221
222
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
222
223
|
|
|
223
|
-
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.`+(w!=="codex"?`
|
|
224
225
|
|
|
225
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!k&&a.threadId?await G.getThreadHistory(a.threadId):void 0,pe=k?null:await
|
|
226
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!k&&a.threadId?await G.getThreadHistory(a.threadId):void 0,pe=k?null:await ie.loadModel();L=k??Kr(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:w,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}L+=qr(a.memoryReview),D&&(L+=Wn(a.imprintContext)),L+=`
|
|
226
227
|
|
|
227
|
-
${Gr}`;let C=id(a.color,`[\u22B9 ${y}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${C} Reviewing ${O} (provider: ${I})${a.threadId?` (thread: ${a.threadId})`:""}${F?` (resuming: ${F.slice(0,8)})`:""}`);let Q=new Jn(a.id),U=(de,pe)=>{if(de.type==="delta"&&"text"in de){let Ce=Q.push(de.text);Ce.visibleText&&(N.accumulateText(pe,"response",Ce.visibleText),N.broadcast({...de,text:Ce.visibleText},pe,a.sourceId));for(let $e of Ce.orientations)N.broadcast({type:"orientation",jobId:pe,orientation:$e},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&N.accumulateText(pe,"thinking",de.text);N.broadcast(de,pe,a.sourceId)},{process:ie,result:ae}=I==="codex"?hn(a.id,{prompt:L,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:F,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:un(a.agentSettings),onEvent:U}):I==="copilot"?sr(a.id,{prompt:L,projectRoot:r,resumeSessionId:F,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??w,onEvent:U}):mn(a.id,{prompt:L,projectRoot:r,maxTurns:c,maxBudgetUsd:l,allowedTools:j?["Read"]:h,claudePath:R,resumeSessionId:F,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:g,onEvent:U});N.setActiveProcess(a.id,ie);let re=await ae,be=Q.finalize(re.text),ye=be.visibleText,K=D?Hn(ye):{visibleText:ye,draft:void 0,error:void 0},we=K.visibleText;for(let de of be.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=we,re.success){console.log(`${C} Iteration complete`),re.fileEdits&&re.fileEdits.length>0&&console.log(`${C} Captured ${re.fileEdits.length} file edit(s): ${re.fileEdits.map(z=>`${z.tool} ${z.file_path}`).join(", ")}`),re.editEvents&&re.editEvents.length>0&&console.log(`${C} Captured ${re.editEvents.length} edit event(s): ${re.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Kr(ye),pe=Xr(ye);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 Ce=re.fileEdits&&re.fileEdits.length>0?re.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):re.toolsUsed,$e=N.getBufferedEvents(a.id),Ze=$e?td($e.events,r):void 0,Pe,ee=Hr(ye),me=Ur(ye);if(me)if(!(a.memoryReview?.packets.some(se=>se.proposalId===me.proposalId)||a.surfacedProposalIds?.includes(me.proposalId)))Pe={status:"rejected",action:me.action,proposalId:me.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Pe=await q.commitConversationalReview(me)}catch(se){Pe={status:"rejected",action:me.action,proposalId:me.proposalId,message:se instanceof Error?se.message:String(se)}}let Re=[...(re.fileEdits??[]).map(z=>z.file_path),...(re.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],xe,ft=a.imprintContext?.pendingGroundingExplanationIds??[];if(K.draft?.decision==="none"&&fe.recordNoop(K.draft.reason),a.threadId&&K.draft?.decision==="mutate"&&!me&&!ee)try{xe=await fe.capture(K.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await V.loadModel(),pendingGroundingExplanationIds:ft}),xe&&await q.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 K.error&&console.warn(`${C} Ignored invalid imprint block: ${K.error}`);let Ue=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let z=await G.getThread(a.threadId),se=new Set(xe.changes.map(Ke=>Ke.explanationId)),Ve=z?ed(z.messages,se):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 qt=us({question:de,resolutions:pe,changedFiles:Re,decisionRequired:!!ee,imprintTransactionId:Ue,groundingRequired:!!xe?.grounding}),X=Ze?.flatMap(z=>z.kind==="orientation"?[z.orientation]:[])??[];if(a.threadId){let z=j?ee?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":we;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:re.sessionId,toolsUsed:j?void 0:Ce,editEvents:!j&&re.editEvents&&re.editEvents.length>0?re.editEvents:void 0,segments:!j&&Ze&&Ze.length>0?Ze:void 0,turn:{phase:"complete",orientation:X,result:qt},result:qt,memoryReviewCard:ee??void 0,memoryReceipt:Pe,imprintSummary:xe,model:a.model,provider:I})}if(a.threadId&&!me&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let z=a.feedback.annotations.flatMap(se=>se.linkedSelector?[se.pathname?`${se.pathname}:${se.linkedSelector}`:se.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:m??(On(a.feedback)||"[request unavailable]"),responseSummary:de??we,outcome:de?"question_asked":pe.some(se=>se.status==="resolved")?"completed":"no_change",execution:{provider:I,model:a.model,sessionId:re.sessionId},subjectHints:z,filePaths:[...(re.fileEdits??[]).map(se=>se.file_path),...(re.editEvents??[]).flatMap(se=>se.filePath?[se.filePath]:[])].map(se=>Fo(se)?gs(r,se):se),resolutions:pe.map(se=>({status:se.status,summary:se.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(se=>se.id)})}catch(se){console.warn(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,se instanceof Error?se.message:String(se))}}if(Pe?.status==="committed"&&Pe.decisionId&&I!=="copilot"&&await Ft({provider:I,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Pe.decisionId}`}),a.kind==="run_eval"&&we&&a.evalId&&a.evalRunId){let z=await q.findJournalEvalCase(a.evalId),se=a._evalRunScope;if(z&&se){let Ve=ar(ye,z.assertions),Ke=Date.now(),Fs={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:se,provider:I,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:Is(r),rawResponse:ye,scopeFingerprint:a._evalScopeFingerprint,...Ve};await q.recordEvalVerification(z,Fs),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 ${Y.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 ue=Yr(ye);ue.length>0&&(console.log(`${C} Novel pattern(s): ${ue.map(z=>`${z.category}/${z.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:a.id,patterns:ue,threadId:a.threadId},a.id,a.sourceId)),N.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:we,threadId:a.threadId,annotationIds:a.annotationIds,result:qt},a.id,a.sourceId),Ie.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${C} Error: ${re.error}`),a.status="error",a.error=re.error,a.threadId&&await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:re.error||"Unknown error",model:a.model,provider:I}),N.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:re.error||"Unknown error",provider:I,model:a.model,recoverable:re.recoverableError,code:re.errorCode},a.id,a.sourceId),Ie.push({id:a.id,status:"error",completedAt:Date.now(),error:re.error,threadId:a.threadId,annotationIds:a.annotationIds});_e()});let xt=Uc(async(a,u)=>{if(rd(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let k=a.url||"/",m=k.split("?")[0],P=new URL(k,`http://127.0.0.1:${y}`),I=P.pathname,j=sd(a,P);if(j&&j!==s){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Yn(r)});return}if(a.headers.origin){if(!Rs(a.headers.origin)){M(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){M(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Yn(r)});return}}try{if(a.method==="POST"&&I==="/send")await st(a,u);else if(a.method==="GET"&&I==="/events")Ye(a,u);else if(a.method==="GET"&&I==="/status")await it(a,u,j);else if(a.method==="PATCH"&&I==="/config")await at(a,u);else if(a.method==="POST"&&I==="/leases"){if(p!=="detached"){M(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Ge(a),D=typeof $.leaseId=="string"?$.leaseId.trim():"",F=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){M(u,400,{error:"A valid leaseId is required."});return}ne();let L=B.acquire(D,F);M(u,201,{ok:!0,lease:L,ttlMs:ys})}catch{M(u,400,{error:"Invalid lease request."})}}else if(I.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){M(u,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(I.slice(8))}catch{M(u,400,{error:"Invalid lease id."});return}if(!$){M(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat($);if(!D){M(u,404,{error:"Lease not found."});return}M(u,200,{ok:!0,lease:D})}else{let D=B.release($);M(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&he()}}else if(a.method==="POST"&&I==="/shutdown"){if(p!=="detached"){M(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}M(u,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&I==="/restart"){if(p!=="detached"){M(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}M(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of Y)try{$.res.end()}catch{}xt.close(()=>{hs(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"&&I==="/capabilities")M(u,200,{providers:f});else if(I.startsWith("/imprint/"))await ve(a,u,I);else if(I.startsWith("/memory/"))await oo(a,u,I);else if(a.method==="POST"&&I==="/mcp/install")await so(a,u);else if(a.method==="POST"&&I==="/reply")await Ae(a,u);else if(a.method==="POST"&&I==="/cancel")ut(a,u);else if(a.method==="POST"&&I==="/materialize")M(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&I==="/materialization-runs")M(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&I==="/projection-runs"){let $=await V.loadRuns();M(u,200,$)}else if(a.method==="GET"&&I==="/projection/proposals"){let $=await V.loadModelProposals();M(u,200,$)}else if(a.method==="POST"&&I.startsWith("/projection/proposals/")&&I.endsWith("/apply-selected")){let $=I.slice(22,-15);await zt($,a,u)}else if(a.method==="POST"&&I.startsWith("/projection/proposals/")&&I.endsWith("/apply")){let $=I.slice(22,-6);await ro($,u)}else if(a.method==="POST"&&I.startsWith("/projection/proposals/")&&I.endsWith("/dismiss")){let $=I.slice(22,-8);await Ne($,a,u)}else if(I.startsWith("/model/proposals/"))M(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&I==="/model/component")await ln(a,u);else if(a.method==="DELETE"&&I==="/model/component")await _s(a,u);else if(a.method==="PATCH"&&I==="/model/token")await As(a,u);else if(a.method==="DELETE"&&I==="/model/token")await Cs(a,u);else if(a.method==="POST"&&I==="/model/consolidate")M(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&I==="/model/synthesize")M(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&I==="/evals/synthesize")M(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&I==="/evals"){let $=await V.loadModel(),D=await Promise.all((await q.getJournalEvalCases()).map(async C=>{let O=await bs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),F=Is(r),L=(await q.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===F);M(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:L,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&I.startsWith("/evals/")&&I.endsWith("/run")){let $=I.slice(7,-4);await ct($,a,u)}else if(a.method==="PATCH"&&I.startsWith("/evals/"))await St(I.slice(7),a,u);else if(a.method==="GET"&&I==="/model"){let $=await V.loadModel();M(u,200,{model:$})}else if(a.method==="GET"&&I.startsWith("/jobs/")&&I.endsWith("/events")){let $=I.slice(6,I.length-7),D=parseInt(P.searchParams.get("afterSeq")??"-1",10),F=N.getBufferedEvents($,isNaN(D)?-1:D);F?M(u,200,F):M(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await Js(m.slice(7),u);else if(a.method==="GET"&&I==="/threads/recent"){let $=Math.min(Math.max(parseInt(P.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent($);M(u,200,D)}else if(a.method==="GET"&&I.startsWith("/decision/")){let $=I.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))M(u,400,{error:"Invalid decision id"});else{let D=await G.getThread($),F=[...D?.messages??[]].reverse().find(L=>L.annotationSnapshot);if(D&&F?.annotationSnapshot){let L=[...D.messages].reverse().find(C=>C.resolutions?.length);M(u,200,{decision:{id:D.id,createdAt:F.timestamp,url:F.annotationSnapshot.url,viewport:F.annotationSnapshot.viewport,color:F.annotationSnapshot.color,annotations:F.annotationSnapshot.annotations,resolutions:L?.resolutions??[]},authority:"thread_snapshot"})}else{let L=await E.loadDecision($);L?M(u,200,{decision:L,authority:"legacy_archive"}):M(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&I.startsWith("/thread/")){let $=I.slice(8);await Ns($,u)}else if(a.method==="DELETE"&&I.startsWith("/thread/")){let $=I.slice(8);await Bs($,u)}else a.method==="GET"&&(I==="/canvas"||I==="/canvas/")?$s(a,u):a.method==="GET"&&I==="/canvas/manifest"?await Os(u):a.method==="GET"&&I==="/canvas/app.mjs"?await Ds(u):M(u,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),M(u,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function oo(a,u,k){try{if(a.method==="GET"&&k==="/memory/status"){M(u,200,await q.status());return}if(a.method==="GET"&&k==="/memory/diagnostics"){M(u,200,await q.diagnostics());return}if(a.method==="GET"&&k==="/memory/model-view"){M(u,200,await q.getModelView());return}if(a.method==="POST"&&k==="/memory/constraints"){let m=await Ge(a),P=typeof m.reactComponent=="string"?m.reactComponent.trim():"",I=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",$=await q.getModelView(),D=P?$.entries.filter(C=>C.key===`components.${P}`||C.key.startsWith(`components.${P}.`)):[],F=(C,O)=>{if(!O)return!1;if(!C.includes("*"))return C===O;let Q=C.split("*").map(U=>U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`).test(O)},L=(await q.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(U=>U.kind==="route"&&F(U.value,I)||U.kind==="subject"&&U.value===j),Q=(C.scenarios??[]).some(U=>!!P&&(U.components??[]).some(ie=>ie.name===P||ie.exportName===P)||!!I&&!!U.route&&U.route===I||!!I&&!!U.routePattern&&F(U.routePattern,I));return O||Q}).map(C=>({id:C.id,title:C.title,verificationState:C.verificationState,assertions:C.assertions}));M(u,200,{modelEntries:D,evals:L});return}if(a.method==="POST"&&k==="/memory/conversation-action"){let m=await Ge(a),P=typeof m.threadId=="string"?m.threadId:"",I=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!P||!I||!["accept","edit_and_accept","reject","defer"].includes(j)){M(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===I)?.memoryReviewCard;if(!$||!D){M(u,409,{error:"This decision review card is not available in the thread."});return}let F=await V.findModelProposalsByThread(P),L=(await Promise.all(F.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(re=>q.findPendingProposalForLegacyDecision(re)))).some(re=>re?.proposalId===I)})))).find(ae=>ae.matches)?.proposal,C={proposalId:I,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){M(u,400,{error:"Edited decision wording is required."});return}let O=await q.commitConversationalReview(C),Q=`memory-${pt().slice(0,8)}`,U=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:Q,replyToQuestion:U}),await G.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:Q,responseText:"",memoryReceipt:O,provider:bt(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&L&&await V.dismissModelProposal(L.id);let ie=bt(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&ie!=="copilot"&&await Ft({provider:ie,model:typeof m.model=="string"?m.model:void 0,agentSettings:ht(m),threadId:P,reason:`Project accepted decision ${O.decisionId}`}),M(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&k==="/memory/analyze"){let m=await Ge(a),P=await q.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),I=Object.fromEntries([...new Set(P.issues.map(j=>j.code))].map(j=>[j,P.issues.filter($=>$.code===j).length]));M(u,200,{...P,issues:void 0,issueCounts:I});return}if(a.method==="POST"&&k==="/memory/review"){let m=await Ge(a),P=await q.review(Oo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,200,P);return}if(a.method==="POST"&&k==="/memory/context"){let m=await Ge(a),P=await q.contextualize(Oo(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,200,P);return}if(a.method==="POST"&&k==="/memory/initialize"){let m=await Ge(a),P=await q.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:ot});M(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 Ge(a),P=await q.planReview($o(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});M(u,P.result.ok?200:422,P);return}if(a.method==="POST"&&k==="/memory/commit"){let m=await Ge(a),P=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},I=await q.commitReview($o(m.command),{transactionId:typeof P.transactionId=="string"?P.transactionId:"",committedAt:typeof P.committedAt=="string"?P.committedAt:""});M(u,200,{status:await q.status(),journal:I.report});return}if(a.method==="POST"&&k==="/memory/recover"){let m=await Ge(a),P=await q.recover(m.confirm===!0);M(u,200,{status:await q.status(),journal:P.report});return}M(u,404,{error:"Memory endpoint not found."})}catch(m){let P=m instanceof Error?m.message:String(m),I=/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(I||j){M(u,I?409:400,{error:P});return}throw m}}async function ve(a,u,k){if(a.method==="GET"&&k==="/imprint/status"){let[m,P]=await Promise.all([fe.store.load(),G.load()]),I=[...new Set(Object.values(P.threads).flatMap(j=>Zn(j.messages)))];M(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:I.length,recoveredTransactions:m.recoveredTransactions,admission:fe.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&k==="/imprint/action"){let m=await Ge(a),P=typeof m.threadId=="string"?m.threadId:"",I=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!P||!I||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(j)){M(u,400,{error:"A valid thread, imprint update, and action are required."});return}let D=await G.getThread(P),F=[...D?.messages??[]].reverse().find(ie=>ie.role==="assistant"&&ie.imprintSummary?.transactionId===I),L=F?.imprintSummary;if(!D||!F||!L){M(u,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){M(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${pt().slice(0,8)}`;await fe.applyGroundingAction({summary:L,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:P,jobId:C}),await q.recordImprintEvidence({summary:L,action:j,threadId:P,jobId:C}).catch(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let O=Dt(F.result,!!F.question),Q=F.turn?{...F.turn,result:Dt(F.turn.result,!!F.question)}:void 0;await G.updateAssistantMessage(P,F.jobId,{imprintSummary:{...L,resolvedAction:j},...O?{result:O}:{},...Q?{turn:Q}:{}});let U={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:U[j]}),M(u,200,{ok:!0,action:j});return}M(u,404,{error:"Imprint endpoint not found."})}async function st(a,u){let{screenshot:k,feedback:m,color:P,provider:I,model:j,reasoningEffort:$,serviceTier:D,sourceId:F,pastedImages:L,pageScreenshots:C}=await Dn(a),O;try{O=JSON.parse(m)}catch{M(u,400,{error:"Invalid feedback JSON"});return}let Q=pt().slice(0,8),U={};if(C.length>0)for(let ee of C){let me=encodeURIComponent(ee.pathname),Re=Ee(d,`screenshot-${Q}-${me}.webp`);await dn(Re,ee.data),U[ee.pathname]=Re}let ie=Ee(d,`screenshot-${Q}.webp`);await dn(ie,k);let ae={};if(L.length>0)for(let ee of L){let me=Ee(d,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await dn(me,ee.data),ae[ee.annotationId]||(ae[ee.annotationId]=[]),ae[ee.annotationId].push(me)}let re=O.annotations.map(ee=>ee.linkedSelector?ee.pathname?`${ee.pathname}:${ee.linkedSelector}`:ee.linkedSelector:null).filter(ee=>!!ee),be;if(re.length>0){let ee=await G.findContinuationThread(re);ee?(be=ee.id,await G.addElementIdentifiers(be,re)):be=(await G.createThread(Q,re)).id}else be=(await G.createThread(Q,[])).id;let ye=O.annotations.map(ee=>ee.id),K=Object.keys(U).length>0,we=await zr(q,O,re,ee=>console.warn(`[\u22B9 ${y}:${Q}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),de=await fe.contextualize({text:On(O),subjectHints:[...re,...O.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(me=>!!me))],pendingGroundingExplanationIds:Zn((await G.getThread(be))?.messages??[])}).catch(ee=>{console.warn(`[\u22B9 ${y}:${Q}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),pe={id:Q,status:"queued",screenshotPath:ie,feedback:O,createdAt:Date.now(),color:P,threadId:be,annotationIds:ye,provider:bt(I),model:j||void 0,agentSettings:ht({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:F||void 0,...K?{screenshotPaths:U}:{},...we?{memoryReview:we}:{},...de?{imprintContext:de}:{}},Ce=new Set(O.annotations.map(ee=>ee.pathname).filter(Boolean)),$e;if(Ce.size>1){let ee=new Map;for(let me of O.annotations){let Re=me.pathname||"(unknown)";ee.has(Re)||ee.set(Re,[]),ee.get(Re).push(me.instruction||ws({...O,annotations:[me]}))}$e=[...ee.entries()].map(([me,Re])=>`\`${me}\`
|
|
228
|
-
${
|
|
228
|
+
${Vr}`;let C=bd(a.color,`[\u22B9 ${y}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${C} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${F?` (resuming: ${F.slice(0,8)})`:""}`);let K=new Jn(a.id),q=(de,pe)=>{if(de.type==="delta"&&"text"in de){let _e=K.push(de.text);_e.visibleText&&(N.accumulateText(pe,"response",_e.visibleText),N.broadcast({...de,text:_e.visibleText},pe,a.sourceId));for(let Ce of _e.orientations)N.broadcast({type:"orientation",jobId:pe,orientation:Ce},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&N.accumulateText(pe,"thinking",de.text);N.broadcast(de,pe,a.sourceId)},{process:se,result:ae}=w==="codex"?hn(a.id,{prompt:L,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:F,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:un(a.agentSettings),onEvent:q}):w==="copilot"?ir(a.id,{prompt:L,projectRoot:r,resumeSessionId:F,model:a.model,timeoutMs:g,copilotPath:f.copilot?.path??I,onEvent:q}):mn(a.id,{prompt:L,projectRoot:r,maxTurns:c,maxBudgetUsd:l,allowedTools:j?["Read"]:h,claudePath:R,resumeSessionId:F,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:g,onEvent:q});N.setActiveProcess(a.id,se);let oe=await ae,be=K.finalize(oe.text),ve=be.visibleText,V=D?Hn(ve):{visibleText:ve,draft:void 0,error:void 0},Ie=V.visibleText;for(let de of be.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=Ie,oe.success){console.log(`${C} Iteration complete`),oe.fileEdits&&oe.fileEdits.length>0&&console.log(`${C} Captured ${oe.fileEdits.length} file edit(s): ${oe.fileEdits.map(z=>`${z.tool} ${z.file_path}`).join(", ")}`),oe.editEvents&&oe.editEvents.length>0&&console.log(`${C} Captured ${oe.editEvents.length} edit event(s): ${oe.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Qr(ve),pe=Yr(ve);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let z=new Set(a.annotationIds);pe.every(Ve=>z.has(Ve.annotationId))||(pe=pe.map((Ve,Ke)=>({...Ve,annotationId:a.annotationIds[Ke%a.annotationIds.length]})))}let _e=oe.fileEdits&&oe.fileEdits.length>0?oe.fileEdits.map(z=>`${z.tool} ${z.file_path.split("/").pop()}`):oe.toolsUsed,Ce=N.getBufferedEvents(a.id),et=Ce?gd(Ce.events,r):void 0,Re,Z=Wr(ve),fe=Hr(ve);if(fe)if(!(a.memoryReview?.packets.some(re=>re.proposalId===fe.proposalId)||a.surfacedProposalIds?.includes(fe.proposalId)))Re={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Re=await U.commitConversationalReview(fe)}catch(re){Re={status:"rejected",action:fe.action,proposalId:fe.proposalId,message:re instanceof Error?re.message:String(re)}}let ke=[...(oe.fileEdits??[]).map(z=>z.file_path),...(oe.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],xe,gt=a.imprintContext?.pendingGroundingExplanationIds??[];if(V.draft?.decision==="none"&&he.recordNoop(V.draft.reason),a.threadId&&V.draft?.decision==="mutate"&&!fe&&!Z)try{xe=await he.capture(V.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await ie.loadModel(),pendingGroundingExplanationIds:gt}),xe&&await U.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(z=>console.warn(`${C} Canonical Imprint evidence linkage failed:`,z))}catch(z){console.warn(`${C} Continuous imprint update failed; the thread result remains available:`,z instanceof Error?z.message:String(z))}else V.error&&console.warn(`${C} Ignored invalid imprint block: ${V.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let z=await G.getThread(a.threadId),re=new Set(xe.changes.map(Ke=>Ke.explanationId)),Ve=z?hd(z.messages,re):void 0;if(Ve?.imprintSummary){let Ke=Ve.imprintSummary;await G.updateAssistantMessage(a.threadId,Ve.jobId,{imprintSummary:{...Ke,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Ke.additionalObservationCount??0)+1,coalescedTransactionIds:[...Ke.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let Ut=ms({question:de,resolutions:pe,changedFiles:ke,decisionRequired:!!Z,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),Q=et?.flatMap(z=>z.kind==="orientation"?[z.orientation]:[])??[];if(a.threadId){let z=j?Z?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Ie;await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:z,resolutions:!j&&pe.length>0?pe:void 0,question:j?void 0:de??void 0,sessionId:oe.sessionId,toolsUsed:j?void 0:_e,editEvents:!j&&oe.editEvents&&oe.editEvents.length>0?oe.editEvents:void 0,segments:!j&&et&&et.length>0?et:void 0,turn:{phase:"complete",orientation:Q,result:Ut},result:Ut,memoryReviewCard:Z??void 0,memoryReceipt:Re,imprintSummary:xe,model:a.model,provider:w})}if(a.threadId&&!fe&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let z=a.feedback.annotations.flatMap(re=>re.linkedSelector?[re.pathname?`${re.pathname}:${re.linkedSelector}`:re.linkedSelector]:[]);try{await U.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:m??(On(a.feedback)||"[request unavailable]"),responseSummary:de??Ie,outcome:de?"question_asked":pe.some(re=>re.status==="resolved")?"completed":"no_change",execution:{provider:w,model:a.model,sessionId:oe.sessionId},subjectHints:z,filePaths:[...(oe.fileEdits??[]).map(re=>re.file_path),...(oe.editEvents??[]).flatMap(re=>re.filePath?[re.filePath]:[])].map(re=>zo(re)?Is(r,re):re),resolutions:pe.map(re=>({status:re.status,summary:re.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(re=>re.id)})}catch(re){console.warn(`${C} Canonical memory capture failed; iteration remains available in legacy history:`,re instanceof Error?re.message:String(re))}}if(Re?.status==="committed"&&Re.decisionId&&w!=="copilot"&&await je({provider:w,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Re.decisionId}`}),a.kind==="run_eval"&&Ie&&a.evalId&&a.evalRunId){let z=await U.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(z&&re){let Ve=cr(ve,z.assertions),Ke=Date.now(),Vs={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Ke,durationMs:Ke-a.createdAt,scope:re,provider:w,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:Ps(r),rawResponse:ve,scopeFingerprint:a._evalScopeFingerprint,...Ve};await U.recordEvalVerification(z,Vs),console.log(`${C} Eval run: ${z.title} \u2192 ${Ve.status}`)}}de&&(console.log(`${C} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${X.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),N.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:de,annotationIds:a.annotationIds},a.id,a.sourceId));let me=Zr(ve);me.length>0&&(console.log(`${C} Novel pattern(s): ${me.map(z=>`${z.category}/${z.element}`).join(", ")}`),N.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),N.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:Ie,threadId:a.threadId,annotationIds:a.annotationIds,result:Ut},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${C} Error: ${oe.error}`),a.status="error",a.error=oe.error,a.threadId&&await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:oe.error||"Unknown error",model:a.model,provider:w}),N.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:oe.error||"Unknown error",provider:w,model:a.model,recoverable:oe.recoverableError,code:oe.errorCode},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:oe.error,threadId:a.threadId,annotationIds:a.annotationIds});Ue()});let Ft=sd(async(a,u)=>{if(wd(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let k=a.url||"/",m=k.split("?")[0],P=new URL(k,`http://127.0.0.1:${y}`),w=P.pathname,j=Id(a,P);if(j&&j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Zn(r)});return}if(a.headers.origin){if(!Es(a.headers.origin)){E(u,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Zn(r)});return}}try{if(a.method==="POST"&&w==="/send")await Ae(a,u);else if(a.method==="GET"&&w==="/events")at(a,u);else if(a.method==="GET"&&w==="/status")await ct(a,u,j);else if(a.method==="GET"&&w==="/ui-preferences")await ro(u);else if(a.method==="PATCH"&&w==="/ui-preferences")await so(a,u);else if(a.method==="PATCH"&&w==="/config")await ft(a,u);else if(a.method==="POST"&&w==="/leases"){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await ze(a),D=typeof $.leaseId=="string"?$.leaseId.trim():"",F=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!D||D.length>128){E(u,400,{error:"A valid leaseId is required."});return}te();let L=B.acquire(D,F);E(u,201,{ok:!0,lease:L,ttlMs:bs})}catch{E(u,400,{error:"Invalid lease request."})}}else if(w.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){E(u,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(w.slice(8))}catch{E(u,400,{error:"Invalid lease id."});return}if(!$){E(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat($);if(!D){E(u,404,{error:"Lease not found."});return}E(u,200,{ok:!0,lease:D})}else{let D=B.release($);E(u,D.found?200:404,{ok:D.found}),D.becameEmpty&&ge()}}else if(a.method==="POST"&&w==="/shutdown"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0}),setTimeout(ne,100)}else if(a.method==="POST"&&w==="/restart"){if(p!=="detached"){E(u,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}E(u,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of X)try{$.res.end()}catch{}Ft.close(()=>{ws(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&w==="/capabilities")E(u,200,{providers:f});else if(w.startsWith("/imprint/"))await it(a,u,w);else if(w.startsWith("/memory/"))await we(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await Ds(a,u);else if(a.method==="POST"&&w==="/reply")await Ze(a,u);else if(a.method==="POST"&&w==="/cancel")zt(a,u);else if(a.method==="POST"&&w==="/materialize")E(u,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&w==="/materialization-runs")E(u,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&w==="/projection-runs"){let $=await ie.loadRuns();E(u,200,$)}else if(a.method==="GET"&&w==="/projection/proposals"){let $=await ie.loadModelProposals();E(u,200,$)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply-selected")){let $=w.slice(22,-15);await dt($,a,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply")){let $=w.slice(22,-6);await Ne($,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/dismiss")){let $=w.slice(22,-8);await Pt($,a,u)}else if(w.startsWith("/model/proposals/"))E(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await Js(a,u);else if(a.method==="DELETE"&&w==="/model/component")await Ns(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Bs(a,u);else if(a.method==="DELETE"&&w==="/model/token")await Ls(a,u);else if(a.method==="POST"&&w==="/model/consolidate")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/model/synthesize")E(u,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&w==="/evals/synthesize")E(u,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&w==="/evals"){let $=await ie.loadModel(),D=await Promise.all((await U.getJournalEvalCases()).map(async C=>{let O=await Rs(r,C,$);return C.verificationState==="passing"&&(!C.verifiedScopeFingerprint||!O||C.verifiedScopeFingerprint!==O)?{...C,verificationState:"stale"}:C})),F=Ps(r),L=(await U.getJournalEvalRuns()).filter(C=>!C.codeFingerprint||C.codeFingerprint===F);E(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:L,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&w.startsWith("/evals/")&&w.endsWith("/run")){let $=w.slice(7,-4);await io($,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await ln(w.slice(7),a,u);else if(a.method==="GET"&&w==="/model"){let $=await ie.loadModel();E(u,200,{model:$})}else if(a.method==="GET"&&w.startsWith("/jobs/")&&w.endsWith("/events")){let $=w.slice(6,w.length-7),D=parseInt(P.searchParams.get("afterSeq")??"-1",10),F=N.getBufferedEvents($,isNaN(D)?-1:D);F?E(u,200,F):E(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await qs(m.slice(7),u);else if(a.method==="GET"&&w==="/threads/recent"){let $=Math.min(Math.max(parseInt(P.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent($);E(u,200,D)}else if(a.method==="GET"&&w.startsWith("/decision/")){let $=w.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))E(u,400,{error:"Invalid decision id"});else{let D=await G.getThread($),F=[...D?.messages??[]].reverse().find(L=>L.annotationSnapshot);if(D&&F?.annotationSnapshot){let L=[...D.messages].reverse().find(C=>C.resolutions?.length);E(u,200,{decision:{id:D.id,createdAt:F.timestamp,url:F.annotationSnapshot.url,viewport:F.annotationSnapshot.viewport,color:F.annotationSnapshot.color,annotations:F.annotationSnapshot.annotations,resolutions:L?.resolutions??[]},authority:"thread_snapshot"})}else{let L=await Y.loadDecision($);L?E(u,200,{decision:L,authority:"legacy_archive"}):E(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let $=w.slice(8);await Hs($,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let $=w.slice(8);await Ws($,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?Fs(a,u):a.method==="GET"&&w==="/canvas/manifest"?await zs(u):a.method==="GET"&&w==="/canvas/app.mjs"?await Us(u):E(u,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),E(u,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function we(a,u,k){try{if(a.method==="GET"&&k==="/memory/status"){E(u,200,await U.status());return}if(a.method==="GET"&&k==="/memory/diagnostics"){E(u,200,await U.diagnostics());return}if(a.method==="GET"&&k==="/memory/model-view"){E(u,200,await U.getModelView());return}if(a.method==="POST"&&k==="/memory/constraints"){let m=await ze(a),P=typeof m.reactComponent=="string"?m.reactComponent.trim():"",w=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",$=await U.getModelView(),D=P?$.entries.filter(C=>C.key===`components.${P}`||C.key.startsWith(`components.${P}.`)):[],F=(C,O)=>{if(!O)return!1;if(!C.includes("*"))return C===O;let K=C.split("*").map(q=>q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${K}$`).test(O)},L=(await U.getJournalEvalCases()).filter(C=>{if(C.status==="rejected")return!1;let O=(C.dependencies??[]).some(q=>q.kind==="route"&&F(q.value,w)||q.kind==="subject"&&q.value===j),K=(C.scenarios??[]).some(q=>!!P&&(q.components??[]).some(se=>se.name===P||se.exportName===P)||!!w&&!!q.route&&q.route===w||!!w&&!!q.routePattern&&F(q.routePattern,w));return O||K}).map(C=>({id:C.id,title:C.title,verificationState:C.verificationState,assertions:C.assertions}));E(u,200,{modelEntries:D,evals:L});return}if(a.method==="POST"&&k==="/memory/conversation-action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!P||!w||!["accept","edit_and_accept","reject","defer"].includes(j)){E(u,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await G.getThread(P),D=$?.messages.find(ae=>ae.memoryReviewCard?.proposalId===w)?.memoryReviewCard;if(!$||!D){E(u,409,{error:"This decision review card is not available in the thread."});return}let F=await ie.findModelProposalsByThread(P),L=(await Promise.all(F.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(oe=>U.findPendingProposalForLegacyDecision(oe)))).some(oe=>oe?.proposalId===w)})))).find(ae=>ae.matches)?.proposal,C={proposalId:w,action:j,kind:D.kind,claim:j==="edit_and_accept"&&typeof m.claim=="string"?m.claim.trim():void 0,reason:j==="defer"?void 0:`The owner explicitly chose ${j.replaceAll("_"," ")} from the decision review card.`,taskContext:j==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:j==="defer"?["different_action","owner_request"]:void 0};if(C.action==="edit_and_accept"&&!C.claim){E(u,400,{error:"Edited decision wording is required."});return}let O=await U.commitConversationalReview(C),K=`memory-${ut().slice(0,8)}`,q=j==="accept"?"> Accepted decision":j==="edit_and_accept"?"> Edited and accepted decision":j==="reject"?"> Rejected decision":"> Deferred decision";await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:q}),await G.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:K,responseText:"",memoryReceipt:O,provider:St(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&L&&await ie.dismissModelProposal(L.id);let se=St(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&se!=="copilot"&&await je({provider:se,model:typeof m.model=="string"?m.model:void 0,agentSettings:yt(m),threadId:P,reason:`Project accepted decision ${O.decisionId}`}),E(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&k==="/memory/analyze"){let m=await ze(a),P=await U.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),w=Object.fromEntries([...new Set(P.issues.map(j=>j.code))].map(j=>[j,P.issues.filter($=>$.code===j).length]));E(u,200,{...P,issues:void 0,issueCounts:w});return}if(a.method==="POST"&&k==="/memory/review"){let m=await ze(a),P=await U.review(Do(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/context"){let m=await ze(a),P=await U.contextualize(Do(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,P);return}if(a.method==="POST"&&k==="/memory/initialize"){let m=await ze(a),P=await U.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:rt});E(u,201,{status:P.status,report:{source:P.report.source,imported:P.report.imported,unresolvedAcceptance:P.report.unresolvedAcceptance,deferredModelEntries:P.report.deferredModelEntries,proofCases:P.report.proofCases,schemaIssues:P.report.schemaIssues}});return}if(a.method==="POST"&&k==="/memory/plan"){let m=await ze(a),P=await U.planReview(Oo(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,P.result.ok?200:422,P);return}if(a.method==="POST"&&k==="/memory/commit"){let m=await ze(a),P=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},w=await U.commitReview(Oo(m.command),{transactionId:typeof P.transactionId=="string"?P.transactionId:"",committedAt:typeof P.committedAt=="string"?P.committedAt:""});E(u,200,{status:await U.status(),journal:w.report});return}if(a.method==="POST"&&k==="/memory/recover"){let m=await ze(a),P=await U.recover(m.confirm===!0);E(u,200,{status:await U.status(),journal:P.report});return}E(u,404,{error:"Memory endpoint not found."})}catch(m){let P=m instanceof Error?m.message:String(m),w=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(P),j=/required|invalid|unsupported|expected|must be|confirmation/i.test(P);if(w||j){E(u,w?409:400,{error:P});return}throw m}}async function it(a,u,k){if(a.method==="GET"&&k==="/imprint/status"){let[m,P]=await Promise.all([he.store.load(),G.load()]),w=[...new Set(Object.values(P.threads).flatMap(j=>eo(j.messages)))];E(u,200,{state:"ready",head:m.graph.head,updatedAt:m.graph.updatedAt,explanationCount:m.graph.explanations.filter(j=>j.state!=="retired").length,concreteCount:m.graph.concrete.length,relationCount:m.graph.relations.length,pendingGroundingCount:w.length,recoveredTransactions:m.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&k==="/imprint/action"){let m=await ze(a),P=typeof m.threadId=="string"?m.threadId:"",w=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!P||!w||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(j)){E(u,400,{error:"A valid thread, imprint update, and action are required."});return}let D=await G.getThread(P),F=[...D?.messages??[]].reverse().find(se=>se.role==="assistant"&&se.imprintSummary?.transactionId===w),L=F?.imprintSummary;if(!D||!F||!L){E(u,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){E(u,409,{error:"This imprint summary has already been resolved."});return}let C=`imprint-${ut().slice(0,8)}`;await he.applyGroundingAction({summary:L,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:P,jobId:C}),await U.recordImprintEvidence({summary:L,action:j,threadId:P,jobId:C}).catch(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));let O=Jt(F.result,!!F.question),K=F.turn?{...F.turn,result:Jt(F.turn.result,!!F.question)}:void 0;await G.updateAssistantMessage(P,F.jobId,{imprintSummary:{...L,resolvedAction:j},...O?{result:O}:{},...K?{turn:K}:{}});let q={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:C,replyToQuestion:q[j]}),E(u,200,{ok:!0,action:j});return}E(u,404,{error:"Imprint endpoint not found."})}async function Ae(a,u){let{screenshot:k,feedback:m,color:P,provider:w,model:j,reasoningEffort:$,serviceTier:D,sourceId:F,pastedImages:L,pageScreenshots:C}=await Dn(a),O;try{O=JSON.parse(m)}catch{E(u,400,{error:"Invalid feedback JSON"});return}let K=ut().slice(0,8),q={};if(C.length>0)for(let Z of C){let fe=encodeURIComponent(Z.pathname),ke=Me(d,`screenshot-${K}-${fe}.webp`);await dn(ke,Z.data),q[Z.pathname]=ke}let se=Me(d,`screenshot-${K}.webp`);await dn(se,k);let ae={};if(L.length>0)for(let Z of L){let fe=Me(d,`pasted-${K}-${Z.annotationId}-${Z.index}.webp`);await dn(fe,Z.data),ae[Z.annotationId]||(ae[Z.annotationId]=[]),ae[Z.annotationId].push(fe)}let oe=O.annotations.map(Z=>Z.linkedSelector?Z.pathname?`${Z.pathname}:${Z.linkedSelector}`:Z.linkedSelector:null).filter(Z=>!!Z),be;if(oe.length>0){let Z=await G.findContinuationThread(oe);Z?(be=Z.id,await G.addElementIdentifiers(be,oe)):be=(await G.createThread(K,oe)).id}else be=(await G.createThread(K,[])).id;let ve=O.annotations.map(Z=>Z.id),V=Object.keys(q).length>0,Ie=await Ur(U,O,oe,Z=>console.warn(`[\u22B9 ${y}:${K}] Contextual memory unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))),de=await he.contextualize({text:On(O),subjectHints:[...oe,...O.annotations.flatMap(Z=>[Z.pathname,Z.elements?.[0]?.reactComponent].filter(fe=>!!fe))],pendingGroundingExplanationIds:eo((await G.getThread(be))?.messages??[])}).catch(Z=>{console.warn(`[\u22B9 ${y}:${K}] Imprint context unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))}),pe={id:K,status:"queued",screenshotPath:se,feedback:O,createdAt:Date.now(),color:P,threadId:be,annotationIds:ve,provider:St(w),model:j||void 0,agentSettings:yt({reasoningEffort:$,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:F||void 0,...V?{screenshotPaths:q}:{},...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}},_e=new Set(O.annotations.map(Z=>Z.pathname).filter(Boolean)),Ce;if(_e.size>1){let Z=new Map;for(let fe of O.annotations){let ke=fe.pathname||"(unknown)";Z.has(ke)||Z.set(ke,[]),Z.get(ke).push(fe.instruction||Ss({...O,annotations:[fe]}))}Ce=[...Z.entries()].map(([fe,ke])=>`\`${fe}\`
|
|
229
|
+
${ke.map(xe=>`- ${xe}`).join(`
|
|
229
230
|
`)}`).join(`
|
|
230
|
-
`)}else
|
|
231
|
-
`):
|
|
232
|
-
`):
|
|
233
|
-
`)),
|
|
231
|
+
`)}else Ce=Ss(O);let et=en(O,Object.keys(ae).length>0?ae:void 0);await G.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:K,screenshotPath:se,...V?{screenshotPaths:q}:{},...Object.keys(ae).length>0?{imagePaths:ae}:{},annotationIds:ve,annotationSnapshot:{url:O.url,viewport:O.viewport,annotations:O.annotations,color:P||void 0},feedbackSummary:Ce,feedbackContext:et||void 0,...Ie?{memoryReview:Ie}:{},...de?{imprintContext:de}:{}});let Re=N.enqueue(pe);E(u,200,{jobId:K,position:Re,threadId:be})}async function Ze(a,u){let k=a.headers["content-type"]||"",m,P,w,j,$,D,F,L,C,O=[];if(k.includes("multipart/form-data")){let Q=await Dn(a),me=Q.feedback?JSON.parse(Q.feedback):{};m=me.threadId,P=me.reply,w=me.color,j=me.provider,$=me.model,D=yt(me),F=me.sourceId||Q.sourceId,L=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0,C=me.evalRemediation?.action==="resolve"&&typeof me.evalRemediation.evalId=="string"?{evalId:me.evalRemediation.evalId,action:"resolve"}:void 0;for(let z of Q.pastedImages)O.push(z.data)}else{let Q=[];for await(let re of a)Q.push(typeof re=="string"?Buffer.from(re):re);let me=Buffer.concat(Q).toString("utf-8"),z;try{z=JSON.parse(me)}catch{E(u,400,{error:"Invalid JSON"});return}m=z.threadId,P=z.reply,w=z.color,j=z.provider,$=z.model,D=yt(z),F=z.sourceId,L=z.memoryReviewProposalId,C=z.evalRemediation?.action==="resolve"&&typeof z.evalRemediation.evalId=="string"?{evalId:z.evalRemediation.evalId,action:"resolve"}:void 0}if(!m||!P){E(u,400,{error:"Missing threadId or reply"});return}let K=await G.getThread(m);if(!K){E(u,404,{error:"Thread not found"});return}let q,se;if(C){let Q=await U.findJournalEvalCase(C.evalId),me=(await U.getJournalEvalRuns()).filter(z=>z.evalId===C.evalId&&z.threadId===m).sort((z,re)=>re.completedAt-z.completedAt)[0];if(!Q||!me){E(u,409,{error:"The failed eval run is not available in this thread."});return}if(me.status!=="fail"){E(u,409,{error:"Only a failed eval can start remediation."});return}se={evalCase:Q,run:me}}if(L){let Q=await ie.findModelProposalsByThread(m);if(q=(await Promise.all(Q.flatMap(z=>z.authorityStatus==="accepted"?[]:z.decisionIds.map(async re=>({modelProposalId:z.id,underlying:await U.findPendingProposalForLegacyDecision(re)}))))).filter(z=>!!z.underlying).find(z=>z.underlying.proposalId===L),!q){E(u,409,{error:"The requested memory decision is not pending in this thread."});return}}let ae="";{let Q=await G.getThreadHistory(m);for(let me=Q.length-1;me>=0;me--)if(Q[me].screenshotPath){ae=Q[me].screenshotPath;break}}let oe=await Os(m);if(!ae&&!oe){E(u,400,{error:"No screenshot available"});return}let be=N.hasActiveThread(m),ve=be?N.getQueuedThreadJob(m,Q=>Q._replyText!==void 0||Q._replyPrompt!==void 0):null,V=ve?.id??ut().slice(0,8),Ie=[],de=`${V}-${Date.now()}`;for(let Q=0;Q<O.length;Q++){let me=Me(d,`reply-${de}-${Q}.webp`);await dn(me,O[Q]),Ie.push(me)}await G.appendMessage(m,{role:"human",timestamp:Date.now(),jobId:V,replyToQuestion:P,screenshotPath:ae,...be?{queued:!0}:{},...Ie.length>0?{replyImagePaths:Ie}:{}});let pe=await G.getThreadHistory(m),_e=[...pe].reverse().find(Q=>Q.memoryReview)?.memoryReview,Ce=await he.contextualize({text:P,subjectHints:K.elementIdentifiers,pendingGroundingExplanationIds:eo(pe)}).catch(Q=>{console.warn(`[\u22B9 ${y}:${V}] Imprint context unavailable for reply; continuing without it:`,Q instanceof Error?Q.message:String(Q))}),et=new Set(pe.flatMap(Q=>Q.memoryReceipt?.status==="committed"?[Q.memoryReceipt.proposalId]:[])),Re=[...pe].reverse().find(Q=>Q.memoryReviewCard&&!et.has(Q.memoryReviewCard.proposalId))?.memoryReviewCard,Z=[];for(let Q of pe)if(Q.annotationIds)for(let me of Q.annotationIds)Z.includes(me)||Z.push(me);let fe=St(j),ke=q,xe=ke?[ke.underlying.proposalId]:Re?[Re.proposalId]:[],gt=Xr(ae,pe,fe,Ie.length>0?Ie:void 0);if(se?gt+=["","## Failed eval remediation","This is a new implementation goal based on a failed Popmelt eval. Fix the product gaps identified by the evaluator.","Do not weaken, rewrite, approve, retire, or otherwise modify the eval specification unless the developer explicitly asks.","Treat the accepted product decision as governing truth; the failed implementation is what should change.",`Eval: ${JSON.stringify(se.evalCase)}`,`Failed attempt: ${JSON.stringify({summary:se.run.summary,assertionResults:se.run.assertionResults,scope:se.run.scope})}`,"Inspect the relevant source, implement the fixes, verify them proportionally, and finish with the normal <resolution> block."].join(`
|
|
232
|
+
`):ke?gt+=["","## Decision review card",`Privately review proposal ${ke.underlying.proposalId}: ${ke.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
|
|
233
|
+
`):Re&&(gt+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Re)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
|
|
234
|
+
`)),ve){let Q=ve,z=[...Q._replyTexts??(Q._replyText?[Q._replyText]:[]),P],re=[...Q._replyImagePaths??[],...Ie];Q._replyTexts=z,Q._replyText=xs(z),Q._replyImagePaths=re.length>0?re:void 0,Q._replyPrompt=gt,Q.annotationIds=Z.length>0?Z:Q.annotationIds,Q.agentSettings=D??Q.agentSettings,Q.memoryReview=_e??Q.memoryReview,Q.imprintContext=Ce??Q.imprintContext,Q.surfacedProposalIds=[...new Set([...Q.surfacedProposalIds??[],...xe])],E(u,200,{jobId:V,position:1,threadId:m,bundled:!0});return}let qe={id:V,status:"queued",screenshotPath:ae,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:w,threadId:m,annotationIds:Z.length>0?Z:void 0,provider:fe,model:$||void 0,agentSettings:D,sourceId:F||void 0,..._e?{memoryReview:_e}:{},...Ce?{imprintContext:Ce}:{},...xe.length?{surfacedProposalIds:xe}:{}};se?qe.kind="resolve_eval":oe&&(qe.kind=oe),qe._replyPrompt=gt,qe._evalRemediation=!!se,qe._replyTexts=[P],qe._replyText=xs([P]),Ie.length>0&&(qe._replyImagePaths=Ie);let Ut=be?N.enqueueNext(qe):N.enqueue(qe);E(u,200,{jobId:V,position:Ut,threadId:m})}function at(a,u){u.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),u.write(`event: connected
|
|
234
235
|
data: {"status":"connected"}
|
|
235
236
|
|
|
236
|
-
`);let m=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,P={id:
|
|
237
|
-
`)});let me={id:ie,status:"queued",screenshotPath:ae,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:Pe,kind:"run_eval",evalId:m,evalRunId:U,provider:O,model:D||void 0,agentSettings:ht({reasoningEffort:F,serviceTier:L}),sourceId:C||void 0};me._replyPrompt=$e,me._evalRunScope=K,me._evalScreenshotPath=re,me._evalScopeFingerprint=de;let Re=N.enqueue(me);M(k,200,{jobId:ie,runId:U,position:Re,threadId:Pe,screenshotPath:re})}async function St(a,u,k){let m=decodeURIComponent(a),P={},I,j,$;try{let F=[];for await(let C of u)F.push(typeof C=="string"?Buffer.from(C):C);let L=JSON.parse(Buffer.concat(F).toString());I=L.status,j=L.title,$=L.assertions}catch{M(k,400,{error:"Invalid JSON"});return}if(I!==void 0&&I!=="pending"&&I!=="approved"&&I!=="rejected"){M(k,400,{error:"Invalid status"});return}if(I&&(P.status=I),j!==void 0){if(typeof j!="string"||j.trim().length===0){M(k,400,{error:"Invalid title"});return}P.title=j.trim()}if($!==void 0){if(!Array.isArray($)){M(k,400,{error:"Invalid assertions"});return}let F=$.filter(L=>typeof L=="string").map(L=>L.trim()).filter(Boolean);if(F.length===0){M(k,400,{error:"Invalid assertions"});return}P.assertions=F}if(!P.status&&!P.title&&!P.assertions){M(k,400,{error:"No eval changes provided"});return}let D=await q.updateJournalEvalCase(m,P);if(!D){M(k,404,{error:"Eval not found"});return}M(k,200,{eval:D})}async function mt(a){let u=Je.get(a);if(u)return u;let P=(await G.getThread(a))?.messages.find(I=>I.role==="human")?.feedbackSummary??"";if(P.startsWith("Synthesize evals"))return Je.set(a,"synthesize_evals"),"synthesize_evals";if(P.startsWith("Synthesize rules"))return Je.set(a,"synthesize"),"synthesize";if(P.startsWith("Run eval"))return Je.set(a,"run_eval"),"run_eval";if(P.startsWith("Materialize model")||P.startsWith("Project model"))return Je.set(a,"project_model"),"project_model"}async function so(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 kr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&P.push(await Tr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&P.push(await jr(m,f.copilot.path??w));let[I,j,$]=await Promise.all([wo(r),Io(r),bo(r,f.copilot?.path??w)]);f.claude&&(f.claude.mcp=I),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),M(u,200,{results:P,capabilities:{providers:f}})}async function ln(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{M(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){M(u,400,{error:"Missing or invalid name"});return}let P=await q.recordDirectModelMutation({key:`components.${m.name}`,value:{description:""},claim:`${m.name} is an explicitly governed component in the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let I=await qe({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});M(u,200,{added:!0,alreadyExists:!1,...P,evalId:I})}async function _s(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{M(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){M(u,400,{error:"Missing or invalid name"});return}let P=await q.recordDirectModelMutation({key:`components.${m.name}`,value:null,claim:`${m.name} is not governed as a component in the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let I=await qe({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});M(u,200,{removed:!0,...P,evalId:I})}async function As(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{M(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){M(u,400,{error:"Missing or invalid path/value"});return}let P=m.value;try{let $=JSON.parse(m.value);$&&typeof $=="object"&&(P=$)}catch{}let I=await q.recordDirectModelMutation({key:`tokens.${m.path}`,value:P,claim:`${m.path} uses ${m.value} in the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let j=await qe({decisionId:I.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});M(u,200,{updated:!0,...I,evalId:j})}async function Cs(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{M(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){M(u,400,{error:"Missing or invalid path"});return}let P=await q.recordDirectModelMutation({key:`tokens.${m.path}`,value:null,claim:`${m.path} is intentionally absent from the product model.`});await V.applyCanonicalEntries(await q.getCanonicalModelEntries());let I=await qe({decisionId:P.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});M(u,200,{removed:!0,...P,evalId:I})}function $s(a,u){let k=i??"http://localhost:3000";if(!i){let P=a.headers.referer||a.headers.origin;if(P)try{let I=new URL(typeof P=="string"?P:P[0]||"");(I.hostname==="localhost"||I.hostname==="127.0.0.1")&&(k=I.origin)}catch{}}let m=Go(y,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Os(a){let u=Date.now();if(rt&&u<rt.expires){M(a,200,rt.data);return}try{let{scanForComponents:k}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),P=await k(r);rt={data:P,expires:u+5e3},m(P,r,Lt).then(I=>{Lt=I}).catch(I=>console.warn("[Bridge] Render generation failed:",I)),M(a,200,P)}catch(k){console.error("[Bridge] Scanner error:",k),M(a,500,{error:"Failed to scan components"})}}async function Ds(a){let u=[Ee(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ee(r,"packages","popmelt","dist","canvas.mjs")];try{let k=Gc(import.meta.url);u.unshift(Ee(Wc(k),"canvas.mjs"))}catch{}for(let k of u)try{let m=await Lo(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),M(a,404,{error:"Canvas bundle not found"})}async function Js(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){M(u,400,{error:"Invalid filename"});return}try{let k=[Ee(d,a),Ee(r,".popmelt","artifacts","thread-media",a),Ee(r,".popmelt","artifacts","eval-screenshots",a),Ee(r,".popmelt","evals","screenshots",a),Ee(r,".popmelt","screenshots",a)],m;for(let j of k)try{m=await Lo(j);break}catch{}if(!m)throw new Error("File not found");let P=a.split(".").pop()?.toLowerCase(),I=P==="png"?"image/png":P==="webp"?"image/webp":P==="jpg"||P==="jpeg"?"image/jpeg":"application/octet-stream";u.writeHead(200,{"Content-Type":I,"Cache-Control":"public, max-age=3600"}),u.end(m)}catch{M(u,404,{error:"File not found"})}}function pn(a){return`/files/${Yn(a)}`}async function Ns(a,u){let k=await G.getThread(a);if(!k){M(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")),[I,j]=await Promise.all([m?q.getJournalEvalRuns().then(C=>C.filter(O=>O.threadId===a).sort((O,Q)=>Q.completedAt-O.completedAt)[0]):Promise.resolve(void 0),P.length>0?V.findModelProposalsByThread(a):Promise.resolve([])]),$=I?await q.findJournalEvalCase(I.evalId):null,D=await Promise.all(j.map(async(C,O)=>{if(C.authorityStatus==="accepted")return C;let Q=(await Promise.all(C.decisionIds.map(U=>q.findPendingProposalForLegacyDecision(U)))).find(Boolean);return{...C,authorityStatus:"legacy_untrusted",presentationJobId:C.presentationJobId??P[O]?.jobId??P.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),F=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,L=k.messages.map(({screenshotPath:C,screenshotPaths:O,imagePaths:Q,replyImagePaths:U,...ie})=>({...ie,...ie.role==="assistant"&&I&&ie.responseText?.includes("<eval_run_result>")?{evalRun:{...I,title:$?.title}}:{},...C?{screenshotUrl:pn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,re])=>[ae,pn(re)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ae,re])=>[ae,re.map(pn)]))}:{},...U?{replyImageUrls:U.map(pn)}:{}}));M(u,200,{id:k.id,createdAt:k.createdAt,messages:L,modelProposal:F,modelProposals:D})}async function Bs(a,u){let k=decodeURIComponent(a);if(!await G.deleteThread(k)){M(u,404,{deleted:!1,error:"Thread not found"});return}M(u,200,{deleted:!0})}let Uo=9,Ho=!1;for(let a=n;a<n+Uo;a++)try{await ad(xt,a),y=a,Ho=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await no(a);if(sn(k,{projectId:s,version:ot,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Ho)throw new Error(`[Bridge] All ports ${n}\u2013${n+Uo-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 Y)eo(m,{type:"capabilities_changed",data:{}})}});let Ls=setInterval(()=>{xs(d).catch(()=>{})},Qc),Wo=setInterval(()=>{B.expireStale().becameEmpty&&he()},Yc);return Wo.unref?.(),{port:y,projectId:s,close:async()=>{clearInterval(Ls),clearInterval(Wo),ne(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{xt.close(()=>a())})}}}async function xs(o){try{let e=await Lc(o),n=Date.now();for(let t of e){let r=Ee(o,t);try{let s=await zc(r);n-s.mtimeMs>Xc&&await qc(r)}catch{}}}catch{}}import{randomUUID as dd}from"crypto";var ld=5e3,pd=250;function zo(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function Ts(o,e=fetch){let n=`${process.pid}-${dd()}`,t=`http://127.0.0.1:${o.port}`,r=!1,s=!1,i=async()=>(await e(`${t}/leases`,{method:"POST",headers:zo(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await i())return null}catch(h){return console.warn("[popmelt] failed to register bridge lease:",h instanceof Error?h.message:String(h)),null}let d=async()=>{if(!(r||s)){s=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:zo(o)})).status===404&&!r&&await i()}catch{}finally{s=!1}}},c=setInterval(()=>{d()},ld);return c.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(c);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:zo(o),keepalive:!0})}catch{}}}}}function js(o,e=process){let n=!1,t=new Map,r=()=>{if(!n){n=!0;for(let[s,i]of t)e.removeListener(s,i);t.clear()}};for(let s of["SIGINT","SIGTERM"]){let i=()=>{let d=e.listenerCount(s),c=o.release();if(d>0)return;let l=new Promise(h=>{setTimeout(h,pd)});Promise.race([c,l]).finally(()=>{r(),e.kill(e.pid,s)})};t.set(s,i),e.prependOnceListener(s,i)}return r}var bd=1111,Es=3e4,xd=8e3;async function Sd(o){return vd(o).catch(()=>o)}async function Ms(o,e){let t=(await yd(e,"utf8").catch(()=>"")).slice(-xd).trim();return new Error(t?`${o}
|
|
237
|
+
`);let m=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,P={id:ut().slice(0,8),res:u,sourceId:m};X.add(P),a.on("close",()=>{X.delete(P)})}async function ct(a,u,k){i??=ls(a.headers),Ue();let m=[...N.allActive,...T.allActive.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds??[],color:"#000000",kind:"project_model",standalone:V.standalone}))],[P,w,j,$,D]=await Promise.allSettled([ie.loadRuns(),ie.loadModelProposals(),U.status(),he.store.load(),G.load()]),F=[],L=V=>V.reason instanceof Error?V.reason.message:String(V.reason);P.status==="rejected"&&F.push({subsystem:"projection",message:L(P)}),w.status==="rejected"&&F.push({subsystem:"projection",message:L(w)}),j.status==="rejected"?F.push({subsystem:"memory",message:L(j)}):j.value.state==="degraded"&&F.push({subsystem:"memory",message:j.value.error??"Product memory is degraded."}),$.status==="rejected"&&F.push({subsystem:"imprint",message:L($)}),D.status==="rejected"&&F.push({subsystem:"threads",message:L(D)});let C=P.status==="fulfilled"?P.value.runs:[],O=w.status==="fulfilled"?w.value.proposals:[],K=ps(C,O),q=K.actionableProposals.map(V=>({id:V.id,status:V.status,title:V.title,summary:V.summary,decisionIds:V.decisionIds,threadId:V.threadId,runId:V.runId,presentationJobId:V.presentationJobId,authorityStatus:V.authorityStatus,underlyingProposalId:V.underlyingProposalId,createdAt:V.createdAt,updatedAt:V.updatedAt,appliedAt:V.appliedAt,dismissedAt:V.dismissedAt,generatedEvalIds:V.generatedEvalIds,evalProjections:V.evalProjections,error:V.error})),se=j.status==="fulfilled"?j.value:{initialized:!1,state:"degraded",error:L(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(V=>eo(V.messages)))]:[],oe=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(V=>V.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:$.value.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:L($),pendingGroundingCount:ae.length,admission:he.diagnostics(),admissionWindowStartedAt:e},be=F.length>0?"degraded":se.state==="absent"||se.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();E(u,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:be,issues:F},version:rt,restartMode:p,projectId:s,projectName:Zn(r),projectRoot:r,requestProjectId:k,projectIdVerified:k===s,devOrigin:i,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds,color:V.color,kind:V.kind,standalone:"standalone"in V?V.standalone:void 0})),queueDepth:N.depth+T.depth,projectionQueueDepth:T.depth,leases:{active:B.isActivated,count:B.size,nextExpiryAt:B.nextExpiryAt,shutdownPending:W},projection:{state:P.status==="fulfilled"&&w.status==="fulfilled"?"ready":"degraded",activeJob:T.active?{id:T.active.id,status:T.active.status,threadId:T.active.threadId,annotationIds:T.active.annotationIds??[],provider:T.active.provider,model:T.active.model}:null,queueDepth:T.depth,recentRuns:K.recentRuns,recentAppliedRuns:K.recentAppliedRuns,actionableProposalCounts:K.actionableProposalCounts,actionableProposals:q},memory:se,imprint:oe,recentJobsRetentionMs:Je,recentJobs:Pe})}async function ft(a,u){let k=await new Promise(m=>{let P="";a.on("data",w=>{P+=w.toString()}),a.on("end",()=>m(P))});try{let m=JSON.parse(k);typeof m.devOrigin=="string"&&(i=m.devOrigin||null),E(u,200,{ok:!0,devOrigin:i})}catch{E(u,400,{error:"Invalid JSON"})}}async function ro(a){let u=await M.load();E(a,200,{ok:!0,...u})}async function so(a,u){let k=await ze(a);if(!ys(k.theme)){E(u,400,{error:"theme must be light, dark, or auto"});return}let m=await M.setTheme(k.theme);E(u,200,{ok:!0,exists:!0,preferences:m})}async function zt(a,u){let m=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),P=m?N.allActive.filter(L=>L.id===m):N.allActive,w=m?T.allActive.filter(L=>L.id===m):T.allActive,j=[...P.map(L=>L.threadId),...w.map(L=>L.threadId)].filter(Boolean),$=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),F=!!($||D);for(let L of j)await G.appendMessage(L,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});E(u,200,{cancelled:F})}async function je(a){let u=ut().slice(0,8),k=a.threadId,m=!k;k||(k=(await G.createThread(u,[])).id,Ge.set(k,"project_model")),m&&await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:u,feedbackSummary:a.reason}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:u,responseText:m?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let P={id:u,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:k,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:m},w=T.enqueue(P);return{jobId:u,position:w,threadId:k}}async function Ne(a,u){let k=decodeURIComponent(a),m=await ie.findModelProposal(k);if(!m){E(u,404,{error:"Model proposal not found"});return}E(u,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:m})}async function dt(a,u,k){let m=decodeURIComponent(a),P=[];for await(let O of u)P.push(typeof O=="string"?Buffer.from(O):O);let w;try{w=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{E(k,400,{error:"Invalid JSON"});return}let j=(w.changes??[]).flatMap(O=>{if(!Array.isArray(O.path)||O.path.length===0)return[];let K=O.path.filter(se=>typeof se=="string"||typeof se=="number");if(K.length!==O.path.length)return[];let q=Array.isArray(O.decisionIds)?O.decisionIds.filter(se=>typeof se=="string"):void 0;return[{path:K,value:O.value,remove:O.remove===!0,decisionIds:q}]});if(j.length===0){E(k,400,{error:"No selected model changes"});return}let $=(w.changeSummaries??[]).flatMap(O=>{if(!O||typeof O!="object")return[];let K=Array.isArray(O.path)?O.path.filter(q=>typeof q=="string"||typeof q=="number"):void 0;return Array.isArray(O.path)&&K?.length!==O.path.length?[]:[{group:typeof O.group=="string"?O.group:void 0,label:typeof O.label=="string"?O.label:void 0,detail:typeof O.detail=="string"?O.detail:void 0,path:K,value:O.value,currentValue:O.currentValue}]}),D=await ie.findModelProposal(m);if(!D){E(k,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){E(k,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){E(k,409,{error:`Model proposal is already ${D.status}.`});return}let F=D.decisionIds.map(O=>{let K=D.changes?.filter(ae=>ae.decisionIds.includes(O)).length??0,q=j.filter(ae=>ae.decisionIds?.includes(O)).length,se=q===0?"unprojected":K>q?"partially_projected":"projected";return{decisionId:O,status:se}}),L=await U.applyModelProjection({runId:D.runId??D.id,presentationJobId:D.presentationJobId,decisionIds:D.decisionIds,changes:j.map(O=>({path:O.path,value:O.value,decisionIds:O.decisionIds})),coverage:F}),C=await ie.applySelectedModelProposal(m,j,$);if(!C){E(k,404,{error:"Model proposal not found"});return}if(await Ye(C),C.threadId){let O=St(w.provider),K=typeof w.model=="string"&&w.model?w.model:void 0;await G.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${C.id}`,responseText:"",provider:O,model:K})}E(k,200,{proposal:C,projection:L})}async function Pt(a,u,k){let m=decodeURIComponent(a),{provider:P,model:w}=await ht(u),j=await ie.dismissModelProposal(m);if(!j){E(k,404,{error:"Model proposal not found"});return}j.threadId&&await G.appendMessage(j.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${j.id}`,responseText:"",provider:P,model:w}),E(k,200,{proposal:j})}async function ht(a){try{let u=[];for await(let m of a)u.push(typeof m=="string"?Buffer.from(m):m);if(u.length===0)return{};let k=JSON.parse(Buffer.concat(u).toString());return{provider:St(typeof k.provider=="string"?k.provider:void 0),model:typeof k.model=="string"&&k.model?k.model:void 0,agentSettings:yt(k)}}catch{return{}}}async function io(a,u,k){let m=decodeURIComponent(a),P=await U.findJournalEvalCase(m);if(!P){E(k,404,{error:"Eval not found"});return}if(P.status!=="approved"){E(k,400,{error:"Only approved evals can be run"});return}let{screenshot:w,feedback:j,provider:$,model:D,reasoningEffort:F,serviceTier:L,sourceId:C}=await Dn(u),O=St($)??b;if(O==="copilot"){E(k,400,{error:"Eval runs are not available for Copilot yet."});return}let K={};try{K=j?JSON.parse(j):{}}catch{E(k,400,{error:"Invalid eval run context JSON"});return}let q=ut().slice(0,8),se=ut().slice(0,8),ae=Me(d,`eval-run-${q}.webp`);await dn(ae,w);let oe=await ue.persistEvalScreenshot(w),be=K.viewport,ve=be&&typeof be=="object"?be:{},V={type:"current_page",url:typeof K.url=="string"?K.url:"",viewport:{width:typeof ve.width=="number"?ve.width:0,height:typeof ve.height=="number"?ve.height:0}},Ie=await ie.loadModel(),de=await Rs(r,P,Ie),pe=O==="claude"?S.name:O==="codex"?A.name:null,_e=O==="codex"?_.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=pr({evalCase:P,scope:V,model:Ie,screenshotPath:ae,chromeDevtoolsAvailable:_e}),Re=(await G.createThread(se,[])).id;Ge.set(Re,"run_eval");let Z={timestamp:new Date().toISOString(),url:V.url,viewport:V.viewport,scrollPosition:{x:typeof K.scrollX=="number"?K.scrollX:0,y:typeof K.scrollY=="number"?K.scrollY:0},annotations:[],styleModifications:[]};await G.appendMessage(Re,{role:"human",timestamp:Date.now(),jobId:se,screenshotPath:ae,feedbackSummary:`Run eval \u2014 ${P.title}`,feedbackContext:[`Eval: ${P.title}`,"Scope: current page",`URL: ${V.url||"unknown"}`,"Assertions:",...P.assertions.map(xe=>`- ${xe}`)].join(`
|
|
238
|
+
`)});let fe={id:se,status:"queued",screenshotPath:ae,feedback:Z,createdAt:Date.now(),color:"#111827",threadId:Re,kind:"run_eval",evalId:m,evalRunId:q,provider:O,model:D||void 0,agentSettings:yt({reasoningEffort:F,serviceTier:L}),sourceId:C||void 0};fe._replyPrompt=Ce,fe._evalRunScope=V,fe._evalScreenshotPath=oe,fe._evalScopeFingerprint=de;let ke=N.enqueue(fe);E(k,200,{jobId:se,runId:q,position:ke,threadId:Re,screenshotPath:oe})}async function ln(a,u,k){let m=decodeURIComponent(a),P={},w,j,$;try{let F=[];for await(let C of u)F.push(typeof C=="string"?Buffer.from(C):C);let L=JSON.parse(Buffer.concat(F).toString());w=L.status,j=L.title,$=L.assertions}catch{E(k,400,{error:"Invalid JSON"});return}if(w!==void 0&&w!=="pending"&&w!=="approved"&&w!=="rejected"){E(k,400,{error:"Invalid status"});return}if(w&&(P.status=w),j!==void 0){if(typeof j!="string"||j.trim().length===0){E(k,400,{error:"Invalid title"});return}P.title=j.trim()}if($!==void 0){if(!Array.isArray($)){E(k,400,{error:"Invalid assertions"});return}let F=$.filter(L=>typeof L=="string").map(L=>L.trim()).filter(Boolean);if(F.length===0){E(k,400,{error:"Invalid assertions"});return}P.assertions=F}if(!P.status&&!P.title&&!P.assertions){E(k,400,{error:"No eval changes provided"});return}let D=await U.updateJournalEvalCase(m,P);if(!D){E(k,404,{error:"Eval not found"});return}E(k,200,{eval:D})}async function Os(a){let u=Ge.get(a);if(u)return u;let P=(await G.getThread(a))?.messages.find(w=>w.role==="human")?.feedbackSummary??"";if(P.startsWith("Synthesize evals"))return Ge.set(a,"synthesize_evals"),"synthesize_evals";if(P.startsWith("Synthesize rules"))return Ge.set(a,"synthesize"),"synthesize";if(P.startsWith("Run eval"))return Ge.set(a,"run_eval"),"run_eval";if(P.startsWith("Materialize model")||P.startsWith("Project model"))return Ge.set(a,"project_model"),"project_model"}async function Ds(a,u){let k=[];for await(let D of a)k.push(typeof D=="string"?Buffer.from(D):D);let m;if(k.length>0)try{m=JSON.parse(Buffer.concat(k).toString("utf-8")).serverUrl}catch{}let P=[];f.claude?.available&&f.claude.mcp&&!f.claude.mcp.found&&P.push(await Tr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&P.push(await jr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&P.push(await Er(m,f.copilot.path??I));let[w,j,$]=await Promise.all([Io(r),bo(r),xo(r,f.copilot?.path??I)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=$),E(u,200,{results:P,capabilities:{providers:f}})}async function Js(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:{description:""},claim:`${m.name} is an explicitly governed component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await st({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});E(u,200,{added:!0,alreadyExists:!1,...P,evalId:w})}async function Ns(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.name||typeof m.name!="string"){E(u,400,{error:"Missing or invalid name"});return}let P=await U.recordDirectModelMutation({key:`components.${m.name}`,value:null,claim:`${m.name} is not governed as a component in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await st({decisionId:P.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});E(u,200,{removed:!0,...P,evalId:w})}async function Bs(a,u){let k=[];for await(let $ of a)k.push(typeof $=="string"?Buffer.from($):$);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"||typeof m.value!="string"){E(u,400,{error:"Missing or invalid path/value"});return}let P=m.value;try{let $=JSON.parse(m.value);$&&typeof $=="object"&&(P=$)}catch{}let w=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:P,claim:`${m.path} uses ${m.value} in the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let j=await st({decisionId:w.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} uses ${m.value} in the product model.`});E(u,200,{updated:!0,...w,evalId:j})}async function Ls(a,u){let k=[];for await(let j of a)k.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(u,400,{error:"Invalid JSON"});return}if(!m.path||typeof m.path!="string"){E(u,400,{error:"Missing or invalid path"});return}let P=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:null,claim:`${m.path} is intentionally absent from the product model.`});await ie.applyCanonicalEntries(await U.getCanonicalModelEntries());let w=await st({decisionId:P.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});E(u,200,{removed:!0,...P,evalId:w})}function Fs(a,u){let k=i??"http://localhost:3000";if(!i){let P=a.headers.referer||a.headers.origin;if(P)try{let w=new URL(typeof P=="string"?P:P[0]||"");(w.hostname==="localhost"||w.hostname==="127.0.0.1")&&(k=w.origin)}catch{}}let m=Vo(y,k);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function zs(a){let u=Date.now();if(mt&&u<mt.expires){E(a,200,mt.data);return}try{let{scanForComponents:k}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:m}=await import("./render-generator-HWFLZYC3.mjs"),P=await k(r);mt={data:P,expires:u+5e3},m(P,r,Lt).then(w=>{Lt=w}).catch(w=>console.warn("[Bridge] Render generation failed:",w)),E(a,200,P)}catch(k){console.error("[Bridge] Scanner error:",k),E(a,500,{error:"Failed to scan components"})}}async function Us(a){let u=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let k=cd(import.meta.url);u.unshift(Me(ad(k),"canvas.mjs"))}catch{}for(let k of u)try{let m=await Fo(k,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(m);return}catch{}console.error("[Bridge] Canvas bundle not found in:",u),E(a,404,{error:"Canvas bundle not found"})}async function qs(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(u,400,{error:"Invalid filename"});return}try{let k=[Me(d,a),Me(r,".popmelt","artifacts","thread-media",a),Me(r,".popmelt","artifacts","eval-screenshots",a),Me(r,".popmelt","evals","screenshots",a),Me(r,".popmelt","screenshots",a)],m;for(let j of k)try{m=await Fo(j);break}catch{}if(!m)throw new Error("File not found");let P=a.split(".").pop()?.toLowerCase(),w=P==="png"?"image/png":P==="webp"?"image/webp":P==="jpg"||P==="jpeg"?"image/jpeg":"application/octet-stream";u.writeHead(200,{"Content-Type":w,"Cache-Control":"public, max-age=3600"}),u.end(m)}catch{E(u,404,{error:"File not found"})}}function pn(a){return`/files/${Zn(a)}`}async function Hs(a,u){let k=await G.getThread(a);if(!k){E(u,404,{error:"Thread not found"});return}let m=k.messages.some(C=>C.role==="assistant"&&C.responseText?.includes("<eval_run_result>")),P=k.messages.filter(C=>C.role==="assistant"&&C.responseText?.includes("Model suggestion ready")),[w,j]=await Promise.all([m?U.getJournalEvalRuns().then(C=>C.filter(O=>O.threadId===a).sort((O,K)=>K.completedAt-O.completedAt)[0]):Promise.resolve(void 0),P.length>0?ie.findModelProposalsByThread(a):Promise.resolve([])]),$=w?await U.findJournalEvalCase(w.evalId):null,D=await Promise.all(j.map(async(C,O)=>{if(C.authorityStatus==="accepted")return C;let K=(await Promise.all(C.decisionIds.map(q=>U.findPendingProposalForLegacyDecision(q)))).find(Boolean);return{...C,authorityStatus:"legacy_untrusted",presentationJobId:C.presentationJobId??P[O]?.jobId??P.at(-1)?.jobId,underlyingProposalId:K?.proposalId,underlyingClaim:K?.claim}})),F=[...D].sort((C,O)=>O.updatedAt-C.updatedAt)[0]??null,L=k.messages.map(({screenshotPath:C,screenshotPaths:O,imagePaths:K,replyImagePaths:q,...se})=>({...se,...se.role==="assistant"&&w&&se.responseText?.includes("<eval_run_result>")?{evalRun:{...w,title:$?.title}}:{},...C?{screenshotUrl:pn(C)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,oe])=>[ae,pn(oe)]))}:{},...K?{imageUrls:Object.fromEntries(Object.entries(K).map(([ae,oe])=>[ae,oe.map(pn)]))}:{},...q?{replyImageUrls:q.map(pn)}:{}}));E(u,200,{id:k.id,createdAt:k.createdAt,messages:L,modelProposal:F,modelProposals:D})}async function Ws(a,u){let k=decodeURIComponent(a);if(!await G.deleteThread(k)){E(u,404,{deleted:!1,error:"Thread not found"});return}E(u,200,{deleted:!0})}let Ho=9,Wo=!1;for(let a=n;a<n+Ho;a++)try{await xd(Ft,a),y=a,Wo=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(u){if(u.code==="EADDRINUSE"){let k=await oo(a);if(sn(k,{projectId:s,version:rt,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!Wo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Ho-1} in use`);for(let[a,u]of Object.entries(f))!u.available||!u.path||x(a,u.path).then(k=>{if(k)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),u.available=!1,u.path=null;for(let m of X)to(m,{type:"capabilities_changed",data:{}})}});let Gs=setInterval(()=>{ks(d).catch(()=>{})},pd),Go=setInterval(()=>{B.expireStale().becameEmpty&&ge()},md);return Go.unref?.(),{port:y,projectId:s,close:async()=>{clearInterval(Gs),clearInterval(Go),te(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of X)try{a.res.end()}catch{}return X.clear(),new Promise(a=>{Ft.close(()=>a())})}}}async function ks(o){try{let e=await td(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let s=await od(r);n-s.mtimeMs>ud&&await rd(r)}catch{}}}catch{}}import{randomUUID as Pd}from"crypto";var Rd=5e3,kd=250;function Uo(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function As(o,e=fetch){let n=`${process.pid}-${Pd()}`,t=`http://127.0.0.1:${o.port}`,r=!1,s=!1,i=async()=>(await e(`${t}/leases`,{method:"POST",headers:Uo(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await i())return null}catch(h){return console.warn("[popmelt] failed to register bridge lease:",h instanceof Error?h.message:String(h)),null}let d=async()=>{if(!(r||s)){s=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:Uo(o)})).status===404&&!r&&await i()}catch{}finally{s=!1}}},c=setInterval(()=>{d()},Rd);return c.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(c);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:Uo(o),keepalive:!0})}catch{}}}}}function _s(o,e=process){let n=!1,t=new Map,r=()=>{if(!n){n=!0;for(let[s,i]of t)e.removeListener(s,i);t.clear()}};for(let s of["SIGINT","SIGTERM"]){let i=()=>{let d=e.listenerCount(s),c=o.release();if(d>0)return;let l=new Promise(h=>{setTimeout(h,kd)});Promise.race([c,l]).finally(()=>{r(),e.kill(e.pid,s)})};t.set(s,i),e.prependOnceListener(s,i)}return r}var Dd=1111,Cs=3e4,Jd=8e3;async function Nd(o){return Cd(o).catch(()=>o)}async function $s(o,e){let t=(await _d(e,"utf8").catch(()=>"")).slice(-Jd).trim();return new Error(t?`${o}
|
|
238
239
|
Bridge log (${e}):
|
|
239
|
-
${t}`:o)}async function
|
|
240
|
+
${t}`:o)}async function Nu(o){if(process.env.NODE_ENV==="production"&&!o?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(o?.detached){let n=await Bd(o);if(o.manageLease===!1)return n;let t=await As({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let r=_s(t);return{...n,close:async()=>{r(),await t.release()}}}let e=await Ms(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Bd(o){let e=o.port??Dd,n=await Nd(o.projectRoot??process.cwd()),t=Yn(n);for(let R=e;R<e+10;R++){let I=await oo(R);if(I&&I.projectId===t){if(I.version&&I.version!==rt){if(I.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${R}/shutdown`,{method:"POST"})}catch{}await new Promise(g=>setTimeout(g,500));break}continue}if(!sn(I,{projectId:t,version:rt,restartMode:"detached"}))continue;let b=o.devOrigin;if(b&&I.devOrigin!==b)try{await fetch(`http://127.0.0.1:${R}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:b})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(R),process.env.POPMELT_PROJECT_ID=t,{port:R,projectId:t,close:async()=>{}}}}let r=qo($d(Od(import.meta.url)),"bridge-entry.mjs"),s=qo(n,".popmelt"),i=qo(s,"bridge.log");await Ad(s,{recursive:!0}),await Md(i,`
|
|
240
241
|
[${new Date().toISOString()}] Starting detached bridge
|
|
241
|
-
`);let d=
|
|
242
|
+
`);let d=Ed(i,"a"),c;try{c=Td(process.execPath,[r],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{jd(d)}let l=null;c.once("error",R=>{l=`spawn error: ${R.message}`}),c.once("exit",(R,I)=>{l=`child exited before becoming healthy (${I?`signal ${I}`:`code ${R??"unknown"}`})`}),c.unref();let h=Date.now()+Cs;for(;Date.now()<h;){if(await new Promise(R=>setTimeout(R,100)),l)throw await $s(`[Bridge] Detached bridge ${l}`,i);for(let R=e;R<e+10;R++){let I=await oo(R);if(sn(I,{projectId:t,version:rt,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(R),process.env.POPMELT_PROJECT_ID=t,{port:R,projectId:t,close:async()=>{}}}}throw c.kill("SIGTERM"),await $s(`[Bridge] Detached bridge failed to start within ${Cs/1e3}s (port ${e})`,i)}export{Dt as ImprintService,Ot as ImprintStore,Wn as formatImprintPrompt,Hn as parseImprintDraft,Nu as startPopmelt};
|