@popmelt.com/core 0.8.4 → 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/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/bridge-entry.mjs +116 -299
- package/dist/{chunk-RBFQCZQP.mjs → chunk-EYFN72RC.mjs} +1 -1
- package/dist/chunk-NOHXTT24.mjs +1 -0
- package/dist/cli.mjs +116 -299
- package/dist/index.d.mts +7 -4
- package/dist/index.mjs +112 -40
- package/dist/memory-legacy.d.mts +446 -0
- package/dist/memory-legacy.mjs +1 -0
- package/dist/memory-store.d.mts +1048 -0
- package/dist/memory-store.mjs +3 -0
- package/dist/memory.d.mts +662 -0
- package/dist/memory.mjs +1 -0
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-KCVEM3PH.mjs +242 -0
- package/dist/server.d.mts +268 -1
- package/dist/server.mjs +119 -298
- package/package.json +19 -2
- package/dist/chunk-3TS7MVTZ.mjs +0 -1
- package/dist/server-7UMGXB6S.mjs +0 -421
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as
|
|
2
|
+
import{spawn as Id}from"child_process";import{readFile as bd,unlink as xd}from"fs/promises";import{join as Sd}from"path";import{execFileSync as eo,spawn as ws}from"child_process";import{createHash as Ts,randomUUID as ut}from"crypto";import{mkdir as Kc,readFile as Fo,readdir as Qc,realpath as Xc,stat as Yc,unlink as Zc,writeFile as ln}from"fs/promises";import{createServer as ed}from"http";import{tmpdir as td}from"os";import{basename as Xn,dirname as nd,isAbsolute as Lo,join as Ae,relative as Is,resolve as js}from"path";import{fileURLToPath as od}from"url";function Ho(o,e){return`<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -19,105 +19,50 @@ import{spawn as Fr}from"child_process";import{readFile as jr,unlink as Lr}from"f
|
|
|
19
19
|
}}
|
|
20
20
|
</script>
|
|
21
21
|
<script type="module">
|
|
22
|
-
import { mountCanvas } from 'http://localhost:${
|
|
22
|
+
import { mountCanvas } from 'http://localhost:${o}/canvas/app.mjs';
|
|
23
23
|
mountCanvas(document.getElementById('root'), {
|
|
24
24
|
devOrigin: '${e}',
|
|
25
|
-
bridgeOrigin: 'http://localhost:${
|
|
25
|
+
bridgeOrigin: 'http://localhost:${o}',
|
|
26
26
|
});
|
|
27
27
|
</script>
|
|
28
28
|
</body>
|
|
29
|
-
</html>`}var
|
|
30
|
-
\u2026[truncated]`:t}function
|
|
31
|
-
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let
|
|
32
|
-
`)[0].slice(0,80)}`:"Bash";
|
|
33
|
-
`)}`)),
|
|
34
|
-
`)[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&&(
|
|
35
|
-
|
|
36
|
-
The designer does NOT work eval-first. They use annotations and conversation threads to zhuzh the UI over time. Your job is to infer useful eval proposals from that trail. The developer will reject, refine, or approve proposals in this thread. Do not write files or run commands.
|
|
37
|
-
|
|
38
|
-
## Current Design Model
|
|
39
|
-
\`\`\`json
|
|
40
|
-
${JSON.stringify(s.model??null,null,2)}
|
|
41
|
-
\`\`\`
|
|
42
|
-
|
|
43
|
-
## Existing Eval Suite
|
|
44
|
-
\`\`\`json
|
|
45
|
-
${JSON.stringify(s.existingSuite,null,2)}
|
|
46
|
-
\`\`\`
|
|
47
|
-
|
|
48
|
-
## Recent Decisions
|
|
49
|
-
${e.map(co).join(`
|
|
50
|
-
|
|
51
|
-
`)||"No decisions found."}
|
|
52
|
-
|
|
53
|
-
## Recent Threads
|
|
54
|
-
${n.map(uo).join(`
|
|
55
|
-
|
|
56
|
-
`)||"No threads found."}
|
|
57
|
-
|
|
58
|
-
## Instructions
|
|
59
|
-
1. Infer evals that encode reusable taste, design judgment, product behavior, or interaction expectations.
|
|
60
|
-
2. Prefer proposals backed by multiple decisions, rich thread context, or explicit approved/resolved outcomes.
|
|
61
|
-
3. Avoid one-off implementation chores, temporary bug fixes, vague preferences, or evals that cannot be checked later.
|
|
62
|
-
4. Cite source decision ids and thread ids for each proposal.
|
|
63
|
-
5. Present proposals as clear text first. Group them by Component, Layout, Copy, Interaction, Visual, and Workflow.
|
|
64
|
-
6. Ask the developer what to approve, reject, or adjust.
|
|
65
|
-
7. Include a machine-readable <eval_proposals> block containing the same proposals as pending eval JSON. These will be saved as draft proposals for panel review.
|
|
66
|
-
8. Tell the developer that the proposals have been saved to the Eval panel for accept/reject review.
|
|
67
|
-
9. Do NOT output an <evals> block yet. First get the developer's approval.
|
|
68
|
-
|
|
69
|
-
## After Approval
|
|
70
|
-
When the developer approves or asks you to save the final set, output a complete JSON array inside <evals> tags. Each object must use this shape:
|
|
71
|
-
|
|
72
|
-
\`\`\`json
|
|
73
|
-
{
|
|
74
|
-
"id": "eval-short-stable-id",
|
|
75
|
-
"title": "Short human-readable name",
|
|
76
|
-
"status": "approved",
|
|
77
|
-
"category": "component",
|
|
78
|
-
"prompt": "The eval instruction an agent should satisfy.",
|
|
79
|
-
"assertions": ["Observable expectation 1", "Observable expectation 2"],
|
|
80
|
-
"rationale": "Why this eval represents the designer's taste.",
|
|
81
|
-
"sourceDecisionIds": ["decision-id"],
|
|
82
|
-
"sourceThreadIds": ["thread-id"]
|
|
83
|
-
}
|
|
84
|
-
\`\`\`
|
|
85
|
-
|
|
86
|
-
Allowed categories: component, layout, copy, interaction, visual, workflow.
|
|
87
|
-
Return only the <evals> block after approval.
|
|
88
|
-
|
|
89
|
-
## First Response Structured Block
|
|
90
|
-
At the end of your first proposal response, output a JSON array inside <eval_proposals> tags using the same schema, but with "status": "pending".`}function dn(s){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.
|
|
29
|
+
</html>`}var qs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ws=new Set(["default","flex","fast","priority"]);function yt(o){let e=typeof o.reasoningEffort=="string"&&qs.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Ws.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function mn(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as Hs}from"child_process";import{createInterface as Gs}from"readline";var Vs=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"]),Go=1e5;function Ks(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Vs.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>Go?t.slice(0,Go)+`
|
|
30
|
+
\u2026[truncated]`:t}function fn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:s=1,allowedTools:i=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:l,reasoningEffort:g,timeoutMs:R=3e5,onEvent:b}=e,I=[];d?I.push("--resume",d,"-p",n):I.push("-p",n),I.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(s)),l&&I.push("--model",l),g&&I.push("--effort",g);for(let h of i)I.push("--allowedTools",h);let y=Hs(c,I,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(h=>{let f,v=[],x=[],S=[],A=!1,J="",_,N,T=!1,B=setTimeout(()=>{T=!0,y.kill("SIGTERM"),setTimeout(()=>{try{y.kill("SIGKILL")}catch{}},5e3)},R),W=Gs({input:y.stdout}),ee=new Set;W.on("line",te=>{if(te.trim())try{let ne=JSON.parse(te);ne.session_id&&!f&&(f=ne.session_id);let ge=ne.type??(ne.event?.type?`event.${ne.event.type}`:"unknown");if(ee.add(ge),ne.type==="result"&&ne.result&&v.length===0){let X=typeof ne.result=="string"?ne.result:"";X&&(v.push(X),b?.({type:"delta",jobId:o,text:X},o))}if(ne.type==="assistant"&&Array.isArray(ne.message?.content)){typeof ne.error=="string"&&(_=ne.error);for(let X of ne.message.content){if(X.type==="text"&&X.text&&(v.push(X.text),b?.({type:"delta",jobId:o,text:X.text},o)),X.type==="tool_use"&&X.name){let G=X.input?.file_path||X.input?.path||void 0,U=Ks(X);if(b?.({type:"tool_use",jobId:o,tool:X.name,...G?{file:G}:{},...U?{content:U}:{}},o),X.name==="Edit"&&X.input?.file_path){let he={tool:"Edit",file_path:X.input.file_path,old_string:X.input.old_string,new_string:X.input.new_string,replace_all:X.input.replace_all};x.push(he),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:he.file_path,oldString:typeof he.old_string=="string"?he.old_string:void 0,newString:typeof he.new_string=="string"?he.new_string:void 0,replaceAll:typeof he.replace_all=="boolean"?he.replace_all:void 0})}else X.name==="Write"&&X.input?.file_path&&(x.push({tool:"Write",file_path:X.input.file_path,content:X.input.content}),S.push({sequence:S.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:X.input.file_path,content:typeof X.input.content=="string"?X.input.content:void 0}))}X.type==="thinking"&&X.thinking&&b?.({type:"thinking",jobId:o,text:X.thinking},o)}}ne.type==="result"&&ne.is_error===!0&&(A=!0,typeof ne.error=="string"&&(_=ne.error),typeof ne.result=="string"&&(N=ne.result)),ne.type==="user"&&ne.tool_use_result?.file?.filePath&&b?.({type:"tool_use",jobId:o,tool:"Read",file:ne.tool_use_result.file.filePath},o)}catch{}});let H=[];y.stderr?.on("data",te=>{H.push(te.toString())}),y.on("close",te=>{if(clearTimeout(B),W.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=H.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=Qs(J,_);h({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})}),y.on("error",te=>{clearTimeout(B),A=!0,J=te.message,h({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:y,result:p}}function Qs(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 Xs,spawnSync as Zo}from"child_process";import{readFileSync as Ys,statSync as Zs}from"fs";import{basename as ei,extname as ti,isAbsolute as ni,relative as er,resolve as oi}from"path";import{createInterface as ri}from"readline";function Vo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Ko=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),ro=2e5,si=1e5,tr=2e5;function nr(o){let e=ei(o).toLowerCase(),n=ti(o).toLowerCase();return Ko.has(n)||Ko.has(e)}function qt(o,e){let n=ni(e)?e:oi(o,e),t=er(o,n);return t===""||t.startsWith("..")?null:n}function hn(o,e){if(!nr(e))return;let n=qt(o,e);if(n)try{let t=Zs(n);return t.isFile()?t.size>ro?{exists:!0,truncated:!0}:{exists:!0,content:Ys(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function ii(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function ai(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 Qo(o){return ii(o,["patch","diff","unifiedDiff","unified_diff"])}function so(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Xo(o,e){let n=Zo("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:tr+65536});return n.status!==0?null:n.stdout??""}function ci(o){let e=new Set;for(let n of o.split(`
|
|
31
|
+
`)){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 Yo(o){let e=Xo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Xo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=so(n,tr);return{status:e,changedFiles:ci(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function di(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function li(o,e){if(!nr(e))return;let n=qt(o,e);if(!n)return;let t=er(o,n);if(t===""||t.startsWith(".."))return;let r=Zo("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:ro+65536});if(r.status!==0)return{exists:!1};let s=r.stdout??"",i=so(s,ro);return{exists:!0,content:i.text,...i.truncated?{truncated:!0}:{}}}function pi(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):li(o,t),s=hn(o,t);return{filePath:t,...r?{before:r}:{},...s?{after:s}:{}}})}function gn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:s,model:i,onEvent:c,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,g=[];if(s){g.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let I of l)g.push("-c",I);i&&g.push("-m",i),g.push(s),g.push(n),r&&g.push("--image",r)}else{g.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let I of l)g.push("-c",I);i&&g.push("-m",i),g.push(n),r&&g.push("--image",r)}let R=Xs("codex",g,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),b=new Promise(I=>{let y,p=[],h=[],f=[],v=new Map,x=new Map,S=!1,A="",J=ri({input:R.stdout}),_=new Set;J.on("line",T=>{if(T.trim())try{let B=JSON.parse(T),W=B.type??"unknown";if(_.add(W),W==="thread.started"&&B.thread_id&&!y&&(y=B.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&B.delta?.text&&(p.push(B.delta.text),c?.({type:"delta",jobId:o,text:B.delta.text},o)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&B.delta?.text&&c?.({type:"thinking",jobId:o,text:B.delta.text},o),(W==="item.started"||W==="item/started")&&B.item){let ee=B.item.type;if(ee==="command_execution"){let H=B.item.command,te=H?Vo(H):void 0,ne=Yo(t),ge=new Map;for(let G of ne?.changedFiles??[])ge.set(G,hn(t,G));typeof B.item.id=="string"&&x.set(B.item.id,{...H?{rawCommand:H}:{},...te?{command:te}:{},...ne?{beforeWorktree:ne}:{},beforeSnapshots:ge});let X=te?`Bash: ${te.split(`
|
|
32
|
+
`)[0].slice(0,80)}`:"Bash";h.push(X),c?.({type:"tool_use",jobId:o,tool:"Bash",...te?{content:te}:{}},o)}else if(ee==="file_change"){let H=B.item.filename||B.item.path;H&&!v.has(H)&&v.set(H,hn(t,H)),h.push(H?`Edit ${H.split("/").pop()}`:"Edit");let te=H?qt(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...te?{file:te}:{}},o)}else if(ee==="file_read"){let H=B.item.filename||B.item.path;h.push(H?`Read ${H.split("/").pop()}`:"Read");let te=H?qt(t,H)??H:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...te?{file:te}:{}},o)}else if(ee==="web_search")h.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(ee==="mcp_tool_call"){let H=B.item.tool_name||B.item.name||"MCP";h.push(H),c?.({type:"tool_use",jobId:o,tool:H},o)}}if((W==="item.completed"||W==="item/completed")&&B.item){if(B.item.type==="agent_message"){let ee=B.item.text;typeof ee=="string"&&ee&&(p.push(ee),c?.({type:"delta",jobId:o,text:ee},o))}else if(B.item.type==="reasoning"){let ee=B.item.text;typeof ee=="string"&&ee&&c?.({type:"thinking",jobId:o,text:ee},o)}else if(B.item.type==="file_change"&&Array.isArray(B.item.changes))for(let ee of B.item.changes){let H=ee.path||ee.filename,te=ee.kind==="add"?"Write":"Edit";if(H){h.push(`${te} ${H.split("/").pop()}`);let ne=qt(t,H)??H;c?.({type:"tool_use",jobId:o,tool:te,file:ne},o);let ge=ee,X=typeof ge.kind=="string"?ge.kind:void 0,G=ai(X),U=v.get(H),he=hn(t,H);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:G,filePath:H,...U?{before:U}:{},...he?{after:he}:{},...Qo(ge)?{patch:Qo(ge)}:{},...X?{rawKind:X}:{}}),v.set(H,he)}}else if(B.item.type==="command_execution"){let ee=typeof B.item.id=="string"?B.item.id:void 0,H=ee?x.get(ee):void 0,te=typeof B.item.command=="string"?B.item.command:H?.rawCommand,ne=te?Vo(te):H?.command,ge=Yo(t);if(di(H?.beforeWorktree,ge)){let X=[...new Set([...H?.beforeWorktree?.changedFiles??[],...ge?.changedFiles??[]])],G=typeof B.item.aggregated_output=="string"?so(B.item.aggregated_output,si):void 0,U=typeof B.item.exit_code=="number"?B.item.exit_code:B.item.exit_code===null?null:void 0,he=typeof B.item.status=="string"?B.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...te?{rawCommand:te}:{},...ne?{command:ne}:{},...U!==void 0?{exitCode:U}:{},...he?{status:he}:{},...G?{output:G.text}:{},...G?.truncated?{outputTruncated:!0}:{},...H?.beforeWorktree?{beforeWorktree:H.beforeWorktree}:{},...ge?{afterWorktree:ge}:{},...X.length>0?{touchedFiles:pi(t,X,H?.beforeSnapshots??new Map)}:{}})}ee&&x.delete(ee)}}W==="turn.failed"&&(S=!0,A=B.error?.message||B.message||"Turn failed")}catch{}});let N=[];R.stderr?.on("data",T=>{N.push(T.toString())}),R.on("close",T=>{J.close(),p.length===0&&_.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[..._].join(", ")}`),T!==0&&T!==null&&(S=!0,A=N.join("")||`Codex process exited with code ${T}`),I({sessionId:y,text:p.join(""),success:!S,error:S?A:void 0,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})}),R.on("error",T=>{S=!0,A=T.message,I({sessionId:y,text:p.join(""),success:!1,error:A,editEvents:f.length>0?f:void 0,toolsUsed:h.length>0?h:void 0})})});return{process:R,result:b}}import{spawn as ui}from"child_process";import{createInterface as mi}from"readline";function or(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 rr(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:s,timeoutMs:i=3e5,onEvent:c,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),s&&l.push("--model",s),l.push("-p",n);let g=ui(d,l,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(b=>{let I,y=[],p=[],h=!1,f="",v=!1,x=setTimeout(()=>{v=!0,g.kill("SIGTERM"),setTimeout(()=>{try{g.kill("SIGKILL")}catch{}},5e3)},i),S=mi({input:g.stdout}),A=new Set,J=[];S.on("line",N=>{if(N.trim())try{let T=JSON.parse(N),B=Ht(T);A.add(B),J.length<5&&hi(B)&&J.push(N.slice(0,800));let W=Wt(T,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!I&&(I=W);let ee=fi(T,y.length===0);ee&&(y.push(ee),c?.({type:"delta",jobId:o,text:ee},o));let H=gi(T);H&&c?.({type:"thinking",jobId:o,text:H},o);let te=yi(T);te&&(p.push(te.label),c?.({type:"tool_use",jobId:o,tool:te.tool,...te.file?{file:te.file}:{},...te.content?{content:te.content}:{}},o));let ne=vi(T);ne&&(h=!0,f=ne)}catch{}});let _=[];g.stderr?.on("data",N=>{_.push(N.toString())}),g.on("close",N=>{clearTimeout(x),S.close(),y.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(`
|
|
33
|
+
`)}`)),v?(h=!0,f=`Timed out after ${Math.round(i/6e4)} minutes`):N!==0&&N!==null&&(h=!0,f=_.join("").trim()||f||`Copilot process exited with code ${N}`);let T=h?or(f,s):null;b({sessionId:I,text:y.join(""),success:!h,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),g.on("error",N=>{clearTimeout(x);let T=or(N.message,s);b({sessionId:I,text:y.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:g,result:R}}function Ht(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 fi(o,e=!1){let n=Ht(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"&&io(o))return o.text;if(typeof o.message=="string"&&io(o))return o.message;if(typeof o.delta=="string"&&io(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 hi(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function gi(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 yi(o){let e=Wt(o,["tool","toolName","tool_name","name"]),n=Wt(o,["command","cmd"]),t=Wt(o,["file","path","filename","filePath"]),r=Ht(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
34
|
+
`)[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 vi(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"&&Ht(o).toLowerCase().includes("error"))return o.message}function Wt(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=Wt(r,e);if(s)return s}}function io(o){let e=Ht(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as wi,readFile as Ii}from"fs/promises";import{join as ao}from"path";var yn=class{constructor(e){let n=ao(e,".popmelt");this.decisionsDir=ao(n,"decisions")}async listDecisionIds(){try{return(await wi(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 Ii(ao(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 ir(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=ji(t.assertionResults,e),s=Ei(r);return{status:s,summary:nt(t.summary)||lr(s),assertionResults:r,tooling:Mi(t.tooling)}}catch{}return{status:"needs_review",summary:Ai(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 ar(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),c=new Set(s.map(v=>v.value)),d=e.cases.find(v=>v.status!=="rejected"&&(v.sourceDecisionIds.some(x=>i.has(x))||(v.dependencies??[]).some(x=>x.kind==="model_path"&&c.has(x.value)))),l=(o.selectedChanges??[]).find(v=>v.label?.trim())?.label?.trim()??t.find(v=>v.label?.trim())?.label?.trim()??o.title,g=d?.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}]:[]),I=(R.length>0?R:t.map(v=>({path:v.path,value:v.value,label:v.label,detail:v.rationale}))).flatMap(v=>bi(v,o.decisionIds)),y=wn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!g?d.assertions:[],...I,...I.length===0&&y?[y]:[]])],h=s[0].value,f=h.startsWith("components.")?"component":h.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!g?d.title:l,status:"pending",category:d?.category??f,prompt:d&&!g?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!g?d.rationale:ki(h),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...s].map(v=>[`${v.kind}:${v.value}`,v])).values()]}]}function bi(o,e){let n=String(o.path[0]??"");if(n==="rules")return xi(o.value,e);if(n==="components"){let i=cr(String(o.path[1]??o.label??"component")),c=vn(o.value),d=c?Vt(c.usage):[];if(d.length>0){let g=Pi(d),R=d.length===1?"uses":"use";return[`The ${g} ${R} the same shared implementation for the ${i} pattern.`]}if(c?.shared===!0)return[`The product uses a shared implementation for the ${i} pattern.`];let l=c?nt(c.constraint):"";if(l){let g=Si(l,i);if(g)return[g]}}if(n==="tokens"){let i=o.path.slice(1).map(String).join("."),c=vn(o.value),d=c&&"value"in c?c.value:o.value,l=Ri(d);if(i&&l)return[`The ${i} token resolves to ${l}.`]}let t=vn(o.value),r=t?nt(t.text)||nt(t.constraint):typeof o.value=="string"?o.value:"",s=wn(r||o.detail||"");return s?[s]:[]}function xi(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(i=>{let c=vn(i),d=c?nt(c.text):"";return d?[{text:d,sources:c?Vt(c.sources):[]}]:[]}),r=t.filter(i=>i.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(i=>wn(i.text)).filter(i=>!!i)}function Si(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])}`):wn(o)}function co(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Rt(`${sr(n[1])} is ${Gt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Rt(sr(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 wn=co;function ki(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${cr(e[1]??"component")} contract across its declared product surfaces.`:e[0]==="tokens"?`Protects the ${e.slice(1).join(".")} token from implementation drift.`:e[0]==="rules"?"Protects an enforceable product rule across its declared scope.":"Protects an enforceable product expectation across its declared scope."}function vn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function cr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function Pi(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 Ri(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 sr(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 dr(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.
|
|
91
35
|
|
|
92
36
|
## Eval
|
|
93
37
|
\`\`\`json
|
|
94
|
-
${JSON.stringify(
|
|
38
|
+
${JSON.stringify(o.evalCase,null,2)}
|
|
95
39
|
\`\`\`
|
|
96
40
|
|
|
97
41
|
## Scope
|
|
98
42
|
\`\`\`json
|
|
99
|
-
${JSON.stringify(
|
|
43
|
+
${JSON.stringify(o.scope,null,2)}
|
|
100
44
|
\`\`\`
|
|
101
45
|
|
|
102
46
|
## Current Design Model
|
|
103
47
|
\`\`\`json
|
|
104
|
-
${JSON.stringify(
|
|
48
|
+
${JSON.stringify(o.model??null,null,2)}
|
|
105
49
|
\`\`\`
|
|
106
50
|
|
|
107
51
|
## Evidence
|
|
108
|
-
- Current page screenshot: ${
|
|
109
|
-
- Chrome DevTools MCP is ${
|
|
52
|
+
- Current page screenshot: ${o.screenshotPath}
|
|
53
|
+
- Chrome DevTools MCP is ${o.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
|
|
110
54
|
|
|
111
55
|
## Instructions
|
|
112
|
-
1. Evaluate only the current
|
|
113
|
-
2.
|
|
114
|
-
3.
|
|
115
|
-
4.
|
|
116
|
-
5.
|
|
117
|
-
6.
|
|
118
|
-
7.
|
|
119
|
-
8.
|
|
120
|
-
9.
|
|
56
|
+
1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
|
|
57
|
+
2. Compare the runtime URL, component evidence, and visible state with the eval's declared scenarios. If the runtime does not satisfy an applicable declared scenario, mark affected assertions "needs_review" and name the scope mismatch instead of guessing.
|
|
58
|
+
3. Use the screenshot as baseline evidence.
|
|
59
|
+
4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
|
|
60
|
+
5. Judge each assertion independently as "pass", "fail", or "needs_review".
|
|
61
|
+
6. Keep failures actionable and grounded in observed evidence.
|
|
62
|
+
7. Do not propose visual markers yet.
|
|
63
|
+
8. End with exactly one machine-readable <eval_run_result> block.
|
|
64
|
+
9. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
|
|
65
|
+
10. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
|
|
121
66
|
|
|
122
67
|
The block must be valid JSON with this shape:
|
|
123
68
|
|
|
@@ -142,106 +87,42 @@ The block must be valid JSON with this shape:
|
|
|
142
87
|
\`\`\`
|
|
143
88
|
|
|
144
89
|
Allowed statuses: pass, fail, needs_review.
|
|
145
|
-
Allowed chromeDevtools values: available, unavailable, unknown.`}function un(s){return`You are turning an approved Popmelt taste-model update into draft evals.
|
|
146
|
-
|
|
147
|
-
|
|
90
|
+
Allowed chromeDevtools values: available, unavailable, unknown.`}function nt(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 Ti(o){let e=nt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function ji(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let s=r,i=nt(s.assertion);return i?{assertion:i,status:Ti(s.status)??"needs_review",summary:nt(s.summary)||lr("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 Ei(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Mi(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=nt(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Vt(e.evidenceTypes).length>0?Vt(e.evidenceTypes):["screenshot"]}}function lr(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 Ai(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as _i}from"crypto";import{mkdir as $i,writeFile as Ci}from"fs/promises";import{join as lo}from"path";var In=class{constructor(e){this.root=lo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=lo(this.root,"eval-screenshots"),t=_i("sha256").update(e).digest("hex"),r=lo(n,`${t}.webp`);return await $i(n,{recursive:!0}),await Ci(r,e,{flag:"wx"}).catch(s=>{if(s.code!=="EEXIST")throw s}),r}};import{randomUUID as pr}from"crypto";import{mkdir as po,readFile as uo,writeFile as bn}from"fs/promises";import{dirname as mo,join as Tt}from"path";var He="[ProjectionWorker]",Oi={version:1,runs:[]},Di={version:1,updatedAt:0,proposals:[]},Ji=12;function Ni(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 ur(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 Bi(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Fi(o,e,n){let t=new Set(e),r=new Set,s=Array.isArray(o.rules)?o.rules:[];for(let y of s){if(!y||typeof y!="object")continue;let p=y.sources;if(Array.isArray(p))for(let h of p)typeof h=="string"&&t.has(h)&&r.add(h)}let i=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=s.filter(y=>{if(!y||typeof y!="object")return!1;let p=y.id,h=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(h)!==JSON.stringify(y)}).length,g=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},R=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(i).filter(y=>JSON.stringify(i[y])!==JSON.stringify(g[y])).length,I=Object.keys(c).filter(y=>JSON.stringify(c[y])!==JSON.stringify(R[y])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:I,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(y=>!r.has(y))}}function Li(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function zi(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 xn(o,e,n){let t=o;for(let s=0;s<e.length-1;s++)t=zi(t,e[s],e[s+1]);let r=e[e.length-1];t[String(r)]=Li(n)}function mr(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 Ui(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 qi(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 fr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Ui(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?qi(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Sn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Tt(e,".popmelt");this.runsPath=Tt(t,"projection-runs.json"),this.legacyRunsPath=Tt(t,"materialization-runs.json"),this.proposalsPath=Tt(t,"projection-queue.json"),this.legacyProposalsPath=Tt(t,"model-proposals.json"),this.modelPath=Tt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await uo(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Ni(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?mr(n,r):xn(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(Ji),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(y=>y.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(),c=Vi(r,i),d=Bi(r,t.totalCandidateDecisionCount,c);n=pr().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:s,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let g=!0,R,b,I;try{let y=`projection-${Date.now()}`,{provider:p,result:h}=this.spawnModelAgent(y,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let f=await h;if(!f.success)g=!1,R=f.error,console.error(`${He} ${p} spawn error:`,R);else{let v=Gi(f.text,s);if(v){let x=structuredClone(i??{tokens:{},components:{},rules:[]});for(let J of v)xn(x,J.path,J.value);Array.isArray(x.rules)&&(x.rules=ur(x.rules));let S=Fi(x,s,i);if(v){let J=[...new Set(v.flatMap(_=>_.decisionIds))];S.coveredDecisionIds=J,S.uncoveredDecisionIds=s.filter(_=>!J.includes(_))}b=S;let A=await this.createModelProposal({decisionIds:s,proposedModel:x,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:b,changes:v});I=A.id,console.log(`${He} Created model proposal ${A.id} for ${s.length} decision(s)`)}else g=!1,R="No valid bounded <model-changes> block found in response",console.error(`${He} ${R}`)}}catch(y){g=!1,R=y instanceof Error?y.message:String(y),console.error(`${He} Error:`,R)}return await this.persistRun({...l,status:g?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:b,proposalId:I}),this.options.onEvent?.({type:"projection_done",decisionIds:s,success:g,error:R}),{processedIds:s,success:g,error:R,runId:n,proposalId:I}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=ur(e.rules)),await bn(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 po(mo(this.runsPath),{recursive:!0}),await bn(this.runsPath,JSON.stringify(n,null,2)),n):{...Oi,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??{...Di,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??[])xn(s,i.path,i.value);return{...r,proposedModel:s}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let s=await this.findModelProposal(e);if(!s)return null;if(s.status==="dismissed")return s;let i=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?mr(i,d.path):xn(i,d.path,d.value));return await this.writeModel(i),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),s=new Map((t.evalProjections??[]).map(i=>[i.evalId,i]));for(let i of n){let c=typeof i=="string"?{evalId:i,title:i,action:"created"}:i;r.add(c.evalId),s.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...s.values()]})}async createModelProposal(e){let n={id:pr().slice(0,8),status:"pending",title:Wi(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"}.`:Hi(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 po(mo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await bn(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 po(mo(this.runsPath),{recursive:!0}),await bn(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 uo(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await uo(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let s=t.provider??this.options.provider??"claude",i=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return s==="codex"?{provider:"codex",...gn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:mn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:i})}:(s==="copilot"&&console.warn(`${He} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...fn(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 Wi(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 Hi(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 Gi(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),s=t.flatMap((i,c)=>{if(!i||typeof i!="object"||Array.isArray(i))return[];let d=i;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(R=>typeof R=="string"||typeof R=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let g=Array.isArray(d.decisionIds)?d.decisionIds.filter(R=>typeof R=="string"&&r.has(R)):[];return g.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:g,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return s.length===t.length?s:null}catch{return null}}function Vi(o,e){let n=o.map(s=>`### Accepted decision ${s.id} (${s.createdAt})
|
|
91
|
+
Kind: ${s.kind}
|
|
92
|
+
Claim: ${s.claim}
|
|
93
|
+
${s.rationale?`Rationale: ${s.rationale}`:""}
|
|
94
|
+
Subjects: ${s.subjects.map(i=>`${i.role}:${i.subjectId}`).join(", ")}
|
|
95
|
+
Authority: ${s.authority.level}/${s.authority.mode}`).join(`
|
|
148
96
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
## Approved Model Proposal
|
|
152
|
-
\`\`\`json
|
|
153
|
-
${JSON.stringify({id:s.proposal.id,title:s.proposal.title,summary:s.proposal.summary,decisionIds:s.proposal.decisionIds,proposedModel:s.proposal.proposedModel},null,2)}
|
|
154
|
-
\`\`\`
|
|
155
|
-
|
|
156
|
-
## Current Applied Model
|
|
157
|
-
\`\`\`json
|
|
158
|
-
${JSON.stringify(s.currentModel??null,null,2)}
|
|
159
|
-
\`\`\`
|
|
160
|
-
|
|
161
|
-
## Existing Eval Suite
|
|
162
|
-
\`\`\`json
|
|
163
|
-
${JSON.stringify(s.existingSuite,null,2)}
|
|
164
|
-
\`\`\`
|
|
165
|
-
|
|
166
|
-
## Instructions
|
|
167
|
-
1. Generate only evals that directly project the approved model proposal into observable checks.
|
|
168
|
-
2. Prefer a small number of durable evals over broad coverage. Avoid duplicates of existing evals.
|
|
169
|
-
3. Each eval should include concise assertions that can be judged on a page or codebase.
|
|
170
|
-
4. Set every generated eval status to "pending" so the designer can approve, edit, or reject it.
|
|
171
|
-
5. Cite the proposal's decision IDs in sourceDecisionIds.
|
|
172
|
-
6. End with exactly one <eval_proposals> block containing valid JSON.
|
|
173
|
-
|
|
174
|
-
Each eval must use this shape:
|
|
175
|
-
|
|
176
|
-
\`\`\`json
|
|
177
|
-
{
|
|
178
|
-
"id": "eval-short-stable-id",
|
|
179
|
-
"title": "Short human-readable name",
|
|
180
|
-
"status": "pending",
|
|
181
|
-
"category": "component",
|
|
182
|
-
"prompt": "The eval instruction an agent should satisfy.",
|
|
183
|
-
"assertions": ["Observable expectation 1", "Observable expectation 2"],
|
|
184
|
-
"rationale": "Why this eval projects the approved model value.",
|
|
185
|
-
"sourceDecisionIds": ["decision-id"],
|
|
186
|
-
"sourceThreadIds": ["${s.proposal.threadId??""}"]
|
|
187
|
-
}
|
|
188
|
-
\`\`\`
|
|
189
|
-
|
|
190
|
-
Allowed categories: component, layout, copy, interaction, visual, workflow.
|
|
191
|
-
|
|
192
|
-
<eval_proposals>
|
|
193
|
-
[]
|
|
194
|
-
</eval_proposals>`}function co(s){let e=s.annotations??[],n=s.resolutions??[],t=s.editEvents??[],o=e.map(l=>l.instruction).filter(Boolean).join(`
|
|
195
|
-
`),i=n.map(l=>{let f=l.finalScope??l.inferredScope??l.declaredScope;return`- ${l.status}: ${l.summary}${f?` [${f.breadth}/${f.target}]`:""}`}).join(`
|
|
196
|
-
`),a=[...new Set([...n.flatMap(l=>l.filesModified??[]),...t.map(l=>l.filePath).filter(l=>!!l)])].slice(0,12);return`### Decision ${s.id}
|
|
197
|
-
Thread: ${s.threadId??"none"}
|
|
198
|
-
Created: ${new Date(s.createdAt).toISOString()}
|
|
199
|
-
URL: ${s.url||"unknown"}
|
|
200
|
-
Instructions:
|
|
201
|
-
${et(o||"(none)",sn)}
|
|
202
|
-
Resolutions:
|
|
203
|
-
${et(i||"(none)",sn)}
|
|
204
|
-
Files: ${a.length>0?a.join(", "):"none"}`}function uo(s){let n=s.messages.slice(0,2).concat(s.messages.length>4?s.messages.slice(-2):s.messages.slice(2)).map(t=>{let o=t.feedbackSummary??t.replyToQuestion??t.question??t.responseText??"",i=t.resolutions?.map(a=>`${a.status}: ${a.summary}`).join("; ")??"";return`- ${t.role}: ${et(o||i||"(no text)",500)}`}).join(`
|
|
205
|
-
`);return`### Thread ${s.id}
|
|
206
|
-
Messages: ${s.messages.length}
|
|
207
|
-
Updated: ${new Date(s.updatedAt).toISOString()}
|
|
208
|
-
${n}`}function ye(s){return typeof s=="string"?s.trim():""}function Te(s){return Array.isArray(s)?s.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function po(s){let e=ye(s);return e==="component"||e==="layout"||e==="copy"||e==="interaction"||e==="visual"||e==="workflow"?e:"visual"}function fo(s){let e=ye(s);return e==="pending"||e==="approved"||e==="rejected"?e:null}function ho(s){let e=ye(s);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function mo(s,e){let t=(Array.isArray(s)?s:[]).map(o=>{if(!o||typeof o!="object")return null;let i=o,a=ye(i.assertion);return a?{assertion:a,status:ho(i.status)??"needs_review",summary:ye(i.summary)||pn("needs_review"),evidence:Te(i.evidence)}:null}).filter(o=>o!==null);return t.length>0?t:e.map(o=>({assertion:o,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function go(s){return s.some(e=>e.status==="fail")?"fail":s.some(e=>e.status==="needs_review")?"needs_review":"pass"}function yo(s){if(!s||typeof s!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=s,n=ye(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Te(e.evidenceTypes).length>0?Te(e.evidenceTypes):["screenshot"]}}function pn(s){return s==="pass"?"The current page appears to satisfy this eval.":s==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function vo(s){return fn(s).slice(0,48)}function fn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function et(s,e){return s.length>e?`${s.slice(0,e)}...`:s}import{randomUUID as hn}from"crypto";import{mkdir as bt,readFile as tt,writeFile as Ie}from"fs/promises";import{dirname as It,join as Ne}from"path";var ae="[Materializer]",mn={version:2,decisions:{},lastRunAt:null,lastRunDecisionIds:[],lastRunError:null},wo={version:1,runs:[]},So={version:1,updatedAt:0,proposals:[]},xo=12;function bo(s){return Array.isArray(s)?s.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 Je(s){let e=[];for(let n of s){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${ae} 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(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${ae} Rule count ${e.length} exceeds cap of 30`),e}function Io(s,e,n){return{decisionCount:s.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Po(s,e){let n=new Set(e),t=new Set,o=Array.isArray(s.rules)?s.rules:[];for(let l of o){if(!l||typeof l!="object")continue;let f=l.sources;if(Array.isArray(f))for(let v of f)typeof v=="string"&&n.has(v)&&t.add(v)}let i=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?s.tokens:{},a=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?s.components:{};return{ruleCount:o.length,tokenSectionCount:Object.keys(i).length,componentCount:Object.keys(a).length,coveredDecisionIds:[...t],uncoveredDecisionIds:e.filter(l=>!t.has(l))}}function ko(s){if(s!==void 0)return JSON.parse(JSON.stringify(s))}function Ro(s,e,n){let t=s[e];if(t&&typeof t=="object")return t;let o=typeof n=="number"?[]:{};return s[String(e)]=o,o}function Mo(s,e,n){let t=s;for(let i=0;i<e.length-1;i++)t=Ro(t,e[i],e[i+1]);let o=e[e.length-1];t[String(o)]=ko(n)}function Eo(s,e){let n=s;for(let o=0;o<e.length-1;o++){let i=n[String(e[o])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}var nt=class{constructor(e,n,t={}){this.projectRoot=e;this.decisionStore=n;this.options=t;this.cachedIndex=null;this.running=!1;let o=Ne(e,".popmelt");this.indexPath=Ne(o,"materialized.json"),this.runsPath=Ne(o,"materialization-runs.json"),this.proposalsPath=Ne(o,"model-proposals.json"),this.modelPath=Ne(o,"model.json")}get isRunning(){return this.running}async loadModel(){try{let e=await tt(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=bo(n.rules)),n}catch{return null}}async addComponent(e){let n=await this.loadModel();n||(n={tokens:{},components:{},rules:[]}),(!n.components||typeof n.components!="object")&&(n.components={});let t=n.components;return t[e]?{added:!1,alreadyExists:!0}:(t[e]={description:""},await Ie(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Added component "${e}" to model`),{added:!0,alreadyExists:!1})}async updateToken(e,n){let t=await this.loadModel();t||(t={tokens:{},components:{},rules:[]});let o=e.split("."),i=t;for(let f=0;f<o.length-1;f++){let v=o[f];(!i[v]||typeof i[v]!="object")&&(i[v]={}),i=i[v]}let a=o[o.length-1],l;try{l=JSON.parse(n)}catch{l=null}if(l&&typeof l=="object"&&l!==null&&"value"in l)i[a]=l;else{let f=i[a];f&&typeof f=="object"&&f!==null&&"value"in f?f.value=n:i[a]=n}return await Ie(this.modelPath,JSON.stringify(t,null,2)),console.log(`${ae} Updated token "${e}" \u2192 "${n.slice(0,80)}"`),{updated:!0}}async removeToken(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=e.split("."),o=n;for(let a=0;a<t.length-1;a++){let l=t[a];if(!o[l]||typeof o[l]!="object")return{removed:!1};o=o[l]}let i=t[t.length-1];return i in o?(delete o[i],await Ie(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Removed token "${e}" from model`),{removed:!0}):{removed:!1}}async removeComponent(e){let n=await this.loadModel();if(!n)return{removed:!1};let t=n.components;return!t||!t[e]?{removed:!1}:(delete t[e],await Ie(this.modelPath,JSON.stringify(n,null,2)),console.log(`${ae} Removed component "${e}" from model`),{removed:!0})}async getUnmaterializedPatternDecisions(){return(await this.selectUnmaterializedPatternDecisions()).decisions}async selectUnmaterializedPatternDecisions(){let e=await this.loadIndex(),t=(await this.decisionStore.listDecisionIds()).filter(l=>{let f=e.decisions[l];return f?f.status==="applied"||f.status==="merged"||f.status==="rejected"||f.status==="running"||f.status==="queued"||f.status==="proposed"?!1:f.attemptCount<3:!0});if(t.length===0)return{decisions:[],totalCandidateDecisionCount:0};let i=(await this.decisionStore.loadDecisions(t)).filter(l=>l.resolutions.some(f=>(f.finalScope??f.inferredScope)?.breadth==="pattern")),a=i.sort((l,f)=>f.createdAt-l.createdAt).slice(0,xo);return i.length>a.length&&console.log(`${ae} Selected ${a.length}/${i.length} pattern decision(s); remaining decisions stay pending for later runs.`),{decisions:a,totalCandidateDecisionCount:i.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnmaterializedPatternDecisions(),o=t.decisions;if(o.length===0)return{processedIds:[],success:!0};let i=o.map(W=>W.id);console.log(`${ae} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"materialize_started",decisionIds:i});let a=await this.loadModel(),l=$o(o,a),f=Io(o,t.totalCandidateDecisionCount,l);n=hn().slice(0,8);let v={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,decisionIds:i,startedAt:Date.now(),promptStats:f};await this.persistRun(v),await this.updateDecisionStates(i,"running",n);let x=!0,E,B,J;try{let W=`mat-${Date.now()}`,{provider:w,result:q}=this.spawnModelAgent(W,l,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});v={...v,provider:w},await this.persistRun(v);let V=await q;if(!V.success)x=!1,E=V.error,console.error(`${ae} ${w} spawn error:`,E);else{let Q=st(V.text);if(Q){Array.isArray(Q.rules)&&(Q.rules=Je(Q.rules)),B=Po(Q,i);let K=await this.createModelProposal({decisionIds:i,proposedModel:Q,runId:n,threadId:e.threadId,provider:w,model:e.model??this.options.model});J=K.id,console.log(`${ae} Created model proposal ${K.id} for ${i.length} decision(s)`)}else x=!1,E="No <model> block found in response",console.error(`${ae} ${E}`)}}catch(W){x=!1,E=W instanceof Error?W.message:String(W),console.error(`${ae} Error:`,E)}let U=await this.loadIndex();return U.lastRunAt=Date.now(),U.lastRunDecisionIds=i,U.lastRunError=E??null,await this.persistIndex(U),await this.updateDecisionStates(i,x?"proposed":"failed",n,E),await this.persistRun({...v,status:x?"proposed":"failed",completedAt:Date.now(),error:E,outputStats:B,proposalId:J}),this.options.onEvent?.({type:"materialize_done",decisionIds:i,success:x,error:E}),{processedIds:i,success:x,error:E,runId:n,proposalId:J}}finally{this.running=!1}}async consolidate(e={}){if(this.running)return{success:!1,error:"Already running"};this.running=!0;try{let n=await this.loadModel();if(!n)return{success:!1,error:"No model exists"};let t=Co(n),{provider:o,result:i}=this.spawnModelAgent(`consolidate-${Date.now()}`,t,e,{maxTurns:this.options.maxTurns??3,maxBudgetUsd:this.options.maxBudgetUsd??.3,allowedTools:[]}),a=await i;if(!a.success)return console.error(`${ae} ${o} consolidation spawn error:`,a.error),{success:!1,error:a.error};let l=st(a.text);return l?(Array.isArray(l.rules)&&(l.rules=Je(l.rules)),!l.tokens&&n.tokens&&(l.tokens=n.tokens),!l.components&&n.components&&(l.components=n.components),await Ie(this.modelPath,JSON.stringify(l,null,2)),console.log(`${ae} Consolidation complete with ${o} \u2192 ${this.modelPath}`),{success:!0}):(console.error(`${ae} No <model> block in consolidation response`),{success:!1,error:"No <model> block found"})}catch(n){let t=n instanceof Error?n.message:String(n);return console.error(`${ae} Consolidation error:`,t),{success:!1,error:t}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Je(e.rules)),await Ie(this.modelPath,JSON.stringify(e,null,2)),console.log(`${ae} Model written \u2192 ${this.modelPath}`)}async loadIndex(){if(this.cachedIndex)return this.cachedIndex;try{let e=await tt(this.indexPath,"utf-8"),n=JSON.parse(e);if(n.version===2&&n.decisions)return this.cachedIndex=n,this.cachedIndex;if(n.version===1&&Array.isArray(n.materializedIds)){let t=Date.now(),o=Object.fromEntries(n.materializedIds.map(i=>[i,{status:"applied",runIds:[],attemptCount:1,updatedAt:t}]));return this.cachedIndex={version:2,decisions:o,lastRunAt:n.lastRunAt??null,lastRunDecisionIds:n.lastRunDecisionIds??[],lastRunError:n.lastRunError??null,materializedIds:n.materializedIds},this.cachedIndex}}catch{return this.cachedIndex={...mn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}return this.cachedIndex={...mn,decisions:{},lastRunDecisionIds:[]},this.cachedIndex}async persistIndex(e){e.materializedIds=Object.entries(e.decisions).filter(([,n])=>n.status==="applied"||n.status==="merged").map(([n])=>n),this.cachedIndex=e;try{await bt(It(this.indexPath),{recursive:!0}),await Ie(this.indexPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write index:`,n)}}async loadRuns(){try{let e=await tt(this.runsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.runs))return n}catch{}return{...wo,runs:[]}}async loadModelProposals(){try{let e=await tt(this.proposalsPath,"utf-8"),n=JSON.parse(e);if(n.version===1&&Array.isArray(n.proposals))return n}catch{}return{...So,proposals:[]}}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,o)=>o.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,o)=>t.createdAt-o.createdAt||t.updatedAt-o.updatedAt)}async applyModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;if(n.status==="dismissed")return n;await this.writeModel(n.proposedModel);let t=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0});return await this.updateDecisionStates(n.decisionIds,"applied",n.runId??e),t}async applySelectedModelProposal(e,n,t){let o=await this.findModelProposal(e);if(!o)return null;if(o.status==="dismissed")return o;let i=await this.loadModel()??{};for(let l of n)!Array.isArray(l.path)||l.path.length===0||(l.remove?Eo(i,l.path):Mo(i,l.path,l.value));await this.writeModel(i);let a=await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),error:void 0,selectedChanges:t});return await this.updateDecisionStates(o.decisionIds,"applied",o.runId??e),a}async dismissModelProposal(e){let n=await this.findModelProposal(e);if(!n)return null;let t=await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()});return await this.updateDecisionStates(n.decisionIds,"rejected",n.runId??e),t}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let o=new Set(t.generatedEvalIds??[]);for(let i of n)o.add(i);return this.updateModelProposal(e,{generatedEvalIds:[...o]})}async createModelProposal(e){let n={id:hn().slice(0,8),status:"pending",title:To(e.proposedModel),summary:Ao(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,provider:e.provider,model:e.model,proposedModel:e.proposedModel,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(o=>o.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),o=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(o={...i,...n,updatedAt:Date.now()},o)),o?(t.updatedAt=Date.now(),await this.persistModelProposals(t),o):null}async persistModelProposals(e){try{await bt(It(this.proposalsPath),{recursive:!0}),await Ie(this.proposalsPath,JSON.stringify(e,null,2))}catch(n){console.error(`${ae} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(o=>o.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await bt(It(this.runsPath),{recursive:!0}),await Ie(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${ae} Failed to write materialization run:`,n)}}async updateDecisionStates(e,n,t,o){let i=await this.loadIndex(),a=Date.now();for(let l of e){let f=i.decisions[l],v=f?.runIds.includes(t)?f.runIds:[...f?.runIds??[],t];i.decisions[l]={status:n,runIds:v,error:o,attemptCount:n==="running"?f?.attemptCount??0:(f?.attemptCount??0)+1,updatedAt:a}}await this.persistIndex(i)}spawnModelAgent(e,n,t,o){let i=t.provider??this.options.provider??"claude",a=this.options.onEvent?(l,f)=>this.options.onEvent?.(l):void 0;return i==="codex"?{provider:"codex",...Ve(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:Qe(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:a})}:(i==="copilot"&&console.warn(`${ae} Copilot materialization is not available yet; falling back to Claude.`),{provider:"claude",...Xe(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:a})})}};function To(s){let n=(Array.isArray(s.rules)?s.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Ao(s,e){let n=Array.isArray(s.rules)?s.rules.length:0,t=s.tokens&&typeof s.tokens=="object"&&!Array.isArray(s.tokens)?Object.keys(s.tokens).length:0,o=s.components&&typeof s.components=="object"&&!Array.isArray(s.components)?Object.keys(s.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function st(s){let e=s.match(/<model>\s*([\s\S]*?)\s*<\/model>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}function $o(s,e){let n=s.map(i=>{let l=i.resolutions.filter(x=>(x.finalScope??x.inferredScope)?.breadth==="pattern").map(x=>{let B=(x.finalScope??x.inferredScope)?.target??"unknown",J=x.filesModified?.join(", ")??"none";return`- **${x.summary}** [scope: pattern/${B}]
|
|
209
|
-
Files modified: ${J}`}).join(`
|
|
210
|
-
`),f=i.annotations.map(x=>x.instruction).filter(Boolean).join(`
|
|
211
|
-
`),v=i.gitDiff?`
|
|
212
|
-
\`\`\`diff
|
|
213
|
-
${i.gitDiff.slice(0,2e3)}
|
|
214
|
-
\`\`\``:"";return`### Decision ${i.id} (${new Date(i.createdAt).toISOString()})
|
|
215
|
-
Page: ${i.url}
|
|
216
|
-
${l}
|
|
217
|
-
${v}
|
|
218
|
-
${f?`
|
|
219
|
-
Original instructions:
|
|
220
|
-
${f}`:""}`}).join(`
|
|
221
|
-
|
|
222
|
-
`),t=s.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
|
|
97
|
+
`),t=o.map(s=>s.id);return`You are extracting a local design model from accumulated design decisions.
|
|
223
98
|
|
|
224
99
|
## Instructions
|
|
225
100
|
1. Review the current model (if any) and the new decisions below.
|
|
226
|
-
2. Determine
|
|
227
|
-
3.
|
|
228
|
-
4.
|
|
101
|
+
2. Determine the smallest concrete set of design-token, component-pattern, and rule changes supported by those decisions.
|
|
102
|
+
3. Attribute every change to one or more accepted decision IDs from this prompt.
|
|
103
|
+
4. Output no more than 40 changes as a JSON array inside <model-changes> tags.
|
|
104
|
+
5. Do not edit files or run commands. Return only the <model-changes> block.
|
|
229
105
|
|
|
230
106
|
${e?`## Current Model
|
|
231
107
|
\`\`\`json
|
|
232
108
|
${JSON.stringify(e,null,2)}
|
|
233
109
|
\`\`\`
|
|
234
110
|
|
|
235
|
-
|
|
111
|
+
Use this only to understand the existing state and avoid proposing unchanged values.`:"No model exists yet. Propose only the entries directly supported by the accepted decisions below."}
|
|
236
112
|
|
|
237
|
-
##
|
|
113
|
+
## Accepted Decisions to Project
|
|
238
114
|
${n}
|
|
239
115
|
|
|
240
116
|
## Output Format
|
|
241
|
-
|
|
242
|
-
- \`
|
|
243
|
-
- \`
|
|
244
|
-
- \`
|
|
117
|
+
Each change is a JSON object with:
|
|
118
|
+
- \`id\`: stable descriptive identifier for this proposed change
|
|
119
|
+
- \`path\`: JSON path in the derived model; the first segment must be \`tokens\`, \`components\`, or \`rules\`
|
|
120
|
+
- \`label\`: short human-readable label
|
|
121
|
+
- \`value\`: complete JSON value to set at that path
|
|
122
|
+
- \`decisionIds\`: one or more IDs from ${JSON.stringify(t)} that directly support the change
|
|
123
|
+
- \`rationale\`: concise explanation of the projection from decision to model entry
|
|
124
|
+
|
|
125
|
+
For tokens and components, choose the narrowest durable path. For rules, emit a single change at path \`["rules"]\` whose value is the complete next rules array. Preserve unchanged rule IDs and order, and keep the array at 30 rules maximum.
|
|
245
126
|
|
|
246
127
|
### Rule format
|
|
247
128
|
Each rule is a JSON object:
|
|
@@ -261,163 +142,99 @@ Fields:
|
|
|
261
142
|
- **Keep:** Enforceable patterns, constraints, relationships between elements, accessibility requirements.
|
|
262
143
|
|
|
263
144
|
Example:
|
|
264
|
-
<model>
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
"
|
|
268
|
-
"
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
},
|
|
277
|
-
"rules": [
|
|
278
|
-
{ "id": "a1b2c3d4", "scope": "typography", "text": "Body text uses Inter at 16px/1.5", "sources": ["d-abc123"] },
|
|
279
|
-
{ "id": "e5f6a7b8", "scope": "color", "text": "Primary actions use the primary color token", "sources": ["d-def456"] }
|
|
280
|
-
]
|
|
281
|
-
}
|
|
282
|
-
</model>
|
|
145
|
+
<model-changes>
|
|
146
|
+
[
|
|
147
|
+
{
|
|
148
|
+
"id": "primary-color",
|
|
149
|
+
"path": ["tokens", "colors", "primary"],
|
|
150
|
+
"label": "Primary color",
|
|
151
|
+
"value": "#3b82f6",
|
|
152
|
+
"decisionIds": [${JSON.stringify(t[0]??"")}],
|
|
153
|
+
"rationale": "The accepted decision establishes this as the shared primary action color."
|
|
154
|
+
}
|
|
155
|
+
]
|
|
156
|
+
</model-changes>
|
|
283
157
|
|
|
284
158
|
## Guidelines
|
|
285
159
|
- Map token-scoped decisions to \`tokens\`, component-scoped to \`components\`.
|
|
286
160
|
- Extract clear, enforceable rules into the \`rules\` array as structured objects.
|
|
287
|
-
-
|
|
161
|
+
- Do not silently override conflicting existing values; propose the explicit change for owner review.
|
|
288
162
|
- Keep the model concise \u2014 only include patterns with clear evidence from decisions.
|
|
289
|
-
- Do
|
|
163
|
+
- Do not emit unchanged entries or copy the complete model.
|
|
164
|
+
- Do NOT output resolution or question blocks. Just output the <model-changes> block.
|
|
290
165
|
- Spacing tokens can be plain strings ("8px") or objects with code bindings:
|
|
291
166
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
292
167
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
293
168
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
294
|
-
Include property and bindings when the decision context has class-level evidence.`}function
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
## Instructions
|
|
302
|
-
1. Review all current rules.
|
|
303
|
-
2. Merge rules that cover the same concern into single, clear rules.
|
|
304
|
-
3. Remove rules that are:
|
|
305
|
-
- Workflow advice ("After SSR fixes, re-verify headless output")
|
|
306
|
-
- Instance-level observations ("Footer tagline is 'Design everything.'")
|
|
307
|
-
- Restating tokens or components already defined elsewhere in the model
|
|
308
|
-
- Procedural instructions rather than design constraints
|
|
309
|
-
4. Output the full model with consolidated rules.
|
|
310
|
-
5. Do not edit files or run commands. Return only the <model> block.
|
|
311
|
-
|
|
312
|
-
## Rule format
|
|
313
|
-
Each rule MUST be a JSON object:
|
|
314
|
-
{ "id": "a1b2c3d4", "scope": "<scope>", "text": "<rule text>", "sources": ["<decision-id>", ...] }
|
|
315
|
-
|
|
316
|
-
- \`id\`: 8-char hex. Preserve the ID of the most representative source rule when merging. Generate new 8-char hex IDs for genuinely new rules.
|
|
317
|
-
- \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
|
|
318
|
-
- \`text\`: Clear, enforceable design constraint
|
|
319
|
-
- \`sources\`: Merge source arrays when combining rules
|
|
320
|
-
|
|
321
|
-
## Hard cap: 30 rules maximum.
|
|
322
|
-
|
|
323
|
-
Prioritize rules that are:
|
|
324
|
-
- Enforceable constraints (not preferences)
|
|
325
|
-
- Cross-cutting (affect many elements)
|
|
326
|
-
- Not already captured by tokens or component definitions in the model
|
|
327
|
-
|
|
328
|
-
## Output
|
|
329
|
-
Output the complete model inside <model> tags. Preserve tokens and components as-is \u2014 only rules change.
|
|
330
|
-
|
|
331
|
-
<model>
|
|
332
|
-
{ "tokens": { ... }, "components": { ... }, "rules": [ ... ] }
|
|
333
|
-
</model>`}function gn(s){return`You are a design system curator reviewing a project's design model. Your job is to propose improvements to the rules \u2014 merging duplicates, filling gaps, removing noise.
|
|
334
|
-
|
|
335
|
-
## Current Model
|
|
336
|
-
\`\`\`json
|
|
337
|
-
${JSON.stringify(s,null,2)}
|
|
338
|
-
\`\`\`
|
|
339
|
-
|
|
340
|
-
## Instructions
|
|
341
|
-
1. Review all current rules, tokens, and components.
|
|
342
|
-
2. Propose specific changes \u2014 additions, merges, removals \u2014 with brief reasoning for each.
|
|
343
|
-
3. Present your proposals as clear text so the developer can review them.
|
|
344
|
-
4. Do NOT output a <model> block yet. First get the developer's approval.
|
|
345
|
-
|
|
346
|
-
## Output format
|
|
347
|
-
- List each proposed change as a numbered item with a short rationale.
|
|
348
|
-
- Group by action: **Merge**, **Add**, **Remove**, **Reword**.
|
|
349
|
-
- After your proposals, output a <question> block asking the developer to approve, adjust, or reject.
|
|
350
|
-
|
|
351
|
-
Example:
|
|
352
|
-
**Merge**
|
|
353
|
-
1. Rules "Body text uses Inter 16px" and "Paragraph text is Inter 16/1.5" \u2192 "Body/paragraph text uses Inter at 16px/1.5" (they say the same thing)
|
|
354
|
-
|
|
355
|
-
**Remove**
|
|
356
|
-
2. "After fixing SSR, re-verify headless output" \u2014 workflow advice, not a design constraint
|
|
357
|
-
|
|
358
|
-
**Add**
|
|
359
|
-
3. "Primary actions use the primary color token; secondary actions use gray-500" \u2014 implied by token usage but not codified
|
|
360
|
-
|
|
361
|
-
<question>
|
|
362
|
-
These are my proposed rule changes. Would you like to approve all of them, adjust specific items, or add more? Once you're happy I'll output the final model.
|
|
363
|
-
</question>
|
|
364
|
-
|
|
365
|
-
## After approval
|
|
366
|
-
When the developer approves (says "yes", "looks good", "go ahead", etc.), output the complete updated model inside <model> tags \u2014 the full JSON with tokens, components, and the revised rules array. Do NOT output partial models. Preserve tokens and components as-is unless the developer asks to change them.`}var ot=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 o of this.listeners)o(e,n,t)}cancelJob(e){let n=this.queue.findIndex(o=>o.id===e);if(n>=0){let[o]=this.queue.splice(n,1);return o?(o.status="cancelled",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),o):null}let 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:"materialize_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 _o}from"child_process";import{readFile as kt}from"fs/promises";import{homedir as it}from"os";import{join as he}from"path";var Rt=/popmelt/i,Do=/chrome|devtools/i;function Re(){return{found:!1,name:null,scope:null,disabled:!1}}function Ae(s,e,n=!1){return{found:!0,name:s,scope:e,disabled:n}}function ze(s){for(let e of Object.keys(s))if(Rt.test(e))return e;return null}async function rt(s){try{let e=await kt(s,"utf-8");return JSON.parse(e)}catch{return null}}async function Mt(s){let e=it(),n=await rt(he(e,".claude.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let i=ze(o.mcpServers);if(i)return Ae(i,"user")}if(o.projects&&typeof o.projects=="object"){let a=o.projects[s];if(a&&typeof a=="object"){let l=a;if(l.mcpServers&&typeof l.mcpServers=="object"){let f=ze(l.mcpServers);if(f){let v=Array.isArray(l.disabledMcpjsonServers)&&l.disabledMcpjsonServers.some(x=>Rt.test(x));return Ae(f,"project",v)}}}}}let t=await rt(he(s,".mcp.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let a=ze(o.mcpServers);if(a){let l=await yn(s,a);return Ae(a,"mcp.json",l)}}let i=ze(o);if(i&&i!=="mcpServers"){let a=await yn(s,i);return Ae(i,"mcp.json",a)}}return Re()}async function yn(s,e){let n=he(s,".claude","settings.local.json"),t=await rt(n);if(t&&typeof t=="object"){let o=t;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(i=>i===e)}return!1}var Oo=/^\[mcp_servers\.([^\]]+)\]/;function No(s){return s.replace(/^"(.+)"$/,"$1")}function Jo(s){return/\.tools\./.test(s)||/"\.tools\./.test(s)}function wn(s){let e=s.split(`
|
|
367
|
-
`),n=[],t=null;for(let o of e){let i=o.match(Oo);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
368
|
-
`)}),t={name:i[1],bodyLines:[]}):o.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
369
|
-
`)}),t=null):t&&t.bodyLines.push(o)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
370
|
-
`)}),n}function Sn(s){return/enabled\s*=\s*false/i.test(s)}async function Et(s){let e=process.env.CODEX_HOME||he(it(),".codex"),n=await vn(he(e,"config.toml"),"user");if(n.found)return n;let t=await vn(he(s,".codex","config.toml"),"project");return t.found?t:Re()}async function zo(s,e){let n=process.env.CODEX_HOME||he(it(),".codex"),t=new Set;for(let o of[he(n,"config.toml"),he(s,".codex","config.toml")])try{let i=await kt(o,"utf-8");for(let a of wn(i)){if(Jo(a.name)||Sn(a.body))continue;let l=No(a.name);e.test(l)&&t.add(l)}}catch{}return[...t]}async function xn(s){return zo(s,Do)}async function Tt(s,e="copilot"){let n=await Bo(e);if(n.found)return n;let t=process.env.COPILOT_HOME||he(it(),".copilot"),o=await Pt(he(t,"mcp-config.json"),"user");if(o.found)return o;let i=await Pt(he(s,".mcp.json"),"mcp.json");if(i.found)return i;let a=await Pt(he(s,".github","mcp.json"),"mcp.json");return a.found?a:Re()}async function Bo(s){try{let e=await new Promise((n,t)=>{_o(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return bn(JSON.parse(e),"user")}catch{return Re()}}async function Pt(s,e){let n=await rt(s);return bn(n,e)}function bn(s,e){if(!s||typeof s!="object")return Re();let n=s,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,o=ze(t);return o?Ae(o,e):Re()}async function vn(s,e){try{let n=await kt(s,"utf-8"),t=wn(n);for(let o of t)if(Rt.test(o.name)){let i=Sn(o.body);return Ae(o.name,e,i)}}catch{}return Re()}import{execFile as In}from"child_process";import{mkdir as Fo,readFile as Pn,writeFile as kn}from"fs/promises";import{homedir as Rn}from"os";import{dirname as jo,join as At}from"path";var $t="https://mcp.popmelt.com/mcp";async function Mn(s=$t){let e=At(Rn(),".claude.json"),n;try{let o=await Pn(e,"utf-8");n=JSON.parse(o)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let o of Object.keys(t))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:s},await kn(e,JSON.stringify(n,null,2)+`
|
|
371
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function En(s=$t){let e=process.env.CODEX_HOME||At(Rn(),".codex"),n=At(e,"config.toml"),t;try{t=await Pn(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Fo(jo(n),{recursive:!0});let o=`
|
|
169
|
+
Include property and bindings when the decision context has class-level evidence.`}var kn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as Ki}from"child_process";import{readFile as ho}from"fs/promises";import{homedir as Rn}from"os";import{join as Fe}from"path";var go=/popmelt/i,Qi=/chrome|devtools/i;function vt(){return{found:!1,name:null,scope:null,disabled:!1}}function jt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Kt(o){for(let e of Object.keys(o))if(go.test(e))return e;return null}async function Pn(o){try{let e=await ho(o,"utf-8");return JSON.parse(e)}catch{return null}}async function yo(o){let e=Rn(),n=await Pn(Fe(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 jt(s,"user")}if(r.projects&&typeof r.projects=="object"){let i=r.projects[o];if(i&&typeof i=="object"){let c=i;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Kt(c.mcpServers);if(d){let l=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(g=>go.test(g));return jt(d,"project",l)}}}}}let t=await Pn(Fe(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 c=await hr(o,i);return jt(i,"mcp.json",c)}}let s=Kt(r);if(s&&s!=="mcpServers"){let i=await hr(o,s);return jt(s,"mcp.json",i)}}return vt()}async function hr(o,e){let n=Fe(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 Xi=/^\[mcp_servers\.([^\]]+)\]/;function Yi(o){return o.replace(/^"(.+)"$/,"$1")}function Zi(o){return/\.tools\./.test(o)||/"\.tools\./.test(o)}function yr(o){let e=o.split(`
|
|
170
|
+
`),n=[],t=null;for(let r of e){let s=r.match(Xi);s?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
171
|
+
`)}),t={name:s[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
172
|
+
`)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
173
|
+
`)}),n}function vr(o){return/enabled\s*=\s*false/i.test(o)}async function vo(o){let e=process.env.CODEX_HOME||Fe(Rn(),".codex"),n=await gr(Fe(e,"config.toml"),"user");if(n.found)return n;let t=await gr(Fe(o,".codex","config.toml"),"project");return t.found?t:vt()}async function ea(o,e){let n=process.env.CODEX_HOME||Fe(Rn(),".codex"),t=new Set;for(let r of[Fe(n,"config.toml"),Fe(o,".codex","config.toml")])try{let s=await ho(r,"utf-8");for(let i of yr(s)){if(Zi(i.name)||vr(i.body))continue;let c=Yi(i.name);e.test(c)&&t.add(c)}}catch{}return[...t]}async function wr(o){return ea(o,Qi)}async function wo(o,e="copilot"){let n=await ta(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Fe(Rn(),".copilot"),r=await fo(Fe(t,"mcp-config.json"),"user");if(r.found)return r;let s=await fo(Fe(o,".mcp.json"),"mcp.json");if(s.found)return s;let i=await fo(Fe(o,".github","mcp.json"),"mcp.json");return i.found?i:vt()}async function ta(o){try{let e=await new Promise((n,t)=>{Ki(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,s)=>{if(r){t(r);return}n(s)})});return Ir(JSON.parse(e),"user")}catch{return vt()}}async function fo(o,e){let n=await Pn(o);return Ir(n,e)}function Ir(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?jt(r,e):vt()}async function gr(o,e){try{let n=await ho(o,"utf-8"),t=yr(n);for(let r of t)if(go.test(r.name)){let s=vr(r.body);return jt(r.name,e,s)}}catch{}return vt()}import{execFile as br}from"child_process";import{mkdir as na,readFile as xr,writeFile as Sr}from"fs/promises";import{homedir as kr}from"os";import{dirname as oa,join as Io}from"path";var bo="https://mcp.popmelt.com/mcp";async function Pr(o=bo){let e=Io(kr(),".claude.json"),n;try{let r=await xr(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 Sr(e,JSON.stringify(n,null,2)+`
|
|
174
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Rr(o=bo){let e=process.env.CODEX_HOME||Io(kr(),".codex"),n=Io(e,"config.toml"),t;try{t=await xr(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await na(oa(n),{recursive:!0});let r=`
|
|
372
175
|
[mcp_servers.popmelt]
|
|
373
|
-
url = "${
|
|
374
|
-
`;return await kn(n,t+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Tn(s=$t,e="copilot"){let n=await Lo(e);if(Uo(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,o)=>{In(e,["mcp","add","--transport","http","--json","popmelt",s],{encoding:"utf-8",timeout:1e4},i=>{if(i){o(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function Lo(s){try{let e=await new Promise((n,t)=>{In(s,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,i)=>{if(o){t(o);return}n(i)})});return JSON.parse(e)}catch{return null}}function Uo(s){if(!s||typeof s!="object")return!1;let e=s,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var at=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 o=this.leases.get(e),i={id:e,ownerPid:n,createdAt:o?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,o]of this.leases)o.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()}};async function lt(s){let n=(s.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],o=await Wo(s),i=Buffer.from(`--${t}`),a=Buffer.from(`--${t}--`),l,f,v,x,E,B,J,U,W,w,q,V,Q,K,z=[],Z=[],D=0,A=[];for(;D<o.length;){let k=o.indexOf(i,D);if(k===-1)break;let R=k+i.length;if(o.slice(k,k+a.length).equals(a))break;let N=R;o[N]===13&&o[N+1]===10&&(N+=2);let C=o.indexOf(`\r
|
|
176
|
+
url = "${o}"
|
|
177
|
+
`;return await Sr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Tr(o=bo,e="copilot"){let n=await ra(e);if(sa(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{br(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 ra(o){try{let e=await new Promise((n,t)=>{br(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 sa(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var Tn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let 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 Eo,readFile as _t,writeFile as Mo}from"fs/promises";import{join as pt}from"path";var ia=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function xo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function jn(o){return new Set(xo(o).split(" ").filter(e=>e.length>2&&!ia.has(e)))}function jr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function aa(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 ca(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(xo).filter(Boolean),s=jn([e.action,e.text].filter(Boolean).join(" "));for(let i of o){if(t.has(i.id)){n.set(i.id,{subjectId:i.id,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of aa(i)){let l=xo(d.value);for(let b of r){let I=l===b?95:l.includes(b)||b.includes(l)?75:0;I>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:I>=90?"exact":"strong",matchedBy:d.by,score:I})}let R=["/","#","[","]","="].some(b=>d.value.includes(b))?0:Math.round(jr(jn(l),s)*55);R>=30&&R>(c?.score??0)&&(c={subjectId:i.id,label:i.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}c&&n.set(i.id,c)}return n}function da(o,e){let n=new Set(o.sourceRefs.filter(i=>i.kind==="iteration").map(i=>i.id)),t=new Set(o.sourceRefs.filter(i=>i.kind==="thread").map(i=>i.id)),r=e.filter(i=>i.iterationIds.some(c=>n.has(c))||i.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let s=new Set(r.map(i=>i.state));return{state:s.size>1?"mixed":s.has("completed")?"completed":"attempted",attemptIds:r.map(i=>i.id)}}function la(o){return Math.ceil(JSON.stringify(o).length/4)}function Qt(o,e){let n=o.records.filter(h=>h.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,s=o.records.filter(h=>{if(h.recordType!=="proposal"||r&&!r.has(h.id))return!1;if(h.state==="pending")return!0;if(h.state!=="deferred")return!1;let f=[...o.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===h.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(h=>h.recordType==="implementation_attempt"),c=ca(n,e),d=[...c.values()].sort((h,f)=>f.score-h.score),l=jn([e.action,e.text].filter(Boolean).join(" ")),g=s.flatMap(h=>{let f=h.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),v=Math.max(0,...f.map(A=>A.score)),x=Math.round(jr(jn(h.claim),l)*35),S=v+x;return S>=50?[{proposal:h,proposalMatches:f,score:S}]:[]}).sort((h,f)=>f.score-h.score||h.proposal.id.localeCompare(f.proposal.id)),R=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),I=[],y=0;for(let h of g){if(I.length>=R)break;let f=h.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${h.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:h.proposalMatches.length?`Historical proposal intersects ${h.proposalMatches.map(S=>S.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:h.proposalMatches.map(({score:S,...A})=>A)},proposal:{id:h.proposal.id,claim:h.proposal.claim,state:h.proposal.state,proposedKind:h.proposal.proposedKind,subjectIds:h.proposal.subjects.map(S=>S.subjectId),origin:h.proposal.origin.mode},authority:"unaccepted",presentation:h.score>=100&&["constraint","rule"].includes(h.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:da(h.proposal,i),evidence:{sourceCount:h.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:h.proposal.id},...f]},x={...v,estimatedTokens:la(v)};if(y+x.estimatedTokens>b)break;I.push(x),y+=x.estimatedTokens}let p=Math.max(0,g.length-I.length);return{packets:I,subjectMatches:d.map(({score:h,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:g.length,omittedPacketCount:p,maxEstimatedTokens:b,estimatedTokens:y},uncertainty:c.size===0?"subject_unresolved":g.length===0?"no_relevant_pending_proposal":void 0}}var pa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function So(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function En(o){return new Set(So(o).split(" ").filter(e=>e.length>2&&!pa.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 ua(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(So).filter(Boolean),r=En([e.action,e.text].filter(Boolean).join(" ")),s=[];for(let i of o){if(n.has(i.id)){s.push({subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:i.label,by:"semantic"},...i.aliases.map(l=>({value:l,by:"alias"})),...i.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let g=So(l.value);for(let I of t){let y=g===I?95:g.includes(I)||I.includes(g)?75:0;y>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:y>=90?"exact":"strong",matchedBy:l.by,score:y})}let b=["/","#","[","]","="].some(I=>l.value.includes(I))?0:Math.round(Er(En(g),r)*55);b>=30&&b>(c?.score??0)&&(c={subjectId:i.id,subjectType:i.subjectType,label:i.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}c&&s.push(c)}return s.sort((i,c)=>c.score-i.score||i.subjectId.localeCompare(c.subjectId))}function ma(o){return Math.ceil(JSON.stringify(o).length/4)}function Et(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function fa(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 ha(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),s=t[0],i=r?"stale":s?s.state==="passed"?"passing":s.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(s.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:i,attemptIds:t.map(c=>c.id)}}function Mr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(_=>_.recordType==="subject"),s=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,i=o.records.filter(_=>_.recordType==="decision"&&_.state==="active"),c=s?i.filter(_=>s.has(_.id)):i,d=o.records.filter(_=>_.recordType==="implementation_attempt"),l=o.records.filter(_=>_.recordType==="verification_attempt"),g=o.records.filter(_=>_.recordType==="freshness_signal"&&_.state==="open"),R=o.records.filter(_=>_.recordType==="evidence"),b=o.records.filter(_=>_.recordType==="model_entry"),I=[...o.records].reverse().filter(_=>_.recordType==="eval_spec").filter((_,N,T)=>T.findIndex(B=>B.legacyId===_.legacyId)===N),y=ua(r,e),p=new Map(y.map(_=>[_.subjectId,_.score])),h=En([e.action,e.text].filter(Boolean).join(" ")),f=c.flatMap(_=>{let N=Math.max(0,..._.subjects.map(W=>p.get(W.subjectId)??0)),T=Math.round(Er(En(_.claim),h)*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(!Et(_,"excepts")&&!Et(_,"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=g.filter(M=>M.target.entityType==="decision"&&T.has(M.target.entityId)),W=new Set(o.relationships.filter(M=>Et(M,"excepts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).flatMap(M=>[M.from.entityId,M.to.entityId])),H=o.relationships.filter(M=>Et(M,"contradicts")&&T.has(M.from.entityId)&&T.has(M.to.entityId)).map(M=>({id:M.id,decisionIds:[M.from.entityId,M.to.entityId],unresolvedQuestion:M.reason,expansionRefs:[{kind:"record",id:M.id}]})),te=new Set(H.flatMap(M=>M.decisionIds)),ne=R.filter(M=>M.sourceRefs.some(Y=>Y.kind==="record"&&T.has(Y.id))||o.relationships.some(Y=>Y.relationshipType==="supports"&&Y.from.entityType==="evidence"&&Y.from.entityId===M.id&&Y.to.entityType==="decision"&&T.has(Y.to.entityId))),ge=Math.max(0,f.length-_.length),X=o.relationships.some(M=>Et(M,"contradicts")&&S(M)&&(!T.has(M.from.entityId)||!T.has(M.to.entityId))),G=N||ge>0||X,U=[];y.length===0&&(e.subjectHints?.length??0)>0?U.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):_.length===0&&U.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),H.length&&U.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.flatMap(M=>M.expansionRefs)}),ne.some(M=>M.availability!=="available")&&U.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:ne.map(M=>({kind:"record",id:M.id}))}),G&&U.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let he={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:y.map(({score:M,...Y})=>Y),modelEntries:b.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,key:M.key,value:M.value,decisionIds:M.decisionIds})),evalSpecs:I.filter(M=>M.decisionIds.some(Y=>T.has(Y))).map(M=>({id:M.id,legacyId:M.legacyId,state:M.state,title:M.title,assertionCount:M.assertions.length,decisionIds:M.decisionIds,expansionRef:{kind:"record",id:M.id}})),decisions:_.map(M=>({id:M.id,kind:M.kind,claim:M.claim,subjectIds:M.subjects.map(Y=>Y.subjectId),authority:M.authority,effectiveState:te.has(M.id)?"conflicted":W.has(M.id)?"excepted":"active",freshness:B.filter(Y=>Y.target.entityId===M.id).map(Y=>Y.signalType),expansionRef:{kind:"record",id:M.id}})),conflicts:H,uncertainties:U,implementation:_.map(M=>fa(M.id,d)),verification:_.map(M=>ha(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=ma(he),he},J=A(x);for(;J.budget.estimatedTokens>n&&x.length>0;){let _=x.pop(),N=o.relationships.filter(T=>Et(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 ga=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Mt(o){return ga.test(o)}function ya(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 ko(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function je(o,e,n){Mt(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 va={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"])},wa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ia(o,e,n){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(o,`${n}.participantId`,e.participantId),je(o,`${n}.entity.entityId`,e.entity.entityId),lt(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=va[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(wa.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 ba(o,e,n,t){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(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"&&ko(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&&ko(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&ko(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function xa(o,e,n){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(o,`${n}.participantId`,e.participantId),je(o,`${n}.from.entityId`,e.from.entityId),je(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=[];je(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,h)=>{let f=n.get(p);f?ce(e,h,"duplicate_id",`ID is already used at ${f}.`):n.set(p,h)};o.records.forEach((p,h)=>{let f=`records[${h}]`;t(p.id,f),ba(e,p,f,o.manifest.projectId)}),o.events.forEach((p,h)=>{let f=`events[${h}]`;t(p.id,f),Ia(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,h)=>{let f=`relationships[${h}]`;t(p.id,f),xa(e,p,f),p.projectId!==o.manifest.projectId&&ce(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,h)=>{t(p.id,`artifacts[${h}]`),je(e,`artifacts[${h}].id`,p.id)}),o.tombstones.forEach((p,h)=>{let f=`tombstones[${h}]`;t(p.id,f),je(e,`${f}.id`,p.id),je(e,`${f}.objectId`,p.objectId),je(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,h)=>{let f=`${p.entityType}:${p.entityId}`;!r.has(f)&&!s.has(f)&&ce(e,h,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,h)=>i(p.entity,`events[${h}].entity`)),o.relationships.forEach((p,h)=>{i(p.from,`relationships[${h}].from`),i(p.to,`relationships[${h}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,h)=>{c.has(p)||ce(e,h,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,h,f)=>{!r.has(`${p}:${h}`)&&!s.has(`${p}:${h}`)&&ce(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,h)=>{let f=`records[${h}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${f}.granteeId`),l("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((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)=>d(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)=>d(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)=>d(v,`${f}.artifactIds[${x}]`));break;case"evidence":p.artifactIds.forEach((v,x)=>d(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)=>d(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 g=new Map(o.events.map(p=>[p.id,p])),R=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),b=new Map;o.events.forEach((p,h)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,v=b.get(f)??new Set;v.add(p.toState),b.set(f,v),v.size>1&&ce(e,`events[${h}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let I=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),y=(p,h,f,v,x)=>{if(p.level!=="delegate"||!p.grantId)return;let S=I.get(p.grantId);if(!S){ce(e,x,"invalid_authority_grant","Delegated authority references a missing grant.");return}(S.granteeId!==h||S.level!=="delegate")&&ce(e,x,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let A=Date.parse(f);(A<Date.parse(S.startsAt)||S.endsAt&&A>Date.parse(S.endsAt)||S.revokedAt&&A>=Date.parse(S.revokedAt))&&ce(e,x,"inactive_authority_grant","The delegated authority grant was not active at this time."),S.subjectIds.length&&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"&&y(p.authority,p.acceptedById,p.createdAt,p.subjects.map(h=>h.subjectId),`records:${p.id}.authority`);o.events.forEach((p,h)=>{let f=R.get(`${p.entity.entityType}:${p.entity.entityId}`),v=f&&"subjects"in f?f.subjects.map(x=>x.subjectId):[];y(p.authority,p.participantId,p.createdAt,v,`events[${h}].authority`)}),o.relationships.forEach((p,h)=>{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):[]});y(p.authority,p.participantId,p.createdAt,f,`relationships[${h}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let h=g.get(p.acceptanceEventId);(!h||h.entity.entityType!=="proposal"||h.entity.entityId!==p.proposalId||h.toState!=="accepted")&&ce(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),h&&h.participantId!==p.acceptedById&&ce(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${p.proposalId}`)||ce(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(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 ya(e)}function Xt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function 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 Sa(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 Mn(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."}),Mt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let s of Sa(e))Mt(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={...Xt(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={...Xt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Xt(o,s,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:s.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Ar(o,s,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:s.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s,d],events:[i,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:s.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let s={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Xt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as ka}from"crypto";import{readFile as Pa,readdir as Ra,realpath as Ta}from"fs/promises";import{join as Yt,relative as ja}from"path";var Ea=["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 At(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 _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=ka("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(i[3],16)&3|8).toString(16);return`${s.slice(0,8)}-${s.slice(8)}-7${i.slice(0,3)}-${c}${i.slice(4,7)}-${i.slice(7,19)}`}async function Po(o,e){try{return JSON.parse(await Pa(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Ma(o){let e=At(o);if(!e)return 0;let n=0,t=r=>{let s=At(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 Aa(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function bt(o){let e=[],n=await Ta(o.projectRoot).catch(()=>o.projectRoot),t=Yt(n,".popmelt"),r=await Po(Yt(t,"threads.json"),e),s=await Po(Yt(t,"model.json"),e),i=At(r),c=At(i?.threads)??{},d=Object.entries(c).map(([M,Y])=>({key:M,value:At(Y)})).filter(M=>!!M.value),l=Yt(t,"decisions"),g=await Ra(l).catch(()=>[]),R=[];for(let M of g.filter(Y=>Y.endsWith(".json")).sort()){let Y=At(await Po(Yt(l,M),e));Y&&R.push({file:M,value:Y})}let b=d.flatMap(({value:M})=>[M.createdAt,M.updatedAt]).filter(M=>typeof M=="number"&&Number.isFinite(M)),I=b.length?Math.min(...b):0,y=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(y,"project",y,I),h=ye(y,"participant","legacy-owner",I),f=ye(y,"participant","legacy-agent",I),v=ye(y,"subject","project",I),x=ze(Math.max(I,...b)),S=[],A=[],J=new Map,_=new Map,N=new Map(R.map(M=>[M.value.id??M.file.replace(/^d-|\.json$/g,""),M.value])),T=new Map,B=(M,Y,ue,ie,Je)=>{let Ne=J.get(ue);if(Ne)return Ne;let Pe=ye(y,"artifact",M,ie);return A.push({id:Pe,kind:Y,mediaType:Je,location:ue,availability:"available"}),J.set(ue,Pe),Pe};for(let{file:M,value:Y}of R){let ue=Y.id??M.replace(/^d-|\.json$/g,""),ie=Y.createdAt??I,Je=[B(`${ue}:envelope`,"other",`.popmelt/decisions/${M}`,ie,"application/json")];Y.screenshotPath&&Je.push(B(`${ue}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,ie,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ne,Pe]of(Y.pastedImagePaths??[]).entries())Je.push(B(`${ue}:image:${Ne}`,"image",Pe,ie));T.set(ue,Je)}let W=(M,Y,ue)=>({id:M,schemaVersion:1,projectId:p,createdAt:x,participantId:Y,sourceRefs:ue}),ee=(M,Y)=>{S.push(Y);let ue=_.get(M)??[];ue.push(Y.id),_.set(M,ue)},H=[{...W(h,h,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...W(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];S.push(...H),S.push({...W(v,h,[]),recordType:"subject",subjectType:"project",label:ja(process.cwd(),n)||n,aliases:[],locators:[{id:ye(y,"locator",n,I),kind:"project_root",value:n,status:"current",validFrom:ze(I),sourceRefs:[]}]});let te=new Map,ne=(M,Y)=>{let ue=te.get(M);if(ue)return ue;let ie=ye(y,"subject",M,Y),Je={...W(ie,h,[{kind:"external",id:M}]),createdAt:ze(Y),recordType:"subject",subjectType:"element",label:M,aliases:[],locators:[{id:ye(y,"locator",M,Y),kind:"dom_selector",value:M,status:"current",validFrom:ze(Y),sourceRefs:[{kind:"external",id:M}]}]};return S.push(Je),te.set(M,ie),ie};for(let{key:M,value:Y}of d){let ue=Y.id??M,ie=Y.createdAt??I,Je=ye(y,"thread",ue,ie),Ne={kind:"thread",id:ue},Pe=[],qe=[],Ve=Array.isArray(Y.messages)?Y.messages:[],Ze,st,mt=0;Ve.forEach((Ie,it)=>{let _e=Ie.timestamp??ie,et=ye(y,"artifact",`${ue}:message:${it}`,_e);if(Pe.push(et),A.push({id:et,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${it}`,availability:"available"}),J.set(`.popmelt/threads.json#/threads/${ue}/messages/${it}`,et),Ie.screenshotPath&&B(`${ue}:message:${it}:screenshot`,"screenshot",Ie.screenshotPath,_e),Ie.role==="human"){Ze=Ie;let Ee=Ie.feedbackSummary??Ie.replyToQuestion;if(Ee?.trim()){let Be=ye(y,"observation",`${ue}:${it}`,_e),dt=Y.elementIdentifiers??[],Pt={...W(Be,h,[Ne,{kind:"message",id:et}]),createdAt:ze(_e),recordType:"observation",state:"open",statement:Ee,captureContext:{subjectIds:dt.map(ht=>ne(ht,ie)),artifactIds:[et]},resolvedByIds:[]};ee(ue,Pt),st=Be,qe.push({entityType:"observation",entityId:Be})}return}if(Ie.role!=="assistant")return;let at=Ie.jobId??`${ue}:${it}`,ct=ye(y,"iteration",at,_e),ft=N.get(at),to=Ie.cancelled?"cancelled":Ie.error?"failed":Ie.question?"question_asked":(Ie.resolutions?.length??0)>0?"completed":"no_change",no={...W(ct,f,[Ne,{kind:"message",id:et},...(T.get(at)??[]).map(Ee=>({kind:"artifact",id:Ee}))]),createdAt:ze(_e),recordType:"iteration",threadIds:[Je],startedAt:ze(Ze?.timestamp,_e),completedAt:ze(_e),requestSummary:_r(Ze?.feedbackSummary,Ze?.replyToQuestion)??"[legacy request unavailable]",responseSummary:Ie.question??Ie.error??Ie.responseText?.slice(0,1e3),outcome:to,execution:{provider:Ie.provider??ft?.provider,model:Ie.model??ft?.model,sessionId:Ie.sessionId??ft?.sessionId},artifactIds:[et,...T.get(at)??[]]};ee(ue,no),qe.push({entityType:"iteration",entityId:ct});let zt=Ie.resolutions??ft?.resolutions??[];for(let[Ee,Be]of zt.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let dt=Y.elementIdentifiers??[],Pt=(dt.length?dt:[n]).map(pn=>({subjectId:pn===n?v:ne(pn,ie),role:"governed"})),ht=ye(y,"proposal",`${at}:${Be.annotationId??"resolution"}:${Ee}`,_e),oo={...W(ht,f,[Ne,{kind:"iteration",id:ct}]),createdAt:ze(_e),recordType:"proposal",state:"pending",claim:Be.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(Ze?.feedbackSummary,Ze?.replyToQuestion,Be.summary),iterationId:ct,inferredById:f}};ee(ue,oo),qe.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(Ee=>Ee.status==="resolved")||ft?.gitDiff){let Ee=ye(y,"implementation",at,_e),Be={...W(Ee,f,[Ne,{kind:"iteration",id:ct}]),createdAt:ze(_e),recordType:"implementation_attempt",state:"completed",iterationIds:[ct],coverageClaims:[],summary:zt.map(dt=>dt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};ee(ue,Be),qe.push({entityType:"implementation_attempt",entityId:Ee}),mt+=1}st&&(st=void 0)});let Ft=Ve.at(-1),Lt={...W(Je,h,[Ne]),createdAt:ze(ie),recordType:"thread",state:Ft?.question?"open":"resolved",messageArtifactIds:Pe,outcome:Ft?.question?"question_unresolved":mt?"implementation_only":"no_outcome",resultRefs:qe};S.push(Lt),_.set(ue,[Je,..._.get(ue)??[]])}let ge=Ma(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:ze(I),updatedAt:x,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:S,events:[],relationships:[],artifacts:A,tombstones:[]},G=It(X),he=(o.proofCaseIds??Ea).map(M=>({legacyId:M,threadFound:d.some(({key:Y,value:ue})=>(ue.id??Y)===M),decisionEnvelopeFound:N.has(M),recordIds:_.get(M)??[]}));return{bundle:X,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((M,Y)=>M+(Y.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:ge,artifactsReferenced:A.length},imported:Aa(S),unresolvedAcceptance:e.filter(M=>M.code==="acceptance_unresolved").length,deferredModelEntries:ge,proofCases:he,issues:e,schemaIssues:G.issues}}}import{createHash as _a}from"crypto";import{mkdir as $r,open as Ro,readFile as To,readdir as $a,rename as Ca,unlink as jo}from"fs/promises";import{join as ot}from"path";var Oa={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function _n(o){return _a("sha256").update(JSON.stringify(o)).digest("hex")}function Cr(o){return _n(o)}function Or(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 Da(o,e,n){return Or(structuredClone(o),e,n)}async function xt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ro(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ca(n,o)}catch(r){throw await jo(n).catch(()=>{}),r}}async function An(o){return JSON.parse(await To(o,"utf8"))}var $n=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=ot(e,".popmelt","memory"),this.journalDir=ot(this.memoryDir,"journal"),this.manifestPath=ot(this.memoryDir,"manifest.json"),this.checkpointPath=ot(this.memoryDir,"checkpoint.json"),this.lockPath=ot(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 $r(this.journalDir,{recursive:!0});try{throw await To(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 To(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 xt(this.checkpointPath,r),await xt(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 xt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=_n(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await xt(ot(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await xt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Mt(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:Cr(s)},c=Da(t.bundle,e,n.committedAt),d=It(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await xt(ot(this.journalDir,l),i),t.manifest.head={sequence:r,hash:i.hash},t.manifest.updatedAt=n.committedAt,await xt(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:i.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Oa,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await An(this.manifestPath),n=await An(ot(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(b=>b.endsWith(".tmp")),i=t.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,g=new Set;for(let b of i){let I=await An(ot(this.journalDir,b)),{hash:y,...p}=I;if(y!==Cr(p))throw new Error(`Journal hash mismatch: ${b}`);if(I.sequence!==d+1)throw new Error(`Journal sequence gap at ${b}`);if(I.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(I.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(g.has(I.transactionId))throw new Error(`Duplicate transaction ID: ${I.transactionId}`);Or(c,I.mutation,I.committedAt),d=I.sequence,l=I.hash,g.add(I.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=It(c);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:c,manifest:e,transactionIds:g,report:{checkpointSequence:n.sequence,appliedTransactions:i.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await $r(this.memoryDir,{recursive:!0});let n;try{n=await Ro(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await An(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 jo(this.lockPath),n=await Ro(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await jo(this.lockPath).catch(()=>{})}}};import{randomBytes as Ja}from"crypto";function le(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Ja(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 Na=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Dr(o,e){let n=o.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active"),t=o.records.find(x=>x.recordType==="participant"&&x.kind==="ai"&&x.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,s=`${e.threadId}:${e.jobId}`,i=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Na(),l=d.records,g=o.records.find(x=>x.recordType==="thread"&&x.sourceRefs.some(S=>S.kind==="thread"&&S.id===e.threadId));g||(g={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(g));let R=[];for(let x of[...new Set(e.subjectHints.filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"element",label:x,aliases:[],locators:[{id:ye(r,"live-locator",x,e.createdAt),kind:"dom_selector",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}for(let x of[...new Set((e.filePaths??[]).filter(Boolean))]){let S=o.records.find(A=>A.recordType==="subject"&&A.locators.some(J=>J.kind==="source_file"&&J.value===x&&J.status==="current"));S||(S={id:ye(r,"live-file-subject",x,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"external",id:x}],recordType:"subject",subjectType:"file",label:x,aliases:[],locators:[{id:ye(r,"live-file-locator",x,e.createdAt),kind:"source_file",value:x,status:"current",validFrom:i,sourceRefs:[{kind:"external",id:x}]}]},l.push(S)),R.push(S)}let b=(e.semanticCandidates??[]).filter(x=>x.claim.trim()),I;if(b.length>0){I=ye(r,"live-observation",s,e.createdAt);let x={id:I,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(S=>S.claim.trim()).join(" "),captureContext:{subjectIds:R.map(S=>S.id),artifactIds:[]},resolvedByIds:[]};l.push(x)}let y=ye(r,"live-iteration",s,e.completedAt),p={id:y,schemaVersion:1,projectId:o.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...I?[{kind:"record",id:I}]:[]],recordType:"iteration",threadIds:[g.id],startedAt:i,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let h=[],f=e.resolutions.filter(x=>x.status==="resolved"&&x.summary.trim()),v=R.length>0?R:o.records.filter(x=>x.recordType==="subject"&&x.subjectType==="project").slice(0,1);if(b.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[x,S]of b.entries()){let A=ye(r,"live-proposal",`${s}:${x}`,e.completedAt),J=v.map(N=>({subjectId:N.id,role:"governed"})),_={id:A,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:y},{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:y,inferredById:t.id}};l.push(_),h.push(A)}if(f.length>0){let x=new Set(e.governingDecisionIds??[]),S=o.records.filter(J=>J.recordType==="decision"&&J.state==="active"&&x.has(J.id)),A={id:ye(r,"live-implementation",s,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:y}],recordType:"implementation_attempt",state:"completed",iterationIds:[y],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:y}]})),summary:f.map(J=>J.summary).join(" "),artifactIds:[]};l.push(A)}return{mutation:d,iterationId:y,proposalIds:h,observationId:I}}import{createHash as Ba}from"crypto";import{mkdir as Fa,open as La,readFile as za,rename as Ua,unlink as qa}from"fs/promises";import{join as Jr}from"path";function Nr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Br(o){return Ba("sha256").update(JSON.stringify(o)).digest("hex")}async function Wa(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await La(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
179
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ua(n,o)}catch(r){throw await qa(n).catch(()=>{}),r}}function Ha(o,e,n=new Date().toISOString()){let t={},r={},s={},i=(d,l,g)=>{let R=d[l]??=[];R.includes(g)||R.push(g)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let g of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Nr(g);R&&i(t,R,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)i(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)i(s,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:s};return{...c,checksum:Br(c)}}function Fr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Nr(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=Jr(e,".popmelt","memory","indexes"),this.indexPath=Jr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await za(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===Br(i))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ha(e,n);return await Fa(this.indexDir,{recursive:!0}),await Wa(this.indexPath,t),t}};var On=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 _t(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 bt({...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 bt({...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 _t(n,"utf8"));return{migrated:!1,specs:s.specs??0,runs:s.runs??0}}catch{}let t=[],r=[];try{let s=JSON.parse(await _t(pt(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(s.cases)?s.cases:[]}catch{}try{let s=JSON.parse(await _t(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 Eo(e,{recursive:!0}),await Mo(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 _t(n,"utf8"));return{migrated:!1,explanations:s.explanations??0,evidence:s.evidence??0}}catch{}let t;try{t=JSON.parse(await _t(pt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Eo(e,{recursive:!0}),await Mo(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=0;for(let s of t.explanations){let i=s.evidence.length?s.evidence:[{id:s.id,kind:"observation",stance:"supports",summary:s.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:s.createdAt}];for(let c of i){let d=c.kind==="confirmation"?"confirm":c.kind==="correction"||c.kind==="rejection"?"reason_wrong":c.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:c.id,kind:d?"strengthened":"added",title:s.statement.slice(0,120),detail:c.summary,changes:[{explanationId:s.id,action:d==="reason_wrong"?"challenged":"supported",statement:s.statement,state:s.state}]},threadId:c.threadId,jobId:c.jobId,action:d,occurredAt:c.createdAt}),r+=1}}return await Eo(e,{recursive:!0}),await Mo(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:Qt(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Mr(t.bundle,r),reviewSelection:Qt(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Mn(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 bt({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=Mn(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let s=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(s),s}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let s=Date.now(),i=new Date(s).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:i},d=e.action==="accept"?{...c,action:"accept",eventId:le(s),decisionId:le(s),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:le(s),replacementProposalId:le(s),acceptanceEventId:le(s),decisionId:le(s),relationshipId:le(s),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:le(s),reason:e.reason}:{...c,action:"defer",eventId:le(s),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=Mn(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let g=await this.store.commitReviewPlan(l.plan,{transactionId:le(s),committedAt:i});await this.refreshIndex(g);let R=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:g.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=Dr(n.bundle,e),r=ye(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let s=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(s),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:s.report.headSequence}}catch(s){if(s instanceof Error&&s.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw s}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active"),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="ai"&&b.status==="active"),s=e.action?t:r??t,i=n.bundle.records.find(b=>b.recordType==="subject"&&b.subjectType==="project");if(!s||!i)return;let c=e.occurredAt??new Date().toISOString(),d=Date.parse(c),l=[],g=[];for(let b of e.summary.changes){let I={kind:"external",id:b.explanationId,uri:"popmelt:imprint"},y=n.bundle.records.find(h=>h.recordType==="observation"&&h.sourceRefs.some(f=>f.kind==="external"&&f.id===b.explanationId&&f.uri==="popmelt:imprint"));y||(y={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:b.statement,captureContext:{subjectIds:[i.id],artifactIds:[]},resolvedByIds:[]},l.push(y));let p={id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};l.push(p),g.push({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[I],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:y.id},to:{entityType:"evidence",entityId:p.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=ye(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,d);try{let b=await this.store.commit({records:l,events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:c});await this.refreshIndex(b)}catch(b){if(!(b instanceof Error)||!b.message.includes("Transaction already exists"))throw b}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="model_projection"&&i.state==="applied"?i.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(i=>i.relationshipType==="contradicts"&&i.from.entityType==="decision"&&i.to.entityType==="decision"?[i.from.entityId,i.to.entityId]:[])),s=new Set(n.records.flatMap(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.target.entityType==="decision"?[i.target.entityId]:[]));return n.records.filter(i=>i.recordType==="decision"&&i.state==="active"&&!t.has(i.id)&&!r.has(i.id)&&!s.has(i.id)).sort((i,c)=>c.createdAt.localeCompare(i.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(s=>s.recordType==="model_entry").sort((s,i)=>s.createdAt.localeCompare(i.createdAt)))r.decisionIds.some(s=>n.has(s))&&t.set(r.key,r);return[...t.values()]}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let r=[...t.values()],s=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=s.filter(l=>l.targets.some(g=>g.entityType==="decision"&&g.entityId===c.id)).sort((l,g)=>g.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="decision"&&e.includes(s.id)?s.subjects.map(i=>i.subjectId):[])),r=[];for(let s of n.records)if(!(s.recordType!=="subject"||!t.has(s.id)))for(let i of s.locators.filter(c=>c.status==="current"))i.kind==="source_file"?r.push({kind:"source_file",value:i.value,subjectId:s.id}):i.kind==="route_pattern"?r.push({kind:"route",value:i.value,subjectId:s.id}):i.kind==="token_path"?r.push({kind:"model_path",value:i.value,subjectId:s.id}):(i.kind==="dom_selector"||i.kind==="file_export"||i.kind==="source_span")&&r.push({kind:"subject",value:i.value,subjectId:s.id});return[...new Map(r.map(s=>[`${s.kind}:${s.value}:${s.subjectId??""}`,s])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),r=n.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let s=Date.now(),i=new Date(s).toISOString(),c=le(s),d=le(s),l=le(s),g=le(s),R=le(s),b=new Set(n.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),I=n.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&b.has(T.id)),y={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],h={...y,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},f={...y,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...y,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:i},x={...y,id:g,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},S={...y,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:[g],coverage:[{decisionId:l,status:"projected"}]},A={...y,id:le(s),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},J=I.map(T=>({...y,id:le(s),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=I.map(T=>({...y,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:[h,v,x,S],events:[f,...J],relationships:[A,..._],artifacts:[],tombstones:[],projectionUpdates:I.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:le(s),committedAt:i});return await this.refreshIndex(N),{decisionId:l,entryId:g}}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(y=>y.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===y.id||y.sourceRefs.some(h=>h.id===p))?[y.id]:[]),i=[...new Set(n.bundle.records.flatMap(y=>y.recordType==="decision"&&s.includes(y.id)?y.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:s,subjectIds:i,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="human"&&y.status==="active");if(!l)throw new Error("No active local owner participant is available.");let g=Date.now(),R=new Date(g).toISOString(),b={id:le(g),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...s.map(y=>({kind:"record",id:y}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:s.map(y=>({entityType:"decision",entityId:y})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},I=r?[{id:le(g),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:R,participantId:l.id,sourceRefs:[{kind:"record",id:b.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:b.id},to:{entityType:"eval_spec",entityId:r.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[b],events:[],relationships:I,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(g),committedAt:R})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(i=>i.objectType==="eval_spec").map(i=>i.objectId)),t=e.records.filter(i=>i.recordType==="eval_spec").reverse().filter((i,c,d)=>d.findIndex(l=>l.legacyId===i.legacyId)===c).filter(i=>!n.has(i.id)),r=e.records.filter(i=>i.recordType==="verification_attempt"),s=e.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open"&&i.targetKind==="verification_result");return t.map(i=>{let c=r.filter(g=>g.evalSpecId===i.id).sort((g,R)=>R.createdAt.localeCompare(g.createdAt))[0],d=c&&s.some(g=>g.target.entityType==="verification_attempt"&&g.target.entityId===c.id),l=i.state==="draft"?"draft":i.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:i.legacyId,canonicalSpecId:i.id,verificationState:l,title:i.title,status:i.state==="draft"?"pending":i.state==="active"?"approved":"rejected",category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,sourceDecisionIds:i.decisionIds,sourceThreadIds:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let s=t.evalRun,i=Date.parse(t.createdAt);return[{id:s?.id??t.id,evalId:r.legacyId,threadId:s?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:s?.createdAt??i,completedAt:s?.completedAt??i,durationMs:s?.durationMs??0,scope:s?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:s?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:s?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:s?.provider,model:s?.model,screenshotPath:s?.screenshotPath,codeFingerprint:s?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(b=>b.recordType==="verification_attempt"&&b.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let s=t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active"&&b.kind==="ai")??t.bundle.records.find(b=>b.recordType==="participant"&&b.status==="active");if(!s)return;let i=n.completedAt,c=new Date(i).toISOString(),d={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:s.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},g=r.targets.map(b=>({id:le(i),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:b,reason:n.summary})),R=await this.store.commit({records:[d,l],events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((s,i)=>s.completedAt-i.completedAt)){let s=t.get(r.evalId);s&&await this.recordEvalVerification(s,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let s=Date.now(),i=new Date(s).toISOString(),c={id:le(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:i,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(s),committedAt:i});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),r=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),s=e.filter(d=>!r.includes(d)).map(d=>d.id);if(s.length===0)return{valid:r,discardedIds:s};let i=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!i)return{valid:r,discardedIds:s};let c=s.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(g=>({id:le(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:g.id,objectType:"eval_spec",deletedAt:l,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:le(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:s}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(s=>s.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(y=>y.recordType==="model_projection"&&y.state==="applied"&&y.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(y=>y.recordType==="decision"&&e.decisionIds.includes(y.id)&&y.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(y=>y.recordType==="participant"&&y.kind==="human"&&y.status==="active");if(!s)throw new Error("No active local owner participant is available.");let i=Date.now(),c=new Date(i).toISOString(),d=le(i),l=e.changes.map(y=>{let p=y.decisionIds?.filter(v=>e.decisionIds.includes(v)),h=p?.length?p:e.decisionIds,f=[...new Set(r.filter(v=>h.includes(v.id)).flatMap(v=>v.subjects.map(x=>x.subjectId)))];return{id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:h.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:y.path.map(String).join("."),subjectIds:f,decisionIds:h,value:y.value}}),g=new Set(l.flatMap(y=>y.decisionIds)),R={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:e.decisionIds.map(y=>({kind:"record",id:y})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:s.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(y=>y.id),coverage:e.decisionIds.map(y=>e.coverage?.find(p=>p.decisionId===y)??{decisionId:y,status:g.has(y)?"projected":"unprojected"})},b=l.flatMap(y=>y.decisionIds.map(p=>({id:le(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:s.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:y.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),I=await this.store.commit({records:[...l,R],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(i),committedAt:c});return await this.refreshIndex(I),{projectionId:d,entryIds:l.map(y=>y.id),headSequence:I.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await bt({...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 Ct(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function ke(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=ke(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Ao(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"]),c={proposalId:ke(e.proposalId,"proposalId"),participantId:ke(e.participantId,"participantId"),occurredAt:ke(e.occurredAt,"occurredAt"),authority:{level:s,mode:i,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:ke(e.eventId,"eventId"),decisionId:ke(e.decisionId,"decisionId"),kind:$t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:ke(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:ke(e.eventId,"eventId"),reason:ke(e.reason,"reason")};case"defer":{let d=Ct(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:ke(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>ke(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>$t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:ke(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:ke(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:ke(e.acceptanceEventId,"acceptanceEventId"),decisionId:ke(e.decisionId,"decisionId"),relationshipId:ke(e.relationshipId,"relationshipId"),claim:ke(e.claim,"claim"),kind:$t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=Ct(d);return{subjectId:ke(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:ke(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function _o(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(c=>ke(c,i))}},t=(s,i)=>{if(s!==void 0){if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(`${i} must be a positive number.`);return s}},r=e.resurface===void 0?void 0: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 Dn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
180
|
+
`)}async function Lr(o,e,n,t){let r=Dn(e);if(!(!r&&n.length===0))try{let s=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(s.actionPacket.decisions.length===0&&s.reviewSelection.packets.length===0)return;let i=new Map(s.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(s.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:s.source,...s.actionPacket.decisions.length>0?{acceptedTruth:{decisions:s.actionPacket.decisions.map(d=>({...d,implementation:i.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:s.actionPacket.conflicts,truncated:s.actionPacket.completeness.status==="truncated"}}:{},packets:s.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:s.reviewSelection.completeness.status==="truncated",estimatedTokens:s.actionPacket.budget.estimatedTokens+s.reviewSelection.completeness.estimatedTokens}}catch(s){t?.(s);return}}function zr(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(`
|
|
181
|
+
`)}function Ur(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!r||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let s=new Set(["different_action","new_evidence","new_conflict","owner_request"]),i=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&s.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:i}}catch{return null}}function qr(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 Jn(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 Ga(o),s=Buffer.from(`--${t}`),i=Buffer.from(`--${t}--`),c,d,l,g,R,b,I,y,p,h,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 W=B;r[W]===13&&r[W+1]===10&&(W+=2);let ee=r.indexOf(`\r
|
|
375
182
|
\r
|
|
376
|
-
`,
|
|
377
|
-
|
|
378
|
-
`)}function
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
`));return ut([...dt,...f])}function ct(s,e,n=5e3){return new Promise((t,o)=>{qo(s,e,{encoding:"utf-8",timeout:n},(i,a)=>{if(i){o(i);return}t(a)})})}async function zn(s){return Xo(s,"utf-8")}async function tr(s){let e=[xe(s,"projects"),xe(s,"telemetry")],n=[];for(let t of e)await Bn(t,n,4);return n.sort((t,o)=>o.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Bn(s,e,n){if(n<0)return;let t;try{t=await Qo(s,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async o=>{let i=xe(s,o.name);if(o.isDirectory()){await Bn(i,e,n-1);return}if(!(!o.isFile()||!nr(o.name)))try{let a=await Yo(i);if(a.size>2e6)return;e.push({path:i,mtimeMs:a.mtimeMs})}catch{}}))}function nr(s){return s.endsWith(".json")||s.endsWith(".jsonl")||s.endsWith(".md")||s.endsWith(".txt")}function ut(s){let e=new Set,n=[];for(let t of s)e.has(t.id)||(e.add(t.id),n.push(t));return n}function sr(s){return[...new Set(s)]}function or(s){return s.charAt(0).toUpperCase()+s.slice(1)}var pt=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,o=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),o}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 o=this.bufferEvent(n,e);for(let i of this.listeners)i(o,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let o={...n,seq:t.nextSeq++};return t.events.push(o),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),o}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let a=n<0?t.events:t.events.filter(l=>l.seq>n);return{jobId:e,events:a,currentSeq:t.nextSeq-1,accumulated:{...o},jobActive:i}}accumulateText(e,n,t){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[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(o=>{let i=!1,a=()=>{i||(i=!0,o())};t.on("exit",a),t.on("error",a),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(a,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==="materialize_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{mkdir as rr,readFile as ir,writeFile as ar}from"fs/promises";import{dirname as lr,join as cr}from"path";var dr={version:1,threads:{}},ft=class{constructor(e){this.cache=null;this.writeChain=Promise.resolve();this.filePath=cr(e,".popmelt","threads.json")}async load(){if(this.cache)return this.cache;try{let e=await ir(this.filePath,"utf-8"),n=JSON.parse(e);if(n&&n.version===1&&n.threads)return this.cache=n,this.cache}catch{}return this.cache={...dr,threads:{}},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 o of Object.values(n.threads))if(o.elementIdentifiers.some(a=>t.has(a)))return o;return null}async createThread(e,n){let t=await this.load(),o={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=o,await this.persist(),o}async appendMessage(e,n){let o=(await this.load()).threads[e];o&&(o.messages.push(n),o.updatedAt=Date.now(),await this.persist())}async appendMessageBeforeQueuedReplies(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=o.messages.findIndex(a=>a.role==="human"&&!!a.replyToQuestion&&a.queued);i>=0?o.messages.splice(i,0,n):o.messages.push(n),o.updatedAt=Date.now(),await this.persist()}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let a=i.messages.filter(l=>l.jobId===n);if(a.length===0)return!1;for(let l of a)Object.assign(l,t);return i.updatedAt=Date.now(),await this.persist(),!0}async addElementIdentifiers(e,n){let o=(await this.load()).threads[e];if(!o)return;let i=new Set(o.elementIdentifiers);for(let a of n)i.has(a)||o.elementIdentifiers.push(a);o.updatedAt=Date.now(),await this.persist()}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.persist(),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((o,i)=>i.updatedAt-o.updatedAt),t.slice(0,e).map(o=>{let a=o.messages.find(l=>l.role==="human")?.feedbackSummary||"[thread]";return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:a,messageCount:o.messages.length,elementIdentifiers:o.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 persist(){this.writeChain=this.writeChain.then(async()=>{if(this.cache)try{await rr(lr(this.filePath),{recursive:!0}),await ar(this.filePath,JSON.stringify(this.cache,null,2))}catch(e){console.error("[ThreadStore] Failed to persist:",e)}}),await this.writeChain}};function Fn(s){return pr(s).slice(0,12)}var ur=[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 pr(s){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(s)):fr(s),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let B=7;B>=0;B--)e.push(n/Math.pow(2,B*8)&255);let t=1779033703,o=3144134277,i=1013904242,a=2773480762,l=1359893119,f=2600822924,v=528734635,x=1541459225,E=new Array(64);for(let B=0;B<e.length;B+=64){for(let z=0;z<16;z++){let Z=B+z*4;E[z]=(e[Z]<<24|e[Z+1]<<16|e[Z+2]<<8|e[Z+3])>>>0}for(let z=16;z<64;z++){let Z=be(E[z-15],7)^be(E[z-15],18)^E[z-15]>>>3,D=be(E[z-2],17)^be(E[z-2],19)^E[z-2]>>>10;E[z]=E[z-16]+Z+E[z-7]+D>>>0}let J=t,U=o,W=i,w=a,q=l,V=f,Q=v,K=x;for(let z=0;z<64;z++){let Z=be(q,6)^be(q,11)^be(q,25),D=q&V^~q&Q,A=K+Z+D+ur[z]+E[z]>>>0,k=be(J,2)^be(J,13)^be(J,22),R=J&U^J&W^U&W,N=k+R>>>0;K=Q,Q=V,V=q,q=w+A>>>0,w=W,W=U,U=J,J=A+N>>>0}t=t+J>>>0,o=o+U>>>0,i=i+W>>>0,a=a+w>>>0,l=l+q>>>0,f=f+V>>>0,v=v+Q>>>0,x=x+K>>>0}return[t,o,i,a,l,f,v,x].map(B=>B.toString(16).padStart(8,"0")).join("")}function be(s,e){return s>>>e|s<<32-e}function fr(s){let e=[];for(let n=0;n<s.length;n++){let t=s.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 jn={name:"@popmelt.com/core",version:"0.8.4",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"},"./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"],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",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 Ln=jn.version;var kr=1111,Rr=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Mr=1800*1e3,Er=3600*1e3,Gn=45e3,Tr=5e3,Ar=1e4;function Hn(s){return s.length<=1?s[0]??"":["The developer sent these queued steering messages while you were working:","",...s.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
183
|
+
`,W);if(ee===-1)break;let H=r.slice(W,ee).toString("utf-8"),te=ee+4,ne=r.indexOf(s,te),ge=ne!==-1?ne-2:r.length;N.push({headers:H,body:r.slice(te,ge)}),_=ne!==-1?ne:r.length}for(let T of N){let B=T.headers.match(/name="([^"]+)"/);if(!B)continue;let W=B[1];if(W==="screenshot")c=T.body;else if(W==="feedback")d=T.body.toString("utf-8");else if(W==="color")l=T.body.toString("utf-8");else if(W==="provider")g=T.body.toString("utf-8");else if(W==="model")R=T.body.toString("utf-8");else if(W==="reasoningEffort")b=T.body.toString("utf-8");else if(W==="serviceTier")I=T.body.toString("utf-8");else if(W==="goal")y=T.body.toString("utf-8");else if(W==="pageUrl")p=T.body.toString("utf-8");else if(W==="viewport")h=T.body.toString("utf-8");else if(W==="planId")f=T.body.toString("utf-8");else if(W==="manifest")v=T.body.toString("utf-8");else if(W==="tasks")x=T.body.toString("utf-8");else if(W==="sourceId")S=T.body.toString("utf-8");else if(W.startsWith("screenshot-")){let ee=W.slice(11);try{let H=decodeURIComponent(ee);J.push({pathname:H,data:T.body})}catch{}}else if(W.startsWith("image-")){let ee=W.split("-"),H=parseInt(ee[ee.length-1],10),te=ee.slice(1,-1).join("-");te&&!isNaN(H)&&A.push({annotationId:te,index:H,data:T.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:l,provider:g,model:R,reasoningEffort:b,serviceTier:I,goal:y,pageUrl:p,viewport:h,planId:f,manifest:v,tasks:x,sourceId:S,pastedImages:A,pageScreenshots:J}}function Ga(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 Va}from"crypto";var Ka=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,Qa=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Xa=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 Ya(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Wr(o,e,n,t=Date.now()){let r=Ya(o);if(!r)return null;let s=typeof r.transition=="string"&&Qa.has(r.transition)?r.transition:null,i=Zt(r.focus);if(!s||!i)return null;let c=typeof r.evidencePosture=="string"&&Xa.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Va(),jobId:e,sequence:n,timestamp:t,transition:s,snapshot:{focus:i,seeking:Zt(r.seeking),workingHypothesis:Zt(r.workingHypothesis),evidencePosture:c,update:Zt(r.update),nextObservation:Zt(r.nextObservation)},contextPolicy:"exclude"}}function $o(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Za(o,e,n=0){let t=[],r=new Set,s=n;return{visibleText:o.replace(Ka,(c,d)=>{try{let l=Wr(JSON.parse(d),e,s);if(!l)return"";let g=$o(l);if(r.has(g))return"";r.add(g),t.push(l),s++}catch{}return""}).replace(/\n{3,}/g,`
|
|
184
|
+
|
|
185
|
+
`).trim(),orientations:t}}function ec(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 Nn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let c=ec(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,r);let s=this.buffer.indexOf("</orientation>",r+13);if(s<0){this.buffer=this.buffer.slice(r);break}let i=this.buffer.slice(r+13,s).trim();this.buffer=this.buffer.slice(s+14);try{let c=Wr(JSON.parse(i),this.jobId,this.sequence);if(!c)continue;let d=$o(c);if(this.signatures.has(d))continue;this.signatures.add(d),t.push(c),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=Za(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let s=$o(r);return this.signatures.has(s)?!1:(this.signatures.add(s),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Hr=`## Public orientation updates
|
|
186
|
+
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
187
|
+
<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>
|
|
188
|
+
|
|
189
|
+
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
190
|
+
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
191
|
+
|
|
192
|
+
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(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),s=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${s} \u2192 Elements: ${r||"none"}`);let i=e?.[t.id];if(i&&i.length>0)for(let c of i)n.push(` Attached image: use the Read tool to view ${c}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let s of t.changes)n.push(`- ${t.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=JSON.stringify(t.original),i=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${c}: ${s} \u2192 ${i}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",s=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",i=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${s} \u2192 ${t.targetParentSelector}${i}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
|
|
193
|
+
### ${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(`
|
|
194
|
+
`)}function Gr(o,e,n){let t=[],s=new Set(e.annotations.map(i=>i.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!s&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let i=0;for(let c of n.threadHistory)if(c.role==="human")i++,c.replyToQuestion?(t.push(`### Round ${i} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${i} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${i} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${i} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let l=d.finalScope??d.inferredScope,g=l?` [${l.breadth} ${l.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${g} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let i=n.designModel.rules;if(Array.isArray(i)&&i.length>0)if(t.push(""),t.push("Rules:"),i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"scope"in i[0]){let g=new Map;for(let R of i)if(typeof R=="object"&&R!==null&&"text"in R){let b=R,I=b.scope||"general";g.has(I)||g.set(I,[]),g.get(I).push(b.text)}for(let[R,b]of g){t.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let I of b)t.push(`- ${I}`)}}else for(let g of i)typeof g=="string"&&t.push(`- ${g}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),s){let i=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;c.has(l)||c.set(l,[]),c.get(l).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of c){t.push(""),t.push(`## Page: ${d}`);let g=i[d];g&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${g}`):!g&&n?.provider!=="codex"&&(Object.keys(i).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:l,styleModifications:e.styleModifications},b=en(R,n?.imagePaths);b&&(t.push(""),t.push(b))}}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(`
|
|
195
|
+
`)}function Vr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Kr(o,e,n,t){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let s=e.find(i=>i.role==="human"&&i.feedbackContext);if(s?.feedbackContext&&(r.push(""),r.push(s.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let i=0;for(let c of e)c.role==="human"?(i++,c.replyToQuestion?(r.push(`### Round ${i} (human) \u2014 reply`),r.push(`"${c.replyToQuestion}"`)):(r.push(`### Round ${i} (human)`),c.feedbackSummary&&r.push(`Annotations: ${c.feedbackSummary}`))):c.question?(r.push(`### Round ${i} (assistant) \u2014 question`),r.push(`"${c.question}"`)):(r.push(`### Round ${i} (assistant)`),c.responseText&&r.push(`Response: ${c.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let i of t)r.push(`Attached image: use the Read tool to view the image at: ${i}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
|
|
196
|
+
`)}function tc(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 nc(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&&!tc(e[n]))return!1;return!0}function Qr(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(nc):[]}catch{return[]}}function Xr(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 oc}from"child_process";import{readdir as rc,readFile as sc,stat as ic}from"fs/promises";import{homedir as tn}from"os";import{join as Xe}from"path";var Fn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Yr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Yr()}],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"},ac=/^\s*-\s+"([^"]+)"/;function cc(o){let e=[],n=!1;for(let t of o.split(`
|
|
197
|
+
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(ac);if(!r?.[1])continue;let s=r[1];e.push({id:s,label:Co(s),source:"cli"})}return Ln([on,...e])}function dc(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():Co(r),i=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:s,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...i&&i.length>0?{supportedReasoningLevels:i}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function Yr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function lc(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Ln(e.map(n=>({id:n,label:Co(n),source:"cli"})))}function Co(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":fc(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 Zr(o="copilot"){let e=await Bn(o,["help","config"]),n=cc(e);return n.length>1?n:[on]}async function es(o="codex"){let e=await Bn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Xe(tn(),".codex");return ns(Xe(t,"models_cache.json"))}),n=dc(e);return n.length>0?Ln([...n,...nn]):nn}async function ts(o="claude"){let e=Xe(tn(),".claude"),n=[Xe(tn(),".claude","stats-cache.json"),Xe(tn(),".claude","settings.json"),Xe(tn(),".claude.json"),Xe(e,"cache","changelog.md")],[t,r,s]=await Promise.all([Bn(o,["--help"]).catch(()=>""),Bn(o,["--version"]).catch(()=>""),pc(e).catch(()=>[])]),i=mc([...n,...s]),c=await Promise.all(i.map(l=>ns(l).catch(()=>""))),d=lc([t,r,...c].join(`
|
|
198
|
+
`));return Ln([...Fn,...d])}function Bn(o,e,n=5e3){return new Promise((t,r)=>{oc(o,e,{encoding:"utf-8",timeout:n},(s,i)=>{if(s){r(s);return}t(i)})})}async function ns(o){return sc(o,"utf-8")}async function pc(o){let e=[Xe(o,"projects"),Xe(o,"telemetry")],n=[];for(let t of e)await os(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function os(o,e,n){if(n<0)return;let t;try{t=await rc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let s=Xe(o,r.name);if(r.isDirectory()){await os(s,e,n-1);return}if(!(!r.isFile()||!uc(r.name)))try{let i=await ic(s);if(i.size>2e6)return;e.push({path:s,mtimeMs:i.mtimeMs})}catch{}}))}function uc(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 mc(o){return[...new Set(o)]}function fc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var zn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let s=this.queue.length-1;s>=0;s--)if(this.queue[s]?.threadId===e.threadId){n=s;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let s of this.listeners)s(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},s=this.activeJobs.has(e);if(!t)return null;let i=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:i,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:s}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let s=!1,i=()=>{s||(s=!0,r())};t.on("exit",i),t.on("error",i),setTimeout(()=>{if(!s){try{t.kill("SIGKILL")}catch{}setTimeout(i,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="synthesize_evals"||e.kind==="run_eval"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as Ge}from"crypto";import{createHash as hc}from"crypto";import{mkdir as gc,open as yc,readFile as rs,readdir as vc,rename as wc,unlink as Ic}from"fs/promises";import{dirname as bc,join as Ot}from"path";function Oe(o){return structuredClone(o)}function ss(o){return hc("sha256").update(JSON.stringify(o)).digest("hex")}async function rn(o,e){await gc(bc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await yc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
199
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await wc(n,o)}catch(r){throw await Ic(n).catch(()=>{}),r}}function xc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Sc(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 Oo(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")Sc(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 kc(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(c=>c.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=Oo(t,[r])}return n}function is(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 Un=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ot(e,".popmelt","imprint"),this.manifestPath=Ot(this.imprintDir,"manifest.json"),this.graphPath=Ot(this.imprintDir,"graph.json"),this.journalDir=Ot(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await rs(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 vc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=xc(this.projectId,e.createdAt),s=[],i=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await rs(Ot(this.journalDir,t[c]),"utf8")),{hash:l,...g}=d;if(d.sequence!==c+1||d.previousHash!==i||l!==ss(g))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Oo(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},s.push(d),i=d.hash}return{graph:r,transactions:s,recoveredTransactions:Math.max(0,s.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,s=kc(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}:{}},c={...i,hash:ss(i)},d=Oo(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await rn(Ot(this.journalDir,l),c);let g={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await rn(this.graphPath,d),await rn(this.manifestPath,g),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let s=await this.load(),i=s.transactions.find(l=>l.transactionId===e);if(!i)throw new Error("The imprint update is no longer available to undo.");if(s.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(i.mutations.flatMap(is));if(s.transactions.filter(l=>l.sequence>i.sequence).some(l=>l.mutations.some(g=>is(g).some(R=>c.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${i.summary}`,mutations:i.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await 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 Pc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Rc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Tc(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(Tc(o).split(" ").filter(e=>e.length>2&&!Rc.has(e)))}function Wn(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 Do(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function rt(o,e,n){return{id:Ge(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function Me(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function as(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 jc(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 Jo(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let b=String(r.reason);if(!Pc.has(b))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:b},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let s=r.summary,i=s?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(i)))throw new Error("summary.kind is invalid");let c={kind:i,title:Me(s?.title,120),detail:Me(s?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(b=>typeof b=="string"&&!!b.trim()):[],l=[];for(let b of Array.isArray(r.mutations)?r.mutations:[]){if(!b||typeof b!="object")continue;let I=b;if(I.op==="add"&&["intention","principle","pattern"].includes(String(I.kind))){let y=Me(I.statement),p=Me(I.rationale);if(!y||!p)continue;l.push({op:"add",clientId:Me(I.clientId,100)||void 0,kind:I.kind,statement:y,rationale:p,scope:as(I.scope)})}else if(I.op==="revise"&&typeof I.explanationId=="string"){let y={op:"revise",explanationId:I.explanationId,statement:Me(I.statement)||void 0,rationale:Me(I.rationale)||void 0,scope:as(I.scope),reopenGrounding:I.reopenGrounding===!0};(y.statement||y.rationale||y.scope||y.reopenGrounding)&&l.push(y)}else if(I.op==="evidence"&&typeof I.explanationId=="string"&&["supports","challenges","excepts"].includes(String(I.stance))){let y=Me(I.summary);y&&l.push({op:"evidence",explanationId:I.explanationId,stance:I.stance,summary:y})}else if(I.op==="relation"&&typeof I.fromId=="string"&&typeof I.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(I.type)))l.push({op:"relation",type:I.type,fromId:I.fromId,toId:I.toId,rationale:Me(I.rationale)});else if(I.op==="supersede"&&typeof I.explanationId=="string"&&typeof I.replacementId=="string"){let y=Me(I.reason);y&&l.push({op:"supersede",explanationId:I.explanationId,replacementId:I.replacementId,reason:y})}else if(I.op==="bind_concrete"&&typeof I.explanationId=="string"){let y=Me(I.modelPath,300);y&&l.push({op:"bind_concrete",explanationId:I.explanationId,modelPath:y,rationale:Me(I.rationale)})}else I.op==="retire"&&typeof I.explanationId=="string"&&l.push({op:"retire",explanationId:I.explanationId,reason:Me(I.reason)})}let g=r.grounding,R=g&&typeof g.explanationId=="string"&&Me(g.question)?{explanationId:g.explanationId,question:Me(g.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:R},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function No(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(`
|
|
200
|
+
`)),...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(`
|
|
201
|
+
`)}var sn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Un(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(d=>d.state!=="retired"&&d.state!=="challenged").map(d=>{let l=qn([d.statement,d.rationale].join(" ")),g=qn(d.scope.values.join(" ")),R=Wn(l,n),b=Wn(g,n),I=Wn(g,t),y=Wn(l,t),p=R+b*.2+I*.25+y*.1+(d.state==="grounded"?.08:0)+(r.has(d.id)?1:0),h=r.has(d.id)||(n.size?R>=.12||b>=.5:I>=.2||y>=.2);return{item:d,score:p,relevant:h}}).filter(d=>d.relevant&&d.score>=.18).sort((d,l)=>l.score-d.score||l.item.updatedAt.localeCompare(d.item.updatedAt)),c=Math.max(1,e.maxExplanations??4);if(i.length)return{explanations:i.slice(0,c).map(({item:d})=>{let l=new Set(s.relations.filter(g=>g.fromId===d.id&&g.type==="instantiates").map(g=>g.toId));return{id:d.id,kind:d.kind,statement:d.statement,rationale:d.rationale,scope:d.scope,state:d.state,concrete:s.concrete.filter(g=>l.has(g.id)).map(g=>({id:g.id,modelPath:g.modelPath,value:g.value}))}}),truncated:i.length>c,...r.size?{pendingGroundingExplanationIds:[...r]}:{}}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),s=new Map(r.graph.explanations.map(S=>[S.id,S])),i=new Map,c=new Map,d=[],l=new Set,g=new Set(n.pendingGroundingExplanationIds??[]);for(let S of e.mutations){if(S.op!=="add")continue;let A=Ge();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:Do(S.scope),state:J?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[rt(n,"supports",e.summary.detail)]};s.set(A,_),l.add(A),d.push({op:"add_explanation",explanation:_})}let R=S=>i.get(S)??S;for(let S of e.mutations){if(S.op!=="revise")continue;let A=R(S.explanationId),J=s.get(A);if(J?.state!=="grounded")continue;let _=Ge(),N={id:_,kind:J.kind,statement:S.statement??J.statement,rationale:S.rationale??J.rationale,scope:S.scope?Do(S.scope):J.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[rt(n,"supports",e.summary.detail)]};s.set(_,N),c.set(A,_),l.add(_),d.push({op:"add_explanation",explanation:N}),d.push({op:"add_relation",relation:{id:Ge(),type:"refines",fromId:_,toId:A,rationale:S.rationale??e.summary.detail,createdAt:t}})}let b=S=>{let A=R(S);return c.get(A)??A};for(let S of e.mutations){if(S.op==="add")continue;if(S.op==="bind_concrete"){let J=b(S.explanationId);if(!s.has(J))continue;let _=jc(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:Ge(),modelPath:S.modelPath,value:structuredClone(_.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:N})),d.push({op:"add_relation",relation:{id:Ge(),type:"instantiates",fromId:J,toId:N.id,rationale:S.rationale,createdAt:t}}),l.add(J);continue}if(S.op==="relation"){let J=b(S.fromId),_=b(S.toId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_relation",relation:{id:Ge(),type:S.type,fromId:J,toId:_,rationale:S.rationale,createdAt:t}}),l.add(J),l.add(_);continue}if(S.op==="supersede"){let J=b(S.explanationId),_=b(S.replacementId);if(!s.has(J)||!s.has(_)||J===_)continue;d.push({op:"add_evidence",explanationId:J,evidence:rt(n,"challenges",S.reason)}),d.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:_},updatedAt:t}),d.push({op:"add_relation",relation:{id:Ge(),type:"contradicts",fromId:_,toId:J,rationale:S.reason,createdAt:t}}),l.add(J),l.add(_);continue}let A=b(S.explanationId);if(s.has(A))if(l.add(A),S.op==="revise"){if(c.has(R(S.explanationId)))continue;let J={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:Do(S.scope)}:{},...S.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:A,patch:J,updatedAt:t})}else S.op==="evidence"?(d.push({op:"add_evidence",explanationId:A,evidence:rt(n,S.stance,S.summary)}),S.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"challenged"},updatedAt:t})):S.op==="retire"&&(d.push({op:"add_evidence",explanationId:A,evidence:rt(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let S of e.appliedExplanationIds){let A=b(S),J=s.get(A);!J||J.state==="grounded"||J.state==="retired"||g.has(A)&&!l.has(A)||(l.has(A)||(l.add(A),d.push({op:"add_evidence",explanationId:A,evidence:{...rt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=Ge(),y=await this.store.commit({transactionId:I,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),p=new Map(y.graph.explanations.map(S=>[S.id,S])),h=[...l].flatMap(S=>{let A=p.get(S);if(!A)return[];let J=!r.graph.explanations.some(N=>N.id===S),_=A.state==="challenged"||A.state==="retired";return[{explanationId:S,action:J?"added":_?"challenged":"revised",statement:A.statement,state:A.state}]}),f=e.grounding?b(e.grounding.explanationId):void 0,v=f?p.get(f):void 0,x=v?.state==="testing"&&!g.has(v.id)?{explanationId:v.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:I,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:h,...x?{grounding:x}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let g of l)await this.store.undo(g,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,Ge());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let s=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!s||s.state==="retired")throw new Error("This explanation is no longer active.");let i={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${s.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${s.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(g=>g.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:s.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${s.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${s.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:Ge(),committedAt:n,source:i,summary:d,mutations:c})}};function cs(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Hn(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(Hn(o.origin));if(e)return e;let n=Bo(Hn(o.referer));if(n)return n;let t=Hn(o["x-forwarded-host"]);if(!t)return null;let r=Hn(o["x-forwarded-proto"])==="https"?"https":"http";return Bo(`${r}://${t}`)}function ls(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),s=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),i=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=i.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:s,actionableProposalCounts:c,actionableProposals:i}}import{createHash as Gn}from"crypto";import{mkdir as an,readFile as St,unlink as Ac,writeFile as Jt}from"fs/promises";import{dirname as Vn,extname as _c,join as De}from"path";var Ec={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 Mc(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??Mc(o);return{kind:n,...Ec[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 Cc(o){return JSON.stringify(o,null,2)}function Oc(o){return Object.fromEntries(ms.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Dc(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 Kn=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 St(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let 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 St(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(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(c=>c.jobId===n);if(i.length===0)return!1;for(let c of i)if(Object.assign(c,t),c.error){let d=Nt(c);Object.assign(c,d),delete c.responseText}return s.updatedAt=Date.now(),await this.persistThread(s),!0}async updateAssistantMessage(e,n,t){let s=(await this.load()).threads[e];if(!s)return!1;let i=[...s.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return i?(Object.assign(i,t),s.updatedAt=Date.now(),await this.persistThread(s),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let s=new Set(r.elementIdentifiers);for(let i of n)s.has(i)||r.elementIdentifiers.push(i);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,s)=>s.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let i=r.messages.find(h=>h.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(h=>h.role==="assistant"),d=h=>{if(h.role!=="assistant")return;if(h.question)return h.question;let f=h.imprintSummary?.grounding;if(f?.question&&!h.imprintSummary?.resolvedAction)return f.question},l=r.messages.findLastIndex(h=>!!d(h)),g=r.messages.findLastIndex(h=>h.role==="human"),R=l>g?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,I=Array.from(new Set(r.messages.slice(0,Math.max(0,g)).filter(h=>h.role==="assistant"&&!!h.jobId).map(h=>h.jobId))),y=c.some(h=>!!h.responseText||!!h.question||!!h.result||!!h.memoryReviewCard||!!h.memoryReceipt),p=c.some(h=>!!h.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:i,messageCount:r.messages.length,hasReply:y,hasError:p,lastMessageRole:b,pendingQuestion:R,acknowledgedJobIds:I,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await St(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...s})=>{let i={};if(r?.path)try{let c=await St(De(Vn(this.legacyFilePath),r.path),"utf8");Gn("sha256").update(c).digest("hex")===r.sha256&&(i=JSON.parse(c))}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=Oc(e),t=Dc(e);if(Object.keys(n).length===0)return t;let r=Cc(n),s=Gn("sha256").update(r).digest("hex"),i=De("artifacts","thread-messages",`${s}.json`);await an(this.artifactsDir,{recursive:!0});try{await St(De(Vn(this.legacyFilePath),i),"utf8")}catch{await Jt(De(Vn(this.legacyFilePath),i),r)}return{...t,detailArtifact:{path:i,sha256:s}}}async persistMessageMedia(e){let n=async t=>{if(Vn(t)===this.mediaDir)return t;try{let r=await St(t),s=Gn("sha256").update(r).digest("hex"),i=De(this.mediaDir,`${s}${_c(t)||".bin"}`);await an(this.mediaDir,{recursive:!0});try{await St(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]??`${Gn("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 Ac(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}};import{mkdir as Jc,open as Nc,readFile as Bc,rename as Fc,unlink as Lc}from"fs/promises";import{dirname as zc,join as Uc}from"path";var fs={schemaVersion:1,theme:"auto",updatedAt:null};function hs(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function qc(o,e){await Jc(zc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Nc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
202
|
+
`,"utf8"),await t.sync()}finally{await t.close()}await Fc(n,o)}catch(t){throw await Lc(n).catch(()=>{}),t}}var Qn=class{constructor(e){this.path=Uc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Bc(this.path,"utf8")),n=hs(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...fs}}}catch{return{exists:!1,preferences:{...fs}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await qc(this.path,n),n}};function gs(o){return hs(o)!==null}function ys(o){return Hc(o).slice(0,12)}var Wc=[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 Hc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Gc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(n/Math.pow(2,b*8)&255);let t=1779033703,r=3144134277,s=1013904242,i=2773480762,c=1359893119,d=2600822924,l=528734635,g=1541459225,R=new Array(64);for(let b=0;b<e.length;b+=64){for(let A=0;A<16;A++){let J=b+A*4;R[A]=(e[J]<<24|e[J+1]<<16|e[J+2]<<8|e[J+3])>>>0}for(let A=16;A<64;A++){let J=Ye(R[A-15],7)^Ye(R[A-15],18)^R[A-15]>>>3,_=Ye(R[A-2],17)^Ye(R[A-2],19)^R[A-2]>>>10;R[A]=R[A-16]+J+R[A-7]+_>>>0}let I=t,y=r,p=s,h=i,f=c,v=d,x=l,S=g;for(let A=0;A<64;A++){let J=Ye(f,6)^Ye(f,11)^Ye(f,25),_=f&v^~f&x,N=S+J+_+Wc[A]+R[A]>>>0,T=Ye(I,2)^Ye(I,13)^Ye(I,22),B=I&y^I&p^y&p,W=T+B>>>0;S=x,x=v,v=f,f=h+N>>>0,h=p,p=y,y=I,I=N+W>>>0}t=t+I>>>0,r=r+y>>>0,s=s+p>>>0,i=i+h>>>0,c=c+f>>>0,d=d+v>>>0,l=l+x>>>0,g=g+S>>>0}return[t,r,s,i,c,d,l,g].map(b=>b.toString(16).padStart(8,"0")).join("")}function Ye(o,e){return o>>>e|o<<32-e}function Gc(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 dn=vs.version;var rd=1111,sd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],id=1800*1e3,ad=3600*1e3,bs=45e3,cd=5e3,dd=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(`
|
|
203
|
+
`)}function Yn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function ld(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 pd(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let s=n[n.length-1];s&&s.kind==="text"?s.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",s=t.file??void 0,i=t.content??void 0,c=s?s.split("/").pop()??s:void 0,d;switch(r){case"Read":d=c?`Reading ${c}`:"Reading file";break;case"Edit":d=c?`Editing ${c}`:"Editing file";break;case"Write":d=c?`Writing ${c}`:"Writing file";break;case"Bash":d=i?i.split(`
|
|
204
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let l=s??i??void 0,g=s?Lo(s)?s:js(e,s):void 0,R=n[n.length-1];R&&R.kind==="tool_group"&&R.tool===r?R.items.push({label:d,detail:l,...g?{filePath:g}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:l,...g?{filePath:g}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function ud(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(`
|
|
205
|
+
`)}function md(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 c=i.element?.reactComponent||i.element?.tagName||i.selector;return i.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(i=>`${i.tokenName}: ${i.originalPx}px -> ${i.newPx}px`),t=(o.textModifications??[]).map(i=>`${i.element?.reactComponent||i.element?.tagName||i.selector}: text ${i.original||"empty"} -> ${i.modified||"empty"}`),r=o.annotations.map(i=>{let c=i.instruction?.trim();if(c)return c;if(i.imageCount&&i.imageCount>0)return`${i.imageCount} image${i.imageCount===1?"":"s"}`;let d=i.elements?.[0]?.reactComponent||i.elements?.[0]?.selector||i.linkedSelector||i.type;return`${i.type==="annotation"?"Annotation":`${i.type} annotation`} on ${d}`}),s=[...e,...t,...n,...r].map(i=>md(i)).filter(Boolean);return s.length===0?"Annotation":s.length<=3?s.join("; "):`${s.slice(0,3).join("; ")}; +${s.length-3} more`}function fd(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 Ue(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 hd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function gd(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 Zn(o,e){try{o.res.write(`event: ${e.type}
|
|
386
206
|
data: ${JSON.stringify(e)}
|
|
387
207
|
|
|
388
|
-
`)}catch{}}function
|
|
208
|
+
`)}catch{}}function kt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function yd(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 vd(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 ks(o){try{let e=eo("git",["rev-parse","HEAD"],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim(),n=["--",".",":(exclude).popmelt/**",":(exclude)**/.popmelt/**"],t=eo("git",["status","--porcelain","--untracked-files=all",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:1024*1024}),r=eo("git",["diff","HEAD",...n],{cwd:o,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3,maxBuffer:2*1024*1024});return Ts("sha256").update(`${e}
|
|
389
209
|
${t}
|
|
390
|
-
${
|
|
210
|
+
${r}`).digest("hex").slice(0,16)}catch{return}}function wd(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 Ps(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let s of[...t].sort((i,c)=>`${i.kind}:${i.value}`.localeCompare(`${c.kind}:${c.value}`)))if(s.kind==="model_path")r.push([s.kind,s.value,wd(n,s.value)]);else if(s.kind==="source_file"){let i=js(o,s.value),d=i===o||i.startsWith(`${o}/`)?await Fo(i,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([s.kind,s.value,d])}else r.push([s.kind,s.value]);return Ts("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function zo(o={}){let e=new Date().toISOString(),n=o.port??rd,t=o.projectRoot??process.cwd(),r=await Xc(t).catch(()=>t),s=ys(r),i=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ae(td(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,g=[...o.allowedTools??sd],R=o.claudePath??"claude",b=o.copilotPath??"copilot",I=o.provider??"claude",y=o.timeoutMs,p=o.restartMode??"embedded",h=n,f={},v={claude:R,codex:"codex",copilot:b};for(let[a,u]of Object.entries(v))try{let P=u.includes("/")?u:eo("which",[u],{encoding:"utf-8"}).trim();f[a]={available:!0,path:P}}catch{f[a]={available:!1,path:null}}function x(a,u){return new Promise(P=>{let m=ws(u,["--version"],{stdio:["ignore","ignore","ignore"]}),k=!1,w=C=>{k||(k=!0,P(C))},j=setTimeout(()=>{m.kill("SIGTERM"),w(!0)},5e3);m.on("error",()=>{clearTimeout(j),w(!1)}),m.on("close",C=>{clearTimeout(j),w(C===0)})})}await Promise.all([(async()=>{f.claude&&(f.claude.models=f.claude.available&&f.claude.path?await ts(f.claude.path).catch(()=>Fn):Fn)})(),(async()=>{f.codex&&(f.codex.models=f.codex.available&&f.codex.path?await es(f.codex.path).catch(()=>nn):nn)})(),(async()=>{f.copilot&&(f.copilot.models=f.copilot.available&&f.copilot.path?await Zr(f.copilot.path).catch(()=>[on]):[on])})()]);let[S,A,J]=await Promise.all([yo(r),vo(r),wo(r,f.copilot?.path??b)]),_=await wr(r);f.claude&&(f.claude.mcp=S),f.codex&&(f.codex.mcp=A),f.copilot&&(f.copilot.mcp=J),S.found&&S.name&&g.push(`mcp__${S.name}__*`),await Kc(c,{recursive:!0}),Rs(c).catch(()=>{});let N=new zn(1),T=new kn,B=new Tn(bs),W=null,ee=0,H=!1,te=()=>{ee+=1,H=!1,W&&clearTimeout(W),W=null},ne=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ge=()=>{if(p!=="detached"||B.size>0||H)return;H=!0;let a=++ee,u=Date.now()+dd,P=()=>{if(a!==ee)return;if(B.size>0){te();return}if(!(N.isRunning||N.depth>0||T.isRunning||T.depth>0)||Date.now()>=u){H=!1,W=setTimeout(ne,50),W.unref?.();return}W=setTimeout(P,250),W.unref?.()};P()},X=new Set,G=new Kn(r),U=new On(r),he=new sn(r,s),M=new Qn(r),Y=new yn(r),ue=new In(r),ie=new Sn(r,{claudePath:R,provider:I,timeoutMs:y,loadProjectableDecisions:a=>U.getProjectableDecisions(a),onEvent:a=>{for(let u of X)Zn(u,a)}});U.beginAutomaticInitialization({writerVersion:dn}).then(async a=>{a.state==="ready"?(await U.migrateLegacyEvals(),await U.migrateImprintSnapshot(),await ie.applyCanonicalEntries(await U.getCanonicalModelEntries()),I!=="copilot"&&(await ie.getUnprojectedPatternDecisions()).length>0&&await Ee({provider:I,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${h}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let Je=20,Ne=300*1e3,Pe=[];function qe(){let a=Date.now()-Ne;for(;Pe.length>0&&(Pe[0].completedAt<a||Pe.length>Je);)Pe.shift()}let Ve=new Map;async function Ze(a){if(a.status!=="applied")return[];let u={version:1,updatedAt:Date.now(),cases:await U.getJournalEvalCases()},P=ar(a,u);if(P.length===0)return[];let m=await U.getEvalDependenciesForDecisions(a.decisionIds),k=a.threadId?await G.getThread(a.threadId):null,w=[...new Set((k?.messages??[]).flatMap(D=>(D.editEvents??[]).flatMap(L=>L.filePath?[L.filePath]:[])).map(D=>Lo(D)?Is(r,D):D))].map(D=>({kind:"source_file",value:D})),j=P.map(D=>{let L=[...new Map([...D.dependencies??[],...m,...w].map(q=>[`${q.kind}:${q.value}:${"subjectId"in q?q.subjectId??"":""}`,q])).values()],F=L.filter(q=>q.kind==="route"),$=L.flatMap(q=>q.kind==="model_path"&&q.value.startsWith("components.")?[q.value.slice(11).split(".")[0]]:[]),O=[...new Set(L.flatMap(q=>"subjectId"in q&&q.subjectId?[q.subjectId]:[]))],K=F.length>0?F.map((q,se)=>({id:`route-${se+1}`,...q.value.includes("*")?{routePattern:q.value}:{route:q.value},components:$.map(ae=>({name:ae})),subjectIds:O})):[{id:$.length>0?`component-${$[0]}`:"current-page",components:$.map(q=>({name:q})),subjectIds:O}];return{...D,dependencies:L,scenarios:D.scenarios?.length?D.scenarios:K}}),C=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:C.has(D.id)&&(a.evalProjections?.some(L=>L.evalId===D.id)||!a.generatedEvalIds?.includes(D.id))?"extended":"created"}))),j.map(D=>D.id)}async function st(a){let u=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",P=co(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:[P],rationale:`Protects the ${a.modelPath} constraint from implementation drift.`,sourceDecisionIds:[a.decisionId],sourceThreadIds:[],dependencies:[{kind:"model_path",value:a.modelPath}],scenarios:[{id:a.modelPath.startsWith("components.")?`component-${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,Ft;N.addListener((a,u,P)=>{for(let m of X)(!P||!m.sourceId||m.sourceId===P)&&Zn(m,a)}),T.addListener((a,u,P)=>{for(let m of X)(!P||!m.sourceId||m.sourceId===P)&&Zn(m,a)}),T.setProcessor(async a=>{let u=a.provider??I;try{let P=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(),k=P.runId?m.runs.find(j=>j.id===P.runId):void 0;if(P.success&&P.proposalId){let j=await ie.findModelProposal(P.proposalId),C=await ie.loadModel(),D=j?fr(j,C):null;if(j&&D){let L=j.decisionIds.map($=>({decisionId:$,status:"projected"}));await U.applyModelProjection({runId:j.runId??j.id,presentationJobId:j.presentationJobId,decisionIds:j.decisionIds,changes:D.map($=>({path:$.path,value:$.value,decisionIds:$.decisionIds})),coverage:L});let F=await ie.applySelectedModelProposal(j.id,D.map($=>({path:$.path,value:$.value})),D.map($=>({group:$.path[0]==="rules"||$.path[0]==="components"||$.path[0]==="tokens"?$.path[0]:"model",label:$.label??$.id,detail:$.rationale,path:$.path,value:$.value})),"automatic");F&&await Ze(F)}}let w=ud(P,k);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})),P.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"}),qe();else{if(a.status="error",a.error=P.error??"Projection failed",a.threadId){let j=`Model projection failed.
|
|
391
211
|
|
|
392
|
-
${
|
|
212
|
+
${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"}),qe()}}catch(P){if(a.status==="cancelled")return;if(a.status="error",a.error=P instanceof Error?P.message:String(P),a.threadId){let m=`Model projection failed.
|
|
393
213
|
|
|
394
|
-
${
|
|
214
|
+
${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"}),qe()}}),N.setProcessor(async a=>{let u=a,P=u._replyPrompt,m=u._replyText,k=u._replyImagePaths,w=a.provider??I,j=!!(a.surfacedProposalIds?.length&&P),C=!!u._evalRemediation,D=!j&&!["run_eval","synthesize_evals","synthesize","project_model"].includes(a.kind??"");a.threadId&&m!==void 0&&await G.updateMessage(a.threadId,a.id,{queued:!1});let L;if(a.threadId){let de=await G.getThread(a.threadId);if(de){for(let pe=de.messages.length-1;pe>=0;pe--)if(de.messages[pe].sessionId){L=de.messages[pe].sessionId;break}}}(j||C)&&(L=void 0);let F;if(L&&P){if(F=m??P,k&&k.length>0){F+=`
|
|
395
215
|
|
|
396
|
-
The developer attached reference images with their reply:`;for(let
|
|
397
|
-
Attached image: use the Read tool to view the image at: ${
|
|
216
|
+
The developer attached reference images with their reply:`;for(let de of k)F+=`
|
|
217
|
+
Attached image: use the Read tool to view the image at: ${de}`}a.kind==="synthesize"||a.kind==="synthesize_evals"||a.kind==="run_eval"?F+=`
|
|
398
218
|
|
|
399
|
-
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:
|
|
219
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+=`
|
|
400
220
|
|
|
401
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(
|
|
221
|
+
After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(L)F=en(a.feedback,a.imagePaths)+`
|
|
402
222
|
|
|
403
223
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
404
224
|
|
|
405
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(
|
|
225
|
+
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(w!=="codex"?`
|
|
406
226
|
|
|
407
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${r.screenshotPath}`:"");else{let O=!u&&r.threadId?await y.getThreadHistory(r.threadId):void 0,G=u?null:await H.loadModel();g=u??An(r.screenshotPath,r.feedback,{threadHistory:O&&O.length>0?O:void 0,provider:d,imagePaths:r.imagePaths,designModel:G??void 0,screenshotPaths:r.screenshotPaths})}let b=Jr(r.color,`[\u22B9 ${W}:${r.id}]`),P=r.screenshotPaths&&Object.keys(r.screenshotPaths).length>0?`${Object.keys(r.screenshotPaths).length} pages [${Object.keys(r.screenshotPaths).join(", ")}]`:r.screenshotPath;console.log(`${b} Reviewing ${P} (provider: ${d})${r.threadId?` (thread: ${r.threadId})`:""}${I?` (resuming: ${I.slice(0,8)})`:""}`);let $=(O,G)=>{O.type==="delta"&&"text"in O?D.accumulateText(G,"response",O.text):O.type==="thinking"&&"text"in O&&D.accumulateText(G,"thinking",O.text),D.broadcast(O,G,r.sourceId)},{process:te,result:X}=d==="codex"?Ve(r.id,{prompt:g,projectRoot:t,screenshotPath:r.screenshotPath,resumeSessionId:I,model:r.model,configOverrides:Qe(r.agentSettings),onEvent:$}):d==="copilot"?Zt(r.id,{prompt:g,projectRoot:t,resumeSessionId:I,model:r.model,timeoutMs:J,copilotPath:w.copilot?.path??E,onEvent:$}):Xe(r.id,{prompt:g,projectRoot:t,maxTurns:l,maxBudgetUsd:f,allowedTools:v,claudePath:x,resumeSessionId:I,model:r.model,reasoningEffort:r.agentSettings?.reasoningEffort,timeoutMs:J,onEvent:$});D.setActiveProcess(r.id,te);let S=await X;if(r.result=S.text,S.success){console.log(`${b} Iteration complete`),S.fileEdits&&S.fileEdits.length>0&&console.log(`${b} Captured ${S.fileEdits.length} file edit(s): ${S.fileEdits.map(F=>`${F.tool} ${F.file_path}`).join(", ")}`),S.editEvents&&S.editEvents.length>0&&console.log(`${b} Captured ${S.editEvents.length} edit event(s): ${S.editEvents.map(F=>`${F.operation} ${F.filePath}`).join(", ")}`),r.status="done";let O=$n(S.text),G=Cn(S.text),se=G.some(F=>(F.finalScope??F.inferredScope)?.breadth==="pattern");if(G.length>0&&r.annotationIds&&r.annotationIds.length>0){let F=new Set(r.annotationIds);G.every(ne=>F.has(ne.annotationId))||(G=G.map((ne,fe)=>({...ne,annotationId:r.annotationIds[fe%r.annotationIds.length]})))}let ce=S.fileEdits&&S.fileEdits.length>0?S.fileEdits.map(F=>`${F.tool} ${F.file_path.split("/").pop()}`):S.toolsUsed,ue=D.getBufferedEvents(r.id),pe=ue?$r(ue.events):void 0;if(r.threadId&&await y.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,responseText:S.text,resolutions:G.length>0?G:void 0,question:O??void 0,sessionId:S.sessionId,toolsUsed:ce,editEvents:S.editEvents&&S.editEvents.length>0?S.editEvents:void 0,segments:pe&&pe.length>0?pe:void 0,model:r.model,provider:d}),r.kind!=="run_eval"&&le.captureGitDiff(t).then(async F=>{let oe=Date.now(),ne=r.imagePaths?Object.values(r.imagePaths).flat():[],fe=[];if(r.imagePaths)for(let[j,M]of Object.entries(r.imagePaths))for(let Y=0;Y<M.length;Y++)fe.push(`screenshots/p-${r.id}-${j}-${Y}.webp`);await le.persist({version:1,id:r.id,createdAt:r.createdAt,completedAt:oe,durationMs:oe-r.createdAt,url:r.feedback.url,viewport:r.feedback.viewport,screenshotPath:`screenshots/s-${r.id}.webp`,pastedImagePaths:fe,annotations:r.feedback.annotations,styleModifications:r.feedback.styleModifications,inspectedElement:r.feedback.inspectedElement,provider:d,model:r.model,sessionId:S.sessionId,threadId:r.threadId,responseText:S.text,resolutions:G.length>0?G:[],question:O??void 0,fileEdits:S.fileEdits??[],editEvents:S.editEvents??[],toolsUsed:ce,gitDiff:F},r.screenshotPath,ne),se&&d!=="copilot"?await Nt({provider:d,model:r.model,agentSettings:r.agentSettings,threadId:r.threadId,annotationIds:r.annotationIds,sourceId:r.sourceId,reason:`Materialize model \u2014 ${r.feedback.annotations[0]?.instruction??"pattern decision"}`}):se&&console.log(`${b} Skipping materialization for Copilot provider`)}).catch(()=>{}),r.kind==="synthesize"&&S.text){let F=st(S.text);if(F){Array.isArray(F.rules)&&(F.rules=Je(F.rules));let oe=await H.loadModel();oe&&(!F.tokens&&oe.tokens&&(F.tokens=oe.tokens),!F.components&&oe.components&&(F.components=oe.components)),await H.writeModel(F),console.log(`${b} Synthesize: model.json updated`)}}else if(r.kind==="synthesize_evals"&&S.text){let F=on(S.text),oe=rn(S.text),ne=F??oe;if(ne&&ne.length>0){let fe=await ie.writeSynthesized(ne),j=r._proposalId;j&&await H.attachGeneratedEvals(j,ne.map(M=>M.id)),console.log(`${b} Eval synthesis: wrote ${ne.length} ${F?"approved":"pending"} eval(s) \u2192 .popmelt/evals/evals.json (${fe.cases.length} total)`)}}else if(r.kind==="run_eval"&&S.text&&r.evalId&&r.evalRunId){let F=await ie.findCase(r.evalId),oe=r._evalRunScope;if(F&&oe){let ne=an(S.text,F.assertions),fe=Date.now();await ie.writeRun({id:r.evalRunId,evalId:r.evalId,threadId:r.threadId,createdAt:r.createdAt,completedAt:fe,durationMs:fe-r.createdAt,scope:oe,provider:d,model:r.model,screenshotPath:r._evalScreenshotPath,codeFingerprint:Qn(t),rawResponse:S.text,...ne}),console.log(`${b} Eval run: ${F.title} \u2192 ${ne.status}`)}}O&&(console.log(`${b} \u{1F4AC} Question detected: "${O.slice(0,120)}" \u2192 broadcasting to ${ee.size} SSE clients (threadId=${r.threadId??r.id}, annotationIds=${r.annotationIds?.join(",")??"none"})`),D.broadcast({type:"question",jobId:r.id,threadId:r.threadId??r.id,question:O,annotationIds:r.annotationIds},r.id,r.sourceId));let de=_n(S.text);de.length>0&&(console.log(`${b} Novel pattern(s): ${de.map(F=>`${F.category}/${F.element}`).join(", ")}`),D.broadcast({type:"novel_patterns",jobId:r.id,patterns:de,threadId:r.threadId},r.id,r.sourceId)),D.broadcast({type:"done",jobId:r.id,success:!0,resolutions:G.length>0?G:void 0,responseText:S.text,threadId:r.threadId},r.id,r.sourceId),we.push({id:r.id,status:"done",completedAt:Date.now(),threadId:r.threadId,annotationIds:r.annotationIds})}else console.error(`${b} Error: ${S.error}`),r.status="error",r.error=S.error,r.threadId&&await y.appendMessageBeforeQueuedReplies(r.threadId,{role:"assistant",timestamp:Date.now(),jobId:r.id,error:S.error||"Unknown error",model:r.model,provider:d}),D.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:S.error||"Unknown error",provider:d,model:r.model,recoverable:S.recoverableError,code:S.errorCode},r.id,r.sourceId),we.push({id:r.id,status:"error",completedAt:Date.now(),error:S.error,threadId:r.threadId,annotationIds:r.annotationIds});Ge()});let yt=xr(async(r,c)=>{if(Dr(r,c),r.method==="OPTIONS"){c.writeHead(204),c.end();return}let u=r.url||"/",p=u.split("?")[0],h=new URL(u,`http://127.0.0.1:${W}`),d=h.pathname,I=Nr(r,h);if(I&&I!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,projectName:ht(t)});return}if(r.headers.origin){if(!Yn(r.headers.origin)){m(c,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(I!==o){m(c,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:o,requestProjectId:I,projectName:ht(t)});return}}try{if(r.method==="POST"&&d==="/send")await Zn(r,c);else if(r.method==="GET"&&d==="/events")ts(r,c);else if(r.method==="GET"&&d==="/status")await ns(c,I);else if(r.method==="PATCH"&&d==="/config")await ss(r,c);else if(r.method==="POST"&&d==="/leases"){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}try{let g=await Or(r),b=typeof g.leaseId=="string"?g.leaseId.trim():"",P=typeof g.ownerPid=="number"&&Number.isInteger(g.ownerPid)&&g.ownerPid>0?g.ownerPid:void 0;if(!b||b.length>128){m(c,400,{error:"A valid leaseId is required."});return}T();let $=k.acquire(b,P);m(c,201,{ok:!0,lease:$,ttlMs:Gn})}catch{m(c,400,{error:"Invalid lease request."})}}else if(d.startsWith("/leases/")&&(r.method==="PATCH"||r.method==="DELETE")){if(U!=="detached"){m(c,409,{error:"Bridge leases are only available for detached bridges."});return}let g="";try{g=decodeURIComponent(d.slice(8))}catch{m(c,400,{error:"Invalid lease id."});return}if(!g){m(c,400,{error:"A lease id is required."});return}if(r.method==="PATCH"){let b=k.heartbeat(g);if(!b){m(c,404,{error:"Lease not found."});return}m(c,200,{ok:!0,lease:b})}else{let b=k.release(g);m(c,b.found?200:404,{ok:b.found}),b.becameEmpty&&_()}}else if(r.method==="POST"&&d==="/shutdown"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0}),setTimeout(L,100)}else if(r.method==="POST"&&d==="/restart"){if(U!=="detached"){m(c,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:U});return}m(c,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let g of ee)try{g.res.end()}catch{}yt.close(()=>{Un(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(r.method==="GET"&&d==="/capabilities")m(c,200,{providers:w});else if(r.method==="POST"&&d==="/mcp/install")await ms(r,c);else if(r.method==="POST"&&d==="/reply")await es(r,c);else if(r.method==="POST"&&d==="/cancel")os(r,c);else if(r.method==="POST"&&d==="/materialize")await rs(r,c);else if(r.method==="GET"&&d==="/materialization-runs"){let g=await H.loadRuns();m(c,200,g)}else if(r.method==="GET"&&d==="/model/proposals"){let g=await H.loadModelProposals();m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply-selected")){let g=d.slice(17,-15);await as(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/apply")){let g=d.slice(17,-6);await is(g,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/dismiss")){let g=d.slice(17,-8);await ls(g,r,c)}else if(r.method==="POST"&&d.startsWith("/model/proposals/")&&d.endsWith("/project-evals")){let g=d.slice(17,-14);await cs(g,r,c)}else if(r.method==="POST"&&d==="/model/component")await gs(r,c);else if(r.method==="DELETE"&&d==="/model/component")await ys(r,c);else if(r.method==="PATCH"&&d==="/model/token")await vs(r,c);else if(r.method==="DELETE"&&d==="/model/token")await ws(r,c);else if(r.method==="POST"&&d==="/model/consolidate"){let{provider:g,model:b,agentSettings:P}=await Me(r);if(g==="copilot"){m(c,400,{error:"Model consolidation is not available for Copilot yet."});return}H.consolidate({provider:g,model:b,agentSettings:P}).catch($=>console.error("[Bridge] Consolidation error:",$)),m(c,200,{started:!0})}else if(r.method==="POST"&&d==="/model/synthesize")await ds(r,c);else if(r.method==="POST"&&d==="/evals/synthesize")await us(r,c);else if(r.method==="GET"&&d==="/evals"){let g=await ie.loadSuiteWithCurrentRuns(Qn(t));m(c,200,g)}else if(r.method==="POST"&&d.startsWith("/evals/")&&d.endsWith("/run")){let g=d.slice(7,-4);await ps(g,r,c)}else if(r.method==="PATCH"&&d.startsWith("/evals/"))await fs(d.slice(7),r,c);else if(r.method==="GET"&&d==="/model"){let g=await H.loadModel();m(c,200,{model:g})}else if(r.method==="GET"&&d.startsWith("/jobs/")&&d.endsWith("/events")){let g=d.slice(6,d.length-7),b=parseInt(h.searchParams.get("afterSeq")??"-1",10),P=D.getBufferedEvents(g,isNaN(b)?-1:b);P?m(c,200,P):m(c,404,{error:"Unknown job"})}else if(r.method==="GET"&&p.startsWith("/files/"))await Is(p.slice(7),c);else if(r.method==="GET"&&d==="/threads/recent"){let g=Math.min(Math.max(parseInt(h.searchParams.get("limit")??"5",10)||5,1),20),b=await y.listRecent(g);m(c,200,b)}else if(r.method==="GET"&&d.startsWith("/thread/")){let g=d.slice(8);await Ps(g,c)}else if(r.method==="DELETE"&&d.startsWith("/thread/")){let g=d.slice(8);await ks(g,c)}else r.method==="GET"&&(d==="/canvas"||d==="/canvas/")?Ss(r,c):r.method==="GET"&&d==="/canvas/manifest"?await xs(c):r.method==="GET"&&d==="/canvas/app.mjs"?await bs(c):m(c,404,{error:"Not found"})}catch(g){console.error("[Bridge] Request error:",g),m(c,500,{error:g instanceof Error?g.message:"Internal error"})}});async function Zn(r,c){let{screenshot:u,feedback:p,color:h,provider:d,model:I,reasoningEffort:g,serviceTier:b,sourceId:P,pastedImages:$,pageScreenshots:te}=await lt(r),X;try{X=JSON.parse(p)}catch{m(c,400,{error:"Invalid feedback JSON"});return}let S=Pe().slice(0,8),O={};if(te.length>0)for(let M of te){let Y=encodeURIComponent(M.pathname),re=ve(a,`screenshot-${S}-${Y}.webp`);await Ue(re,M.data),O[M.pathname]=re}let G=ve(a,`screenshot-${S}.webp`);await Ue(G,u);let se={};if($.length>0)for(let M of $){let Y=ve(a,`pasted-${S}-${M.annotationId}-${M.index}.webp`);await Ue(Y,M.data),se[M.annotationId]||(se[M.annotationId]=[]),se[M.annotationId].push(Y)}let ce=X.annotations.map(M=>M.linkedSelector?M.pathname?`${M.pathname}:${M.linkedSelector}`:M.linkedSelector:null).filter(M=>!!M),ue;if(ce.length>0){let M=await y.findContinuationThread(ce);M?(ue=M.id,await y.addElementIdentifiers(ue,ce)):ue=(await y.createThread(S,ce)).id}else ue=(await y.createThread(S,[])).id;let pe=X.annotations.map(M=>M.id),de=Object.keys(O).length>0,F={id:S,status:"queued",screenshotPath:G,feedback:X,createdAt:Date.now(),color:h,threadId:ue,annotationIds:pe,provider:We(d),model:I||void 0,agentSettings:Ee({reasoningEffort:g,serviceTier:b}),...Object.keys(se).length>0?{imagePaths:se}:{},sourceId:P||void 0,...de?{screenshotPaths:O}:{}},oe=new Set(X.annotations.map(M=>M.pathname).filter(Boolean)),ne;if(oe.size>1){let M=new Map;for(let Y of X.annotations){let re=Y.pathname||"(unknown)";M.has(re)||M.set(re,[]),M.get(re).push(Y.instruction||qn({...X,annotations:[Y]}))}ne=[...M.entries()].map(([Y,re])=>`\`${Y}\`
|
|
408
|
-
|
|
227
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let de=!P&&a.threadId?await G.getThreadHistory(a.threadId):void 0,pe=P?null:await ie.loadModel();F=P??Gr(a.screenshotPath,a.feedback,{threadHistory:de&&de.length>0?de:void 0,provider:w,imagePaths:a.imagePaths,designModel:pe??void 0,screenshotPaths:a.screenshotPaths})}F+=zr(a.memoryReview),D&&(F+=No(a.imprintContext)),F+=`
|
|
228
|
+
|
|
229
|
+
${Hr}`;let $=gd(a.color,`[\u22B9 ${h}:${a.id}]`),O=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${$} Reviewing ${O} (provider: ${w})${a.threadId?` (thread: ${a.threadId})`:""}${L?` (resuming: ${L.slice(0,8)})`:""}`);let K=new Nn(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"?gn(a.id,{prompt:F,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:L,model:a.model,sandboxMode:j?"read-only":void 0,configOverrides:mn(a.agentSettings),onEvent:q}):w==="copilot"?rr(a.id,{prompt:F,projectRoot:r,resumeSessionId:L,model:a.model,timeoutMs:y,copilotPath:f.copilot?.path??b,onEvent:q}):fn(a.id,{prompt:F,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:j?["Read"]:g,claudePath:R,resumeSessionId:L,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:y,onEvent:q});N.setActiveProcess(a.id,se);let oe=await ae,xe=K.finalize(oe.text),we=xe.visibleText,V=D?Jo(we):{visibleText:we,draft:void 0,error:void 0},be=V.visibleText;for(let de of xe.orientations)N.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=be,oe.success){console.log(`${$} Iteration complete`),oe.fileEdits&&oe.fileEdits.length>0&&console.log(`${$} 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(`${$} Captured ${oe.editEvents.length} edit event(s): ${oe.editEvents.map(z=>`${z.operation} ${z.filePath}`).join(", ")}`),a.status="done";let de=Vr(we),pe=Qr(we);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let z=new Set(a.annotationIds);pe.every(Ke=>z.has(Ke.annotationId))||(pe=pe.map((Ke,Qe)=>({...Ke,annotationId:a.annotationIds[Qe%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),tt=Ce?pd(Ce.events,r):void 0,Re,Z=qr(we),fe=Ur(we);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 Te=[...(oe.fileEdits??[]).map(z=>z.file_path),...(oe.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])],Se,gt=a.imprintContext?.pendingGroundingExplanationIds??[];if(V.draft?.decision==="none"&&he.recordNoop(V.draft.reason),a.threadId&&V.draft?.decision==="mutate"&&!fe&&!Z)try{Se=await he.capture(V.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await ie.loadModel(),pendingGroundingExplanationIds:gt}),Se&&await U.recordImprintEvidence({summary:Se,threadId:a.threadId,jobId:a.id}).catch(z=>console.warn(`${$} Canonical Imprint evidence linkage failed:`,z))}catch(z){console.warn(`${$} Continuous imprint update failed; the thread result remains available:`,z instanceof Error?z.message:String(z))}else V.error&&console.warn(`${$} Ignored invalid imprint block: ${V.error}`);let We=Se?.transactionId;if(a.threadId&&Se&&!Se.grounding){let z=await G.getThread(a.threadId),re=new Set(Se.changes.map(Qe=>Qe.explanationId)),Ke=z?ld(z.messages,re):void 0;if(Ke?.imprintSummary){let Qe=Ke.imprintSummary;await G.updateAssistantMessage(a.threadId,Ke.jobId,{imprintSummary:{...Qe,detail:Se.detail,changes:Se.changes,additionalObservationCount:(Qe.additionalObservationCount??0)+1,coalescedTransactionIds:[...Qe.coalescedTransactionIds??[],Se.transactionId]}}),Se=void 0}}let Ut=us({question:de,resolutions:pe,changedFiles:Te,decisionRequired:!!Z,imprintTransactionId:We,groundingRequired:!!Se?.grounding}),Q=tt?.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.":be;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&&tt&&tt.length>0?tt:void 0,turn:{phase:"complete",orientation:Q,result:Ut},result:Ut,memoryReviewCard:Z??void 0,memoryReceipt:Re,imprintSummary:Se,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??(Dn(a.feedback)||"[request unavailable]"),responseSummary:de??be,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=>Lo(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(`${$} 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 Ee({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"&&be&&a.evalId&&a.evalRunId){let z=await U.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(z&&re){let Ke=ir(we,z.assertions),Qe=Date.now(),Us={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Qe,durationMs:Qe-a.createdAt,scope:re,provider:w,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:ks(r),rawResponse:we,scopeFingerprint:a._evalScopeFingerprint,...Ke};await U.recordEvalVerification(z,Us),console.log(`${$} Eval run: ${z.title} \u2192 ${Ke.status}`)}}de&&(console.log(`${$} \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=Xr(we);me.length>0&&(console.log(`${$} 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:be,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(`${$} 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});qe()});let Lt=ed(async(a,u)=>{if(fd(a,u),a.method==="OPTIONS"){u.writeHead(204),u.end();return}let P=a.url||"/",m=P.split("?")[0],k=new URL(P,`http://127.0.0.1:${h}`),w=k.pathname,j=hd(a,k);if(j&&j!==s){E(u,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:s,requestProjectId:j,projectName:Xn(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:Xn(r)});return}}try{if(a.method==="POST"&&w==="/send")await _e(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 to(u);else if(a.method==="PATCH"&&w==="/ui-preferences")await no(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 C=await Ue(a),D=typeof C.leaseId=="string"?C.leaseId.trim():"",L=typeof C.ownerPid=="number"&&Number.isInteger(C.ownerPid)&&C.ownerPid>0?C.ownerPid:void 0;if(!D||D.length>128){E(u,400,{error:"A valid leaseId is required."});return}te();let F=B.acquire(D,L);E(u,201,{ok:!0,lease:F,ttlMs: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 C="";try{C=decodeURIComponent(w.slice(8))}catch{E(u,400,{error:"Invalid lease id."});return}if(!C){E(u,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let D=B.heartbeat(C);if(!D){E(u,404,{error:"Lease not found."});return}E(u,200,{ok:!0,lease:D})}else{let D=B.release(C);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 C of X)try{C.res.end()}catch{}Lt.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 Ie(a,u,w);else if(a.method==="POST"&&w==="/mcp/install")await As(a,u);else if(a.method==="POST"&&w==="/reply")await et(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 C=await ie.loadRuns();E(u,200,C)}else if(a.method==="GET"&&w==="/projection/proposals"){let C=await ie.loadModelProposals();E(u,200,C)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply-selected")){let C=w.slice(22,-15);await dt(C,a,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/apply")){let C=w.slice(22,-6);await Be(C,u)}else if(a.method==="POST"&&w.startsWith("/projection/proposals/")&&w.endsWith("/dismiss")){let C=w.slice(22,-8);await Pt(C,a,u)}else if(w.startsWith("/model/proposals/"))E(u,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&w==="/model/component")await _s(a,u);else if(a.method==="DELETE"&&w==="/model/component")await $s(a,u);else if(a.method==="PATCH"&&w==="/model/token")await Cs(a,u);else if(a.method==="DELETE"&&w==="/model/token")await Os(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 C=await ie.loadModel(),D=await Promise.all((await U.getJournalEvalCases()).map(async $=>{let O=await Ps(r,$,C);return $.verificationState==="passing"&&(!$.verifiedScopeFingerprint||!O||$.verifiedScopeFingerprint!==O)?{...$,verificationState:"stale"}:$})),L=ks(r),F=(await U.getJournalEvalRuns()).filter($=>!$.codeFingerprint||$.codeFingerprint===L);E(u,200,{version:1,updatedAt:Date.now(),cases:D,runs:F,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&w.startsWith("/evals/")&&w.endsWith("/run")){let C=w.slice(7,-4);await oo(C,a,u)}else if(a.method==="PATCH"&&w.startsWith("/evals/"))await pn(w.slice(7),a,u);else if(a.method==="GET"&&w==="/model"){let C=await ie.loadModel();E(u,200,{model:C})}else if(a.method==="GET"&&w.startsWith("/jobs/")&&w.endsWith("/events")){let C=w.slice(6,w.length-7),D=parseInt(k.searchParams.get("afterSeq")??"-1",10),L=N.getBufferedEvents(C,isNaN(D)?-1:D);L?E(u,200,L):E(u,404,{error:"Unknown job"})}else if(a.method==="GET"&&m.startsWith("/files/"))await Bs(m.slice(7),u);else if(a.method==="GET"&&w==="/threads/recent"){let C=Math.min(Math.max(parseInt(k.searchParams.get("limit")??"5",10)||5,1),20),D=await G.listRecent(C);E(u,200,D)}else if(a.method==="GET"&&w.startsWith("/decision/")){let C=w.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(C))E(u,400,{error:"Invalid decision id"});else{let D=await G.getThread(C),L=[...D?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(D&&L?.annotationSnapshot){let F=[...D.messages].reverse().find($=>$.resolutions?.length);E(u,200,{decision:{id:D.id,createdAt:L.timestamp,url:L.annotationSnapshot.url,viewport:L.annotationSnapshot.viewport,color:L.annotationSnapshot.color,annotations:L.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await Y.loadDecision(C);F?E(u,200,{decision:F,authority:"legacy_archive"}):E(u,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&w.startsWith("/thread/")){let C=w.slice(8);await Fs(C,u)}else if(a.method==="DELETE"&&w.startsWith("/thread/")){let C=w.slice(8);await Ls(C,u)}else a.method==="GET"&&(w==="/canvas"||w==="/canvas/")?Ds(a,u):a.method==="GET"&&w==="/canvas/manifest"?await Js(u):a.method==="GET"&&w==="/canvas/app.mjs"?await Ns(u):E(u,404,{error:"Not found"})}catch(C){console.error("[Bridge] Request error:",C),E(u,500,{error:C instanceof Error?C.message:"Internal error"})}});async function Ie(a,u,P){try{if(a.method==="GET"&&P==="/memory/status"){E(u,200,await U.status());return}if(a.method==="GET"&&P==="/memory/diagnostics"){E(u,200,await U.diagnostics());return}if(a.method==="GET"&&P==="/memory/model-view"){E(u,200,await U.getModelView());return}if(a.method==="POST"&&P==="/memory/constraints"){let m=await Ue(a),k=typeof m.reactComponent=="string"?m.reactComponent.trim():"",w=typeof m.pathname=="string"?m.pathname.trim():"",j=typeof m.selector=="string"?m.selector.trim():"",C=await U.getModelView(),D=k?C.entries.filter($=>$.key===`components.${k}`||$.key.startsWith(`components.${k}.`)):[],L=($,O)=>{if(!O)return!1;if(!$.includes("*"))return $===O;let K=$.split("*").map(q=>q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${K}$`).test(O)},F=(await U.getJournalEvalCases()).filter($=>{if($.status==="rejected")return!1;let O=($.dependencies??[]).some(q=>q.kind==="route"&&L(q.value,w)||q.kind==="subject"&&q.value===j),K=($.scenarios??[]).some(q=>!!k&&(q.components??[]).some(se=>se.name===k||se.exportName===k)||!!w&&!!q.route&&q.route===w||!!w&&!!q.routePattern&&L(q.routePattern,w));return O||K}).map($=>({id:$.id,title:$.title,verificationState:$.verificationState,assertions:$.assertions}));E(u,200,{modelEntries:D,evals:F});return}if(a.method==="POST"&&P==="/memory/conversation-action"){let m=await Ue(a),k=typeof m.threadId=="string"?m.threadId:"",w=typeof m.proposalId=="string"?m.proposalId:"",j=String(m.action);if(!k||!w||!["accept","edit_and_accept","reject","defer"].includes(j)){E(u,400,{error:"A valid thread, proposal, and review action are required."});return}let C=await G.getThread(k),D=C?.messages.find(ae=>ae.memoryReviewCard?.proposalId===w)?.memoryReviewCard;if(!C||!D){E(u,409,{error:"This decision review card is not available in the thread."});return}let L=await ie.findModelProposalsByThread(k),F=(await Promise.all(L.map(async ae=>({proposal:ae,matches:(await Promise.all(ae.decisionIds.map(oe=>U.findPendingProposalForLegacyDecision(oe)))).some(oe=>oe?.proposalId===w)})))).find(ae=>ae.matches)?.proposal,$={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($.action==="edit_and_accept"&&!$.claim){E(u,400,{error:"Edited decision wording is required."});return}let O=await U.commitConversationalReview($),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(k,{role:"human",timestamp:Date.now(),jobId:K,replyToQuestion:q}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:K,responseText:"",memoryReceipt:O,provider:kt(typeof m.provider=="string"?m.provider:void 0),model:typeof m.model=="string"?m.model:void 0}),O.status==="committed"&&F&&await ie.dismissModelProposal(F.id);let se=kt(typeof m.provider=="string"?m.provider:void 0);O.status==="committed"&&O.decisionId&&se!=="copilot"&&await Ee({provider:se,model:typeof m.model=="string"?m.model:void 0,agentSettings:yt(m),threadId:k,reason:`Project accepted decision ${O.decisionId}`}),E(u,O.status==="committed"?200:409,{receipt:O});return}if(a.method==="POST"&&P==="/memory/analyze"){let m=await Ue(a),k=await U.analyzeLegacy({projectKey:typeof m.projectKey=="string"?m.projectKey:void 0}),w=Object.fromEntries([...new Set(k.issues.map(j=>j.code))].map(j=>[j,k.issues.filter(C=>C.code===j).length]));E(u,200,{...k,issues:void 0,issueCounts:w});return}if(a.method==="POST"&&P==="/memory/review"){let m=await Ue(a),k=await U.review(_o(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,k);return}if(a.method==="POST"&&P==="/memory/context"){let m=await Ue(a),k=await U.contextualize(_o(m.query),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,200,k);return}if(a.method==="POST"&&P==="/memory/initialize"){let m=await Ue(a),k=await U.initializeFromLegacy({confirmed:m.confirm===!0,projectKey:typeof m.projectKey=="string"?m.projectKey:void 0,writerVersion:dn});E(u,201,{status:k.status,report:{source:k.report.source,imported:k.report.imported,unresolvedAcceptance:k.report.unresolvedAcceptance,deferredModelEntries:k.report.deferredModelEntries,proofCases:k.report.proofCases,schemaIssues:k.report.schemaIssues}});return}if(a.method==="POST"&&P==="/memory/plan"){let m=await Ue(a),k=await U.planReview(Ao(m.command),{projectKey:typeof m.projectKey=="string"?m.projectKey:void 0});E(u,k.result.ok?200:422,k);return}if(a.method==="POST"&&P==="/memory/commit"){let m=await Ue(a),k=m.transaction&&typeof m.transaction=="object"&&!Array.isArray(m.transaction)?m.transaction:{},w=await U.commitReview(Ao(m.command),{transactionId:typeof k.transactionId=="string"?k.transactionId:"",committedAt:typeof k.committedAt=="string"?k.committedAt:""});E(u,200,{status:await U.status(),journal:w.report});return}if(a.method==="POST"&&P==="/memory/recover"){let m=await Ue(a),k=await U.recover(m.confirm===!0);E(u,200,{status:await U.status(),journal:k.report});return}E(u,404,{error:"Memory endpoint not found."})}catch(m){let k=m instanceof Error?m.message:String(m),w=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(k),j=/required|invalid|unsupported|expected|must be|confirmation/i.test(k);if(w||j){E(u,w?409:400,{error:k});return}throw m}}async function it(a,u,P){if(a.method==="GET"&&P==="/imprint/status"){let[m,k]=await Promise.all([he.store.load(),G.load()]),w=[...new Set(Object.values(k.threads).flatMap(j=>Yn(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"&&P==="/imprint/action"){let m=await Ue(a),k=typeof m.threadId=="string"?m.threadId:"",w=typeof m.transactionId=="string"?m.transactionId:"",j=String(m.action);if(!k||!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(k),L=[...D?.messages??[]].reverse().find(se=>se.role==="assistant"&&se.imprintSummary?.transactionId===w),F=L?.imprintSummary;if(!D||!L||!F){E(u,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){E(u,409,{error:"This imprint summary has already been resolved."});return}let $=`imprint-${ut().slice(0,8)}`;await he.applyGroundingAction({summary:F,action:j,value:typeof m.value=="string"?m.value:void 0,threadId:k,jobId:$}),await U.recordImprintEvidence({summary:F,action:j,threadId:k,jobId:$}).catch(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));let O=Dt(L.result,!!L.question),K=L.turn?{...L.turn,result:Dt(L.turn.result,!!L.question)}:void 0;await G.updateAssistantMessage(k,L.jobId,{imprintSummary:{...F,resolvedAction:j},...O?{result:O}:{},...K?{turn:K}:{}});let q={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:$,replyToQuestion:q[j]}),E(u,200,{ok:!0,action:j});return}E(u,404,{error:"Imprint endpoint not found."})}async function _e(a,u){let{screenshot:P,feedback:m,color:k,provider:w,model:j,reasoningEffort:C,serviceTier:D,sourceId:L,pastedImages:F,pageScreenshots:$}=await Jn(a),O;try{O=JSON.parse(m)}catch{E(u,400,{error:"Invalid feedback JSON"});return}let K=ut().slice(0,8),q={};if($.length>0)for(let Z of $){let fe=encodeURIComponent(Z.pathname),Te=Ae(c,`screenshot-${K}-${fe}.webp`);await ln(Te,Z.data),q[Z.pathname]=Te}let se=Ae(c,`screenshot-${K}.webp`);await ln(se,P);let ae={};if(F.length>0)for(let Z of F){let fe=Ae(c,`pasted-${K}-${Z.annotationId}-${Z.index}.webp`);await ln(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),xe;if(oe.length>0){let Z=await G.findContinuationThread(oe);Z?(xe=Z.id,await G.addElementIdentifiers(xe,oe)):xe=(await G.createThread(K,oe)).id}else xe=(await G.createThread(K,[])).id;let we=O.annotations.map(Z=>Z.id),V=Object.keys(q).length>0,be=await Lr(U,O,oe,Z=>console.warn(`[\u22B9 ${h}:${K}] Contextual memory unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))),de=await he.contextualize({text:Dn(O),subjectHints:[...oe,...O.annotations.flatMap(Z=>[Z.pathname,Z.elements?.[0]?.reactComponent].filter(fe=>!!fe))],pendingGroundingExplanationIds:Yn((await G.getThread(xe))?.messages??[])}).catch(Z=>{console.warn(`[\u22B9 ${h}:${K}] Imprint context unavailable; continuing without it:`,Z instanceof Error?Z.message:String(Z))}),pe={id:K,status:"queued",screenshotPath:se,feedback:O,createdAt:Date.now(),color:k,threadId:xe,annotationIds:we,provider:kt(w),model:j||void 0,agentSettings:yt({reasoningEffort:C,serviceTier:D}),...Object.keys(ae).length>0?{imagePaths:ae}:{},sourceId:L||void 0,...V?{screenshotPaths:q}:{},...be?{memoryReview:be}:{},...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 Te=fe.pathname||"(unknown)";Z.has(Te)||Z.set(Te,[]),Z.get(Te).push(fe.instruction||Ss({...O,annotations:[fe]}))}Ce=[...Z.entries()].map(([fe,Te])=>`\`${fe}\`
|
|
230
|
+
${Te.map(Se=>`- ${Se}`).join(`
|
|
409
231
|
`)}`).join(`
|
|
410
|
-
`)}else
|
|
232
|
+
`)}else Ce=Ss(O);let tt=en(O,Object.keys(ae).length>0?ae:void 0);await G.appendMessage(xe,{role:"human",timestamp:Date.now(),jobId:K,screenshotPath:se,...V?{screenshotPaths:q}:{},...Object.keys(ae).length>0?{imagePaths:ae}:{},annotationIds:we,annotationSnapshot:{url:O.url,viewport:O.viewport,annotations:O.annotations,color:k||void 0},feedbackSummary:Ce,feedbackContext:tt||void 0,...be?{memoryReview:be}:{},...de?{imprintContext:de}:{}});let Re=N.enqueue(pe);E(u,200,{jobId:K,position:Re,threadId:xe})}async function et(a,u){let P=a.headers["content-type"]||"",m,k,w,j,C,D,L,F,$,O=[];if(P.includes("multipart/form-data")){let Q=await Jn(a),me=Q.feedback?JSON.parse(Q.feedback):{};m=me.threadId,k=me.reply,w=me.color,j=me.provider,C=me.model,D=yt(me),L=me.sourceId||Q.sourceId,F=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0,$=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,k=z.reply,w=z.color,j=z.provider,C=z.model,D=yt(z),L=z.sourceId,F=z.memoryReviewProposalId,$=z.evalRemediation?.action==="resolve"&&typeof z.evalRemediation.evalId=="string"?{evalId:z.evalRemediation.evalId,action:"resolve"}:void 0}if(!m||!k){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($){let Q=await U.findJournalEvalCase($.evalId),me=(await U.getJournalEvalRuns()).filter(z=>z.evalId===$.evalId&&z.threadId===m).sort((z,re)=>re.completedAt-z.completedAt)[0];if(!Q||!me){E(u,409,{error:"The failed eval run is not available in this thread."});return}if(me.status!=="fail"){E(u,409,{error:"Only a failed eval can start remediation."});return}se={evalCase:Q,run:me}}if(F){let Q=await ie.findModelProposalsByThread(m);if(q=(await Promise.all(Q.flatMap(z=>z.authorityStatus==="accepted"?[]:z.decisionIds.map(async re=>({modelProposalId:z.id,underlying:await U.findPendingProposalForLegacyDecision(re)}))))).filter(z=>!!z.underlying).find(z=>z.underlying.proposalId===F),!q){E(u,409,{error:"The requested memory decision is not pending in this thread."});return}}let ae="";{let Q=await G.getThreadHistory(m);for(let me=Q.length-1;me>=0;me--)if(Q[me].screenshotPath){ae=Q[me].screenshotPath;break}}let oe=await Ms(m);if(!ae&&!oe){E(u,400,{error:"No screenshot available"});return}let xe=N.hasActiveThread(m),we=xe?N.getQueuedThreadJob(m,Q=>Q._replyText!==void 0||Q._replyPrompt!==void 0):null,V=we?.id??ut().slice(0,8),be=[],de=`${V}-${Date.now()}`;for(let Q=0;Q<O.length;Q++){let me=Ae(c,`reply-${de}-${Q}.webp`);await ln(me,O[Q]),be.push(me)}await G.appendMessage(m,{role:"human",timestamp:Date.now(),jobId:V,replyToQuestion:k,screenshotPath:ae,...xe?{queued:!0}:{},...be.length>0?{replyImagePaths:be}:{}});let pe=await G.getThreadHistory(m),$e=[...pe].reverse().find(Q=>Q.memoryReview)?.memoryReview,Ce=await he.contextualize({text:k,subjectHints:K.elementIdentifiers,pendingGroundingExplanationIds:Yn(pe)}).catch(Q=>{console.warn(`[\u22B9 ${h}:${V}] Imprint context unavailable for reply; continuing without it:`,Q instanceof Error?Q.message:String(Q))}),tt=new Set(pe.flatMap(Q=>Q.memoryReceipt?.status==="committed"?[Q.memoryReceipt.proposalId]:[])),Re=[...pe].reverse().find(Q=>Q.memoryReviewCard&&!tt.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=kt(j),Te=q,Se=Te?[Te.underlying.proposalId]:Re?[Re.proposalId]:[],gt=Kr(ae,pe,fe,be.length>0?be: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(`
|
|
233
|
+
`):Te?gt+=["","## Decision review card",`Privately review proposal ${Te.underlying.proposalId}: ${Te.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(`
|
|
234
|
+
`):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(`
|
|
235
|
+
`)),we){let Q=we,z=[...Q._replyTexts??(Q._replyText?[Q._replyText]:[]),k],re=[...Q._replyImagePaths??[],...be];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??[],...Se])],E(u,200,{jobId:V,position:1,threadId:m,bundled:!0});return}let We={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:C||void 0,agentSettings:D,sourceId:L||void 0,...$e?{memoryReview:$e}:{},...Ce?{imprintContext:Ce}:{},...Se.length?{surfacedProposalIds:Se}:{}};se?We.kind="resolve_eval":oe&&(We.kind=oe),We._replyPrompt=gt,We._evalRemediation=!!se,We._replyTexts=[k],We._replyText=xs([k]),be.length>0&&(We._replyImagePaths=be);let Ut=xe?N.enqueueNext(We):N.enqueue(We);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
|
|
411
236
|
data: {"status":"connected"}
|
|
412
237
|
|
|
413
|
-
`);let
|
|
414
|
-
|
|
415
|
-
${
|
|
416
|
-
${p.summary}`}),m(c,200,{proposal:p})}async function as(r,c,u){let p=decodeURIComponent(r),h=[];for await(let P of c)h.push(typeof P=="string"?Buffer.from(P):P);let d;try{d=JSON.parse(Buffer.concat(h).toString("utf-8"))}catch{m(u,400,{error:"Invalid JSON"});return}let I=(d.changes??[]).flatMap(P=>{if(!Array.isArray(P.path)||P.path.length===0)return[];let $=P.path.filter(te=>typeof te=="string"||typeof te=="number");return $.length!==P.path.length?[]:[{path:$,value:P.value,remove:P.remove===!0}]});if(I.length===0){m(u,400,{error:"No selected model changes"});return}let g=(d.changeSummaries??[]).flatMap(P=>{if(!P||typeof P!="object")return[];let $=Array.isArray(P.path)?P.path.filter(te=>typeof te=="string"||typeof te=="number"):void 0;return Array.isArray(P.path)&&$?.length!==P.path.length?[]:[{group:typeof P.group=="string"?P.group:void 0,label:typeof P.label=="string"?P.label:void 0,detail:typeof P.detail=="string"?P.detail:void 0,path:$,value:P.value,currentValue:P.currentValue}]}),b=await H.applySelectedModelProposal(p,I,g);if(!b){m(u,404,{error:"Model proposal not found"});return}if(b.threadId){let P=We(d.provider),$=typeof d.model=="string"&&d.model?d.model:void 0;await y.appendMessage(b.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${b.id}`,responseText:`Model proposal applied with ${I.length} selected change${I.length===1?"":"s"}.
|
|
417
|
-
|
|
418
|
-
${b.title}`,provider:P,model:$})}m(u,200,{proposal:b})}async function ls(r,c,u){let p=decodeURIComponent(r),{provider:h,model:d}=await Me(c),I=await H.dismissModelProposal(p);if(!I){m(u,404,{error:"Model proposal not found"});return}I.threadId&&await y.appendMessage(I.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${I.id}`,responseText:`Model proposal dismissed.
|
|
419
|
-
|
|
420
|
-
${I.title}`,provider:h,model:d}),m(u,200,{proposal:I})}async function cs(r,c,u){let p=decodeURIComponent(r),h=await H.findModelProposal(p);if(!h){m(u,404,{error:"Model proposal not found"});return}if(h.status!=="applied"){m(u,400,{error:"Only applied model proposals can be projected into evals"});return}let{provider:d,model:I,agentSettings:g}=await Me(c),b=d??h.provider??B;if(b==="copilot"){m(u,400,{error:"Eval projection is not available for Copilot yet."});return}let P=await H.loadModel(),$=await ie.loadSuite(),te=un({proposal:h,currentModel:P,existingSuite:$}),X=Pe().slice(0,8),S=h.threadId??(await y.createThread(X,[])).id;Se.set(S,"synthesize_evals"),await y.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:X,feedbackSummary:`Create eval drafts \u2014 ${h.title}`,feedbackContext:[`Model proposal: ${h.title}`,`Sources: ${h.decisionIds.length} decisions`,"Projection target: pending eval proposals"].join(`
|
|
421
|
-
`)});let O={id:X,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#111827",threadId:S,kind:"synthesize_evals",provider:b,model:I??h.model,agentSettings:g};O._replyPrompt=te,O._proposalId=h.id;let G=D.enqueue(O);m(u,200,{jobId:X,position:G,threadId:S})}async function Me(r){try{let c=[];for await(let p of r)c.push(typeof p=="string"?Buffer.from(p):p);if(c.length===0)return{};let u=JSON.parse(Buffer.concat(c).toString());return{provider:We(typeof u.provider=="string"?u.provider:void 0),model:typeof u.model=="string"&&u.model?u.model:void 0,agentSettings:Ee(u)}}catch{return{}}}async function ds(r,c){let u=await H.loadModel();if(!u){m(c,400,{error:"No model exists yet"});return}let{provider:p,model:h,agentSettings:d}=await Me(r);if(p==="copilot"){m(c,400,{error:"Rule synthesis is not available for Copilot yet."});return}let I=gn(u),g=Pe().slice(0,8),P=(await y.createThread(g,[])).id;Se.set(P,"synthesize"),await y.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:"Synthesize rules \u2014 review and propose improvements"});let $={id:g,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),threadId:P,kind:"synthesize",provider:p,model:h,agentSettings:d};$._replyPrompt=I;let te=D.enqueue($);m(c,200,{jobId:g,position:te,threadId:P})}async function us(r,c){let{provider:u,model:p,agentSettings:h}=await Me(r);if(u==="copilot"){m(c,400,{error:"Eval synthesis is not available for Copilot yet."});return}let d=await le.listDecisionIds(),I=await le.loadDecisions(d),g=await y.load(),b=await H.loadModel(),P=await ie.loadSuite(),$=cn({decisions:I,threads:g,model:b,existingSuite:P}),te=Pe().slice(0,8),S=(await y.createThread(te,[])).id;Se.set(S,"synthesize_evals"),await y.appendMessage(S,{role:"human",timestamp:Date.now(),jobId:te,feedbackSummary:"Synthesize evals \u2014 infer evals from design history"});let O={id:te,status:"queued",screenshotPath:"",feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:"#6b7280",threadId:S,kind:"synthesize_evals",provider:u,model:p||void 0,agentSettings:h};O._replyPrompt=$;let G=D.enqueue(O);m(c,200,{jobId:te,position:G,threadId:S})}async function ps(r,c,u){let p=decodeURIComponent(r),h=await ie.findCase(p);if(!h){m(u,404,{error:"Eval not found"});return}if(h.status!=="approved"){m(u,400,{error:"Only approved evals can be run"});return}let{screenshot:d,feedback:I,provider:g,model:b,reasoningEffort:P,serviceTier:$,sourceId:te}=await lt(c),X=We(g)??B;if(X==="copilot"){m(u,400,{error:"Eval runs are not available for Copilot yet."});return}let S={};try{S=I?JSON.parse(I):{}}catch{m(u,400,{error:"Invalid eval run context JSON"});return}let O=Pe().slice(0,8),G=Pe().slice(0,8),se=ve(a,`eval-run-${O}.webp`);await Ue(se,d);let ce=await ie.writeRunScreenshot(O,d),ue=S.viewport,pe=ue&&typeof ue=="object"?ue:{},de={type:"current_page",url:typeof S.url=="string"?S.url:"",viewport:{width:typeof pe.width=="number"?pe.width:0,height:typeof pe.height=="number"?pe.height:0}},F=await H.loadModel(),oe=X==="claude"?Q.name:X==="codex"?K.name:null,ne=X==="codex"?Z.length>0:typeof oe=="string"&&/chrome|devtools/i.test(oe),fe=dn({evalCase:h,scope:de,model:F,screenshotPath:se,chromeDevtoolsAvailable:ne}),M=(await y.createThread(G,[])).id;Se.set(M,"run_eval");let Y={timestamp:new Date().toISOString(),url:de.url,viewport:de.viewport,scrollPosition:{x:typeof S.scrollX=="number"?S.scrollX:0,y:typeof S.scrollY=="number"?S.scrollY:0},annotations:[],styleModifications:[]};await y.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:G,screenshotPath:se,feedbackSummary:`Run eval \u2014 ${h.title}`,feedbackContext:[`Eval: ${h.title}`,"Scope: current page",`URL: ${de.url||"unknown"}`,"Assertions:",...h.assertions.map(Ms=>`- ${Ms}`)].join(`
|
|
422
|
-
`)});let re={id:G,status:"queued",screenshotPath:se,feedback:Y,createdAt:Date.now(),color:"#111827",threadId:M,kind:"run_eval",evalId:p,evalRunId:O,provider:X,model:b||void 0,agentSettings:Ee({reasoningEffort:P,serviceTier:$}),sourceId:te||void 0};re._replyPrompt=fe,re._evalRunScope=de,re._evalScreenshotPath=ce;let vt=D.enqueue(re);m(u,200,{jobId:G,runId:O,position:vt,threadId:M,screenshotPath:ce})}async function fs(r,c,u){let p=decodeURIComponent(r),h={},d,I,g;try{let P=[];for await(let te of c)P.push(typeof te=="string"?Buffer.from(te):te);let $=JSON.parse(Buffer.concat(P).toString());d=$.status,I=$.title,g=$.assertions}catch{m(u,400,{error:"Invalid JSON"});return}if(d!==void 0&&d!=="pending"&&d!=="approved"&&d!=="rejected"){m(u,400,{error:"Invalid status"});return}if(d&&(h.status=d),I!==void 0){if(typeof I!="string"||I.trim().length===0){m(u,400,{error:"Invalid title"});return}h.title=I.trim()}if(g!==void 0){if(!Array.isArray(g)){m(u,400,{error:"Invalid assertions"});return}let P=g.filter($=>typeof $=="string").map($=>$.trim()).filter(Boolean);if(P.length===0){m(u,400,{error:"Invalid assertions"});return}h.assertions=P}if(!h.status&&!h.title&&!h.assertions){m(u,400,{error:"No eval changes provided"});return}let b=await ie.updateCase(p,h);if(!b){m(u,404,{error:"Eval not found"});return}m(u,200,{eval:b})}async function hs(r){let c=Se.get(r);if(c)return c;let h=(await y.getThread(r))?.messages.find(d=>d.role==="human")?.feedbackSummary??"";if(h.startsWith("Synthesize evals"))return Se.set(r,"synthesize_evals"),"synthesize_evals";if(h.startsWith("Synthesize rules"))return Se.set(r,"synthesize"),"synthesize";if(h.startsWith("Run eval"))return Se.set(r,"run_eval"),"run_eval";if(h.startsWith("Materialize model"))return Se.set(r,"materialize_model"),"materialize_model"}async function ms(r,c){let u=[];for await(let b of r)u.push(typeof b=="string"?Buffer.from(b):b);let p;if(u.length>0)try{p=JSON.parse(Buffer.concat(u).toString("utf-8")).serverUrl}catch{}let h=[];w.claude?.available&&w.claude.mcp&&!w.claude.mcp.found&&h.push(await Mn(p)),w.codex?.available&&w.codex.mcp&&!w.codex.mcp.found&&h.push(await En(p)),w.copilot?.available&&w.copilot.mcp&&!w.copilot.mcp.found&&h.push(await Tn(p,w.copilot.path??E));let[d,I,g]=await Promise.all([Mt(t),Et(t),Tt(t,w.copilot?.path??E)]);w.claude&&(w.claude.mcp=d),w.codex&&(w.codex.mcp=I),w.copilot&&(w.copilot.mcp=g),m(c,200,{results:h,capabilities:{providers:w}})}async function gs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await H.addComponent(p.name);m(c,200,h)}async function ys(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.name||typeof p.name!="string"){m(c,400,{error:"Missing or invalid name"});return}let h=await H.removeComponent(p.name);m(c,200,h)}async function vs(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"||typeof p.value!="string"){m(c,400,{error:"Missing or invalid path/value"});return}let h=await H.updateToken(p.path,p.value);m(c,200,h)}async function ws(r,c){let u=[];for await(let d of r)u.push(typeof d=="string"?Buffer.from(d):d);let p;try{p=JSON.parse(Buffer.concat(u).toString("utf-8"))}catch{m(c,400,{error:"Invalid JSON"});return}if(!p.path||typeof p.path!="string"){m(c,400,{error:"Missing or invalid path"});return}let h=await H.removeToken(p.path);m(c,200,h)}function Ss(r,c){let u=i??"http://localhost:3000";if(!i){let h=r.headers.referer||r.headers.origin;if(h)try{let d=new URL(typeof h=="string"?h:h[0]||"");(d.hostname==="localhost"||d.hostname==="127.0.0.1")&&(u=d.origin)}catch{}}let p=Ft(W,u);c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(p)}async function xs(r){let c=Date.now();if(He&&c<He.expires){m(r,200,He.data);return}try{let{scanForComponents:u}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:p}=await import("./render-generator-EANIDD2E.mjs"),h=await u(t);He={data:h,expires:c+5e3},p(h,t,Ot).then(d=>{Ot=d}).catch(d=>console.warn("[Bridge] Render generation failed:",d)),m(r,200,h)}catch(u){console.error("[Bridge] Scanner error:",u),m(r,500,{error:"Failed to scan components"})}}async function bs(r){let c=[ve(t,"node_modules","@popmelt.com","core","dist","canvas.mjs"),ve(t,"packages","popmelt","dist","canvas.mjs")];try{let u=Pr(import.meta.url);c.unshift(ve(Ir(u),"canvas.mjs"))}catch{}for(let u of c)try{let p=await Wn(u,"utf-8");r.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),r.end(p);return}catch{}console.error("[Bridge] Canvas bundle not found in:",c),m(r,404,{error:"Canvas bundle not found"})}async function Is(r,c){if(!r||r.includes("/")||r.includes("\\")||r.includes("..")){m(c,400,{error:"Invalid filename"});return}try{let u=await Wn(ve(a,r)),p=r.split(".").pop()?.toLowerCase(),h=p==="png"?"image/png":p==="webp"?"image/webp":p==="jpg"||p==="jpeg"?"image/jpeg":"application/octet-stream";c.writeHead(200,{"Content-Type":h,"Cache-Control":"public, max-age=3600"}),c.end(u)}catch{m(c,404,{error:"File not found"})}}function qe(r){return`/files/${ht(r)}`}async function Ps(r,c){let u=await y.getThread(r);if(!u){m(c,404,{error:"Thread not found"});return}let p=(await ie.loadRuns()).runs.filter(b=>b.threadId===r).sort((b,P)=>P.completedAt-b.completedAt)[0],h=p?await ie.findCase(p.evalId):null,d=await H.findModelProposalsByThread(r),I=[...d].sort((b,P)=>P.updatedAt-b.updatedAt)[0]??null,g=u.messages.map(({screenshotPath:b,screenshotPaths:P,imagePaths:$,replyImagePaths:te,...X})=>({...X,...X.role==="assistant"&&p?{evalRun:{...p,title:h?.title}}:{},...b?{screenshotUrl:qe(b)}:{},...P?{screenshotUrls:Object.fromEntries(Object.entries(P).map(([S,O])=>[S,qe(O)]))}:{},...$?{imageUrls:Object.fromEntries(Object.entries($).map(([S,O])=>[S,O.map(qe)]))}:{},...te?{replyImageUrls:te.map(qe)}:{}}));m(c,200,{id:u.id,createdAt:u.createdAt,messages:g,modelProposal:I,modelProposals:d})}async function ks(r,c){let u=decodeURIComponent(r);if(!await y.deleteThread(u)){m(c,404,{deleted:!1,error:"Thread not found"});return}m(c,200,{deleted:!0})}let Jt=9,zt=!1;for(let r=e;r<e+Jt;r++)try{await Br(yt,r),W=r,zt=!0,console.log(`[\u22B9 is watching :${W}]`);break}catch(c){if(c.code==="EADDRINUSE"){let u=await zr(r);if(u&&u.projectId===o)return console.log(`[\u22B9 already watching :${r}]`),{port:r,projectId:o,close:async()=>{}};continue}throw c}if(!zt)throw new Error(`[Bridge] All ports ${e}\u2013${e+Jt-1} in use`);for(let[r,c]of Object.entries(w))!c.available||!c.path||V(r,c.path).then(u=>{if(u)console.log(`[Bridge] ${r} warmed up`);else{console.warn(`[Bridge] ${r} warm-up failed \u2014 marking unavailable`),c.available=!1,c.path=null;for(let p of ee)mt(p,{type:"capabilities_changed",data:{}})}});let Rs=setInterval(()=>{Xn(a).catch(()=>{})},Mr),Bt=setInterval(()=>{k.expireStale().becameEmpty&&_()},Tr);return Bt.unref?.(),{port:W,projectId:o,close:async()=>{clearInterval(Rs),clearInterval(Bt),T(),k.clear(),await D.destroyAsync(),A.destroy();for(let r of ee)try{r.res.end()}catch{}return ee.clear(),new Promise(r=>{yt.close(()=>r())})}}}async function Xn(s){try{let e=await yr(s),n=Date.now();for(let t of e){let o=ve(s,t);try{let i=await wr(o);n-i.mtimeMs>Er&&await Sr(o)}catch{}}}catch{}}var ge="\x1B[35m[popmelt]\x1B[0m";async function Wr(){let s=process.argv.slice(2);if(s[0]==="wrap"){let e=s.indexOf("--");(e===-1||e===s.length-1)&&(console.error(`${ge} Usage: popmelt wrap -- <dev command>`),console.error(`${ge} Example: popmelt wrap -- next dev`),console.error(`${ge} Example: popmelt wrap -- astro dev`),process.exit(1));let n=s.slice(e+1);await qr(n);return}if(s[0]==="bridge"){await Gr();return}if(s[0]==="stop"){await Hr();return}console.log(`${ge} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function Gr(){let s=await Dt({projectRoot:process.cwd()});console.log(`${ge} Bridge running on http://localhost:${s.port}`),await new Promise(e=>{let n=async()=>{console.log(`
|
|
423
|
-
${ge} Shutting down bridge...`),await s.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function Hr(){let s=Ur(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await jr(s,"utf8"))}catch{console.log(`${ge} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${ge} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${ge} Bridge process ${e.pid} already dead`);else throw n}try{await Lr(s)}catch{}}async function qr(s){let e=await Dt({projectRoot:process.cwd()});console.log(`${ge} Bridge running on http://localhost:${e.port}`);let[n,...t]=s;console.log(`${ge} Starting: ${s.join(" ")}`);let o=Fr(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),i=a=>{o.kill(a)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),o.on("exit",async(a,l)=>{await e.close(),l?process.kill(process.pid,l):process.exit(a??0)})}Wr().catch(s=>{console.error(`${ge} Fatal:`,s),process.exit(1)});
|
|
238
|
+
`);let m=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,k={id:ut().slice(0,8),res:u,sourceId:m};X.add(k),a.on("close",()=>{X.delete(k)})}async function ct(a,u,P){i??=ds(a.headers),qe();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}))],[k,w,j,C,D]=await Promise.allSettled([ie.loadRuns(),ie.loadModelProposals(),U.status(),he.store.load(),G.load()]),L=[],F=V=>V.reason instanceof Error?V.reason.message:String(V.reason);k.status==="rejected"&&L.push({subsystem:"projection",message:F(k)}),w.status==="rejected"&&L.push({subsystem:"projection",message:F(w)}),j.status==="rejected"?L.push({subsystem:"memory",message:F(j)}):j.value.state==="degraded"&&L.push({subsystem:"memory",message:j.value.error??"Product memory is degraded."}),C.status==="rejected"&&L.push({subsystem:"imprint",message:F(C)}),D.status==="rejected"&&L.push({subsystem:"threads",message:F(D)});let $=k.status==="fulfilled"?k.value.runs:[],O=w.status==="fulfilled"?w.value.proposals:[],K=ls($,O),q=K.actionableProposals.map(V=>({id:V.id,status:V.status,title:V.title,summary:V.summary,decisionIds:V.decisionIds,threadId:V.threadId,runId:V.runId,presentationJobId:V.presentationJobId,authorityStatus:V.authorityStatus,underlyingProposalId:V.underlyingProposalId,createdAt:V.createdAt,updatedAt:V.updatedAt,appliedAt:V.appliedAt,dismissedAt:V.dismissedAt,generatedEvalIds:V.generatedEvalIds,evalProjections:V.evalProjections,error:V.error})),se=j.status==="fulfilled"?j.value:{initialized:!1,state:"degraded",error:F(j)},ae=D.status==="fulfilled"?[...new Set(Object.values(D.value.threads).flatMap(V=>Yn(V.messages)))]:[],oe=C.status==="fulfilled"?{state:"ready",head:C.value.graph.head,updatedAt:C.value.graph.updatedAt,explanationCount:C.value.graph.explanations.filter(V=>V.state!=="retired").length,concreteCount:C.value.graph.concrete.length,relationCount:C.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:C.value.recoveredTransactions,admission:he.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(C),pendingGroundingCount:ae.length,admission:he.diagnostics(),admissionWindowStartedAt:e},xe=L.length>0?"degraded":se.state==="absent"||se.state==="initializing"?"initializing":"healthy",we=new Date().toISOString();E(u,200,{ok:!0,schemaVersion:3,generatedAt:we,serverStartedAt:e,health:{state:xe,issues:L},version:dn,restartMode:p,projectId:s,projectName:Xn(r),projectRoot:r,requestProjectId:P,projectIdVerified:P===s,devOrigin:i,activeJob:m[0]?{id:m[0].id,status:m[0].status}:null,activeJobs:m.map(V=>({id:V.id,status:V.status,threadId:V.threadId,annotationIds:V.annotationIds,color:V.color,kind:V.kind,standalone:"standalone"in V?V.standalone:void 0})),queueDepth:N.depth+T.depth,projectionQueueDepth:T.depth,leases:{active:B.isActivated,count:B.size,nextExpiryAt:B.nextExpiryAt,shutdownPending:H},projection:{state:k.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:Ne,recentJobs:Pe})}async function ft(a,u){let P=await new Promise(m=>{let k="";a.on("data",w=>{k+=w.toString()}),a.on("end",()=>m(k))});try{let m=JSON.parse(P);typeof m.devOrigin=="string"&&(i=m.devOrigin||null),E(u,200,{ok:!0,devOrigin:i})}catch{E(u,400,{error:"Invalid JSON"})}}async function to(a){let u=await M.load();E(a,200,{ok:!0,...u})}async function no(a,u){let P=await Ue(a);if(!gs(P.theme)){E(u,400,{error:"theme must be light, dark, or auto"});return}let m=await M.setTheme(P.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:${h}`).searchParams.get("jobId"),k=m?N.allActive.filter(F=>F.id===m):N.allActive,w=m?T.allActive.filter(F=>F.id===m):T.allActive,j=[...k.map(F=>F.threadId),...w.map(F=>F.threadId)].filter(Boolean),C=m?N.cancelJob(m):N.cancelActive(),D=m?T.cancelJob(m):T.cancelActive(),L=!!(C||D);for(let F of j)await G.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:m||D?.id||"",cancelled:!0});E(u,200,{cancelled:L})}async function Ee(a){let u=ut().slice(0,8),P=a.threadId,m=!P;P||(P=(await G.createThread(u,[])).id,Ve.set(P,"project_model")),m&&await G.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:u,feedbackSummary:a.reason}),await G.appendMessage(P,{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 k={id:u,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:P,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:m},w=T.enqueue(k);return{jobId:u,position:w,threadId:P}}async function Be(a,u){let P=decodeURIComponent(a),m=await ie.findModelProposal(P);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,P){let m=decodeURIComponent(a),k=[];for await(let O of u)k.push(typeof O=="string"?Buffer.from(O):O);let w;try{w=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{E(P,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(P,400,{error:"No selected model changes"});return}let C=(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(P,404,{error:"Model proposal not found"});return}if(D.authorityStatus!=="accepted"){E(P,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(D.status!=="pending"){E(P,409,{error:`Model proposal is already ${D.status}.`});return}let L=D.decisionIds.map(O=>{let K=D.changes?.filter(ae=>ae.decisionIds.includes(O)).length??0,q=j.filter(ae=>ae.decisionIds?.includes(O)).length,se=q===0?"unprojected":K>q?"partially_projected":"projected";return{decisionId:O,status:se}}),F=await U.applyModelProjection({runId:D.runId??D.id,presentationJobId:D.presentationJobId,decisionIds:D.decisionIds,changes:j.map(O=>({path:O.path,value:O.value,decisionIds:O.decisionIds})),coverage:L}),$=await ie.applySelectedModelProposal(m,j,C);if(!$){E(P,404,{error:"Model proposal not found"});return}if(await Ze($),$.threadId){let O=kt(w.provider),K=typeof w.model=="string"&&w.model?w.model:void 0;await G.appendMessage($.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${$.id}`,responseText:"",provider:O,model:K})}E(P,200,{proposal:$,projection:F})}async function Pt(a,u,P){let m=decodeURIComponent(a),{provider:k,model:w}=await ht(u),j=await ie.dismissModelProposal(m);if(!j){E(P,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:k,model:w}),E(P,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 P=JSON.parse(Buffer.concat(u).toString());return{provider:kt(typeof P.provider=="string"?P.provider:void 0),model:typeof P.model=="string"&&P.model?P.model:void 0,agentSettings:yt(P)}}catch{return{}}}async function oo(a,u,P){let m=decodeURIComponent(a),k=await U.findJournalEvalCase(m);if(!k){E(P,404,{error:"Eval not found"});return}if(k.status!=="approved"){E(P,400,{error:"Only approved evals can be run"});return}let{screenshot:w,feedback:j,provider:C,model:D,reasoningEffort:L,serviceTier:F,sourceId:$}=await Jn(u),O=kt(C)??I;if(O==="copilot"){E(P,400,{error:"Eval runs are not available for Copilot yet."});return}let K={};try{K=j?JSON.parse(j):{}}catch{E(P,400,{error:"Invalid eval run context JSON"});return}let q=ut().slice(0,8),se=ut().slice(0,8),ae=Ae(c,`eval-run-${q}.webp`);await ln(ae,w);let oe=await ue.persistEvalScreenshot(w),xe=K.viewport,we=xe&&typeof xe=="object"?xe:{},V={type:"current_page",url:typeof K.url=="string"?K.url:"",viewport:{width:typeof we.width=="number"?we.width:0,height:typeof we.height=="number"?we.height:0}},be=await ie.loadModel(),de=await Ps(r,k,be),pe=O==="claude"?S.name:O==="codex"?A.name:null,$e=O==="codex"?_.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=dr({evalCase:k,scope:V,model:be,screenshotPath:ae,chromeDevtoolsAvailable:$e}),Re=(await G.createThread(se,[])).id;Ve.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 ${k.title}`,feedbackContext:[`Eval: ${k.title}`,"Scope: current page",`URL: ${V.url||"unknown"}`,"Assertions:",...k.assertions.map(Se=>`- ${Se}`)].join(`
|
|
239
|
+
`)});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:L,serviceTier:F}),sourceId:$||void 0};fe._replyPrompt=Ce,fe._evalRunScope=V,fe._evalScreenshotPath=oe,fe._evalScopeFingerprint=de;let Te=N.enqueue(fe);E(P,200,{jobId:se,runId:q,position:Te,threadId:Re,screenshotPath:oe})}async function pn(a,u,P){let m=decodeURIComponent(a),k={},w,j,C;try{let L=[];for await(let $ of u)L.push(typeof $=="string"?Buffer.from($):$);let F=JSON.parse(Buffer.concat(L).toString());w=F.status,j=F.title,C=F.assertions}catch{E(P,400,{error:"Invalid JSON"});return}if(w!==void 0&&w!=="pending"&&w!=="approved"&&w!=="rejected"){E(P,400,{error:"Invalid status"});return}if(w&&(k.status=w),j!==void 0){if(typeof j!="string"||j.trim().length===0){E(P,400,{error:"Invalid title"});return}k.title=j.trim()}if(C!==void 0){if(!Array.isArray(C)){E(P,400,{error:"Invalid assertions"});return}let L=C.filter(F=>typeof F=="string").map(F=>F.trim()).filter(Boolean);if(L.length===0){E(P,400,{error:"Invalid assertions"});return}k.assertions=L}if(!k.status&&!k.title&&!k.assertions){E(P,400,{error:"No eval changes provided"});return}let D=await U.updateJournalEvalCase(m,k);if(!D){E(P,404,{error:"Eval not found"});return}E(P,200,{eval:D})}async function Ms(a){let u=Ve.get(a);if(u)return u;let k=(await G.getThread(a))?.messages.find(w=>w.role==="human")?.feedbackSummary??"";if(k.startsWith("Synthesize evals"))return Ve.set(a,"synthesize_evals"),"synthesize_evals";if(k.startsWith("Synthesize rules"))return Ve.set(a,"synthesize"),"synthesize";if(k.startsWith("Run eval"))return Ve.set(a,"run_eval"),"run_eval";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return Ve.set(a,"project_model"),"project_model"}async function As(a,u){let P=[];for await(let D of a)P.push(typeof D=="string"?Buffer.from(D):D);let m;if(P.length>0)try{m=JSON.parse(Buffer.concat(P).toString("utf-8")).serverUrl}catch{}let k=[];f.claude?.available&&f.claude.mcp&&!f.claude.mcp.found&&k.push(await Pr(m)),f.codex?.available&&f.codex.mcp&&!f.codex.mcp.found&&k.push(await Rr(m)),f.copilot?.available&&f.copilot.mcp&&!f.copilot.mcp.found&&k.push(await Tr(m,f.copilot.path??b));let[w,j,C]=await Promise.all([yo(r),vo(r),wo(r,f.copilot?.path??b)]);f.claude&&(f.claude.mcp=w),f.codex&&(f.codex.mcp=j),f.copilot&&(f.copilot.mcp=C),E(u,200,{results:k,capabilities:{providers:f}})}async function _s(a,u){let P=[];for await(let j of a)P.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(P).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 k=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:k.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is an explicitly governed component in the product model.`});E(u,200,{added:!0,alreadyExists:!1,...k,evalId:w})}async function $s(a,u){let P=[];for await(let j of a)P.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(P).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 k=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:k.decisionId,modelPath:`components.${m.name}`,claim:`${m.name} is not governed as a component in the product model.`});E(u,200,{removed:!0,...k,evalId:w})}async function Cs(a,u){let P=[];for await(let C of a)P.push(typeof C=="string"?Buffer.from(C):C);let m;try{m=JSON.parse(Buffer.concat(P).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 k=m.value;try{let C=JSON.parse(m.value);C&&typeof C=="object"&&(k=C)}catch{}let w=await U.recordDirectModelMutation({key:`tokens.${m.path}`,value:k,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 Os(a,u){let P=[];for await(let j of a)P.push(typeof j=="string"?Buffer.from(j):j);let m;try{m=JSON.parse(Buffer.concat(P).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 k=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:k.decisionId,modelPath:`tokens.${m.path}`,claim:`${m.path} is intentionally absent from the product model.`});E(u,200,{removed:!0,...k,evalId:w})}function Ds(a,u){let P=i??"http://localhost:3000";if(!i){let k=a.headers.referer||a.headers.origin;if(k)try{let w=new URL(typeof k=="string"?k:k[0]||"");(w.hostname==="localhost"||w.hostname==="127.0.0.1")&&(P=w.origin)}catch{}}let m=Ho(h,P);u.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),u.end(m)}async function Js(a){let u=Date.now();if(mt&&u<mt.expires){E(a,200,mt.data);return}try{let{scanForComponents:P}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:m}=await import("./render-generator-EANIDD2E.mjs"),k=await P(r);mt={data:k,expires:u+5e3},m(k,r,Ft).then(w=>{Ft=w}).catch(w=>console.warn("[Bridge] Render generation failed:",w)),E(a,200,k)}catch(P){console.error("[Bridge] Scanner error:",P),E(a,500,{error:"Failed to scan components"})}}async function Ns(a){let u=[Ae(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ae(r,"packages","popmelt","dist","canvas.mjs")];try{let P=od(import.meta.url);u.unshift(Ae(nd(P),"canvas.mjs"))}catch{}for(let P of u)try{let m=await Fo(P,"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 Bs(a,u){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(u,400,{error:"Invalid filename"});return}try{let P=[Ae(c,a),Ae(r,".popmelt","artifacts","thread-media",a),Ae(r,".popmelt","artifacts","eval-screenshots",a),Ae(r,".popmelt","evals","screenshots",a),Ae(r,".popmelt","screenshots",a)],m;for(let j of P)try{m=await Fo(j);break}catch{}if(!m)throw new Error("File not found");let k=a.split(".").pop()?.toLowerCase(),w=k==="png"?"image/png":k==="webp"?"image/webp":k==="jpg"||k==="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 un(a){return`/files/${Xn(a)}`}async function Fs(a,u){let P=await G.getThread(a);if(!P){E(u,404,{error:"Thread not found"});return}let m=P.messages.some($=>$.role==="assistant"&&$.responseText?.includes("<eval_run_result>")),k=P.messages.filter($=>$.role==="assistant"&&$.responseText?.includes("Model suggestion ready")),[w,j]=await Promise.all([m?U.getJournalEvalRuns().then($=>$.filter(O=>O.threadId===a).sort((O,K)=>K.completedAt-O.completedAt)[0]):Promise.resolve(void 0),k.length>0?ie.findModelProposalsByThread(a):Promise.resolve([])]),C=w?await U.findJournalEvalCase(w.evalId):null,D=await Promise.all(j.map(async($,O)=>{if($.authorityStatus==="accepted")return $;let K=(await Promise.all($.decisionIds.map(q=>U.findPendingProposalForLegacyDecision(q)))).find(Boolean);return{...$,authorityStatus:"legacy_untrusted",presentationJobId:$.presentationJobId??k[O]?.jobId??k.at(-1)?.jobId,underlyingProposalId:K?.proposalId,underlyingClaim:K?.claim}})),L=[...D].sort(($,O)=>O.updatedAt-$.updatedAt)[0]??null,F=P.messages.map(({screenshotPath:$,screenshotPaths:O,imagePaths:K,replyImagePaths:q,...se})=>({...se,...se.role==="assistant"&&w&&se.responseText?.includes("<eval_run_result>")?{evalRun:{...w,title:C?.title}}:{},...$?{screenshotUrl:un($)}:{},...O?{screenshotUrls:Object.fromEntries(Object.entries(O).map(([ae,oe])=>[ae,un(oe)]))}:{},...K?{imageUrls:Object.fromEntries(Object.entries(K).map(([ae,oe])=>[ae,oe.map(un)]))}:{},...q?{replyImageUrls:q.map(un)}:{}}));E(u,200,{id:P.id,createdAt:P.createdAt,messages:F,modelProposal:L,modelProposals:D})}async function Ls(a,u){let P=decodeURIComponent(a);if(!await G.deleteThread(P)){E(u,404,{deleted:!1,error:"Thread not found"});return}E(u,200,{deleted:!0})}let Uo=9,qo=!1;for(let a=n;a<n+Uo;a++)try{await vd(Lt,a),h=a,qo=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(u){if(u.code==="EADDRINUSE"){let P=await yd(a);if(cs(P,{projectId:s,version:dn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:s,close:async()=>{}};continue}throw u}if(!qo)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(P=>{if(P)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)Zn(m,{type:"capabilities_changed",data:{}})}});let zs=setInterval(()=>{Rs(c).catch(()=>{})},id),Wo=setInterval(()=>{B.expireStale().becameEmpty&&ge()},cd);return Wo.unref?.(),{port:h,projectId:s,close:async()=>{clearInterval(zs),clearInterval(Wo),te(),B.clear(),await N.destroyAsync(),T.destroy();for(let a of X)try{a.res.end()}catch{}return X.clear(),new Promise(a=>{Lt.close(()=>a())})}}}async function Rs(o){try{let e=await Qc(o),n=Date.now();for(let t of e){let r=Ae(o,t);try{let s=await Yc(r);n-s.mtimeMs>ad&&await Zc(r)}catch{}}}catch{}}var ve="\x1B[35m[popmelt]\x1B[0m";async function kd(){let o=process.argv.slice(2);if(o[0]==="memory"){await Rd(o.slice(1));return}if(o[0]==="wrap"){let e=o.indexOf("--");(e===-1||e===o.length-1)&&(console.error(`${ve} Usage: popmelt wrap -- <dev command>`),console.error(`${ve} Example: popmelt wrap -- next dev`),console.error(`${ve} Example: popmelt wrap -- astro dev`),process.exit(1));let n=o.slice(e+1);await Ed(n);return}if(o[0]==="bridge"){await Td();return}if(o[0]==="stop"){await jd();return}console.log(`${ve} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(" popmelt memory import Analyze legacy project memory"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}function Bt(o,e){let n=o.indexOf(e);return n>=0?o[n+1]:void 0}function Pd(){console.log(`${ve} Memory commands`),console.log(""),console.log(" popmelt memory import [--project <path>] [--project-key <key>] [--json]"),console.log(" popmelt memory review --subject <hint> [--action <text>] [--project <path>] [--json]"),console.log(""),console.log("The import command is analysis-only. It does not modify legacy or canonical storage."),console.log("Future namespace: memory inspect, verify, export, and commit.")}async function Rd(o){if(o[0]!=="import"&&o[0]!=="review"){Pd(),o.length>0&&o[0]!=="help"&&o[0]!=="--help"&&(process.exitCode=1);return}if(o.includes("--write")||o.includes("--commit"))throw new Error("Legacy import is currently read-only; --write and --commit are not supported.");let e=Bt(o,"--project")??process.cwd(),n=Bt(o,"--project-key"),t=await bt({projectRoot:e,projectKey:n});if(o[0]==="review"){let c=Bt(o,"--subject");if(!c)throw new Error("memory review requires --subject <hint>");let d=Qt(t.bundle,{subjectHints:[c],action:Bt(o,"--action"),maxPackets:Number(Bt(o,"--max-packets")??3),maxEstimatedTokens:Number(Bt(o,"--max-tokens")??1200)});if(o.includes("--json")){console.log(JSON.stringify(d,null,2));return}console.log(`${ve} Contextual memory review (read-only)`),console.log(`${ve} Subject: ${c}`),console.log(`${ve} Matches: ${d.subjectMatches.length}; packets: ${d.packets.length}; status: ${d.completeness.status}`),d.uncertainty&&console.log(`${ve} Uncertainty: ${d.uncertainty}`);for(let[l,g]of d.packets.entries())console.log(""),console.log(`${l+1}. ${g.proposal.claim}`),console.log(` Authority: ${g.authority}; presentation: ${g.presentation}; implementation: ${g.implementation.state}`),console.log(` Why now: ${g.trigger.reason}`),console.log(` Proposal: ${g.proposal.id}`);return}if(o.includes("--json")){console.log(JSON.stringify(t.report,null,2));return}let r=t.report,s=r.proofCases.filter(c=>c.threadFound).length,i=r.schemaIssues.filter(c=>c.severity==="error");if(console.log(`${ve} Legacy memory analysis (read-only)`),console.log(`${ve} Project: ${r.projectRoot}`),console.log(`${ve} Source: ${r.source.threads} threads, ${r.source.messages} messages, ${r.source.decisionEnvelopes} decision envelopes`),console.log(`${ve} Imported: ${Object.entries(r.imported).map(([c,d])=>`${d} ${c}`).join(", ")}`),console.log(`${ve} Acceptance unresolved: ${r.unresolvedAcceptance}`),console.log(`${ve} Model values deferred: ${r.deferredModelEntries}`),console.log(`${ve} Proof coverage: ${s}/${r.proofCases.length} threads found`),console.log(`${ve} Schema validation: ${i.length===0?"passed":`${i.length} errors`}`),r.issues.length){let c=new Map;for(let d of r.issues)c.set(d.code,(c.get(d.code)??0)+1);console.log(`${ve} Review flags: ${[...c].map(([d,l])=>`${d}=${l}`).join(", ")}`)}}async function Td(){let o=await zo({projectRoot:process.cwd()});console.log(`${ve} Bridge running on http://localhost:${o.port}`),await new Promise(e=>{let n=async()=>{console.log(`
|
|
240
|
+
${ve} Shutting down bridge...`),await o.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function jd(){let o=Sd(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await bd(o,"utf8"))}catch{console.log(`${ve} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${ve} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${ve} Bridge process ${e.pid} already dead`);else throw n}try{await xd(o)}catch{}}async function Ed(o){let e=await zo({projectRoot:process.cwd()});console.log(`${ve} Bridge running on http://localhost:${e.port}`);let[n,...t]=o;console.log(`${ve} Starting: ${o.join(" ")}`);let r=Id(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),s=i=>{r.kill(i)};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM")),r.on("exit",async(i,c)=>{await e.close(),c?process.kill(process.pid,c):process.exit(i??0)})}kd().catch(o=>{console.error(`${ve} Fatal:`,o),process.exit(1)});
|